content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: How to make index=False or get rid of first column while using MultiIndex and to_excel in Python Here is the code sample: import numpy as np import pandas as pd import xlsxwriter tuples = [('bar', 'one'), ('bar', 'two'), ('baz', 'one'), ('baz', 'two'), ('foo', 'one'), ('foo', 'two'), ('qux', 'one'), ('qux', 'two'...
How to make index=False or get rid of first column while using MultiIndex and to_excel in Python
Here is the code sample: import numpy as np import pandas as pd import xlsxwriter tuples = [('bar', 'one'), ('bar', 'two'), ('baz', 'one'), ('baz', 'two'), ('foo', 'one'), ('foo', 'two'), ('qux', 'one'), ('qux', 'two')] index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second']) iterables = [['bar', 'baz', ...
[ "Here's a 5 lines fix - \nOriginal code -\ntuples = [('bar', 'one'), ('bar', 'two'), ('baz', 'one'), ('baz', 'two'), ('foo', 'one'), ('foo', 'two'), ('qux', 'one'), ('qux', 'two')]\nindex = pd.MultiIndex.from_tuples(tuples, names=['first', 'second'])\niterables = [['bar', 'baz', 'foo', 'qux'], ['one', 'two']]\ndf =...
[ 3, 0 ]
[]
[]
[ "multi_index", "pandas", "python", "xlsxwriter" ]
stackoverflow_0054898713_multi_index_pandas_python_xlsxwriter.txt
Q: .env file not gitignored. I had someone do it manually for me once So im currently working on a project and my my .env file is not greyed out (gitignore?). Trying to figure out what I need to do globally because I do have the file but my .env is never greyed out. Any suggestions? I can provide screenshots if neede...
.env file not gitignored. I had someone do it manually for me once
So im currently working on a project and my my .env file is not greyed out (gitignore?). Trying to figure out what I need to do globally because I do have the file but my .env is never greyed out. Any suggestions? I can provide screenshots if needed. I had someone do a a few commands in the terminal and was able to get...
[ "First, make sure your .env is not already tracked (or any amount of .gitignore or core.excludesFile would not change anything)\ncd /apth/to/.env\ngit rm --cached .env\n\nThen check if it is currently ignored with:\ngit check-ignore -v -- .env\n\n" ]
[ 0 ]
[]
[]
[ "django", "env_file", "gitignore", "python" ]
stackoverflow_0074576728_django_env_file_gitignore_python.txt
Q: "ObjectId' object is not iterable" error, while fetching data from MongoDB Atlas Okay, so pardon me if I don't make much sense. I face this 'ObjectId' object is not iterable whenever I run the collections.find() functions. Going through the answers here, I'm not sure where to start. I'm new to programming, please ...
"ObjectId' object is not iterable" error, while fetching data from MongoDB Atlas
Okay, so pardon me if I don't make much sense. I face this 'ObjectId' object is not iterable whenever I run the collections.find() functions. Going through the answers here, I'm not sure where to start. I'm new to programming, please bear with me. Every time I hit the route which is supposed to fetch me data from Mongo...
[ "Exclude the \"_id\" from the output.\nresult = collection.find_one({'OpportunityID': oppid}, {'_id': 0})\n\n", "I was having a similar problem to this myself. Not having seen your code I am guessing the traceback similarly traces the error to FastAPI/Starlette not being able to process the \"_id\" field - what y...
[ 8, 8, 7, 1, 1, 1, 0 ]
[]
[]
[ "api", "fastapi", "mongodb", "objectid", "python" ]
stackoverflow_0063881516_api_fastapi_mongodb_objectid_python.txt
Q: Split one row into multiple rows of 6 hours data based on 15 mins time interval in pandas data frame I want Split one row into multiple rows of 6 hours data based on 15 mins time interval in pandas data frame start_time end_time 0 2022-08-22 00:15:00 2022-08-22 06:15:00 I have tried one hrs tim...
Split one row into multiple rows of 6 hours data based on 15 mins time interval in pandas data frame
I want Split one row into multiple rows of 6 hours data based on 15 mins time interval in pandas data frame start_time end_time 0 2022-08-22 00:15:00 2022-08-22 06:15:00 I have tried one hrs time split and used below code result['start_time'] = result.apply(lambda d: pd.date_range(d['start_time'], ...
[ "Try:\n15T instead of h\nresult['start_time'] = result.apply(lambda d: pd.date_range(d['start_time'],\n d['end_time'], \n freq='15T')[:-1], \n axis=1) \n\n\nOUTPUT:\nDatetimeIndex(['2022-...
[ 2, 1 ]
[]
[]
[ "dataframe", "datetime", "pandas", "python" ]
stackoverflow_0074580249_dataframe_datetime_pandas_python.txt
Q: Django Rest API from Database I have 2 APIs from my existing project. Where One provides the latest blog posts and another one provides sorting details. The 2nd API (sorting) gives blog posts ID and an ordering number, which should be in the 1st,2nd,3rd...n position. If I filter in the first API with that given ID...
Django Rest API from Database
I have 2 APIs from my existing project. Where One provides the latest blog posts and another one provides sorting details. The 2nd API (sorting) gives blog posts ID and an ordering number, which should be in the 1st,2nd,3rd...n position. If I filter in the first API with that given ID I can get the blog post details. H...
[ "After searching, I found that you can make API from Database. In setting you need to set the database credentials and then need to create a class inside your models.py and inside class's meta you need to set meta name to db_table and then create serializers.py and views.py as you create REST API.\nclass SortAPI(mo...
[ 0 ]
[]
[]
[ "django", "django_rest_framework", "django_views", "python" ]
stackoverflow_0074003608_django_django_rest_framework_django_views_python.txt
Q: ParserError: ' ' expected after '"' in python pandas/dask Hi I'm using 3GB txt file and want to change it to CSV but it gives error_bad_lines ParserError: ' ' expected after '"' Code I am using df1 = df.read_csv("path\\logs.txt", delimiter = "\t", encoding = 'cp437',engine="python") df1.to_csv("C:\\Data\\log1.cs...
ParserError: ' ' expected after '"' in python pandas/dask
Hi I'm using 3GB txt file and want to change it to CSV but it gives error_bad_lines ParserError: ' ' expected after '"' Code I am using df1 = df.read_csv("path\\logs.txt", delimiter = "\t", encoding = 'cp437',engine="python") df1.to_csv("C:\\Data\\log1.csv",quotechar='"',error_bad_lines=False, header=None, on_bad_lin...
[ "The following code locates unwanted quotation marks (' and \") between each record or tab, and replaces it with nothing.\nIt then replaces the tab (\\t) with a comma (,).\nThis script uses regex to locate the unwanted quotation marks.\nimport re\n\n# Use regex to locate unwanted quotation marks\npattern = re.comp...
[ 0, 0 ]
[]
[]
[ "dask", "pandas", "python" ]
stackoverflow_0074580371_dask_pandas_python.txt
Q: How to solve a delay differential equation numerically I would like to compute the Buchstab function numerically. It is defined by the delay differential equation: How can I compute this numerically efficiently? A: To get a general feeling of how DDE integration works, I'll give some code, based on the low-orde...
How to solve a delay differential equation numerically
I would like to compute the Buchstab function numerically. It is defined by the delay differential equation: How can I compute this numerically efficiently?
[ "To get a general feeling of how DDE integration works, I'll give some code, based on the low-order Heun method (to avoid uninteresting details while still being marginally useful).\nIn the numerical integration the previous values are treated as a function of time like any other time-depending term. As there is no...
[ 1 ]
[]
[]
[ "differential_equations", "math", "number_theory", "python" ]
stackoverflow_0074578027_differential_equations_math_number_theory_python.txt
Q: Winshell error win32con not found Traceback (most recent call last): File "C:/Users/owner/Desktop/2/test2.py", line 1, in <module> import os, winshell File "C:\py35\lib\site-packages\winshell.py", line 30, in <module> import win32con ImportError: No module named 'win32con' I've seen: http://error.news...
Winshell error win32con not found
Traceback (most recent call last): File "C:/Users/owner/Desktop/2/test2.py", line 1, in <module> import os, winshell File "C:\py35\lib\site-packages\winshell.py", line 30, in <module> import win32con ImportError: No module named 'win32con' I've seen: http://error.news/question/6131746/why-does-pip-install-...
[ "IT WORKED AT LAST\nWhat I did:\nRun CMD with elevated privileges and commands:\ncd pathto\\pythondirectory\\scripts\npywin32_postinstall.py -install\n\nTurns out that this would not have run and the DLLs would not have copied over correctly if you didn't have full admin.\nAlso a very notable page: https://blogs.ms...
[ 3, 3, 0 ]
[]
[]
[ "pip", "python", "python_3.x", "python_winshell" ]
stackoverflow_0033591093_pip_python_python_3.x_python_winshell.txt
Q: How to read docx files from azure blob using Python How to read docx files from azure blob using Python? I use the following code, but finally, blob_content has all unreadable characters. This code works fine for txt files but not for MS Word Documents (*.docx). Please help if you have any solution. blob_service_c...
How to read docx files from azure blob using Python
How to read docx files from azure blob using Python? I use the following code, but finally, blob_content has all unreadable characters. This code works fine for txt files but not for MS Word Documents (*.docx). Please help if you have any solution. blob_service_client_instance = BlobServiceClient(account_url=STORAGEACC...
[ "I tried in my environment and got below results:\nInitially I tried the piece of code to read the docx file from azure blob storage through visual studio code.\nIn portal, I have a docx file in azure blob storage\n\nfrom azure.storage.blob import BlobServiceClient\n\nclient=BlobServiceClient.from_connection_str...
[ 0 ]
[]
[]
[ "azure", "azure_blob_storage", "ms_word", "python" ]
stackoverflow_0074571122_azure_azure_blob_storage_ms_word_python.txt
Q: TensorFlow not found using pip I'm trying to install TensorFlow using pip: $ pip install tensorflow --user Collecting tensorflow Could not find a version that satisfies the requirement tensorflow (from versions: ) No matching distribution found for tensorflow What am I doing wrong? So far I've used Python and pip...
TensorFlow not found using pip
I'm trying to install TensorFlow using pip: $ pip install tensorflow --user Collecting tensorflow Could not find a version that satisfies the requirement tensorflow (from versions: ) No matching distribution found for tensorflow What am I doing wrong? So far I've used Python and pip with no issues.
[ "I found this to finally work.\npython3 -m pip install --upgrade https://storage.googleapis.com/tensorflow/mac/cpu/tensorflow-1.12.0-py3-none-any.whl\n\nEdit 1: This was tested on Windows (8, 8.1, 10), Mac and Linux. Change python3 to python according to your configuration. Change py3 to py2 in the url if you are u...
[ 833, 326, 90, 55, 43, 43, 21, 16, 11, 11, 7, 7, 7, 6, 6, 6, 6, 5, 5, 5, 4, 4, 4, 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ "You may try this\npip install --upgrade tensorflow\n\n", "The above answers helped me to solve my issue specially the first answer. But adding to that point after the checking the version of python and we need it to be 64 bit version.\nBased on the operating system you have we can use the following command to in...
[ -1, -1 ]
[ "pip", "python", "tensorflow" ]
stackoverflow_0038896424_pip_python_tensorflow.txt
Q: Webscraping using Scrapy, where is the output? I am trying to build a spider, that gathers information regarding startups. Therefore I wrote a Python script with scrapy that should access the website and store the information in a dictionary. I think the code should work from a logik point of view, but somehow I d...
Webscraping using Scrapy, where is the output?
I am trying to build a spider, that gathers information regarding startups. Therefore I wrote a Python script with scrapy that should access the website and store the information in a dictionary. I think the code should work from a logik point of view, but somehow I do not get any output. My code: import scrapy class...
[ "\nYou're not getting output because your allowed_domains is wrong.\nIn the last line (Adresse), you're trying to concatenate list and str types so you'll get an error.\nYour pagination link is wrong, in the first page you're getting the next page, and in the second page you're getting the previous page.\nYou're no...
[ 1, 0 ]
[]
[]
[ "python", "scrapy", "web_crawler", "web_scraping" ]
stackoverflow_0074576610_python_scrapy_web_crawler_web_scraping.txt
Q: Unable to click through option boxes in Selenium I am trying to make a Python script that will check appointment availability and inform me when an earlier date opens up. I am stuck at the 4th selection page, for locations. I can't seem to click the 'regions' to display the available actual locations. This is what...
Unable to click through option boxes in Selenium
I am trying to make a Python script that will check appointment availability and inform me when an earlier date opens up. I am stuck at the 4th selection page, for locations. I can't seem to click the 'regions' to display the available actual locations. This is what I have: from selenium import webdriver from selenium....
[ "You miss the white space, it should be 'btn btn-sm btn-default '\nregion = WebDriverWait(browser, 10).until(EC.presence_of_element_located((By.XPATH,\"//label[@class='btn btn-sm btn-default '][4]\")))\nregion.click()\n\n", "You may stumble now and again on attribute values containing all sort of spaces at beginn...
[ 0, 0 ]
[]
[]
[ "python", "selenium", "selenium_webdriver", "web_scraping" ]
stackoverflow_0074580360_python_selenium_selenium_webdriver_web_scraping.txt
Q: How can I make the origin of the x-axis and the origin of the y-axis of a plot overlap in matplotlib? I have a simple graph to make, whose source code is below: import pandas as pd def plot_responses(index, y): index='Arsen initial' y=pd.Series({1: 0.8, 2: 0.8, 3: 0.59, 4: 0.54, 5: 0.86, 6: 0.54, 7: 0.97,...
How can I make the origin of the x-axis and the origin of the y-axis of a plot overlap in matplotlib?
I have a simple graph to make, whose source code is below: import pandas as pd def plot_responses(index, y): index='Arsen initial' y=pd.Series({1: 0.8, 2: 0.8, 3: 0.59, 4: 0.54, 5: 0.86, 6: 0.54, 7: 0.97, 8: 0.69, 9: 1.39, 10: 0.95, 11: 2.12, 12: 1.95, 13: 0.99, 14: 0.76, 15: 0.82, 16: 0.63, 17: 1.09, 18: 0.9,...
[ "ax.spines['left'].set_position('zero')\nax.spines['bottom'].set_position('zero')\n\nax.set_xlim(0, y.size)\nax.set_ylim(0, max(y) + 0.5)\n\nthis helps you to overlap both axises at (0,0) and gets rid of the lines that exceed the plot.\n\n", "Use this functions xlim() and ylim()\nLink: https://pythonguides.com/ma...
[ 1, 1 ]
[]
[]
[ "matplotlib", "pandas", "python", "series" ]
stackoverflow_0074580527_matplotlib_pandas_python_series.txt
Q: Allow to user to Enter only numbers and disable letters can you help me I have this code Label (self.window,width=55,text=":Enter your wight ").pack () self.kg = StringVar () Entry (self.window,width=55, textvariable=self.kg).pack () And I want to allow user to enter Numbers only and I want user Enter...
Allow to user to Enter only numbers and disable letters
can you help me I have this code Label (self.window,width=55,text=":Enter your wight ").pack () self.kg = StringVar () Entry (self.window,width=55, textvariable=self.kg).pack () And I want to allow user to enter Numbers only and I want user Enter maximum 3 numbers and maximum The number 250 please help me ...
[ "Too late but here you go:\ndef comm(self):\n def val():\n try:\n int(entry.get())\n if len(entry.get()) <= 3:\n sum = 250 - int(entry.get())\n if sum < 0:\n entry.delete(0, 'end')\n else:\n entry.delete(0, '...
[ 0 ]
[]
[]
[ "letter", "numbers", "python", "user_interface" ]
stackoverflow_0066558547_letter_numbers_python_user_interface.txt
Q: TypeError: descriptor 'collidelist' for 'pygame.Rect' objects doesn't apply to a 'list' object Trying to set up a system to earn score points by killing enemies. but i keep getting: TypeError: descriptor 'collidelist' for 'pygame.Rect' objects doesn't apply to a 'list' object. But it worked one line before. This i...
TypeError: descriptor 'collidelist' for 'pygame.Rect' objects doesn't apply to a 'list' object
Trying to set up a system to earn score points by killing enemies. but i keep getting: TypeError: descriptor 'collidelist' for 'pygame.Rect' objects doesn't apply to a 'list' object. But it worked one line before. This is the first program that ive trying to write on my own. im still very new to this so any help would ...
[ "fire_ball is a list. However, collidelist is there to detect collisions between a single rectangle and a list of rectangles. If you want to detect the collision between 2 lists of rectangles, you must do it in a loop:\nfor ball in fire_ball:\n if ball.collidelist(enemy_rect_list) >= 0:\n score += 1\n\n\n...
[ 0 ]
[]
[]
[ "pygame", "python", "python_3.x" ]
stackoverflow_0074580611_pygame_python_python_3.x.txt
Q: Image size during training in yolov5 I am trying to train a custom dataset in yolov5. So I am trying to run it with an image size of 640x480 but it is not working. python3 /YOLOv5/yolov5/train.py --img-size 640 480 --batch 8 --epochs 300 --data data.yaml --weights yolov5s.pt --cache usage: train.py [-h] [--we...
Image size during training in yolov5
I am trying to train a custom dataset in yolov5. So I am trying to run it with an image size of 640x480 but it is not working. python3 /YOLOv5/yolov5/train.py --img-size 640 480 --batch 8 --epochs 300 --data data.yaml --weights yolov5s.pt --cache usage: train.py [-h] [--weights WEIGHTS] [--cfg CFG] [--data DATA] [...
[ "--img-size\n\nonly takes one argument. Use:\npython3 /YOLOv5/yolov5/train.py --img-size 640 --batch 8 --epochs 300 --data data.yaml --weights yolov5s.pt --cache\n\nthe height of the image will be adjusted accordingly, respecting the aspect ratio and stride needs.\n" ]
[ 0 ]
[]
[]
[ "python", "python_3.x", "pytorch", "yolov5" ]
stackoverflow_0074457702_python_python_3.x_pytorch_yolov5.txt
Q: ValueError: The view **** didn't return an HttpResponse object. It returned None instead I'm using Django forms to handle user input for some point on my Django app. but it keeps showing this error whenever the user tries to submit the form. ValueError: The view *my view name goes here* didn't return an HttpRespo...
ValueError: The view **** didn't return an HttpResponse object. It returned None instead
I'm using Django forms to handle user input for some point on my Django app. but it keeps showing this error whenever the user tries to submit the form. ValueError: The view *my view name goes here* didn't return an HttpResponse object. It returned None instead Here's the code: Forms.py class sendBreachForm(forms.For...
[ "The error makes complete sense, the view should return some response in all the conditions, currently you have both if and else condition for everything, except if form.is_valid() so also maintain in that.\n@login_required\ndef web_app(request):\n if request.user.is_staff or request.user.is_superuser:\n ...
[ 2 ]
[]
[]
[ "django", "django_forms", "django_templates", "django_views", "python" ]
stackoverflow_0074580563_django_django_forms_django_templates_django_views_python.txt
Q: Why are Pytorch transform functions not being differentiated with autograd? I have been trying to write a set of transforms on input data. I also need the transforms to be differentiable to compute the gradients. However, gradients do not seem to be calculated for the resize, normalize transforms. from torchvision...
Why are Pytorch transform functions not being differentiated with autograd?
I have been trying to write a set of transforms on input data. I also need the transforms to be differentiable to compute the gradients. However, gradients do not seem to be calculated for the resize, normalize transforms. from torchvision import transforms from torchvision.transforms import ToTensor resize = transfo...
[ "Trying to reproduce your error, what I get when backpropagating the gradient from normalized is:\n\nRuntimeError: grad can be implicitly created only for scalar outputs\n\nWhat this error means is that the tensor you are calling backward onto should be a scalar and not a vector or multi-dimensional tensor. General...
[ 1 ]
[]
[]
[ "deep_learning", "machine_learning", "python", "pytorch" ]
stackoverflow_0074577705_deep_learning_machine_learning_python_pytorch.txt
Q: Syntax for `apply` pandas function in ruby I need to convert a python script into ruby. I use for that the gems Pandas and Numpy which make the work quite simple. For example I have these kind of lines: # python # DF is a dataframe from Pandas DF['VAL'].ewm(span = vDAY).mean() DF['VOLAT'].rolling(vDAY).std() so ...
Syntax for `apply` pandas function in ruby
I need to convert a python script into ruby. I use for that the gems Pandas and Numpy which make the work quite simple. For example I have these kind of lines: # python # DF is a dataframe from Pandas DF['VAL'].ewm(span = vDAY).mean() DF['VOLAT'].rolling(vDAY).std() so no question asked, I convert like this: # ruby d...
[ "\nIf someone can \"translate\" this apply function from python syntax to ruby, it would be really nice\n\nThe equivalent Ruby syntax is:\nDF['VAL'].rolling(vDAY).apply(-> x { np.polyfit(range(len(x)), x, 1)[0] })\n\n" ]
[ 0 ]
[]
[]
[ "dataframe", "pandas", "pycall", "python", "ruby" ]
stackoverflow_0074578142_dataframe_pandas_pycall_python_ruby.txt
Q: Singleton-comparison suggestion by pylint For the given code def greater(n): if n > 3: res = True else: res = False return res a = greater(5) print(hex(id(a))) print(hex(id(True))) b = True print(hex(id(b))) if a == True: print('yes') else: print('no') pylint suggests pyli...
Singleton-comparison suggestion by pylint
For the given code def greater(n): if n > 3: res = True else: res = False return res a = greater(5) print(hex(id(a))) print(hex(id(True))) b = True print(hex(id(b))) if a == True: print('yes') else: print('no') pylint suggests pylint_example.py:16:4: C0121: Comparison 'a == Tr...
[ "True and False are unique singletons, not immutable. If a has the value True, then a and True do have the same memory address.\nSource: PEP-0285 and In Python are the built in constants True and False unique?\n", "PEP 8 claims that correct way is to use if variable giving following example\nif greeting:\n\nand c...
[ 2, 0 ]
[]
[]
[ "pylint", "python", "python_3.x" ]
stackoverflow_0074580659_pylint_python_python_3.x.txt
Q: how to manipulate elements of a tensor if you have a set of indices? (torch.topk()) suppose i have a tensor and using torch.topk function i get the max k elements of a tensor and their indices. like the following code >>> x = torch.arange(1., 6.) >>> x tensor([ 1., 2., 3., 4., 5.]) >>> torch.topk(x, 3) torch.r...
how to manipulate elements of a tensor if you have a set of indices? (torch.topk())
suppose i have a tensor and using torch.topk function i get the max k elements of a tensor and their indices. like the following code >>> x = torch.arange(1., 6.) >>> x tensor([ 1., 2., 3., 4., 5.]) >>> torch.topk(x, 3) torch.return_types.topk(values=tensor([5., 4., 3.]), indices=tensor([4, 3, 2])) now suppose i w...
[ "The torch.topk function returns the indices of the top-k elements on the provided dimension. You can perform the reassignment operation using torch.scatter:\n>>> _, i = x.topk(k=3)\n>>> x.scatter(dim=0, index=i, value=0)\ntensor([1., 2., 0., 0., 0.])\n\n" ]
[ 0 ]
[]
[]
[ "python", "pytorch", "tensor" ]
stackoverflow_0074577249_python_pytorch_tensor.txt
Q: Getting data between two div or a tags in BeautifulSoup I am working on a scraping project in which there is some data between two different divs and two different a tags and we want to fetch everything in between them. Sample problem 1: <div id ="startID"></div> <table> <tr> data </tr> </table> <...
Getting data between two div or a tags in BeautifulSoup
I am working on a scraping project in which there is some data between two different divs and two different a tags and we want to fetch everything in between them. Sample problem 1: <div id ="startID"></div> <table> <tr> data </tr> </table> <p>Paragraph data</p> <div id="endID"></div> Expected outcome...
[ "You can use .next_sibling to iteratively extract text from the startID tag until you find the endID tag.\nstartID = soup.find(id=\"startID\")\nendID = soup.find(id=\"endID\")\ndata = []\nfor sibling in startID.next_siblings:\n if sibling == endID:\n break\n text = sibling.get_text(strip=True)\n if ...
[ 1 ]
[]
[]
[ "beautifulsoup", "html", "python", "web_scraping" ]
stackoverflow_0074580668_beautifulsoup_html_python_web_scraping.txt
Q: Python print class member name from value I have a class with list of class members (variabls), each assigned to its own value. class PacketType: HEARTBEAT = 0xF0 DEBUG = 0xFC ECHO = 0xFF @staticmethod def get_name(value): # Get variable name from value ...
Python print class member name from value
I have a class with list of class members (variabls), each assigned to its own value. class PacketType: HEARTBEAT = 0xF0 DEBUG = 0xFC ECHO = 0xFF @staticmethod def get_name(value): # Get variable name from value # Print the variable in string format r...
[ "The below works. (But I dont understand why you want to have such thing)\nclass PacketType:\n HEARTBEAT = 0xF0\n DEBUG = 0xFC\n ECHO = 0xFF\n\n @staticmethod\n def get_name(value):\n for k, v in PacketType.__dict__.items():\n if v == value:\n return k\n return...
[ 3, 1 ]
[]
[]
[ "python" ]
stackoverflow_0074580745_python.txt
Q: How to add input how many integers do you want? I'm starting next month full stack developer and im doing some practicing i started with Python and i want to make some code with while loop that will ask the user to input how many integers they want and i want to calculate all the numbers im doing something wrong n...
How to add input how many integers do you want?
I'm starting next month full stack developer and im doing some practicing i started with Python and i want to make some code with while loop that will ask the user to input how many integers they want and i want to calculate all the numbers im doing something wrong not sure what thanks in advance oz example: number = ...
[ "number = int(input('Enter how many integer: '))\nmy_list = []\nwhile len(my_list) < number:\n user_input = int(input('Enter a integer: '))\n my_list.append(user_input)\n print(user_input, ' ' ,number) \nprint(my_list)\n\n" ]
[ 0 ]
[]
[]
[ "input", "integer", "python", "while_loop" ]
stackoverflow_0074580482_input_integer_python_while_loop.txt
Q: Is there an efficient way to calculate when a record was replaced by another? I am going to use a soccer analogy to illustrate the problem. I have a table representing players in a soccer game. player | position | start minute ------------------------------ Bob | keeper | 0 Pedro | Center M...
Is there an efficient way to calculate when a record was replaced by another?
I am going to use a soccer analogy to illustrate the problem. I have a table representing players in a soccer game. player | position | start minute ------------------------------ Bob | keeper | 0 Pedro | Center Midfielder | 0 Joe | Striker | 0 Tim | Center Midfielder | 20 I wan...
[ "One approach could be as follows:\nData\nimport pandas as pd\n\n# adding some subs to get a more informative example\ndata = {'player': {0: 'Bob', 1: 'Pedro', 2: 'Joe', 3: 'Tim', 4: 'Keith',\n 5: 'Leo'}, \n 'position': {0: 'keeper', 1: 'Center Midfielder', 2: 'Striker', \n ...
[ 1 ]
[]
[]
[ "pandas", "python", "sql_order_by" ]
stackoverflow_0074580331_pandas_python_sql_order_by.txt
Q: The transaction declared chain ID 5777, but the connected node is on 1337 I am trying to deploy my SimpleStorage.sol contract to a ganache local chain by making a transaction using python. It seems to have trouble connecting to the chain. from solcx import compile_standard from web3 import Web3 import json import ...
The transaction declared chain ID 5777, but the connected node is on 1337
I am trying to deploy my SimpleStorage.sol contract to a ganache local chain by making a transaction using python. It seems to have trouble connecting to the chain. from solcx import compile_standard from web3 import Web3 import json import os from dotenv import load_dotenv load_dotenv() with open("./SimpleStorage.so...
[ "Had this issue myself, apparently it's some sort of Ganache CLI error but the simplest fix I could find was to change the network id in Ganache through settings>server to 1337. It restarts the session so you'd then need to change the address and private key variable.\nIf it's the same tutorial I'm doing, you're li...
[ 33, 11, 7, 2, 1, 0, 0 ]
[]
[]
[ "ethereum", "ganache", "python", "smartcontracts", "solidity" ]
stackoverflow_0070731492_ethereum_ganache_python_smartcontracts_solidity.txt
Q: Pandas and bs4 html scraping I am extracting data from an html file, it is in a table format so I made this line of code to convert all the tables to a data frame with pandas. dfs = pd.read_html("synced_contacts.html") Now, printing the 2nd row of tables of the data frame dfs[1] The output is the following: How...
Pandas and bs4 html scraping
I am extracting data from an html file, it is in a table format so I made this line of code to convert all the tables to a data frame with pandas. dfs = pd.read_html("synced_contacts.html") Now, printing the 2nd row of tables of the data frame dfs[1] The output is the following: How can I do so that the information ...
[ "It is caused by the struture, everything is placed in a single <td> and will be concatenated, the colspan is creating the second column.\npd.read_html() is a good for the first and easiest pass, not necessarily that it will handle every messy table in real life.\nSo instead using the pd.read_html() you could use B...
[ 0 ]
[]
[]
[ "beautifulsoup", "dataframe", "pandas", "python", "web_scraping" ]
stackoverflow_0074578362_beautifulsoup_dataframe_pandas_python_web_scraping.txt
Q: cannot be loaded because running scripts is disabled on this system. For more information, see about_Execution_Policies at It was working fine and then i got an error. after solving it i always get this error, whatever the project is output: & : File C:\Users\pc\Documents\python\venv\Scripts\Activate.ps1 cannot be...
cannot be loaded because running scripts is disabled on this system. For more information, see about_Execution_Policies at
It was working fine and then i got an error. after solving it i always get this error, whatever the project is output: & : File C:\Users\pc\Documents\python\venv\Scripts\Activate.ps1 cannot be loaded because running scripts is disabled on this system. For more information, see about_Execution_Policies at http...
[ "This is because the user your running the script as has a undefined ExecutionPolicy You could fix this by running the following in powershell:\nSet-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy Unrestricted\n\n", "If you are getting error like this,\n\nWe can resolve that using the following steps,\n\nGet ...
[ 108, 18, 13, 5, 4, 4, 2, 1, 0 ]
[ "workon \"namefolder\"\n.\\venv\\scripts\\activate\n", "I got a similar error about the execution policies. I used the commands posted above. After that, the error message didn't appear.\nRun the Powershell as administrator and use those commands.\nstep 1: -Press the Windows button on your keyboard.\nstep 2: -Typ...
[ -1, -1 ]
[ "python", "visual_studio_code" ]
stackoverflow_0067150436_python_visual_studio_code.txt
Q: Getting real time output from iperf3 using python's subprocess This is a follow-on to: Getting realtime output using subprocess I'm trying to use subprocess to capture output from iperf3 in real time (using python 3.6 on windows). The goal is to leave the iperf3 session running continuously and grab the data to up...
Getting real time output from iperf3 using python's subprocess
This is a follow-on to: Getting realtime output using subprocess I'm trying to use subprocess to capture output from iperf3 in real time (using python 3.6 on windows). The goal is to leave the iperf3 session running continuously and grab the data to update a real time plot. I created an implementation based on the refe...
[ "Sorry for my late answer. There is an API for Iperf3, luckily this comes with the standard iperf3 build/installation.\nThis API allows python to take the common output of iperf3.\nI let you the official website of the python wrapper for iperf3. It comes with simple examples for your use. Hope I could have gave you...
[ 0, 0 ]
[]
[]
[ "iperf", "python", "subprocess" ]
stackoverflow_0061737867_iperf_python_subprocess.txt
Q: Unsatisfiable error installing QIIME in conda environment glibc==2.31=0 I've been trying to install QIIME2 on Linux with the command conda install -c qiime2 qiime2 and get this error message: Collecting package metadata (current_repodata.json): done Solving environment: failed with initial frozen solve. Retrying ...
Unsatisfiable error installing QIIME in conda environment glibc==2.31=0
I've been trying to install QIIME2 on Linux with the command conda install -c qiime2 qiime2 and get this error message: Collecting package metadata (current_repodata.json): done Solving environment: failed with initial frozen solve. Retrying with flexible solve. Solving environment: failed with repodata from current_r...
[ "./conda install -c anaconda appnope\n./conda install -c anaconda libgfortran\n\n" ]
[ 0 ]
[]
[]
[ "anaconda", "conda", "linux", "python", "qiime" ]
stackoverflow_0074048596_anaconda_conda_linux_python_qiime.txt
Q: Python: .count() doesn't count I'm writing a simple program that takes user input and prints the number of even, odd and zeros. The program doesn't yield any errors but it seems to skip line 5 and 15 I want to count and display the zeroes in the numbers list numbers = input("Numbers seperated by space:").split() ...
Python: .count() doesn't count
I'm writing a simple program that takes user input and prints the number of even, odd and zeros. The program doesn't yield any errors but it seems to skip line 5 and 15 I want to count and display the zeroes in the numbers list numbers = input("Numbers seperated by space:").split() print("Numbers:" + str(numbers)) ...
[ "Youre code isnt working because inputs in Python are strings. So when you enter a number like 5, Python turns it into \"5\". So to make your code work change .count(0) to .count(\"0\")\nnumbers = input(\"Numbers seperated by space:\").split()\n \nprint(\"Numbers:\" + str(numbers))\n \nzero = numbers.count(\"0\")\n...
[ 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074561070_python.txt
Q: How to make a bot to automatically open Zoom meeting and enter class when it's time in the schedule by using Python? I am making a bot to automatically open Zoom meeting and enter the class when it's time. I set the time when it is from 8:00 PM to 8:10 PM the computer will automatically open Zoom and enter the co...
How to make a bot to automatically open Zoom meeting and enter class when it's time in the schedule by using Python?
I am making a bot to automatically open Zoom meeting and enter the class when it's time. I set the time when it is from 8:00 PM to 8:10 PM the computer will automatically open Zoom and enter the code and password, but it's not running. I have tried many ways but nothing happen. So hopefully someone can help to fix thi...
[ "Assuming you do have a working zoom link e.g.\nhttps://yourCompanyName.zoom.us/j/1234567890\n\nTo launch zoom on MacOS (tested) and Linux (untested) you can do a C system(...) call like this:\nsystem(\"open -a zoom.us 'https://yourCompanyName.zoom.us/j/1234567890'\");\n\nWhich in Python would translate to:\nimpor...
[ 0 ]
[]
[]
[ "python", "python_3.9", "python_3.x" ]
stackoverflow_0068985648_python_python_3.9_python_3.x.txt
Q: Can we use `bool or None` instead of Union[bool, None] for type annotating? I'm using python3.8 and have a variable which can be True, False or None. For type-hinting this variable I know I can use Union for variables where they may have divergent types. But personally I don't prefer using Union. I think it's easi...
Can we use `bool or None` instead of Union[bool, None] for type annotating?
I'm using python3.8 and have a variable which can be True, False or None. For type-hinting this variable I know I can use Union for variables where they may have divergent types. But personally I don't prefer using Union. I think it's easier to use the newer python syntax bool | None but it's not available in python3.8...
[ "You've answered on your issue youself.\nbool or None # returns bool type\nbool | None # just equal to Union[bool, None] for Python 3.10+ \n # and provides cleanest syntax for Type Hinting\n\nSure you can't use this in Python 3.9 or lower, because this structure (bitwise or) is not implemented. If you...
[ 0, 0 ]
[]
[]
[ "python", "type_annotation" ]
stackoverflow_0074580752_python_type_annotation.txt
Q: Consider a set of items I = {1, 2,..., N}. What is the size of all possible valid itemsets? I have been thinking about this question but have not come up with an answer. Is there a subject area I could look at that my question relates to? Question is as mentioned in title. Are there any ways I could implement perh...
Consider a set of items I = {1, 2,..., N}. What is the size of all possible valid itemsets?
I have been thinking about this question but have not come up with an answer. Is there a subject area I could look at that my question relates to? Question is as mentioned in title. Are there any ways I could implement perhaps a small python program to help myself in this case using items in a dataframe? I feel like th...
[ "I think this is covered thoroughly in most introductory probability texts in the sections covering combinatorics. I'd look up topics like counting for combinations and permutations to get some foundational knowledge on this\n" ]
[ 0 ]
[]
[]
[ "associations", "data_mining", "dataframe", "python", "set" ]
stackoverflow_0074579091_associations_data_mining_dataframe_python_set.txt
Q: Django Rest how to save current user when creating an new blog? When I am creating an blog post I also want to automatically save the current user without selecting the user manually as a blog author. here is my code: models.py: class Blog(models.Model): author = models.ForeignKey( settings.AUTH_USER_M...
Django Rest how to save current user when creating an new blog?
When I am creating an blog post I also want to automatically save the current user without selecting the user manually as a blog author. here is my code: models.py: class Blog(models.Model): author = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True) blog_title...
[ "You can modify your serializer like below. It picks up the user from the request context and creates the blog.\nclass BlogSerializer(serializers.ModelSerializer):\n class Meta:\n model = Blog\n fields = \"__all__\"\n read_only_fields = [\"author\"]\n\n def create(self, validated_data):\n...
[ 0 ]
[]
[]
[ "django", "django_rest_framework", "python", "python_3.x" ]
stackoverflow_0074580843_django_django_rest_framework_python_python_3.x.txt
Q: How could I create a system for my trading bots I want to create a system where I can manage a privet trading bots ,I don't Know how to architects it with OOP or create a file for each bot I will store the strategies in one file so I can import it create a class for the bot that have stop and start methods this ...
How could I create a system for my trading bots
I want to create a system where I can manage a privet trading bots ,I don't Know how to architects it with OOP or create a file for each bot I will store the strategies in one file so I can import it create a class for the bot that have stop and start methods this is all easy , what I don't Know to do is how to creat...
[ "You can try to write bots in a separate projects and run them via a subprocess from main file. Just create main.py with GUI and set functions that calls or stops your bots.\np = subprocess.Popen(['python3', 'bot1.py']) # on start button\np.kill() # on stop button\n\nAlso you can track subprocess activity using P...
[ 1 ]
[]
[]
[ "architecture", "class", "object", "oop", "python" ]
stackoverflow_0074580855_architecture_class_object_oop_python.txt
Q: how to parse the xml thru xml parser by using xml.etree.ElementTree with the below sample trying to parse below XML which seems to be a different model. <?xml version="1.0" encoding="UTF-8"?> <book> <item neighbor-name="ABC-LENGTH" pos="1" size="8" type="INT"/> <item neighbor-name="ABC-CODE" pos="9" size="3" typ...
how to parse the xml thru xml parser by using xml.etree.ElementTree with the below sample
trying to parse below XML which seems to be a different model. <?xml version="1.0" encoding="UTF-8"?> <book> <item neighbor-name="ABC-LENGTH" pos="1" size="8" type="INT"/> <item neighbor-name="ABC-CODE" pos="9" size="3" type="STRING"/> <item neighbor-name="DEF-IND" pos="12" size="1" type="STRING"/> <item neighbor-nam...
[ "I copied your XML in a file named \"book.xml\".\nThan you can easy walk through with .iter() and grap the values of the attributes with .get():\nimport pandas as pd\nimport xml.etree.ElementTree as ET \n\ntree = ET.parse(\"book.xml\")\nroot = tree.getroot()\n\ncolumns = [\"neighbor-name\", \"pos\", \"size\", \"typ...
[ 1 ]
[]
[]
[ "parsing", "python", "xml" ]
stackoverflow_0074555021_parsing_python_xml.txt
Q: Receive all messages in AWS SQS queue using boto library until queue is empty I have a case where a script is writing all unused volume ids to AWS SQS queue and after some time, we need to receive all those messages with volume ids and delete those volumes. Is there a way to achieve this using python boto library?...
Receive all messages in AWS SQS queue using boto library until queue is empty
I have a case where a script is writing all unused volume ids to AWS SQS queue and after some time, we need to receive all those messages with volume ids and delete those volumes. Is there a way to achieve this using python boto library? Receive all messages in AWS SQS queue using boto library until queue is empty
[ "Your Python script should use the boto3 receive_message() command:\n\nRetrieves one or more messages (up to 10), from the specified queue.\n\nOnce your program has finished processing a message, it should call delete_message() or delete_message_batch() to delete the message, passing the ReceiptHandle for each mess...
[ 0 ]
[]
[]
[ "amazon_sqs", "amazon_web_services", "boto3", "python" ]
stackoverflow_0074578070_amazon_sqs_amazon_web_services_boto3_python.txt
Q: Spotipy (sp.track() specifically) takes too long to run I am trying to extract the release data, explicit flag and popularity score of approximately 18,000 songs. I want to append these results to my data frame Initially, I tried this. - for i,track in enumerate(df['uri']): release_dates.append(sp.track(track...
Spotipy (sp.track() specifically) takes too long to run
I am trying to extract the release data, explicit flag and popularity score of approximately 18,000 songs. I want to append these results to my data frame Initially, I tried this. - for i,track in enumerate(df['uri']): release_dates.append(sp.track(track)['album']['release_date']) But I took too long to run, so ...
[ "It's much faster to request 50 tracks at once with sp.tracks(uri_list)\n# function to divide a list of uris (or ids) into chuncks of 50.\nchunker = lambda y, x: [y[i : i + x] for i in range(0, len(y), x)]\n\n# using the function\nuri_chunks = chunker(uri_list, 50)\n\nupdated_popularity, explicit_flags, release_dat...
[ 0 ]
[]
[]
[ "machine_learning", "python", "spotify", "spotify_app", "spotipy" ]
stackoverflow_0074579070_machine_learning_python_spotify_spotify_app_spotipy.txt
Q: Python: Is order preserved when iterating a tuple? In Python, if I run the code: T=('A','B','C','D') D={} i=0 for item in T: D[i]=item i=i+1 Can I be sure that D will be organized as: D = {0:'A', 1:'B', 2:'C', 3:'D'} I know that tuples' order cannot be changed because they are immutable, but am I guarant...
Python: Is order preserved when iterating a tuple?
In Python, if I run the code: T=('A','B','C','D') D={} i=0 for item in T: D[i]=item i=i+1 Can I be sure that D will be organized as: D = {0:'A', 1:'B', 2:'C', 3:'D'} I know that tuples' order cannot be changed because they are immutable, but am I guaranteed that it will always be iterated in order as well?
[ "Yes, tuples are ordered and iteration follows that order. Guaranteed™.\nYou can generate your D in one expression with enumerate() to produce the indices:\nD = dict(enumerate(T))\n\nThat's because enumerate() produces (index, value) tuples, and dict() accepts a sequence of (key, value) tuples to produce the dictio...
[ 22, 0 ]
[]
[]
[ "loops", "python", "tuples" ]
stackoverflow_0025670989_loops_python_tuples.txt
Q: yes/no loop not working properly when i used OR keyword I was using a yes/no loop to make an infinite loop which would end when user enters no or No but the program was not working properly. I know the what the error is but i don't know why is it occuring like this. Can anyone tell how to fix the error without cha...
yes/no loop not working properly when i used OR keyword
I was using a yes/no loop to make an infinite loop which would end when user enters no or No but the program was not working properly. I know the what the error is but i don't know why is it occuring like this. Can anyone tell how to fix the error without changing my initial program when i use this code it works but wh...
[ "You have a few options:\nwhile True:\n a = input(\"Enter yes/no to continue\")\n if a.lower()=='yes':\n print(\"enter the program\")\n elif a.lower()=='no':\n print(\"EXIT\")\n break\n else:\n print(\"Enter either yes/no\")\n\nor you can do this:\nwhile True:\n a = input(...
[ 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074580988_python.txt
Q: Setting command parameter descriptions in discord.py I am making a command in a bot to create a profile for a user. It is working fine, but I would like the description of the "name" parameter to say "What would you like to be called?". Here is the code I currently have: import discord from discord import app_comm...
Setting command parameter descriptions in discord.py
I am making a command in a bot to create a profile for a user. It is working fine, but I would like the description of the "name" parameter to say "What would you like to be called?". Here is the code I currently have: import discord from discord import app_commands @tree.command(name="makeprofile", description="Make y...
[ "From the documentation:\n\n@discord.app_commands.describe(**parameters)\n\nDescribes the given parameters by their name using the key of the keyword argument as the name.\n\nSo in your case:\n@app_commands.describe(preferred_name = \"What would you like to be called?\")\n\n" ]
[ 2 ]
[]
[]
[ "discord", "discord.py", "field_description", "parameters", "python" ]
stackoverflow_0074580979_discord_discord.py_field_description_parameters_python.txt
Q: numpy.core._exceptions.MemoryError: Unable to allocate space for array error numpy.core._exceptions.MemoryError: Unable to allocate 362. GiB for an array with shape (2700000, 18000) and data type float64 https://www.kaggle.com/datasets/netflix-inc/netflix-prize-data im working on this netflix prize data set which...
numpy.core._exceptions.MemoryError: Unable to allocate space for array
error numpy.core._exceptions.MemoryError: Unable to allocate 362. GiB for an array with shape (2700000, 18000) and data type float64 https://www.kaggle.com/datasets/netflix-inc/netflix-prize-data im working on this netflix prize data set which has a lot of movies and user ids my work is to apply matrix factorization s...
[ "Your 3 million by 20000 matrix better be sparse or you will need a computer with a very large amount of memory. One copy of a full real matrix that size will require a few hundreds GB or even a few TB of contiguous space.\n\nExploit more efficient matrix representation, like sparse one scipy.sparse.csc_matrix. The...
[ 1 ]
[]
[]
[ "kaggle", "machine_learning", "matrix_factorization", "numpy", "python" ]
stackoverflow_0074580778_kaggle_machine_learning_matrix_factorization_numpy_python.txt
Q: Are dictionaries ordered in Python 3.6+? Dictionaries are insertion ordered as of Python 3.6. It is described as a CPython implementation detail rather than a language feature. The documentation states: dict() now uses a “compact” representation pioneered by PyPy. The memory usage of the new dict() is between 20%...
Are dictionaries ordered in Python 3.6+?
Dictionaries are insertion ordered as of Python 3.6. It is described as a CPython implementation detail rather than a language feature. The documentation states: dict() now uses a “compact” representation pioneered by PyPy. The memory usage of the new dict() is between 20% and 25% smaller compared to Python 3.5. PEP 4...
[ "\nAre dictionaries ordered in Python 3.6+?\n\nThey are insertion ordered[1].\nAs of Python 3.6, for the CPython implementation of Python, dictionaries remember the order of items inserted. This is considered an implementation detail in Python 3.6; you need to use OrderedDict if you want insertion ordering that's g...
[ 774, 82, 36, 21, 12, 0 ]
[]
[]
[ "dictionary", "python", "python_3.6", "python_3.x", "python_internals" ]
stackoverflow_0039980323_dictionary_python_python_3.6_python_3.x_python_internals.txt
Q: 'DataFrame' object has no attribute 'plt' import numpy as np import pandas as pd import matplotlib.pyplot as plt #loding data file=pd.read_csv("students_scoure.csv") # print(file.shape) # print(file.head()) # print(file.describe()) #plot the data file.plt(x='Hours',y='Scores',style='o') plt.show() and i am gett...
'DataFrame' object has no attribute 'plt'
import numpy as np import pandas as pd import matplotlib.pyplot as plt #loding data file=pd.read_csv("students_scoure.csv") # print(file.shape) # print(file.head()) # print(file.describe()) #plot the data file.plt(x='Hours',y='Scores',style='o') plt.show() and i am getting error: 5902 return object.__getattribute__(...
[ "matplotlib.pyplot:\n\nmatplotlib.pyplot is a collection of functions that make matplotlib work like MATLAB. Each pyplot function makes some change to a figure: e.g., creates a figure, creates a plotting area in a figure, plots some lines in a plotting area, decorates the plot with labels, etc.\n\nYou can either us...
[ 0 ]
[]
[]
[ "matplotlib", "pandas", "python" ]
stackoverflow_0074581022_matplotlib_pandas_python.txt
Q: How to get click position on QPixmap There is a QLabel: self.image_label = QtGui.QLabel(self.centralwidget) self.image_label.setSizePolicy(sizePolicy) to which I put QPixmap (generated dynamically): pixmap = QtGui.QPixmap(os.getcwd() + '\\deafult_title.png') self.image_label.setPixmap(pixmap) How to get xy coord...
How to get click position on QPixmap
There is a QLabel: self.image_label = QtGui.QLabel(self.centralwidget) self.image_label.setSizePolicy(sizePolicy) to which I put QPixmap (generated dynamically): pixmap = QtGui.QPixmap(os.getcwd() + '\\deafult_title.png') self.image_label.setPixmap(pixmap) How to get xy coordinates of click, but in respect to image t...
[ "I know it's been a while but i found a solution by calculation the mouse click coordinates relative to the QPixmap object.\nlabel = QLabel(...)\nimg_pix = QPixmap(...)\nlabel.setPixmap(img_pix)\n\n# now you can get mouse click coordinates on the label by overriding `label.mousePressEvent`\n\n# assuming we have the...
[ 0 ]
[]
[]
[ "pyqt", "pyqt4", "python", "python_2.7", "qt" ]
stackoverflow_0035507127_pyqt_pyqt4_python_python_2.7_qt.txt
Q: capture video stream from a website to Flutter App i am trying to build an app that runs video stream after performing some image processing in python. which after processing lives it on a site. from flask import Flask,render_template,Response import string from datetime import datetime ...
capture video stream from a website to Flutter App
i am trying to build an app that runs video stream after performing some image processing in python. which after processing lives it on a site. from flask import Flask,render_template,Response import string from datetime import datetime from datetime import date import cv2 ...
[ "Video Stream Coming from RTSP Protocol can easily be Streamed on to Flutter using Flutter VLC Player. So you don't need to integrate it with Python Server.\nJust Add Link in the Controller:\n _videoPlayerController = VlcPlayerController.network(\n 'rtsp://your Link',\n hwAcc: HwAcc.FULL,\n autoPlay: false,\n ...
[ 0 ]
[]
[]
[ "flutter", "live", "python", "video_streaming" ]
stackoverflow_0071920292_flutter_live_python_video_streaming.txt
Q: Pandas rolling window selection based on a condition and calculate How can I calculate rolling window mean based on a condition? Need to calculate rolling window mean where for each index, I capture coordinate difference within a range < 400. I need to add this as a new column. e.g. at Index cg13869341 = mean(cg1...
Pandas rolling window selection based on a condition and calculate
How can I calculate rolling window mean based on a condition? Need to calculate rolling window mean where for each index, I capture coordinate difference within a range < 400. I need to add this as a new column. e.g. at Index cg13869341 = mean(cg13869341, cg14008030) cg14008030 = mean(cg13869341, cg14008030) cg140080...
[ "With the dataframe you provided:\nimport pandas as pd\n\ndf = pd.DataFrame(\n {\n \"index\": [\n \"cg13869341\",\n \"cg14008030\",\n \"cg14008031\",\n \"cg40826798\",\n \"cg14008033\",\n \"cg14008034\",\n \"cg40826792\",\n ...
[ 0 ]
[]
[]
[ "mean", "pandas", "python", "rolling_computation" ]
stackoverflow_0074558364_mean_pandas_python_rolling_computation.txt
Q: java.lang.NoClassDefFoundError: scala/Product$class using read function from PySpark I'm new to PySpark, and I'm just trying to read a table from my redshift bank. The code looks like the following: import findspark findspark.add_packages("io.github.spark-redshift-community:spark-redshift_2.11:4.0.1") findspark.in...
java.lang.NoClassDefFoundError: scala/Product$class using read function from PySpark
I'm new to PySpark, and I'm just trying to read a table from my redshift bank. The code looks like the following: import findspark findspark.add_packages("io.github.spark-redshift-community:spark-redshift_2.11:4.0.1") findspark.init() spark = SparkSession.builder.appName("Dim_Customer").getOrCreate() df_read_1 = sp...
[ "You're using wrong version of the spark-redshift connector - your version is for Spark 2.4 that uses Scala 2.11, while you need version for Spark 3 that uses Scala 2.12 - change version to 5.1.0 that was released recently (all released versions are listed here)\n" ]
[ 0 ]
[]
[]
[ "amazon_redshift", "amazon_s3", "apache_spark", "pyspark", "python" ]
stackoverflow_0074578273_amazon_redshift_amazon_s3_apache_spark_pyspark_python.txt
Q: Tensorflow calculate hessian of model weights in a batch I am replicating a paper. I have a basic Keras CNN model for MNIST classification. Now for sample z in the training, I want to calculate the hessian matrix of the model parameters with respect to the loss of that sample. I want to average out this hessian ov...
Tensorflow calculate hessian of model weights in a batch
I am replicating a paper. I have a basic Keras CNN model for MNIST classification. Now for sample z in the training, I want to calculate the hessian matrix of the model parameters with respect to the loss of that sample. I want to average out this hessian over the training data (n is number of training data). My final...
[ "That's how hessians are defined, you can only calculate a hessian of a scalar function.\nBut nothing new here, the same happens with gradients, and what is done to handle batches is to accumulate the gradients, something similar can be done with the hessian.\nIf you know how to compute the hessian of the loss, it ...
[ 1, 1 ]
[]
[]
[ "keras", "machine_learning", "python", "tensorflow", "vectorization" ]
stackoverflow_0074454228_keras_machine_learning_python_tensorflow_vectorization.txt
Q: No module named 'tensorflow.keras' ModuleNotFoundError: My system information : Windows version : 11 Python version : 3.10.7 Tensorflow : 2.11.0 pip : 22.3.1 I have checked the previous questions which are similar to mine but they didn't help. ModuleNotFoundError: No module named 'tensorflo...
No module named 'tensorflow.keras' ModuleNotFoundError:
My system information : Windows version : 11 Python version : 3.10.7 Tensorflow : 2.11.0 pip : 22.3.1 I have checked the previous questions which are similar to mine but they didn't help. ModuleNotFoundError: No module named 'tensorflow.keras' Traceback Error: ModuleNotFoundError: No module nam...
[]
[]
[ "Issue will resolve easily by doing the following steps\n\nFirst you have to check whether you had installed tensorflow in system or not if yes then it will work in jupyter notebook.\n\nBut after installing in system tensorflow it shows this error same then uninstall python version and download 3.9 version and afte...
[ -1 ]
[ "jupyter_notebook", "modulenotfounderror", "python", "tensorflow" ]
stackoverflow_0074580987_jupyter_notebook_modulenotfounderror_python_tensorflow.txt
Q: How should I use docker for multiple scripts when each script is running a different logic? I have a project in which 2 scripts are generating data (24/7) and sending it to Kafka. At the same time a consumer/s script is consuming the data from Kafka and processing it. My question is about how should I deploy this...
How should I use docker for multiple scripts when each script is running a different logic?
I have a project in which 2 scripts are generating data (24/7) and sending it to Kafka. At the same time a consumer/s script is consuming the data from Kafka and processing it. My question is about how should I deploy this application, as I am quite new to docker. I have two ideas in mind, but not sure which should I ...
[ "When trying to get something working, a useful maxim is:\n\nPremature optimization is the root of all evil.\n\nThe right answer will depend on exactly how the two producer scripts work. But in general, Docker expects containers to run a single service process on a single port. So the 4 container approach is where ...
[ 0 ]
[]
[]
[ "deployment", "docker", "docker_compose", "python" ]
stackoverflow_0074574848_deployment_docker_docker_compose_python.txt
Q: Python 3.9+ Bluetooth on Windows 10 I've found already very similar questions for this problem but I can't figure it out. I'm trying to connect a TimeBox evo with bluetooth to windows 10 using python with this code: import socket serverMACAddress = "11:75:58:ce:c7:52" port = 4 print("Start") s = socket.socket(soc...
Python 3.9+ Bluetooth on Windows 10
I've found already very similar questions for this problem but I can't figure it out. I'm trying to connect a TimeBox evo with bluetooth to windows 10 using python with this code: import socket serverMACAddress = "11:75:58:ce:c7:52" port = 4 print("Start") s = socket.socket(socket.AF_BLUETOOTH, socket.SOCK_STREAM, soc...
[ "I had the same issue and it worked with a port value of 1...\n" ]
[ 0 ]
[]
[]
[ "bluetooth", "python", "sockets" ]
stackoverflow_0073113252_bluetooth_python_sockets.txt
Q: Unable to parse span tag using python Selenium I am unable to parse the date in the form of " 2022-11-26 " Used css selector and xpath but could parse the "2022-" in the span tag Can you please advise me on the same? <div class="medium-widget event-widget last"> <div class="shrubbery"> <h2 class="widget-title">...
Unable to parse span tag using python Selenium
I am unable to parse the date in the form of " 2022-11-26 " Used css selector and xpath but could parse the "2022-" in the span tag Can you please advise me on the same? <div class="medium-widget event-widget last"> <div class="shrubbery"> <h2 class="widget-title"><span aria-hidden="true" class="icon-calendar"></spa...
[ "Try the below one:\ndriver.find_element(By.XPATH, \".//time\").text\n\nIt gives the output as:\n2022-11-26\n\n" ]
[ 0 ]
[]
[]
[ "python", "selenium" ]
stackoverflow_0074577867_python_selenium.txt
Q: Code completion is not working for OpenCV and Python I am using Ubuntu 14.04. I have installed OpenCV using Adrian Rosebrock's guide. I am also using PyCharm for programming python and opencv. My problem is that I can use code completion for cv2 modules but code completion wont work for instances initiated from cv...
Code completion is not working for OpenCV and Python
I am using Ubuntu 14.04. I have installed OpenCV using Adrian Rosebrock's guide. I am also using PyCharm for programming python and opencv. My problem is that I can use code completion for cv2 modules but code completion wont work for instances initiated from cv2. An example is shown below. This works: This does not: ...
[ "Though I am Window user, I also had faced similar problem with you. In my case, I could solve this problem by importing this way:\nfrom cv2 import cv2\n\nAs I'm lack of knowledge of how does the python imports module, I can't explain you clearly about why this solve the problem, but it works anyway.\nGood luck.\n"...
[ 11, 8, 1, 0 ]
[]
[]
[ "code_completion", "intellisense", "opencv", "python" ]
stackoverflow_0043093400_code_completion_intellisense_opencv_python.txt
Q: How to count length of column while some rows have NaN in it? I have a pandas dataframe. In column I have list. But, some rows NaN. I want to find length of each list, in case it is NaN, I want 0 as length. My_column [1, 2]-> should return 2 [] -> should return 0 NaN -> should return 0 Any help? Thank you. A: d...
How to count length of column while some rows have NaN in it?
I have a pandas dataframe. In column I have list. But, some rows NaN. I want to find length of each list, in case it is NaN, I want 0 as length. My_column [1, 2]-> should return 2 [] -> should return 0 NaN -> should return 0 Any help? Thank you.
[ "df['column'].str.len().fillna(0).astype(int)\n\n", "You can check to see if the item is a list:\n\nIf it is a list - identify the length of that list\nIf it is not a list (eg. np.nan) - then set to zero.\n\noutput = [len(x) if isinstance(x, list) else 0 for x in df['column']]\n\n\n\nHere is an example using your...
[ 3, 1 ]
[]
[]
[ "list", "pandas", "python" ]
stackoverflow_0074579167_list_pandas_python.txt
Q: MinMaxScaler Python Changes original Data I am trying to have 4 of my 5 csv column to predict the last column. i used MinMaxScaler to scale my data to 0-1 range, but at some point when i want to invers_transform it, MinMaxScaler changes my original data. Here is my Code: dataset = read_csv('zz.csv', header=0, inde...
MinMaxScaler Python Changes original Data
I am trying to have 4 of my 5 csv column to predict the last column. i used MinMaxScaler to scale my data to 0-1 range, but at some point when i want to invers_transform it, MinMaxScaler changes my original data. Here is my Code: dataset = read_csv('zz.csv', header=0, index_col=0) values = dataset.values scaler = MinMa...
[ "You are scaling your data when your label column is at the second index.\ntrain_X, train_y = train[:, [0,1,3,4]], train[:, 2]\ntest_X, test_y = test[:, [0,1,3,4]], test[:, 2]\n\nIf you inverse scale the label column is at a different position.\ninv_yhat = np.concatenate((yhat, test_X), axis=1)\ninv_y = np.concaten...
[ 3 ]
[]
[]
[ "lstm", "python", "scikit_learn" ]
stackoverflow_0074580438_lstm_python_scikit_learn.txt
Q: How do I change the text/value of "Add [Model-Name]" button in Django Admin? When we login to Django Admin Interface as a superuser, we see the list of models on the left sidebar. When we click on any model name, we go to the list display page of that model which have 'Add [Model-Name]" button on uuper right corne...
How do I change the text/value of "Add [Model-Name]" button in Django Admin?
When we login to Django Admin Interface as a superuser, we see the list of models on the left sidebar. When we click on any model name, we go to the list display page of that model which have 'Add [Model-Name]" button on uuper right corner. How do I change the text/value of that button? In my case, I have User Model, a...
[ "You can use Meta class options {verbose_name, verbose_name_plural} to change model name.\nfor example,\nfrom django.contrib.auth.models import AbstractUser\n\nclass User(AbstractUser):\n ...\n \n class Meta:\n verbose_name = \"Invite User\"\n verbose_name_plural = \"Invite Users\"\n\nfor mor...
[ 0 ]
[]
[]
[ "django", "django_admin", "django_admin_tools", "python", "python_3.x" ]
stackoverflow_0074533766_django_django_admin_django_admin_tools_python_python_3.x.txt
Q: Executing external python file from inside ns3 I have a python file, containing a pre-trained model. How can I execute this file from inside ns-3 code? The python file will start execution when enough amount of data is gerenerated by the ns-3, which will be given to the pre-trained model. Later, the model predicts...
Executing external python file from inside ns3
I have a python file, containing a pre-trained model. How can I execute this file from inside ns-3 code? The python file will start execution when enough amount of data is gerenerated by the ns-3, which will be given to the pre-trained model. Later, the model predicts one value and it is used in ns-3 during simulation....
[ "In my case, I have tried the following piece of code in a function where I was required to execute the external python file from ns-3. This specific example is for the Ubuntu environment.\nsystem(\"/[path_to_your_python]/anaconda3/bin/python /[path_to_your_inference_file]/inference.py\");\n\nNote: The inference.py...
[ 1 ]
[]
[]
[ "c++", "ns_3", "python" ]
stackoverflow_0074548280_c++_ns_3_python.txt
Q: Python Selenium and Docker I'm trying to create multiple containers with RPAs using selenium and Python, how can I do this without installing python and its libraries in each container? Like a base container with all dependencies and I can export these dependencies to the other containers. Or it cannot be done? s...
Python Selenium and Docker
I'm trying to create multiple containers with RPAs using selenium and Python, how can I do this without installing python and its libraries in each container? Like a base container with all dependencies and I can export these dependencies to the other containers. Or it cannot be done? services: chromedriver: con...
[ "The usual way of doing this is to create an image and host it on DockerHub/ECR. When you change the code, you re-build the image and push a new version, meaning that the dependencies will be re-fetched once. And then your docker-compose services will reference this remote image as many times as needed.\nTo automat...
[ 0 ]
[]
[]
[ "docker", "docker_compose", "python", "selenium" ]
stackoverflow_0074574253_docker_docker_compose_python_selenium.txt
Q: Replace tokens with other words with NLTK in python this is my first question. I've been working in this assignment in which I had to do a Notepad, and then add a lexical analyzer function in it. The goal was to write code in the notepad and then use the lexical analyzer to break it up and categorize it; and for t...
Replace tokens with other words with NLTK in python
this is my first question. I've been working in this assignment in which I had to do a Notepad, and then add a lexical analyzer function in it. The goal was to write code in the notepad and then use the lexical analyzer to break it up and categorize it; and for the last part, it had to change the tokenized words catego...
[ "I would add\nid_count = 0\n\njust before the for loop, and then modify the handling of identifiers like this:\nelif (re.findall(RE_Identificadores, token)):\n id_count += 1\n notepad.insert(END, \"\\n \" + f\"Id{id_count:02d}' + \" --------> Identificadores\")\n\nEDIT\nOn second thoughts, what happens if an ...
[ 0 ]
[]
[]
[ "nlp", "nltk", "python" ]
stackoverflow_0074568563_nlp_nltk_python.txt
Q: How to build python with --enable-framework (--enable-shared) on macos? I want to use PyInstaller to build a MultiOS application. The Project already has a virtual environment using the venv which comes with python by default (have not installed pyenv). I ran into multiple problems and searched a lot. Finally I've...
How to build python with --enable-framework (--enable-shared) on macos?
I want to use PyInstaller to build a MultiOS application. The Project already has a virtual environment using the venv which comes with python by default (have not installed pyenv). I ran into multiple problems and searched a lot. Finally I've come to the conclusion that the problem is my installed version of python do...
[ "For anyone using pyenv, this is what has worked for me:\nPYTHON_CONFIGURE_OPTS=\"--enable-framework\" pyenv install 3.6.15\n\nFound here.\n" ]
[ 0 ]
[]
[]
[ "pyinstaller", "python", "python_3.x" ]
stackoverflow_0060917013_pyinstaller_python_python_3.x.txt
Q: VS Code Azure functions deployment failing with Python Version 3.9 I have a function app (python) in the azure portal which is in python version 3.7. The FUNCTIONS_EXTENSION_VERSION of the function app is ~3. When I deploy the function python) from VS code to update the function in the portal, I'm able to deploy a...
VS Code Azure functions deployment failing with Python Version 3.9
I have a function app (python) in the azure portal which is in python version 3.7. The FUNCTIONS_EXTENSION_VERSION of the function app is ~3. When I deploy the function python) from VS code to update the function in the portal, I'm able to deploy and the update is reflected in the azure portal. But when I change the py...
[ "To upgrade the Python Version 3.7 to 3.9\nStep 1: Update FUNCTIONS_EXTENSION_VERSION to 4 and Python version of Azure Function App in the Portal using the cmdlet:\naz functionapp config set --name krishpyfunapp37to39 --resource-group HariTestRG --linux-fx-version \"PYTHON|3.9\"\n\n\n\nMake Sure Runtime Version is ...
[ 0 ]
[]
[]
[ "azure_functions", "azure_functions_core_tools", "python", "visual_studio_code" ]
stackoverflow_0074572839_azure_functions_azure_functions_core_tools_python_visual_studio_code.txt
Q: How to replace countries other than 'India' and 'U.S.A' by 'Other' in pandas dataframe? I have the following df: df = pd.DataFrame({ 'Q0_0': ["India", "Algeria", "India", "U.S.A", "Morocco", "Tunisia", "U.S.A", "France", "Russia", "Algeria"], 'Q1_1': [np.random.randint(1,100) for i in range(10)], 'Q1_2...
How to replace countries other than 'India' and 'U.S.A' by 'Other' in pandas dataframe?
I have the following df: df = pd.DataFrame({ 'Q0_0': ["India", "Algeria", "India", "U.S.A", "Morocco", "Tunisia", "U.S.A", "France", "Russia", "Algeria"], 'Q1_1': [np.random.randint(1,100) for i in range(10)], 'Q1_2': np.random.random(10), 'Q1_3': np.random.randint(2, size=10), 'Q2_1': [np.random.ra...
[ "You can use pandas.Series.mask with pandas.Series.fillna :\ndf[\"Q0_0\"]= df[\"Q0_0\"].mask(~df[\"Q0_0\"].isin([\"India\", \"U.S.A\"])).fillna(\"Other\")\n\n# Output :\nprint(df)\n\n Q0_0 Q1_1 Q1_2 Q1_3 Q2_1 Q2_2 Q2_3\n0 India 43 0.681795 0 36 0.772289 0\n1 Other 85 0.695352 ...
[ 1, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074581359_dataframe_pandas_python.txt
Q: Clear way to check if n consecutive values out of N are bigger than a threshold and save their index (corresponding to n) I would like to locate n consecutive points out of N from a vector of data with length L. Example: 2 out 3 consecutive points bigger than a certain threshold tr. data = [201,202,203, ..., L] L ...
Clear way to check if n consecutive values out of N are bigger than a threshold and save their index (corresponding to n)
I would like to locate n consecutive points out of N from a vector of data with length L. Example: 2 out 3 consecutive points bigger than a certain threshold tr. data = [201,202,203, ..., L] L = len(data) N=3 tr = 200 for i in range(L-N+1): subset = data[i:i+N] if (subset[0] > tr and subset[1] > tr) or (subset[...
[ "Start by flagging the items that are within the desired range. Then perform a rolling sum of the flags and select the matching indexes in subranges that have the minimum count of flagged items.\nfrom itertools import islice\n\ndef getOver(data,minVal=200,minCount=2,window=3):\n inRange = [minVal<=n for n in da...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0071179081_python.txt
Q: Pandas: sum next 5 items of dataframe after some specific item I have DataFrame which looks like just a list of numbers: original option 1 option 2 1 NaN NaN -1 NaN 9 4 NaN NaN -1 NaN 15 6 9 NaN 7 NaN NaN 2 15 NaN 3 NaN NaN 0 NaN NaN I need to sum next 3 values of df after each negative value - see "opt...
Pandas: sum next 5 items of dataframe after some specific item
I have DataFrame which looks like just a list of numbers: original option 1 option 2 1 NaN NaN -1 NaN 9 4 NaN NaN -1 NaN 15 6 9 NaN 7 NaN NaN 2 15 NaN 3 NaN NaN 0 NaN NaN I need to sum next 3 values of df after each negative value - see "option1" or "option2" columns. If will also work if I ...
[ "One approach could be as follows:\nimport pandas as pd\n\ndata = {'original': {0: 1, 1: -1, 2: 4, 3: -1, 4: 6, 5: 7, 6: 2, 7: 3, 8: 0}}\ndf = pd.DataFrame(data)\n\nn = 3\n\ndf['option 1'] = (df['original'].rolling(n).sum()\n .where(df['original'].shift(n).lt(0))\n )\n ...
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074581217_dataframe_pandas_python.txt
Q: ImportError: No module named 'pygame' I have installed python 3.3.2 and pygame 1.9.2a0. Whenever I try to import pygame by typing: import pygame I get following error message : Python 3.3.2 (v3.3.2:d047928ae3f6, May 16 2013, 00:03:43) [MSC v.1600 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()...
ImportError: No module named 'pygame'
I have installed python 3.3.2 and pygame 1.9.2a0. Whenever I try to import pygame by typing: import pygame I get following error message : Python 3.3.2 (v3.3.2:d047928ae3f6, May 16 2013, 00:03:43) [MSC v.1600 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> import pygame T...
[ "go to python/scripts folder, open a command window to this path, type the\nfollowing:\nC:\\python34\\scripts> python -m pip install pygame\n\nTo test it, open python IDE and type\nimport pygame\n\nprint (pygame.ver)\n\nIt worked for me...\n", "Here are instructions for users with the newer Python 3.5 (Google bro...
[ 32, 14, 12, 10, 3, 3, 2, 2, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ "You gotta use Pycharm and install it in Terminal using pip install pygame and also after that enter Pycharm and hover on pygame in the \"Import pygame\" and in Pycharm it will tell you to download that and you can easily download it and enjoy your result\n", "You could use\npip install pygame\n\nbut if you use I...
[ -1, -1, -4 ]
[ "import", "pygame", "python" ]
stackoverflow_0018317521_import_pygame_python.txt
Q: Why does a yield from inside __next__() return generator object? I am using yield to return the next value in the __next__() function in my class. However it does not return the next value, it returns the generator object. I am trying to better understand iterators and yield. I might be doing it in the wrong way. ...
Why does a yield from inside __next__() return generator object?
I am using yield to return the next value in the __next__() function in my class. However it does not return the next value, it returns the generator object. I am trying to better understand iterators and yield. I might be doing it in the wrong way. Have a look. class MyString: def __init__(self,s): self.s...
[ "next pretty much just calls __next__() in this case. Calling __next__ on your object will start the generator and return it (no magic is done at this point).\n\nIn this case, you might be able to get away with not defining __next__ at all:\nclass MyString:\n def __init__(self,s):\n self.s=s\n\n def _...
[ 17, 13, 0, 0 ]
[]
[]
[ "generator", "next", "python" ]
stackoverflow_0037929956_generator_next_python.txt
Q: pd.read_csv gives entire data in object dtype. How do I convert to int type? I am trying to read the a particular csv (plane-data.csv) but the entire df is in object type. I require 'year' to be in integer type so that I can perform calculations. Please take look at my screenshot My dataset is from plane-data.csv ...
pd.read_csv gives entire data in object dtype. How do I convert to int type?
I am trying to read the a particular csv (plane-data.csv) but the entire df is in object type. I require 'year' to be in integer type so that I can perform calculations. Please take look at my screenshot My dataset is from plane-data.csv link Would really love to have some help, I have been searching the entire interne...
[ "You get the following error:\nTypeError: 'method' object is not subscriptable\n\nbecause you used [] instead of () in df['year'] = df['year'].astype[int]. You should use df['year'] = df['year'].astype(int)\n", "Since the column year contains a string value (literally None), pandas is consedering the whole column...
[ 0, 0 ]
[]
[]
[ "dataframe", "integer", "object", "pandas", "python" ]
stackoverflow_0074581355_dataframe_integer_object_pandas_python.txt
Q: Console/Terminal interactive chosen menu with keyboard arrow main.py: import keyboard import ui import os os.system("cls") ui.play[ui.counter] = "> " + ui.play[ui.counter] + " <" ui.navmenuprint(ui.play) while True: while ui.state == "play": keypressed = keyboard.read_key() while keyboard.is_...
Console/Terminal interactive chosen menu with keyboard arrow
main.py: import keyboard import ui import os os.system("cls") ui.play[ui.counter] = "> " + ui.play[ui.counter] + " <" ui.navmenuprint(ui.play) while True: while ui.state == "play": keypressed = keyboard.read_key() while keyboard.is_pressed("down"): pass while keyboard.is_pressed("up"): pas...
[ "I had to expand global variables with lists inside switchstate function:\ndef switchstate(fromwhere):\n global state, counter, play, play2, shop, shop2\n\n" ]
[ 0 ]
[]
[]
[ "console", "python", "python_3.x", "terminal" ]
stackoverflow_0074578818_console_python_python_3.x_terminal.txt
Q: Counting the keys in a nested dictionary and create a list containing the count under each keys I've the following dictionary { "Africa":{ "All":{"ABC":0,"DEF":0,"GHI":0}, "NA":{"GHI":0}, "EXPORT":{"ABC":0,"DEF":0,"GHI":0}, "RE-EXPORT":{"ABC":0,"DEF":0,"GHI":0} }, "Asia":{ "All":{"ABC":0,"DEF":0,"GH...
Counting the keys in a nested dictionary and create a list containing the count under each keys
I've the following dictionary { "Africa":{ "All":{"ABC":0,"DEF":0,"GHI":0}, "NA":{"GHI":0}, "EXPORT":{"ABC":0,"DEF":0,"GHI":0}, "RE-EXPORT":{"ABC":0,"DEF":0,"GHI":0} }, "Asia":{ "All":{"ABC":0,"DEF":0,"GHI":0}, "NA":{"ABC":0,"DEF":0}, "RE-EXPORT":{"ABC":0,"GHI":0} }, "Australia":{ "All":{"DEF":0...
[ "you can use:\nstart=0\nv1=[]\nv2=[]\nfor i in a: # a= dictionary\n for j in list(a[i].keys()):\n mask=list(a[i][j].keys())\n leng=len(mask)\n mask[0:leng]=x[start:start+ leng]\n start+=leng\n v1.append(mask)\n v2.append(v1)\n v1=[]\n\nprint(v2)\n'''\n[\n [[1, 2, 3], ...
[ 0 ]
[]
[]
[ "dictionary", "grouping", "json", "python", "recursion" ]
stackoverflow_0074581221_dictionary_grouping_json_python_recursion.txt
Q: I am unable to use np.concatenate I have 2 variables from polynomial regression: y_test = [1.57325397 0.72686416] y_pred= [1.57325397 0.72686416] y_test is the y axis of the test i did, while y_pred is are the values i got from regressor.predict (regressor is the object of LinearRegression class). I tried to use ...
I am unable to use np.concatenate
I have 2 variables from polynomial regression: y_test = [1.57325397 0.72686416] y_pred= [1.57325397 0.72686416] y_test is the y axis of the test i did, while y_pred is are the values i got from regressor.predict (regressor is the object of LinearRegression class). I tried to use np.concatenate((y_test),(y_predict)) bu...
[ "You should first separate your list values with a comma:\ny_test = [1.57325397,0.72686416]\ny_pred= [1.57325397,0.72686416]\n\nFor concatenation you should define an axis and use following syntax:\nnp.concatenate((y_test, y_pred), axis=0)\n\nThen you would get\narray([1.57325397, 0.72686416, 1.57325397, 0.72686416...
[ 1 ]
[]
[]
[ "data_science", "linear_regression", "np", "python" ]
stackoverflow_0074581517_data_science_linear_regression_np_python.txt
Q: How can I save the texts I have extracted with OCR from different images in multiple .txt files I made an OCR program using the Python programming language and the tesserOCR library. In the program I have made, I scan all the pictures in a folder and extract the texts in them. But these extracted texts are saved i...
How can I save the texts I have extracted with OCR from different images in multiple .txt files
I made an OCR program using the Python programming language and the tesserOCR library. In the program I have made, I scan all the pictures in a folder and extract the texts in them. But these extracted texts are saved in a single .txt file. How can I save the texts in each image to different .txt files. That is, the te...
[ "I ran a version of your extract function where I removed all the stuff unrelated to writing to a file, and it writes a file for every single file in files.\ndef extract():\n from os.path import splitext\n for file in files:\n try:\n with open(splitext(file)[0] + \".txt\", 'w') as n:\n ...
[ 0, 0 ]
[]
[]
[ "ocr", "python", "python_tesseract", "tesseract" ]
stackoverflow_0074573071_ocr_python_python_tesseract_tesseract.txt
Q: How do I combine similar dates based on a particular value? Trade Date Options Class Underlying Product Type Volume 0 2022-01-03 A A S 14 1 2022-01-03 A A S 3 2 2022-01-03 A A S 42 3 2022-01-03 A A S 10 4 2022-01-03 AA AA S 1924 print(df.groupby('Trade Date','Unde...
How do I combine similar dates based on a particular value?
Trade Date Options Class Underlying Product Type Volume 0 2022-01-03 A A S 14 1 2022-01-03 A A S 3 2 2022-01-03 A A S 42 3 2022-01-03 A A S 10 4 2022-01-03 AA AA S 1924 print(df.groupby('Trade Date','Underlying').sum()) How do combine all the similar dates together b...
[ "df.groupby(['Trade Date', 'Underlying'])['Volume'].sum()\n\noutput:\n> Trade Date Underlying\n> 2022-01-03 A 69\n> AA 1924\n> Name: Volume, dtype: int64\n\n", "You're close, you can in fact use GroupBy.sum but you need to put the groups/columns inside square...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074581568_python.txt
Q: Struggling to make a nested json API ouput into a pandas df I am working with json data for the first time in Python (API output). I am struggling a bit to understand how to convert the following results to a pandas-like dataframe: {'coord': {'lon': 13.4105, 'lat': 52.5244}, 'weather': [{'id': 801, 'main': 'Clouds...
Struggling to make a nested json API ouput into a pandas df
I am working with json data for the first time in Python (API output). I am struggling a bit to understand how to convert the following results to a pandas-like dataframe: {'coord': {'lon': 13.4105, 'lat': 52.5244}, 'weather': [{'id': 801, 'main': 'Clouds', 'description': 'few clouds', 'icon': '02d'}], 'base': 'station...
[ "Note: Do not share your data as a picture in your next questions. If you share it as a text, we can easily copy and paste it. You can use this for now.\na={'coord': {'lon': 13.4105, 'lat': 52.5244}, 'weather': [{'id': 741, 'main': 'Fog', 'description': 'fog', 'icon': '50d'}], 'bas e': 'stations', 'main': {'temp': ...
[ 1 ]
[]
[]
[ "json", "pandas", "python" ]
stackoverflow_0074574216_json_pandas_python.txt
Q: Sprite shadow changing to full black player.png shadow comparison The shadows are different when I blit the player image to a surface and then loading that surface to the display vs loading the entire image on the display import pygame pygame.init() display = pygame.display.set_mode((1280, 736)) display.fill('#55...
Sprite shadow changing to full black
player.png shadow comparison The shadows are different when I blit the player image to a surface and then loading that surface to the display vs loading the entire image on the display import pygame pygame.init() display = pygame.display.set_mode((1280, 736)) display.fill('#555358') clock = pygame.time.Clock() if __...
[ "You need to create a surface with an alpha channel (pygame.SRCALPHA) instead of converting it with convert_alpha and setting a color key with set_colorkey:\nimage_1 = pygame.Surface((16, 16), pygame.SRCALPHA)\nimage_1.blit(\n pygame.image.load('player.png').convert_alpha(),\n (0, 0),\n (16, 32...
[ 1 ]
[]
[]
[ "pygame", "pygame_surface", "python", "python_3.x" ]
stackoverflow_0074581665_pygame_pygame_surface_python_python_3.x.txt
Q: Asyncio lock acquire task at end of event loop Consider the code below import asyncio async def waiter2(lock): print('2 waiting for it ...') async with lock: print('2 ... got it!') async def waiter(lock): print('waiting for it ...') async with lock: print('... got...
Asyncio lock acquire task at end of event loop
Consider the code below import asyncio async def waiter2(lock): print('2 waiting for it ...') async with lock: print('2 ... got it!') async def waiter(lock): print('waiting for it ...') async with lock: print('... got it!') async def main(): lock = asyncio.Lock(...
[ "You need to await for the tasks to finish. In asyncio only one task is running at time. So when you release the lock your main function and the whole program will finish without switching to waiter2 task.\nimport asyncio\n\n\nasync def waiter2(lock):\n print(\"2 waiting for it ...\")\n async with lock:\n ...
[ 1 ]
[]
[]
[ "asynchronous", "python", "python_asyncio" ]
stackoverflow_0074581494_asynchronous_python_python_asyncio.txt
Q: List matches of page.search_for() with PyMuPDF I'm writing a script to highlight text from a list of quotes in a PDF. The quotes are in the list text_list. I use this code to highlight the text in the PDF: import fitz #Load Document doc = fitz.open(filename) #Iterate over pages for page in doc: # iterate through ...
List matches of page.search_for() with PyMuPDF
I'm writing a script to highlight text from a list of quotes in a PDF. The quotes are in the list text_list. I use this code to highlight the text in the PDF: import fitz #Load Document doc = fitz.open(filename) #Iterate over pages for page in doc: # iterate through each text using for loop and annotate for i, tex...
[ "The list of hit rectangles / quads rl will be empty if nothing was found.\nI suggest you check if rl == []: and depend adding highlights on this as well as adding the respective text to some no_hit list.\nProbably better the other way round:\nYour text list better should be a Python set. If a text was ever found p...
[ 2 ]
[]
[]
[ "pymupdf", "python" ]
stackoverflow_0074581135_pymupdf_python.txt
Q: How to %run a list of notebooks in Databricks I'd like to %run a list of notebooks from another Databricks notebook. my_notebooks = ["./setup", "./do_the_main_thing", "./check_results"] for notebook in my_notebooks: %run notebook This doesn't work ofcourse. I don't want to use dbutils.notebook.run() as this c...
How to %run a list of notebooks in Databricks
I'd like to %run a list of notebooks from another Databricks notebook. my_notebooks = ["./setup", "./do_the_main_thing", "./check_results"] for notebook in my_notebooks: %run notebook This doesn't work ofcourse. I don't want to use dbutils.notebook.run() as this creates new jobs and doesn't return anything back - ...
[ "Unfortunately it's not possible to do - %run doesn't allow to pass notebook name as a variable (see this answer with more details, and possible workaround).\nAnother approach would be to use so-called arbitrary files in repos functionality - if you define code as a Python file instead of notebook, then you'll be a...
[ 0 ]
[]
[]
[ "databricks", "ipython", "python" ]
stackoverflow_0074518979_databricks_ipython_python.txt
Q: Python change diction value from key in a string I have successfully used recursion to find a key to a variable I want to change in an API reponse json. The recursion returns the key the equivilant is like this: obj_key = "obj['key1']['key2'][1]['key3'][4]['key4'][0]" if I eval this: eval(obj_key) I get the valu...
Python change diction value from key in a string
I have successfully used recursion to find a key to a variable I want to change in an API reponse json. The recursion returns the key the equivilant is like this: obj_key = "obj['key1']['key2'][1]['key3'][4]['key4'][0]" if I eval this: eval(obj_key) I get the value no problem. Now I want to change the value if it isn...
[ "Using exec instead of eval seems solving this problem:\neval(\"y=12\") #SyntaxError: invalid syntax\n\nBut replacing it with exec:\nexec(\"y=12\")\nprint(y) #12\n\n", "Instead of using eval, you could keep a list of keys and a reference to the object. So instead of building a string\n\"obj['key1']['key2'][1]['ke...
[ 1, 0 ]
[]
[]
[ "dictionary", "object", "python", "string" ]
stackoverflow_0074581669_dictionary_object_python_string.txt
Q: Qt - update view size on delegate sizeHint change I have a QTreeView with a QStyledItemDelegate inside of it. When a certain action occurs to the delegate, its size is supposed to change. However I haven't figured out how to get the QTreeView's rows to resize in response to the delegate's editor size changing. I t...
Qt - update view size on delegate sizeHint change
I have a QTreeView with a QStyledItemDelegate inside of it. When a certain action occurs to the delegate, its size is supposed to change. However I haven't figured out how to get the QTreeView's rows to resize in response to the delegate's editor size changing. I tried QTreeView.updateGeometry and QTreeView.repaint and...
[ "As the documentation about updateGeometries() explains, it:\n\nUpdates the geometry of the child widgets of the view.\n\nThis is used to update the widgets (editors, scroll bars, headers, etc) based on the current view state. It doesn't consider the editor size hints, so that call or the attempt to update the size...
[ 1, 1 ]
[]
[]
[ "pyside2", "python" ]
stackoverflow_0071358160_pyside2_python.txt
Q: Getting ValueError: y contains new labels when using scikit learn's LabelEncoder I have a series like: df['ID'] = ['ABC123', 'IDF345', ...] I'm using scikit's LabelEncoder to convert it to numerical values to be fed into the RandomForestClassifier. During the training, I'm doing as follows: le_id = LabelEncoder()...
Getting ValueError: y contains new labels when using scikit learn's LabelEncoder
I have a series like: df['ID'] = ['ABC123', 'IDF345', ...] I'm using scikit's LabelEncoder to convert it to numerical values to be fed into the RandomForestClassifier. During the training, I'm doing as follows: le_id = LabelEncoder() df['ID'] = le_id.fit_transform(df.ID) But, now for testing/prediction, when I pass ...
[ "I think the error message is very clear: Your test dataset contains ID labels which have not been included in your training data set. For this items, the LabelEncoder can not find a suitable numeric value to represent. There are a few ways to solve this problem. You can either try to balance your data set, so that...
[ 8, 4, 2, 0, 0, 0, 0 ]
[ "I hope this helps someone as it's more recent.\nsklearn uses the fit_transform to perform the fit function and transform function directing on label encoding.\nTo solve the problem for Y label throwing error for unseen values, use:\nfrom sklearn.preprocessing import LabelEncoder\nle = LabelEncoder() \nle.fit_t...
[ -1, -4 ]
[ "categorical_data", "encoding", "machine_learning", "python", "scikit_learn" ]
stackoverflow_0046288517_categorical_data_encoding_machine_learning_python_scikit_learn.txt
Q: cannot find element after being redirected to a webpage - python selenium this is not the exact code but basically the bug is the same. I use python selenium to go on a website. There are two buttons. The first one redirects me to one page. The second button is on that page that is has redirectd me to. For some re...
cannot find element after being redirected to a webpage - python selenium
this is not the exact code but basically the bug is the same. I use python selenium to go on a website. There are two buttons. The first one redirects me to one page. The second button is on that page that is has redirectd me to. For some reason, it says that the button on the second page cannot be found. from selenium...
[ "Try this:\n# Needed libs\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\n#Define web driver as a Chrome driver and navigate. I am in Linux, in Windows you can def...
[ 0 ]
[]
[]
[ "python", "selenium", "selenium_chromedriver", "selenium_webdriver" ]
stackoverflow_0074581734_python_selenium_selenium_chromedriver_selenium_webdriver.txt
Q: Adding test's docstring to the html report of a parametrized test as Description (pytest, Python) I am running a parametrized test and I want to use kind of parametrized docstring in the html report. Normally, without the parametrization, it is the docstring of each test that I see as the description for the parti...
Adding test's docstring to the html report of a parametrized test as Description (pytest, Python)
I am running a parametrized test and I want to use kind of parametrized docstring in the html report. Normally, without the parametrization, it is the docstring of each test that I see as the description for the particular test. Now, with the parametrization, it is, of course, always the same text. Can I add a name, or...
[ "If you're following the guide to modify the results table from the pytest-html plugin documentation, you can use the item object to add the ID into the cell with item.callspec.id:\n@pytest.hookimpl(hookwrapper=True)\ndef pytest_runtest_makereport(item, call):\n outcome = yield\n report = outcome.get_result()...
[ 0 ]
[]
[]
[ "parametrized_testing", "pytest", "python" ]
stackoverflow_0074547592_parametrized_testing_pytest_python.txt
Q: Adding Key-Value pair to a Series that does not have a given Key (Pandas) I want to update a series if it is missing a key, but my code is generating an error. This is my code: for item in list: if item not in my_series.keys(): my_series = my_series[item] = 0 Where my_series is a series of dtype int64...
Adding Key-Value pair to a Series that does not have a given Key (Pandas)
I want to update a series if it is missing a key, but my code is generating an error. This is my code: for item in list: if item not in my_series.keys(): my_series = my_series[item] = 0 Where my_series is a series of dtype int64. It's actually a value count. My code above is generating the following error ...
[ "What do you mean by \"series\"? There's no such data type in python if I'm not mistaken. You seem to use it as it was a dict. Do you need to set default value to 0 for a key \"item\"?\nIf so:\nfor item in <definitely_list_is_a_bad_name>:\n my_series[item] = my_series.get(item) if my_series.get(item, None) is no...
[ 0, 0 ]
[]
[]
[ "list", "pandas", "python", "series" ]
stackoverflow_0074577836_list_pandas_python_series.txt
Q: Splitting an image in half, leaving one half transparent, keeping the same image dimensions I have an image, I want to split it vertically. When I do this I want to maintain the same aspect ratio (1024x1024), but make the other half of each image transparent. (Imagine going into photoshop, and just deleting half o...
Splitting an image in half, leaving one half transparent, keeping the same image dimensions
I have an image, I want to split it vertically. When I do this I want to maintain the same aspect ratio (1024x1024), but make the other half of each image transparent. (Imagine going into photoshop, and just deleting half of an image leaving the transparent mask.) I used image slicer to easily slice in half vertically....
[ "You don't really actually want to split the image in half, since you want to retain the original dimensions. So you actually just want to make one half transparent - remember the alpha/transparency is just a layer in your image, so all you need is a new, alpha layer that is white where you want to see the original...
[ 1 ]
[]
[]
[ "image", "python", "python_imaging_library" ]
stackoverflow_0074578586_image_python_python_imaging_library.txt
Q: Setting SQLAlchemy autoincrement start value The autoincrement argument in SQLAlchemy seems to be only True and False, but I want to set the pre-defined value aid = 1001, the via autoincrement aid = 1002 when the next insert is done. In SQL, can be changed like: ALTER TABLE article AUTO_INCREMENT = 1001; I'm usin...
Setting SQLAlchemy autoincrement start value
The autoincrement argument in SQLAlchemy seems to be only True and False, but I want to set the pre-defined value aid = 1001, the via autoincrement aid = 1002 when the next insert is done. In SQL, can be changed like: ALTER TABLE article AUTO_INCREMENT = 1001; I'm using MySQL and I have tried following, but it doesn't...
[ "You can achieve this by using DDLEvents. This will allow you to run additional SQL statements just after the CREATE TABLE ran. Look at the examples in the link, but I am guessing your code will look similar to below:\nfrom sqlalchemy import event\nfrom sqlalchemy import DDL\nevent.listen(\n Article.__table__,\n...
[ 24, 20, 3, 3, 1, 0 ]
[]
[]
[ "auto_increment", "python", "sqlalchemy" ]
stackoverflow_0010494033_auto_increment_python_sqlalchemy.txt
Q: How is the text from this pdf encoded? I have some pdfs with data about machine parts and i am trying to extract sizes. I extracted the text from a pdf via pypdfium2. import pypdfium2 as pdfium pdf = pdfium.PdfDocument("myfile.pdf") page=pdf[1] textpage = page.get_textpage() Most of the text is readable but for s...
How is the text from this pdf encoded?
I have some pdfs with data about machine parts and i am trying to extract sizes. I extracted the text from a pdf via pypdfium2. import pypdfium2 as pdfium pdf = pdfium.PdfDocument("myfile.pdf") page=pdf[1] textpage = page.get_textpage() Most of the text is readable but for some reason the important data is not readabl...
[ "This is not uncommon CID CMAP substitution as output in python notation, and is usua;;y specific to a single font with 6 random ID e.g.UHIIUQ+Font name\noften found for subsetting fonts that have a limited range of characters.\nshould be 3,0 8,8 +0,058/0 5,0 4,0 4,5\n\\r\\n\\ = cR Nl (windows line feed \\x0d\\x0a)...
[ 1, 0 ]
[]
[]
[ "encoding", "pdf_extraction", "python" ]
stackoverflow_0074534840_encoding_pdf_extraction_python.txt
Q: Calculate Average Dynamically in Python I have 3 variables A, B, C. I need to calculate the average of the values of A, B and C. But sometimes I want to exclude a variable when it has no data. for example, if all variable have data, formula should be (A+B+C)/3. if A didn't have data, formula should be like (B+C)/2...
Calculate Average Dynamically in Python
I have 3 variables A, B, C. I need to calculate the average of the values of A, B and C. But sometimes I want to exclude a variable when it has no data. for example, if all variable have data, formula should be (A+B+C)/3. if A didn't have data, formula should be like (B+C)/2. Any suggestions? I tried avg() function, bu...
[ "you can use the following, which basically excludes the value from the list if its None\nimport numpy as np\nA=None\nB=5\nC=4\n\nnp.mean([num for num in[A,B,C] if num is not None])\n>>> 4.5\n\n" ]
[ 0 ]
[]
[]
[ "average", "python", "python_3.x" ]
stackoverflow_0074581841_average_python_python_3.x.txt
Q: How to extract multiple strings from list spaced apart I have the following list: lst = ['L38A', '38', 'L', 'A', '-6.7742', '-3.5671', '0.00226028', '0.4888', 'L38C', '38', 'L', 'C', '-7.7904', '-6.6306', '0.0', '0.4888', 'L38D', '38', 'L', 'D', '-6.3475', '-3.0068', '0.00398551', '0.4888', 'L38E', '38', 'L', 'E',...
How to extract multiple strings from list spaced apart
I have the following list: lst = ['L38A', '38', 'L', 'A', '-6.7742', '-3.5671', '0.00226028', '0.4888', 'L38C', '38', 'L', 'C', '-7.7904', '-6.6306', '0.0', '0.4888', 'L38D', '38', 'L', 'D', '-6.3475', '-3.0068', '0.00398551', '0.4888', 'L38E', '38', 'L', 'E', '-6.4752', '-3.4645', '0.00250913', '0.4888'] I'm looking t...
[ "This works:\na=[(x,y) for x,y in zip(*[iter(lst[::4])]*2)]\n\nprint(a)\n\n# [('L38A', '-6.7742'), ('L38C', '-7.7904'), ('L38D', '-6.3475'), ('L38E', '-6.4752')]\n\n", "We can handle this via a zip operation and list comprehension:\nlst = ['L38A', '38', 'L', 'A', '-6.7742', '-3.5671', '0.00226028', '0.4888', 'L38...
[ 2, 2 ]
[]
[]
[ "list", "python" ]
stackoverflow_0074581912_list_python.txt
Q: Running poetry fails with /usr/bin/env: ‘python’: No such file or directory I just installed poetry with the following install script curl -sSL https://raw.githubusercontent.com/python-poetry/poetry/master/get-poetry.py | python3 However, when I execute poetry it fails with the following error $ poetry /usr/bin/e...
Running poetry fails with /usr/bin/env: ‘python’: No such file or directory
I just installed poetry with the following install script curl -sSL https://raw.githubusercontent.com/python-poetry/poetry/master/get-poetry.py | python3 However, when I execute poetry it fails with the following error $ poetry /usr/bin/env: ‘python’: No such file or directory I recently upgraded to ubuntu 20.04, is ...
[ "poetry is dependent on whatever python is and doesn't attempt to use a specific version of python unless otherwise specified.\nThe above issue will exist on ubuntu systems moving forward 20.04 onwards as python2.7 is deprecated and the python command does not map to python3.x\nYou'll find specifying an alias for p...
[ 23, 4, 1 ]
[]
[]
[ "python", "python_poetry", "ubuntu_20.04" ]
stackoverflow_0061921940_python_python_poetry_ubuntu_20.04.txt
Q: ThreadPoolExecutor - How can you bring results to Excel? I'm using the Yahoo finance API to extract data using ThreadPoolExecutor. Can anyone show me how to bring the output to excel if possible? Thanks Code import yfinance as yf from concurrent.futures import ThreadPoolExecutor def get_stats(ticker): info = ...
ThreadPoolExecutor - How can you bring results to Excel?
I'm using the Yahoo finance API to extract data using ThreadPoolExecutor. Can anyone show me how to bring the output to excel if possible? Thanks Code import yfinance as yf from concurrent.futures import ThreadPoolExecutor def get_stats(ticker): info = yf.Tickers(ticker).tickers[ticker].info print(f"{ticker} {...
[ "First, you can make a empty list and feed id with every returned result by the API, then construct a dataframe from it and finally use pandas.to_excel to make the Excel spreadsheet.\nTry this :\nimport yfinance as yf\nfrom concurrent.futures import ThreadPoolExecutor\nimport pandas as pd\n\n\nlist_of_futures= []\n...
[ 2 ]
[]
[]
[ "pandas", "python", "threadpoolexecutor" ]
stackoverflow_0074581604_pandas_python_threadpoolexecutor.txt
Q: How to print 'x' if the input int is b/w the desired numbers in python? So, I started making a program and now I require it to print anything I like if the number is between 1-100, How to I make the program realize that it needs to print it if the number's between 90 and 100? #This is a sample code F2 = int(input(...
How to print 'x' if the input int is b/w the desired numbers in python?
So, I started making a program and now I require it to print anything I like if the number is between 1-100, How to I make the program realize that it needs to print it if the number's between 90 and 100? #This is a sample code F2 = int(input()) if F2 == range(90 , 100): print("A") else: print("BRUH") I'm real...
[ "You're checking if f2 is equal to range(90,100), correct form is if it's IN the range(90,100).\nif F2 in range(90,101): #last number is not included in range(101 won't be included)\n print('A')\n\nalso, if you try\nf2 = range(90,100)\nprint(f2)\n\nyou'll understand what f2 == range(90,100) means.\nif you use in...
[ 2, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0074581868_python.txt
Q: Web scrape data from exchange using API I am looking to web scrape the second table containing the "Number of Insider Shares Traded" from the following website: https://www.nasdaq.com/market-activity/stocks/aapl/insider-activity Preferably I need someone to show how to use the Nasdaq api if possible. I believe the...
Web scrape data from exchange using API
I am looking to web scrape the second table containing the "Number of Insider Shares Traded" from the following website: https://www.nasdaq.com/market-activity/stocks/aapl/insider-activity Preferably I need someone to show how to use the Nasdaq api if possible. I believe the way I'd normally webscrape (using beautifulS...
[ "Here is one way of getting that data (as a dictionary: please say if you want it as a table):\nimport requests\n\nheaders = {\n 'accept-language': 'en-US,en;q=0.9',\n 'origin': 'https://www.nasdaq.com/',\n 'referer': 'https://www.nasdaq.com/',\n 'accept': 'application/json, text/plain, */*',\n 'User...
[ 1 ]
[]
[]
[ "api", "json", "python" ]
stackoverflow_0074581988_api_json_python.txt
Q: How to sort the elements of a list based off associated index python I am looking to sort MyArray[] of size n elements so that MyArray[n] = n. If the element is missing it should be replaced with a -1. Here is an example: Input : MyArray = [-1, -1, 6, 1, 9, 3, 2, -1, 4, -1] Output : [-1, 1, 2, 3, 4, -1, 6, -1, -1,...
How to sort the elements of a list based off associated index python
I am looking to sort MyArray[] of size n elements so that MyArray[n] = n. If the element is missing it should be replaced with a -1. Here is an example: Input : MyArray = [-1, -1, 6, 1, 9, 3, 2, -1, 4, -1] Output : [-1, 1, 2, 3, 4, -1, 6, -1, -1, 9] MyArray = [-1, -1, 6, 1, 9, 3, 2, -1, 4, -1] MyArrayNew = [] for n in ...
[ "Two ways to sort an array that I know in python\n\nfor an inplace sorting: apply the sort() method to your array as\nMyArray.sort()\nThe second way is to use nested FOR ... LOOP and compare values in the array from Index 0 to the final item. I normally use a temp value to keep the previous value, compare it with t...
[ 1, 1 ]
[]
[]
[ "list", "python", "sorting" ]
stackoverflow_0074581970_list_python_sorting.txt
Q: NameError: name 'array' is not defined in python I get NameError: name 'array' is not defined in python error when I want to create array, for example: a = array([1,8,3]) What am I doing wrong? How to use arrays? A: You need to import the array method from the module. from array import array http://docs.python....
NameError: name 'array' is not defined in python
I get NameError: name 'array' is not defined in python error when I want to create array, for example: a = array([1,8,3]) What am I doing wrong? How to use arrays?
[ "You need to import the array method from the module.\nfrom array import array\nhttp://docs.python.org/library/array.html\n", "For basic Python, you should just use a list (as others have already noted).\nIf you are trying to use NumPy and you want a NumPy array:\nimport numpy as np\n\na = np.array([1,8,3])\n\nIf...
[ 61, 25, 2, 2, 1, 1, 0, 0 ]
[]
[]
[ "arrays", "python" ]
stackoverflow_0007098938_arrays_python.txt
Q: communication with my bot discord doesnt work Hello im trying to communicate with my bot discord but its doesnt answer the bot is online but no answer here the following code : import discord client = discord.Client(intents=discord.Intents.default()) client.run("token") @client.event async def on_message(message...
communication with my bot discord doesnt work
Hello im trying to communicate with my bot discord but its doesnt answer the bot is online but no answer here the following code : import discord client = discord.Client(intents=discord.Intents.default()) client.run("token") @client.event async def on_message(message): if message.content == "ping": await...
[ "You need to enable the message content intent.\nadd this in your code under your intents definitions\nintents.message_content = True\n\nthen head to the developer dashboard\nand enable the Message Content at the Privileged Intents after that your code should work ;-)\n", "Having your bot to answer to sent messag...
[ 2, 1, 1 ]
[]
[]
[ "discord.py", "python" ]
stackoverflow_0074572757_discord.py_python.txt
Q: How do I express an extended subtype of a generic object in Python? I want to set an attribute on an object, but keep the rest of the object intact, e.g. from typing import cast, TypeVar, Generic T = TypeVar("T") class HasFoo(Generic[T]): foo: str def set_foo_on_obj(obj: T) -> HasFoo[T]: setattr(obj, 'f...
How do I express an extended subtype of a generic object in Python?
I want to set an attribute on an object, but keep the rest of the object intact, e.g. from typing import cast, TypeVar, Generic T = TypeVar("T") class HasFoo(Generic[T]): foo: str def set_foo_on_obj(obj: T) -> HasFoo[T]: setattr(obj, 'foo', 'some_value') return cast(HasFoo[T], obj) def func(a: int) -...
[ "As mentioned by @paweł-rubin, there is no elegant/direct way that generalizes over any given type so long as intersection types are missing from the type system.\nYou can write workarounds with different degrees of complexity for specific use cases though using structural subtyping with what is already offered by ...
[ 2 ]
[]
[]
[ "mypy", "python", "python_typing" ]
stackoverflow_0074570598_mypy_python_python_typing.txt
Q: Importing Numpy into Sublime Text 3 I'm new to coding and I have been learning it on Jupyter. I have anaconda, Sublime Text 3, and the numpy package installed on my Mac. On Jupyter, we would import numpy by simply typing import numpy as np However, this doesnt seem to work on Sublime as I get the error Module...
Importing Numpy into Sublime Text 3
I'm new to coding and I have been learning it on Jupyter. I have anaconda, Sublime Text 3, and the numpy package installed on my Mac. On Jupyter, we would import numpy by simply typing import numpy as np However, this doesnt seem to work on Sublime as I get the error ModuleNotFoundError: No module named 'numpy' I ...
[ "If you have Annaconda, install Spyder. \nIf you continue to have this problem, you could check all the lib install from anaconda.\nI suggest you to install nmpy from anaconda.\n", "import numpy as np\narr=np.array([19,28,48])\n\n" ]
[ 1, 0 ]
[]
[]
[ "numpy", "python", "sublimetext3" ]
stackoverflow_0050929439_numpy_python_sublimetext3.txt
Q: How to use transaction with "async" functions in Django? When async def call_test(request): called async def test(): as shown below (I use Django==3.1.7): async def test(): for _ in range(0, 3): print("Test") async def call_test(request): await test() # Here return HttpResponse("Call_test") ...
How to use transaction with "async" functions in Django?
When async def call_test(request): called async def test(): as shown below (I use Django==3.1.7): async def test(): for _ in range(0, 3): print("Test") async def call_test(request): await test() # Here return HttpResponse("Call_test") There was no error displaying the proper result below on cons...
[ "I found the documentation of Django 4.1 says below:\n\nTransactions do not yet work in async mode. If you have a piece of code that needs transactions behavior, we recommend you write that piece as a single synchronous function and call it using sync_to_async().\n\nSo, @transaction.atomic() cannot be used with asy...
[ 0 ]
[]
[]
[ "asynchronous", "django", "python", "python_3.x", "transactions" ]
stackoverflow_0074575922_asynchronous_django_python_python_3.x_transactions.txt