eshangj/stackoverflow_q_and_a_sample huggingface dataset:
Question: I am designing an app where I can send notification to my discord channel when something happen with my python code (e.g new user signup on my website). It will be a one way communication as only python app will send message to discord channel. Here is what I have tried. import os import discord import asyncio TOKEN = "" GUILD = "" def sendMessage(message): client = discord.Client() @client.event async def on_ready(): channel = client.get_channel(706554288985473048) await channel.send(message) print("done") return "" client.run(TOKEN) print("can you see me?") if __name__ == '__main__': sendMessage("abc") sendMessage("def")  The issue is only first message is being sent (i-e abc) and then aysn function is blocking the second call (def). I don't need to listen to discord events and I don't need to keep the network communication open. Is there any way where I can just post the text (post method of api like we use normally) to discord server without listening to events? Thanks.

Answer: You can send the message to a Discord webhook. First, make a webhook in the Discord channel you'd like to send messages to. Then, use the discord.Webhook.from_url method to fetch a Webhook object from the URL Discord gave you. Finally, use the discord.Webhook.send method to send a message using the webhook. If you're using version 2 of discord.py, you can use this snippet: from discord import SyncWebhook webhook = SyncWebhook.from_url("url-here") webhook.send("Hello World")  Otherwise, you can make use of the requests module: import requests from discord import Webhook, RequestsWebhookAdapter webhook = Webhook.from_url("url-here", adapter=RequestsWebhookAdapter()) webhook.send("Hello World")
Question: On the one hand, I have learned that numbers that can be int or float should be type annotated as float (sources: PEP 484 Type Hints and this stackoverflow question): def add(a: float, b: float): return a + b  On the other hand, an int is not an instance of float:  issubclass(int, float) returns False isinstance(42, float) returns False  I would thus have expected Union[int, float] to be the correct annotation for this use case. Questions:  What is the reason for that counter-intuitive behaviour? Does type hinting follow different mechanics than class comparisons (for instance in some case a "lossless casting" rule or so)? Are int/float a special case in type annotations? Are there other examples like this? Is there any linter that would warn me about Union[float, int] if this is an unintended use? 

Answer:   Are int/float a special case in type annotations?   float is a special case. int is not. PEP 484 says, in the paragraph below the one referenced by the link in your question:  when an argument is annotated as having type float, an argument of type int is acceptable;  So accepting int where float is annotated is explicitly a special case, independent of the way annotations generally deal with a class hierarchy.  Are there other examples like this?  Yes, there's at least one other special case. In that same paragraph PEP 484 goes on to say:  for an argument annotated as having type complex, arguments of type float or int are acceptable.    Is there any linter that would warn me about Union[float, int] if this is an unintended use?   Union[float, int] is perfectly fine. The special treatment of a float annotation is just a convenience (PEP 484 calls it a "shortcut") to allow people to avoid writing out the long-winded Union[float, int] annotation, because arguments that can be a float or an int are very common.
Question: Finally block runs just before the return statement in the try block, as shown in the below example - returns False instead of True: >>> def bool_return(): ... try: ... return True ... finally: ... return False ... >>> bool_return() False  Similarly, the following code returns value set in the Finally block: >>> def num_return(): ... try: ... x=100 ... return x ... finally: ... x=90 ... return x ... >>> num_return() 90  However, for variable assignment without return statement in the finally block, why does value of variable updated by the finally block not get returned by the try block? Is the variable from finally block scoped locally in the finally block? Or is the return value from the try block held in memory buffer and unaffected by assignment in finally block? In the below example, why is the output 100 instead of 90? >>> def num_return(): ... try: ... x=100 ... return x ... finally: ... x=90 ... >>> num_return() 100  Similarly the following example: In [1]: def num_return(): ...: try: ...: x=[100] ...: return x ...: finally: ...: x[0] = 90 ...: In [2]: num_return() Out[2]: [90] In [3]: def num_return(): ...: try: ...: x=[100] ...: return x[0] ...: finally: ...: x[0] = 90 ...: In [4]: num_return() Out[4]: 100 

Answer: I think the problem you have is more related to value assignment than what try and finally do. I suggest to read Facts and myths about Python names and values. When you return a value, it just like assigning the value to a variable, result for example, and finally always execute to reassign the value. Then, your example code may be represent as: # try result = True # return # finally result = False # return (reassign value) print(result) # Output: False # try x = 100 result = x # return # finally x = 90 result = x # return (reassign value) print(result) # Output: 90 # try x = 100 result = x # return # finally x = 90 # no return so result not updated print(result) # Output: 100 print(x) # Output: 90 (x is changed actually) # try x = [100] result = x # return the list (result refer to a list and list is mutable) # finally x[0] = 90 # changing the list in-place so it affects the result print(result) # Output: [90] # try x = [100] result = x[0] # return the integer (result refer to the integer) # finally # changing the list in-place which have no effect to result unless reassign value by return x[0] x[0] = 90 print(result) # Output: 100 print(x) # Output: [90] (x is changed actually)
Question: I am simply trying to publish to an SNS topic using a lambda function. The function code as follows, with ARN being the actual SNS topic ARN: import boto3 print('Loading function') def lambda_handler(event, context): client = boto3.client('sns') response = client.publish( TargetArn='ARN', Message="Test", ) return response  The function execution role as access to SNS. In fact I even gave SNS full access. But I keep getting the error: { "errorMessage": "An error occurred (InternalFailure) when calling the Publish operation (reached max retries: 4): Unknown", "errorType": "ClientError", "stackTrace": [ " File \"/var/task/lambda_function.py\", line 6, in lambda_handler\n response = client.publish(\n", " File \"/var/runtime/botocore/client.py\", line 316, in _api_call\n return self._make_api_call(operation_name, kwargs)\n", " File \"/var/runtime/botocore/client.py\", line 626, in _make_api_call\n raise error_class(parsed_response, operation_name)\n" ] }  I do not find any access denied errors in cloudtrail either. Any idea on what is the issue here ? Edit: Its my bad, I used the subscription ARN instead of the topic ARN causing this issue.

Answer: In case if anyone is facing this issue, make sure you use the correct ARN - use the ARN of the Topic instead of the subscription.
Question: I'm importing data into pandas and want to remove any timezones – if they're present in the data. If the data has a time zone, the following code works successfully: col = "my_date_column" df[col] = pd.to_datetime(df[col]).dt.tz_localize(None) # We don't want timezones...  If the data does not contain a timezone, I'd like to use the following code: df[col] = pd.to_datetime(df[col])  My issue is that I'm not sure how to test for timezone in the datetime object / series.

Answer: Assuming you have a column of type datetime, you can check the tzinfo of each timestamp in the column. It's basically described here (although this is not specific to pytz). Ex: import pandas as pd # example series: s = pd.Series([ pd.Timestamp("2020-06-06").tz_localize("Europe/Berlin"), # tzinfo defined pd.Timestamp("2020-06-07") # tzinfo is None ]) # s # 0 2020-06-06 00:00:00+02:00 # 1 2020-06-07 00:00:00 # dtype: object # now find a mask which is True where the timestamp has a timezone: has_tz = s.apply(lambda t: t.tzinfo is not None) # has_tz # 0 True # 1 False # dtype: bool
Question: Context Are there commands to enhance the error message that is received such that python displays which .dll file it cannot find? For error: python test_cv2.py Traceback (most recent call last): File "test_cv2.py", line 1, in <module> import cv2 File "E:\Anaconda3\envs\py38\lib\site-packages\cv2\__init__.py", line 5, in <module> from .cv2 import * ImportError: DLL load failed while importing cv2: The specified module could not be found. (py38) E:\somepath>  I would like to determine which .dll file is actually not being found. To do so, I downloaded and run DependenciesGui.exe from this repository.. Next I fed the DependenciesGui.exe the cv2.cp38-win_amd64.pyd which indicates api-ms-win-core-wow64-l1-1-1.dll is missing, amongst others. I currently do not have a way to verify that the .dll files that are reported missing by dependenciesGUI.exe are also the files that python 3.8 is not finding in the anaconda environment. A way to implicitly verify that the python 3.8 missing .dll files are the same as the same files reported missing by dependenciesGUI.exe would be to download and paste all the missing .dll files into ../system32/. Followed by inspecting if the error message dissapears/changes. However one of the .dll files reported missing is: api-ms-win-core-wow64-l1-1-1.dll which I am not yet able to find (online). Also I tried to cheat to copy and rename api-ms-win-core-wow64-l1-1-0.dll to api-ms-win-core-wow64-l1-1-1.dll but that (luckily) doesn't enable the dpendenciesGUI.exe to recognize the .dll file as found. Question How can I make the error message/traceback of python explicitly mention which .dll file is (the first .dll file that is) not found? Note This is not about solving the xy-problem of installing opencv.

Answer: Short answer: No. Although it is probably not completely impossible, it would require to bind a tool like dependenciesGUI in Python, in order to be able to call it in that given context (namely taking into account the actually search path for dll in Python and already loaded dynamics libraries). It would be quite a lot of work for little gain. Indeed, the default search path in Python>=3.8 on Windows should be very similar to the one of dependenciesGUI, so that the missing dll should be the same. Personally, I'm developing pre-compiled binary distributions for Python, and so far dependenciesGUI was enough to identify the missing libraries at Python import.
Question: I have run a KNN model. Now i want to plot the residual vs predicted value plot. Every example from different websites shows that i have to first run a linear regression model. But i couldn't understand how to do this. Can anyone help? Thanks in advance. Here is my model- train, validate, test = np.split(df.sample(frac=1), [int(.6*len(df)), int(.8*len(df))]) x_train = train.iloc[:,[2,5]].values y_train = train.iloc[:,4].values x_validate = validate.iloc[:,[2,5]].values y_validate = validate.iloc[:,4].values x_test = test.iloc[:,[2,5]].values y_test = test.iloc[:,4].values clf=neighbors.KNeighborsRegressor(n_neighbors = 6) clf.fit(x_train, y_train) y_pred = clf.predict(x_validate) 

Answer: Residuals are nothing but how much your predicted values differ from actual values. So, it's calculated as actual values-predicted values. In your case, it's residuals = y_test-y_pred. Now for the plot, just use this; import matplotlib.pyplot as plt plt.scatter(residuals,y_pred) plt.show()
Question: So here is my Ubuntu version: No LSB modules are available. Distributor ID: Ubuntu Description: Ubuntu 18.04.2 LTS Release: 18.04 Codename: bionic  I'm trying to run the following command: pyenv install 3.6.2 but i get the error: Command 'pyenv' not found, did you mean: command 'pyvenv' from deb python3-venv command 'p7env' from deb libnss3-tools  I've searched and this post (Ubuntu 14.04 - Python 3.4 - pyenv: command Not Found) states Ubuntu 14.04 and below use Python 2 be default so one has to use virtualenv instead, but why does my 18.04 Ubuntu not recognize the command?

Answer: First see if you have the curl already installed in your machine using the command: $ curl --version If you don't have, install the curl using: $ sudo apt-get install curl After that install the pyenv using the command: $curl https://pyenv.run | bash And after installation update your bashrc adding the lines: export PATH="~/.pyenv/bin:$PATH" eval "$(pyenv init -)" eval "$(pyenv virtualenv-init -)"  Finally Reload the bashrc: $ source ~/.bashrc I think will work fine after that. If you installed the pyenv before, look up at you bashrc to confirm if you added the lines above and reload the bashrc again.
Question: Consider the following code: from io import TextIOWrapper from typing import List from zipfile import ZipFile def read_zip_lines(zippath: str, filename: str) -> List[str]: with ZipFile(zippath) as zf: with zf.open(filename) as bfp: with TextIOWrapper(bfp, 'utf-8') as fp: return fp.readlines()  Running mypy v0.782 on the above code under Python 3.6.9 fails with the following error: zfopen.py:8: error: Argument 1 to "TextIOWrapper" has incompatible type "IO[bytes]"; expected "BinaryIO"  However, I feel that this code should not be regarded as an error, as ZipFile.open() returns a binary filehandle, which TextIOWrapper accepts. Moreover, IO[bytes] and BinaryIO are (as far as I understand) effectively the same thing; it's just that BinaryIO is declared as a subclass of IO[bytes]. I would naïvely expect IO[bytes] to be accepted everywhere that BinaryIO is, except that's not how subclasses work, and I'm not sure how to properly make use of this subclassing when typing. Who is in error here, and how does the error get fixed?  Is typeshed in error for declaring the return type of ZipFile.open() as IO[bytes] instead of BinaryIO? Is typeshed in error for declaring the type of the first argument to TextIOWrapper as BinaryIO instead of IO[bytes]? Is the typing module in error for making BinaryIO a subclass of IO[bytes] instead of an alias? Is my code in error for not performing some sort of cast on bfp? Is my thinking in error for expecting bfp to be passable to TextIOWrapper unmodified? 

Answer: This shorter test case with mypy 0.782 gets the same error:  binary_file = io.open('foo.bin', 'rb') text_file = io.TextIOWrapper(binary_file, encoding='utf-8', newline='')  whether binary_file is explicitly declared as IO[bytes] or inferred. Fix: Use mypy 0.770 or mypy 0.790. It was a regression in mypy's typeshed (Issue 4349) and the fix is in mypy 0.790, fixing both zipfile.open() and io.open().
Question: I am trying to combine the lists below to display a date in the format 'dd/hh:mm'. the lists are as follows: dd = [23, 23, 24, 24, 24, 24, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27] hh = [21, 23, 7, 9, 16, 19, 2, 5, 12, 15, 22, 1, 8, 11, 18, 21, 2, 8, 12, 12, 13, 13, 18, 22] mm = [18, 39, 3, 42, 52, 43, 46, 41, 42, 35, 41, 27, 37, 30, 0, 58, 57, 51, 11, 20, 18, 30, 35, 5]  So combining the lists would look something like 23/21:18, 23/23:39, 24/7:3, 24/9:42 ......  and so on. I tried using a for loop (below) for this, but each time was unsurprisingly met with finaltimes = [] zip_object = zip(dd,hh,mm) for list1, list2, list3 in zip_object: finaltimes.append(list1+'/'+list2+':'+list3) TypeError: unsupported operand type(s) for +: 'int' and 'str'  I know I can't combine int and str in this loop but am not sure how to approach this? Any help is appreciated

Answer: The following should work: finaltimes = ['{}/{}:{}'.format(*tpl) for tpl in zip(dd, hh, m)]
Question: So I was trying to make a game with python and pygame but I noticed that I couldn't make a high resolution display because when I tried to make a display with more pixels, the pygame window was too big for my 4k (3840x2160) monitor. I should note that my monitor is connected to an old Dell laptop with a resolution of (1366x768). But when I entered this: print(pygame.display.list_modes()) it told me that I could use resolutions up to 4k and not just up to the resolution of my laptop. After a lot of searching and trying I accepted the fact that my game will be low resolution and moved on. As I continued coding the game I wanted to have a pop-up window so I imported pyautogui and my pygame window suddenly became much smaller. BOOM problem solved. I increased the resolution and I had no problems, my game was now running at a very high resolution! I was very confused so I made a very simple pygame program so I could test this and it actually worked. This is low quality and can't fit in my screen: import pygame import sys pygame.init() screen = pygame.display.set_mode((3000, 1500)) font = pygame.font.Font('font.otf', 50) while True: screen.fill((255, 255, 255)) txt = font.render("hello", True, (0, 0, 0)) screen.blit(txt, (100, 100)) pygame.display.update() for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit()  screenshot1 And this is high resolution and does fit in my screen: import pygame import sys import pyautogui pygame.init() screen = pygame.display.set_mode((3000, 1500)) font = pygame.font.Font('font.otf', 50) while True: screen.fill((255, 255, 255)) txt = font.render("hello", True, (0, 0, 0)) screen.blit(txt, (100, 100)) pygame.display.update() for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit()  screenshot2 I don't even need to use pyautogui! Can someone explain this to me? Thanks

Answer: After a bunch of source diving I believe I have found the solution: pyautogui imports pyscreeze for the functions center, grab, pixel, pixelMatchesColor, screenshot. On lines 63 to 71 of pyscreeze/__init__.py is the following: if sys.platform == 'win32': # On Windows, the monitor scaling can be set to something besides normal 100%. # PyScreeze and Pillow needs to account for this to make accurate screenshots. # TODO - How does macOS and Linux handle monitor scaling? import ctypes try: ctypes.windll.user32.SetProcessDPIAware() except AttributeError: pass # Windows XP doesn't support monitor scaling, so just do nothing.  The above code calls SetProcessDPIAware, which is equivalent to the following:  System DPI aware. This window does not scale for DPI changes. It will query for the DPI once and use that value for the lifetime of the process. If the DPI changes, the process will not adjust to the new DPI value. It will be automatically scaled up or down by the system when the DPI changes from the system value.  If want to get the same effect without pyautogui you can just include the above call to SetProcessDPIAware in your code.
Question: g = [('Books', '10.000'),('Pen', '10'),('test', 'a')] Here '10.000' and '10' are strings How to convert to below format, string to float Expected out [('Books', 10.000),('Pen', 10),('test', 'a')]  Here 10.000 and 10 are floats and a has to be string newresult = [] for x in result: if x.isalpha(): newresult.append(x) elif x.isdigit(): newresult.append(int(x)) else: newresult.append(float(x)) print(newresult)  I got error AttributeError: 'tuple' object has no attribute 'isalpha' 

Answer: you have a problem in your code because the x that you are using is a tuple. The elements of the list you provided are tuples type (String,String) so you need one more iteration on the elemts of the tuples. I have modified your code to : newresult = [] for tuple in result: temp = [] for x in tuple: if x.isalpha(): temp.append(x) elif x.isdigit(): temp.append(int(x)) else: temp.append(float(x)) newresult.append((temp[0],temp[1])) print(newresult)  I have tested the code :  //input result= [('Books', '10.000'),('Pen', '10'),('test', 'a')] //output [('Books', 10.0), ('Pen', 10), ('test', 'a')]
Question: I am using a simple object detection model in PyTorch and using a Pytoch Model for Inferencing. When I am using a simple iterator over the code for k, image_path in enumerate(image_list): image = imgproc.loadImage(image_path) print(image.shape) with torch.no_grad(): y, feature = net(x) result = image.cuda()  It prints our variable sized images such as torch.Size([1, 3, 384, 320]) torch.Size([1, 3, 704, 1024]) torch.Size([1, 3, 1280, 1280])  So When I am using Batch Inferencing using a DataLoader applying the same transformation the code is not running. However, when I am resizing all the images as 600.600 the batch processing runs successfully. I am having Two Doubts, First why Pytorch is capable of inputting dynamically sized inputs in Deep Learning Model and Why dynamic sized input is failing in Batch Processing.

Answer: PyTorch has what is called a Dynamic Computational Graph (other explanation). It allows the graph of the neural network to dynamically adapt to its input size, from one input to the next, during training or inference. This is what you observe in your first example: providing an image as a Tensor of size [1, 3, 384, 320] to your model, then another one as a Tensor of size [1, 3, 384, 1024], and so forth, is completely fine, as, for each input, your model will dynamically adapt. However, if your input is a actually a collection of inputs (a batch), it is another story. A batch, for PyTorch, will be transformed to a single Tensor input with one extra dimension. For example, if you provide a list of n images, each of the size [1, 3, 384, 320], PyTorch will stack them, so that your model has a single Tensor input, of the shape [n, 1, 3, 384, 320]. This "stacking" can only happen between images of the same shape. To provide a more "intuitive" explanation than previous answers, this stacking operation cannot be done between images of different shapes, because the network cannot "guess" how the different images should "align" with one another in a batch, if they are not all the same size. No matter if it happens during training or testing, if you create a batch out of images of varying size, PyTorch will refuse your input. Several solutions are usually in use: reshaping as you did, adding padding (often small or null values on the border of your images) to extend your smaller images to the size of the biggest one, and so forth.