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:
Pydantic error when reading data from JSON
I am writing code, which loads the data of a JSON file and parses it using Pydantic.
Here is the Python code:
import json
import pydantic
from typing import Optional, List
class Car(pydantic.BaseModel):
manufacturer: str
model: str
date_of_manufacture: str
... | Pydantic error when reading data from JSON | I am writing code, which loads the data of a JSON file and parses it using Pydantic.
Here is the Python code:
import json
import pydantic
from typing import Optional, List
class Car(pydantic.BaseModel):
manufacturer: str
model: str
date_of_manufacture: str
date_of_sale: str
number_plate: str
p... | [
"The problem comes from the fact that the default Pydantic validator for float simply tries to coerce the string value to float (as @Paul mentioned). And float(\"100,000\") leads to a ValueError.\nI am surprised no one suggested this, but if you don't control the source JSON data, you can easily solve this issue by... | [
2,
1,
0
] | [] | [] | [
"json",
"pydantic",
"python"
] | stackoverflow_0074632526_json_pydantic_python.txt |
Q:
Can't click on this element on heroku
I have this robot that takes in some data and places an order in another website. everything worked fine locally, but on heroku the button place order doesn't get clicked for some reason. here is the code:
place_order = driver.find_element(By.ID, 'placeOrderBtn')
driver.execut... | Can't click on this element on heroku | I have this robot that takes in some data and places an order in another website. everything worked fine locally, but on heroku the button place order doesn't get clicked for some reason. here is the code:
place_order = driver.find_element(By.ID, 'placeOrderBtn')
driver.execute_script("arguments[0].click();", place_ord... | [
"Don't try to click any element using JavaScript, use the Selenium plugin API and tools:\nIn Selenium there is a class called WebDriverWait, you can use it for smart waiting until an element is clickable, visible, hidden and so on:\nelement = WebDriverWait(driver, 10).until(\n EC.element_to_be_clickable((By.... | [
0
] | [] | [] | [
"heroku",
"python",
"selenium"
] | stackoverflow_0074641337_heroku_python_selenium.txt |
Q:
Concatenate strings from several rows using Pandas groupby
I want to merge several strings in a dataframe based on a groupedby in Pandas.
This is my code so far:
import pandas as pd
from io import StringIO
data = StringIO("""
"name1","hej","2014-11-01"
"name1","du","2014-11-02"
"name1","aj","2014-12-01"
"name1",... | Concatenate strings from several rows using Pandas groupby | I want to merge several strings in a dataframe based on a groupedby in Pandas.
This is my code so far:
import pandas as pd
from io import StringIO
data = StringIO("""
"name1","hej","2014-11-01"
"name1","du","2014-11-02"
"name1","aj","2014-12-01"
"name1","oj","2014-12-02"
"name2","fin","2014-11-01"
"name2","katt","201... | [
"You can groupby the 'name' and 'month' columns, then call transform which will return data aligned to the original df and apply a lambda where we join the text entries:\nIn [119]:\n\ndf['text'] = df[['name','text','month']].groupby(['name','month'])['text'].transform(lambda x: ','.join(x))\ndf[['name','text','mont... | [
300,
115,
57,
16,
13,
6,
3,
0
] | [] | [] | [
"pandas",
"pandas_groupby",
"python",
"python_3.x"
] | stackoverflow_0027298178_pandas_pandas_groupby_python_python_3.x.txt |
Q:
How do I extract specific rows from a CSV file?
I have three CSV files:
doctors.csv
1,John,Smith,Internal Med
2,Jone,Smith,Pediatrics
3,Jone,Carlos,Cardiology
patients.csv
1,Sara,Smith,20,07012345678,B1234
2,Mike,Jones,37,07555551234,L22AB
3,Daivd,Smith,15,07123456789,C1ABC
... and linked.csv, which I need to po... | How do I extract specific rows from a CSV file? | I have three CSV files:
doctors.csv
1,John,Smith,Internal Med
2,Jone,Smith,Pediatrics
3,Jone,Carlos,Cardiology
patients.csv
1,Sara,Smith,20,07012345678,B1234
2,Mike,Jones,37,07555551234,L22AB
3,Daivd,Smith,15,07123456789,C1ABC
... and linked.csv, which I need to populate based on doctors.csv and patients.csv.
I'm tak... | [
"This looks like a task better suited for a database, but here is a possible solution just using the csv module (pathlib here is just my preferred way to handle files):\nimport csv\nfrom pathlib import Path\n\n# Files\npatients_csv = Path('patients.csv')\ndoctors_csv = Path('doctors.csv')\nlinked_csv = Path('linked... | [
1,
1
] | [] | [] | [
"object",
"python"
] | stackoverflow_0074641071_object_python.txt |
Q:
ImportError: No module named bs4 - despite bs4 and BeautifulSoup being installed
I downloaded Python 3.7 and am running a script with "from bs4 import BeautifulSoup" and am receiving the following error on execution;
"File "myscript.py", line 3, in
from bs4 import BeautifulSoup ImportError: No module name... | ImportError: No module named bs4 - despite bs4 and BeautifulSoup being installed | I downloaded Python 3.7 and am running a script with "from bs4 import BeautifulSoup" and am receiving the following error on execution;
"File "myscript.py", line 3, in
from bs4 import BeautifulSoup ImportError: No module named bs4"
When I type "pip3 install bs4" or "pip3 install BeautifulSoup4" in the termina... | [
"Just pip install bs4. \nProbably, you are maintaining different versions of Python.\n",
"check if you have more than one version of python, if so add the path of python 3.7 in the system setting and try removing the older python if possible\nand then pip install BeautifulSoup \n",
"I had a similar problem with... | [
2,
1,
0
] | [] | [] | [
"macos",
"python"
] | stackoverflow_0052492315_macos_python.txt |
Q:
Python Telegram Bot: show message history for new group members
With a python based telegram bot that should help to setup group settings I want to hide/unhide the message history for new group subscribers. I am using the python-telegram-bot API wrapper (documented here).
For setting other permissions there is a m... | Python Telegram Bot: show message history for new group members | With a python based telegram bot that should help to setup group settings I want to hide/unhide the message history for new group subscribers. I am using the python-telegram-bot API wrapper (documented here).
For setting other permissions there is a method Bot.set_chat_permissions(). But for hide/unhide message history... | [
"python-telegram-bot is a wrapper for the Bot API. Only those methods listed in the API docs have a counterpart in python-telegram-bot.\nThe togglePreHistoryHidden method is an endpoint of the Telegram API != Bot API.\n\nDisclaimer: I'm currently the maintainer of python-telegram-bot.\n"
] | [
1
] | [] | [] | [
"python",
"python_telegram_bot",
"telegram",
"telegram_api",
"telegram_bot"
] | stackoverflow_0074621034_python_python_telegram_bot_telegram_telegram_api_telegram_bot.txt |
Q:
ERROR: Command errored out with exit status 1 when trying to install ciso8601
Im a rookie to start programming. It would so much appreciated if you can help me on this.
Im using Windows 8 64bits and Python 3.7. thank you guys so much!!
The error popped up when I tried to install ciso8601 in Pycharm.
ERROR: Comman... | ERROR: Command errored out with exit status 1 when trying to install ciso8601 | Im a rookie to start programming. It would so much appreciated if you can help me on this.
Im using Windows 8 64bits and Python 3.7. thank you guys so much!!
The error popped up when I tried to install ciso8601 in Pycharm.
ERROR: Command errored out with exit status 1:
Collecting ciso8601
Using cached ciso8601-2.1.3.t... | [
"You have to Install with docker. Beacuse ciso8601 is a Python extension written in C. Source: GitHub\n"
] | [
0
] | [] | [] | [
"installation",
"python"
] | stackoverflow_0068084614_installation_python.txt |
Q:
sh: flake8: not found, though I installed it with python pip
Here I'm going to use flake8 within a docker container. I installed flake8 using the following command and everything installed successfully.
$ sudo -H pip3 install flake8 // worked fine
and it's location path is-
/usr/local/lib/python3.8/dist-packa... | sh: flake8: not found, though I installed it with python pip | Here I'm going to use flake8 within a docker container. I installed flake8 using the following command and everything installed successfully.
$ sudo -H pip3 install flake8 // worked fine
and it's location path is-
/usr/local/lib/python3.8/dist-packages
Then I executed the following command but result was not expe... | [
"When you docker-compose run a container, it is in a new container in a new isolated filesystem. If you ran pip install in a debugging shell in another container, it won't be visible there.\nAs a general rule, never install software into a running container, unless it's for very short-term debugging. This will ge... | [
2
] | [] | [] | [
"docker",
"flake8",
"pip",
"python"
] | stackoverflow_0074637107_docker_flake8_pip_python.txt |
Q:
json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 2 column 1 (char 2) when reading a json?
{
"teams": {
"sp": [
{
"k": {
"attack": 3,
"defense": 4
},
"s": {
"attack": 3,
"defense": 4
},
"... | json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 2 column 1 (char 2) when reading a json? | {
"teams": {
"sp": [
{
"k": {
"attack": 3,
"defense": 4
},
"s": {
"attack": 3,
"defense": 4
},
"b": {
"attack": 3,
"defense": 4
},
"h": {
"attack": 3,
"defense": 4
... | [
"The issue is that you are trying to convert individual lines to json, you need to convert the all file at once\nwith open('playerlist.json', 'r') as f:\n obj = json.load(f)\n\n"
] | [
0
] | [] | [] | [
"json",
"python",
"python_jsons"
] | stackoverflow_0074641598_json_python_python_jsons.txt |
Q:
Django ORM for fetching latest record for specific ID
How do I write a django ORM to fetch the most recent records from the table for a specific id.
Example:
I have table(tr_data) data like:
id
trs(foreign key)
status
last_updated
1
301
3
2022-11-28 06:14:28
2
301
4
2022-11-28 06:15:28
3
302
3
2022-11-28 06:14... | Django ORM for fetching latest record for specific ID | How do I write a django ORM to fetch the most recent records from the table for a specific id.
Example:
I have table(tr_data) data like:
id
trs(foreign key)
status
last_updated
1
301
3
2022-11-28 06:14:28
2
301
4
2022-11-28 06:15:28
3
302
3
2022-11-28 06:14:28
4
302
4
2022-11-28 06:15:28
5
302
2
2022-11... | [
"Possible duplicate\nDjango ORM: Group by and Max\nYou can achieve this by annotate and Max. In the tr_data model, add a related_name parameter to trs something like 'tr_status'.\nWrite an orm:\nlatest_objs = TrData.objects.annotate(temp=Max('trs__tr_status__last_updated')).filter(last_updated).values('trs', 'statu... | [
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0074641547_django_python.txt |
Q:
How to update/upgrade a package using pip?
What is the way to update a package using pip?
those do not work:
pip update
pip upgrade
I know this is a simple question but it is needed as it is not so easy to find (pip documentation doesn't pop up and other questions from stack overflow are relevant but are not exac... | How to update/upgrade a package using pip? | What is the way to update a package using pip?
those do not work:
pip update
pip upgrade
I know this is a simple question but it is needed as it is not so easy to find (pip documentation doesn't pop up and other questions from stack overflow are relevant but are not exactly about that)
| [
"The way is\npip install <package_name> --upgrade\n\nor in short\npip install <package_name> -U\n\nUsing sudo will ask to enter your root password to confirm the action, but although common, is considered unsafe.\nIf you do not have a root password (if you are not the admin) you should probably work with virtualenv... | [
841,
74,
24,
13,
11,
10,
9,
1
] | [
"Execute the below command in your command prompt,\nC:\\Users\\Owner\\AppData\\Local\\Programs\\Python\\Python310>python -m pip install --upgrade pip\n\nOutput will be like below,\nRequirement already satisfied: pip in c:\\users\\owner\\appdata\\local\\programs\\python\\python310\\lib\\site-packages (21.2.4)\nColle... | [
-2
] | [
"pip",
"python"
] | stackoverflow_0047071256_pip_python.txt |
Q:
How to remove entire rows if all columns except one is empty?
I want to remove entire rows if all columns except the one is empty. So, imagine that my DataFrame is
df = pd.DataFrame({"col1": ["s1", "s2", "s3", "s4", "s5", "s6"],
"col2": [41, np.nan, np.nan, np.nan, np.nan, 61],
... | How to remove entire rows if all columns except one is empty? | I want to remove entire rows if all columns except the one is empty. So, imagine that my DataFrame is
df = pd.DataFrame({"col1": ["s1", "s2", "s3", "s4", "s5", "s6"],
"col2": [41, np.nan, np.nan, np.nan, np.nan, 61],
"col3": [24, 51, np.nan, np.nan, np.nan, 84],
... | [
"Use the thresh parameter:\nN = 1\ndf.dropna(thresh=N+1)\n\nOr if you want to match exactly N NAs (no more no less):\nN = 1\nout = df[df.isna().sum(axis=1).ne(df.shape[1]-N)]\n\nOutput:\n col1 col2 col3 col4 col5\n0 s1 41.0 24.0 53.0 43.0\n1 s2 NaN 51.0 64.0 83.0\n2 s3 NaN NaN 81.0 47.0\n3... | [
1,
1,
0,
0,
0,
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074641498_dataframe_pandas_python.txt |
Q:
Import a pandas dataframe in a Streamlit app
I am trying to import a pandas dataframe in a Streamlit app (the goal being to run a Machine Learning model based on this dataframe when clicking a button). I use the usual way:
import pandas as pd
import streamlit as st
df = pd.read_csv('/data/metabolic_syndrome.csv')
... | Import a pandas dataframe in a Streamlit app | I am trying to import a pandas dataframe in a Streamlit app (the goal being to run a Machine Learning model based on this dataframe when clicking a button). I use the usual way:
import pandas as pd
import streamlit as st
df = pd.read_csv('/data/metabolic_syndrome.csv')
if (st.button('Click on this fancy button !')):
... | [
"Try with a dot, like this:\npd.read_csv('./data/metabolic_syndrome.csv')\n\n",
"You need to adapt your path to how you launch streamlit.exe.\nThis should work:\ncd PATH_TO_PROJECT_DIR\nPATH_TO_STREAMLIT\\streamlit.exe run main.py --server.port 8080\n\nOf course, your data folder must be a subfolder of PROJECT_DI... | [
0,
0
] | [] | [] | [
"pandas",
"python",
"streamlit"
] | stackoverflow_0074524715_pandas_python_streamlit.txt |
Q:
using machine learning to find patterns in strings
Im new to AI and machine learning, using python3.
I have a huge data base of strings and each string has a number of 1-3 asign to it.
there are hidden patterns in the strings that make them get a value of 1-3.
I want to try and make a ai that can help me categoriz... | using machine learning to find patterns in strings | Im new to AI and machine learning, using python3.
I have a huge data base of strings and each string has a number of 1-3 asign to it.
there are hidden patterns in the strings that make them get a value of 1-3.
I want to try and make a ai that can help me categorize them and try to find as much patterns as you can.
can ... | [
"The task you are describing would fall in the category of \"Text Classification\", although not quite, because you are not working with Natural Text.\nMy first idea would be to somehow convert to Links into single characters and then into a vector / list of numbers. Computer can only work with numbers, but not wit... | [
0
] | [] | [] | [
"machine_learning",
"python",
"string",
"url_pattern"
] | stackoverflow_0074641530_machine_learning_python_string_url_pattern.txt |
Q:
How to fail a gitlab CI pipeline if the python script throws error code 1?
I have a python file that opens and checks for a word. The program returns 0 if pass and 1 if fails.
import sys
word = "test"
def check():
with open("tex.txt", "r") as file:
for line_number, line in enumerate(file, start=1): ... | How to fail a gitlab CI pipeline if the python script throws error code 1? | I have a python file that opens and checks for a word. The program returns 0 if pass and 1 if fails.
import sys
word = "test"
def check():
with open("tex.txt", "r") as file:
for line_number, line in enumerate(file, start=1):
if word in line:
return 0
retu... | [
"You can use sys.exit(is_word_found). But remember you use sys module (import sys).\nLike this:\nimport sys\nword = \"test\"\ndef check():\n with open(\"tex.txt\", \"r\") as file:\n for line_number, line in enumerate(file, start=1): \n if word in line:\n return 0\n return... | [
0
] | [] | [] | [
"gitlab",
"gitlab_ci",
"pipeline",
"python"
] | stackoverflow_0074630301_gitlab_gitlab_ci_pipeline_python.txt |
Q:
AttributeError: module '_Box2D' has no attribute 'RAND_LIMIT_swigconstant'
I am trying to run a lunar_lander on reinforcement
learning, but when I run it, it occurs an error.
Plus my computer is osx system.
Here is the code of lunar lander:
import numpy as np
import gym
import csv
from keras.models import Sequent... | AttributeError: module '_Box2D' has no attribute 'RAND_LIMIT_swigconstant' | I am trying to run a lunar_lander on reinforcement
learning, but when I run it, it occurs an error.
Plus my computer is osx system.
Here is the code of lunar lander:
import numpy as np
import gym
import csv
from keras.models import Sequential
from keras.layers import Dense, Activation, Flatten
from keras.optimizers im... | [
"Try this 'pip3 install box2d box2d-kengz'\n",
"\"pip install box2d box2d-kengz --user\" worked for me :) \nJust in case other people might find it informative.\n",
"In case you already had box2d-py, uninstall and reinstall it\npip uninstall box2d-py\n\nthen,\npip install box2d-py\n\nthat worked for me.\n"
] | [
36,
3,
0
] | [] | [] | [
"box2d",
"machine_learning",
"python",
"reinforcement_learning"
] | stackoverflow_0050037674_box2d_machine_learning_python_reinforcement_learning.txt |
Q:
Replace number with symbol in a list of lists
I need to replace 0 in a list of lists with dot ".". I aslo need to replace 1 with "o" and 2 with "*"
It should be something like chess board. So far I have this and I am stuck with the replacement. Thank you for your help! :)
chess =[
["0 1 0 1 0 1 0 1 "],
["1... | Replace number with symbol in a list of lists | I need to replace 0 in a list of lists with dot ".". I aslo need to replace 1 with "o" and 2 with "*"
It should be something like chess board. So far I have this and I am stuck with the replacement. Thank you for your help! :)
chess =[
["0 1 0 1 0 1 0 1 "],
["1 0 1 0 1 0 1 0 "],
["0 1 0 1 0 1 0 1 "],
["... | [
"I guess if you just need to print the layout, this would be a way to solve it:\nfrom string import ascii_lowercase\n\nchess = [\n [\"0 1 0 1 0 1 0 1\"],\n [\"1 0 1 0 1 0 1 0\"],\n [\"0 1 0 1 0 1 0 1\"],\n [\"0 0 0 0 0 0 0 0\"],\n [\"0 0 0 0 0 0 0 0\"],\n [\"2 0 2 0 2 0 2 0\"],\n [\"0 2 0 2 0 2... | [
3,
2,
1,
1,
0
] | [] | [] | [
"list",
"python",
"python_3.x"
] | stackoverflow_0074628707_list_python_python_3.x.txt |
Q:
Filter DataFrame for numeric values
Let's assume my DataFrame df has a column called col of type string. What is wrong with the following code line?
df['col'].filter(str.isnumeric)
A:
You can do it like that:
df.loc[df['col'].str.isnumeric()]
A:
First problem, you're using a built-in python method without pare... | Filter DataFrame for numeric values | Let's assume my DataFrame df has a column called col of type string. What is wrong with the following code line?
df['col'].filter(str.isnumeric)
| [
"You can do it like that:\ndf.loc[df['col'].str.isnumeric()]\n\n",
"First problem, you're using a built-in python method without parenthesis which is str.isnumeric. Hence, the TypeError: 'method_descriptor' object is not iterable.\nSecond problem, let's suppose you've added parenthesis to str.isnumeric, this func... | [
1,
1
] | [] | [] | [
"filter",
"numeric",
"pandas",
"python"
] | stackoverflow_0074641647_filter_numeric_pandas_python.txt |
Q:
How to update dataframe already stored in cache using python-streamlit library after some dataframe manipulation?
I’m relatively new to this awesome tool and would like to understand if it is possible to update the cache value with the new value.
Background:
I am developing a tool in python where data is loaded fr... | How to update dataframe already stored in cache using python-streamlit library after some dataframe manipulation? | I’m relatively new to this awesome tool and would like to understand if it is possible to update the cache value with the new value.
Background:
I am developing a tool in python where data is loaded from the SQL database, displayed using Streamlit Ag-Grid, where the user can manipulate the data on the grid, and upon ch... | [
"You can use st.session_state to store the returned data from AgGrid.\nSee the official guide: https://docs.streamlit.io/library/api-reference/session-state\nBy introducing a check if dataframes are equal, you can avoid overwriting the modified df with the originally loaded one.\n"
] | [
0
] | [] | [] | [
"ag_grid",
"caching",
"python",
"streamlit"
] | stackoverflow_0074519675_ag_grid_caching_python_streamlit.txt |
Q:
Convert saved png files into a movie/gif
I am very new to python. I have a folder which contains many .png files (which are scatter plots I previously made in python). I want to write a script that turns these files into a movie.
My files are named 0.png 1.png 2.png .... 49.png
I tried the following
frames = [... | Convert saved png files into a movie/gif | I am very new to python. I have a folder which contains many .png files (which are scatter plots I previously made in python). I want to write a script that turns these files into a movie.
My files are named 0.png 1.png 2.png .... 49.png
I tried the following
frames = []
for i in range(0,M):
frames.appe... | [
"You can use it \"Pillow\" library.\nfrom PIL import Image\n\nsample_image = Image.open(\"sample_image.png\")\nsample_image.save('.gif')\n\n\nYou can look at the other features of Pillow;\nhttps://pillow.readthedocs.io/en/stable/\n",
"You can use imageio.v3, see example from Documentation (code includes frame cre... | [
0,
0
] | [] | [] | [
"directory",
"gif",
"png",
"python",
"video"
] | stackoverflow_0074641705_directory_gif_png_python_video.txt |
Q:
Why does the lookup by index value result in a key error
The code:
df = pd.DataFrame({
'MNumber':['M03400001','M00000021','M10450001','M00003420','M02635915','M51323275','M63061229','M63151022'],
'GPA':[3.01, 4.00, 2.95, 2.90, 3.50, 3.33, 2.99, 3.98],
'major':['IS','BANA','IS','IS','IS','BANA','IS', 'B... | Why does the lookup by index value result in a key error | The code:
df = pd.DataFrame({
'MNumber':['M03400001','M00000021','M10450001','M00003420','M02635915','M51323275','M63061229','M63151022'],
'GPA':[3.01, 4.00, 2.95, 2.90, 3.50, 3.33, 2.99, 3.98],
'major':['IS','BANA','IS','IS','IS','BANA','IS', 'BANA'],
'internship':['P&G', 'IBM', 'P&G', 'IBM', 'P&G', 'E... | [
"x['IBM'] tries to access the column 'IBM', which does not exist.\nx.loc['IBM'] accesses the row 'IBM', which does exist.\n",
"Your dataframe x does not contain a key called IBM.\nTry\nprint(x)\n\nTo see the keys contained in your dataframe.\nEven better, you can try\nprint(x.columns)\n\nTo see the available colu... | [
2,
0,
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074641792_dataframe_pandas_python.txt |
Q:
x and y must be the same size error python
that's what i need to find where the error is (. Make a scatter plot of Nsteps versus starting number. You should adjust your marker symbol
and size such that you can discern patterns in the data, rather than just seeing a solid mass of
points.)
*** basically this is my c... | x and y must be the same size error python | that's what i need to find where the error is (. Make a scatter plot of Nsteps versus starting number. You should adjust your marker symbol
and size such that you can discern patterns in the data, rather than just seeing a solid mass of
points.)
*** basically this is my code:***
#in[]
import numpy as np
import matplot... | [
"That error means that range(1,100001,1) is not the same length as s. Try\nprint(len(range(1,100001,1)))\nprint(len(s))\n\nto confirm. You need to have the same amount of x-coordinates as you do y-coordinates. Make those the same size and it will work.\nIt's unclear to me from your question/code what you're actuall... | [
0,
0
] | [] | [] | [
"matplotlib",
"plot",
"python",
"scatter_plot"
] | stackoverflow_0074641768_matplotlib_plot_python_scatter_plot.txt |
Q:
IO backend error in the xarray for netcdf file
I am trying to open a .netcdf file using xarray and it is showing this error. I am unable to resolve this error and I have found no such solution to resolve this error. I have tried with different versions of Anaconda and Ubuntu but the problem persists.
ValueError: ... | IO backend error in the xarray for netcdf file | I am trying to open a .netcdf file using xarray and it is showing this error. I am unable to resolve this error and I have found no such solution to resolve this error. I have tried with different versions of Anaconda and Ubuntu but the problem persists.
ValueError: did not find a match in any of xarray's currently in... | [
"I had the same issue. I then installed netCDF4 via:\npip install netCDF4 \n\nand xarray worked. Beware of dependencies!!\n",
"I had the same problem as well. In this matter, you need to install IO dependencies.\nBased on their web site here you need to install all IO related packages:\nio = netCDF4, h5netcdf, sc... | [
5,
2,
0,
0,
0
] | [] | [] | [
"io",
"netcdf",
"python",
"python_xarray"
] | stackoverflow_0067725531_io_netcdf_python_python_xarray.txt |
Q:
How to iterate over Pandas Data frame and replace multiple rows
Here is first 5 rows of my Pd dataframe:
0 Stage II
1 Stage III
2 Stage II
3 Stage IV
4 Stage II
It has 428 rows and one column.
I want to replace Stage I, II, III, and IV with Grade I, II, III, and IV respectively so that I will have a pd ... | How to iterate over Pandas Data frame and replace multiple rows | Here is first 5 rows of my Pd dataframe:
0 Stage II
1 Stage III
2 Stage II
3 Stage IV
4 Stage II
It has 428 rows and one column.
I want to replace Stage I, II, III, and IV with Grade I, II, III, and IV respectively so that I will have a pd df like this:
0 Grade II
1 Grade III
2 Grade II
3 Grade IV
4 ... | [
"You can try this:\nfor i in [\"Stage I\", \"Stage II\", \"Stage III\", \"Stage IV\"]:\n your_df[col_name] = your_df[col_name].str.replace(i, \"Grade \" + i.split()[-1])\n\n"
] | [
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074641945_dataframe_pandas_python.txt |
Q:
Can I create a conda environment from multiple yaml files?
Is it possible to create a conda environment from two yaml files?
something like
conda env create -f env1.yml -f env2.yml
or create a enviornment from one yaml file, then update the environment with the second yaml file?
conda env create -f env1.yml
con... | Can I create a conda environment from multiple yaml files? | Is it possible to create a conda environment from two yaml files?
something like
conda env create -f env1.yml -f env2.yml
or create a enviornment from one yaml file, then update the environment with the second yaml file?
conda env create -f env1.yml
conda env update -f env2.yml
| [
"Does not seem to work. conda env create only uses the final --file argument and ignores the others. conda create and conda update do not support yaml files.\n",
"@sam is right, see relevant github issue:\nhttps://github.com/conda/conda/issues/9294\nA potential work around is to use conda-merge, with for example:... | [
1,
1,
0
] | [] | [] | [
"anaconda",
"conda",
"python"
] | stackoverflow_0065668913_anaconda_conda_python.txt |
Q:
AttributeError: 'int' object has no attribute 'keys'. Im not able to understand where I'm going wrong?
So Im basically trying to summarize an output using NLP. Below is the code im using.
stopwords = nltk.corpus.stopwords.words('English')
word_frequencies = {}
for word in nltk.word_tokenize(subject1):
if word... | AttributeError: 'int' object has no attribute 'keys'. Im not able to understand where I'm going wrong? | So Im basically trying to summarize an output using NLP. Below is the code im using.
stopwords = nltk.corpus.stopwords.words('English')
word_frequencies = {}
for word in nltk.word_tokenize(subject1):
if word not in stopwords:
if word not in word_frequencies.keys():
word_frequencies = 1
... | [
"Here you are assigning int object to variable word_frequencies = 1 I think you wanted to do something like word_frequencies[word] = 1 and word_frequencies[word] += 1\n"
] | [
0
] | [] | [] | [
"data_science",
"machine_learning",
"nlp",
"python"
] | stackoverflow_0074642074_data_science_machine_learning_nlp_python.txt |
Q:
How to Make a Looping Discord Bot Task that is Invoked When a Message is Posted in Python
I am trying to write a discord bot that posts yeterday's Wordle solutions but I cannot seem to figure out how to get a task to be invoked by a message and then have that task loop. I tried to use a while loop but then the bot... | How to Make a Looping Discord Bot Task that is Invoked When a Message is Posted in Python | I am trying to write a discord bot that posts yeterday's Wordle solutions but I cannot seem to figure out how to get a task to be invoked by a message and then have that task loop. I tried to use a while loop but then the bot would only work for one server. Trying to use a looping task does not work either. Here is the... | [
"I have solved the issue by wrapping the code in a client class and allowing the storage of multiple channel ids. The new code is shown here.\nimport asyncio\nimport imp\nimport json\nimport requests\nimport discord\nimport os\nimport time\nfrom datetime import date, timedelta\nfrom discord.ext import tasks\nimport... | [
0,
0
] | [] | [] | [
"bots",
"discord",
"discord.py",
"python",
"python_3.x"
] | stackoverflow_0070992844_bots_discord_discord.py_python_python_3.x.txt |
Q:
Automate update of models based on conditions
I have a model
class Session(models.Model):
name = models.CharField(max_length=12)
active = models.BooleanField(default=False)
date = models.DateField()
startTime = models.TimeField()
The active field is set based on the date and start time.
For eg -
S... | Automate update of models based on conditions | I have a model
class Session(models.Model):
name = models.CharField(max_length=12)
active = models.BooleanField(default=False)
date = models.DateField()
startTime = models.TimeField()
The active field is set based on the date and start time.
For eg -
Suppose during the creation of an object, the date i... | [
"I would advise to use a DateTimeField for the start timestamp, and make active a property, so:\nfrom django.utils import timezone\n\n\nclass Session(models.Model):\n name = models.CharField(max_length=12)\n start = models.DateTimeField()\n \n @property\n def active(self):\n return timezone.no... | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0074642066_django_python.txt |
Q:
Pandas KeyError in get_loc when calling entries from dataframe in for loop
I am using a pandas data-frame and for some reason when trying to access one entry after another in a for loop it does gives me an error.
Here is my (simplified) code snippet:
df_original = pd.read_csv(csv_dataframe_filename, sep='\t', hea... | Pandas KeyError in get_loc when calling entries from dataframe in for loop | I am using a pandas data-frame and for some reason when trying to access one entry after another in a for loop it does gives me an error.
Here is my (simplified) code snippet:
df_original = pd.read_csv(csv_dataframe_filename, sep='\t', header=[0, 1], encoding_errors="replace")
df_original.columns = ['A', 'B',
... | [
"The issue is that you are manually incrementing i in the for loop, but this is something the for loop already does for you. This causes i to increment by 2 every loop.\nTry:\n...\nc_mag = np.zeros((len(df_use), 1))\n\nfor i in range(len(df_use)):\n print(df_use['Count_Number'][x]) #THIS IS THE LINE THAT IS THE ... | [
0,
0
] | [] | [] | [
"dataframe",
"keyerror",
"pandas",
"python"
] | stackoverflow_0074641988_dataframe_keyerror_pandas_python.txt |
Q:
Python: Value Error: Watchdog Numpy.Load()
Situation:
Live Camera captures numpy arrays and saves with utc timestamp and exposure time (ms) in a folder.
A parallel running script watches the folder, where the images are saved as .npy files:
import numpy as np
from watchdog.observers import Observer #https://pypi.o... | Python: Value Error: Watchdog Numpy.Load() | Situation:
Live Camera captures numpy arrays and saves with utc timestamp and exposure time (ms) in a folder.
A parallel running script watches the folder, where the images are saved as .npy files:
import numpy as np
from watchdog.observers import Observer #https://pypi.org/project/watchdog/
from watchdog.events import... | [
"Looking at the code provided, I think as you said, file is read before being saved. try below steps:\n\nCheck the ndarray shape to be (1520,2032), else catch the exception, where you wait and call the method again, else avoid the file completely.\n\nElse maintain a .db/.txt/.pickle of the files being saved, with t... | [
0
] | [] | [] | [
"load",
"numpy",
"python",
"watchdog"
] | stackoverflow_0074641943_load_numpy_python_watchdog.txt |
Q:
How do I filter a specific number from a list in python?
current code:
list = [1,2,3,4,5]
for i in list:
Dev.step(2)
if i == 2 or 1 or 0:
Dev.turnLeft()
Dev.step(Dev.x-Item[i].x)
Dev.step(Dev.x-15)
Dev.turnRight()
else:
Dev.turnRight()
Dev.step(Item[i].x... | How do I filter a specific number from a list in python? | current code:
list = [1,2,3,4,5]
for i in list:
Dev.step(2)
if i == 2 or 1 or 0:
Dev.turnLeft()
Dev.step(Dev.x-Item[i].x)
Dev.step(Dev.x-15)
Dev.turnRight()
else:
Dev.turnRight()
Dev.step(Item[i].x-Dev.x)
Dev.step(15-Dev.x)
Dev.turnLeft()
How... | [
"The condition below should represent this:\nif i in {0, 1, 2}:\n #do logic\n\n",
"Your if statement won't work because of i == 2 or 1 or 0. See, when you use or, it checks if each statement is true. So you need to use i == for each number. (If this is a bit confusing, feel free to read more about this here)\... | [
4,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0074642172_python.txt |
Q:
How can I solve a non continuous equation in python?
I have a function:
p = np.arange(0,1,0.01)
EU = (((-(1.3+1-0.5)**(1.2-1.5)/(1-1.5)))**-1)*p + (((-(0.1+1-0.5)**(1.2-1.5)/(1-1.5)))**-1)*(1-p)
And I would like to solve this to get a value of p where EU == 0.5.
My issue is that I checked manually and the p value... | How can I solve a non continuous equation in python? | I have a function:
p = np.arange(0,1,0.01)
EU = (((-(1.3+1-0.5)**(1.2-1.5)/(1-1.5)))**-1)*p + (((-(0.1+1-0.5)**(1.2-1.5)/(1-1.5)))**-1)*(1-p)
And I would like to solve this to get a value of p where EU == 0.5.
My issue is that I checked manually and the p value is 0.4244, but in the function p jumps with steps of 0.01... | [
"your function is a simple linear function, so it could be simply found by just a simple binary search, however if the funciton was more complex and you needed to really calculate the gradient and runt he optimization you could use torch or jax or any other autograd tools to do that\nimport torch\ndef func(p):\n ... | [
1
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0074641607_numpy_python.txt |
Q:
Rest API request not recognizing date parameter in data Python
I'm trying to pull data from a rest api using python requests library.
I can connect fine with the key and can pull other locations on the API however for some reason it isn't picking up the date field
section of code:
Headers = {
'A... | Rest API request not recognizing date parameter in data Python | I'm trying to pull data from a rest api using python requests library.
I can connect fine with the key and can pull other locations on the API however for some reason it isn't picking up the date field
section of code:
Headers = {
'Accept': 'application/json',
'Content-Type': 'applicat... | [
"Required data is \"date\" not \"Date\"\nHeaders = {\n'Accept': 'application/json',\n'Content-Type': 'application/json',\n'cookie' : 'hazelcast.sessionId='+ token\n}\nurl = 'https://uk.calabriocloud.com/api/rest/scheduling/adherence/agent/'\nData = {\n 'date':'2022-11-25'\n }\n\n\nresponse = session.g... | [
0
] | [] | [] | [
"api",
"python",
"python_requests",
"rest"
] | stackoverflow_0074642158_api_python_python_requests_rest.txt |
Q:
Showing flash messages in DJango with close button
I want to display flash messages in Django with the close button.
Existing message framework in Django allows to display messages and does not allow to close it.
As an example, web2py provides such flash messages. I am looking for similar functionality in Django. ... | Showing flash messages in DJango with close button | I want to display flash messages in Django with the close button.
Existing message framework in Django allows to display messages and does not allow to close it.
As an example, web2py provides such flash messages. I am looking for similar functionality in Django.
If it can be done with few lines of code , it would be... | [
"I was unaware that such thing can be solved using boot-strap !\nI did something like this :\n{% if messages %}\n {% for msg in messages %}\n <div class=\"alert alert-info alert-dismissable\">\n <button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">×</button>\n {{ms... | [
11,
4,
2,
1,
0,
0
] | [] | [] | [
"django",
"django_views",
"flash_message",
"python",
"web2py"
] | stackoverflow_0043560532_django_django_views_flash_message_python_web2py.txt |
Q:
Flask Bootstrap Alerts and Close Button not displaying correctly
I am trying to get bootstraps alerts working but I think I missing something. Here is a cut down version of my code that displays the issues...
Python File
from flask import Flask, render_template
from flask_bootstrap import Bootstrap
app = Flask(__... | Flask Bootstrap Alerts and Close Button not displaying correctly | I am trying to get bootstraps alerts working but I think I missing something. Here is a cut down version of my code that displays the issues...
Python File
from flask import Flask, render_template
from flask_bootstrap import Bootstrap
app = Flask(__name__)
Bootstrap(app)
@app.route("/", methods=['GET', 'POST'])
def s... | [
"The cause of the issues was the use of an older Flask-Bootstrap which only support Bootstrap 2 or 3. The components that I wanted to use were not available in these versions.\nI found a couple of options:\nUse a native Bootstrap setup:\n\nFollow the Get Started in setting up Bootstrap on the site. For convivence c... | [
0
] | [] | [] | [
"bootstrap_5",
"flask",
"python"
] | stackoverflow_0074641054_bootstrap_5_flask_python.txt |
Q:
How to delete a k8s deployment using k8s python client?
Is there a way to delete a k8s deployment using python?
the official k8s python client lacks this feature, you can only delete pods & services
I tried doing it using [subprocess] but I'd like to explore other options
def delete_deployment(deployment_name, nam... | How to delete a k8s deployment using k8s python client? | Is there a way to delete a k8s deployment using python?
the official k8s python client lacks this feature, you can only delete pods & services
I tried doing it using [subprocess] but I'd like to explore other options
def delete_deployment(deployment_name, name_space):
subprocess.run(f'kubectl delete deployment {dep... | [
"You can delete a deployment by the following:\n k8s_apps_v1 = client.AppsV1Api()\n k8s_apps_v1.delete_namespaced_deployment('dep_name','name_space')\n\n"
] | [
0
] | [] | [] | [
"kubernetes",
"kubernetes_python_client",
"python"
] | stackoverflow_0074641038_kubernetes_kubernetes_python_client_python.txt |
Q:
How does closures see context variables into the stack?
I would like to understand how the stack frame pushed by calling b() can access the value of x that lives in the stack frame pushed by a().
Is there a pointer from b() frame to a() frame? Or does the runtime copy the value of x as a local variable in the b() ... | How does closures see context variables into the stack? | I would like to understand how the stack frame pushed by calling b() can access the value of x that lives in the stack frame pushed by a().
Is there a pointer from b() frame to a() frame? Or does the runtime copy the value of x as a local variable in the b() frame? Or is there another machanism under the hood?
This exa... | [
"In CPython (the implementation most people use) b itself contains a reference to the value. Consider this modification to your function:\ndef a():\n x = 5\n def b():\n return x + 2\n\n # b.__closure__[0] corresponds to x\n print(b.__closure__[0].cell_contents)\n x = 9\n print(b.__closure__... | [
1
] | [] | [] | [
"closures",
"programming_languages",
"python",
"stack"
] | stackoverflow_0074642004_closures_programming_languages_python_stack.txt |
Q:
tkinter wont let me change the bg color
I have this problem that tkinter wont let me change the bg color. I tried using the normal "white" or "blue", etc. I tried Hex-Code and RGB-Code. Nothing works and I am going crazy. The color also does not change when using widgets, so it is alwasy a dark screen, but I creat... | tkinter wont let me change the bg color | I have this problem that tkinter wont let me change the bg color. I tried using the normal "white" or "blue", etc. I tried Hex-Code and RGB-Code. Nothing works and I am going crazy. The color also does not change when using widgets, so it is alwasy a dark screen, but I creates the widgets since I can see the cursor cha... | [
"Mac OS used keyword highlightbackground.\nChange this:\nwindow.config(bg=\"white\")\n\nto:\nwindow.config(highlightbackground=\"white\")\n\n"
] | [
0
] | [] | [] | [
"colors",
"python",
"tkinter"
] | stackoverflow_0074632246_colors_python_tkinter.txt |
Q:
Python using gattlib for BLE Scanning on Windows 10
I want to create a BLE Connection between my Laptop (Windows 10) and a BLE Device which will be the Master.
I installed Bluez and I can detect Bluetooth devices like my Smartphone but no device that only supports BLE. I want to download gattlib with pip install g... | Python using gattlib for BLE Scanning on Windows 10 | I want to create a BLE Connection between my Laptop (Windows 10) and a BLE Device which will be the Master.
I installed Bluez and I can detect Bluetooth devices like my Smartphone but no device that only supports BLE. I want to download gattlib with pip install gattlib but I got an OSError: Not supported OS which bring... | [
"gattlib is controlling bluez via dbus, bluez is linux only, so gattlib can't be used on windows.\ngattlib is basically wrapper for the dbus api of bluez in python.\nuse vm instead and mount your bt adapter to the vm in order to control it with bluez.\nwsl isn't supporting bluez right now\nWindows 11 and Android - ... | [
2,
0,
0,
0
] | [] | [] | [
"bluetooth_lowenergy",
"python",
"windows_10"
] | stackoverflow_0049238744_bluetooth_lowenergy_python_windows_10.txt |
Q:
plotting very long scientific numbers in python with pandas?
I need to manipulate very long scientific numbers in python and the pandas dataframe format seems convenient... except I can't plot. For instance, the following baby code:
import pandas as pd
import matplotlib.pyplot as plt
import decimal as dec
obs={}
d... | plotting very long scientific numbers in python with pandas? | I need to manipulate very long scientific numbers in python and the pandas dataframe format seems convenient... except I can't plot. For instance, the following baby code:
import pandas as pd
import matplotlib.pyplot as plt
import decimal as dec
obs={}
dec.getcontext().prec=10
obs['x']=[dec.Decimal(1),dec.Decimal(2),de... | [
"decimal.decimal is an object not a numeric value, you have to do the conversion before plotting!\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport decimal as dec\nobs={}\ndec.getcontext().prec=10\nobs['x']=[dec.Decimal(1),dec.Decimal(2),dec.Decimal(3)]\nobs['y']=[dec.Decimal(1),dec.Decimal(2),dec.Decim... | [
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074642136_pandas_python.txt |
Q:
Python memory management and garbage collection
I am currently working on an example to understand Python memory management and garbage collection. In my example, I create a variable (x = 10), collect its id, delete it, initiate garbage collector and check if I can still access object in heap by its id (using ctyp... | Python memory management and garbage collection | I am currently working on an example to understand Python memory management and garbage collection. In my example, I create a variable (x = 10), collect its id, delete it, initiate garbage collector and check if I can still access object in heap by its id (using ctypes).
I think it would return 0 or an error but surpri... | [
"Few things come into play, but here's a simple counterexample:\nimport ctypes\nimport gc\nx = 1\nfor _ in range(10):\n x += x\nid_1st_obj = id(x)\n\ndel x\ngc.collect()\n\nprint(ctypes.cast(id_1st_obj, ctypes.py_object).value)\n\nIf you comment del x, you get 1024. If you don't, we get some \"random\" number.\n... | [
0
] | [] | [] | [
"garbage_collection",
"heap_memory",
"memory_management",
"python"
] | stackoverflow_0074642256_garbage_collection_heap_memory_memory_management_python.txt |
Q:
ModuleNotFoundError while executing a bazel script
I have a python file main.py in which I am importing github package [import github]
I have created a build file as follows:
py_binary(
name = "main",
srcs = ["main.py"],
visibility = ["//visibility:public"]
)
When I run this through Bazel command, baz... | ModuleNotFoundError while executing a bazel script | I have a python file main.py in which I am importing github package [import github]
I have created a build file as follows:
py_binary(
name = "main",
srcs = ["main.py"],
visibility = ["//visibility:public"]
)
When I run this through Bazel command, bazel run: main, I am getting ModuleNotFoundError: No modul... | [
"You can build the python basic bazel example using this link for Bazel Python code build. This. is a good reference to start a one\n"
] | [
0
] | [] | [] | [
"bazel",
"build",
"modulenotfounderror",
"python"
] | stackoverflow_0074342069_bazel_build_modulenotfounderror_python.txt |
Q:
How can I make a Venn diagram in Python of two lists of values 0 and 1 and get the intersection where both values are 1?
I have two lists of the same length of 0s and 1s: e.g. a = [0,0,0,1,1,0,1], b = [0,1,0,1,0,1,1] and want to get a Venn diagram which has the intersection as the sum of values which are both 1, s... | How can I make a Venn diagram in Python of two lists of values 0 and 1 and get the intersection where both values are 1? | I have two lists of the same length of 0s and 1s: e.g. a = [0,0,0,1,1,0,1], b = [0,1,0,1,0,1,1] and want to get a Venn diagram which has the intersection as the sum of values which are both 1, so in this case 2 values would be 1 in the same position.
How can I achieve this?
Thanks in advance!
I tried something like ven... | [
"You need to implement the logic to count the elements in each subset and pass the result in a tuple as the subsets parameter.\nimport pandas as pd\nfrom matplotlib_venn import venn2\nfrom matplotlib import pyplot as plt\n\ndata = { \"A\": [0,0,0,1,1,0,1], \"B\": [0,1,0,1,0,1,1] }\n\ndf = pd.DataFrame(data)\n\n# Cr... | [
0
] | [] | [] | [
"python",
"venn"
] | stackoverflow_0074639775_python_venn.txt |
Q:
How to overwrite specific page of PDF with another page of another PDF with Python's PyPDF2
I want to overwrite the first page of a PDF with another page of another PDF using the PyPDF2 library in Python.
For more detail, I have two separate PDFs (let's call them overwritten.pdf and other.pdf) and I want to replac... | How to overwrite specific page of PDF with another page of another PDF with Python's PyPDF2 | I want to overwrite the first page of a PDF with another page of another PDF using the PyPDF2 library in Python.
For more detail, I have two separate PDFs (let's call them overwritten.pdf and other.pdf) and I want to replace the first (it doesn't have to be the first) page of overwritten.pdf with a specific page of oth... | [
"I don't know if you can literally \"replace a page\" with PyPDF2. I would use the merge function. Example from the PyPDF2 web site:\n\nfrom PyPDF2 import PdfMerger\n\nmerger = PdfMerger()\n\ninput1 = open(\"document1.pdf\", \"rb\")\ninput2 = open(\"document2.pdf\", \"rb\")\ninput3 = open(\"document3.pdf\", \"rb\")... | [
3,
0
] | [] | [] | [
"pdf",
"pypdf2",
"python",
"python_3.x"
] | stackoverflow_0074587276_pdf_pypdf2_python_python_3.x.txt |
Q:
Parse setup.py without setuptools
I'm using python on my ipad and need a way to grab the name, version, packages etc from a packages setup.py. I do not have access to setuptools or distutils. At first I thought that I'd parse setup.py but that does not seem to be the answer as there are many ways to pass args to s... | Parse setup.py without setuptools | I'm using python on my ipad and need a way to grab the name, version, packages etc from a packages setup.py. I do not have access to setuptools or distutils. At first I thought that I'd parse setup.py but that does not seem to be the answer as there are many ways to pass args to setup(). I'd like to create a mock setup... | [
"No kidding. This worked on python 3.4.3 and 2.7.6 ;)\nexport VERSION=$(python my_package/setup.py --version)\n\ncontents of setup.py:\nfrom distutils.core import setup\n\nsetup(\n name='bonsai',\n version='0.0.1',\n packages=['my_package'],\n url='',\n license='MIT',\n author='',\n author_emai... | [
10,
5,
1,
0,
0
] | [] | [] | [
"python",
"python_2.7",
"setuptools"
] | stackoverflow_0027790297_python_python_2.7_setuptools.txt |
Q:
why I can't run terminal pygame?
recently I watch a youtube video learing pygame for 90 min
I write the exactly code that they guide on the video
import pygame
WIDTH, HEIGHT = 900, 500
WIN = pygame.display.set_mode((WIDTH,HEIGHT))
def main() :
run = True
while run :
for event in pygame.event.get... | why I can't run terminal pygame? | recently I watch a youtube video learing pygame for 90 min
I write the exactly code that they guide on the video
import pygame
WIDTH, HEIGHT = 900, 500
WIN = pygame.display.set_mode((WIDTH,HEIGHT))
def main() :
run = True
while run :
for event in pygame.event.get():
if event.type == pygam... | [
"You code in main() is never started really because of this block:\nif __name__ == \"__name__\":\n main()\n\nSo all you see is effect of pygame.display.set_mode() and then program terminates. Proper condition should look like this:\nif __name__ == \"__main__\":\n main()\n\nAlso you should move pygame.display.... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074642384_python.txt |
Q:
Filtering Data from Firestore in Django, passing to HTML template
I have data stored in Firestore and i would like to get data from a collection, filter it and publish it in HTML template.
I am using Django as the framework.
VIEWS.py
from django.shortcuts import render
import pyrebase
from firebase_admin import fi... | Filtering Data from Firestore in Django, passing to HTML template | I have data stored in Firestore and i would like to get data from a collection, filter it and publish it in HTML template.
I am using Django as the framework.
VIEWS.py
from django.shortcuts import render
import pyrebase
from firebase_admin import firestore
import datetime
db = firestore.Client()
config = {
"apiKe... | [
"instead of creating a stream/snapshot of the event_info subCollection, why don't you create a query snapshot/stream of the event_info subCollection which will only return data that satisfies your query filter only::\nI am inferring from this section of your code:\nnba_events = db.collection('xxxx_au').document('ba... | [
0,
0
] | [] | [] | [
"datetime",
"django",
"firebase",
"google_cloud_firestore",
"python"
] | stackoverflow_0074636064_datetime_django_firebase_google_cloud_firestore_python.txt |
Q:
Stop tkinter from flashing when switching Canvas PhotoImages?
My tkinter user-interface involves two large Canvas widgets that are used to display photographs. The photographs update periodically, since they are being fed from live cameras. Problem: with some probability, the Canvas flashes white as it switches ph... | Stop tkinter from flashing when switching Canvas PhotoImages? | My tkinter user-interface involves two large Canvas widgets that are used to display photographs. The photographs update periodically, since they are being fed from live cameras. Problem: with some probability, the Canvas flashes white as it switches photographs. This makes for a very irritating display. I cannot inclu... | [
"Thank you, Lone Lunatic, for highlighting the problem. This line:\nself.photoImage = ImageTk.PhotoImage(image=image1)\n\nwith some probability allows the prior PhotoImage to be garbage collected before the following line displays the new one, and that leaves a white interval. Quite simple… if you have your head ar... | [
0
] | [] | [] | [
"canvas",
"python",
"tkinter",
"tkinter_photoimage"
] | stackoverflow_0074615737_canvas_python_tkinter_tkinter_photoimage.txt |
Q:
Can't get code to execute at certain time
I am trying to get some code to execute at a certain time but I can't figure out what the problem is here. Please help?
import datetime
dt=datetime
set_time=dt.time(12,53)
timenow=dt.datetime.now()
time=False
while not time:
if timenow==set_time:
print("yeeehaaa")
... | Can't get code to execute at certain time | I am trying to get some code to execute at a certain time but I can't figure out what the problem is here. Please help?
import datetime
dt=datetime
set_time=dt.time(12,53)
timenow=dt.datetime.now()
time=False
while not time:
if timenow==set_time:
print("yeeehaaa")
time=True
break
else:
print("naaaaa")
... | [
"First of all you have to update the time inside the loop or it will always be comparing the same timenow to set_time, then convert all to just an hour/minute string and compare\nimport datetime\ndt=datetime\nset_time=str(dt.time(14,19))[0:5]\ntimenow=dt.datetime.now().time()\ntime=False\nwhile not time:\n timenow=... | [
3,
0
] | [] | [] | [
"jupyter_notebook",
"python"
] | stackoverflow_0074642337_jupyter_notebook_python.txt |
Q:
How do I access nested elements inside a json array in python
I want to iterate over the below json array to extract all the referenceValues and the corresponding paymentIDs into one
{
"payments": [{
"paymentID": "xxx",
"externalReferences": [{
"referenceKind": "TRADE_ID",
... | How do I access nested elements inside a json array in python | I want to iterate over the below json array to extract all the referenceValues and the corresponding paymentIDs into one
{
"payments": [{
"paymentID": "xxx",
"externalReferences": [{
"referenceKind": "TRADE_ID",
"referenceValue": "xxx"
}, {
"referenceKind"... | [
"Looking at your structure, first you have to iterate through every dictionary in payments, then iterate through their external references. So the below code should extract all reference values and their payment IDs to a dictionary (and append to a list)\nrefVals = [] # List of all reference values\n\nfor payment i... | [
3
] | [] | [] | [
"arrays",
"json_arrayagg",
"python"
] | stackoverflow_0074642364_arrays_json_arrayagg_python.txt |
Q:
Merging and deleting duplicate items within a list of dictionaries
I have a list of dictionaries
[{'elementid': 'BsWfsElement.1.1', 'obstime': '2022-07-11T20:00:05', 'lon': '59.86400', 'lat': '32.05570', 'paramname': 'multiplicity', 'paramvalue': '4'}, {'elementid': 'BsWfsElement.1.2', 'obstime': '2022-07-11T20:00... | Merging and deleting duplicate items within a list of dictionaries | I have a list of dictionaries
[{'elementid': 'BsWfsElement.1.1', 'obstime': '2022-07-11T20:00:05', 'lon': '59.86400', 'lat': '32.05570', 'paramname': 'multiplicity', 'paramvalue': '4'}, {'elementid': 'BsWfsElement.1.2', 'obstime': '2022-07-11T20:00:05', 'lon': '59.86400', 'lat': '32.05570', 'paramname': 'peak_current',... | [
"from collections import defaultdict\n\ncombined_elements = defaultdict(dict)\nfor element in elements:\n # get values\n elementid = element['elementid'].rsplit('.',1)[0]\n paramname = element['paramname']\n paramvalue = element['paramvalue']\n # remove keys\n for key in ['elementid','paramname','... | [
0,
0
] | [] | [] | [
"dictionary",
"python",
"xml"
] | stackoverflow_0074642259_dictionary_python_xml.txt |
Q:
How to grab substring which meets certain requirements in python?
I have a python string that consists of "0", "1" and "x". I would to know what is the bit location of x in the string. eg. string1= '0100xx11xxx0x1' and the output is [(4,5),(8,10),(12)]. x appears in bit locations 4 to 5, locations 8 to 10, and loc... | How to grab substring which meets certain requirements in python? | I have a python string that consists of "0", "1" and "x". I would to know what is the bit location of x in the string. eg. string1= '0100xx11xxx0x1' and the output is [(4,5),(8,10),(12)]. x appears in bit locations 4 to 5, locations 8 to 10, and location 12. The following scripts are written in python; however, the res... | [
"Here's the solution using regex:\nimport re\nstring1= '0100xx11xxx0x1'\nmatches = []\nfor match in re.finditer(r'x+',string1): # iterates over re.Match object\n if match.start() == match.end()-1: matches.append(tuple([match.start()])) # if you want tuple else remove tuple() and []\n else: matches.append((mat... | [
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074638079_python.txt |
Q:
How can I trigger a Airflow DAG through a REST API , DAG is hosted in google cloud composer?
i want to trigger the dag externally
I was unable to find the solution , i'm new to programming
A:
You can trigger a DAG externally in a several ways :
Solution 1 :
trigger a DAG with gcloud cli and gcloud composer comma... | How can I trigger a Airflow DAG through a REST API , DAG is hosted in google cloud composer? | i want to trigger the dag externally
I was unable to find the solution , i'm new to programming
| [
"You can trigger a DAG externally in a several ways :\nSolution 1 :\ntrigger a DAG with gcloud cli and gcloud composer command :\n gcloud composer environments run ENVIRONMENT_NAME \\\n --location LOCATION \\\n dags trigger -- DAG_ID\n\nReplace :\n\nENVIRONMENT_NAME with the name of the environment.\nLOCATIO... | [
0
] | [] | [] | [
"airflow",
"google_cloud_composer",
"python"
] | stackoverflow_0074642344_airflow_google_cloud_composer_python.txt |
Q:
Can you override a function from a class outside of a class in Python
Can you override a function from a class, like:
class A:
def func():
print("Out of A")
classA = A
# Is something like this possible
def classA.func():
print("Overrided!")
Wanted Output:
Overrided
I googled "python override fun... | Can you override a function from a class outside of a class in Python | Can you override a function from a class, like:
class A:
def func():
print("Out of A")
classA = A
# Is something like this possible
def classA.func():
print("Overrided!")
Wanted Output:
Overrided
I googled "python override function", "python override function from class" and so on but couldnt find a... | [
"You most likely shouldn't do this. If you want to change a single part of some class, make a new class that inherits from it and reimplement the parts you want changed:\nclass A:\n @staticmethod\n def func():\n print(\"Out of A\")\n\nclassA = A\n\nclass B(A):\n @staticmethod\n def func():\n ... | [
0
] | [] | [] | [
"class",
"function",
"overriding",
"python"
] | stackoverflow_0074642654_class_function_overriding_python.txt |
Q:
Find the first two elements that are out of order and swap them
hoping someone can help me with my code. I'm new to python and software development. I'm trying to find the first two elements that are out of order and swap them.
arr = [5, 22, 29, 39, 19, 51, 78, 96, 84]
i = 0
while (i < arr.len() - 1) and (arr[i] <... | Find the first two elements that are out of order and swap them | hoping someone can help me with my code. I'm new to python and software development. I'm trying to find the first two elements that are out of order and swap them.
arr = [5, 22, 29, 39, 19, 51, 78, 96, 84]
i = 0
while (i < arr.len() - 1) and (arr[i] < arr[i+1]):
i += i
print(i)
arr[i] = arr[i+1]
arr[i+1] = arr[i]... | [
"Try this:\narr = [1, 2, 8, 4, 5, 6] \nfor i in range(len(arr)-1):\n if arr[i] > arr[i+1]:\n arr[i], arr[i+1] = arr[i+1], arr[i]\n break\nprint(arr)\n\n",
"arr = [5,22,29,39,19,51,78,96,84]\n\nfor i in range(len(arr)):\n if arr[i]>arr[i+1]:\n temp = arr[i]\n arr[i] = arr[i+1]\... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0074642575_python.txt |
Q:
How to set up Kafka as a dependency when using Delta Lake in PySpark?
This is the code to set up Delta Lake as part of a regular Python script, according to their documentation:
import pyspark
from delta import *
builder = pyspark.sql.SparkSession.builder.appName("MyApp") \
.config("spark.sql.extensions", "io... | How to set up Kafka as a dependency when using Delta Lake in PySpark? | This is the code to set up Delta Lake as part of a regular Python script, according to their documentation:
import pyspark
from delta import *
builder = pyspark.sql.SparkSession.builder.appName("MyApp") \
.config("spark.sql.extensions", "io.delta.sql.DeltaSparkSessionExtension") \
.config("spark.sql.catalog.sp... | [
"Turns out that Delta overwrites any packages provided in spark.jars.packages if you're using configure_spark_with_delta_pip (source). The proper way is to make use of the extra_packages parameter when setting up your Spark Session:\nimport pyspark\nfrom delta import *\n\npackages = [\n \"org.apache.spark:spark-... | [
0
] | [] | [] | [
"apache_kafka",
"databricks",
"delta_lake",
"pyspark",
"python"
] | stackoverflow_0074642812_apache_kafka_databricks_delta_lake_pyspark_python.txt |
Q:
Python: Gaussian filtering an N-channel image along only spatial dimensions?
I have an HxWxN image arr that I want to Gaussian blur.
scipy.ndimage.gaussian_filter seems to treat the image as a generic array and also blur along the final channel dimension. The desired behavior is Gaussian blurring arr[:, :, i] inde... | Python: Gaussian filtering an N-channel image along only spatial dimensions? | I have an HxWxN image arr that I want to Gaussian blur.
scipy.ndimage.gaussian_filter seems to treat the image as a generic array and also blur along the final channel dimension. The desired behavior is Gaussian blurring arr[:, :, i] independently for all is and then concatenating the resultant slices back into an HxWx... | [
"Using scipy.ndimage.gaussian_filter\nSolution\nTo Gaussian blur only the spatial dimensions H and W of an HxWxN image arr with a standard deviation of 1.6, use:\nstd=1.6\ngaussian_filter(arr, sigma=(std, std, 0))\n\nExplanation\nAccording to the SciPy Docs scipy.ndimage.gaussian_filter allows to specify the standa... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0067302611_python.txt |
Q:
How to solve ERROR: Failed building wheel for psycopg2?
I'm having issues building wheel for psycopg2 thru pip install -r requirements.txt. I'm on ubuntu 20.04 + python 3.8.5 + venv.
This is my requirements.txt:
amqp==2.6.1
anyjson==0.3.3
asgiref==3.2.10
billiard==3.6.3.0
brotlipy==0.7.0
celery==4.4.7
celery-progr... | How to solve ERROR: Failed building wheel for psycopg2? | I'm having issues building wheel for psycopg2 thru pip install -r requirements.txt. I'm on ubuntu 20.04 + python 3.8.5 + venv.
This is my requirements.txt:
amqp==2.6.1
anyjson==0.3.3
asgiref==3.2.10
billiard==3.6.3.0
brotlipy==0.7.0
celery==4.4.7
celery-progress==0.0.12
certifi==2020.6.20
cffi==1.14.2
chardet==3.0.4
cr... | [
"Instead pip command use:\nsudo apt-get install libpq-dev\n\nthen use:\npip install psycopg2\n\n",
"On Ubuntu, do you can install psycopg2-binary\npip install psycopg2-binary\n\n",
"Looks like you need to install libpq-dev according to this Problems compiling and installing psycopg2.\npip install libpq-dev shou... | [
30,
4,
2,
0
] | [] | [] | [
"django",
"linux",
"psycopg2",
"python",
"python_3.x"
] | stackoverflow_0065821330_django_linux_psycopg2_python_python_3.x.txt |
Q:
How to make an automatic email list with get requests in python
This is my website food.jackunderwood.org it basically uses a get request to retrieve a JSON file from my school's lunch provider. It then goes through the JSON file and writes it on the website. I want to have an Email List where Monday-Friday it sen... | How to make an automatic email list with get requests in python | This is my website food.jackunderwood.org it basically uses a get request to retrieve a JSON file from my school's lunch provider. It then goes through the JSON file and writes it on the website. I want to have an Email List where Monday-Friday it sends an email at 7:00 AM to every person that has signed up through the... | [
"Requests library isn't meant to send emails, because its using HTTP protocol, however emails use SMTP. I advice you to use smtplib.\nimport smtplib\nfrom email.mime.text import MIMEText\n\nsender = 'admin@example.com'\nreceivers = ['info@example.com']\n\n\nport = 1025\nmsg = MIMEText('This is test mail')\n\nmsg['S... | [
0
] | [] | [] | [
"email",
"html",
"html_email",
"javascript",
"python"
] | stackoverflow_0074642756_email_html_html_email_javascript_python.txt |
Q:
How can I redirect python print statement to browser console
So basically I am making a flask application. I have few python print statement to mark checkpoints (debugging). Instead of print those statements in python console . I want it to be in browser console (i.e. console.log)
When I do:
print("ok")
It should ... | How can I redirect python print statement to browser console | So basically I am making a flask application. I have few python print statement to mark checkpoints (debugging). Instead of print those statements in python console . I want it to be in browser console (i.e. console.log)
When I do:
print("ok")
It should also print ok in browser log( like javascript console.log). Is the... | [] | [] | [
"you can't do it but you can do only in javascript\n"
] | [
-1
] | [
"python"
] | stackoverflow_0050794816_python.txt |
Q:
Closing firebase connection
I have 3 python files chained into one file like this:
#chained.py
import file1
import file2
import file3
Every file in chained.py initializes a firebase admin object with the firebase_admin.initialize_app(cred) method. When I run the three files separately everything works as expected... | Closing firebase connection | I have 3 python files chained into one file like this:
#chained.py
import file1
import file2
import file3
Every file in chained.py initializes a firebase admin object with the firebase_admin.initialize_app(cred) method. When I run the three files separately everything works as expected. When I run chained.py I get the... | [
"You can check if the firebase app has already been initialized using the below code.\nimport firebase_admin\nfrom firebase_admin import credentials, initialize_app, storage\n\nFIREBASE_STORAGE_PATH = \"firebase_storage_path_here\"\n\nif not firebase_admin._apps:\n cred = credentials.Certificate(JSON_FILE)\n ... | [
0
] | [] | [] | [
"firebase",
"google_cloud_firestore",
"python"
] | stackoverflow_0071002596_firebase_google_cloud_firestore_python.txt |
Q:
How to keep selected values in html in flask app
This if my html file and i just want to keep the selected values in the dropdown menu after clicked. That's only my problem I hope for your response. I try a lot of methods but I can't solve my problem. Thankyou for the help
<form action="{{url_for('values')}}" met... | How to keep selected values in html in flask app |
This if my html file and i just want to keep the selected values in the dropdown menu after clicked. That's only my problem I hope for your response. I try a lot of methods but I can't solve my problem. Thankyou for the help
<form action="{{url_for('values')}}" method='POST'>
<div class="s1">
<div class="s1_lbl"... | [
"Frontend\nYou can save selected data in localstorage when you click the button and then select the option which its value is equal to the save data.\nOR\nBackend\nuse session storage\nthis code snippet is frontend solution, link this javascript code to your html and it should work fine\n\n\nlet btn = document.quer... | [
0
] | [] | [] | [
"flask",
"html",
"python"
] | stackoverflow_0074642578_flask_html_python.txt |
Q:
Checking if a .cmd file was executed successfully with python
I wrote a script that executes certain .cmd files. I'm trying to find a way to check if the execution finished with errors or not. This is how the final line of the .cmd file looks like, it shows you the number of warnings and errors:
https://i.stack.im... | Checking if a .cmd file was executed successfully with python | I wrote a script that executes certain .cmd files. I'm trying to find a way to check if the execution finished with errors or not. This is how the final line of the .cmd file looks like, it shows you the number of warnings and errors:
https://i.stack.imgur.com/y6K1m.png (sorry i do not have enough rep to make the image... | [
"Batch scripts usually have a return code that you can check if it completed successfully.\nCheck this link for the exit codes\nAnd check this question for the python code to get them\n"
] | [
0
] | [] | [] | [
"cmd",
"python"
] | stackoverflow_0074642763_cmd_python.txt |
Q:
How do I convert a Django QuerySet into list of dicts?
How can I convert a Django QuerySet into a list of dicts? I haven't found an answer to this so I'm wondering if I'm missing some sort of common helper function that everyone uses.
A:
Use the .values() method:
>>> Blog.objects.values()
[{'id': 1, 'name': 'Be... | How do I convert a Django QuerySet into list of dicts? | How can I convert a Django QuerySet into a list of dicts? I haven't found an answer to this so I'm wondering if I'm missing some sort of common helper function that everyone uses.
| [
"Use the .values() method: \n>>> Blog.objects.values()\n[{'id': 1, 'name': 'Beatles Blog', 'tagline': 'All the latest Beatles news.'}],\n>>> Blog.objects.values('id', 'name')\n[{'id': 1, 'name': 'Beatles Blog'}]\n\nNote: the result is a QuerySet which mostly behaves like a list, but isn't actually an instance of li... | [
269,
36,
19,
7,
4,
3,
2,
1,
1,
1
] | [
"im a newbie in python and i love @David Wolever answer\nuser = Blog.objects.all()\nuser = list(user.values(\"username\", \"id\"))\n\nin my case i use this to print username\nuser = Blog.objects.all()\nuser = list(user.values(\"username\"))\nname = []\nfor i in user:\n name.append(i[\"username\"])\nprint(name)\n... | [
-1,
-2
] | [
"django",
"python"
] | stackoverflow_0007811556_django_python.txt |
Q:
How to auto-wrap widget in tkinter?
I saw this function (layout?) in android a few years ago, but I can't remind what is this function name...
I need an auto-replace widget.
if the new widget' width meets the end of the window, I want to move that widget new line.
The below is my expected output.
I Think, get the... | How to auto-wrap widget in tkinter? | I saw this function (layout?) in android a few years ago, but I can't remind what is this function name...
I need an auto-replace widget.
if the new widget' width meets the end of the window, I want to move that widget new line.
The below is my expected output.
I Think, get the width and calculate new widget position... | [
"Since tkinter has a canvas which gives you absolute control over positioning, you can accomplish this with just a little bit of math when adding items. You'll have to add code to reposition the widgets when the window is resized.\nA simpler approach is to use the text widget, which supports embedded images or widg... | [
5,
0
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0069846517_python_tkinter.txt |
Q:
cv2.error: OpenCV(4.5.2) :-1: error: (-5:Bad argument) in function 'rectangle'
hello guys i'm working on my project with easy ocr for text detection i got some errors, but i don't know how to fix it, it will be greatful if someone can help me?
here's few errors i get
cv2.error: OpenCV(4.5.2) :-1: error: (-5:Bad a... | cv2.error: OpenCV(4.5.2) :-1: error: (-5:Bad argument) in function 'rectangle' | hello guys i'm working on my project with easy ocr for text detection i got some errors, but i don't know how to fix it, it will be greatful if someone can help me?
here's few errors i get
cv2.error: OpenCV(4.5.2) :-1: error: (-5:Bad argument) in function 'rectangle'
Overload resolution failed:
Can't parse 'pt1'. Seq... | [
"cv2.rectangle expects int values, while easyocr can return floats. Try:\n top_left = (int(detection[0][0][0]), int(detection[0][0][1]))\n bottom_right = (int(detection[0][2][0]), int(detection[0][2][1]))\n\n"
] | [
0
] | [] | [] | [
"detection",
"easyocr",
"opencv",
"python",
"text"
] | stackoverflow_0074637234_detection_easyocr_opencv_python_text.txt |
Q:
Unable to spilt data using python
I have a data like below:
data = """1000
2000
3000
4000
5000
6000
7000
8000
9000
10000"""
Now, I want to sum up the elements that appear before the space and maintain the max_sum track with the sum of the next elements that appear before the empty line. So for me, it should b... | Unable to spilt data using python | I have a data like below:
data = """1000
2000
3000
4000
5000
6000
7000
8000
9000
10000"""
Now, I want to sum up the elements that appear before the space and maintain the max_sum track with the sum of the next elements that appear before the empty line. So for me, it should be the sum of 1000,2000,3000 = 6000 comp... | [
"You are trying to cast empty lines to int:\nmax_num = 0\nsum = 0\nfor line in data:\n print(line)\n if line.strip():\n sum = sum + int(line)\n if line in ['\\n', '\\r\\n']:\n sum=0\n max_num = max(max_num, sum)\n\n",
"Here's a quick oneliner:\ndata = \"\"\"1000\n2000\n3000\n\n4000\n\n50... | [
2,
2,
1,
1,
1,
1
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074642735_python_python_3.x.txt |
Q:
Exporting .kml or .kmz from RShiny (with Python)
I had this problem for a few weeks. I couldn't figure out how to get RShiny to allow export of .kml or .kmz files, specifically ones created from a sourced Python package.
I finally figured it out day before yesterday. I don't know how to just make an answer, so I w... | Exporting .kml or .kmz from RShiny (with Python) | I had this problem for a few weeks. I couldn't figure out how to get RShiny to allow export of .kml or .kmz files, specifically ones created from a sourced Python package.
I finally figured it out day before yesterday. I don't know how to just make an answer, so I will add it as the accepted answer for anyone else who ... | [
"I searched pretty much everywhere I could think of to solve this problem, but nothing helped. I finally got it through trial and error of my code on both the R and Python sides. Here's what I found works (in RShiny):\n\nIn ui, just make sure there is a downloadButton with the id of whatever you are trying to expor... | [
0
] | [] | [] | [
"export",
"kml",
"python",
"r",
"shiny"
] | stackoverflow_0074642898_export_kml_python_r_shiny.txt |
Q:
Reading semicolon separated data with read_html
I want to read winequality-white.csv data using pandas.read_html() function.
Here is my code:
import pandas as pd
wine = pd.DataFrame(
pd.read_html(
"https://github.com/shrikant-temburwar/Wine-Quality-Dataset/blob/master/winequality-white.csv",
t... | Reading semicolon separated data with read_html | I want to read winequality-white.csv data using pandas.read_html() function.
Here is my code:
import pandas as pd
wine = pd.DataFrame(
pd.read_html(
"https://github.com/shrikant-temburwar/Wine-Quality-Dataset/blob/master/winequality-white.csv",
thousands=";",
header=0,
)[0]
)
... but t... | [
"Alright, here is an option using pd.read_html:\nimport pandas as pd\n\nwine = pd.read_html(\n \"https://github.com/shrikant-temburwar/Wine-Quality-Dataset/blob/master/winequality-white.csv\",\n header=0\n)[0]\n\nwine.drop('Unnamed: 0', axis=1, inplace=True)\nheaders = wine.columns[0].replace('\"', '').split(... | [
0
] | [
"you could probably better to use the rawdatacontent address of github to remove the problem due to different html interface.\nhere is what you could do\nimport pandas as pd\nimport requests\nimport io\nurl = \"https://raw.githubusercontent.com/shrikant-temburwar/Wine-Quality-Dataset/master/winequality-white.csv\"\... | [
-1
] | [
"pandas",
"python"
] | stackoverflow_0074640187_pandas_python.txt |
Q:
Add counter to Folium map of markers that meet a specific condition
I work for a small ISP and have written a script to collect data from the switches that is then fed into Folium to produce a map of subscribers and their operating status as online of offline.
I need to add a counter, maybe through a div, that wou... | Add counter to Folium map of markers that meet a specific condition | I work for a small ISP and have written a script to collect data from the switches that is then fed into Folium to produce a map of subscribers and their operating status as online of offline.
I need to add a counter, maybe through a div, that would allow for markers of any status to be counted and displayed in the win... | [
"Here is a description of how to add text or images to folium maps:\nhttps://stackoverflow.com/a/65105474/13843906\ntext will be moving with the map, but image seems to be at a fixed position in map window\n"
] | [
0
] | [] | [] | [
"dashboard",
"folium",
"html",
"maps",
"python"
] | stackoverflow_0074618598_dashboard_folium_html_maps_python.txt |
Q:
Python begginer - Can someone tell me why this loop don't finish?
def is_power_of_two(n):
# Check if the number can be divided by two without a remainder
while n % 2 == 0:
n = n / 2
# If after dividing by two the number is 1, it's a power of two
if n == 1:
return True
if n != 0:
return False
... | Python begginer - Can someone tell me why this loop don't finish? | def is_power_of_two(n):
# Check if the number can be divided by two without a remainder
while n % 2 == 0:
n = n / 2
# If after dividing by two the number is 1, it's a power of two
if n == 1:
return True
if n != 0:
return False
print(is_power_of_two(0)) # Should be False
print(is_power_of_two(1)) ... | [
"while n % 2 == 0: will turns out to be a infinate loop.\nThis happening because\nFirst number input is 0\nwhile n % 2 == 0: ---> 0 ==0 --> True\nWhile True:\n #This is infinate loop.\n\nCode correction\nTo avoid this check if n is zero or not before while.\ndef is_power_of_two(n):\n\n if n ==0:\n return... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074642951_python.txt |
Q:
Tkinter: use after five times and then stop
In my app I'm trying to have a blinking image. This image should be blinking just five times and then stay still in the frame for five seconds. Right now I've menaged to make the image flash, but I don't know how to make it blink just five times and then stay still.
I've... | Tkinter: use after five times and then stop | In my app I'm trying to have a blinking image. This image should be blinking just five times and then stay still in the frame for five seconds. Right now I've menaged to make the image flash, but I don't know how to make it blink just five times and then stay still.
I've tried using a for loop but it did not solve it. ... | [
"Keep track of how many times you've 'blinked', then use after_cancel() to stop when you want.\ndef __init__(self, parent, *args, **kwargs):\n ... # code removed for brevity\n self.blink_count = 0 # initialize blink counter\n\ndef blink_img(self):\n current_color = self.first_img_label.cget(\"foreground\... | [
1
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0074642888_python_tkinter.txt |
Q:
scikitlearn SVR giving same values for predictions (have tried scaling)
I have a battery dataframe with rows representing various cycles and a set of features for that cycle:
As an example row 1:
df = pd.DataFrame(columns=['Ecell_V', 'I_mA', 'EnergyCharge_W_h', 'QCharge_mA_h',
'EnergyDischarge_W_h', 'QDisch... | scikitlearn SVR giving same values for predictions (have tried scaling) | I have a battery dataframe with rows representing various cycles and a set of features for that cycle:
As an example row 1:
df = pd.DataFrame(columns=['Ecell_V', 'I_mA', 'EnergyCharge_W_h', 'QCharge_mA_h',
'EnergyDischarge_W_h', 'QDischarge_mA_h', 'Temperature__C',
'cycleNumber', 'SOH', 'Cell'])
df.loc[0]... | [
"Using StandardScaler() on the X and y data corrected this issue, with an inverse called to return it to original values.\n"
] | [
0
] | [] | [] | [
"python",
"regression",
"scikit_learn",
"svm"
] | stackoverflow_0074640628_python_regression_scikit_learn_svm.txt |
Q:
Errors with mlflow and machine learning project using XGBoost and hyperopt in python
I'm experiencing some problems with a machine learning project.
I use XGBoost for forecast on warehouse items supply and i'm trying to select the best hyperparams with hyperopt and mlflow.
This is the code:
import pandas as pd
imp... | Errors with mlflow and machine learning project using XGBoost and hyperopt in python | I'm experiencing some problems with a machine learning project.
I use XGBoost for forecast on warehouse items supply and i'm trying to select the best hyperparams with hyperopt and mlflow.
This is the code:
import pandas as pd
import glob
import holidays
import numpy as np
import matplotlib.pyplot as plt
from scipy imp... | [
"It seems that the problem is related to the number of parallel worker setted. If i change PARALLELISM to some other values (< 8) it works.\n"
] | [
0
] | [] | [] | [
"hyperopt",
"mlflow",
"python",
"xgboost"
] | stackoverflow_0074387655_hyperopt_mlflow_python_xgboost.txt |
Q:
How to create multiple zip folders at once from a dataframe in Python
I have a dataframe consisting of users and a list of pdfs related to each of those users. The pdfs have no standard naming convention, there can be any number of pdfs to a list and the number of users is much longer than the example below.
impor... | How to create multiple zip folders at once from a dataframe in Python | I have a dataframe consisting of users and a list of pdfs related to each of those users. The pdfs have no standard naming convention, there can be any number of pdfs to a list and the number of users is much longer than the example below.
import pandas as pd
from zipfile import ZipFile
data = {'name':['aaron', 'ben',... | [
"I think you're making 3 mistakes:\n\nYou try to iterate over a newly created, empty zip-archive (sidenote: don't use zip as variable name, you're overriding a builtin function):\n zipfiles = ZipFile(user + \".zip\", 'w'),\n for zip in zipfiles:\n\n\nYou try to write every file in df[\"pdfs\"] in the user-zip... | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python",
"python_zipfile"
] | stackoverflow_0074640725_dataframe_pandas_python_python_zipfile.txt |
Q:
fill one dataframe with values from another
I have this Dataframe, which is null values that haven't been populated right.
Unidad Precio Combustible Año_del_vehiculo Caballos \
49 1 1000 Gasolina 1998.0 50.0
63 1 800 Gasolina 1998.0 50.... | fill one dataframe with values from another | I have this Dataframe, which is null values that haven't been populated right.
Unidad Precio Combustible Año_del_vehiculo Caballos \
49 1 1000 Gasolina 1998.0 50.0
63 1 800 Gasolina 1998.0 50.0
88 1 600 Gasolina ... | [
"df1.merge(df2, on='Año_Comunidad')\n\nAs a result you'll have one DataFrame where columns with same names will have a suffix _x for first DataFrame and _y for the second one.\nNow to fill in the blanks you can do this for each column:\ndf1.loc[df1[\"Año_x\"].isnull(),'Año_x'] = df1[\"Año_y\"]\n\nIf a row in Año is... | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074642291_pandas_python.txt |
Q:
Login with python to scrape pages
I need to scrape a page that requires login to access. But I couldn't do it for this web page. How can I do that?
I want to login on 'https://web.tvplus.com.tr/giris' And then scrape pages like: 'https://web.tvplus.com.tr/kanallar'
I haven't tried anything for the question. I do n... | Login with python to scrape pages | I need to scrape a page that requires login to access. But I couldn't do it for this web page. How can I do that?
I want to login on 'https://web.tvplus.com.tr/giris' And then scrape pages like: 'https://web.tvplus.com.tr/kanallar'
I haven't tried anything for the question. I do not know how to do it.
| [
"StackOverflow typically hates questions like these, but the book I used when I started my programming journey actually had a whole entire chapter on this:\nhttps://automatetheboringstuff.com/2e/chapter12/\nThe module you're looking to use is \"selenium\"; even though many would claim that there's better modules to... | [
0
] | [] | [] | [
"authentication",
"python",
"web_scraping"
] | stackoverflow_0074643063_authentication_python_web_scraping.txt |
Q:
Split 7 digit into separate columns in csv with python
Hi I have 100 data in csv file
I want to split 7 digit number into seprate columns with python
My csv file is like this:
A
1234567
Split into new columns:
B
C
D
E
F
G
H
1
2
3
4
5
6
7
I try
Splitdigit= df['A']>str.split(expand=true).add_perfix('A')
A:
... | Split 7 digit into separate columns in csv with python | Hi I have 100 data in csv file
I want to split 7 digit number into seprate columns with python
My csv file is like this:
A
1234567
Split into new columns:
B
C
D
E
F
G
H
1
2
3
4
5
6
7
I try
Splitdigit= df['A']>str.split(expand=true).add_perfix('A')
| [
"If you have strings, you can use:\nout = df['A'].astype(str).str.split('(?<=.)(?=.)', expand=True)\n\nOutput:\n 0 1 2 3 4 5 6\n0 1 2 3 4 5 6 7\n\nWith the column names:\nfrom string import ascii_uppercase\n\nout = (df['A'].astype(str).str.split('(?<=.)(?=.)', expand=True)\n .rename(colu... | [
0
] | [] | [] | [
"arrays",
"digits",
"pandas",
"python"
] | stackoverflow_0074643120_arrays_digits_pandas_python.txt |
Q:
How to check if the set with commas is infinite or finite?
I am trying to use the method math.isinf to find out if the set is infinite.
The set is
{...,-5,-4,-3,-2,-1,0,1,2,3,4,5,...}
import math
Infinte_set = {-math.inf,-5,-4,-3,-2,-1,0,1,2,3,4,5,math.inf}
print(math.isinf(Infinte_set))
I was expecting True or ... | How to check if the set with commas is infinite or finite? | I am trying to use the method math.isinf to find out if the set is infinite.
The set is
{...,-5,-4,-3,-2,-1,0,1,2,3,4,5,...}
import math
Infinte_set = {-math.inf,-5,-4,-3,-2,-1,0,1,2,3,4,5,math.inf}
print(math.isinf(Infinte_set))
I was expecting True or False but what I got is this:
TypeError ... | [
"You can pass the min value or max value of the set in math.isinf function to check for infinity.\nprint(math.isinf(min(Infinte_set)) or math.isinf(max(Infinte_set)))\n\nmath.isinf(min(Infinte_set)) -> min(Infinte_set) would be the minimum numerical value, in your case it would be -infinity.\nmath.isinf(max(Infinte... | [
0
] | [] | [] | [
"infinite",
"math",
"numbers",
"python",
"set"
] | stackoverflow_0074642968_infinite_math_numbers_python_set.txt |
Q:
time lapse of transport data in folium
I have data that resembles routes in the Netherlands. Now I want to show these routes on a folium map using some sort of timelapse.
The underneath code creates a folium map displaying all routes over the last few months.
I want however some sort of slide which you can drag to... | time lapse of transport data in folium | I have data that resembles routes in the Netherlands. Now I want to show these routes on a folium map using some sort of timelapse.
The underneath code creates a folium map displaying all routes over the last few months.
I want however some sort of slide which you can drag to show the routes of for example a specific d... | [
"look at this example which demonstrates how markers / lines are added depending on their timestamp. At the bottom of the map are controls for sliding through data\nhttps://nbviewer.org/github/python-visualization/folium/blob/main/examples/Plugins.ipynb#Timestamped-GeoJSON\n"
] | [
0
] | [] | [] | [
"folium",
"geopandas",
"python",
"time",
"timelapse"
] | stackoverflow_0074641964_folium_geopandas_python_time_timelapse.txt |
Q:
How to remove sprites shadow?
I'm trying to load this image without its shadow
I've tried getting the color key by printing the color where my mouse is and and then setting the images color key to that color. I also tried adding convert_alpha() when loading the image but it still didn't work. Am I just getting the... | How to remove sprites shadow? | I'm trying to load this image without its shadow
I've tried getting the color key by printing the color where my mouse is and and then setting the images color key to that color. I also tried adding convert_alpha() when loading the image but it still didn't work. Am I just getting the color wrong or is there another wa... | [
"I found out the true color of the shadow by using\npygame.image.load(...).convert()\nand then using that color as the colorkey (which works without .covert() )\n"
] | [
0
] | [] | [] | [
"pygame",
"python",
"python_3.x"
] | stackoverflow_0074642639_pygame_python_python_3.x.txt |
Q:
Use different Python version with virtualenv
How do I create a virtual environment for a specified version of Python?
A:
NOTE: For Python 3.3+, see The Aelfinn's answer below.
Use the --python (or short -p) option when creating a virtualenv instance to specify the Python executable you want to use, e.g.:
virtua... | Use different Python version with virtualenv | How do I create a virtual environment for a specified version of Python?
| [
"NOTE: For Python 3.3+, see The Aelfinn's answer below.\n\nUse the --python (or short -p) option when creating a virtualenv instance to specify the Python executable you want to use, e.g.:\nvirtualenv --python=\"/usr/bin/python2.6\" \"/path/to/new/virtualenv/\"\n\n",
"Since Python 3, the documentation suggests cr... | [
1901,
502,
217,
181,
113,
83,
41,
34,
28,
28,
23,
18,
13,
10,
8,
7,
7,
6,
6,
5,
4,
4,
4,
4,
3,
3,
3,
3,
2,
2,
2,
1,
1,
1,
1,
1,
1,
0,
0
] | [
"Suppose I want to use python 3.8 and I'm using MacOS.\nbrew install python@3.8\n\nThen,\npython3.8 -m venv venv\n\n",
"for windows only\n\ninstall the specific version of python in your pc\ngo the directory where you want to create the virtual environment\ntype cmd in the location bar in file explorer\non cmd ty... | [
-1,
-1
] | [
"python",
"virtualenv",
"virtualenvwrapper"
] | stackoverflow_0001534210_python_virtualenv_virtualenvwrapper.txt |
Q:
Pandas: expand group variable to encompass the first n obervations of the next group in a dataframe
Here is my df with an example of the two columns that I have to work (groupand value) with and an example of the output that I am trying to achieve(output_wanted):
egdf = pd.DataFrame({'group': ['A']*6+['B']*6+['C']... | Pandas: expand group variable to encompass the first n obervations of the next group in a dataframe | Here is my df with an example of the two columns that I have to work (groupand value) with and an example of the output that I am trying to achieve(output_wanted):
egdf = pd.DataFrame({'group': ['A']*6+['B']*6+['C']*5+['D']*6,
'value': list(range(1, 7))*2+list(range(1, 6))+list(range(1, 7)),
... | [
"Why not use shift and backfill the first two (n) rows?\negdf['output_wanted'] = egdf.group.shift(2).fillna(method='bfill')\n\nWhere 2 can be replaced by n of course. If needed DataFrame could be sorted by group first.\n"
] | [
1
] | [] | [] | [
"dataframe",
"group_by",
"pandas",
"python"
] | stackoverflow_0074642270_dataframe_group_by_pandas_python.txt |
Q:
bot returning the wrong number
I'm Trying to make a tax calculator but it's returning something strange..
Here's the function:
async def tax(args):
args3 = 5
protax= round(int(args)*args3/100)
if protax == 0:
protax = 1
return protax
here is where I call the function:
c.execute("SELECT price FROM ... | bot returning the wrong number | I'm Trying to make a tax calculator but it's returning something strange..
Here's the function:
async def tax(args):
args3 = 5
protax= round(int(args)*args3/100)
if protax == 0:
protax = 1
return protax
here is where I call the function:
c.execute("SELECT price FROM netflix ")
netfprice = c.fetchal... | [
"I feel really dumb after seeing my mistake...\nmy mistake was in the embed description.. Here:description=f\"tax:{netprice + withtax}\")\nI should've made it description=f\"tax:{newprice + withtax}\")\n"
] | [
0
] | [] | [] | [
"discord.py",
"pycord",
"python"
] | stackoverflow_0074642913_discord.py_pycord_python.txt |
Q:
Why is Django test cases checking actual DB and raising IntegrityError instead of just running in-memory?
When I run my tests with the DB empty (the actual application DB), everything goes fine. But when the DB has data, Django raises an IntegrityError for basically every test. The stact trace looks like the follo... | Why is Django test cases checking actual DB and raising IntegrityError instead of just running in-memory? | When I run my tests with the DB empty (the actual application DB), everything goes fine. But when the DB has data, Django raises an IntegrityError for basically every test. The stact trace looks like the following (but for every test):
======================================================================
ERROR: test_a... | [] | [] | [
"Are your tests classes childs of django.test.TestCase or unittest.TestCase?\nBecause with a db one should use django.test.TestCase...\n"
] | [
-2
] | [
"django",
"django_rest_framework",
"django_unittest",
"python",
"testing"
] | stackoverflow_0074607455_django_django_rest_framework_django_unittest_python_testing.txt |
Q:
zipfile and pandas failure mid-loop
I'm writing this on my phone, so a full code example is sorta out of the question at the moment, but I need some help.
I'm working on parsing a set of .csv files from a zipped infile, pulling out specific columns from each file, generating a new .csv with the chosen columns, and... | zipfile and pandas failure mid-loop | I'm writing this on my phone, so a full code example is sorta out of the question at the moment, but I need some help.
I'm working on parsing a set of .csv files from a zipped infile, pulling out specific columns from each file, generating a new .csv with the chosen columns, and then exporting the new dataframes to a z... | [
"I figured out where it was breaking. Sorry I forgot to update this question with the solution.\nThe issue was in the data of some of the files. Added automated badfile checking based on length of dataframe. Basically, the files causing issues only had 1 or 2 rows in column A but the good files had full tables of m... | [
0
] | [] | [] | [
"data_science",
"file_conversion",
"pandas",
"python",
"python_zipfile"
] | stackoverflow_0070537550_data_science_file_conversion_pandas_python_python_zipfile.txt |
Q:
Extracting all data validation formula values(dropdown) from excel sheet
How can we extract the data validation dropdown values(not just formulas/references or a single valued formula result) from a given excel sheet using python?
Currently openpyxl helps us to get the formulas but not the values directly. It even... | Extracting all data validation formula values(dropdown) from excel sheet | How can we extract the data validation dropdown values(not just formulas/references or a single valued formula result) from a given excel sheet using python?
Currently openpyxl helps us to get the formulas but not the values directly. It even fails in cases where file contain extensions(extLst) to the OOXML specificati... | [
"In order to obtain the results of a dynamic Excel formula you need to automate Excel itself, rather than just parse the worksheet file with an XML reader.\nHard to say this solution will fit all your cases, but it is a starting point. The Excel object model has a Validation Object, which contains all the informati... | [
0
] | [] | [] | [
"excel",
"openpyxl",
"python",
"win32com",
"xlwings"
] | stackoverflow_0074633059_excel_openpyxl_python_win32com_xlwings.txt |
Q:
read files without hardcoding path in python
I am writing a PySpark code to read PARQUET files from my local machine and process them. My directories and file paths look like this:
.
├── customer
│ └── day=20220815
│ └── part-00000-4dff7e82-411b-4940-bdb6-33acf5a189b4-c000.snappy.parquet
└── customer_inter... | read files without hardcoding path in python | I am writing a PySpark code to read PARQUET files from my local machine and process them. My directories and file paths look like this:
.
├── customer
│ └── day=20220815
│ └── part-00000-4dff7e82-411b-4940-bdb6-33acf5a189b4-c000.snappy.parquet
└── customer_interaction
└── day=20220815
└── part-00000... | [
"You can use the glob module, see https://www.geeksforgeeks.org/how-to-use-glob-function-to-find-files-recursively-in-python/ for examples.\nYou can also use pathlib which also as a glob module.\nIn your case, the command is:\nimport glob\n\n# Returns a list of names in list files.\nprint(\"Using glob.glob()\")\nfi... | [
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0074642657_python.txt |
Q:
apply function on two columns in python pandas with 2 arguments (convert GPS type to another)
so i have a database of X and Y coordinates as the ITM type and i want it as WGS-84 type.
i found a function from pyproj library thats convert and it works great but now i'm having troubles to apply this function on two s... | apply function on two columns in python pandas with 2 arguments (convert GPS type to another) | so i have a database of X and Y coordinates as the ITM type and i want it as WGS-84 type.
i found a function from pyproj library thats convert and it works great but now i'm having troubles to apply this function on two separate columns.
for example i want to convert this data :
Column x
Column y
643234
234562
... | [
"https://github.com/geopandas/geopandas/issues/1400\nfrom pyproj import Transformer\n\ntrans = Transformer.from_crs(\n \"epsg:4326\",\n \"+proj=utm +zone=10 +ellps=WGS84\",\n always_xy=True,\n)\nxx, yy = trans.transform(My_data[\"LON\"].values, My_data[\"LAT\"].values)\nMy_data[\"X\"] = xx\nMy_data[\"Y\"] ... | [
0
] | [] | [] | [
"geolocation",
"pandas",
"pyproj",
"python"
] | stackoverflow_0074629073_geolocation_pandas_pyproj_python.txt |
Q:
VScode adding tick to dockerRun command
I'm trying to get the below to run a docker container command via VScode.
Within tasks.json I have:
{
"label": "docker-run: debug",
"type": "docker-run",
"dependsOn": [
"docker-build"
],
"python": {
"module": "simply.py"
},
"docker... | VScode adding tick to dockerRun command | I'm trying to get the below to run a docker container command via VScode.
Within tasks.json I have:
{
"label": "docker-run: debug",
"type": "docker-run",
"dependsOn": [
"docker-build"
],
"python": {
"module": "simply.py"
},
"dockerRun": {
"command": "python3 simply.py... | [
"This fixed itself upon closing and opening VScode\n"
] | [
0
] | [] | [] | [
"docker",
"docker_container",
"python",
"vscode_tasks"
] | stackoverflow_0074631992_docker_docker_container_python_vscode_tasks.txt |
Q:
Jupyter Notebook's terminal command not using correct conda environment
I have 2 conda environments installed:
- env1: base environment where jupyter-notebook is installed and started from
- env2: project environment with ipykernel installed
I manually added kernelspecs for the 2 environments following this guide.... | Jupyter Notebook's terminal command not using correct conda environment | I have 2 conda environments installed:
- env1: base environment where jupyter-notebook is installed and started from
- env2: project environment with ipykernel installed
I manually added kernelspecs for the 2 environments following this guide.
Everything works fine. sys.executable in 2 kernels show separate, correct p... | [
"install nb_conda and nb_conda_kernels into your base.\nconda install nb_conda nb_conda_kernels -n env1\n\nThis should give you the ability to change kernel in jupyter, and use the env2 kernel.\n",
"I would install jupyter notebook in the base env (not env1, not env2)\nThen install nb_conda_kernels in the base\ni... | [
1,
0
] | [] | [] | [
"conda",
"jupyter_notebook",
"python"
] | stackoverflow_0053440940_conda_jupyter_notebook_python.txt |
Q:
How to remove a single tick label on a plot, leaving the tick itself
I'd like to remove all but the first and last tick labels, but keep their ticks on a plot.
However, using the below code, all labels get removed
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots(1, 1)
ax.plot(np.arange(10... | How to remove a single tick label on a plot, leaving the tick itself | I'd like to remove all but the first and last tick labels, but keep their ticks on a plot.
However, using the below code, all labels get removed
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots(1, 1)
ax.plot(np.arange(10))
locs = ax.get_xticks()
labels = ax.get_xticklabels()
labels[1].set_tex... | [
"In\nPython - 3.9.10\nmatplotlib: 3.5.1\n\nUisng Tick_formatter\nplt.xticks(np.arange(min(locs), max(locs)+1, 2))\nax.xaxis.get_major_ticks()[1].draw = lambda *args:None\n\nGives #\n\nif you want to keep ticks\nplt.xticks(np.arange(min(locs), max(locs)+1, 2))\nlabels = [item.get_text() for item in ax.get_xticklabe... | [
1
] | [] | [] | [
"matplotlib",
"python",
"xticks"
] | stackoverflow_0074643201_matplotlib_python_xticks.txt |
Q:
Improving small images for data extraction
In Open CV or with Pillow library how can we improve below images for tesseract.
I tried below code with multiple options like thresholding, blur, enchance, however not able to improve.
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
print(pytesseract.image_to_string(img))
... | Improving small images for data extraction | In Open CV or with Pillow library how can we improve below images for tesseract.
I tried below code with multiple options like thresholding, blur, enchance, however not able to improve.
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
print(pytesseract.image_to_string(img))
img_medianBlur = cv2.blur(img, (3 , 3))
print... | [
"To improve the images for tesseract, you can try using some of the following techniques:\n\nIncrease the contrast of the image by using histogram equalization or\nstretching the intensity range of the image.\n\nimg = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\nequ = cv2.equalizeHist(img)\nprint(pytesseract.image_to_str... | [
0,
0
] | [] | [] | [
"image_processing",
"ocr",
"python",
"python_tesseract",
"tesseract"
] | stackoverflow_0074582794_image_processing_ocr_python_python_tesseract_tesseract.txt |
Q:
How do I pass a user-agent to panda's pd.read_html()?
some websites automatically decline requests due to lack of user-agent, and it's a hassle using bs4 to scrape many different types of tables.
This issue was resolved before through this code:
url = 'http://finance.yahoo.com/quote/A/key-statistics?p=A'
opener = ... | How do I pass a user-agent to panda's pd.read_html()? | some websites automatically decline requests due to lack of user-agent, and it's a hassle using bs4 to scrape many different types of tables.
This issue was resolved before through this code:
url = 'http://finance.yahoo.com/quote/A/key-statistics?p=A'
opener = urllib2.build_opener()
opener.addheaders = [('User-agent', ... | [
"read_html() accepts a URL and string, so u can set headers on request, and pandas ll read this resoponse like a text:\nimport pandas as pd\nimport requests\n\n\nurl = 'http://finance.yahoo.com/quote/A/key-statistics?p=A'\nresponse = requests.get(url, headers={'User-agent': 'Mozilla/5.0'})\ntables = pd.read_html(re... | [
0
] | [] | [] | [
"python",
"urllib2",
"urllib3",
"user_agent"
] | stackoverflow_0074642461_python_urllib2_urllib3_user_agent.txt |
Q:
Create a dataframe out of dbutils.fs.ls output in Databricks
So, I'm a beginner and learning spark programming (pyspark) on Databricks -
What am I trying to do ?
List all the files in a directory and save it into a dataframe so that I am able to apply filter, sort etc on this list of files. Why ? Because I am tryi... | Create a dataframe out of dbutils.fs.ls output in Databricks | So, I'm a beginner and learning spark programming (pyspark) on Databricks -
What am I trying to do ?
List all the files in a directory and save it into a dataframe so that I am able to apply filter, sort etc on this list of files. Why ? Because I am trying to find the biggest file in my directory.
Why doesn't below wor... | [
"ok, actually, I figured it out :). Just wanna leave the question here incase some one benefits from it.\nSo basically, the problem was with the schema. Not all the elements in the list was of String Type. So I explicitly created a schema and used it in createDataFrame function.\nWorking code -\nfrom pyspark.sql.ty... | [
4,
1,
0
] | [] | [] | [
"apache_commons_dbutils",
"databricks",
"pyspark",
"python"
] | stackoverflow_0066166411_apache_commons_dbutils_databricks_pyspark_python.txt |
Q:
What is the best way to combine dataframes that have been created through a for loop?
I am trying to combine dataframes with 2 columns into a single dataframe. The initial dataframes are generated through a for loop and stored in a list. I am having trouble getting the data from the list of dataframes into a singl... | What is the best way to combine dataframes that have been created through a for loop? | I am trying to combine dataframes with 2 columns into a single dataframe. The initial dataframes are generated through a for loop and stored in a list. I am having trouble getting the data from the list of dataframes into a single dataframe. Right now when I run my code, it treats each full dataframe as a row.
def line... | [
"You can use pd.concat to merge a list of DataFrames into a single big DataFrame.\nappended_data = []\nfor infile in glob.glob(\"*.xlsx\"):\n data = pandas.read_excel(infile)\n # store DataFrame in list\n appended_data.append(data)\n# see pd.concat documentation for more info\nappended_data = pd.concat(app... | [
1
] | [] | [] | [
"dataframe",
"for_loop",
"jupyter_notebook",
"python"
] | stackoverflow_0074643318_dataframe_for_loop_jupyter_notebook_python.txt |
Q:
How can I remove duplicate words in a string with Python?
Following example:
string1 = "calvin klein design dress calvin klein"
How can I remove the second two duplicates "calvin" and "klein"?
The result should look like
string2 = "calvin klein design dress"
only the second duplicates should be removed and the ... | How can I remove duplicate words in a string with Python? | Following example:
string1 = "calvin klein design dress calvin klein"
How can I remove the second two duplicates "calvin" and "klein"?
The result should look like
string2 = "calvin klein design dress"
only the second duplicates should be removed and the sequence of the words should not be changed!
| [
"string1 = \"calvin klein design dress calvin klein\"\nwords = string1.split()\nprint (\" \".join(sorted(set(words), key=words.index)))\n\nThis sorts the set of all the (unique) words in your string by the word's index in the original list of words.\n",
"def unique_list(l):\n ulist = []\n [ulist.append(x) f... | [
53,
25,
12,
7,
7,
5,
2,
2,
1,
1,
0,
0,
0,
0,
0
] | [
"You can do that simply by getting the set associated to the string, which is a mathematical object containing no repeated elements by definition. It suffices to join the words in the set back into a string:\ndef remove_duplicate_words(string):\n x = string.split()\n x = sorted(set(x), key = x.index)\... | [
-1
] | [
"duplicates",
"python",
"string"
] | stackoverflow_0007794208_duplicates_python_string.txt |
Q:
Unexpected result when concatenating strings of cells in (geo)pandas
I am working the data provided here https://www.opengeodata.nrw.de/produkte/transport_verkehr/unfallatlas/
I am trying to create a concatenated string like this
import geopandas
accidents2020 = gp.read_file("Unfallorte2020_LinRef.shp")
accidents2... | Unexpected result when concatenating strings of cells in (geo)pandas | I am working the data provided here https://www.opengeodata.nrw.de/produkte/transport_verkehr/unfallatlas/
I am trying to create a concatenated string like this
import geopandas
accidents2020 = gp.read_file("Unfallorte2020_LinRef.shp")
accidents2020['joined'] = f"{accidents2020['ULAND']}{accidents2020['UREGBEZ']}{accid... | [
"accidents2020['ULAND'] is a Series, if you convert this Series to a string, it also includes the index and the linefeeds at the end of each line:\nprint(repr(f\"{accidents2020.loc[0:1, 'ULAND']}\"))\n# '0 12\\n1 12\\nName: ULAND, dtype: object'\n\nprint(f\"{accidents2020.loc[0:1, 'ULAND']}\")\n# 0 12\n# 1... | [
1
] | [] | [] | [
"geopandas",
"pandas",
"python",
"string"
] | stackoverflow_0074642979_geopandas_pandas_python_string.txt |
Q:
cannot scrape ratings
My issue is that I cannot use bs4 to scrape sub ratings in its reviews.
Below is an example:
So far, I have discovered where these stars are, but their codes are the same regardless of the color (i.e., green or grey)... I need to be able to identify the color to identify the ratings, not just... | cannot scrape ratings | My issue is that I cannot use bs4 to scrape sub ratings in its reviews.
Below is an example:
So far, I have discovered where these stars are, but their codes are the same regardless of the color (i.e., green or grey)... I need to be able to identify the color to identify the ratings, not just scrape the stars. Below is... | [
"For getting the star rating breakdown (which seems to have no numeric display or meta value), I don't think there's any very simple-and-straight-forward short method since it's done by css in a style tag connected by a class of the container element.\nYou could use something like soup.select('style:-soup-contains(... | [
0
] | [] | [] | [
"beautifulsoup",
"python",
"selenium",
"web_scraping"
] | stackoverflow_0074587603_beautifulsoup_python_selenium_web_scraping.txt |
Q:
Remove minus/dash from date with strftime in Python
Having this:
import datetime
my_date = datetime.date.today()
my_str = my_date.strftime('%Y%m%d')
print(my_date)
I am getting this with the minuses in between:
2022-12-01
I want to get this:
2022121
But just by using some fancy stuff with strftime and not refe... | Remove minus/dash from date with strftime in Python | Having this:
import datetime
my_date = datetime.date.today()
my_str = my_date.strftime('%Y%m%d')
print(my_date)
I am getting this with the minuses in between:
2022-12-01
I want to get this:
2022121
But just by using some fancy stuff with strftime and not referring to the . and formatting a string like in the case h... | [
"You're parsing the datetime correctly - you're just printing the original datetime instead of your string!\n"
] | [
1
] | [] | [] | [
"datetime",
"python",
"strftime"
] | stackoverflow_0074643526_datetime_python_strftime.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.