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:
Using Pandas to dynamically replace values found in other columns
I have a dataset looks like this:
Car
Make
Model
Engine
Toyota Rav 4 8cyl6L
Toyota
8cyl6L
Mitsubishi Eclipse 2.1T
Mitsubishi
2.1T
Monster Gravedigger 25Lsc
Monster
25Lsc
The data was clearly concatenated from Make + Model + Engine at some po... | Using Pandas to dynamically replace values found in other columns | I have a dataset looks like this:
Car
Make
Model
Engine
Toyota Rav 4 8cyl6L
Toyota
8cyl6L
Mitsubishi Eclipse 2.1T
Mitsubishi
2.1T
Monster Gravedigger 25Lsc
Monster
25Lsc
The data was clearly concatenated from Make + Model + Engine at some point but the car Model was not provided to me.
I've been tryi... | [
"you can use:\ndf['Model']=df.apply(lambda x: x['Car'].replace(x['Make'],\"\").replace(x['Engine'],\"\"),axis=1)\nprint(df)\n'''\n Car Make Model Engine\n0 Toyota Rav 4 8cyl6L Toyota Rav 4 8cyl6L\n1 Mitsubishi Eclipse 2.1T Mitsubishi Eclipse ... | [
2,
1
] | [] | [] | [
"dataframe",
"pandas",
"python",
"replace"
] | stackoverflow_0074502929_dataframe_pandas_python_replace.txt |
Q:
SKLearn VotingClassifier is throwing an issue about argument not being iterable?
This might seem a bit simplistic and to be honest I have spent a few hours looking at this and trying back and forth and now cannot see the wood from the trees.
I am constantly falling into the same error of a zip argument not being i... | SKLearn VotingClassifier is throwing an issue about argument not being iterable? | This might seem a bit simplistic and to be honest I have spent a few hours looking at this and trying back and forth and now cannot see the wood from the trees.
I am constantly falling into the same error of a zip argument not being iterable when trying to fit a dataFrame and series to a votingClassifer.
I currently ha... | [
"It turns out I am an arrogant coder who is too reliant on following where the error messages are thrown than actually reading them all the way through. Kaggle Notebooks doesn't have a debugger in the IDE sense, but it turns out I can add %debug to the start of a code block and it will provide a traditional debugge... | [
0
] | [] | [] | [
"machine_learning",
"pandas",
"python",
"scikit_learn"
] | stackoverflow_0074461779_machine_learning_pandas_python_scikit_learn.txt |
Q:
wxPython: Is it possible to manage the hover color of a button?
I'm trying to create a dark theme for my wxPython app, and I'm wondering if I can control the hover color of a button.
import wx
class AppButton(wx.Button):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
... | wxPython: Is it possible to manage the hover color of a button? | I'm trying to create a dark theme for my wxPython app, and I'm wondering if I can control the hover color of a button.
import wx
class AppButton(wx.Button):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.SetLabel('Test')
self.SetOwnBackgroundColour... | [
"So Close!\nwx.EVT_ENTER_WINDOW and wx.EVT_LEAVE_WINDOW will do the job, I guess you missed the implementation somehow.\nimport wx\n\nclass AppButton(wx.Button):\n \n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n \n self.SetLabel('Test')\n self.SetBackg... | [
0
] | [] | [] | [
"python",
"user_interface",
"wxpython"
] | stackoverflow_0074500316_python_user_interface_wxpython.txt |
Q:
Installing pygame through pip error
I'm trying to install pygame to work with python through pip, however when I use the command pip install pygame, it begins working and seems alright until it throws an error. This is the output I get, I'm not sure if i'm doing it correctly or what, I'm new to pip so I'm just not... | Installing pygame through pip error | I'm trying to install pygame to work with python through pip, however when I use the command pip install pygame, it begins working and seems alright until it throws an error. This is the output I get, I'm not sure if i'm doing it correctly or what, I'm new to pip so I'm just not sure. Any help would be appreciated!
C:\... | [
"This is an old question, but the error is usually related with incompatible versions of Python and PyGame. You should check if the version of Python you're using is compatible with the version of PyGame.\nYou may need to install a specific version of PyGame, e.g. python -m pip install pygame==1.9.3\nI've been usin... | [
2,
0
] | [] | [] | [
"command_prompt",
"pip",
"pygame",
"python"
] | stackoverflow_0041339661_command_prompt_pip_pygame_python.txt |
Q:
Dashboard Plotly ValueError: Invalid value
I have a Dash app that plots several graphs. When the Dash app starts, some plots do not get displayed, and I see the error. This only occurs on the initial startup of the app. When the webpage is refreshed, the error does not re-appear, and all plots get displayed withou... | Dashboard Plotly ValueError: Invalid value | I have a Dash app that plots several graphs. When the Dash app starts, some plots do not get displayed, and I see the error. This only occurs on the initial startup of the app. When the webpage is refreshed, the error does not re-appear, and all plots get displayed without errors.
Callback error updating {"index":1,"ta... | [
"I had a similar issue, but found a solution of sorts from LeoWY on the Plotly forums. LeoWY suggests calling the graph within a try/except block in which you add the same function call after both the try statement and the except statement. As LeoWY explains, this method should allow the graph to render properly th... | [
0
] | [] | [] | [
"callback",
"dashboard",
"plotly",
"plotly_dash",
"python"
] | stackoverflow_0074367104_callback_dashboard_plotly_plotly_dash_python.txt |
Q:
Getting error "cannot convert the series to " when trying to convert Unix timestamp (int) to datetime
I have a table called 'Generic' with a date column called 'createdDate' with values as Unix timestamp. The datatype of the Unix timestamp values are currently int64.
I would like to create another column in the da... | Getting error "cannot convert the series to " when trying to convert Unix timestamp (int) to datetime | I have a table called 'Generic' with a date column called 'createdDate' with values as Unix timestamp. The datatype of the Unix timestamp values are currently int64.
I would like to create another column in the dataframe called 'createdDate2' which would contain the Unix dates in a datetime format (e.g. YY/MM/DD)
I am ... | [
"You give the entire dataframe to the function that only needs to take a single integer, so you get an error. You can use the code below.\ngeneric['createdDate2']=pd.to_datetime(generic['createdDate'], unit='s')\n\n"
] | [
0
] | [] | [] | [
"datetime",
"python",
"unix"
] | stackoverflow_0074502981_datetime_python_unix.txt |
Q:
python3 / sqlite3 does not actually insert into DB?
currently, I'm setting an SQLite database, using python.
I seem to lack something fundamental because rows are not actually inserted in the database on the disk.
I'm walking through a digital ocean tutorial from https://www.digitalocean.com/community/tutorials/ho... | python3 / sqlite3 does not actually insert into DB? | currently, I'm setting an SQLite database, using python.
I seem to lack something fundamental because rows are not actually inserted in the database on the disk.
I'm walking through a digital ocean tutorial from https://www.digitalocean.com/community/tutorials/how-to-use-the-sqlite3-module-in-python-3
This is the code ... | [
"you need to commit() see docs\nI slightly modified your code to be more clear\nimport sqlite3\n\nconnection = sqlite3.connect(\"aquarium.db\")\nprint(f\"Number of changes {connection.total_changes}\")\ncursor = connection.cursor()\n\nupdate = False\nif update:\n try:\n cursor.execute(\"CREATE TABLE fish ... | [
2
] | [] | [] | [
"python",
"sqlite"
] | stackoverflow_0074503029_python_sqlite.txt |
Q:
Printing different things on different SSH sessions
I'm making a TUI card game for a school project, where each player would take turns sitting on the machine to play a card, get up, and let the next player play and so on.
The layout I have for the moment is printing the table (on which you can find all of the pre... | Printing different things on different SSH sessions | I'm making a TUI card game for a school project, where each player would take turns sitting on the machine to play a card, get up, and let the next player play and so on.
The layout I have for the moment is printing the table (on which you can find all of the previously put cards), then a line of cards in the hand of t... | [
"You may find it convenient to append (timestamp, cards) tuples\nto files that follow a certain naming scheme:\n\n/tmp/player1.csv\n/tmp/player2.csv\n/tmp/player3.csv\n\nBy convention player1 will only write to that first file,\nplayer2 to the 2nd file and so on.\nNow, to obtain the state of the game at some timest... | [
0
] | [] | [] | [
"python",
"ssh"
] | stackoverflow_0074502233_python_ssh.txt |
Q:
spacy doc.char_span raises error whenever there is any number in string
I was trying to train a model from spacy. I have strings and their token offsets saved into the JSON file.
I have read that file using utf-8 encoding and there is no special character in it. But it raises TypeError: object of type 'NoneType' h... | spacy doc.char_span raises error whenever there is any number in string | I was trying to train a model from spacy. I have strings and their token offsets saved into the JSON file.
I have read that file using utf-8 encoding and there is no special character in it. But it raises TypeError: object of type 'NoneType' has no len()
# code for reading file
with open("data/results.json", "r", encod... | [
"The error TypeError: object of type 'NoneType' has no len() occurs in line doc.ents = ents when one of the entries in ents is None.\nThe reason for having a None in the list is that doc.char_span(start, end, label) returns None when the start and end provided don't align with token boundaries.\nThe tokenizer of th... | [
1
] | [] | [] | [
"json",
"nlp",
"python",
"spacy",
"spacy_3"
] | stackoverflow_0074494620_json_nlp_python_spacy_spacy_3.txt |
Q:
Difficulties with call a method from a subclass in python - AttributeError: 'str' object has no attribute
I want to call a method in a subclass using threading. This method is a while loop that executes a method in the main class.
I don't understand the error, as I interpret it, I am doing something wrong with the... | Difficulties with call a method from a subclass in python - AttributeError: 'str' object has no attribute | I want to call a method in a subclass using threading. This method is a while loop that executes a method in the main class.
I don't understand the error, as I interpret it, I am doing something wrong with the inheritance.
A minimal example of my code:
class Echo(WebSocket):
def __init__(self, client, server, sock... | [
"One problem is that you're referring to Temperature_Controll3.temp_controll directly, which is the wrong way to do it.\nInstead, you need to create an instance of that class:\nt3 = Temperature_Controll3()\n\nAnd then refer to the method of the instance:\ntarget=t3.temp_controll\n\nHowever, there are also other pro... | [
0
] | [] | [] | [
"class",
"inheritance",
"multithreading",
"python"
] | stackoverflow_0074503178_class_inheritance_multithreading_python.txt |
Q:
Filter out thin shapes produced by skimage.measure
I'm trying to detect large blob objects.
I've used skimage.measure to sort out connected components with a connectivity of 1 with counts greater than 9.
from skimage import measure
from skimage import measure
all_labels = measure.label(np.isnan(arr), connectivity... | Filter out thin shapes produced by skimage.measure | I'm trying to detect large blob objects.
I've used skimage.measure to sort out connected components with a connectivity of 1 with counts greater than 9.
from skimage import measure
from skimage import measure
all_labels = measure.label(np.isnan(arr), connectivity=1)
unique, counts = np.unique(all_labels, return_count... | [
"You can use cv functions that return rotated bounding boxes and ellipses: you are basically interested to see if the minimum bounding box around your blobs has an area < threshold. You can get that (possibly rotated) bounding box or ellipse with cv2.minAreaRect(cnt)\nafter you got your contours, or cv2.fitEllipse(... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074503117_python.txt |
Q:
Sorting keys in a map
Program gets an input at the beginning. That inputed string can contain capital letters or any other ascii letters. We don't difference between them, so we just use lower() method. Also any letters other than letters from alphabet (numbers etc.) are used as spaces between strings. Function is... | Sorting keys in a map | Program gets an input at the beginning. That inputed string can contain capital letters or any other ascii letters. We don't difference between them, so we just use lower() method. Also any letters other than letters from alphabet (numbers etc.) are used as spaces between strings. Function is supposed to analyse the in... | [
"The easiest solution would involve regex and Counter, which is a type of dictionary specifically tailored to counting occurrences of values like this:\n>>> import re\n>>> from collections import Counter\n\n>>> words = 'Idk, Idc, Idk, Idf'\n\n>>> re.findall('[a-z]+', words.lower())\n['idk', 'idc', 'idk', 'idf']\n\n... | [
2
] | [] | [] | [
"dictionary",
"list",
"python"
] | stackoverflow_0074503013_dictionary_list_python.txt |
Q:
How to compare dataframes with the same size but different information
I have two data frames where each row is a product and each column is a different month,they always have the same size and are something like this:
data1 = {
"product": ['A', "B", "C", "D"],
"2022-01": [1, 2, 3, 4],
"2022-02": [1, 2... | How to compare dataframes with the same size but different information | I have two data frames where each row is a product and each column is a different month,they always have the same size and are something like this:
data1 = {
"product": ['A', "B", "C", "D"],
"2022-01": [1, 2, 3, 4],
"2022-02": [1, 2, 3, 4],
"2022-03": [1, 2, 3, 4]
}
data2 = {
"product": ['A', "B", ... | [
"You can use pandas.DataFrame.mask to get directly the output you're looking for:\ndf1= pd.DataFrame(data1)\ndf2= pd.DataFrame(data2)\n\nout = df1.mask(df2.replace(\"None\", None).isna())\n#out = df1.mask(df2.eq(\"None\")) --- another alternative\n\n# Output :\nprint(out)\n\n product 2022-01 2022-02 2022-03\n0 ... | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python",
"python_3.x"
] | stackoverflow_0074503228_dataframe_pandas_python_python_3.x.txt |
Q:
How can I split Flask search engine results into different pages?
I've created a search engine using Flask that returns search results from a Wikipedia corpus generated from articles relating to the topic of health. Some queries return hundreds of results, so I would like to add a feature that splits the results u... | How can I split Flask search engine results into different pages? | I've created a search engine using Flask that returns search results from a Wikipedia corpus generated from articles relating to the topic of health. Some queries return hundreds of results, so I would like to add a feature that splits the results up into multiple pages. Below is the index.html code that generates the ... | [
"If you are using the Flask-SQLAlchemy extension, you can use the paginate() method to split the search engine results into different pages.\n"
] | [
0
] | [] | [] | [
"css",
"flask",
"heroku",
"html",
"python"
] | stackoverflow_0074503054_css_flask_heroku_html_python.txt |
Q:
Is there a quick way to turn a pandas DataFrame into a pretty HTML table?
Problem: the output of df.to_html() is a plain html table, which isn't much to look at:
Meanwhile, the visual representation of dataframes in the Jupyter Notebook is much nicer, but if there's an easy way to replicate it, I haven't found it... | Is there a quick way to turn a pandas DataFrame into a pretty HTML table? | Problem: the output of df.to_html() is a plain html table, which isn't much to look at:
Meanwhile, the visual representation of dataframes in the Jupyter Notebook is much nicer, but if there's an easy way to replicate it, I haven't found it.
I know it should be possible to generate a more aesthetically-pleasing table... | [
"Consider my dataframe df\ndf = pd.DataFrame(np.arange(9).reshape(3, 3), list('ABC'), list('XYZ'))\n\ndf\n\n X Y Z\nA 0 1 2\nB 3 4 5\nC 6 7 8\n\nI ripped this style off of my jupyter notebook\nmy_style = \"\"\"background-color: rgba(0, 0, 0, 0);\nborder-bottom-color: rgb(0, 0, 0);\nborder-bottom-style:... | [
13,
8,
2,
2,
0
] | [] | [] | [
"css",
"html",
"jupyter",
"pandas",
"python"
] | stackoverflow_0045422378_css_html_jupyter_pandas_python.txt |
Q:
S3 PreSigned URL is cut when sent in an email
I have a script which generates an S3 PreSigned URL and sends it in an email.
The script works fine, but when the email is sent, it adds a new-line to the URL, which breaks it and makes it unusable in the email.
The only packages installed:
boto3
Jinja2
The script:
i... | S3 PreSigned URL is cut when sent in an email | I have a script which generates an S3 PreSigned URL and sends it in an email.
The script works fine, but when the email is sent, it adds a new-line to the URL, which breaks it and makes it unusable in the email.
The only packages installed:
boto3
Jinja2
The script:
import boto3
from botocore.config import Config
from... | [
"It looks like the problem is related to max line length defined in the \"Internet Message Format\" RFC document 5322\n\n2.1.1. Line Length Limits\nThere are two limits that this standard places on the number of characters in a line. Each line of characters MUST be no more than 998 characters, and SHOULD be no more... | [
0,
0
] | [] | [] | [
"boto3",
"jinja2",
"python",
"python_3.x"
] | stackoverflow_0074389781_boto3_jinja2_python_python_3.x.txt |
Q:
Confusion between commands.Bot and discord.Client | Which one should I use?
Whenever you look at YouTube tutorials or code from this website there is a real variation. Some developers use client = discord.Client(intents=intents) while the others use bot = commands.Bot(command_prefix="something", intents=intents). ... | Confusion between commands.Bot and discord.Client | Which one should I use? | Whenever you look at YouTube tutorials or code from this website there is a real variation. Some developers use client = discord.Client(intents=intents) while the others use bot = commands.Bot(command_prefix="something", intents=intents). Now I know slightly about the difference but I get errors from different places f... | [
"The difference is that commands.Bot provides a lot more functionality (like Commands), which Client doesn't do. Bot is a subclass of Client, so it can do everything that a Client can do, but not the other way around.\nIn the long run you should use the one that you need. If you want to use Bot features then use a ... | [
3
] | [] | [] | [
"discord",
"discord.py",
"python"
] | stackoverflow_0074503328_discord_discord.py_python.txt |
Q:
How to automatically get user in django admin through form
I have a form in my django website where the user requests coins and the information is sent to the admin for me to process. I want to automatically get the user who filled the form without them doing it themselves.
Here's the model.py file:
class Requestp... | How to automatically get user in django admin through form | I have a form in my django website where the user requests coins and the information is sent to the admin for me to process. I want to automatically get the user who filled the form without them doing it themselves.
Here's the model.py file:
class Requestpayment (models.Model):
username= models.ForeignKey(User, on_de... | [
"You need to assign it to the instance wrapped in the form, so:\n@login_required(login_url='login')\ndef redeemcoins(request):\n form = Requestpaymentform()\n if request.method == 'POST':\n form = Requestpaymentform(request.POST)\n if form.is_valid():\n form.instance.username = reques... | [
0,
0
] | [] | [] | [
"django",
"django_forms",
"python"
] | stackoverflow_0074502951_django_django_forms_python.txt |
Q:
Increment Integer Field in Django
I am creating a simple blogging application and would like users to be able to like a post.
In terms of scalability I've decided it would be best to have likes as a separate table made up of pointers to both the user and post.
I have managed to enable the post request adding a lik... | Increment Integer Field in Django | I am creating a simple blogging application and would like users to be able to like a post.
In terms of scalability I've decided it would be best to have likes as a separate table made up of pointers to both the user and post.
I have managed to enable the post request adding a like to the model however the likes field ... | [
"You can use F() only when doing queries.\npost = Post.objects.get(id=post_id)\npost.likes = post.likes + 1\npost.save()\n\nor if you don't mind doing one more query, but also make sure that the post has always the correct number of likes:\npost = Post.objects.get(id=post_id)\npost.likes = Like.objects.filter(post=... | [
0,
0
] | [] | [] | [
"django",
"increment",
"python",
"serialization"
] | stackoverflow_0074500748_django_increment_python_serialization.txt |
Q:
Python: mark method as implementing/overriding
Given a 'contract' of sorts that I want to implement, I want the code to
tell the reader what the intent is
allow the type checker to correct me (fragile base class problem)
E.g. in C++, you can
class X: public Somethingable {
int get_something() const override
... | Python: mark method as implementing/overriding | Given a 'contract' of sorts that I want to implement, I want the code to
tell the reader what the intent is
allow the type checker to correct me (fragile base class problem)
E.g. in C++, you can
class X: public Somethingable {
int get_something() const override
{ return 10; }
};
Now when I rename Somethingable::... | [
"I was overestimating the complexity of such solution, it is shorter:\nimport warnings\n\ndef override(func):\n if hasattr(func, 'fget'): # We see a property, go to actual callable\n func.fget.__overrides__ = True\n else:\n func.__overrides__ = True\n return func\n\n\nclass InterfaceMeta(typ... | [
2,
1
] | [] | [] | [
"abstract_base_class",
"class_design",
"python",
"type_annotation"
] | stackoverflow_0072316756_abstract_base_class_class_design_python_type_annotation.txt |
Q:
Plotting multiple data values inside function call
I want to plot multiple subplots of scatter plots inside a function, after calling the *args parameter to unpack (x,y) input values. However, I keep getting a simple error:
ValueError: s must be a scalar, or float array-like with the same size as x and y
I canno... | Plotting multiple data values inside function call | I want to plot multiple subplots of scatter plots inside a function, after calling the *args parameter to unpack (x,y) input values. However, I keep getting a simple error:
ValueError: s must be a scalar, or float array-like with the same size as x and y
I cannot seem to solve it even after changing the function into... | [
"I have achieved it with the follow, so perhaps there is a cleaner alternative?\ndef test(*args):\n figs, axs = plt.subplots( 1 , 2 , figsize = ( 8 , 8 ) )\n xy = np.array(args)\n for x_y , ax in zip( xy , axs.flat ) :\n (x, y) = np.hsplit(np.ndarray.flatten(x_y), 2)\n ax.scatter(x, y)\n\ntes... | [
0,
0
] | [] | [] | [
"matplotlib",
"plot",
"python"
] | stackoverflow_0074503195_matplotlib_plot_python.txt |
Q:
'list','_AtIndexer' object is not callable PandaPy
mp = pd.read_csv("Stock price over the last 24 months of Adidas, Nike, and Puma.csv",index_col=0)
mr = pd.DataFrame()
# compute monthly returns
for s in mp.columns:
date = mp.index[0]
pr0 = mp[s][date]
for t in range(1,len(mp.index)):
date = m... | 'list','_AtIndexer' object is not callable PandaPy |
mp = pd.read_csv("Stock price over the last 24 months of Adidas, Nike, and Puma.csv",index_col=0)
mr = pd.DataFrame()
# compute monthly returns
for s in mp.columns:
date = mp.index[0]
pr0 = mp[s][date]
for t in range(1,len(mp.index)):
date = mp.index[t]
pr1 = mp[s][date]
ret = (pr1... | [
"you should use .at like this:\nmr.at[date,s]=ret\n\nfull code:\nmp = pd.read_csv(\"Stock price over the last 24 months of Adidas, Nike, and Puma.csv\",index_col=0)\nmr = pd.DataFrame()\n# compute monthly returns\nfor s in mp.columns:\n date = mp.index[0]\n pr0 = mp[s][date] \n for t in range(1,len(mp.inde... | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074503352_dataframe_pandas_python.txt |
Q:
Trying to open a csv file that lives in the same directory as my Python script, but getting error2 file doesn't exist?
I am trying to open a CSV file that I recently saved using Python. Here is global directory:
So the folder is called Parsing Data Using Python, and there are 3 files inside, we only concern ourse... | Trying to open a csv file that lives in the same directory as my Python script, but getting error2 file doesn't exist? | I am trying to open a CSV file that I recently saved using Python. Here is global directory:
So the folder is called Parsing Data Using Python, and there are 3 files inside, we only concern ourselves with the codealong.py file, which is some Python code that I want to run to open the 'patrons.csv' file.
Here is the co... | [
"One approach would be to set the working directory to be the same location as where your script is. To do this for any script, add this to the top:\nimport os \nos.chdir(os.path.dirname(os.path.abspath(__file__)))\n\nThis takes the full name of where your script is located, takes just the path element and sets ... | [
0,
0
] | [] | [] | [
"csv",
"python"
] | stackoverflow_0072159867_csv_python.txt |
Q:
Pyautogui cursor not working after seclect a text box and click at other object
I'm currently having trouble with pyautogui's cursor
When I execute the code, it click the text box and write text there. But after its done writitng and move to another object I aslo want it to click but the cursor didn't change, make... | Pyautogui cursor not working after seclect a text box and click at other object | I'm currently having trouble with pyautogui's cursor
When I execute the code, it click the text box and write text there. But after its done writitng and move to another object I aslo want it to click but the cursor didn't change, make the cursor stay text cursor and it cannot click anything after that despite the curs... | [
"If you are trying to click on Roblox, there are issues with Pyautogui clicking the mouse in Roblox but i've found a workaround for that:\nimport autoit\n if empty != None:\n print(empty)\n pg.moveTo(empty)\n t.sleep(0.001)\n autoit.mouse_click(\"left\") #Instead of using pyautogui to click, we are g... | [
1
] | [] | [] | [
"cursor",
"debugging",
"pyautogui",
"python"
] | stackoverflow_0074501236_cursor_debugging_pyautogui_python.txt |
Q:
Installing my project from testpypi gives me an error
I am learning how to package python projects and publish them and I ran into a problem I have been trying to solve ,but failed.
I have this small project and I am trying to upload it to Testpypi
I managed to upload it there and I can even find it at (https://te... | Installing my project from testpypi gives me an error | I am learning how to package python projects and publish them and I ran into a problem I have been trying to solve ,but failed.
I have this small project and I am trying to upload it to Testpypi
I managed to upload it there and I can even find it at (https://test.pypi.org/project/cli-assistant/)
Problem: When I try to ... | [
"You have uploaded only an .egg file. Pip cannot install eggs. You should upload a source distribution (.tar.gz or .zip) and/or a wheel (.whl).\n"
] | [
0
] | [] | [] | [
"pypi",
"python",
"python_packaging",
"setup.py"
] | stackoverflow_0074502468_pypi_python_python_packaging_setup.py.txt |
Q:
How to find nearest nodes in a driving network considering streets directions
I am trying to compute the distance between 2 points (lat, lon), using osmnx package.
While testing osmnx.nearest_nodes() to firstly find the nearest node from a point, I noticed that it doesn't seem to take into account the street direc... | How to find nearest nodes in a driving network considering streets directions | I am trying to compute the distance between 2 points (lat, lon), using osmnx package.
While testing osmnx.nearest_nodes() to firstly find the nearest node from a point, I noticed that it doesn't seem to take into account the street direction when computing the nearest node (for example when the point is on a one-way st... | [
"A possible workaround could be the following:\n\nfind the nearest edge from the origin point, using ox.nearest_edges() function. You will get the one-way road;\nthe edge is defined by u,v nodes: u is the starting node of the way, v the ending node, following the street direction;\nthe v node is the node you want t... | [
0
] | [] | [] | [
"networkx",
"osmnx",
"python"
] | stackoverflow_0074495397_networkx_osmnx_python.txt |
Q:
MultiValueDictKeyError at /"" when uploading empty file
I have a django 4 application and if a a user try to upload a empty file, then this error occurs:
MultiValueDictKeyError at /controlepunt140
'upload_file'
I searched for that error. But it seems that the template is oke. Because the enctype is set correct: ... | MultiValueDictKeyError at /"" when uploading empty file | I have a django 4 application and if a a user try to upload a empty file, then this error occurs:
MultiValueDictKeyError at /controlepunt140
'upload_file'
I searched for that error. But it seems that the template is oke. Because the enctype is set correct: enctype="multipart/form-data"
<form
class="f... | [
"cf MultiValueDictKeyError in Django\nYou're executing\n uploadfile = UploadFile(\n image=self.request.FILES[\"upload_file\"])\n\nEither use try / except to catch the error,\nor rely on .get(): self.request.FILES.get(\"upload_file\", None)\nYou might want to check for None before c... | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0074503345_django_python.txt |
Q:
Making an if statement in antlr4 not working
I've been trying to create an if statement in my programming language in antlr4
My grammar that is failing is:
if_stmt: IF conditional_block stmt_block (ELSE IF conditional_block stmt_block)* (ELSE conditional_block stmt_block)?;
But it gives the error:
line 3:2 extran... | Making an if statement in antlr4 not working | I've been trying to create an if statement in my programming language in antlr4
My grammar that is failing is:
if_stmt: IF conditional_block stmt_block (ELSE IF conditional_block stmt_block)* (ELSE conditional_block stmt_block)?;
But it gives the error:
line 3:2 extraneous input 'else' expecting {<EOF>, '!', BOOLEAN, ... | [
"This look suspicious:\n(ELSE conditional_block stmt_block)?\n\nwhich should probably be:\n(ELSE stmt_block)?\n\nNot sure if that would solve your problem. If not, you'll need to edit your question and add enough of your grammar so that other are able to reproduce the error you mention.\n"
] | [
0
] | [] | [] | [
"antlr4",
"python"
] | stackoverflow_0074502698_antlr4_python.txt |
Q:
Looking for Simple Python Help: Counting the Number of Vehicles in a CSV by their Fuel Type
MY DATA IN EXCEL
MY CODE
Hello Everyone!
I am brand new to python and have some simple data I want to separate and graph in a bar chart.
I have a data set on the cars currently being driven in California. They are separated... | Looking for Simple Python Help: Counting the Number of Vehicles in a CSV by their Fuel Type | MY DATA IN EXCEL
MY CODE
Hello Everyone!
I am brand new to python and have some simple data I want to separate and graph in a bar chart.
I have a data set on the cars currently being driven in California. They are separated by Year, Fuel type, Zip Code, Make, and 'Light/Heavy'.
I want to tell python to count the number... | [
"You mentioned it's a CSV specifically. Read in the file line by line, split the data by comma (which produces a list for the current row), then if currentrow[3] == fuel type increment your count.\nExample:\ngas_cars=0\nwith open(\"data.csv\", \"r\") as file:\n for line in file:\n row = line.split(\",\")\... | [
1,
1
] | [] | [] | [
"bar_chart",
"dataframe",
"matplotlib",
"python"
] | stackoverflow_0074503284_bar_chart_dataframe_matplotlib_python.txt |
Q:
How to list all folders inside aws s3 bucket via python boto3
I am trying to get only all the folders/directories in an AWS S3 Bucket, not its files.
I have multiple date folders in S3 Bucket like [dt=20190926,dt=20191017,dt=20191128,dt=20200127,dt=20200128,dt=20200629,dt=20201108,dt=20210918,dt=20201121]
But, It ... | How to list all folders inside aws s3 bucket via python boto3 | I am trying to get only all the folders/directories in an AWS S3 Bucket, not its files.
I have multiple date folders in S3 Bucket like [dt=20190926,dt=20191017,dt=20191128,dt=20200127,dt=20200128,dt=20200629,dt=20201108,dt=20210918,dt=20201121]
But, It is reading some random folder dt=20210918
But, what I am getting is... | [
"EDIT: I agree with @lipeiran, there is no such thing as a directory in S3 structure, so there is no way for boto3 to return only \"folders\". You will have to iterate through all objects and extract their path on your own.\nAccording to boto3 documentation, filter() can take some parameters, including\nMaxKeys:\n\... | [
0
] | [] | [] | [
"amazon_s3",
"amazon_web_services",
"aws_lambda",
"boto3",
"python"
] | stackoverflow_0074498408_amazon_s3_amazon_web_services_aws_lambda_boto3_python.txt |
Q:
How to reorder data from a character string with re.sub only in cases where it detects a certain regex pattern,amd not in other cases
import re
#example
input_text = 'Alrededor de las 00:16 am o las 23:30 pm , quizas cerca del 2022_-_02_-_18 llega el avion, pero no a las (2022_-_02_-_18 00:16 am), de esos hay dos... | How to reorder data from a character string with re.sub only in cases where it detects a certain regex pattern,amd not in other cases | import re
#example
input_text = 'Alrededor de las 00:16 am o las 23:30 pm , quizas cerca del 2022_-_02_-_18 llega el avion, pero no a las (2022_-_02_-_18 00:16 am), de esos hay dos (22)'
identify_time_regex = r"(?P<hh>\d{2}):(?P<mm>\d{2})[\s|]*(?P<am_or_pm>(?:am|pm))"
restructuring_structure_00 = r"(\g<hh>----\g<mm... | [
"You can use\nimport re\n\ninput_text = 'Alrededor de las 00:16 am o las 23:30 pm , quizas cerca del 2022_-_02_-_18 llega el avion, pero no a las (2022_-_02_-_18 00:16 am), de esos hay dos (22)'\nidentify_time_regex = r\"(\\b\\d{4}_-_\\d{2}_-_\\d{2}\\s+)?(?P<hh>\\d{2}):(?P<mm>\\d{2})[\\s|]*(?P<am_or_pm>[ap]m)\"\nre... | [
1
] | [] | [] | [
"python",
"python_3.x",
"regex",
"regex_group",
"replace"
] | stackoverflow_0074503120_python_python_3.x_regex_regex_group_replace.txt |
Q:
deepface ResourceExhaustedError: failed to allocate memory [Op:AddV2]
I am new to deeplearning.
I am trying to use the deepface library in my local machine. I used pip install deepface to install the library, tried on python 3.7.13, 3.8.13 and 3.9.13 which were all created using conda virtual environment.
However ... | deepface ResourceExhaustedError: failed to allocate memory [Op:AddV2] | I am new to deeplearning.
I am trying to use the deepface library in my local machine. I used pip install deepface to install the library, tried on python 3.7.13, 3.8.13 and 3.9.13 which were all created using conda virtual environment.
However when running the code snippet below, I am getting the same error when runni... | [
"Why do not you disable GPU?\nimport os\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=\"\"\n\n"
] | [
0
] | [] | [] | [
"deep_learning",
"deepface",
"oom",
"python",
"tensorflow"
] | stackoverflow_0074379226_deep_learning_deepface_oom_python_tensorflow.txt |
Q:
How do I pull a single object from a nested array?
I've got Mongo running in a Docker container.
In Mongo Bash I can pull the entire JSON file with db..find()
But I can't isolate a single object with the code below:
db.FilmList.find({"Films" : {Title : "Clue"}}) or any variation I can think of.
Thanks.
A:
... | How do I pull a single object from a nested array? | I've got Mongo running in a Docker container.
In Mongo Bash I can pull the entire JSON file with db..find()
But I can't isolate a single object with the code below:
db.FilmList.find({"Films" : {Title : "Clue"}}) or any variation I can think of.
Thanks.
| [
"This fixed it:\ndb.FilmList.find({\"Films.Title\" : \"Clue\"}, {\"Films.$\": 1, _id : 0})\n\n"
] | [
0
] | [] | [] | [
"mongodb",
"python"
] | stackoverflow_0074503507_mongodb_python.txt |
Q:
list comprehension always returns empty list
making a function that recieves numbers separated by spaces and adds the first element to the rest, the ouput should be a list of numbers if the first element is a number
i'm trying to remove all non numeric elements of list b
examples- input: 1 2 3 4
output: [3, 4, 5] ... | list comprehension always returns empty list | making a function that recieves numbers separated by spaces and adds the first element to the rest, the ouput should be a list of numbers if the first element is a number
i'm trying to remove all non numeric elements of list b
examples- input: 1 2 3 4
output: [3, 4, 5] (2+1, 3+1, 4+1)
input: 1 2 b 4
output: [3, 5] (2+1... | [
"Two things:\n\nThe results of input are always strings. When you split the string, you end up with more strings. So even if that string is '7', it is the string 7, not the integer 7.\n\nIf you want to check if an object is of a type, use isinstance(x,int) rather than type(x)==int.\n\n\nTo accomplish what it looks ... | [
2,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074503151_python.txt |
Q:
Got error TypeError: 'numpy.ndarray' object is not callable
I try to use panda by using this code
dat = pd.DataFrame()
return_data = dat.values().T
And I got error
TypeError
Traceback (most recent call last)
Input In [27], in <cell line: 1>()
----> 1 return_data = dat.valu... | Got error TypeError: 'numpy.ndarray' object is not callable | I try to use panda by using this code
dat = pd.DataFrame()
return_data = dat.values().T
And I got error
TypeError
Traceback (most recent call last)
Input In [27], in <cell line: 1>()
----> 1 return_data = dat.values().T
TypeError: 'numpy.ndarray' object is not callable... | [
"Replace dat.values().T by dat.values.T. This error happens when you call a numpy array as function.\n"
] | [
2
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074503624_pandas_python.txt |
Q:
Removing every nth element in an array
How do I remove every nth element in an array?
import numpy as np
x = np.array([0,10,27,35,44,32,56,35,87,22,47,17])
n = 3 # remove every 3rd element
...something like the opposite of x[0::n]? I've tried this, but of course it doesn't work:
for i in np.arange(0,len(x),n):
... | Removing every nth element in an array | How do I remove every nth element in an array?
import numpy as np
x = np.array([0,10,27,35,44,32,56,35,87,22,47,17])
n = 3 # remove every 3rd element
...something like the opposite of x[0::n]? I've tried this, but of course it doesn't work:
for i in np.arange(0,len(x),n):
x = np.delete(x,i)
| [
"You're close... Pass the entire arange as subslice to delete instead of attempting to delete each element in turn, eg:\nimport numpy as np\n\nx = np.array([0,10,27,35,44,32,56,35,87,22,47,17])\nx = np.delete(x, np.arange(0, x.size, 3))\n# [10 27 44 32 35 87 47 17]\n\n",
"I just add another way with reshaping if ... | [
20,
5,
0
] | [] | [] | [
"arrays",
"numpy",
"python"
] | stackoverflow_0021922314_arrays_numpy_python.txt |
Q:
Python: pandas dataframe: Remove "  " BOM character
I used Scrapy on a Linux machine to crawl some websites and saved in a CSV. When I retrieve the dataset and view on a Windows machine, I saw these characters . Here is what I do to re-encode them to UTF-8-SIG:
import pandas as pd
my_data = pd.read_csv("./... | Python: pandas dataframe: Remove "  " BOM character | I used Scrapy on a Linux machine to crawl some websites and saved in a CSV. When I retrieve the dataset and view on a Windows machine, I saw these characters . Here is what I do to re-encode them to UTF-8-SIG:
import pandas as pd
my_data = pd.read_csv("./dataset/my_data.csv")
output = "./dataset/my_data_converted.... | [
"Given your comment, I suppose that you ended up having two BOMs.\nLet's look at a small example.\nI'm using built-in open instead of pd.read_csv/pd.to_csv, but the meaning of the encoding parameter is the same.\nLet's create a file saved as UTF-8 with a BOM:\n>>> text = 'foo'\n>>> with open('/tmp/foo', 'w', encodi... | [
6,
0
] | [] | [] | [
"pandas",
"python",
"python_3.x",
"utf_8"
] | stackoverflow_0060064238_pandas_python_python_3.x_utf_8.txt |
Q:
If I install anaconda, do I still have to use vscode?
I'm new in programming, actually I use it for Machine Learning.
I have installed python and anaconda (I don't know if that is right, or I have to install only anaconda?).
And I can see in start menu: (Anaconda powershell, Jupyter, Spyder, Anaconda navigator, An... | If I install anaconda, do I still have to use vscode? | I'm new in programming, actually I use it for Machine Learning.
I have installed python and anaconda (I don't know if that is right, or I have to install only anaconda?).
And I can see in start menu: (Anaconda powershell, Jupyter, Spyder, Anaconda navigator, Anaconda prompt).
So my question is: Do I still have to use v... | [
"Anaconda is a Python distribution, that not only comes with Python itself, but a lot of additional Python packages from the \"scientific stack\", like numpy, pandas, matplotlib, scipy, scikit-learn: exactly what you need for ML. You don't have to install anything else from python.org.\nAnaconda also comes with the... | [
0,
0
] | [] | [] | [
"anaconda",
"dataset",
"machine_learning",
"python"
] | stackoverflow_0074503272_anaconda_dataset_machine_learning_python.txt |
Q:
Combine awaitables like Promise.all
In asynchronous JavaScript, it is easy to run tasks in parallel and wait for all of them to complete using Promise.all:
async function bar(i) {
console.log('started', i);
await delay(1000);
console.log('finished', i);
}
async function foo() {
await Promise.all([bar(1)... | Combine awaitables like Promise.all | In asynchronous JavaScript, it is easy to run tasks in parallel and wait for all of them to complete using Promise.all:
async function bar(i) {
console.log('started', i);
await delay(1000);
console.log('finished', i);
}
async function foo() {
await Promise.all([bar(1), bar(2)]);
}
// This works too:
async f... | [
"The equivalent would be using asyncio.gather:\nimport asyncio\n\nasync def bar(i):\n print('started', i)\n await asyncio.sleep(1)\n print('finished', i)\n\nasync def main():\n await asyncio.gather(*[bar(i) for i in range(10)])\n\nloop = asyncio.get_event_loop()\nloop.run_until_complete(main())\nloop.close()\n\... | [
98,
23,
14,
1
] | [] | [] | [
"async_await",
"future",
"python",
"python_3.x",
"python_asyncio"
] | stackoverflow_0034377319_async_await_future_python_python_3.x_python_asyncio.txt |
Q:
How to parse the regex text between multiline and between two braces?
I am new to python and trying to learn the regex by example.
In this example I am trying the extract the dictionary parts from the multiline text.
How to extract the parts between the two braces in the following example?
MWE: How to get pandas d... | How to parse the regex text between multiline and between two braces? | I am new to python and trying to learn the regex by example.
In this example I am trying the extract the dictionary parts from the multiline text.
How to extract the parts between the two braces in the following example?
MWE: How to get pandas dataframe from this data?
import re
s = """
[
{
speci... | [
"I suggest to add double quotes around the keys, then cast the string to a list of dictionaries and then simply read the structure into pandas dataframe using pd.from_dict:\nimport pandas as pd\nfrom ast import literal_eval\nimport re\n\ns = \"YOU STRING HERE\"\nfixed_s = re.sub(r\"^(\\s*)(\\w+):\", r'\\1\"\\2\":',... | [
2
] | [] | [] | [
"python",
"python_re",
"regex"
] | stackoverflow_0074503346_python_python_re_regex.txt |
Q:
What kind of machine learning solves this?
i have some basic knowledge in AI and machine learning, but a bit confused solving a concrete problem.
i have the following scenario: Given are features and labeled data (0 or 1). I want to predict the probability, new data takes 0 based on the feature values of this new ... | What kind of machine learning solves this? | i have some basic knowledge in AI and machine learning, but a bit confused solving a concrete problem.
i have the following scenario: Given are features and labeled data (0 or 1). I want to predict the probability, new data takes 0 based on the feature values of this new data.
I know this is supervised learning, but wh... | [
"For both quick overview and example implementations, please visit scikit-learn estimators. Your task is more likely of classification, which you can think it as how it's possible to fit (from 0.0 to 1.0) to a specific category.\nThere are vastly available models to use. Most of them work through minimizing (or ite... | [
0,
0
] | [] | [] | [
"artificial_intelligence",
"machine_learning",
"python"
] | stackoverflow_0074500016_artificial_intelligence_machine_learning_python.txt |
Q:
[PYTHON/BINARY FILE]: Sorting the bits read
The file 'binary_file.bin' contains the following binary data (hexadecimal base used for simplicity):
A43CB90F
Each 2 bytes correspond to an unsigned integer of 16 bits: first number is A43C and second number is B90F, which in decimal base correspond respectively to 42... | [PYTHON/BINARY FILE]: Sorting the bits read | The file 'binary_file.bin' contains the following binary data (hexadecimal base used for simplicity):
A43CB90F
Each 2 bytes correspond to an unsigned integer of 16 bits: first number is A43C and second number is B90F, which in decimal base correspond respectively to 42044 and to 47375. I'm trying to read the binary ... | [
"You need to specify the byteorder of the data type.\nFor example:\nimport numpy as np\nbinary_stream = open('/tmp/binary_file.bin', 'rb')\nnumbers_to_read=2\nnumbers = np.fromfile(binary_stream,\n dtype=np.dtype('>H'),\n count=numbers_to_read,\n sep=\"... | [
1
] | [] | [] | [
"binary_data",
"numpy",
"python"
] | stackoverflow_0074501863_binary_data_numpy_python.txt |
Q:
Match in Python a LARGE set of (x, y) points to another set with outliers
I have two large sets of (x, y) points and I want to associate in Python each point of one set with "the corresponding point" of the other.
The second set can also contain outliers, i.e. extra noise points, as you can see in this picture, wh... | Match in Python a LARGE set of (x, y) points to another set with outliers | I have two large sets of (x, y) points and I want to associate in Python each point of one set with "the corresponding point" of the other.
The second set can also contain outliers, i.e. extra noise points, as you can see in this picture, where there are more green dots than red dots:
The association between the two s... | [
"I found a method which can recover which points correspond to which other points fairly accurately, using two phases. The first phase corrects for affine transformation, and the second phase corrects for nonlinear distortion.\nNote: I chose to match red points to green points, rather than the other way around.\nAs... | [
2
] | [] | [] | [
"affinetransform",
"computer_vision",
"opencv",
"performance",
"python"
] | stackoverflow_0074493193_affinetransform_computer_vision_opencv_performance_python.txt |
Q:
Subscription fees to use blpapi package
I am want to connect/know if there are ways to get Bloomberg data to Python. I see we can connect through blpapi/pdblp package.
So wanted to check what is the pricing for this. Appreciate if anyone can help me here?
Getting ways to connect to Python to get Bloomberg data
A:... | Subscription fees to use blpapi package | I am want to connect/know if there are ways to get Bloomberg data to Python. I see we can connect through blpapi/pdblp package.
So wanted to check what is the pricing for this. Appreciate if anyone can help me here?
Getting ways to connect to Python to get Bloomberg data
| [
"Bloomberg has a number of products, which support the real-time API known as the BLP API. This API is a microservice based API. They have microservices for streaming marketdata (//blp/mktdata), requesting static reference (//blp/refdata), contributing OTC pricing (//firm/c-gdco), submitting orders (//blp/emsx), et... | [
1
] | [] | [] | [
"bloomberg",
"blpapi",
"python"
] | stackoverflow_0074284145_bloomberg_blpapi_python.txt |
Q:
How to solve (cid:x) pdfplumber python text extraction
PDF_Doc
I've been working with the pdfplumber library to extract text from pdf documents and it's been fine, however in the documents I'm working on now, I just get spaces and lots of (cid:x) instead of text. Any solution?
Thanks
with pdfplumber.open(fatura) a... | How to solve (cid:x) pdfplumber python text extraction | PDF_Doc
I've been working with the pdfplumber library to extract text from pdf documents and it's been fine, however in the documents I'm working on now, I just get spaces and lots of (cid:x) instead of text. Any solution?
Thanks
with pdfplumber.open(fatura) as pdf:
lista_paginas = pdf.pages
fatura_individual ... | [
"Try PyPDF2 : https://pypdf2.readthedocs.io/en/latest/user/extract-text.html\nfrom PyPDF2 import PdfReader\n\nreader = PdfReader(\"example.pdf\")\nfor page in reader.pages:\n print(page.extract_text())\n\n"
] | [
0
] | [] | [] | [
"pdfplumber",
"pdftotext",
"pypdf2",
"python"
] | stackoverflow_0074416930_pdfplumber_pdftotext_pypdf2_python.txt |
Q:
Switch the values from x-axis to y-axis while using the correct labels(Python Matplotlib.pyplot OR Seaborn)
I have a small table of information that I'm trying to turn into a histogram. It has one column of Department names and a second column of totals. I would like the x-axis to use the Department names and the ... | Switch the values from x-axis to y-axis while using the correct labels(Python Matplotlib.pyplot OR Seaborn) | I have a small table of information that I'm trying to turn into a histogram. It has one column of Department names and a second column of totals. I would like the x-axis to use the Department names and the y-axis to use the numbers from the totals column. When I try to code it, the x-axis is the totals and the y-axis ... | [
"I think main confusion is coming from the name of the plot. It's called bar chart, histogram is something else.\nimport matplotlib.pyplot as plt\n\ndata = {\n 'Admin': 857,\n 'Engineering': 26,\n 'IT': 49,\n 'Marketing': 16,\n 'Operations': 1013,\n 'Sales': 1551\n}\ndepartments = data.keys()\ncou... | [
0
] | [] | [] | [
"axis",
"histogram",
"matplotlib",
"python",
"python_3.x"
] | stackoverflow_0074503294_axis_histogram_matplotlib_python_python_3.x.txt |
Q:
How can I remove a string from a txt file?
I am trying to create a contact info txt file with python
what_you_want = input("Do you want to add or remove (if add write add), (if remove write remove): ")
if what_you_want == "remove":
what_you_want_remove = input("What contact number you want to remove: ")
w... | How can I remove a string from a txt file? | I am trying to create a contact info txt file with python
what_you_want = input("Do you want to add or remove (if add write add), (if remove write remove): ")
if what_you_want == "remove":
what_you_want_remove = input("What contact number you want to remove: ")
with open("All Contact.txt", "r") as f:
c... | [
"You can read the file into a string or list, remove the substring, and write back to the file. For instance,\nwith open(\"file.txt\", \"w\") as f:\n string = f.readlines()\n string = string.replace(substring, \"\")\n f.write(string)\n\nIf substring does not exist in file.txt, the replace function will not... | [
0,
0
] | [] | [] | [
"file",
"python",
"python_3.x",
"text"
] | stackoverflow_0074503739_file_python_python_3.x_text.txt |
Q:
Importing rotated text from a PDF table such as with tabula-py in python
Is there a way to import rotated text from a PDF table such as with tabula-py in python?
I realize I can just rename the column headers in this case, but I was wondering if there is a way to set a parameter for importing rotated text. I don'... | Importing rotated text from a PDF table such as with tabula-py in python | Is there a way to import rotated text from a PDF table such as with tabula-py in python?
I realize I can just rename the column headers in this case, but I was wondering if there is a way to set a parameter for importing rotated text. I don't see any mention of rotation in the readthedocs for tabula-py and haven't fou... | [
"I just tried using camelot and it correctly reads the rotated text in the columns header: this is the result.\n",
"As @Francesco mentioned, there is a particular way in which camelot is a better than tabula-py, since camelot finds the rotated text.\nIt was a difficult process to install camelot, so I thought to ... | [
1,
1
] | [] | [] | [
"pdf",
"python",
"tabula_py"
] | stackoverflow_0074392817_pdf_python_tabula_py.txt |
Q:
List - take elements with equal name
Having a List like this:
[utc1_1.tga, utc1_2.tga, utc1_3.tga, utc1_4.tga,
utc2_1.tga, utc2_2.tga, utc2_3.tga, utc2_4.tga,
utc3_1.tga, utc3_2.tga, utc3_3.tga, utc3_4.tga,..]
I separated with this:
images = list(sorted([int(name.split('_')[0]) for name in directory_files]))
o... | List - take elements with equal name | Having a List like this:
[utc1_1.tga, utc1_2.tga, utc1_3.tga, utc1_4.tga,
utc2_1.tga, utc2_2.tga, utc2_3.tga, utc2_4.tga,
utc3_1.tga, utc3_2.tga, utc3_3.tga, utc3_4.tga,..]
I separated with this:
images = list(sorted([int(name.split('_')[0]) for name in directory_files]))
only timestamp names remain:
[utc1, utc1, u... | [
"Not sure if I got it.\nBut if you want to separate them by timestamp. I would map them into a dict using timestamp as key.\nBasically you would need to grab all different timestamp then start a dict, after that you could separate them by pushing to the respective timestamp key from the dict.\n"
] | [
0
] | [] | [] | [
"combining_marks",
"extract",
"list",
"python"
] | stackoverflow_0074503715_combining_marks_extract_list_python.txt |
Q:
Pygame Buttons, First button working, second button not working
I have recently been working on a game using python and pygame and have started on buttons for various things. An issue that I have been running into is when I create a button class and create two objects of that class for each button, both of them wi... | Pygame Buttons, First button working, second button not working | I have recently been working on a game using python and pygame and have started on buttons for various things. An issue that I have been running into is when I create a button class and create two objects of that class for each button, both of them will turn darker when hovered over by the mouse as expected, but only t... | [
"pygame.event.get() get all the events and remove them from the queue. See the documentation:\n\nThis will get all the messages and remove them from the queue. [...]\n\nIf pygame.event.get() is called multiple times per frame, the events are only retuned once, but never all calls will return all all events. As a re... | [
1
] | [] | [] | [
"button",
"pygame",
"python"
] | stackoverflow_0074503738_button_pygame_python.txt |
Q:
Applying a function for multiple dataframes
I am trying to apply the function on multiple data frames. I created a list for the data frames. If the ranking is less than 100, high performance column would be assigned values copied over from the ranking column and if the ranking is between 100 and 200, the average c... | Applying a function for multiple dataframes | I am trying to apply the function on multiple data frames. I created a list for the data frames. If the ranking is less than 100, high performance column would be assigned values copied over from the ranking column and if the ranking is between 100 and 200, the average column would be assigned the values copied over fr... | [
"You get no error bc your code is syntactically correct. But watch out for the logic. I hope the below code change helps:\ndef func (file):\n if (file['ranking']) < 100:\n (file['ranking']) == (file['High Performance'])\n elif (file['ranking']) > 100 & (file['ranking'] < 200):\n (file['ranking']... | [
1,
0,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0074501622_list_python.txt |
Q:
Python, Twitter Sentiment analysis
i am getting this error upon running my code.
text = str(text.encode("utf-8"))
AttributeError: 'float' object has no attribute 'encode'
I tried to convert my data into string using df['Translated_message']=df['Translated_message'].values.astype('string')
but that doesnt worked.
... | Python, Twitter Sentiment analysis | i am getting this error upon running my code.
text = str(text.encode("utf-8"))
AttributeError: 'float' object has no attribute 'encode'
I tried to convert my data into string using df['Translated_message']=df['Translated_message'].values.astype('string')
but that doesnt worked.
| [
"Text is a float. Check to cast as str before encoding.\n"
] | [
0
] | [] | [] | [
"nltk",
"numpy",
"pandas",
"python"
] | stackoverflow_0074503855_nltk_numpy_pandas_python.txt |
Q:
3D Phase portrait of Rössler System using Python
I'm running into a specific problem when attempting to plot the 3D phase portrait of the Rössler system in Python. The problem is that certain arrows are excessively long, and thus the visualization isn't a good one at all:
Bad 3d phase portrait
This is my code so f... | 3D Phase portrait of Rössler System using Python | I'm running into a specific problem when attempting to plot the 3D phase portrait of the Rössler system in Python. The problem is that certain arrows are excessively long, and thus the visualization isn't a good one at all:
Bad 3d phase portrait
This is my code so far, and I don't really know what to alter to make an a... | [
"I believe that you won't be able to accurately visualize this vector field with quivers, because there is quite a big variation in magnitude in your view area. A better way is to visualize streamlines, and that's not easy either:\n\nmatplotlib doesn't support 3D streamlines.\nPlotly support streamtubes, but when I... | [
0
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0074503174_matplotlib_python.txt |
Q:
I need a way to compare two strings in python without using sets in a pandas dataframe
I am currently working on a huge csv file with pandas, and I need to find and print similarity between the selected row and every other row. For example if the string is "Card" and the second string is "Credit Card Debit Card" i... | I need a way to compare two strings in python without using sets in a pandas dataframe | I am currently working on a huge csv file with pandas, and I need to find and print similarity between the selected row and every other row. For example if the string is "Card" and the second string is "Credit Card Debit Card" it should return 2 or if the first string is "Credit Card" and the second string is "Credit C... | [
"You can use numpy.intersect1d to get the common words but the % is different for the third row.\nimport numpy as np\n\ndf[\"Similarity_%\"] = (\n df.apply(lambda x: \"%\" + str(round(len(np.intersect1d(x['Col1'].split(), x['Col2'].split()))\n ... | [
0,
0,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074500458_pandas_python.txt |
Q:
Sorting a list of dictionaries based on one couple key-value
One of the dictionary in the list is:
[{' School': 'GP',
'Age': '18',
'StudyTime': '2',
'Failures': '0',
'Health': '3',
'Absences': '6',
'G1': '5',
'G2': '6',
'G3': '6'}
………………….]
I want to sort them by Age so the output should be like... | Sorting a list of dictionaries based on one couple key-value | One of the dictionary in the list is:
[{' School': 'GP',
'Age': '18',
'StudyTime': '2',
'Failures': '0',
'Health': '3',
'Absences': '6',
'G1': '5',
'G2': '6',
'G3': '6'}
………………….]
I want to sort them by Age so the output should be like:
Range for age is 15 to 22
{ 15 : [
{'School': 'GP',
... | [
"Based on the expected input and output, it appears that there are three tasks involved:\n\nDigit strings should be converted to integers when possible (e.g., \"15\" should become 15).\nDictionary entries should be collated based on the \"Age\" key.\nIn the sorted result, each entry should no longer have the \"Age\... | [
0
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0074486182_dictionary_python.txt |
Q:
How to stop a loop triggered by tkinter in Python
I'm new to Python and even more so to tkinter, and I decided to try to create a start and stop button for an infinite loop through Tkinter. Unfortunately, once I click start, it won't allow me to click stop. The start button remains indented, and I assume this is b... | How to stop a loop triggered by tkinter in Python | I'm new to Python and even more so to tkinter, and I decided to try to create a start and stop button for an infinite loop through Tkinter. Unfortunately, once I click start, it won't allow me to click stop. The start button remains indented, and I assume this is because the function it triggered is still running. How ... | [
"You're calling while True. Long story short, Tk() has it's own event loop. So, whenever you call some long running process it blocks this event loop and you can't do anything. You should probably use after\nI avoided using global here by just giving an attribute to window.\ne.g. -\nimport tkinter\n\ndef stop():\n\... | [
2,
0
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0036847769_python_tkinter.txt |
Q:
I want to pass side input AsDIct but getting error "ValueError: dictionary update sequence element #0 has length 101; 2 is required"
class load_side_input(beam.DoFn):
def process(self,pubsub_message):
message = pubsub_message.decode("utf8")
output:typing.Dict={}
for key in mess... | I want to pass side input AsDIct but getting error "ValueError: dictionary update sequence element #0 has length 101; 2 is required" | class load_side_input(beam.DoFn):
def process(self,pubsub_message):
message = pubsub_message.decode("utf8")
output:typing.Dict={}
for key in message.keys():
output[key] = self.tag_model[key]
return [output]
side_input = (p
| "AMM Events" >> beam.io... | [
"You feed the function beam.pvalue.AsDict the incorrect input format. According to the documentation:\n\nParameters: pcoll – Input pcollection. All elements should be key-value pairs (i.e. 2-tuples) with unique keys.\n\nHere is a minimum working example, which can be run at Apache Play\nimport apache_beam as beam... | [
2
] | [] | [] | [
"apache_beam",
"python"
] | stackoverflow_0074497838_apache_beam_python.txt |
Q:
Python how to convert monthly employment data into annual, csv, panda
I've been stuck on this problem for two days. Below is the csv file.
df = pd.read_csv('/14100017.csv')
df = pd.DataFrame(data)
df.head()
df_year = df.groupby('REF_DATE')['REF_DATE'].count()
print(df_year)
This is my code. Could you please tell... | Python how to convert monthly employment data into annual, csv, panda | I've been stuck on this problem for two days. Below is the csv file.
df = pd.read_csv('/14100017.csv')
df = pd.DataFrame(data)
df.head()
df_year = df.groupby('REF_DATE')['REF_DATE'].count()
print(df_year)
This is my code. Could you please tell me or give me a hint or show me the website has similar questions. How to ... | [
"Just convert REF_DATE to datetime and then extract year:\ndf['date'] = pd.to_datetime(df['REF_DATE'])\ndf['year'] = pd.DatetimeIndex(df['date']).year\n\nAfter, you need to aggregate the value by year:\nmonthly_year_avg = df.groupby('year')['VALUE'].mean()\n\n"
] | [
2
] | [] | [] | [
"dataframe",
"pandas",
"python",
"rsample"
] | stackoverflow_0074503891_dataframe_pandas_python_rsample.txt |
Q:
Avoid reCAPTCHA using Selenium
I tried to use Selenium (chromedriver) for webscraping, but always get reCaptchas (around 5-8 in a row) which I have to solve.
When I visit the same website manually with Google Chrome, I don't even get one Captcha.
I don't use headless option...
Is there any solution to avoid these ... | Avoid reCAPTCHA using Selenium | I tried to use Selenium (chromedriver) for webscraping, but always get reCaptchas (around 5-8 in a row) which I have to solve.
When I visit the same website manually with Google Chrome, I don't even get one Captcha.
I don't use headless option...
Is there any solution to avoid these Captchas? Or to get maximum 1-2 Capt... | [
"There are captcha solvers like 2captcha that solve them at around 15-40 seconds each captcha. Captcha was made to detect bots in various shapes and forms and well... that's what it has done. The simple answer is: no, there is no \"bypass\"\nThere are some workarounds to avoid the system as a whole such as using an... | [
1,
0
] | [] | [] | [
"python",
"recaptcha",
"selenium",
"selenium_chromedriver",
"web_scraping"
] | stackoverflow_0066755142_python_recaptcha_selenium_selenium_chromedriver_web_scraping.txt |
Q:
(Guizero) Writing code that so that when the user clicks on the button a new window will open containg detail from a listbox (not using tkinter)
I am having trouble where I am writing code where I take a csv file and populate it on a listbox, Then I am using another csv file to relate to the item on the first csv.... | (Guizero) Writing code that so that when the user clicks on the button a new window will open containg detail from a listbox (not using tkinter) | I am having trouble where I am writing code where I take a csv file and populate it on a listbox, Then I am using another csv file to relate to the item on the first csv. When the user selects a car and pushes the button called "Get Info" under the listbox, a new window will open. That new window will contain detail on... | [
"You are using the wrong window name\n txt2 = Text(window, text=output2)\n\n\nshould be :\ntxt2 = Text(newwindow, text=output2)\n\nFor the error window repetition remove the for in this place, you already have the right one later\n with open('Cars database.csv') as fh:\n for items in f... | [
0
] | [] | [] | [
"guizero",
"python"
] | stackoverflow_0074503523_guizero_python.txt |
Q:
How to upload file using many to many field in django rest framework
I have two models. One is article and other is documents model. Document model contains the filefield for uploading document along with some other metadata of uploaded document. Article has a m2m field that relates to Document Model. Article mode... | How to upload file using many to many field in django rest framework | I have two models. One is article and other is documents model. Document model contains the filefield for uploading document along with some other metadata of uploaded document. Article has a m2m field that relates to Document Model. Article model has a field user according to which article is being which article is be... | [
"You cannot add files to M2M fields, because M2M fields hold objects of other models.\nIf you have a M2M of DocumentModel, it will only accept the objects of DocumentModel. It only expects the primary keys of DocumentModel objects.\nTo upload files, you can use a FileField instead.\n"
] | [
0
] | [] | [] | [
"django",
"django_models",
"django_rest_framework",
"django_serializer",
"python"
] | stackoverflow_0074429890_django_django_models_django_rest_framework_django_serializer_python.txt |
Q:
New variable in plt.streamplot() broken_streamlines does not work, how to fix this?
I need my streamlines on the plot in Python to be continuous. I am using plt.streamplot() which by default plots broken lines. I have found that in the source code someone has already made up a variable which is called broken_strea... | New variable in plt.streamplot() broken_streamlines does not work, how to fix this? | I need my streamlines on the plot in Python to be continuous. I am using plt.streamplot() which by default plots broken lines. I have found that in the source code someone has already made up a variable which is called broken_streamlines and it can be True or False, by default it is True broken_streamlines.
In document... | [
"Upgrade your version of the matplotlib package by running pip install matplotlib --upgrade\nThe broken_streamlines parameter was introduced in Matplotlib 3.6.0 - see the relevant changelog entry below:\nhttps://matplotlib.org/stable/users/prev_whats_new/whats_new_3.6.0.html#streamplot-can-disable-streamline-breaks... | [
0
] | [] | [] | [
"github",
"matplotlib",
"plot",
"python",
"variables"
] | stackoverflow_0073119873_github_matplotlib_plot_python_variables.txt |
Q:
How to calculate average of monthly sales data from python pandas dataframe
I have below pandas dataframe which has employees sales data for october month.
Employee Timerange Dials Conn Conv Mtg Bkd Talk Dial
0 Ricky Ponting 10/3 - 10/7 1,869 102 ... | How to calculate average of monthly sales data from python pandas dataframe | I have below pandas dataframe which has employees sales data for october month.
Employee Timerange Dials Conn Conv Mtg Bkd Talk Dial
0 Ricky Ponting 10/3 - 10/7 1,869 102 60.0 2.0 3h:08m 5h:23m
1 Adam Gilchrist 10/... | [
"I will assume that your Timerange always starts with the month you are interested in, and that all data comes from the same year (this year). If these are reasonable assumptions, this works:\nemps = [\n \"Ricky Ponting\", \"Adam Gilchrist\", \"Michael Clarke\", \"Shane Warne\"\n]\n\ntimeranges = [\n \"10/3 -... | [
1,
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074503501_pandas_python.txt |
Q:
Streamlit: Using Multiple Conditions and Colors for Bars in a Bar Chart
I'm using Streamlit to create a dashboard. I have a bar graph using altair and in their docs, they show how to color a bar if it meets a condition. I don't see anything on how to color multiple bars and with multiple, different conditions.
I a... | Streamlit: Using Multiple Conditions and Colors for Bars in a Bar Chart | I'm using Streamlit to create a dashboard. I have a bar graph using altair and in their docs, they show how to color a bar if it meets a condition. I don't see anything on how to color multiple bars and with multiple, different conditions.
I aiming to use three different colors based on three different conditions but I... | [
"Rather than\n alt.datum.Team == ['Arsenal', 'Manchester City'],\n\nI think you want\n alt.datum.Team in ['Arsenal', 'Manchester City'],\n\n"
] | [
0
] | [] | [] | [
"altair",
"python",
"streamlit"
] | stackoverflow_0074503952_altair_python_streamlit.txt |
Q:
Finding the number of combinations possible, given 4 dictionaries
Given the following dictionaries:
dict_first_attempt = {'Offense': ['Jack','Jill','Tim'],
'Defense':['Robert','Kevin','Sam']}
dict_second_attempt = {'Offense': ['Jack','McKayla','Heather'],
'Defense':['Chris','Tim','Julia']}
From this dictionaries... | Finding the number of combinations possible, given 4 dictionaries | Given the following dictionaries:
dict_first_attempt = {'Offense': ['Jack','Jill','Tim'],
'Defense':['Robert','Kevin','Sam']}
dict_second_attempt = {'Offense': ['Jack','McKayla','Heather'],
'Defense':['Chris','Tim','Julia']}
From this dictionaries, my focus is just the offense, so if I just wanted the list of those, ... | [
"import itertools\nlist(itertools.product(first, second))\n\n"
] | [
1
] | [] | [] | [
"dictionary",
"list",
"python"
] | stackoverflow_0074504019_dictionary_list_python.txt |
Q:
Python - HTML Parser - Narrow Down Scrape
I am new to HTML Parser. I have written a Spider in Python which aims to crawl a website. I have included my code below. This code specifically looks for all URLs which are identified with an "a" start tag and a href attribute. However, I would like to further filter this ... | Python - HTML Parser - Narrow Down Scrape | I am new to HTML Parser. I have written a Spider in Python which aims to crawl a website. I have included my code below. This code specifically looks for all URLs which are identified with an "a" start tag and a href attribute. However, I would like to further filter this by only scraping URLs which contain a specific ... | [
"You may have an easier time using BeautifulSoup than the lower level HTMLParser.\nTo add the additional filter to your current implementation, you could add an additional parameter to your LinkFinder class, store the value, and use it in the conditional:\nclass LinkFinder(HTMLParser):\n def __init__(self, base_... | [
0
] | [] | [] | [
"html_parser",
"python",
"web_crawler"
] | stackoverflow_0074503859_html_parser_python_web_crawler.txt |
Q:
how do i use a random function in this
I wrote this code to split a big number into smaller parts in a certain range. Now i am trying to randomize it but I'm not sure what module to use in random function and I'm stuck. Pardon my English
import random
op = ''
start = 664613997892457936451903530140172288
step = 922... | how do i use a random function in this | I wrote this code to split a big number into smaller parts in a certain range. Now i am trying to randomize it but I'm not sure what module to use in random function and I'm stuck. Pardon my English
import random
op = ''
start = 664613997892457936451903530140172288
step = 9223372036854775808
stop = 13292279957849158729... | [
"Convert your hexadecimal start and stop to decimal then use random.randint(start,stop) to generate a random number. Convert it back to hexadecimal afterwards.\nConvert hex string to integer in Python\n"
] | [
0
] | [] | [] | [
"python",
"python_3.x",
"random"
] | stackoverflow_0074503964_python_python_3.x_random.txt |
Q:
What exactly does += do?
I need to know what += does in Python. It's that simple. I also would appreciate links to definitions of other shorthand tools in Python.
A:
In Python, += is sugar coating for the __iadd__ special method, or __add__ or __radd__ if __iadd__ isn't present. The __iadd__ method of a class c... | What exactly does += do? | I need to know what += does in Python. It's that simple. I also would appreciate links to definitions of other shorthand tools in Python.
| [
"In Python, += is sugar coating for the __iadd__ special method, or __add__ or __radd__ if __iadd__ isn't present. The __iadd__ method of a class can do anything it wants. The list object implements it and uses it to iterate over an iterable object appending each element to itself in the same way that the list's ... | [
186,
166,
66,
32,
29,
14,
10,
7,
3,
2,
1,
1,
0,
0,
0,
0,
0
] | [] | [] | [
"compound_assignment",
"operators",
"python"
] | stackoverflow_0004841436_compound_assignment_operators_python.txt |
Q:
YTMUSIC ERROR: 'YTMusic' object has no attribute 'parser'
I've a problem with ytmusicapi. I used it for some tests and was all ok, but now when I search for a song I get this error: 'YTMusic' object has no attribute 'parser'.
Here is a test:
from ytmusicapi import YTMusic
ytmusic = YTMusic()
ric = ytmusic.search... | YTMUSIC ERROR: 'YTMusic' object has no attribute 'parser' | I've a problem with ytmusicapi. I used it for some tests and was all ok, but now when I search for a song I get this error: 'YTMusic' object has no attribute 'parser'.
Here is a test:
from ytmusicapi import YTMusic
ytmusic = YTMusic()
ric = ytmusic.search("fix you coldplay")
print(ric)
I tried to analyze the scrip... | [
"You are probably using an older version of ytmusicapi. Just update it with pip install -U ytmusicapi and it will work. I tested it on my machine and it works\n"
] | [
0
] | [] | [] | [
"attributeerror",
"python",
"python_3.x"
] | stackoverflow_0074504038_attributeerror_python_python_3.x.txt |
Q:
Reading csv with scrapy
Trying to read the csv file but I am getting error that TypeError: Request url must be str, got list how to solve that kindly how to read list any suggestion recommend me
import scrapy
from scrapy.http import Request
import pandas as pd
from scrapy_selenium import SeleniumRequest
from io im... | Reading csv with scrapy | Trying to read the csv file but I am getting error that TypeError: Request url must be str, got list how to solve that kindly how to read list any suggestion recommend me
import scrapy
from scrapy.http import Request
import pandas as pd
from scrapy_selenium import SeleniumRequest
from io import open
class SampleSpid... | [
"You need to iterate through the list and pass each url as a request.\n def start_requests(self):\n for url in self.start_urls:\n yield Request(url,callback=self.parse)\n\n\n"
] | [
1
] | [] | [] | [
"python",
"scrapy",
"web_scraping"
] | stackoverflow_0074503930_python_scrapy_web_scraping.txt |
Q:
pip not installing modules
As per object. I'm running Python 2.7.10 under Windows 7 64 bit. I added C:\Python27\Scripts to my PATH, and I can run pip, but it's not able to install modules. For example
pip install numpy
gives
Collecting numpy
Retrying (Retry(total=4, connect=None, read=None, redirect=None)) after
... | pip not installing modules | As per object. I'm running Python 2.7.10 under Windows 7 64 bit. I added C:\Python27\Scripts to my PATH, and I can run pip, but it's not able to install modules. For example
pip install numpy
gives
Collecting numpy
Retrying (Retry(total=4, connect=None, read=None, redirect=None)) after
connection broken by 'ProtocolEr... | [
"A proxy shall be used. For example:\npython.exe -m pip install numpy --proxy=\"proxy.com:8080\"\n\nwhere \"proxy.com:8080\" is the proxy server address and port. This can be found in OS settings.\nHow to get them:\n\nWindows: What Is a Proxy or Proxy Server\nLinux How can I find out the proxy address I am behind?\... | [
19,
2,
1,
0,
0
] | [] | [] | [
"numpy",
"pip",
"python"
] | stackoverflow_0033996026_numpy_pip_python.txt |
Q:
How to append item from list in front of specific list in list of lists?
I am trying to get the subset of list_a with the highest summation of both lists b and c that are below or equal to the threshold. (List b and list c corresponds to list a)
For example
list_a = [1, 2, 3, 4, 5]
list_b = [3,4,7,8,2]
list_c = [4... | How to append item from list in front of specific list in list of lists? | I am trying to get the subset of list_a with the highest summation of both lists b and c that are below or equal to the threshold. (List b and list c corresponds to list a)
For example
list_a = [1, 2, 3, 4, 5]
list_b = [3,4,7,8,2]
list_c = [4,6,1,5,8]
Threshold = 12
In descending order, I want to obtain a list with all... | [
"Here's my (perhaps not totally complete, because your goal is not perfectly clear to me) method:\nlist_a = [1, 2, 3, 4, 5]\nlist_b = [3,4,7,8,2]\nlist_c = [4,6,1,5,8]\nThreshold = 12\n\nl = len(list_a)\n\ndef total(n):\n # convert n to binary form with l digits\n mask = bin(n)[2:].zfill(l)\n # calculates ... | [
0
] | [] | [] | [
"python",
"subset"
] | stackoverflow_0074502849_python_subset.txt |
Q:
Pydantic - Upgrading object to another model
I have a NewUser model that is something that the end user inputs, I want to update the object to a UserInDB so that I can pass it to my db engine (DynamoDB, which expects a dict)
At the moment I'm calling .dict twice, which doesn't feel like the correct way to do it
... | Pydantic - Upgrading object to another model | I have a NewUser model that is something that the end user inputs, I want to update the object to a UserInDB so that I can pass it to my db engine (DynamoDB, which expects a dict)
At the moment I'm calling .dict twice, which doesn't feel like the correct way to do it
from pydantic import BaseModel, Field
from d... | [
"You could try to define an __init__ and the code would look nicer (to me at least).\nfrom pydantic import BaseModel, Field\nfrom datetime import datetime\nfrom typing import Optional\nfrom uuid import uuid4\n\nclass NewUser(BaseModel):\n name: str\n email: str\n company_name: Optional[str]\n\nclass UserIn... | [
1
] | [] | [] | [
"fastapi",
"pydantic",
"python"
] | stackoverflow_0064446491_fastapi_pydantic_python.txt |
Q:
How to lookup different dataframes and return the values?
Im trying to lookup the index in two different datframes and return the values.
For example, in df1 i would like to lookup in df2 and return the same index and values.
DF1
DF2
I would like my result to be like this.
RESULTS
A:
Get the IDs from df2 wher... | How to lookup different dataframes and return the values? | Im trying to lookup the index in two different datframes and return the values.
For example, in df1 i would like to lookup in df2 and return the same index and values.
DF1
DF2
I would like my result to be like this.
RESULTS
| [
"Get the IDs from df2 where the ID is in df1\nfiltered_df = df2[(df2['ID'].isin(df1['ID']))]\n\n",
"Try this\nnew_df = df2[df2.ID == [list(df1.ID)]]\n\n"
] | [
1,
1
] | [] | [] | [
"anaconda",
"dataframe",
"list",
"python"
] | stackoverflow_0074504099_anaconda_dataframe_list_python.txt |
Q:
KeyError on adjacency list
Getting a KeyError and can't figure out why.
I'm importing data from an excel sheet using pandas and using it to create a graph using an adjacency list. The data imports fine, but when using the add_edge function I created I keep getting a KeyError.
Link to a sample of the dataset: https... | KeyError on adjacency list | Getting a KeyError and can't figure out why.
I'm importing data from an excel sheet using pandas and using it to create a graph using an adjacency list. The data imports fine, but when using the add_edge function I created I keep getting a KeyError.
Link to a sample of the dataset: https://www.dropbox.com/s/80v3dhdf0c0... | [
"The last station in a line (Like Elephant & Castle) is not on Station A column that you use to create your dictionary, and it should be in your dictionary (nodes). That is why you get the error.\nyou could change to this:\nfor index, row, in df.iterrows():\n station_a = row['Station A']\n station_b = row['St... | [
0
] | [] | [] | [
"excel",
"keyerror",
"pandas",
"python"
] | stackoverflow_0074503911_excel_keyerror_pandas_python.txt |
Q:
mypy does not use narrowed types inside function definitions
I have a problem with mypy. mypy does not use narrowed types inside function definitions.
I have the following code:
from typing import Callable
def foo(a: str | int) -> list[str]:
x: list[str] = ["abc", "def"]
if isinstance(a, int):
x.i... | mypy does not use narrowed types inside function definitions | I have a problem with mypy. mypy does not use narrowed types inside function definitions.
I have the following code:
from typing import Callable
def foo(a: str | int) -> list[str]:
x: list[str] = ["abc", "def"]
if isinstance(a, int):
x.insert(a, "ghi")
elif isinstance(a, str):
x.insert(0, ... | [
"I suspect this is because nested function definitions make name resolution and type narrowing pretty complex. You can fix it by just re-assigning a to a well-typed variable and then close over that with modify in each branch:\nfrom typing import Callable\n\ndef bar(a: str | int) -> Callable[[list[str]], list[str]]... | [
2
] | [] | [] | [
"mypy",
"python",
"type_hinting"
] | stackoverflow_0074504085_mypy_python_type_hinting.txt |
Q:
How to code for the value of "month" which produced the highest profit in a year?
Out of all the months in the year, I need to code the month with largest total balance (it's June as all together June has the biggest "amount" value)
lst = [
{'account': 'x\\*', 'amount': 300, 'day': 3, 'month': 'June'},
{'a... | How to code for the value of "month" which produced the highest profit in a year? | Out of all the months in the year, I need to code the month with largest total balance (it's June as all together June has the biggest "amount" value)
lst = [
{'account': 'x\\*', 'amount': 300, 'day': 3, 'month': 'June'},
{'account': 'y\\*', 'amount': 550, 'day': 9, 'month': 'May'},
{'account': 'z\\*', 'amo... | [
"A simple solution with pandas.\nimport pandas as pd\n\nlst = [\n {'account': 'x\\\\*', 'amount': 300, 'day': 3, 'month': 'June'},\n {'account': 'y\\\\*', 'amount': 550, 'day': 9, 'month': 'May'},\n {'account': 'z\\\\*', 'amount': -200, 'day': 21, 'month': 'June'},\n {'account': 'g', 'amount': 80, 'day'... | [
1,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0074503697_list_python.txt |
Q:
Getting rid of unwanted panel plot in subplots in a loop
I have a daily data named and share here as data_link. I've done all the necessary operation on it and I want to bar chart from the need eleven (11) column separately using panel plot (3x4). My code worked correctly until I plot my desired results in subplot... | Getting rid of unwanted panel plot in subplots in a loop | I have a daily data named and share here as data_link. I've done all the necessary operation on it and I want to bar chart from the need eleven (11) column separately using panel plot (3x4). My code worked correctly until I plot my desired results in subplots. Since am plotting results from eleven columns in 3x4 panel ... | [
"You can use matplotlib.axes.Axes.set_axis_off:\nfor i in range (3):\n for j in range (4):\n try:\n event_occurrence = fname[[fname_col[m],'month']][fname[fname_col[m]]>0]\n num_event = event_occurrence.groupby('month').count().reindex(month_name)\n num_event = num_event.f... | [
0
] | [] | [] | [
"loops",
"math",
"matplotlib",
"pandas",
"python"
] | stackoverflow_0074504144_loops_math_matplotlib_pandas_python.txt |
Q:
Celery auto reload on ANY changes
I could make celery reload itself automatically when there is changes on modules in CELERY_IMPORTS in settings.py.
I tried to give mother modules to detect changes even on child modules but it did not detect changes in child modules. That make me understand that detecting is not d... | Celery auto reload on ANY changes | I could make celery reload itself automatically when there is changes on modules in CELERY_IMPORTS in settings.py.
I tried to give mother modules to detect changes even on child modules but it did not detect changes in child modules. That make me understand that detecting is not done recursively by celery. I searched i... | [
"Celery --autoreload doesn't work and it is deprecated.\nSince you are using django, you can write a management command for that. \nDjango has autoreload utility which is used by runserver to restart WSGI server when code changes.\nThe same functionality can be used to reload celery workers. Create a seperate manag... | [
31,
19,
19,
3,
2,
0,
0
] | [] | [] | [
"celery",
"django_celery",
"python"
] | stackoverflow_0021666229_celery_django_celery_python.txt |
Q:
Got warning: warnings.warn(msg, UserWarning)
I try to use cvxpy by using this code
`# Number of variables
n = len(symbols)
The variables vector
x = Variable(n)
The minimum return
req_return = 0.02
The return
ret = r.T*x
The risk in xT.Q.x format
risk = quad_form(x, C)
The core problem definition with the Problem c... | Got warning: warnings.warn(msg, UserWarning) | I try to use cvxpy by using this code
`# Number of variables
n = len(symbols)
The variables vector
x = Variable(n)
The minimum return
req_return = 0.02
The return
ret = r.T*x
The risk in xT.Q.x format
risk = quad_form(x, C)
The core problem definition with the Problem class from CVXPY
prob = Problem(Minimize(risk), [su... | [
"It's Warning mean your code run properly so Let's see the warning\n\nThe Warning tell us that\nUsing ``*`` for matrix multiplication has been deprecated since CVXPY 1.1.\n\nso you already use CVXPY version upper 1.1\nHow to solve:\n Use ``*`` for matrix-scalar and vector-scalar multiplication.\nUse ``@`` for ma... | [
0
] | [] | [] | [
"cvxpy",
"python"
] | stackoverflow_0074503922_cvxpy_python.txt |
Q:
how to upper case every other word in string in python
I am wondering how to uppercase every other word in a string. For example, i want to change "Here is my dog" to "Here IS my DOG"
Can anyone help me get it started? All i can find is how to capitalize the first letter in each word.
A:
' '.join( w.upper() if ... | how to upper case every other word in string in python | I am wondering how to uppercase every other word in a string. For example, i want to change "Here is my dog" to "Here IS my DOG"
Can anyone help me get it started? All i can find is how to capitalize the first letter in each word.
| [
"' '.join( w.upper() if i%2 else w\n for (i, w) in enumerate(sentence.split(' ')) )\n\n",
"I think the method you are looking for is upper().\nYou can use split() to split your string into words and the call upper() on every other word and then join the strings back together, using join()\n",
"words = ... | [
7,
2,
1,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0008452616_python.txt |
Q:
How do I create an object with subvalues without creating a class?
I want to create an object, A, with x and y values without creating a class.
#<Code I am looking for goes here.>
print(A.x, A.y)
Is there an easy way to do this that I am missing, or is it too hacky?
A:
Another way to accomplish this would be:
... | How do I create an object with subvalues without creating a class? | I want to create an object, A, with x and y values without creating a class.
#<Code I am looking for goes here.>
print(A.x, A.y)
Is there an easy way to do this that I am missing, or is it too hacky?
| [
"Another way to accomplish this would be:\nimport types\n\nA = types.SimpleNamespace(x=5, y=2)\nprint(A.x, A.y)\n\n",
"I found an answer to this question:\nA = type('any name', (), {'x': 15, 'y': 23})\n\nprint(A.x, A.y)\n\nRead more about it here.\n"
] | [
1,
0
] | [] | [] | [
"class",
"oop",
"python"
] | stackoverflow_0074504174_class_oop_python.txt |
Q:
How to Scroll the Left Quadrant
How can I make Selenium run scroll only in the left quadrant?
when I use the command below it is executed in the zoom of the map and that is not my intention, because I want to scrape the links of the companies that are in the left column
driver.execute_script("window.scrollBy(0, 20... | How to Scroll the Left Quadrant | How can I make Selenium run scroll only in the left quadrant?
when I use the command below it is executed in the zoom of the map and that is not my intention, because I want to scrape the links of the companies that are in the left column
driver.execute_script("window.scrollBy(0, 200)")
| [
"You need to find the scrollable div element and then you can apply JavaScript as following:\nelement = wait.until(EC.presence_of_element_located((By.XPATH, \"//div[@role='main']//div[contains(@aria-label,'lanchonet')]\")))\ndriver.execute_script(\"arguments[0].scroll(0, arguments[0].scrollHeight);\", element)\n\nT... | [
1
] | [] | [] | [
"python",
"scroll",
"selenium",
"selenium_webdriver"
] | stackoverflow_0074504065_python_scroll_selenium_selenium_webdriver.txt |
Q:
Nested loop code to create right triangle in Python
Professor gave us a simple code that executes a square and we need to add/change the code to output the right triangle shape as shown below. It's just a simple loop within a loop code, but I can't find tips or help anywhere for creating shapes with Python without... | Nested loop code to create right triangle in Python | Professor gave us a simple code that executes a square and we need to add/change the code to output the right triangle shape as shown below. It's just a simple loop within a loop code, but I can't find tips or help anywhere for creating shapes with Python without the code looking extremely confusing/difficult. I need a... | [
"Just change while col <= size: to while col <= row:\nThis will print out row number of X.\nIf rowis 1the ouput is: X \nIf rowis 2the ouput is: X X \nIf rowis 3the ouput is: X X X \nIf rowis 4the ouput is: X X X X \n",
"Here is some code:\nsize = int(raw_input(\"Enter the size: \")) #Instead of input, \n#convert ... | [
2,
1,
0,
0,
0,
0
] | [
" def pattStar():\n print 'Enter no. of rows of pattern'\n noOfRows=input()\n for i in range(1,noOfRows+1):\n for j in range(i):\n print'*',\n print''\n\n",
"for x in range(10,0,-1):\n print x*\"*\"\n\noutput:\n**********\n*********\n********\n*******\n****... | [
-1,
-1,
-2
] | [
"geometry",
"loops",
"nested",
"python"
] | stackoverflow_0019784772_geometry_loops_nested_python.txt |
Q:
pandas dropna dropping the whole dataframe, need only to drop empty rows
I'm using this piece of code:
import pandas as pd
df = pd.read_excel('input.xls', sheet_name='Nouveau concept')
print(f"Dataframe:\n{df}")
new_df = df.dropna()
print(f"Dataframe now:\n{new_df}")
To read an Excel file (it has to be xls and no... | pandas dropna dropping the whole dataframe, need only to drop empty rows | I'm using this piece of code:
import pandas as pd
df = pd.read_excel('input.xls', sheet_name='Nouveau concept')
print(f"Dataframe:\n{df}")
new_df = df.dropna()
print(f"Dataframe now:\n{new_df}")
To read an Excel file (it has to be xls and not xlsx) and drop all empty rows, i.e., rows that contain no data at all.
When... | [
"First thing, import only the required columns (i.e. exclude blank ones by using use_cols)\ndf = pd.read_excel('input.xls', sheet_name='Nouveau concept',usecols=\"A:M\")\n\nThen, to drop the empty rows, you have to consider a subset of columns. Currently, there are a few columns that are completely empty, so that i... | [
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074504298_dataframe_pandas_python.txt |
Q:
how to group AWS dynamodb table and get latest value of partition key using boto3(lambda)?
I am new to AWS dynamodb, lambda. i have pretty good knowledge in RDB(MySQL).
here is my sample table
partitian key sort key attribute
Device TimeStamp REMARKS
D1 2022-12-12 12:13:14 hello
D1 2022-12-12 12:14:14 t... | how to group AWS dynamodb table and get latest value of partition key using boto3(lambda)? | I am new to AWS dynamodb, lambda. i have pretty good knowledge in RDB(MySQL).
here is my sample table
partitian key sort key attribute
Device TimeStamp REMARKS
D1 2022-12-12 12:13:14 hello
D1 2022-12-12 12:14:14 testing
D2 2022-12-12 12:18:14 hello
D2 2022-12-12 12:19:14 testing
D3 2022-11-12 12:13:14 hel... | [
"For this you would need to issue a single Query for each device and set ScanIndexForward=False and Limit=1.\nHowever, if for example you need all of the devices latest info then that would require you to create a Global Secondary Index (GSI). It was also require you to keep a \"meta\" record for each device which ... | [
0,
0
] | [] | [] | [
"amazon_dynamodb",
"aws_lambda",
"boto3",
"python"
] | stackoverflow_0074502349_amazon_dynamodb_aws_lambda_boto3_python.txt |
Q:
Replacing new vector after it gets empty on Python
Hi have an original vector, I would like to put the first 3 elements into new vector, do some math and then get new elements after the math. Put those new elements into a new vector, delete the original first 3 elements from original vector and repeat this exact p... | Replacing new vector after it gets empty on Python | Hi have an original vector, I would like to put the first 3 elements into new vector, do some math and then get new elements after the math. Put those new elements into a new vector, delete the original first 3 elements from original vector and repeat this exact procedure until the original vector is empty.
This is wha... | [
"Not sure what c_ is in your code, but regardless since numpy arrays are not dynamic, you can't remove or add elements to them. Deleting elements creates a new array without those elements, which is not optimal. I think you should either use a python deque which has fast pop methods for removing one element from th... | [
0
] | [] | [] | [
"arrays",
"matrix_multiplication",
"python",
"vector"
] | stackoverflow_0074504293_arrays_matrix_multiplication_python_vector.txt |
Q:
How to declare instance variables in abstract class?
class ILinkedListElem:
@property
def value(self):
raise NotImplementedError
@property
def next(self):
raise NotImplementedError
class ListElem(ILinkedListElem):
def __init__(self, value, next_node=None):
self.value =... | How to declare instance variables in abstract class? | class ILinkedListElem:
@property
def value(self):
raise NotImplementedError
@property
def next(self):
raise NotImplementedError
class ListElem(ILinkedListElem):
def __init__(self, value, next_node=None):
self.value = value
self.next = next_node
I wanna something l... | [
"If you want to force/require all instances of any subclass of ILinkedListElem to have the attributes \"value\" and \"nxt\", the following standard implementation with abstractmethod seems to do what you're after:\nfrom abc import ABC, abstractmethod\n\nclass ILinkedListElem (ABC):\n @property\n @abstractmeth... | [
0
] | [] | [] | [
"abstract_class",
"inheritance",
"oop",
"python",
"python_3.x"
] | stackoverflow_0074504278_abstract_class_inheritance_oop_python_python_3.x.txt |
Q:
how to use the venv in pycharm for solving my problem?
first I should say that I am newcomer in programming with python , and my problem is I try to make an telegram bot by python in pycharm , I install the telegram and telegram-python-bot package with pip in cmd in terminal of pycharm but when I run my project , ... | how to use the venv in pycharm for solving my problem? | first I should say that I am newcomer in programming with python , and my problem is I try to make an telegram bot by python in pycharm , I install the telegram and telegram-python-bot package with pip in cmd in terminal of pycharm but when I run my project , the error be shown is the telegram module is not found .
I t... | [] | [] | [
"\nYou should create a local virtual environment with python3 -m venv venv\n\nConfigure this Pycharm project to select this environment: Pycharm - Preferences - Project - Python interpreter. Then select the gear, select add; choose this local environment.\n\nQuit and reopen your Pycharm project\n\n\nThen you can in... | [
-1
] | [
"pycharm",
"python",
"telegram_bot",
"virtualenv"
] | stackoverflow_0074504335_pycharm_python_telegram_bot_virtualenv.txt |
Q:
Python - Loop through lists and join them when they match
I have a dict of lists. I have to loop through join them where possible. When joining them I have to add two columns together. I can either use the dict or list. Depending on what is easiest/recommended.
e.g.
id
name
date
value
1
hotel1
22-11-22
90
2
hot... | Python - Loop through lists and join them when they match | I have a dict of lists. I have to loop through join them where possible. When joining them I have to add two columns together. I can either use the dict or list. Depending on what is easiest/recommended.
e.g.
id
name
date
value
1
hotel1
22-11-22
90
2
hotel2
22-11-22
90
3
hotel3
22-11-22
90
4
hotel1
23-11-... | [
"Here is a stab at it =)\nhotels = {}\nfor ind,row in df.iterrows():\n hotel = row['name']\n if hotel in hotels:\n hotels[hotel]['value'] += row['value']\n hotels[hotel]['date'].append(row['date'])\n else:\n hotels[hotel] = {\n 'value': row['value'],\n 'date': [ro... | [
0
] | [] | [] | [
"dictionary",
"list",
"python"
] | stackoverflow_0074504266_dictionary_list_python.txt |
Q:
tkinter: NameError: name 'root' is not defined
I've split my tkinter app in more file, and right now I've two file:
main.py
import tkinter as tk
from login_info import LoginInfo
class Main(tk.Frame):
def __init__(self, parent, *args, **kwargs):
tk.Frame.__init__(self, parent, *args, **kwargs) ... | tkinter: NameError: name 'root' is not defined | I've split my tkinter app in more file, and right now I've two file:
main.py
import tkinter as tk
from login_info import LoginInfo
class Main(tk.Frame):
def __init__(self, parent, *args, **kwargs):
tk.Frame.__init__(self, parent, *args, **kwargs)
self.login_page = LoginInfo(self)
... | [
"Remove the duplicated ...\nif __name__ == \"__main__\":\n root = tk.Tk()\n LoginInfo(root).pack(side=\"top\", fill=\"both\", expand=True)\n root.mainloop()\n\n... from the login_page.py and launch the code from main.py.\nUse if __name__ == '__main__':... only once and only in the module which starts the prog... | [
1
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0074504480_python_tkinter.txt |
Q:
Class method called in __init__ not giving same output as the same function used outside the class
I'm sure I'm missing something in how classes work here, but basically this is my class:
import pandas as pd
import numpy as np
import scipy
#example DF with OHLC columns and 100 rows
gold = pd.DataFrame({'Open':[i ... | Class method called in __init__ not giving same output as the same function used outside the class | I'm sure I'm missing something in how classes work here, but basically this is my class:
import pandas as pd
import numpy as np
import scipy
#example DF with OHLC columns and 100 rows
gold = pd.DataFrame({'Open':[i for i in range(100)],'Close':[i for i in range(100)],'High':[i for i in range(100)],'Low':[i for i in ra... | [
"You would have to address pivot_points() as self.pivot_points()\nAnd there is no need to add period as an argument if you are not changing it, if you are, its okay there.\nI'm not sure if this helps, but here are some tips about your class:\nclass Backtest:\n\n def __init__(self, ticker, df):\n self.tick... | [
1,
0
] | [] | [] | [
"dataframe",
"oop",
"pandas",
"python"
] | stackoverflow_0074504314_dataframe_oop_pandas_python.txt |
Q:
How to turn this into O(nlogn)?
From a list of distinct numbers, I want to find the sum of the largest numbers of len(a)//3. Examples if len(a) = 9, you need to find the sum of the largest 3 numbers. If len(a)=40, you need to find the sum of the largest 13 numbers. I was able to code it as such:
def largestthree(a... | How to turn this into O(nlogn)? | From a list of distinct numbers, I want to find the sum of the largest numbers of len(a)//3. Examples if len(a) = 9, you need to find the sum of the largest 3 numbers. If len(a)=40, you need to find the sum of the largest 13 numbers. I was able to code it as such:
def largestthree(a):
max2 = 0
for i in range(... | [
"This one has about the same efficiency as sorted(list), which is n log(n).\nsum(sorted(a, reverse=True)[:len(a)//3])\n\n",
"Use a min heap, then if size > len(a)//3, pop. After iterating through all items, you are left with the biggest len(a)//3 numbers. Sum up said numbers.\nimport heapq\nl = [100, 1,2,3,4 ,545... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0074504345_python.txt |
Q:
Counting contiguous sawtooth subarrays
Given an array of integers arr, your task is to count the number of contiguous subarrays that represent a sawtooth sequence of at least two elements.
For arr = [9, 8, 7, 6, 5], the output should be countSawSubarrays(arr) = 4. Since all the elements are arranged in decreasing ... | Counting contiguous sawtooth subarrays | Given an array of integers arr, your task is to count the number of contiguous subarrays that represent a sawtooth sequence of at least two elements.
For arr = [9, 8, 7, 6, 5], the output should be countSawSubarrays(arr) = 4. Since all the elements are arranged in decreasing order, it won’t be possible to form any sawt... | [
"Here's my solution using dynamic programming. This is a bit more readable to me than the accepted answer (or the added answer in the OP), although there's probably still room for improvement.\nO(n) time and O(1) space.\ndef solution(arr):\n # holds the count of sawtooths at each index of our input array,\n #... | [
3,
2,
0,
0,
0,
0,
0
] | [] | [] | [
"algorithm",
"arrays",
"dynamic_programming",
"python"
] | stackoverflow_0069356332_algorithm_arrays_dynamic_programming_python.txt |
Q:
How to find a total year sales from a dictionary?
I have this dictionary, and when I code for it, I only have the answer for June, May, September. How would I code for the months that are not given in the dictionary? Obviously, I have zero for them.
{'account': 'Amazon', 'amount': 300, 'day': 3, 'month': 'June'}
... | How to find a total year sales from a dictionary? | I have this dictionary, and when I code for it, I only have the answer for June, May, September. How would I code for the months that are not given in the dictionary? Obviously, I have zero for them.
{'account': 'Amazon', 'amount': 300, 'day': 3, 'month': 'June'}
{'account': 'Facebook', 'amount': 550, 'day': 5, 'month... | [
"import calendar\n\nmonths = calendar.month_name[1:]\nresults = dict(zip(months, [0]*len(months)))\n\nfor d in data:\n results[d[\"month\"]] += d[\"amount\"]\n\n# then you have results dict with monthly amounts\n# sum everything to get yearly total\ntotal = sum(results.values())\n\n",
"This might help:\nfrom c... | [
0,
0
] | [
"You can read the following blog regarding the usage of dictionaries and how to perform calculations.\n5 best ways to sum dictionary values in python\nThis is on of the examples given in the blog.\nwages = {'01': 910.56, '02': 1298.68, '03': 1433.99, '04': 1050.14, '05': 877.67}\ntotal = sum(wages.values())\nprint(... | [
-1
] | [
"dictionary",
"python",
"sum"
] | stackoverflow_0074504560_dictionary_python_sum.txt |
Q:
itertools combination can only work for one copy
when I use combinations from itertools, I find that I can only use it once, and afterwards I must repeat the line of code for it to work again. For example,
from itertools import combinations
comb = combinations( range( 0 , 5 ) , 2 )
xyLabels = [ (f'PCA{x}', f'PCA{y... | itertools combination can only work for one copy | when I use combinations from itertools, I find that I can only use it once, and afterwards I must repeat the line of code for it to work again. For example,
from itertools import combinations
comb = combinations( range( 0 , 5 ) , 2 )
xyLabels = [ (f'PCA{x}', f'PCA{y}') for x , y in comb ]
>[('PCA0', 'PCA1'), ('PCA0',... | [
"You need to define comb as a list instead of a generator - like this:\ncomb = list(combinations( range( 0 , 5 ) , 2 ))\n\nThat will then give you the result you expect. it will however increase your memory utilisation because you evaluate comb fully, instead of having it wait in the wings to hand you values on dem... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074504575_python.txt |
Q:
Is there a way to install Anki Add ons programmatically?
I would like to install Anki add-ons programmatically without resorting to the GUI, like "anki install 2055492159" or within python like:
import anki
anki.addons.install("2055492159")
This way I would be able to use the CLI and create bash scripts to port ... | Is there a way to install Anki Add ons programmatically? | I would like to install Anki add-ons programmatically without resorting to the GUI, like "anki install 2055492159" or within python like:
import anki
anki.addons.install("2055492159")
This way I would be able to use the CLI and create bash scripts to port my installation configurations between systems easily. I trie... | [
"I don't know of a way to install add-ons programatically, but the process is simple enough that you can include instructions. The Anki manual has instructions on how to install add-ons.\n"
] | [
0
] | [] | [] | [
"anki",
"python"
] | stackoverflow_0074504658_anki_python.txt |
Q:
Getting "Could not find function xmlCheckVersion in library libxml2. Is libxml2 installed?" when installing lxml through pip
I'm getting an error Could not find function xmlCheckVersion in library libxml2. Is libxml2 installed? when trying to install lxml through pip.
c:\users\f\appdata\local\temp\xmlXPathInitqj... | Getting "Could not find function xmlCheckVersion in library libxml2. Is libxml2 installed?" when installing lxml through pip | I'm getting an error Could not find function xmlCheckVersion in library libxml2. Is libxml2 installed? when trying to install lxml through pip.
c:\users\f\appdata\local\temp\xmlXPathInitqjzysz.c(1) : fatal error C1083: Cannot open include file: 'libxml/xpath.h': No such file or directory
***************************... | [
"I had this issue and realised that whilst I did have libxml2 installed, I didn't have the necessary development libraries required by the python package. Installing them solved the problem:\nsudo apt-get install libxml2-dev libxslt1-dev\nsudo pip install lxml\n\n",
"Install lxml from http://www.lfd.uci.edu/~gohl... | [
167,
157,
38,
24,
21,
10,
2,
2,
1,
1,
0
] | [
"I am using venv.\nIn my case it was enough to add lxml==4.6.3 to requirements.txt.\nOne library wanted earlier version and this was causing this error, so when I forced pip to use newest version (currently 4.6.3) installation was successful.\n"
] | [
-1
] | [
"python"
] | stackoverflow_0033785755_python.txt |
Q:
Streamlit via Google Colab through LocalTunnel does not work anymore
I am using LocalTunnel on Colab. It worked perfectly until yesterday. But it stopped working since. My code has this structure :
! pip install streamlit -q
Then
%%writefile app.py
import streamlit as st
st.write('# test')
Finally
!streamlit run... | Streamlit via Google Colab through LocalTunnel does not work anymore | I am using LocalTunnel on Colab. It worked perfectly until yesterday. But it stopped working since. My code has this structure :
! pip install streamlit -q
Then
%%writefile app.py
import streamlit as st
st.write('# test')
Finally
!streamlit run /content/app.py & npx localtunnel --port 8501
I now get this output :
Tr... | [
"I was getting the same error, I resolved it by going back to a previous version of Streamlit like so:\npip install streamlit==1.13.0\n\nYou can see in the changelog that with version 1.14.0 some changes were made regarding Enum classes.\n"
] | [
1
] | [] | [] | [
"google_colaboratory",
"localtunnel",
"python",
"streamlit"
] | stackoverflow_0074500526_google_colaboratory_localtunnel_python_streamlit.txt |
Q:
Simulating orbit of planet around the sun with RK4
I am trying to simulate a planet going around the sun with the RK4 algorithm.
This is my code that i tried:
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
def calcvec(x1,y1,x2,y2):
r = np.array([0,0,0])
r[0]=x2-x1
r[1... | Simulating orbit of planet around the sun with RK4 | I am trying to simulate a planet going around the sun with the RK4 algorithm.
This is my code that i tried:
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
def calcvec(x1,y1,x2,y2):
r = np.array([0,0,0])
r[0]=x2-x1
r[1]=y2-y1
r[2]= (r[0]**2 + r[1]**2)**(3/2)
re... | [
"First good night. OK! first the star is fixed at the origin of the Cartesian coordinate system and the planet describes a flat orbit around the star due to the mutual iteration of the two. The equations of motion are obtained by applying Newton's laws of dynamics in conjunction with the Newtonian theory of gravita... | [
0
] | [] | [] | [
"orbital_mechanics",
"python",
"runge_kutta"
] | stackoverflow_0074302139_orbital_mechanics_python_runge_kutta.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.