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: Why is this blitting two times? I am trying to make a microsoft paint like program using pygame, however im running into an issue while trying to create "stickers". my sticker code looks like: if canvasRect.collidepoint(mx,my) and mb[0]: for j in range(12,len(tools)): screen.set_clip(canvasRect...
Why is this blitting two times?
I am trying to make a microsoft paint like program using pygame, however im running into an issue while trying to create "stickers". my sticker code looks like: if canvasRect.collidepoint(mx,my) and mb[0]: for j in range(12,len(tools)): screen.set_clip(canvasRect) if tool==tools[j]: ...
[ "It's pretty difficult to determine what it is you want from the small snippet of code, but I'm guessing the desire is:\n\nIf the mouse-button-1 is clicked mb[0], draw a \"stamp\" (AKA \"sticker\") at the mouse-cordinates mx,my.\n\nIt looks like your code is drawing the image as the click is made. As I said in a c...
[ 0 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0074503479_pygame_python.txt
Q: Labeling year on time series I am working on a timeseries plot from data that looks like the following: import pandas as pd data = {'index': [1, 34, 78, 900, 1200, 5000, 9001, 12000, 15234, 23432], 'rating': [90, 85, 89, 82, 78, 65, 54, 32, 39, 45], 'Year': [2005, 2005, 2005, 2006, 2006, 2006, 2...
Labeling year on time series
I am working on a timeseries plot from data that looks like the following: import pandas as pd data = {'index': [1, 34, 78, 900, 1200, 5000, 9001, 12000, 15234, 23432], 'rating': [90, 85, 89, 82, 78, 65, 54, 32, 39, 45], 'Year': [2005, 2005, 2005, 2006, 2006, 2006, 2007, 2008, 2009, 2009]} df = pd.D...
[ "I am assuming that you have already sorted the DataFrame using the index column.\nHere's a solution using bar (column) chart using matplotlib.\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n# [optional] create a dictionary of colors with year as keys. It is better if this is dynamically generated if you h...
[ 1 ]
[]
[]
[ "data_analysis", "numpy", "plotly", "python", "time_series" ]
stackoverflow_0074525913_data_analysis_numpy_plotly_python_time_series.txt
Q: Websites using scrapy-playwright and only playwright work differently I am trying to log into a webpage using scrapy-playwright, as I want the nice integration with scrapy. I can't log in using scrapy-playwright, as it redirects to a page that does not exist. I have also tried doing a post request instead of click...
Websites using scrapy-playwright and only playwright work differently
I am trying to log into a webpage using scrapy-playwright, as I want the nice integration with scrapy. I can't log in using scrapy-playwright, as it redirects to a page that does not exist. I have also tried doing a post request instead of clicking, that doesn't work either. However, if I try the same thing using only ...
[ "As a possible workaround, if you are redirected(to the broken page) after the token/cookie is granted, you can as well navigate to a normal site url, and you should be logged in\n" ]
[ 0 ]
[]
[]
[ "playwright", "playwright_python", "python", "scrapy", "web_scraping" ]
stackoverflow_0072375388_playwright_playwright_python_python_scrapy_web_scraping.txt
Q: Railway.app: Is Procfile Successfully Loading a Worker? Migrating from Heroku to Railway.app: Python Flask app with Redis and Postgres. Using Redis as an asynchronous job queue, with the RQ Redis queue python library. Procfile, which works in dev, looks like this: web: gunicorn app:app worker: rq worker --with-sch...
Railway.app: Is Procfile Successfully Loading a Worker?
Migrating from Heroku to Railway.app: Python Flask app with Redis and Postgres. Using Redis as an asynchronous job queue, with the RQ Redis queue python library. Procfile, which works in dev, looks like this: web: gunicorn app:app worker: rq worker --with-scheduler The last line of the Deploy log looks as if the worke...
[ "You can use docker deployment.\n" ]
[ 0 ]
[]
[]
[ "flask", "python", "python_3.x", "redis", "rq" ]
stackoverflow_0073998727_flask_python_python_3.x_redis_rq.txt
Q: PuLP not printing output on IPython cell I am using PuLP and IPython/Jupyter Notebook for a project. I have the following cell of code: import pulp model = pulp.LpProblem('Example', pulp.LpMinimize) x1 = pulp.LpVariable('x1', lowBound=0, cat='Integer') x2 = pulp.LpVariable('x2', lowBound=0, cat='Integer') model +...
PuLP not printing output on IPython cell
I am using PuLP and IPython/Jupyter Notebook for a project. I have the following cell of code: import pulp model = pulp.LpProblem('Example', pulp.LpMinimize) x1 = pulp.LpVariable('x1', lowBound=0, cat='Integer') x2 = pulp.LpVariable('x2', lowBound=0, cat='Integer') model += -2*x1 - 3*x2 model += x1 + 2*x2 <= 7 model ...
[ "Use %%python cell magic to print terminal's output.\n%%python\nimport pulp\nmodel = pulp.LpProblem('Example', pulp.LpMinimize)\nx1 = pulp.LpVariable('x1', lowBound=0, cat='Integer')\nx2 = pulp.LpVariable('x2', lowBound=0, cat='Integer')\n\nmodel += -2*x1 - 3*x2 \nmodel += x1 + 2*x2 <= 7\nmodel += 2*x1 + x2 <= 7\n\...
[ 1, 0 ]
[]
[]
[ "ipython_notebook", "mathematical_optimization", "pulp", "python" ]
stackoverflow_0034475510_ipython_notebook_mathematical_optimization_pulp_python.txt
Q: Split Polygons by Overlap in Python I have the Json data that I want to Split by overlap polygons data_01 = { "type": "FeatureCollection", "features": [ { "type": "Feature", "geometry": { "type": "Polygon", "coordinates": [ ...
Split Polygons by Overlap in Python
I have the Json data that I want to Split by overlap polygons data_01 = { "type": "FeatureCollection", "features": [ { "type": "Feature", "geometry": { "type": "Polygon", "coordinates": [ [[2, 2], [2, 22], [22, 22], [22, 2], [2...
[ "You can read/write GeoJSON objects and do spatial set operations like this with geopandas:\nIn [8]: df = gpd.read_file(\"data_01.json\", engine=\"GeoJSON\")\n\nIn [9]: df\nOut[9]:\n z la geometry\n0 1412.5 ba POLYGON ((2.00000 2.00000, 2.00000 22.00000, 2...\n1 ...
[ 0 ]
[]
[]
[ "json", "polygon", "python" ]
stackoverflow_0074526297_json_polygon_python.txt
Q: seeming memory leak in numpy for Mac? I used the following process the generate a numpy array with size = (720, 720, 3). In principle, it should cost 720 * 720 * 3 * 8Byte = 12.3MB. However, in the ans = memory_benchmark(), it costs 188 MB. Why does it cost much more memory than expected? I think it should have sa...
seeming memory leak in numpy for Mac?
I used the following process the generate a numpy array with size = (720, 720, 3). In principle, it should cost 720 * 720 * 3 * 8Byte = 12.3MB. However, in the ans = memory_benchmark(), it costs 188 MB. Why does it cost much more memory than expected? I think it should have same cost as the line m1 = np.ones((720, 720,...
[ "I can't reproduce the results you're getting. In python 3.7.3, numpy 1.21.4, and memory_profiler 0.61.0, I'm getting the following results\n\nLine # Mem usage Increment Occurrences Line Contents\n=============================================================\n 23 57.6 MiB 57.6 MiB 1 ...
[ 0, 0 ]
[]
[]
[ "macos", "memory_leaks", "numpy", "python" ]
stackoverflow_0074526223_macos_memory_leaks_numpy_python.txt
Q: Selenium AttributeError: 'WebDriver' object has no attribute 'find_element_by_css_selector' I am following this build of a scraper for LinkedIn job data. Here is my code: from selenium import webdriver import time import pandas as pd url = 'https://www.linkedin.com/jobs/search?keywords=&location=San%20Francisco%2...
Selenium AttributeError: 'WebDriver' object has no attribute 'find_element_by_css_selector'
I am following this build of a scraper for LinkedIn job data. Here is my code: from selenium import webdriver import time import pandas as pd url = 'https://www.linkedin.com/jobs/search?keywords=&location=San%20Francisco%2C%20California%2C%20United%20States&locationId=&geoId=102277331&f_TPR=&distance=100&position=1&pa...
[ "Okay, I answered my own question. The individual methods find_element_by_* have been replaced by find_element, e.g.\nno_of_jobs = int(wd.find_element(By.CSS_SELECTOR, 'h1>span'))\n\nMore info is here\n", "Selenium just removed that method in version 4.3.0. See the CHANGES: https://github.com/SeleniumHQ/selenium/...
[ 15, 4, 3, 0 ]
[]
[]
[ "python", "selenium", "selenium_webdriver" ]
stackoverflow_0072854116_python_selenium_selenium_webdriver.txt
Q: Python regular expression split by multiple delimiters Given the sentence "I want to eat fish and I want to buy a car. Therefore, I have to make money." I want to split the sentene by ['I want to eat fish', 'I want to buy a car", Therefore, 'I have to make money'] I am trying to split the sentence re.split('.|and'...
Python regular expression split by multiple delimiters
Given the sentence "I want to eat fish and I want to buy a car. Therefore, I have to make money." I want to split the sentene by ['I want to eat fish', 'I want to buy a car", Therefore, 'I have to make money'] I am trying to split the sentence re.split('.|and', sentence) However, it splits the sentence by '.', 'a', 'n...
[ "In addition to escaping the dot (.), which matches any non-newline character in regex, you should also match any leading or trailing spaces in order for the delimiter of the split to consume undesired leading and trailing spaces from the results. Use a positive lookahead pattern to assert a following non-whitespac...
[ 2, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0074526464_python_regex.txt
Q: Is it possible to Average only certain sections of a spreadsheet with python by specifying the sections you want based on another factor? I am trying to average the sea temperature for the fall and spring of each year in my data set. Imagine three columns (year/season/temp) which list things such as: 1963, FALL, 7...
Is it possible to Average only certain sections of a spreadsheet with python by specifying the sections you want based on another factor?
I am trying to average the sea temperature for the fall and spring of each year in my data set. Imagine three columns (year/season/temp) which list things such as: 1963, FALL, 75 and continues with various years and the spring/fall season. How could I code to find the average of the temperatures that are in the fall of...
[ "With pandas you can perform a groupby on the data frame. Assuming the column names are year, season and Temp something like the following should work:\nimport numpy as np\nimport pandas as pd\n\navg_df = df.groupby(['year','season']).agg({'Temp':[np.mean, np.std]})\navg_df.columns = ['Mean', 'STD']\n\n" ]
[ 0 ]
[]
[]
[ "average", "pandas", "python", "sorting", "spreadsheet" ]
stackoverflow_0074526459_average_pandas_python_sorting_spreadsheet.txt
Q: Using an extra python package index url with setup.py Is there a way to use an extra Python package index (ala pip --extra-index-url pypi.example.org mypackage) with setup.py so that running python setup.py install can find the packages hosted on pypi.example.org? A: If you're the package maintainer, and you wan...
Using an extra python package index url with setup.py
Is there a way to use an extra Python package index (ala pip --extra-index-url pypi.example.org mypackage) with setup.py so that running python setup.py install can find the packages hosted on pypi.example.org?
[ "If you're the package maintainer, and you want to host one or more dependencies for your package somewhere other than PyPi, you can use the dependency_links option of setuptools in your distribution's setup.py file. This allows you to provide an explicit location where your package can be located.\nFor example:\nf...
[ 49, 17, 5, 4, 2, 0 ]
[ "As far as I know, you cant do that.\nYou need to tell pip this, or by passing a parameter like you mentioned, or by setting this on the user environment.\nCheck my ~/.pip/pip.conf:\n[global]\ndownload_cache = ~/.cache/pip\nindex-url = http://user:pass@localpypiserver.com:80/simple\ntimeout = 300\n\nIn this case, m...
[ -2, -6 ]
[ "packaging", "pip", "pypi", "python", "setup.py" ]
stackoverflow_0024443583_packaging_pip_pypi_python_setup.py.txt
Q: Make parent class do something "once" in Python class TaskInput: def __init__(self): self.cfg = my_config #### Question: How do I do this only once? class TaskA(TaskInput): def __init__(self): pass class TaskB (TaskInput): def __init__(self): pass There are many tasks like Ta...
Make parent class do something "once" in Python
class TaskInput: def __init__(self): self.cfg = my_config #### Question: How do I do this only once? class TaskA(TaskInput): def __init__(self): pass class TaskB (TaskInput): def __init__(self): pass There are many tasks like TaskA, TaskB etc, they all are inherited from TaskInpu...
[ "Make the configuration a class attribute by defining it on the class rather than in __init__.\nclass TaskInput:\n cfg = my_config\n\nIt is now accessible as self.cfg on any instance of TaskInput or its children.\n", "I will not try to guess your need so I will assume you mean exactly what you said below, name...
[ 2, 0 ]
[]
[]
[ "inheritance", "python" ]
stackoverflow_0074524574_inheritance_python.txt
Q: How to upload a dataset folder to an already existing folder in vs code (connected to remote ssh) I kind of have a structure of my vs repository as follow: * shh remote host * workspace * main folder * folder where I want to upload a 20 GB file of dataset Please note that I can't locate t...
How to upload a dataset folder to an already existing folder in vs code (connected to remote ssh)
I kind of have a structure of my vs repository as follow: * shh remote host * workspace * main folder * folder where I want to upload a 20 GB file of dataset Please note that I can't locate the folder in the computer system. How can I upload a zip file or a direct folder in the 'folder where I...
[ "The comments have given a reasonable solution. Of course, if you must use SSH, you can use rsync to transfer files.\nAn alternative to using SSHFS to access remote files is to use rsync to copy the entire contents of a folder on remote host to your local machine. The rsync command will determine which files need t...
[ 0 ]
[]
[]
[ "python", "visual_studio_code" ]
stackoverflow_0074519802_python_visual_studio_code.txt
Q: Selenium's version of seleniumwire's requests So, originally my code was something like this: from seleniumwire import webdriver driver = webdriver.Firefox(options=self.web_options driver.get(user_site) ret = list(driver.requests) verify = extract_verify(ret) driver.requests.clear() driver.get(self.root + '?verify...
Selenium's version of seleniumwire's requests
So, originally my code was something like this: from seleniumwire import webdriver driver = webdriver.Firefox(options=self.web_options driver.get(user_site) ret = list(driver.requests) verify = extract_verify(ret) driver.requests.clear() driver.get(self.root + '?verify={}'.format(urllib.parse.quote(verify))) resp = sel...
[ "I was able to fix this with from seleniumrequests.request import RequestsSessionMixin. It was still helpful to get my thoughts on paper like this.\n" ]
[ 0 ]
[]
[]
[ "dependencies", "python", "selenium", "selenium_webdriver" ]
stackoverflow_0074526370_dependencies_python_selenium_selenium_webdriver.txt
Q: Blob.generate_signed_url() failing to AttributeError So I'm trying to produce temporary globally readable URLs for my Google Cloud Storage objects using the google-cloud-storage Python library (https://googlecloudplatform.github.io/google-cloud-python/latest/storage/blobs.html) - more specifically the Blob.generat...
Blob.generate_signed_url() failing to AttributeError
So I'm trying to produce temporary globally readable URLs for my Google Cloud Storage objects using the google-cloud-storage Python library (https://googlecloudplatform.github.io/google-cloud-python/latest/storage/blobs.html) - more specifically the Blob.generate_signed_url() method. I doing this from within a Compute ...
[ "I was having the same issue. Ended up fixing it by starting the storage client directly from the service account json.\nstorage_client = storage.Client.from_service_account_json('path_to_service_account_key.json')\n\nI know I'm late to the party but hopefully this helps!\n", "Currently, it's not possible to use ...
[ 15, 11, 0 ]
[]
[]
[ "google_cloud_python", "google_cloud_storage", "google_compute_engine", "python" ]
stackoverflow_0046540894_google_cloud_python_google_cloud_storage_google_compute_engine_python.txt
Q: An output image file with red contours of all objects I have the following code: import cv2 as cv import numpy as np image = cv.imread("input1.jpg") img_gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY) img_denoised = cv.GaussianBlur(img_gray,(5,5),2) ret, thresh = cv.threshold(img_denoised, 216, 255, cv.THRESH_BINA...
An output image file with red contours of all objects
I have the following code: import cv2 as cv import numpy as np image = cv.imread("input1.jpg") img_gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY) img_denoised = cv.GaussianBlur(img_gray,(5,5),2) ret, thresh = cv.threshold(img_denoised, 216, 255, cv.THRESH_BINARY) kernel = np.ones((1,1),np.uint8) opening = cv.dilate(t...
[ "I messed with this a bit and the best outcome I could get was the following, I think with some tweaking you could ignore the shading, as I'm converting it to grayscale it seems to be dropping the correct contour on the shapes, but the text is working as expected;\nimport cv2\nimport numpy as np\n\nsrc = cv2.imread...
[ 1 ]
[]
[]
[ "opencv", "python" ]
stackoverflow_0074526315_opencv_python.txt
Q: UnboundLocalError - local variable 'emprendedores' referenced before assignment I can't figure out why am I getting this error message: "UnboundLocalError - local variable 'emprendedores' referenced before assignment" enter image description here Hey fellows, i'm building an app in Django and almost is pretty well...
UnboundLocalError - local variable 'emprendedores' referenced before assignment
I can't figure out why am I getting this error message: "UnboundLocalError - local variable 'emprendedores' referenced before assignment" enter image description here Hey fellows, i'm building an app in Django and almost is pretty well. However, I cannot find solution to a problem in my search view. The main idea is al...
[ "This is the error:\nUnboundLocalError at /consulta/\nlocal variable 'emprendedores' referenced before assignment\nRequest Method: POST\nRequest URL: http://127.0.0.1:8000/consulta/\nDjango Version: 3.2.8\nException Type: UnboundLocalError\nException Value: \nlocal variable 'emprendedores' referenced before a...
[ 0 ]
[]
[]
[ "django", "django_errors", "django_views", "python" ]
stackoverflow_0074525798_django_django_errors_django_views_python.txt
Q: Adding a word after every particular word in a list in Python I'm sorry if my Title seems kinda weird, English is not my first Language and I didn't know how to express myself correctly. I have a list and I want to add a word every time after a particular word: Example: list = ['add', 'add', 'ball', 'cup', 'add'] ...
Adding a word after every particular word in a list in Python
I'm sorry if my Title seems kinda weird, English is not my first Language and I didn't know how to express myself correctly. I have a list and I want to add a word every time after a particular word: Example: list = ['add', 'add', 'ball', 'cup', 'add'] Expected result: list = ['add','Nice', 'add', 'Nice, 'ball', 'cup'...
[ "Mutating the list you're iterating over easily leads to unexpected results since the internal iterator of the loop has no idea of your modification to the sequence.\nInstead, you can create a new list to append output to:\nlst = ['add', 'add', 'ball', 'cup', 'add']\noutput = []\nfor word in lst:\n output.append...
[ 1, 0 ]
[]
[]
[ "for_loop", "list", "python" ]
stackoverflow_0074526532_for_loop_list_python.txt
Q: Error trying to make a discord selfbot in python So I'm trying to make a discord selfbot in python and I got this error Traceback (most recent call last): File "C:\Users\tauga\Documents\luna.py", line 4, in <module> client = commands.Bot(command_prefix="*", self_bot=True, help_command=False) TypeError: __ini...
Error trying to make a discord selfbot in python
So I'm trying to make a discord selfbot in python and I got this error Traceback (most recent call last): File "C:\Users\tauga\Documents\luna.py", line 4, in <module> client = commands.Bot(command_prefix="*", self_bot=True, help_command=False) TypeError: __init__() missing 1 required keyword-only argument: 'inten...
[ "Try this client= commands.Bot(command_prefix='!', intents=discord.Intents.all())\nYour error was because discord api requires intents, which you never set.\nTo run the bot use client.run(\"token\", bot=False)\nAnd for the command, use ctx.channel.send(\"test message here\")\nPlease note, self botting is a very bad...
[ 0 ]
[]
[]
[ "discord", "discord.py", "python", "python_3.x" ]
stackoverflow_0074524007_discord_discord.py_python_python_3.x.txt
Q: Vs code doesn't regognize tkinter on pop os I have a code, where i use tkinter to make a window and stuff. It's a brawler picker for brawl stars. Im using pop os-linux and vs code and i have tried so many ways, but anything doesn't work. When i run the code, i get this: (.venv) sh-5.1$ python -u "/home/"my_name"/D...
Vs code doesn't regognize tkinter on pop os
I have a code, where i use tkinter to make a window and stuff. It's a brawler picker for brawl stars. Im using pop os-linux and vs code and i have tried so many ways, but anything doesn't work. When i run the code, i get this: (.venv) sh-5.1$ python -u "/home/"my_name"/Documents/Vs-code_projektit/Joku.py" Traceback (mo...
[ "First of all, you need to know what interpreter is currently used by vscode, which is displayed in the lower right corner of the interface.\n\nClicking on the displayed python version will open a Select Interpreter panel where you can select the interpreter with the tkinter package installed to run the code\n\nOr ...
[ 0 ]
[]
[]
[ "linux", "python", "tkinter", "visual_studio_code" ]
stackoverflow_0074518489_linux_python_tkinter_visual_studio_code.txt
Q: What does the Abstract Base Class register method actually do? I am confused about the ABC register method. Take the following code: import io from abc import ABCMeta, abstractmethod class IStream(metaclass=ABCMeta): @abstractmethod def read(self, maxbytes=-1): pass @abstractmethod def wri...
What does the Abstract Base Class register method actually do?
I am confused about the ABC register method. Take the following code: import io from abc import ABCMeta, abstractmethod class IStream(metaclass=ABCMeta): @abstractmethod def read(self, maxbytes=-1): pass @abstractmethod def write(self, data): pass IStream.register(io.IOBase) f = open(...
[ "It simply makes issubclass(io.IOBase, IStream) return True (which then implies that an instance of io.IOBase is an instance of IStream). It is up to the programmer registering the class to ensure that io.IOBase actually conforms to the API defined by IStream.\nThe reason is to let you define an interface in the fo...
[ 2, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0059740972_python_python_3.x.txt
Q: Frozenset Intersection with Wildcards I'm trying to intersect frozensets in Python, but not getting the desired result. My intersection array, LCC, has 100s of strings. LCC = ['A','E...'] fs1 = frozenset('A') fs2 = frozenset('E830') fs1.intersection(LCC) fs2.intersection(LCC) The results are: frozenset({'A'}) fro...
Frozenset Intersection with Wildcards
I'm trying to intersect frozensets in Python, but not getting the desired result. My intersection array, LCC, has 100s of strings. LCC = ['A','E...'] fs1 = frozenset('A') fs2 = frozenset('E830') fs1.intersection(LCC) fs2.intersection(LCC) The results are: frozenset({'A'}) frozenset() I would expect the second functio...
[ "I assume your '...' is a wildcard pattern meaning any characters of length three.(Regular expression syntax)\nYou can use regular expressions like this.\nimport re\n\nLCC = ['A', 'E...']\nfs = frozenset({'A', 'E830', 'E2'})\n\nre_patterns = [re.compile(pattern) for pattern in LCC]\nintersection = {e for e in fs fo...
[ 0 ]
[]
[]
[ "frozenset", "intersection", "python", "wildcard" ]
stackoverflow_0074525886_frozenset_intersection_python_wildcard.txt
Q: Show class docstring in VSCode There are some classes written with the docstring at the class level, as opposed to under methods like the init method, for example PyTorch's CrossEntropy loss class. How can I show the class docstring in VSCode with a shortcut, similar to this question? A: Set these three key-bind...
Show class docstring in VSCode
There are some classes written with the docstring at the class level, as opposed to under methods like the init method, for example PyTorch's CrossEntropy loss class. How can I show the class docstring in VSCode with a shortcut, similar to this question?
[ "\n\nSet these three key-bindings in the picture.\nClick or move the cursor to what you want to display the content\nUse the shortcuts to get.\n\nYou can also use the methods in the comments, hover over an instance of that class with your mouse.\n" ]
[ 0 ]
[]
[]
[ "python", "visual_studio_code" ]
stackoverflow_0074523665_python_visual_studio_code.txt
Q: How do I spell out each inputted digits in python I need to make a program that takes an integer input and when you enter a number, it types out the spelling of each digit. For example, I inputted 12, the program will print out: One Two I have a little problem with the code, how do I print out the results (or the ...
How do I spell out each inputted digits in python
I need to make a program that takes an integer input and when you enter a number, it types out the spelling of each digit. For example, I inputted 12, the program will print out: One Two I have a little problem with the code, how do I print out the results (or the spellings) vertically and in separate lines? The output...
[ "In this line:\nans = number_2_word(int(num/10)) + small_ans + \" \"\n\nUse line break rather than space\nans = number_2_word(int(num / 10)) + small_ans + \"\\n\"\n\nI did a few tests, seems work as you expected\n" ]
[ 0 ]
[]
[]
[ "for_loop", "loops", "python", "while_loop" ]
stackoverflow_0074526674_for_loop_loops_python_while_loop.txt
Q: Selenium_Datepicker (Calendar) Python I am writing code with selenium to fulfill information in a websites. I am not able to instruct the code to select a specific date. Here is the html code: <div id="subview1:itemViewFragment1:itemForm1:texti0023_POPUP" name="subview1:itemViewFragment1:itemForm1:texti0023_POPUP_...
Selenium_Datepicker (Calendar) Python
I am writing code with selenium to fulfill information in a websites. I am not able to instruct the code to select a specific date. Here is the html code: <div id="subview1:itemViewFragment1:itemForm1:texti0023_POPUP" name="subview1:itemViewFragment1:itemForm1:texti0023_POPUP_HXPOPUP" style="position: absolute; top: 48...
[]
[]
[ "<div id=\"subview1:itemViewFragment1:itemForm1:texti0023_POPUP\" name=\"subview1:itemViewFragment1:itemForm1:texti0023_POPUP_HXPOPUP\" style=\"position: absolute; top: 482px; left: 425px; z-index: 1000000; padding: 0px; margin: 0px; vertical-align: top; overflow: visible; display: block; visibility: visible;\" cla...
[ -2 ]
[ "calendar", "datepicker", "python", "selenium" ]
stackoverflow_0074526712_calendar_datepicker_python_selenium.txt
Q: Concatenate fails in simple example I am trying the simple examples of this page In it it says: arr=np.array([4,7,12]) arr1=np.array([5,9,15]) np.concatenate((arr,arr1)) # Must give array([ 4, 7, 12, 5, 9, 15]) np.concatenate((arr,arr1),axis=1) #Must give #[[4,5],[7,9],[12,15]] # but it gives *** numpy.AxisErr...
Concatenate fails in simple example
I am trying the simple examples of this page In it it says: arr=np.array([4,7,12]) arr1=np.array([5,9,15]) np.concatenate((arr,arr1)) # Must give array([ 4, 7, 12, 5, 9, 15]) np.concatenate((arr,arr1),axis=1) #Must give #[[4,5],[7,9],[12,15]] # but it gives *** numpy.AxisError: axis 1 is out of bounds for array of ...
[ "np.vstack is what you're looking for. Note the transpose at the end, this converts vstack's 2x3 result to a 3x2 array.\nimport numpy as np\n\narr = np.array([4,7,12])\narr1 = np.array([5,9,15])\n\na = np.vstack((arr,arr1)).T\nprint(a)\n\nOutput:\n[[ 4 5]\n [ 7 9]\n [12 15]]\n\n" ]
[ 1 ]
[]
[]
[ "arrays", "numpy", "python" ]
stackoverflow_0074526645_arrays_numpy_python.txt
Q: Python - Function I'm new to Python which I'm currently studying function. I'm coding mile to kilometer conversion with a constant ratio number and constant value for "mile" using the 'def_function' This is code. mile=12 def distance_con(mile): km = 1.6 * mile print(km) return km result=distance_con(...
Python - Function
I'm new to Python which I'm currently studying function. I'm coding mile to kilometer conversion with a constant ratio number and constant value for "mile" using the 'def_function' This is code. mile=12 def distance_con(mile): km = 1.6 * mile print(km) return km result=distance_con(mile) print(result) Bu...
[ "you got the error at print(km) km is define within the function scope so that you cannot access outside the function that you created.\nIn python there's a scope for a variable that we created see https://www.datacamp.com/tutorial/scope-of-variables-python for more info\n", "You are trying to print something in ...
[ 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0074526696_python.txt
Q: Remove single quote of string using `ast` but receive: ValueError: malformed node or string on line 1: - Python a='[{"M":{"Options":{"L":[{"M":{"Label":{"S":"5PCS "},"Selected":{"BOOL":false},"OptionId":{"S":"3080a2b2-2fd1-11ed-a261-0242ac120002"},"Price":{"N":"0"}}},{"M":{"Label":{"S":"8PCS"},"Selected":{"BOOL":...
Remove single quote of string using `ast` but receive: ValueError: malformed node or string on line 1: - Python
a='[{"M":{"Options":{"L":[{"M":{"Label":{"S":"5PCS "},"Selected":{"BOOL":false},"OptionId":{"S":"3080a2b2-2fd1-11ed-a261-0242ac120002"},"Price":{"N":"0"}}},{"M":{"Label":{"S":"8PCS"},"Selected":{"BOOL":false},"OptionId":{"S":"27f2148c-2fd1-11ed-a261-0242ac120002"},"Price":{"N":"600"}}}]},"Type":{"S":"multiple"},"Descri...
[ "What you have is not a valid Python \"literal\". If you look carefully at the value of a, you'll see the value false, which is not the same as the Python Boolean literal False.\nThe value of a is, however, a valid JSON array (as false and true are the JSON Boolean values).\n>>> json.loads(a)\n[{'M': {'Options': {'...
[ 1 ]
[]
[]
[ "character", "python", "string" ]
stackoverflow_0074526406_character_python_string.txt
Q: how do I construct a pandas boolean series from an arbitrary number of conditions I have a dataframe and I want to locate rows in the dataframe based on an arbitrary number of boolean conditions on multiple columns. Currently I'm doing this by formatting a complex query string, which is an unsafe pattern (although...
how do I construct a pandas boolean series from an arbitrary number of conditions
I have a dataframe and I want to locate rows in the dataframe based on an arbitrary number of boolean conditions on multiple columns. Currently I'm doing this by formatting a complex query string, which is an unsafe pattern (although I'm not too concerned about the specific code here). It looks like this: df = pd.DataF...
[ "You could do with any\ncol = [f'{c}_id' for c in components_to_query]\nout = df[df[col].isin(ids_of_interest).any(1)]\nOut[268]: \n a_id b_id c_id\n1 3 7 4\n\n" ]
[ 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074526510_pandas_python.txt
Q: How can I make a non-blocking UDP server and a periodic task in the same script? I am trying to make a UDP server and next to it a periodic task that updates a global variable every 5 minutes. But the problem is that my UDP server and my task part blocks the rest of the code (because I use while True:). I was look...
How can I make a non-blocking UDP server and a periodic task in the same script?
I am trying to make a UDP server and next to it a periodic task that updates a global variable every 5 minutes. But the problem is that my UDP server and my task part blocks the rest of the code (because I use while True:). I was looking at this example: https://docs.python.org/3/library/asyncio-protocol.html#asyncio-u...
[ "Replace your asyncio.sleep(3600) with a wait for an asyncio.Event that never happens. That will suspend the task forever but leave the event loop running. The only way to terminate the program is with Ctrl-C or some other operating system action.\ntry:\n await asyncio.Event().wait() # wait here until the Uni...
[ 1, 0 ]
[]
[]
[ "python", "python_asyncio" ]
stackoverflow_0074523668_python_python_asyncio.txt
Q: Would someone please help me understand this logic? I have a dictionary variable that stores two columns of a pandas array, and it prints perfectly. However, when I assign variable to a template for json metadata, only the one row of the array is written to the json file. I'm having trouble wrapping my head around...
Would someone please help me understand this logic?
I have a dictionary variable that stores two columns of a pandas array, and it prints perfectly. However, when I assign variable to a template for json metadata, only the one row of the array is written to the json file. I'm having trouble wrapping my head around why this is happening. for i in range(attributesQuantity...
[ "Based on the pandas.DataFrame.loc, codes like dfM.loc[i, \"trait_type\"] should get the element of trait_type column in the ith row, and the print output would only be something like {\"trait_type\": \" Race\", \"value\": \" human\"}.\nprompt_metadata[\"attributes\"] in this loop, is reassigning prompt_metadata[\"...
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074526731_pandas_python.txt
Q: VS Code not finding pytest tests I have PyTest setup in vs-code but none of the tests are being found even though running pytest from the command line works fine. (I'm developing a Django app on Win10 using MiniConda and a Python 3.6.6 virtual env. VS Code is fully updated and I have the Python and Debugger for Ch...
VS Code not finding pytest tests
I have PyTest setup in vs-code but none of the tests are being found even though running pytest from the command line works fine. (I'm developing a Django app on Win10 using MiniConda and a Python 3.6.6 virtual env. VS Code is fully updated and I have the Python and Debugger for Chrome extensions installed) Pytest.ini:...
[ "If anyone comes across this post-2020, this issue in the vscode-python repo saved my life. Basically, just do the following:\n\nUninstall the Python extension\nDelete the file that contains the extension from your ~/.vscode folder (mine looked like ms-python.python-[YEAR].[MONTH].[VERSION])\nReinstall the extensio...
[ 17, 4, 4, 4, 3, 3, 2, 1, 1, 0 ]
[]
[]
[ "pytest", "pytest_django", "python", "python_3.x", "visual_studio_code" ]
stackoverflow_0054387442_pytest_pytest_django_python_python_3.x_visual_studio_code.txt
Q: Python: add a book with user input I’m trying to add a book to an inventory list, based on user input and get a "str not callable" error? #Add a book, based on user input def add_book(): # purpose: add a book print() print("Adding a New Book..") print() title = input("Title> ") au...
Python: add a book with user input
I’m trying to add a book to an inventory list, based on user input and get a "str not callable" error? #Add a book, based on user input def add_book(): # purpose: add a book print() print("Adding a New Book..") print() title = input("Title> ") author = input("Author> ") isbn = inpu...
[ "That is not the correct syntax to append to a list.\nAssuming inventory is a list type, the append() method takes a single argument and appends it to the list.\ninventory.append(title)\n\nYou will need to do this for each element you wish to append, or append them as a tuple of items\ninventory.append((title, auth...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074526642_python.txt
Q: Obtaining a HashMap or dictionary and a diagram in Python to visualize the overlaps between multiple lists Context: I roughly have a dictionary of about 130 lists in the form of a key and a list of indexes. {‘key1’:[0,1,2], ‘key2’: [2, 3, 4], ‘key3’:[5, 6],…, ‘key130’:[0, 450, 1103, 500,…]} Lists are all different...
Obtaining a HashMap or dictionary and a diagram in Python to visualize the overlaps between multiple lists
Context: I roughly have a dictionary of about 130 lists in the form of a key and a list of indexes. {‘key1’:[0,1,2], ‘key2’: [2, 3, 4], ‘key3’:[5, 6],…, ‘key130’:[0, 450, 1103, 500,…]} Lists are all different sizes. This is a two-part problem where: I want some form of data structure to store the number of overlaps be...
[ "import numpy as np\nimport pandas as pd\n\nd = {'key1':[0,1,2], 'key2': [2, 3, 4], 'key3':[5, 6]}\ns = []\n[s.append(list(set(x) & set(y))) for x in d.values() for y in d.values()]\n\nmatrix1 = np.array(s, dtype = object)\nmatrix2 = matrix1.reshape(int(np.sqrt(len(matrix1))),int(np.sqrt(len(matrix1))))\nmatrix2 = ...
[ 1, 0 ]
[]
[]
[ "comparison", "python", "upsetplot", "visualization" ]
stackoverflow_0074526134_comparison_python_upsetplot_visualization.txt
Q: How can I split a three letter string so that it produces a list? I need to do an input of the string 'AEN' and it must split into ('A', 'E', 'N') Ive tried several different splits, but it never produces what i need. The image shows the code I have done. What im trying is that x produces a result like y. But, Im ...
How can I split a three letter string so that it produces a list?
I need to do an input of the string 'AEN' and it must split into ('A', 'E', 'N') Ive tried several different splits, but it never produces what i need. The image shows the code I have done. What im trying is that x produces a result like y. But, Im having issues whit how to achieve it. x=input('Letras: ') y=input('Let...
[ "You just want list, which will take an arbitrary iterable and produce a new list, one item per element. A string is considered to be an iterable of individual characters.\n>>> list('AEN')\n['A', 'E', 'N']\n\nstr.split is for splitting a string base on a given delimiter (or arbitrary whitespace, when no delimiter i...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074526224_python.txt
Q: What does singular "*" as an argument in a python function definition do? I am trying to look through some code and don't know what the asterisk in the following code means. def pylog(func=None, *, mode='cgen', path=WORKSPACE, backend='vhls', \ board='ultra96', freq=None): What does the lonely asterisk ...
What does singular "*" as an argument in a python function definition do?
I am trying to look through some code and don't know what the asterisk in the following code means. def pylog(func=None, *, mode='cgen', path=WORKSPACE, backend='vhls', \ board='ultra96', freq=None): What does the lonely asterisk signify in a function definition when not followed by the name of an argument? ...
[ "This syntax forces arguments after the * to be called with their keyword names when someone calls the function/method.\nExample:\n# This is allowed\npylog(math.log, mode='cgen')\n\n# This is *NOT* allowed\npylog(math.log, 'cgen')\n\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074526883_python.txt
Q: Pandas: resampling data with mixed, missing or difficult to 'normalize' dates Im trying to deal with some timeseries data that looks like this. As you can see the data is monthly, but some dates are at EOM, some at BOM and some simply a month name: The solution i thought of was: assuming this is monthly data and ...
Pandas: resampling data with mixed, missing or difficult to 'normalize' dates
Im trying to deal with some timeseries data that looks like this. As you can see the data is monthly, but some dates are at EOM, some at BOM and some simply a month name: The solution i thought of was: assuming this is monthly data and that i know the start and end dates, i would like to create a date range from that ...
[ "When you use freq=\"MS\" inside pd.date_range, pandas understands that you wish to create a range of dates with a month start frequency. The reason why it starts with '2020-12-01' is because December is the first start of a month that occurs, given '11/30/2020' as the start date. If you wish to include November in...
[ 1, 1 ]
[]
[]
[ "data_science", "numpy", "pandas", "python" ]
stackoverflow_0074526777_data_science_numpy_pandas_python.txt
Q: How to create a data frame using two lists in Python? L1 = ['a','b','c','a','b','c'] L2 = ['Cat','Fish','Crow','Dog','Frog','Eagle'] Desired Output 1: D1 = {'a':['Cat','Dog'], 'b':['Fish','Frog'], 'c':['Crow','Eagle']} Desired Output 2: DF1 = A B C ...
How to create a data frame using two lists in Python?
L1 = ['a','b','c','a','b','c'] L2 = ['Cat','Fish','Crow','Dog','Frog','Eagle'] Desired Output 1: D1 = {'a':['Cat','Dog'], 'b':['Fish','Frog'], 'c':['Crow','Eagle']} Desired Output 2: DF1 = A B C Cat Fish Crow ...
[ "Try:\nL1 = [\"a\", \"b\", \"c\", \"a\", \"b\", \"c\"]\nL2 = [\"Cat\", \"Fish\", \"Crow\", \"Dog\", \"Frog\", \"Eagle\"]\n\nout = {}\nfor a, b in zip(L1, L2):\n out.setdefault(a, []).append(b)\n\nprint(out)\n\nPrints:\n{\"a\": [\"Cat\", \"Dog\"], \"b\": [\"Fish\", \"Frog\"], \"c\": [\"Crow\", \"Eagle\"]}\n\nThen...
[ 2, 0 ]
[]
[]
[ "dictionary", "list", "pandas", "python" ]
stackoverflow_0074525311_dictionary_list_pandas_python.txt
Q: NetworkX vs Scipy all shortest path algorithms What are the differences between the NetworkX all shortest paths algorithm and the scipy floyd warshall algorithm? Are there any reasons to prefer one over another? Which is fastest? A: (for those who aren't aware the numpy floyd-warshall algorithm is available in...
NetworkX vs Scipy all shortest path algorithms
What are the differences between the NetworkX all shortest paths algorithm and the scipy floyd warshall algorithm? Are there any reasons to prefer one over another? Which is fastest?
[ "(for those who aren't aware the numpy floyd-warshall algorithm is available in networkx)\nThe networkx description of floyd_warshall_numpy states: \n\nFloyd’s algorithm is appropriate for finding shortest paths in dense graphs or graphs with negative weights when Dijkstra’s algorithm fails. This algorithm can stil...
[ 2, 0 ]
[]
[]
[ "networkx", "python", "scipy", "shortest_path" ]
stackoverflow_0023463713_networkx_python_scipy_shortest_path.txt
Q: How to plot list if values with respect to its key of a dictionary in python I have a dictionary with list of values df_param = {}; for i in range(0,1000): df_param[i]=[[0]] print(df_param) df_param={0: [[0], [20], [20], [20], [5], [1], [5]], 1: [[0], [20], [20], [5], [1], [5]], 2: [[0], [20], [20], [5], [5]], ...
How to plot list if values with respect to its key of a dictionary in python
I have a dictionary with list of values df_param = {}; for i in range(0,1000): df_param[i]=[[0]] print(df_param) df_param={0: [[0], [20], [20], [20], [5], [1], [5]], 1: [[0], [20], [20], [5], [1], [5]], 2: [[0], [20], [20], [5], [5]], 3: [[0], [20], [5], [5]], 4: [[0], [5], [5]], 5: [[0], [5]], 6: [[0]], 7: [[0]], 8...
[ "If your df_param is a dict of form:\n{x0: [[y0_a], [y0_b], ...], x1: [[y1_a], [y1_b], ...], ...} and you wish to make a scatter plot of all the (xk, yk_i), then you can first make a proper xy array with two columns x and y:\nimport numpy as np\n\nxy = np.array([\n (x, y) for x, lst in df_param.items()\n for ...
[ 0 ]
[]
[]
[ "dictionary", "matplotlib", "python", "visualization" ]
stackoverflow_0074526399_dictionary_matplotlib_python_visualization.txt
Q: How to use virtualenv in makefile I want to perform several operations while working on a specified virtualenv. For example command make install would be equivalent to source path/to/virtualenv/bin/activate pip install -r requirements.txt Is it possible? A: I like using something that runs only when requiremen...
How to use virtualenv in makefile
I want to perform several operations while working on a specified virtualenv. For example command make install would be equivalent to source path/to/virtualenv/bin/activate pip install -r requirements.txt Is it possible?
[ "I like using something that runs only when requirements.txt changes:\nThis assumes that source files are under project in your project's root directory and that tests are under project/test. (You should change project to match your actually project name.)\nvenv: venv/touchfile\n\nvenv/touchfile: requirements.txt\...
[ 75, 69, 33, 20, 15, 8, 7, 0, 0, 0 ]
[ "You should use this, it's functional for me at moment.\nreport.ipynb : merged.ipynb\n ( bash -c \"source ${HOME}/anaconda3/bin/activate py27; which -a python; \\\n jupyter nbconvert \\\n --to notebook \\\n --ExecutePreprocessor.kernel_name=python2 \\\n --ExecutePreprocessor.timeout=3...
[ -3 ]
[ "makefile", "python", "virtualenv" ]
stackoverflow_0024736146_makefile_python_virtualenv.txt
Q: Strange python dictionary keys I encounter a strange dictionary. Let's call it cp_dict. When I type: cp_dict['ZnS-Zn'] it returns: {Element Zn: -1.159460605, Element S: -4.384479766249999} The child key looks like a string but without quotation marks. How I can access the child keys (for example: Element Zn) a...
Strange python dictionary keys
I encounter a strange dictionary. Let's call it cp_dict. When I type: cp_dict['ZnS-Zn'] it returns: {Element Zn: -1.159460605, Element S: -4.384479766249999} The child key looks like a string but without quotation marks. How I can access the child keys (for example: Element Zn) and modify the values? I tried cp_dic...
[ "It is quite easy to make a custom class which represents itself in that way (\"looking like a string but without quotation marks\"). The result returned by a __repr__ method is what gets used when representing instances inside collections such as dicts and lists:\n>>> class Element:\n... def __init__(self, sym...
[ 4 ]
[]
[]
[ "python" ]
stackoverflow_0074526968_python.txt
Q: how to compare each cell of dataframe with list of dictionary in python? I am trying to compare column values of each rows of dataframe with predefined list of dictionary, and do filtering. I tried pandas to compare column value by row-wise with list of dictionary, but it is not quite working, I got type error. I ...
how to compare each cell of dataframe with list of dictionary in python?
I am trying to compare column values of each rows of dataframe with predefined list of dictionary, and do filtering. I tried pandas to compare column value by row-wise with list of dictionary, but it is not quite working, I got type error. I think I may need to convert dataframe into dictionary then compare it with lis...
[ "The code below should do what you are asking for, but I haven't tested it yet if it actually really does what it should. I have put some effort in appropriate naming of the variables to make it easier to understand what the code does and how it works.\nIn the first step the code transforms the list with dictionari...
[ 2, 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074525516_dataframe_pandas_python.txt
Q: Python-Custom decimal precision printing I want my integer variable to be rounded to 4 decimal places. A number like 3.345679 should be represented as 3.3457.Additionally, the value zero must be represented as 0 and not any other representation.(e.g., -0.0, 0.0, 0.00000). Additionally, I do not want to add extra 0...
Python-Custom decimal precision printing
I want my integer variable to be rounded to 4 decimal places. A number like 3.345679 should be represented as 3.3457.Additionally, the value zero must be represented as 0 and not any other representation.(e.g., -0.0, 0.0, 0.00000). Additionally, I do not want to add extra 0s to floating point numbers. For example, 3.9 ...
[ "You'll need to examine the number before you print it. You could write a function for determining how many zeros would appear if you rounded to 4 decimal places:\ndef getZeroCount(num):\n # this check avoids infinite loop\n if num == 0:\n return 4\n\n x = num\n tens = 0\n while x % 10 == 0:\n...
[ 0, 0, 0 ]
[]
[]
[ "format", "precision", "printing", "python" ]
stackoverflow_0074525555_format_precision_printing_python.txt
Q: Unzip file content hosted in s3 to multiple cloudfront url through a single lambda function Is there any specific way to unzip single file contents from s3 to multiple cloudfront urls by triggering lambda once. Lets say in there is a zip file contains multiple jpg/ png files already uploaded to s3. Intention is to...
Unzip file content hosted in s3 to multiple cloudfront url through a single lambda function
Is there any specific way to unzip single file contents from s3 to multiple cloudfront urls by triggering lambda once. Lets say in there is a zip file contains multiple jpg/ png files already uploaded to s3. Intention is to run lambda function only once to unzip all its file content and make them available in multiple ...
[ "Hello Prathap Parameswar,\nI think you can resolve your problem like this:\n\nFirst you need to exact your zip file\nSeconds you upload them again to S3.\n\nThis is lambda python function:\nimport json\nimport boto3\nfrom io import BytesIO\nimport zipfile\n\ndef lambda_handler(event, context):\n # TODO implemen...
[ 0 ]
[]
[]
[ "amazon_s3", "amazon_web_services", "aws_lambda", "node.js", "python" ]
stackoverflow_0074526898_amazon_s3_amazon_web_services_aws_lambda_node.js_python.txt
Q: Delete specific duplicate values ​in the same row en ko Fetishistic transvestism(F65.1) 물품음란성 의상도착증(F65.1) Obsessive-compulsive disorder(F42.-) 강박장애(F42.-) Conduct disorders(F91.-) 행동장애(F91.-) Schizophrenia(F20.-) 조현병(F20.-) I want to remove duplicate values ​​in the same row in this data frame. en ko Fetis...
Delete specific duplicate values ​in the same row
en ko Fetishistic transvestism(F65.1) 물품음란성 의상도착증(F65.1) Obsessive-compulsive disorder(F42.-) 강박장애(F42.-) Conduct disorders(F91.-) 행동장애(F91.-) Schizophrenia(F20.-) 조현병(F20.-) I want to remove duplicate values ​​in the same row in this data frame. en ko Fetishistic transvestism 물품음란성 의상도착증 Ob...
[ "Probably you can use difflib:\nimport difflib\nimport pandas as pd\n\ndef remove_common_postfix(row: pd.Series, column1: str, column2: str):\n \"\"\"\n Remove common postfix of 2 columns in 1 row\n :param row: a dataframe row\n :param column1: column name 1\n :param column2: column name 2\n :retu...
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074526440_dataframe_pandas_python.txt
Q: Need to drop the oldest record (can be multiple "oldest records") My dataset looks like this: ID DATE 111 29/07/2022 111 30/03/2022 111 30/03/2022 111 30/03/2022 111 02/08/2022 222 08/11/2022 222 07/07/2022 222 11/11/2022 222 10/07/2022 I need to drop the oldest record per ID but keeping all the others,...
Need to drop the oldest record (can be multiple "oldest records")
My dataset looks like this: ID DATE 111 29/07/2022 111 30/03/2022 111 30/03/2022 111 30/03/2022 111 02/08/2022 222 08/11/2022 222 07/07/2022 222 11/11/2022 222 10/07/2022 I need to drop the oldest record per ID but keeping all the others, the problem is that I may have various "oldest record...
[ "You can try this:\ndef discard_min(g):\n return g[g > g.min()]\n\nnewdf = df.groupby('ID')['DATE'].apply(discard_min).droplevel(1).reset_index()\n>>> newdf\n ID DATE\n0 111 2022-07-29\n1 111 2022-08-02\n2 222 2022-11-08\n3 222 2022-11-11\n4 222 2022-07-10\n\nReproducible setup for the above:\ndf =...
[ 2 ]
[]
[]
[ "date", "numpy", "pandas", "python", "sorting" ]
stackoverflow_0074526324_date_numpy_pandas_python_sorting.txt
Q: I'm having trouble cleaning up this Bad code script. I found a few errors already but I'm currently stuck on this part I need to correct this script on a bad code. There is 5 total errors. Here's what I've corrected so far. I'm stuck at defining an array in line 3. I've gone through and tried to correct this line ...
I'm having trouble cleaning up this Bad code script. I found a few errors already but I'm currently stuck on this part
I need to correct this script on a bad code. There is 5 total errors. Here's what I've corrected so far. I'm stuck at defining an array in line 3. I've gone through and tried to correct this line by line but have had no luck. Would greatly appreciate a push in the right direction to get this code fixed. from array imp...
[ "Here is a version of your code that compiles and seems to run correctly:\nstudents=[]\n\ndef getString(prompt, field):\n valid=False\n while valid==False:\n myString=input(prompt)\n if (len(myString)>0):\n valid=True\n else:\n print(\"The student's \" + field + \" c...
[ 0 ]
[]
[]
[ "arrays", "python" ]
stackoverflow_0074527047_arrays_python.txt
Q: python my selenium "webdriver.Remote" not work? .It's a real headache Why does my "webdriver.Remote" not work? from selenium import webdriver options = webdriver.ChromeOptions() driver = webdriver.Remote( command_executor='http://127.0.0.1:4444/wd/hub', options=options ) driver.get("http://www.google.com"...
python my selenium "webdriver.Remote" not work? .It's a real headache
Why does my "webdriver.Remote" not work? from selenium import webdriver options = webdriver.ChromeOptions() driver = webdriver.Remote( command_executor='http://127.0.0.1:4444/wd/hub', options=options ) driver.get("http://www.google.com") driver.quit() enter image description here I tried running "webdriver.Ch...
[ "I found that he kept Starting \"Starting ChromeDriver 100.0.4896.60\" while running, so I found another \"ChromeDriver \"in the selenium-server.jar sibling directory.How stupid of me.\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074517428_python.txt
Q: model.fit gives me Graph execution error. How do I solve? I am new to image processing and machine learning in python. I have been trying to execute a model in google colab using inceptionv3 but i am stuck at fitting the model. r = model.fit( training_set, validation_data=test_set, epochs=10, steps...
model.fit gives me Graph execution error. How do I solve?
I am new to image processing and machine learning in python. I have been trying to execute a model in google colab using inceptionv3 but i am stuck at fitting the model. r = model.fit( training_set, validation_data=test_set, epochs=10, steps_per_epoch=len(training_set), validation_steps=len(test_set...
[ "Try to truncate to max_length=64 when tokenization. It worked in my case when training the text classification model.\nThe error appears when I set max_lenght to 128 or above.\n" ]
[ 0 ]
[]
[]
[ "machine_learning", "python", "tensorflow" ]
stackoverflow_0072545450_machine_learning_python_tensorflow.txt
Q: ModuleNotFoundError: No module named 'yaml' and AttributeError: module 'yaml' has no attribute 'load'? I have a script that does import yaml and then uses yaml.load and yaml.Loader I previously installed yaml months ago using pip3 install yaml, and that worked for another script Now, running another script was say...
ModuleNotFoundError: No module named 'yaml' and AttributeError: module 'yaml' has no attribute 'load'?
I have a script that does import yaml and then uses yaml.load and yaml.Loader I previously installed yaml months ago using pip3 install yaml, and that worked for another script Now, running another script was saying ModuleNotFoundError: No module named 'yaml' again (but ipython works when doing import yaml as well as f...
[]
[]
[ "python3 -m pip install pyyaml worked. I should rly learn pip/installing\n" ]
[ -2 ]
[ "homebrew", "pip", "python", "yaml" ]
stackoverflow_0074526364_homebrew_pip_python_yaml.txt
Q: How to display the output form a function on a label in Tkinter I'm new to coding and im sure that my code is not very efficient but I just want to take the output from a variable and display it in a window. So far when you run it, it just displays the output in the console. I want it do to that and display it on ...
How to display the output form a function on a label in Tkinter
I'm new to coding and im sure that my code is not very efficient but I just want to take the output from a variable and display it in a window. So far when you run it, it just displays the output in the console. I want it do to that and display it on the window. Hope that all makes sense. from tkinter import * root = T...
[ "For starters, your get_input function isn't returning a value. You should replace the print() statement with the value you'd like this function to return:\ndef get_input():\n ... # code omitted for brevity\n return days[int(p6)] # return the value you want from the `days` list\n\nThat said, if you want th...
[ 0, 0 ]
[]
[]
[ "label", "python", "tkinter", "tkinter_layout" ]
stackoverflow_0074504091_label_python_tkinter_tkinter_layout.txt
Q: Handle event batch in eventhub triggered azure function Am writing a event publisher and consumer. From the publisher am trying to send events as batch using eventhub_client.send_batch(batch) Now in the consumer side am receiving event and using if e.get_body() is not None: try: str = e.get_body()....
Handle event batch in eventhub triggered azure function
Am writing a event publisher and consumer. From the publisher am trying to send events as batch using eventhub_client.send_batch(batch) Now in the consumer side am receiving event and using if e.get_body() is not None: try: str = e.get_body().decode("utf-8") msg = ast.literal_eval(str) p...
[ "It completely depends on how you are receiving events, i.e., if you are using receive or receive_batch method on the EventHubConsumerClient class.\nBased on your code, I suppose you are using receive, so your handler would process events one-by-one.\nCheck the official samples for receive and receive_batch for mor...
[ 0 ]
[]
[]
[ "azure_functions", "python", "python_3.x" ]
stackoverflow_0074206420_azure_functions_python_python_3.x.txt
Q: Checking if proxy is used or not I want to use proxy with pithon web requests. To test, if my request is working or not I send request to jsonip.com. In the response it returns my real ip instead of the proxy. Also The website providing proxy also says "no activity". I want to ask is, am I connecting to proxy corr...
Checking if proxy is used or not
I want to use proxy with pithon web requests. To test, if my request is working or not I send request to jsonip.com. In the response it returns my real ip instead of the proxy. Also The website providing proxy also says "no activity". I want to ask is, am I connecting to proxy correctly. Here the code. import time, req...
[ "Your have to do this to include the proxy\nimport time, requests, random\nfrom requests.auth import HTTPProxyAuth\nauth = HTTPProxyAuth(\"muyjgovw\", \"mtpysgrb3nkj\")\n\ndef reqs(): \n headers = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:107.0) Gecko/20100101 Firefox/107.0',\n ...
[ 1 ]
[]
[]
[ "proxy", "python", "python_requests" ]
stackoverflow_0074522314_proxy_python_python_requests.txt
Q: How to retrieve SQL result column value using column name in Python? Is there a way to retrieve SQL result column value using column name instead of column index in Python? I'm using Python 3 with mySQL. The syntax I'm looking for is pretty much like the Java construct: Object id = rs.get("CUSTOMER_ID"); I've a ...
How to retrieve SQL result column value using column name in Python?
Is there a way to retrieve SQL result column value using column name instead of column index in Python? I'm using Python 3 with mySQL. The syntax I'm looking for is pretty much like the Java construct: Object id = rs.get("CUSTOMER_ID"); I've a table with quite a number of columns and it is a real pain to constantly w...
[ "The MySQLdb module has a DictCursor:\nUse it like this (taken from Writing MySQL Scripts with Python DB-API):\ncursor = conn.cursor(MySQLdb.cursors.DictCursor)\ncursor.execute(\"SELECT name, category FROM animal\")\nresult_set = cursor.fetchall()\nfor row in result_set:\n print \"%s, %s\" % (row[\"name\"], row[...
[ 95, 31, 22, 14, 7, 6, 3, 2, 1, 0, 0 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0010195139_mysql_python.txt
Q: Where is indentation problem in my Python code? I'm trying to solve my homework coding assignment, but I'm facing a indentation error in my code. I spent quite long time now tryibg to figure out what I'm doing wrong but I don't see the error. Moreover, a friend of mine has a very similar code and it works just fin...
Where is indentation problem in my Python code?
I'm trying to solve my homework coding assignment, but I'm facing a indentation error in my code. I spent quite long time now tryibg to figure out what I'm doing wrong but I don't see the error. Moreover, a friend of mine has a very similar code and it works just fine for him. The Indentation error being raised after I...
[ "I've fixed the indentation errors I was able to find in your code, made some changes to it, and added some remark comments as \"# NOTE: ...\":\n\n# == Necessary Imports =========================================================\nimport sys\nimport os\n\nfrom bitstring import BitArray\n\n\n# == Variables ===========...
[ 0 ]
[]
[]
[ "compiler_errors", "indentation", "pylance", "python", "syntax_error" ]
stackoverflow_0074526466_compiler_errors_indentation_pylance_python_syntax_error.txt
Q: Is there a way to detect exisiting link from a text file in python I have code in jupyter notebook with the help of requests to get confirmation on whether that url existed or not and after that prints out the output into the text file. Here is the line code for that import requests Instaurl = open("dictionaries/...
Is there a way to detect exisiting link from a text file in python
I have code in jupyter notebook with the help of requests to get confirmation on whether that url existed or not and after that prints out the output into the text file. Here is the line code for that import requests Instaurl = open("dictionaries/insta.txt", 'w', encoding="utf-8") cli = ['duolingo', 'ryanair', 'mcgui...
[ "You defined a list:\ncli = ['duolingo', ...]\n\nIt sounds like you would prefer to define a set:\ncli = {'duolingo', ...}\n\nThat way, duplicates will be suppressed.\nIt happens for dups in the initial\nassignment, and for any duplicate cli.add(entry) you might attempt later.\n" ]
[ 0 ]
[]
[]
[ "jupyter_notebook", "python", "python_requests" ]
stackoverflow_0074527269_jupyter_notebook_python_python_requests.txt
Q: Remove a widget generated with for loop I work on a python project, and I would like to create a history where each history is erasable with a "delete" button placed in the Frame of the widget I tried to add the « delete » button in the loop where the widget was generated but it didn’t work as planned history_file...
Remove a widget generated with for loop
I work on a python project, and I would like to create a history where each history is erasable with a "delete" button placed in the Frame of the widget I tried to add the « delete » button in the loop where the widget was generated but it didn’t work as planned history_files = os.listdir(history_directory) history_fil...
[ "It's hard to know what do you wish to accomplish. I can't see any button on your code and I'm not clear what do you wish to delete when the delete button is clicked.\nAs per my understanding, If the delete button is on the history_f, and you wish to remove or delete the Labels i.e. date_l and time_l then following...
[ 0, 0 ]
[]
[]
[ "for_loop", "loops", "python", "tkinter", "widget" ]
stackoverflow_0074521835_for_loop_loops_python_tkinter_widget.txt
Q: Using Counter on a list of Spacy tokens returns a non unique dict of the tokens I want to count a list of spacy tokens with the counter class. I.e.: [hello,how,are,you,hello] where each element is of type <class 'spacy.tokens.token.Token'>. However when i want to count the occurences of each Token within the lis...
Using Counter on a list of Spacy tokens returns a non unique dict of the tokens
I want to count a list of spacy tokens with the counter class. I.e.: [hello,how,are,you,hello] where each element is of type <class 'spacy.tokens.token.Token'>. However when i want to count the occurences of each Token within the list via counter, as seen below: return Counter(joined) The result is a non unique ...
[ "Tokens are not equivalent if they have the same text, they have to be in the same position in the same Doc object. But the output in your screenshot (don't post a screenshot of text...) is just the repr of a token, which is its text.\nIf you want to count just the text, use token.text, like so:\nfrom collections i...
[ 0 ]
[]
[]
[ "counter", "dictionary", "nlp", "python", "spacy" ]
stackoverflow_0074522022_counter_dictionary_nlp_python_spacy.txt
Q: Import cv2 error but opencv-python is already installed I've been trying to make a project with opencv, so I followed the YouTube video (It's in python), the video told me to go to cmd (win10) and use the command "pip install opencv-python" so that I can use the command import cv2. But the problem is after I did e...
Import cv2 error but opencv-python is already installed
I've been trying to make a project with opencv, so I followed the YouTube video (It's in python), the video told me to go to cmd (win10) and use the command "pip install opencv-python" so that I can use the command import cv2. But the problem is after I did everything it still gave me an error. I've done some research ...
[ "Welcome to Stack Overflow!\nTry installing with pip3\npip3 install opencv-python\n\n" ]
[ 0 ]
[]
[]
[ "cv2", "pip", "python" ]
stackoverflow_0074526949_cv2_pip_python.txt
Q: creating and visualizing spacy spans I have a problem visualizing manually created spans in spacy: given the simple code: from spacy.tokens import Span text = "Welcome to the Bank of China. " nlp = spacy.blank("en") doc = nlp(text) doc.spans["xx"] = [Span(doc, 0, 1, "ORG")] doc.spans["sc"] = [ Span(doc, 3, 6,...
creating and visualizing spacy spans
I have a problem visualizing manually created spans in spacy: given the simple code: from spacy.tokens import Span text = "Welcome to the Bank of China. " nlp = spacy.blank("en") doc = nlp(text) doc.spans["xx"] = [Span(doc, 0, 1, "ORG")] doc.spans["sc"] = [ Span(doc, 3, 6, "ORG"), Span(doc, 5, 6, "GPE"), ...
[ "As explained in the displaCy documentation, by default the spans in the key \"sc\" are used. You can change it with the spans_key parameter.\nrender doesn't take spans_key correctly, you have to include it in options.\nFrom the docs, modified to use render instead of serve:\ndoc.spans[\"custom\"] = [Span(doc, 3, 6...
[ 1 ]
[]
[]
[ "python", "spacy" ]
stackoverflow_0074522493_python_spacy.txt
Q: How can I rewrite the line of code "asd" == "qwe" in order to have TRUE be displayed in the Terminal? I am guessing there is an ASCII related explanation to this that I am trying to find out more about. I was thinking of assigning a numeric value . A: Simply print its negatin: print("asd" != "qwe") or: print(no...
How can I rewrite the line of code "asd" == "qwe" in order to have TRUE be displayed in the Terminal?
I am guessing there is an ASCII related explanation to this that I am trying to find out more about. I was thinking of assigning a numeric value .
[ "Simply print its negatin:\nprint(\"asd\" != \"qwe\")\n\nor:\nprint(not (\"asd\" == \"qwe\"))\n\n" ]
[ 1 ]
[]
[]
[ "boolean", "pycharm", "python" ]
stackoverflow_0074527332_boolean_pycharm_python.txt
Q: How to measure the time a script is running despite system time changes? I'm developing a timeout functionality for an embedded device where the system time is updated via gps. This means I can't just compare two timestamps to get the elapsed time: import time t1 = time.time() # system time change, e.g. from 1970...
How to measure the time a script is running despite system time changes?
I'm developing a timeout functionality for an embedded device where the system time is updated via gps. This means I can't just compare two timestamps to get the elapsed time: import time t1 = time.time() # system time change, e.g. from 1970-01-01 to 2022-11-10 t2 = time.time() elapsed = t2 - t1 # this is now wrong! ...
[ "Using time.perf_counter()\n>>> wrong = time.time()\n>>> right = time.perf_counter()\n>>> # set clock back to correct time\n>>> time.time() - wrong\n1420070455.9668648\n>>> time.perf_counter() - right\n42.46595245699996\n\n", "This might work\nhttps://docs.python.org/3/library/time.html#time.monotonic\n\nReturn t...
[ 2, 1, 1, 0 ]
[]
[]
[ "python", "time" ]
stackoverflow_0074400978_python_time.txt
Q: Tracking claims using date/timestamp columns and creating a final count using pandas I have an issue where I need to track the progression of patients insurance claim statuses based on the dates of those statuses. I also need to create a count of status based on certain conditions. DF: ClaimID New Accepted Denied...
Tracking claims using date/timestamp columns and creating a final count using pandas
I have an issue where I need to track the progression of patients insurance claim statuses based on the dates of those statuses. I also need to create a count of status based on certain conditions. DF: ClaimID New Accepted Denied Pending Expired Group 001 2021-01-01T09:58:35:335Z 2021-01-01T10:05:43:000Z A ...
[ "First convert the date columns with something like\nfor i in ['New', 'Accepted', 'Denied', 'Pending', 'Expired']:\n df[i] = pd.to_datetime(df[i], format=\"%Y-%m-%dT%H:%M:%S:%f%z\")\n\nThen develop the date range applicable based on your column conditions. In this logic if Denied is there the range is new --> ...
[ 2, 1 ]
[]
[]
[ "datetime", "for_loop", "pandas", "python" ]
stackoverflow_0074479890_datetime_for_loop_pandas_python.txt
Q: When generating texts in JSON, accented characters look different I am having problems with a code created in Python, and it is that when I generate some texts in json, the accents are not appreciated. This is the code I'm using: import requests url = requests.get(f"https://images.habbo.com/habbo-web-news/es/produ...
When generating texts in JSON, accented characters look different
I am having problems with a code created in Python, and it is that when I generate some texts in json, the accents are not appreciated. This is the code I'm using: import requests url = requests.get(f"https://images.habbo.com/habbo-web-news/es/production/front.json") summary = url.json()[0]['summary'] print(summary) T...
[ "JSON is always in unicode.\nSo you want utf8 encoding everywhere.\nThe url you mentioned sends this (correct) header:\ncontent-type: application/json\n\nHere is a snippet of the content:\n\"content\": \"<h2>Invierno en el Onsen Japon&#xE9;s</h2>\\r\\n<p>Hey Habbo, tus p&#xED;xeles estaban rozando el estado de cong...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074526390_python.txt
Q: Letter frequency for loop in Python Hey can anyone help me here I'm supposed to get a number count for each letter used in this string here using for loops and if statement. quote= "I watched in awe as I saw her swim across the ocean" The pseudocode given is this: for every letter in the alphabet list: Create ...
Letter frequency for loop in Python
Hey can anyone help me here I'm supposed to get a number count for each letter used in this string here using for loops and if statement. quote= "I watched in awe as I saw her swim across the ocean" The pseudocode given is this: for every letter in the alphabet list: Create a variable to store the frequency of each...
[ "There are more eloquent ways to do this, but using your algorithm, the problem is that you're mixing up variables. You're comparing i to alphabet, shadowing the variable i, and redefining c_alphabet in every top-level loop. See the changes here:\nquote = \"I watched in awe as I saw her swim across the ocean.\"\nxq...
[ 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074527290_python.txt
Q: Python timeit ImportError I am trying to compute the time my program takes to execute but sometimes it works fine and sometimes I get the following error: ImportError: cannot import name 'N' from '__main__' N = number t = timeit.Timer( "computeArea(N, 4)", "from __main__ import computeArea, N") ...
Python timeit ImportError
I am trying to compute the time my program takes to execute but sometimes it works fine and sometimes I get the following error: ImportError: cannot import name 'N' from '__main__' N = number t = timeit.Timer( "computeArea(N, 4)", "from __main__ import computeArea, N") computeTime = t.tim...
[ "What do you think of just importing time and measuring the time before and after computeArea runs? Honestly speaking, this chunk of code looks pretty funky from a Python style perspective. Measuring the time yourself is easy, and can be easily modified for more interesting examples (say, taking the average time b...
[ 0 ]
[]
[]
[ "python", "timeit" ]
stackoverflow_0074527223_python_timeit.txt
Q: How to access a value inside a value in a python dictionary Im having a small concern if we can access a value inside a value. Eg: myDict = {1:"Hey", 2:"Bye,1,2,3,4"} As in the example above.. How can I print/access the value 4 in myDict?? Is it possible with indexing?? Eg: 4 # Printing 4 from myDict Thanks. A:...
How to access a value inside a value in a python dictionary
Im having a small concern if we can access a value inside a value. Eg: myDict = {1:"Hey", 2:"Bye,1,2,3,4"} As in the example above.. How can I print/access the value 4 in myDict?? Is it possible with indexing?? Eg: 4 # Printing 4 from myDict Thanks.
[ "For this you need to convert string into array by dividing it by comma \",\".\n\nAccess 2nd element: result = myDict[1]\nDivide it by comma: result = result.split(\",\")\nAccess element: ans = result[4]\n\nmyDict = {1:\"Hey\", 2:\"Bye,1,2,3,4\"}\nresult = myDict[1].split(\",\")\nans = result[4]\nprint(ans)\n\n\n",...
[ 0, 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0074527369_dictionary_python.txt
Q: What to do I want to access all [i] in every tuple inside a list or a dictionary (python)? Let's say I have a dictionary called 'testdic' that looks like this. testdic = { [ ( ('Jane','Sophomore','Science'), (4.0,3.5,3.2) ), ( ('Kim','Junior','Business'), (3.2,2.8,4.0) ), ( ('Jack','Sen...
What to do I want to access all [i] in every tuple inside a list or a dictionary (python)?
Let's say I have a dictionary called 'testdic' that looks like this. testdic = { [ ( ('Jane','Sophomore','Science'), (4.0,3.5,3.2) ), ( ('Kim','Junior','Business'), (3.2,2.8,4.0) ), ( ('Jack','Senior','Music'), (3.0,4.0,3.0) ) ] } And I need to pull all the [2] of the key together to ge...
[ "You wrote a list of unhashable type.\nTo solve this error, ensure you only assign a hashable object, such as a string or a tuple, as a key for a dictionary.\ntestdic = {(('Jane','Sophomore','Science'), (4.0,3.5,3.2)),\n\n(('Kim','Junior','Business'), (3.2,2.8,4.0)),\n\n(('Jack','Senior','Music'), (3.0,4.0,3.0))}\n...
[ 0 ]
[]
[]
[ "python", "spyder" ]
stackoverflow_0074527317_python_spyder.txt
Q: Azure function HTTP response type to make the API download a csv whenever get response called new_csv = df.to_csv('sample.csv', index=False, encoding='utf-8') return func.HttpResponse(new_csv, index=False, encoding='utf-8', mimetype='text/csv') How can I pass the CSV file as a GET response to the func.HttpRespons...
Azure function HTTP response type to make the API download a csv whenever get response called
new_csv = df.to_csv('sample.csv', index=False, encoding='utf-8') return func.HttpResponse(new_csv, index=False, encoding='utf-8', mimetype='text/csv') How can I pass the CSV file as a GET response to the func.HttpResponse in Azure functions, so that whenever the API is hit, the CSV file gets automatically downloaded a...
[ "You can set the Content-Disposition header to attachment which forces browsers to download as a file instead of displaying the content.\n" ]
[ 0 ]
[]
[]
[ "azure", "azure_devops", "azure_functions", "function", "python" ]
stackoverflow_0072217126_azure_azure_devops_azure_functions_function_python.txt
Q: How do you check if a variable references another declared object in Python? Printing type of one variable just returns the pointed data's type i = [5,6,7,8] j = i print(type(j)) <class 'list'> and j references a mutable type. So j[0] = 3 print(i) print(j) [3, 6, 7, 8] [3, 6, 7, 8] I want a function that retur...
How do you check if a variable references another declared object in Python?
Printing type of one variable just returns the pointed data's type i = [5,6,7,8] j = i print(type(j)) <class 'list'> and j references a mutable type. So j[0] = 3 print(i) print(j) [3, 6, 7, 8] [3, 6, 7, 8] I want a function that returns true for j and false for i. If it's built-in or anyone could write that it woul...
[ "There's no 'pointers' in Python, like there are in C++ (or similar languages). The only distinction in Python is mutable vs. immutable. But all variables are just references to objects.\nVariables with immutable types refer to values that you cannot modify, only replace. int is an example of an immutable type.\nWh...
[ 2 ]
[]
[]
[ "pointers", "python" ]
stackoverflow_0074527549_pointers_python.txt
Q: ValueError: shapes (1,6) and (5,5) not aligned: 6 (dim 1) != 5 (dim 0) The NN must have 5 inputs, 4 hidden layers and 1 output. Learning rate 0.2, error threshold 0.2. Retrieves the data from an excel: The error ValueError: shapes (1,6) and (5,5) not aligned: 6 (dim 1) != 5 (dim 0) is being displayed. I think I h...
ValueError: shapes (1,6) and (5,5) not aligned: 6 (dim 1) != 5 (dim 0)
The NN must have 5 inputs, 4 hidden layers and 1 output. Learning rate 0.2, error threshold 0.2. Retrieves the data from an excel: The error ValueError: shapes (1,6) and (5,5) not aligned: 6 (dim 1) != 5 (dim 0) is being displayed. I think I have something wrong with multiplying of weights and matrices the error line:...
[ "Going by the convention that of weights are (n_neurons, n_inputs), I think the shape of your first hidden layer (W1) should be -> number of neurons in that layer, number of attributes/features in the sample.\nAssuming you are outputing the Survived column, your features should be 5.\nIf there are 4 neurons in tha...
[ 1 ]
[]
[]
[ "backpropagation", "mlp", "neural_network", "python" ]
stackoverflow_0074521083_backpropagation_mlp_neural_network_python.txt
Q: How can I install pyplot? I tried to install pyplot using 'pip install pyplot' in command prompt while it was installing by mistake i closed command prompt then again i am trying to install pyplot using the same command but it was not installing.Can anyone guide me how to install pyplotKindly find the error in thi...
How can I install pyplot?
I tried to install pyplot using 'pip install pyplot' in command prompt while it was installing by mistake i closed command prompt then again i am trying to install pyplot using the same command but it was not installing.Can anyone guide me how to install pyplotKindly find the error in this image error rectification in ...
[ "pyplot is part of a matplotlib.\nIn order to install pyplot you should install matplotlib\n\npip install matplotlib\n\nSo you can \"import matplotlib.pyplot\"\n", "You can go to https://pypi.org/project/matplotlib to see and install the version you want.\nThen you can import the pylot\nfrom matplotlib import pyp...
[ 1, 0 ]
[]
[]
[ "data_science", "graph_data_science", "matplotlib", "pandas", "python" ]
stackoverflow_0074527084_data_science_graph_data_science_matplotlib_pandas_python.txt
Q: Add a whitespace to every second line and merge every second line in a text file Python I have a text file of lets say this content a b c d e f I want python to read the textfile and edit it to this, add whitespace to the start of every second line then merge with first line above, this is what it should look lik...
Add a whitespace to every second line and merge every second line in a text file Python
I have a text file of lets say this content a b c d e f I want python to read the textfile and edit it to this, add whitespace to the start of every second line then merge with first line above, this is what it should look like a b c d e f How can I achieve this? I written gotten this together but it only prints and ...
[ "I would suggest differnt approch this also may works.\nwith open(\"text.txt\") as file_in:\nlines = []\nfor line in file_in:\n lines.append(line)\n\n#lines ['a\\n', 'b\\n', 'c\\n', 'd']\n\nlines = [x.replace('\\n', '') for x in lines]\nfor x in range(0,len(lines),2):\n print (lines[x], lines[x+1])\n\nshould ...
[ 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074527537_python_python_3.x.txt
Q: conda uninstall quits without removing anything I've tried to remove packages using conda uninstall. The command runs for a long time, takes up a large amount of memory (but doesn't run out I believe) and then quits with no indication of having completed the 'Solving environment' step. When I check, the package ...
conda uninstall quits without removing anything
I've tried to remove packages using conda uninstall. The command runs for a long time, takes up a large amount of memory (but doesn't run out I believe) and then quits with no indication of having completed the 'Solving environment' step. When I check, the package is still there. For example: (base) pm@pm:~/Software...
[ "If you're here because you're trying to install a pre or beta package that isn't available via conda, I was able to do an upgrade via pip.\nI had installed h3-py via conda, which installed v3.7.\n$ conda install h3-py\n\n...\nThe following NEW packages will be INSTALLED:\n\n h3-py conda-forge/linux-6...
[ 0 ]
[]
[]
[ "conda", "python" ]
stackoverflow_0071330613_conda_python.txt
Q: Raspberry pi pico with MPU6050 reading zeros So I am working on a step counter using a raspberry pi pico and a MPU6050 when last night I had the code working fine so I unplugged the pico, then I went to plug the pico back in this morning and now it's displaying zeros. I configured the code accordingly to these hoo...
Raspberry pi pico with MPU6050 reading zeros
So I am working on a step counter using a raspberry pi pico and a MPU6050 when last night I had the code working fine so I unplugged the pico, then I went to plug the pico back in this morning and now it's displaying zeros. I configured the code accordingly to these hookups: VCC to 3v3 GND to GND SCL to GP1 SDA to GP0 ...
[ "I added this code to initialize the MPU6050: mpu6050_init(i2c) to the end of my code (right before the 'steps = 0 #step counter' bit). This is calling a function near the top of the code to initialize the board to get out of sleep mode, which is what causes 'sleep mode' on the device.\n" ]
[ 0 ]
[]
[]
[ "micropython", "mpu6050", "python", "raspberry_pi_pico" ]
stackoverflow_0074518571_micropython_mpu6050_python_raspberry_pi_pico.txt
Q: return self._engine.get_loc(casted_key) 3622 except KeyError as err I have the following code df = pd.DataFrame(columns=['col1', 'col2', 'col3', 'col4', 'col5', 'col6']) vec = [a,b,c,d,...] for v in vec: name = 'name' df.loc[name]['col1'] = v .... And I got error that: ...
return self._engine.get_loc(casted_key) 3622 except KeyError as err
I have the following code df = pd.DataFrame(columns=['col1', 'col2', 'col3', 'col4', 'col5', 'col6']) vec = [a,b,c,d,...] for v in vec: name = 'name' df.loc[name]['col1'] = v .... And I got error that: How to solve such error?
[ "Solved it, using df.at[name] = v\n" ]
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074527207_pandas_python.txt
Q: VTK retrieve a specific actor from a renderer I have the following code: my_renderer = vtkRenderer() my_actor = vtkActor() my_renderer.AddActor(my_actor) Is there a way to recover a specific actor from the renderer? VtkRenderer has the following function GetActors() which returns a collection of actors but I can...
VTK retrieve a specific actor from a renderer
I have the following code: my_renderer = vtkRenderer() my_actor = vtkActor() my_renderer.AddActor(my_actor) Is there a way to recover a specific actor from the renderer? VtkRenderer has the following function GetActors() which returns a collection of actors but I cannot see how to identify any specific one, if say I...
[ "How do you specific the wanted actor?\nOne possible solution is: implement a selfActor which inherits from vtkActor. Then, record a name in selfActor. Then, you can use actor->GetName() to obtain the name. You can identify the actor by the name.\n" ]
[ 0 ]
[]
[]
[ "3d", "python", "vtk" ]
stackoverflow_0074140486_3d_python_vtk.txt
Q: PyAutoGUI random click within area in a radial-like pattern pretty new to python, but I'm trying to have the mouse click on a point within an image using PyAutoGUI. However the project requires I simulate a "human pattern". So what I'm going for is an "accurate-like" accuracy, where most of the points are in the m...
PyAutoGUI random click within area in a radial-like pattern
pretty new to python, but I'm trying to have the mouse click on a point within an image using PyAutoGUI. However the project requires I simulate a "human pattern". So what I'm going for is an "accurate-like" accuracy, where most of the points are in the middle and it gets more sparse the further away the click is, simu...
[ "Generate a random number and add into your x & y positions\nimport random\nfrom PIL import Image\n\nobject = Image.open('Screenshot.png')\ntheWidth = object.width\ntheHeight = object.height\nX = pos.x + random.randint(pos.x - theWidth/2,pos.x + theWidth/2)\nY = pos.y + random.randint(pos.y - theHeight/2,pos.y + th...
[ 0, 0 ]
[]
[]
[ "arrays", "pyautogui", "python" ]
stackoverflow_0074525304_arrays_pyautogui_python.txt
Q: What is the best method of plotting the average line/data of multiple CSV files? I am currently working with 9 different csv files all testing similar samples of a material. The output of data looks similar to this: Time,Displacement,Force,Flexure stress,Flexure strain (Displacement) (s),(mm),(N),(MPa),(%) "0.0000...
What is the best method of plotting the average line/data of multiple CSV files?
I am currently working with 9 different csv files all testing similar samples of a material. The output of data looks similar to this: Time,Displacement,Force,Flexure stress,Flexure strain (Displacement) (s),(mm),(N),(MPa),(%) "0.0000","0.0000","0.0007","0.0000","0.0000" "0.0200","0.0000","0.0069","0.0004","0.0000" "0....
[ "Here is my solution and image result.\nimport os\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n### Set path to the folder containing the .csv files\nPATH = './' \n\n### Fetch all files in path\nfileNames = os.listdir(PATH)\n\n### Filter file name list for files ending with .csv\nfile...
[ 0 ]
[]
[]
[ "csv", "dataframe", "matplotlib", "pandas", "python" ]
stackoverflow_0074527271_csv_dataframe_matplotlib_pandas_python.txt
Q: Blank page when removing all mentions of grid() I've switched from .grid() to .place() in my program, so I decided to remove a frame that contained the grid widgets: BackButtonR = Button(registerPage, text="Back", command=lambda: show_frame(Menu)) BackButtonR.grid(row=0, column=0, sticky=W) Button2F3 = Button(regi...
Blank page when removing all mentions of grid()
I've switched from .grid() to .place() in my program, so I decided to remove a frame that contained the grid widgets: BackButtonR = Button(registerPage, text="Back", command=lambda: show_frame(Menu)) BackButtonR.grid(row=0, column=0, sticky=W) Button2F3 = Button(registerPage, text="Find") Button2F3.grid(row=1, column=1...
[ "When you use pack and grid, these functions will normally adjust the size of a widget's parent to fit all of its children. It's one of the most compelling reasons to use these geometry managers.\nWhen you use place this doesn't happen. If you use place to put a widget in a frame, the frame will not grow or shrink ...
[ 1, 0 ]
[]
[]
[ "grid", "python", "tkinter" ]
stackoverflow_0074524438_grid_python_tkinter.txt
Q: Python [WinError 3] The system cannot find the path specified At first this script run fine but after it show this error "[WinError 3] The system cannot find the path specified" without changing anything in the script import os paths = os.listdir(r'C:\Users\Film\OneDrive\Documents\WORK\Blockfint\Richy_csv_files\R...
Python [WinError 3] The system cannot find the path specified
At first this script run fine but after it show this error "[WinError 3] The system cannot find the path specified" without changing anything in the script import os paths = os.listdir(r'C:\Users\Film\OneDrive\Documents\WORK\Blockfint\Richy_csv_files\Recovery_as_compu_11_14_2022_14_9_32\Tables') def files_with_word(w...
[ "The issue you are having looks like it is with not using absolute paths. paths = os.listdir(r'C:\\Users\\Film\\OneDrive\\Documents\\WORK\\Blockfint\\Richy_csv_files\\Recovery_as_compu_11_14_2022_14_9_32\\Tables') will just get a list of filenames with no path info. So if you are not actually running the python fil...
[ 0 ]
[]
[]
[ "python", "visual_studio_code", "window" ]
stackoverflow_0074521325_python_visual_studio_code_window.txt
Q: How to convert AVIF To PNG with Python? I have an image file in avif format How can I convert this file to png format? I found some code to convert jpg files to avif, but I didn't find any code to reconvert them. A: You need to install this modules: pip install pillow-avif-plugin Pillow Then: from PIL import Ima...
How to convert AVIF To PNG with Python?
I have an image file in avif format How can I convert this file to png format? I found some code to convert jpg files to avif, but I didn't find any code to reconvert them.
[ "You need to install this modules: pip install pillow-avif-plugin Pillow\nThen:\nfrom PIL import Image\nimport pillow_avif\n\nimg = Image.open('input.avif')\nimg.save('output.png')\n\n" ]
[ 0 ]
[]
[]
[ "image", "python" ]
stackoverflow_0074527775_image_python.txt
Q: VS Code / python importing issue when running a script for the first time I am running a python script on VS Code and I am getting a package importing error but only the first time I run it after opening VS Code. If I run the same script again I don't get any errors, which makes me think there is something importa...
VS Code / python importing issue when running a script for the first time
I am running a python script on VS Code and I am getting a package importing error but only the first time I run it after opening VS Code. If I run the same script again I don't get any errors, which makes me think there is something important being loaded only after I run it the first time. Any ideas of what might be ...
[ "This seems to be a solved problem. You can refer to this answer.\nAdd the following path to the system environment variable PATH (Note that this needs to be adjusted according to your actual path. The comment supplied that adding...\\Scripts and... \\Library\\bin solves this problem):\nC:\\Users\\<myusername>\\App...
[ 0 ]
[]
[]
[ "numpy", "python", "visual_studio_code" ]
stackoverflow_0074526548_numpy_python_visual_studio_code.txt
Q: Python stable_baselines3 - AssertionError: The observation returned by `reset()` method must be an int I am trying to learn reinforcement learning to train ai on custom games in python, and decided to use gym for the environment and stable-baselines3 for the training. I decided to start off with a basic tic tac to...
Python stable_baselines3 - AssertionError: The observation returned by `reset()` method must be an int
I am trying to learn reinforcement learning to train ai on custom games in python, and decided to use gym for the environment and stable-baselines3 for the training. I decided to start off with a basic tic tac toe environment. Here's my code import gym from gym import spaces import numpy as np from stable_baselines3.co...
[ "When you do\nself.observation_space = spaces.Discrete(9)\n\nyou're actually defining your observation space as a single value that can take in all values of {0, 1, 2, 3, 4, 5, 6, 7, 8} since you defined it as a discrete single-dimension space (aka an integer).\nAs you said you were trying to make a tic-tac-toe env...
[ 0 ]
[]
[]
[ "openai_gym", "python", "reinforcement_learning", "stable_baselines" ]
stackoverflow_0073201176_openai_gym_python_reinforcement_learning_stable_baselines.txt
Q: Text recognition and detection using TensorFlow I a working on a text recognition project. I have built a classifier using TensorFlow to predict digits but I would like to implement a more complex algorithm of text recognition by using text localization and text segmentation (separating each character) but I didn'...
Text recognition and detection using TensorFlow
I a working on a text recognition project. I have built a classifier using TensorFlow to predict digits but I would like to implement a more complex algorithm of text recognition by using text localization and text segmentation (separating each character) but I didn't find an implementation for those parts of the algor...
[ "To group elements on a page, like paragraphs of text and images, you can use some clustering algo, and/or blob detection with some tresholds.\nYou can use Radon transform to recognize lines and detect skew of a scanned page.\nI think that for character separation you will have to mess with fonts. Some polynomial m...
[ 1, 0 ]
[]
[]
[ "deep_learning", "python", "tensorflow", "text_classification", "text_recognition" ]
stackoverflow_0042868546_deep_learning_python_tensorflow_text_classification_text_recognition.txt
Q: How to train custom model for Tensorflow Lite and have the output be a .TFLITE file I'm new to tensorflow and object detetion, and any help would be greatly appreciated! I got a database of 50 photos, used this video to get me started, and it DID work with Google's Sample Model (I'm using a RPi4B with 8 GB of RAM)...
How to train custom model for Tensorflow Lite and have the output be a .TFLITE file
I'm new to tensorflow and object detetion, and any help would be greatly appreciated! I got a database of 50 photos, used this video to get me started, and it DID work with Google's Sample Model (I'm using a RPi4B with 8 GB of RAM), then I wanted to create my own model. I tried a couple of options, but ultimately faile...
[ "Easy, just downgrade to OpenCV version 3.4.16, and use Tensorflow 1.0 instead of 2.0 and that should solve all your problems. That will allow the use of .LITE files, as well that of .TFLITE\nAlso, try increasing the resolution to a 720x1280, most likely that can cause a ton of errors as well when working with tens...
[ 0, 0 ]
[]
[]
[ "object_detection", "python", "raspberry_pi", "tensorflow", "tensorflow_lite" ]
stackoverflow_0074247205_object_detection_python_raspberry_pi_tensorflow_tensorflow_lite.txt
Q: Groupby and get just top 50% record based on one column pyspark I have a dataframe like this: id item_id score 1 6 1.1 2 6 1 3 6 1.4 7 6 1.3 8 2 1.2 9 2 1.8 1 4 2 10 4 1.1 2 4 1.9 8 4 1.2 . . ...
Groupby and get just top 50% record based on one column pyspark
I have a dataframe like this: id item_id score 1 6 1.1 2 6 1 3 6 1.4 7 6 1.3 8 2 1.2 9 2 1.8 1 4 2 10 4 1.1 2 4 1.9 8 4 1.2 . . . Where combination of column id and item_id is primary key, but ...
[ "this should working using the row_number() and count() window functions. take the count() and divide by 2.\nupdated filter to handle case where there's only one record.\nthere's a case of how do you want to handle odd record counts.\nfor instance 50% of 3 records is 1.5..you can set row_num_val as a whole number b...
[ 3 ]
[]
[]
[ "apache_spark", "apache_spark_sql", "pyspark", "python", "sql" ]
stackoverflow_0074527148_apache_spark_apache_spark_sql_pyspark_python_sql.txt
Q: Convert arrays inside a list into a single array and append zeros The objective of this code snippet was to create a 2D array of shape (10,10) with array[0,0]=1; array[0,9]=100; and array[9,0]=50. Complications arose when the interval between these elements had to be equal as shown in the expected output. Rows had...
Convert arrays inside a list into a single array and append zeros
The objective of this code snippet was to create a 2D array of shape (10,10) with array[0,0]=1; array[0,9]=100; and array[9,0]=50. Complications arose when the interval between these elements had to be equal as shown in the expected output. Rows had to increment with equal intervals up-to 100 and columns had to increme...
[ "The main problem is that you're overwriting your pre-allocated array matrix_list with the result of the list comprehension, which is just a series of lists. Thus, you lose all of the structure that you defined to begin with. To make things simpler (since you also have an issue with making the numpy range up to the...
[ 0, 0 ]
[]
[]
[ "arrays", "numpy", "python", "python_3.x" ]
stackoverflow_0074527685_arrays_numpy_python_python_3.x.txt
Q: selecting where in multiple columns on ANSI SQL (IMPALA SQL) It worked normally in Oracle SQL, but it does not work in ANSI SQL. SELECT whatever WHERE (col1,col2) IN ((val1, val2), (val1, val2), ...) How do I write code in ANSI SQL (IMPALA SQL)? I don't want the following code because there are many lists. WHERE ...
selecting where in multiple columns on ANSI SQL (IMPALA SQL)
It worked normally in Oracle SQL, but it does not work in ANSI SQL. SELECT whatever WHERE (col1,col2) IN ((val1, val2), (val1, val2), ...) How do I write code in ANSI SQL (IMPALA SQL)? I don't want the following code because there are many lists. WHERE (col1 = val1a AND col2 = val2a) OR (col1 = val1b AND col2 = val...
[ "This isnt possible in hive or impala. Only 'other' workaround is concat().\nYou can use below sql-\n...\nwhere concat(col1,'~',col2) IN (concat(val1,'~',val2),concat(val3,'~',val4)...)\n\nPls note if col1/col2 is null, it wont be matched.\nEDIT : this can have severe performance problem. So, you can store val1,val...
[ 0 ]
[]
[]
[ "ansi", "impala", "python", "sql", "where_clause" ]
stackoverflow_0074527754_ansi_impala_python_sql_where_clause.txt
Q: Running python in VS code such that I can test functions on the REPL I am trying to run a Python file in VS code. I have a very simple function that takes in a number and returns the sum of its digits. However, when I actually run the Python file on VS Code, it does nothing and does not open a REPL so I can manual...
Running python in VS code such that I can test functions on the REPL
I am trying to run a Python file in VS code. I have a very simple function that takes in a number and returns the sum of its digits. However, when I actually run the Python file on VS Code, it does nothing and does not open a REPL so I can manually test the function on n. For example, I tried python3 on the terminal, a...
[ "Right-click in the code editor window and select Run Current File in Interactive Window, or select Jupyter: Create Interactive Window in the command palette to open an interactive window.\n\n\nThere is another way you can open the REPL and select the entire content of the script and use the shortcut key Shift+Ente...
[ 1 ]
[]
[]
[ "python", "visual_studio_code" ]
stackoverflow_0074515198_python_visual_studio_code.txt
Q: How do I go skip an element in a list if all the keys in a dictionary which has a value of a set already has that element? As the title suggests, if I had a dictionary with keys and values (in which these values are sets) where all of the key's values already have an element from a list, they move on to see if the...
How do I go skip an element in a list if all the keys in a dictionary which has a value of a set already has that element?
As the title suggests, if I had a dictionary with keys and values (in which these values are sets) where all of the key's values already have an element from a list, they move on to see if they could add the next element into the set. For instance, lst = ['a', 'b', 'v'] lst = ['a', 'b', 'v'] sample_dct = {'test': {'a'}...
[ "You can use python's all function to test that all values contain the list item. If they don't, then the item can be added to all values (as it's a set duplication doesn't really matter) and then return, otherwise move to the next letter in the list.\nlst = ['a', 'b', 'v']\nsample_dct = {'test': {'a'}, 'letter': ...
[ 0 ]
[]
[]
[ "list", "python", "python_3.x", "set" ]
stackoverflow_0074527396_list_python_python_3.x_set.txt
Q: Python jupyter: can't send request to website I'm learning python and trying the below code on Jupyter, but is shown error. import requests response = requests.get("https://en.wikipedia.org/wiki/main_page") ConnectionError: HTTPSConnectionPool(host='en.wikipedia.org', port=443): Max retries exceeded with url: /wi...
Python jupyter: can't send request to website
I'm learning python and trying the below code on Jupyter, but is shown error. import requests response = requests.get("https://en.wikipedia.org/wiki/main_page") ConnectionError: HTTPSConnectionPool(host='en.wikipedia.org', port=443): Max retries exceeded with url: /wiki/main_page (Caused by NewConnectionError('<urllib...
[ "I got problem sovlved with using parameter verify=False\nhttps://www.w3schools.com/python/ref_requests_get.asp\nFor reference,\nI found the answer at here:\nhttps://community.nexthink.com/s/question/0D52p0000ARmsbgCQB/below-code-in-python-tried-on-jupyter-nb-then-it-throws-following-error-sslerror-httpsconnection...
[ 0 ]
[]
[]
[ "jupyter_notebook", "python", "python_requests", "web_scraping" ]
stackoverflow_0046036784_jupyter_notebook_python_python_requests_web_scraping.txt
Q: How to create a fixture for test functions I am trying to create a fixture for those functions but I keep getting no tests were found an empty suite. Maybe I'm doing something wrong but see the code below and what I have tried. import pytest import time from selenium import webdriver from selenium.common import No...
How to create a fixture for test functions
I am trying to create a fixture for those functions but I keep getting no tests were found an empty suite. Maybe I'm doing something wrong but see the code below and what I have tried. import pytest import time from selenium import webdriver from selenium.common import NoSuchElementException from selenium.webdriver.com...
[ "A fixture is just a regular python function, a basic one would have no parameters and return an object or data that you want to use in your test.\nfor example if you wanted to test your selenium driver...\nimport pytest\nfrom selenium import webdriver\n\n@pytest.fixture\ndef driver():\n wd = webdriver.Chrome()\...
[ 0 ]
[]
[]
[ "automated_tests", "pytest", "python", "python_3.x" ]
stackoverflow_0074527840_automated_tests_pytest_python_python_3.x.txt
Q: Global variable in python with image processing how can i make vehicle_count as a global variable so i can call it on the file class it has a use of car counting with opencv class Vehicle_Counting: def __init__(self, window): self.window = window self.window.geometry('1366x768') se...
Global variable in python with image processing
how can i make vehicle_count as a global variable so i can call it on the file class it has a use of car counting with opencv class Vehicle_Counting: def __init__(self, window): self.window = window self.window.geometry('1366x768') self.window.resizable(0, 0) self.window.state('...
[ "You don't need to use global variable, use instance variable of Vehicle_Counting and pass it to instance of Countdown_Timer.\nBelow is the modified code:\nfrom tkinter import *\nfrom tkinter import messagebox\n\nclass Vehicle_Counting:\n\n def __init__(self, window):\n self.window = window\n self....
[ 0 ]
[]
[]
[ "class", "global", "python", "tkinter" ]
stackoverflow_0074527974_class_global_python_tkinter.txt
Q: Scraped Python results have changed from numbers to NaN the last time I ran this code in February, it gave me proper results like this. Sales Income AAPL 365.82B 94.68B MSFT 184.90B 71.19B TSLA 53.82B 5.52B FB 112.33B 40.30B Now I get this with NaN instead of the numbers. The Finv...
Scraped Python results have changed from numbers to NaN
the last time I ran this code in February, it gave me proper results like this. Sales Income AAPL 365.82B 94.68B MSFT 184.90B 71.19B TSLA 53.82B 5.52B FB 112.33B 40.30B Now I get this with NaN instead of the numbers. The Finviz website looks to be using the exact same table as back in ...
[ "Your code was running for the first symbol only\ndef get_fundamental_data(df):\n for symbol in df.index:\n try:\n # url = (\"http://finviz.com/quote.ashx?t=\" + symbol.lower())\n r = requests.get(\"http://finviz.com/quote.ashx?t=\" + symbol.lower(), headers=headers)\n sou...
[ 0 ]
[]
[]
[ "python", "web_scraping" ]
stackoverflow_0074526586_python_web_scraping.txt
Q: ValueError: invalid literal for int() with base 16: 'Interstitial' I want to convert the below string into categorical form or one hot encoded. string1 = "Interstitial markings are diffusely prominent throughout both lungs. Heart size is normal. Pulmonary XXXX normal." st1 = string1.split() I am using below code ...
ValueError: invalid literal for int() with base 16: 'Interstitial'
I want to convert the below string into categorical form or one hot encoded. string1 = "Interstitial markings are diffusely prominent throughout both lungs. Heart size is normal. Pulmonary XXXX normal." st1 = string1.split() I am using below code but it generates error. from numpy import array from numpy import argmax...
[ "Tensorflow has clearly mentioned it here that the tf.keras.utils.to_categorical is for converting a class vector (integers) to binary class matrix.\nYour data variable contains string type elements, which is not same as integer, hence the error.\n", "Logically error wise says you typecasting str to int.\nLike in...
[ 2, 2 ]
[]
[]
[ "keras", "python", "tensorflow" ]
stackoverflow_0074528000_keras_python_tensorflow.txt
Q: Can't install scrapy with Python 3? I am using Python 3.6.3 and Pip 9.0.1 but still can't install scrapy? I am doing this on windows. When executing the following command pip3 install scrapy I am greeted with this error first.. ---------------------------------------- Failed building wheel for Twisted Running setu...
Can't install scrapy with Python 3?
I am using Python 3.6.3 and Pip 9.0.1 but still can't install scrapy? I am doing this on windows. When executing the following command pip3 install scrapy I am greeted with this error first.. ---------------------------------------- Failed building wheel for Twisted Running setup.py clean for Twisted Failed to build Tw...
[ "I had the same problem too but I solved it as follow:\nOpen the Anaconda Prompt as administrator (For Windows10: open cortana/search Anaconda Prompt/choose Run as Administrator)\nYou should go to the path of Anaconda, for me was like:\nC:\\WINDOWS\\system32>cd ..\nC:\\WINDOWS>cd..\nC:\\>cd ProgramData\nC:\\Progra...
[ 6, 0 ]
[]
[]
[ "python", "scrapy" ]
stackoverflow_0047877205_python_scrapy.txt
Q: Threesum problem using python unable to satisfy all the cases I am trying to solve the famous [Threesum][1] problem with the help of dictionaries. The overall idea is to add the element to the dictionary once visited in case of match or unmatch so that the same element is not used twice for adding up and compariso...
Threesum problem using python unable to satisfy all the cases
I am trying to solve the famous [Threesum][1] problem with the help of dictionaries. The overall idea is to add the element to the dictionary once visited in case of match or unmatch so that the same element is not used twice for adding up and comparison. The code is as below: def threeSum(nums): nums.sort() pr...
[ "Dictionary implementation:\nclass Solution(object):\n def threeSum(self, nums):\n length=len(nums) \n res=[] \n dic=dict()\n nums.sort() #Sorted the nums Time- O(NlogN)\n \n for i in range(length):\n dic[nums[i]]=i\n #print(dic)\n i=0\n ...
[ 0 ]
[]
[]
[ "algorithm", "data_structures", "python" ]
stackoverflow_0072498929_algorithm_data_structures_python.txt
Q: How to create a Plotly animation from a list of figure objects? I have a list of Plotly figures and I want to create an animation that iterates over each figure on a button press. Similar the examples found on Intro to Animations in Python. I pretty much tried re-creating several of the examples on the page with n...
How to create a Plotly animation from a list of figure objects?
I have a list of Plotly figures and I want to create an animation that iterates over each figure on a button press. Similar the examples found on Intro to Animations in Python. I pretty much tried re-creating several of the examples on the page with no luck. It seems like there should be a simple solution but I have no...
[ "I think the most helpful example in the plotly documentation was on visualizing mri volume slices. Instead of creating a list of figure objects, we can store the data and layout of each figure in a list of go.Frame objects and then initialize our figure with these frames with something like fig = go.Figure(frames=...
[ 1 ]
[]
[]
[ "plotly", "plotly_dash", "python" ]
stackoverflow_0074526203_plotly_plotly_dash_python.txt