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:
Python requests ConnectionError after few thousands POST requests
im currently working on a python script that executes POST requests a few thousand times to fill dummy data into a database. The POST request sends a string to our backend which fills in this string into the database.
The first 10000 requests are wo... | Python requests ConnectionError after few thousands POST requests | im currently working on a python script that executes POST requests a few thousand times to fill dummy data into a database. The POST request sends a string to our backend which fills in this string into the database.
The first 10000 requests are working fine but then a ConnectionError appears.
This is a simplified imp... | [] | [] | [
"Instead of request.post use httplib.HTTPConnection(url) with concurrency .\nYou need to change your code,That will definitely help to solve this problem.\n"
] | [
-1
] | [
"nestjs",
"python",
"python_requests"
] | stackoverflow_0074601518_nestjs_python_python_requests.txt |
Q:
How to catch SegFault in Python as exception?
Sometimes Python not only throws exception but also segfaults.
Through many years of my experience with Python I saw many segfaults, half of them where inside binary modules (C libraries, i.e. .so/.pyd files), half of them where inside CPython binary itself.
When segfa... | How to catch SegFault in Python as exception? | Sometimes Python not only throws exception but also segfaults.
Through many years of my experience with Python I saw many segfaults, half of them where inside binary modules (C libraries, i.e. .so/.pyd files), half of them where inside CPython binary itself.
When segfault is issued then whole Python program finishes wi... | [
"The simplest way is to have a \"parent\" process which launches your app process, and check its exit value. -11 means the process received the signal 11 which is SEGFAULTV (cf)\nimport subprocess\n\nSEGFAULT_PROCESS_RETURNCODE = -11\n\n\nsegfaulting_code = \"import ctypes ; ctypes.string_at(0)\" # https://codegol... | [
1
] | [] | [] | [
"python",
"segmentation_fault"
] | stackoverflow_0074591919_python_segmentation_fault.txt |
Q:
comparing types between a class and a dictionary
I am working with dictionaries and classes and I want to check that the dictionaries and the classes have the same field types.
For example, I have a dataclass of this form
@dataclasses.dataclass
class FlatDataclass:
first_field: str
second_field: int
and I... | comparing types between a class and a dictionary | I am working with dictionaries and classes and I want to check that the dictionaries and the classes have the same field types.
For example, I have a dataclass of this form
@dataclasses.dataclass
class FlatDataclass:
first_field: str
second_field: int
and I have a dictionary of this form
my_dict={first_field:"... | [
"Either you do this\n[f.type.__name__ for f in dataclasses.fields(klass)]\n\nOr you do this\ndct_value_types = list(type(x) for x in list(dct.values()))\n\nNotice that I added or removed __name__ here, so both type checks should either have it or not\n",
"You can use this function that checks if all the fields in... | [
1,
1
] | [] | [] | [
"class",
"dictionary",
"python",
"python_dataclasses"
] | stackoverflow_0074601644_class_dictionary_python_python_dataclasses.txt |
Q:
Date format conversion to text (yyyymmdd)
I have a date in format of YYYY-MM-DD (2022-11-01). I want to convert it to 'YYYYMMDD' format (without hyphen). Pls support.
I tried this...
df['ConvertedDate']= df['DateOfBirth'].dt.strftime('%m/%d/%Y')... but no luck
A:
If I understand correctly, the format mask you sh... | Date format conversion to text (yyyymmdd) | I have a date in format of YYYY-MM-DD (2022-11-01). I want to convert it to 'YYYYMMDD' format (without hyphen). Pls support.
I tried this...
df['ConvertedDate']= df['DateOfBirth'].dt.strftime('%m/%d/%Y')... but no luck
| [
"If I understand correctly, the format mask you should be using with strftime is %Y%m%d:\ndf[\"ConvertedDate\"] = df[\"DateOfBirth\"].dt.strftime('%Y%m%d')\n\n",
"Pandas itself providing the ability to convert strings to datetime in Pandas dataFrame with desire format.\ndf['ConvertedDate'] = pd.to_datetime(df['Da... | [
0,
0
] | [
"This works\nfrom datetime import datetime \n\ninitial = \"2022-11-01\"\ntime = datetime.strptime(initial, \"%Y-%m-%d\")\nprint(time.strftime(\"%Y%m%d\"))\n\n"
] | [
-1
] | [
"date",
"format",
"python",
"text",
"types"
] | stackoverflow_0074601879_date_format_python_text_types.txt |
Q:
Looping through strings and replacing adjoining characters
I need to know how to switch 2 characters in a string. For example, I have:
###################################
#### ######################
#### ### ### ####
#### ### ### ####
#### ### ####... | Looping through strings and replacing adjoining characters | I need to know how to switch 2 characters in a string. For example, I have:
###################################
#### ######################
#### ### ### ####
#### ### ### ####
#### ### ####
o ### ##################
###########################... | [
"Im assuming you are working with a map thats printed in the terminal\nYou should think of the house as a 2 dimensional array where the 0s are free space and the 1s are the wall (or the other way around, thats just preference).\nThat way when you are printing the map you are just printing an empty space, a # or the... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074601545_python.txt |
Q:
Speaker Diarization
I am trying to do speaker diarization using the pyannote library using the code below:
from pyannote.audio import Pipeline
pipeline = Pipeline.from_pretrained("pyannote/speaker-diarization")
diarization = pipeline("audio.wav")
for turn, _, speaker in diarization.itertracks(yield_label=True):
... | Speaker Diarization | I am trying to do speaker diarization using the pyannote library using the code below:
from pyannote.audio import Pipeline
pipeline = Pipeline.from_pretrained("pyannote/speaker-diarization")
diarization = pipeline("audio.wav")
for turn, _, speaker in diarization.itertracks(yield_label=True):
print(f"start={turn... | [
"I was getting the same error.\nI fixed it by creating a virtual environment and then importing it there, it worked.\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0072479844_python.txt |
Q:
How to fix a warning in pytest
I do tests using py test. There is some kind of warning in the terminal, so I could just skip it, but I would like to remove it from the terminal.
RemovedInDjango50Warning: The USE_L10N setting is deprecated. Starting with Djan
go 5.0, localized formatting of data will always be enab... | How to fix a warning in pytest | I do tests using py test. There is some kind of warning in the terminal, so I could just skip it, but I would like to remove it from the terminal.
RemovedInDjango50Warning: The USE_L10N setting is deprecated. Starting with Djan
go 5.0, localized formatting of data will always be enabled. For example Django will display... | [
"At the top of your Python script, add the following 2 lines of code:\nimport warnings\nwarnings.filterwarnings(action=\"ignore\")\n\nThis will hide all warnings from the terminal.\nHope this helps :)\n",
"It was necessary to add these lines to the project settings:\nimport warnings\nwarnings.filterwarnings(actio... | [
0,
0
] | [] | [] | [
"django",
"pytest",
"python"
] | stackoverflow_0074601892_django_pytest_python.txt |
Q:
Pip package version conflicts despite seemingly matching ranges
When using pip install -r requirements.txt, I get ERROR: Cannot install -r requirements.txt (line 3), [...] because these package versions have conflicting dependencies..
And further:
The conflict is caused by:
tensorflow 2.11.0 depends on protobu... | Pip package version conflicts despite seemingly matching ranges | When using pip install -r requirements.txt, I get ERROR: Cannot install -r requirements.txt (line 3), [...] because these package versions have conflicting dependencies..
And further:
The conflict is caused by:
tensorflow 2.11.0 depends on protobuf<3.20 and >=3.9.2
tensorboard 2.11.0 depends on protobuf<4 and >... | [
"I would suggest that, rather than using a range of versions, use a specific version you know works. That way, there won't be any problems.\nI think that one of the versions of the dependencies is incompatible with the main module, and since it is within the range of versions you ask for, pip tries to intall it and... | [
0
] | [] | [] | [
"pip",
"python"
] | stackoverflow_0074602039_pip_python.txt |
Q:
Django: How to check if something is an email without a form
I have HTML form to post in Django View and because of some constraints, it's easier for me to do the validation without the usual Django form classes.
My only reason to use Django Forms is Email Field(s) that are entered.
Is there any function to chec... | Django: How to check if something is an email without a form | I have HTML form to post in Django View and because of some constraints, it's easier for me to do the validation without the usual Django form classes.
My only reason to use Django Forms is Email Field(s) that are entered.
Is there any function to check if something is an email or I have to use the EmailField to chec... | [
"You can use the following\nfrom django.core.validators import validate_email\nfrom django import forms\n\n...\nif request.method == \"POST\":\n try:\n validate_email(request.POST.get(\"email\", \"\"))\n except forms.ValidationError:\n ...\n\nassuming you have a <input type=\"text\" name=\"email... | [
37,
6,
0
] | [] | [] | [
"django",
"emailfield",
"python"
] | stackoverflow_0013996622_django_emailfield_python.txt |
Q:
How to use PyGithub with Streamlit to build a webapp
I want to create a script that deploys with Streamlit in python that lists the contents of a specific repository. Is it even possible? because I'm trying it and it always says this:
ImportError: cannot import name 'Github' from 'github' (/Library/Frameworks/Pyt... | How to use PyGithub with Streamlit to build a webapp | I want to create a script that deploys with Streamlit in python that lists the contents of a specific repository. Is it even possible? because I'm trying it and it always says this:
ImportError: cannot import name 'Github' from 'github' (/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/git... | [
"Just to let you know that I don't have issues with pygithub and streamlit.\nCode\nmain.py\nfrom github import Github\nimport streamlit as st\n\n\ndef list_content_repo():\n g = Github()\n username = g.get_user(\"gitblanc\")\n repo = username.get_repo(\"Obsidian-Notes\")\n contents = repo.get_contents(\... | [
1
] | [] | [] | [
"python",
"streamlit"
] | stackoverflow_0074585843_python_streamlit.txt |
Q:
cursor.fetchone() returns NoneType but it has value, how to collect values in a list?
def get_user_data(username: str, columns: list):
result = []
for column in columns:
query = f"SELECT {column} FROM ta_users WHERE username = '{username}'"
cursor.execute(query)
print('cursor.fetcho... | cursor.fetchone() returns NoneType but it has value, how to collect values in a list? | def get_user_data(username: str, columns: list):
result = []
for column in columns:
query = f"SELECT {column} FROM ta_users WHERE username = '{username}'"
cursor.execute(query)
print('cursor.fetchone() from loop = ', cursor.fetchone(),
'type= ', type(cursor.fetchone())) # ... | [
"You are \"emptying\" it in the first fetchone() run, that's why you are getting None in the following (it looks for the second record, but can't find it. Try this code:\ndef get_user_data(username: str, columns: list):\n result = []\n for column in columns:\n query = f\"SELECT {column} FROM ta_users W... | [
1
] | [] | [] | [
"database_cursor",
"postgresql",
"python",
"typeerror"
] | stackoverflow_0074602170_database_cursor_postgresql_python_typeerror.txt |
Q:
Docker Run two unending programs python
I am trying to run a flask server (app.py) and a script which, evry 5 minutes, sends a request to that server.
Dockerfile
FROM ubuntu:18.04
RUN apt-get update -y && apt-get install -y python3 python3-pip
COPY ./requirement.txt /app/requirement.txt
WORKDIR /app
RUN pip3 inst... | Docker Run two unending programs python | I am trying to run a flask server (app.py) and a script which, evry 5 minutes, sends a request to that server.
Dockerfile
FROM ubuntu:18.04
RUN apt-get update -y && apt-get install -y python3 python3-pip
COPY ./requirement.txt /app/requirement.txt
WORKDIR /app
RUN pip3 install -r requirement.txt
COPY ./src /app
EXPOS... | [
"The ideal setup is to have one process running in one container. So it's good to run app.py and metricRequestr.py in two separate containers. So have two Dockerfiles:\nDockerfile 1:\nFROM ubuntu:18.04\nRUN apt-get update -y && apt-get install -y python3 python3-pip\n\nCOPY ./requirement.txt /app/requirement.txt\nW... | [
0
] | [] | [] | [
"docker",
"flask",
"python"
] | stackoverflow_0074601447_docker_flask_python.txt |
Q:
Take average of range entities and replace it in pandas column
I have dataframe where one column looks like
Average Weight (Kg)
0.647
0.88
0
0.73
1.7 - 2.1
1.2 - 1.5
2.5
NaN
1.5 - 1.9
1.3 - 1.5
0.4
1.7 - 2.9
Re... | Take average of range entities and replace it in pandas column | I have dataframe where one column looks like
Average Weight (Kg)
0.647
0.88
0
0.73
1.7 - 2.1
1.2 - 1.5
2.5
NaN
1.5 - 1.9
1.3 - 1.5
0.4
1.7 - 2.9
Reproducible data
df = pd.DataFrame([0.647,0.88,0,0.73,'1.7 - 2.1','1.... | [
"Another possible solution, which is based on the following ideas:\n\nConvert column to string.\n\nSplit each cell by \\s-\\s.\n\nExplode column.\n\nConvert back to float.\n\nGroup by and mean.\n\n\ndf['Average Weight (Kg)'] = df['Average Weight (Kg)'].astype(\n str).str.split(r'\\s-\\s').explode().astype(float)... | [
2,
1
] | [] | [] | [
"numpy",
"pandas",
"python"
] | stackoverflow_0074601918_numpy_pandas_python.txt |
Q:
Wxpython: Bind works only on double click, but single click is desired
I have a table with checkboxes. I want to bind the box checking to a method onClick but that method activates only when I double click a record, while I want it to be activated when a single click is pressed.
import wx
from wx import ListEvent
... | Wxpython: Bind works only on double click, but single click is desired | I have a table with checkboxes. I want to bind the box checking to a method onClick but that method activates only when I double click a record, while I want it to be activated when a single click is pressed.
import wx
from wx import ListEvent
class MyFrame(wx.Frame):
def onClick(self, event: ListEvent):
... | [
"Instead of wx.EVT_LIST_ITEM_ACTIVATED use wx.EVT_LIST_ITEM_SELECTED\n"
] | [
0
] | [] | [] | [
"python",
"user_interface",
"wxpython"
] | stackoverflow_0074602199_python_user_interface_wxpython.txt |
Q:
I am trying to sort a csv alphabetically but its not happening
I am trying to sort a csv file alphabetically by the package column. I am using this code
import pandas as pandasForSortingCSV
# assign dataset
csvData = pandasForSortingCSV.read_csv("python_packages.csv")
# displaying unsorted data frame
print("\nBe... | I am trying to sort a csv alphabetically but its not happening | I am trying to sort a csv file alphabetically by the package column. I am using this code
import pandas as pandasForSortingCSV
# assign dataset
csvData = pandasForSortingCSV.read_csv("python_packages.csv")
# displaying unsorted data frame
print("\nBefore sorting:")
print(csvData)
# sort data frame
csvData.sort_value... | [
"The sorting in python is a little weird. Uppercase letters always become first before lower case letters irregardless of the letter. You can use this to sort it properly:\nimport pandas as pandasForSortingCSV\n\n# assign dataset\ncsvData = pandasForSortingCSV.read_csv(\"python_packages.csv\")\n\n# displaying unsor... | [
0
] | [] | [] | [
"csv",
"pandas",
"python",
"python_3.x",
"sorting"
] | stackoverflow_0074599953_csv_pandas_python_python_3.x_sorting.txt |
Q:
How to use two different versions of library in google colab?
How to use two different versions of library (for example, sklearn) in google colab?
I created two files in one I install version 0.21.3, and in the other the same version is installed immediately, how to make the versions in different files different?
... | How to use two different versions of library in google colab? | How to use two different versions of library (for example, sklearn) in google colab?
I created two files in one I install version 0.21.3, and in the other the same version is installed immediately, how to make the versions in different files different?
| [
"I don't think you can do this in python without complicated workarounds.\nYou could run a subprocess in a different python version using virtual environments via pyenv for each script.\nI advise against it though. Maybe someone can make a good alternative suggestion if you tell us why you need to have different ve... | [
0
] | [] | [] | [
"anaconda",
"google_colaboratory",
"python",
"sklearn_pandas"
] | stackoverflow_0074600783_anaconda_google_colaboratory_python_sklearn_pandas.txt |
Q:
Max retries exceeded error when trying to save graph as png
every time when I try to save graph as png files, I could only save for a few times and then it will be a Max retries exceeded error:
MaxRetryError: HTTPConnectionPool(host='localhost', port=49307): Max retries exceeded with url: /session/90fd658175ea8693... | Max retries exceeded error when trying to save graph as png | every time when I try to save graph as png files, I could only save for a few times and then it will be a Max retries exceeded error:
MaxRetryError: HTTPConnectionPool(host='localhost', port=49307): Max retries exceeded with url: /session/90fd658175ea86931fe863c6f0bab370/url (Caused by NewConnectionError('<urllib3.conn... | [
"There are some issues with the altair_saver methods and the next version of altair will likely use a new library called vl-convert which fixes most saving issues, but until that is released, we have to use it manually. First do python -m pip install vl-convert-python from your environment, then you can try this:\n... | [
0
] | [] | [] | [
"altair",
"python"
] | stackoverflow_0074512623_altair_python.txt |
Q:
How to avoid loading wrong libraries when using a subprocess.Popen() from a python script to run a venv?
I want to run a script using a venv python~3.9 from a subprocess call of another application that uses python3.6. However the imported libraries are wrong and from the site-packages of 3.6 version. How can I mo... | How to avoid loading wrong libraries when using a subprocess.Popen() from a python script to run a venv? | I want to run a script using a venv python~3.9 from a subprocess call of another application that uses python3.6. However the imported libraries are wrong and from the site-packages of 3.6 version. How can I modify the subprocess call to load the correct libraries i.e from the venv(3.9 version)
p = Popen([process_name,... | [
"You should use an absolute path to that venv like /path/to/venv/bin/python3.9\n",
"This is my example.\nexample.py\nthis code show python version you run.\nimport sys \nprint(\"version {}\".format(sys.version))\n\ntraverse_python.sh\nthis code traverses various python versions to show what version runs the code.... | [
0,
0
] | [] | [] | [
"loadlibrary",
"python",
"subprocess"
] | stackoverflow_0074600714_loadlibrary_python_subprocess.txt |
Q:
How to make a python application that detects a color and when detected presses a button on the keyboard?
I am trying to write an application that constantly checks for a color and when detected, presses the e button once.
import pyautogui
import time
color = (1, 72, 132)
def clicker():
while True:
x... | How to make a python application that detects a color and when detected presses a button on the keyboard? | I am trying to write an application that constantly checks for a color and when detected, presses the e button once.
import pyautogui
import time
color = (1, 72, 132)
def clicker():
while True:
x, y = pyautogui.position()
pixelColor = pyautogui.screenshot().getpixel((x, y))
if pixelColor =... | [
"To get a tuple of RGB colors at the current mouse position I use this\npixel = pyautogui.pixel(*pyautogui.position())\n\n"
] | [
0
] | [] | [] | [
"action",
"detection",
"python"
] | stackoverflow_0074602233_action_detection_python.txt |
Q:
Spectrochempy Unable to Find "pint.unit" -- Module Not Found Error
I am trying to install spectrochempy (https://www.spectrochempy.fr/stable/gettingstarted/install/install_win.html) via conda on Windows 10. I am able to follow the instructions without an error message; it is only when trying to verify the installa... | Spectrochempy Unable to Find "pint.unit" -- Module Not Found Error | I am trying to install spectrochempy (https://www.spectrochempy.fr/stable/gettingstarted/install/install_win.html) via conda on Windows 10. I am able to follow the instructions without an error message; it is only when trying to verify the installation that I get an error message. The full text of the error message is ... | [
"For Future Reference: The solution was to downgrade pint 0.20 -> 0.19\nThis has turned out to be a bug in the spectrochempy code. There is a thread on github (https://github.com/spectrochempy/spectrochempy/issues/490) which alleges this issue is already solved, however, this was still an issue for me. I used pip t... | [
0
] | [] | [] | [
"pint",
"python"
] | stackoverflow_0074466054_pint_python.txt |
Q:
Better way to generate Postgresql covered index with SQLAlchemy and Alembic
Since Postgresql 11 covered index have been introduced. We create a covered index using INCLUDE keyword like this:
CREATE INDEX index_name ON table_name(indexed_col_name) INCLUDE (covered_col_name);
Here the official postgresql doc for mor... | Better way to generate Postgresql covered index with SQLAlchemy and Alembic | Since Postgresql 11 covered index have been introduced. We create a covered index using INCLUDE keyword like this:
CREATE INDEX index_name ON table_name(indexed_col_name) INCLUDE (covered_col_name);
Here the official postgresql doc for more details.
I have done some research on Google but did not find how to implement ... | [
"Index(\"my_index\", table.c.x, postgresql_include=['y'])\n\nIt's in the postgres-specific part of the documentation\nSee also: issue, commit\n"
] | [
0
] | [] | [] | [
"alembic",
"postgresql",
"python",
"sqlalchemy"
] | stackoverflow_0073546270_alembic_postgresql_python_sqlalchemy.txt |
Q:
opencv mouse callback isn't being triggered
Take a look at this function:
def showImage(im):
def printColor(event, x, y, flag, params):
if event == cv2.EVENT_LBUTTONDOWN:
print(im[x,y])
sys.exit(1)
tag = "image"
cv2.setMouseCallback(tag, printColor)
cv2.imshow(tag, ... | opencv mouse callback isn't being triggered | Take a look at this function:
def showImage(im):
def printColor(event, x, y, flag, params):
if event == cv2.EVENT_LBUTTONDOWN:
print(im[x,y])
sys.exit(1)
tag = "image"
cv2.setMouseCallback(tag, printColor)
cv2.imshow(tag, im)
while True:
if 'q' == chr(cv2.wai... | [
"For setMouseCallback to work you will need to create window object first.\nThis can be done either by calling imshow before setting mouse callback, or by creating it with cv2.namedWindow()\n",
"@You may try the following code\nimport cv2\n\ndef function1(event, x, y, flags, param):\n\n if event==cv2.EVENT_LBU... | [
3,
0
] | [] | [] | [
"callback",
"cv2",
"opencv",
"python"
] | stackoverflow_0052946499_callback_cv2_opencv_python.txt |
Q:
What is the meaning of [:, 1:] after np.genfromtxt()?
I am struggeling with python now. i'm trying this script.
I am sure this is a very common syntax in python, but it is so generic I can't find any explanation that make sense to me.
Can you help me to understand the meaning of [:, 0] and [:, 1:] in the following... | What is the meaning of [:, 1:] after np.genfromtxt()? | I am struggeling with python now. i'm trying this script.
I am sure this is a very common syntax in python, but it is so generic I can't find any explanation that make sense to me.
Can you help me to understand the meaning of [:, 0] and [:, 1:] in the following lines of code?
syms = np.genfromtxt('people.csv', dtype=st... | [
"That's using slice notation to extract specific rows and columns from the dataset.\n[:, 0] means all rows, column 0.\n[:, 1:] means all rows, columns 1 through n (all columns except 0).\nSee Understanding slicing for a good explanation of Python slicing notation.\n"
] | [
1
] | [] | [] | [
"numpy",
"python",
"square_bracket"
] | stackoverflow_0074602285_numpy_python_square_bracket.txt |
Q:
Python: Share a python object instance between child processes
I want to share a python class instance between my child processes that are created with the subprocess.Popen
How can I do it ? What arguments should I use of the Popen?
A:
You can share a pickle over a named pipe.
| Python: Share a python object instance between child processes | I want to share a python class instance between my child processes that are created with the subprocess.Popen
How can I do it ? What arguments should I use of the Popen?
| [
"You can share a pickle over a named pipe.\n"
] | [
0
] | [] | [] | [
"multiprocessing",
"process",
"python",
"subprocess"
] | stackoverflow_0074602221_multiprocessing_process_python_subprocess.txt |
Q:
Draw a line that goes outside the image
I need to draw a line that start from a coordinate in the image and if it goes outside the image it will keep drawing starting from the opposite side like the videogame "Snake".
I don't know how to perform this with Python without using libraries.
Example:
after opening an i... | Draw a line that goes outside the image | I need to draw a line that start from a coordinate in the image and if it goes outside the image it will keep drawing starting from the opposite side like the videogame "Snake".
I don't know how to perform this with Python without using libraries.
Example:
after opening an image
I create a for loop taking the commands ... | [
"Change it to:\nimage[y % image_height ][x % image_width] = (100, 100, 100)\nModulo operator : https://realpython.com/python-modulo-operator/\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074602458_python.txt |
Q:
how to install pip install python-telegram-bot?
how to install pip install python-telegram-bot in pycharm. please help me i get this error msg -
$ : The term '$' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify ... | how to install pip install python-telegram-bot? | how to install pip install python-telegram-bot in pycharm. please help me i get this error msg -
$ : The term '$' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 cha... | [] | [] | [
"There should be a \"Python Packages\" on the bottom slidebar. It's a convenient way to install packages.\n"
] | [
-1
] | [
"python"
] | stackoverflow_0074602418_python.txt |
Q:
is there a way to have parameters be executed in random order in python cli?
i have a program that takes 3 parameters: volume, weight, and model_path. Currently, i have:
volume = int(args[0])
weight = int(args[1])
model_path = args[2]
so i have to execute it like this: python3 example.py 713 382 model.pkl. I w... | is there a way to have parameters be executed in random order in python cli? | i have a program that takes 3 parameters: volume, weight, and model_path. Currently, i have:
volume = int(args[0])
weight = int(args[1])
model_path = args[2]
so i have to execute it like this: python3 example.py 713 382 model.pkl. I want to be able to do it like this: python3 example.py --weight=500 --volume=437 --... | [
"Ignoring the idea of reimplementing the argparse module, just use that module. For example,\nimport argparse\n\np = argparse.ArgumentParser()\np.add_argument('--volume', type=int)\np.add_argument('--weight', type=int)\np.add_argument('--model')\n\nargs = p.parse_args()\n\nThe result will be an instance of argparse... | [
1
] | [] | [] | [
"command_line_interface",
"list",
"python",
"python_3.x"
] | stackoverflow_0074602341_command_line_interface_list_python_python_3.x.txt |
Q:
Python code to have batch numbers within a value in a column in dataframe
I have a dataframe like this
Name Age
0 U 20
1 U 20
2 U 20
3 U 18
4 I 45
5 I 68
6 I 8
7 D 7
8 D 6
9 I 89
and I want to have batch size (say 3) and I want to display another column, whi... | Python code to have batch numbers within a value in a column in dataframe | I have a dataframe like this
Name Age
0 U 20
1 U 20
2 U 20
3 U 18
4 I 45
5 I 68
6 I 8
7 D 7
8 D 6
9 I 89
and I want to have batch size (say 3) and I want to display another column, which increments the batch number staring from 1 and with batch size being repetit... | [
"You can use:\nN = 3\n\n# group successive values\ngroup = df['Name'].ne(df['Name'].shift()).cumsum()\n\n# restart group every N times\ndf['Batch'] = (df.groupby(group)\n .cumcount().mod(N)\n .eq(0).cumsum()\n )\n\nOutput:\n Name Age Batch\n0 U 20 1\n1 U ... | [
3
] | [] | [] | [
"dataframe",
"group_by",
"numpy",
"pandas",
"python"
] | stackoverflow_0074601971_dataframe_group_by_numpy_pandas_python.txt |
Q:
Web scrape of forbes website using requests-html
I'm trying to scrape the list from https://www.forbes.com/best-states-for-business/list/#tab:overall
import requests_html
session= requests_html.HTMLSession()
r = session.get("https://www.forbes.com/best-states-for-business/list/#tab:overall")
r.html.render()
body=r... | Web scrape of forbes website using requests-html | I'm trying to scrape the list from https://www.forbes.com/best-states-for-business/list/#tab:overall
import requests_html
session= requests_html.HTMLSession()
r = session.get("https://www.forbes.com/best-states-for-business/list/#tab:overall")
r.html.render()
body=r.text.find('#list-table-body')
print(body)
This retur... | [
"Data is loaded dynamically from external source via API and You can grab the required data using requests module only then store via pandas DataFrame.\nimport pandas as pd\nimport requests\n\nheaders = {'user-agent':'Mozilla/5.0'}\nurl = 'https://www.forbes.com/ajax/list/data?year=2019&uri=best-states-for-business... | [
1
] | [] | [] | [
"python",
"python_requests_html",
"web_scraping"
] | stackoverflow_0074600929_python_python_requests_html_web_scraping.txt |
Q:
check the boolean value of json Python
Hello I am pretty new working with AWS and SF I am trying to send information and I need to check if the list of json I am checking the information.
I have the next json list:
here...b'[{
"id": "xxxx",
"success": true,
"errors": []
},
{
"id": "yyyy",
"suc... | check the boolean value of json Python | Hello I am pretty new working with AWS and SF I am trying to send information and I need to check if the list of json I am checking the information.
I have the next json list:
here...b'[{
"id": "xxxx",
"success": true,
"errors": []
},
{
"id": "yyyy",
"success": true,
"errors": []
}
]'
and ... | [
"The b in the beginning means you have bytes, instead of a string, meaning you first have to convert your response content into a dictionary (think of a python term for a json) so that you can access the data in your response by their keys. Luckily that's easy to from a requests response with\njson_data = response.... | [
0
] | [] | [] | [
"amazon_web_services",
"json",
"loops",
"python",
"salesforce"
] | stackoverflow_0074602226_amazon_web_services_json_loops_python_salesforce.txt |
Q:
Python Asyncio wait_for decorator
I am trying to write a decorator that calls asyncio.wait_for on the decorated function - the goal is to set a time limit on the decorated function. I expect the decorated function to stop running after time_limit but it does not. The decorator is being called fine but the code jus... | Python Asyncio wait_for decorator | I am trying to write a decorator that calls asyncio.wait_for on the decorated function - the goal is to set a time limit on the decorated function. I expect the decorated function to stop running after time_limit but it does not. The decorator is being called fine but the code just sleeps for 30 seconds instead of bein... | [
"As we can see in this example here, the problem arises from using time.sleep not asyncio.sleep, since time.sleep will block the thread. You need to be careful not to have any blocking code\nimport asyncio\nimport time\n\n\ndef await_time_limit(time_limit):\n def Inner(func):\n async def wrapper(*args, **... | [
1
] | [] | [] | [
"python",
"python_asyncio",
"python_decorators"
] | stackoverflow_0074602321_python_python_asyncio_python_decorators.txt |
Q:
Can Tensorflow Machine Learning Model train data that has None values?
I'm wondering if Tensorflow Machine Learning Model can train data that has None valuess?
I have a Data table with multiple data (in each row) and in some of these rows, there are columns with None/Null value:
Column A
Column B
Column C
50
Non... | Can Tensorflow Machine Learning Model train data that has None values? | I'm wondering if Tensorflow Machine Learning Model can train data that has None valuess?
I have a Data table with multiple data (in each row) and in some of these rows, there are columns with None/Null value:
Column A
Column B
Column C
50
None
2
2
100
None
Or should I not have None values in my dataset an... | [
"TensorFlow is no different to any other ML solution you could find - strickly speaking, no, it cannot learn from Nones and its your responsibility to encode them somehow to a numerical value. It could be any value you find reasonable - I would recommend you to read through https://scikit-learn.org/stable/modules/i... | [
0,
0
] | [] | [] | [
"python",
"tensorflow"
] | stackoverflow_0074602128_python_tensorflow.txt |
Q:
CVAT error during installation of development version
I'm trying to install development version of CVAT according to official instruction but struggling at the step of requirements.txt applying:
pip install -r cvat/requirements/development.txt
... with following error:
Skipping wheel build for av, due to binaries... | CVAT error during installation of development version | I'm trying to install development version of CVAT according to official instruction but struggling at the step of requirements.txt applying:
pip install -r cvat/requirements/development.txt
... with following error:
Skipping wheel build for av, due to binaries being disabled for it.
Skipping wheel build for datumaro, ... | [
"Facing this same problem just last week. I would say the problem is that you are trying to install PyAv without the proper dynamic libraries from FFMPEG. PyAv is just a bunch of Python bindings to connect with binary dynamic libraries in the system. I'm also assuming you are probably on Ubuntu 18.04. The newest FF... | [
0
] | [] | [] | [
"cvat",
"ffmpeg",
"libav",
"pkg_config",
"python"
] | stackoverflow_0072789956_cvat_ffmpeg_libav_pkg_config_python.txt |
Q:
How do I print the person name in DNA PSET5 CS50x
I don't know how to print the person's name that matches the numbers (as strings) returned from "list4"
(sorry for bad english) So I use print(list4) and I get the right values, but I don't know how to get
the name from the person. Example : list4 = ['4', '1', '5']... | How do I print the person name in DNA PSET5 CS50x | I don't know how to print the person's name that matches the numbers (as strings) returned from "list4"
(sorry for bad english) So I use print(list4) and I get the right values, but I don't know how to get
the name from the person. Example : list4 = ['4', '1', '5'], so how I get 'Bob'? I would appreciate any help!
impo... | [
"Start by inspecting the values in your variables. For example, look at dict_list and names for the small.csv file and you will find:\ndict_list:\n[['name', 'AGATC', 'AATG', 'TATC'], ['Alice', '2', '8', '3'], ['Bob', '4', '1', '5'], ['Charlie', '3', '2', '5']]\nnames:\n[[['name', 'AGATC', 'AATG', 'TATC'], ['Alice',... | [
0
] | [] | [] | [
"cs50",
"python",
"python_3.x"
] | stackoverflow_0074586919_cs50_python_python_3.x.txt |
Q:
Tensorflow dataset group by string key
I have a tensorflow dataset that I would like to group by key. However, my keys are strings and not integers to I can't do that:
person_tensor = tf.constant(["person1", "person2", "person1", "person3", "person3"])
value_tensor = tf.constant([1,2,3,4,5])
ds = tf.data.Dataset.f... | Tensorflow dataset group by string key | I have a tensorflow dataset that I would like to group by key. However, my keys are strings and not integers to I can't do that:
person_tensor = tf.constant(["person1", "person2", "person1", "person3", "person3"])
value_tensor = tf.constant([1,2,3,4,5])
ds = tf.data.Dataset.from_tensor_slices((person_tensor, value_tens... | [
"You could try utilizing tf.lookup.StaticHashTable like this:\nimport tensorflow as tf \n\nperson_tensor = tf.constant([\"person1\", \"person2\", \"person1\", \"person3\", \"person3\"])\nvalue_tensor = tf.constant([1,2,3,4,5])\n\nk_tensor = tf.unique(person_tensor)[0]\nv_tensor = tf.cast(tf.range(tf.shape(k_tensor)... | [
1
] | [] | [] | [
"group_by",
"hashmap",
"python",
"tensorflow",
"tensorflow_datasets"
] | stackoverflow_0074602575_group_by_hashmap_python_tensorflow_tensorflow_datasets.txt |
Q:
pandas astype doesn't work as expected (fails silently and badly)
I've encountered this strange behavior of pandas .astype() (I'm using version 1.5.2). When trying to cast a column as integer, and later requesting dtypes, all seems fine. Until you try to extract the values by row, when you get inconsistent types.
... | pandas astype doesn't work as expected (fails silently and badly) | I've encountered this strange behavior of pandas .astype() (I'm using version 1.5.2). When trying to cast a column as integer, and later requesting dtypes, all seems fine. Until you try to extract the values by row, when you get inconsistent types.
Code:
import pandas as pd
import numpy as np
df = pd.DataFrame(np.ran... | [
"I think this is due to the usage of df.values because it will try to return a Numpy representation of the DataFrame. As per the docs\n\nBy default, the dtype of the returned array will be the common NumPy\ndtype of all types in the DataFrame.\n\n>>> from pandas.core.dtypes.cast import find_common_type\n>>> find_co... | [
1
] | [] | [] | [
"casting",
"dtype",
"pandas",
"python"
] | stackoverflow_0074602610_casting_dtype_pandas_python.txt |
Q:
How to update the data on the page without reloading. Python - Django
I am a beginner Python developer. I need to update several values on the page regularly with a frequency of 1 second. I understand that I need to use Ajax, but I have no idea how to do it.
Help write an AJAX script that calls a specific method... | How to update the data on the page without reloading. Python - Django | I am a beginner Python developer. I need to update several values on the page regularly with a frequency of 1 second. I understand that I need to use Ajax, but I have no idea how to do it.
Help write an AJAX script that calls a specific method in the view
I have written view
class MovingAverage(TemplateView):
templ... | [
"Here, we need two functions to call out data from AJAX:\nFirst, we need to create JsonResponse views function in the views.py file.\n# views.py\n\nfrom django.http import JsonResponse\n\ndef get_some_data(request):\n try:\n if request.method == \"POST\":\n get_some_data = [1, 2, 3, 4, 5] # You... | [
0
] | [] | [] | [
"ajax",
"django",
"python"
] | stackoverflow_0074602453_ajax_django_python.txt |
Q:
How can you do an outer summation over only one dimension of a numpy 2D array?
I have a (square) 2 dimensional numpy array where I would like to compare (subtract) all of the values within each row to each other but not to other rows so the output should be a 3D array.
matrix = np.array([[10,1,32],[32,4,15],[6,3,1... | How can you do an outer summation over only one dimension of a numpy 2D array? | I have a (square) 2 dimensional numpy array where I would like to compare (subtract) all of the values within each row to each other but not to other rows so the output should be a 3D array.
matrix = np.array([[10,1,32],[32,4,15],[6,3,1]])
Output should be a 3x3x3 array which looks like:
output = [[[0,-9,22],[0,-28,-1... | [
"You're close, you can do it with broadcasting:\nout = matrix[None, :, :] - matrix.T[:, :, None]\n\nHere .T is the same as np.transpose, and using None as an index introduces a new dummy dimension of size 1.\n"
] | [
4
] | [] | [] | [
"array_broadcasting",
"numpy",
"python"
] | stackoverflow_0074602528_array_broadcasting_numpy_python.txt |
Q:
Is it possible to write a combined version of the OptaPlanner's task assignment and project scheduling examples in OptaPy?
I know that custom shadow variables are currently not supported in optapy, so is there a way to solve the optimization problem below: distribute tasks from the project among employees, given t... | Is it possible to write a combined version of the OptaPlanner's task assignment and project scheduling examples in OptaPy? | I know that custom shadow variables are currently not supported in optapy, so is there a way to solve the optimization problem below: distribute tasks from the project among employees, given that the tasks have a clear order in which they must be performed and people have skills, depending on which the task execution t... | [
"Custom shadow variables ARE supported in optapy: https://www.optapy.org/docs/latest/shadow-variable/shadow-variable.html#customVariableListener ; It uses the old style of @CustomShadowVariable (@custom_shadow_variable in Python) instead of @ShadowVariable. However, ListVariableListener is not currently supported. ... | [
1
] | [] | [] | [
"optaplanner",
"optapy",
"python"
] | stackoverflow_0074572053_optaplanner_optapy_python.txt |
Q:
trying to reverse words while maintaining order and print but having trouble figuring out the problem
I have written code that should do as the title says but im getting "TypeError: can only join an iterable"
on line 12, in reverse_words d.append(''.join(c))
here is my following code-
def reverse_words(text):
... | trying to reverse words while maintaining order and print but having trouble figuring out the problem | I have written code that should do as the title says but im getting "TypeError: can only join an iterable"
on line 12, in reverse_words d.append(''.join(c))
here is my following code-
def reverse_words(text):
#makes 'apple TEST' into ['apple', 'TEST']
a = text.split(' ')
d = []
for i in a:
#take... | [
"Perhaps you could consider utilizing str.join on a comprehension that uses list slicing to reverse a string:\ndef reverse_words(text: str) -> str:\n return ' '.join(word[::-1] for word in text.split(' '))\n\n",
"The reverse() method for lists reverses elements in-place and doesn't return an iterable, meaning it... | [
0,
0
] | [
"d.append('').join(d)\n\nIf this is what you intended try this, otherwise you're gonna need to call a new variable and call .join() on that\n"
] | [
-1
] | [
"python"
] | stackoverflow_0074595185_python.txt |
Q:
Grpcio fails installation for Tensorflow 2.5 on arm64 Apple Silicon
I'm following the instructions here: https://developer.apple.com/metal/tensorflow-plugin/ and having issues installing grpcio. When I try python -m pip install tensorflow-macos I get:
AssertionError: would build wheel with unsupported tag ('cp39... | Grpcio fails installation for Tensorflow 2.5 on arm64 Apple Silicon | I'm following the instructions here: https://developer.apple.com/metal/tensorflow-plugin/ and having issues installing grpcio. When I try python -m pip install tensorflow-macos I get:
AssertionError: would build wheel with unsupported tag ('cp39', 'cp39', 'macosx_11_0_arm64')
---------------------------------------... | [
"What helped me was:\nGRPC_PYTHON_BUILD_SYSTEM_OPENSSL=1 GRPC_PYTHON_BUILD_SYSTEM_ZLIB=1 python -m pip install tensorflow-macos\n\n",
"I had to\n\nBuild boringssl manually (github answer)\nUse the flags while installing grpcio as explained in the previous answer\nUpgrade numpy (TypeError StackOverflow)\n\nInstal... | [
3,
0
] | [] | [] | [
"apple_m1",
"grpcio",
"python",
"tensorflow"
] | stackoverflow_0069151553_apple_m1_grpcio_python_tensorflow.txt |
Q:
Python AWS Lambda Execution New Update
Update
I changed the params to receive the data directly from a JSON dump to see if that fixed the JSON load issue. Received a new error:
(b'{\n "errorType": "ValidationMetadataException",\n
"errorMessage": "The a' b'rgument is null or empty. Provide an
argument that is n... | Python AWS Lambda Execution New Update | Update
I changed the params to receive the data directly from a JSON dump to see if that fixed the JSON load issue. Received a new error:
(b'{\n "errorType": "ValidationMetadataException",\n
"errorMessage": "The a' b'rgument is null or empty. Provide an
argument that is not null or empty, and' b' then try the comm... | [
"I think the problem you have is in the definition of your lambda:\nlambdaName = os.getenv('TF_VAR_lambdaName')\n\nTry following:\nLAMBDA_NAME = os.environ.get('YOUR_LAMBDA_NAME') // make sure you put the exact name of your lambda in ''\n\nThan use it in your code:\nresponse = client.invoke(\n FunctionName=LAMBDA_... | [
0,
0
] | [] | [] | [
"amazon_web_services",
"aws_lambda",
"python"
] | stackoverflow_0074596832_amazon_web_services_aws_lambda_python.txt |
Q:
How to Fetch href links in Chromedriver?
I am trying to scrape the link from a button. If I click the button, it opens a new tab and I can't navigate in it. So I thought I'd scrape the link, go to it via webdriver.get(link) and do it that way since this will be a background program. I cannot find any tutorials on ... | How to Fetch href links in Chromedriver? | I am trying to scrape the link from a button. If I click the button, it opens a new tab and I can't navigate in it. So I thought I'd scrape the link, go to it via webdriver.get(link) and do it that way since this will be a background program. I cannot find any tutorials on this using the most recent version of selenium... | [
"You need to get the href attribute of the button. If your code gets the right button you can just use\nbutton.get_attribute(\"href\")\n\nOf course if you get redirected using Javascript this is a different story, but since you didn't specify I will assume my answer works\n",
"You can use swith_of function to man... | [
0,
0
] | [] | [] | [
"href",
"python",
"screen_scraping",
"selenium_chromedriver"
] | stackoverflow_0074601928_href_python_screen_scraping_selenium_chromedriver.txt |
Q:
How to kill selenium running as a subprocess?
Given the code below, which runs selenium as a multiprocessing.Process. Despite the process being terminated on macOS Ventura 13.0.1, selenium window stays open. Why does the window stay? how to force its termination?
from multiprocessing import Process
from selenium.... | How to kill selenium running as a subprocess? | Given the code below, which runs selenium as a multiprocessing.Process. Despite the process being terminated on macOS Ventura 13.0.1, selenium window stays open. Why does the window stay? how to force its termination?
from multiprocessing import Process
from selenium.webdriver import Chrome
def func():
driver = ... | [
"You could do something along these lines:\ndef func():\n driver = Chrome()\n driver.get('https://google.com')\n driver.quit()\n\nThis should close each window, after the function concludes.\nSee Selenium documentation for more info.\n",
"Assuming you are able to modify function func, then pass to it the... | [
0,
0
] | [] | [] | [
"multiprocessing",
"python",
"selenium"
] | stackoverflow_0074580243_multiprocessing_python_selenium.txt |
Q:
packed bubble chart stack in a rectangle with Python
I want to make a packed bubble chart with Python but stack bubbles in a rectangle-ish format something like this:
What is the best way to achieve this? Also is there any Python package that returns the position (coordinate) of bubbles?
A:
I hope the Treemap c... | packed bubble chart stack in a rectangle with Python | I want to make a packed bubble chart with Python but stack bubbles in a rectangle-ish format something like this:
What is the best way to achieve this? Also is there any Python package that returns the position (coordinate) of bubbles?
| [
"I hope the Treemap chart works for your use case in here.\nplotly implementation\nsquarify implementation\n",
"Plotly is your friend.\nConsidering the example dataframe:\nd = {'Party': ['Democrat', 'Democrat', 'Republican', 'Republican'], 'Keyword': ['Donkey', 'Left', 'Elephant', 'Right'], 'x': [1, 2, 3, 4], 'y'... | [
0,
0,
0,
0
] | [] | [] | [
"bubble_chart",
"python",
"visualization"
] | stackoverflow_0070298696_bubble_chart_python_visualization.txt |
Q:
How to combine these two codes in Kivy?
I have two codes and I want to combine Python code into Kivy code.
python code:
import csv
import socket
import datetime
import time
from itertools import zip_longest
Time =[]
Price = []
fields = ['Time', 'Price']
s = socket.socket(socket.AF_BLUETOOTH, socket.SOCK_STREAM, s... | How to combine these two codes in Kivy? | I have two codes and I want to combine Python code into Kivy code.
python code:
import csv
import socket
import datetime
import time
from itertools import zip_longest
Time =[]
Price = []
fields = ['Time', 'Price']
s = socket.socket(socket.AF_BLUETOOTH, socket.SOCK_STREAM, socket.BTPROTO_RFCOMM)
port = 1
hostMA... | [
"Since your first code has no classes or methods, it will run its loop forever as soon as it is imported by python.\nYou can still use that code by putting its import in a new thread. You can use something like:\ndef doit(self, button):\n print('importing')\n threading.Thread(target=self.do_import, daemon=Tru... | [
0
] | [] | [] | [
"kivy",
"matplotlib_widget",
"python",
"real_time"
] | stackoverflow_0074601897_kivy_matplotlib_widget_python_real_time.txt |
Q:
Python Program to create Container if not exist with partition key and unique Key
I want to write python script to create container only if it not exist with partition key and unique key.
Steps for Creating Alert Container
1. Create Container With Container ID: alerts
2. Add Partition Key as /user_tenant
3. Ad... | Python Program to create Container if not exist with partition key and unique Key | I want to write python script to create container only if it not exist with partition key and unique key.
Steps for Creating Alert Container
1. Create Container With Container ID: alerts
2. Add Partition Key as /user_tenant
3. Add Unique Key as /alert_id
reference link: https://github.com/Azure/azure-cosmos-python... | [
"@Gaurav Mantri\nBelow is the working code as suggested by you.\nfor uniqueKeys we need to add it inside uniqueKeyPolicy as shown in below code.\nimport azure.cosmos.documents as documents\nfrom azure.cosmos import cosmos_client, http_constants, errors\nimport os\n\nurl = os.environ['COSMOS_DB_END_POINT']\nkey = os... | [
0,
0
] | [] | [] | [
"azure_cosmosdb",
"python"
] | stackoverflow_0060772092_azure_cosmosdb_python.txt |
Q:
How to make a ckeck of user permissions in disnake or discord.py
I've got a code with permissions. I need to check a member permissions and if member don`t have such permissions send a message
Main code:
@commands.slash_command(name = "addrole", description="Додати користувачу роль")
@commands.has_permissions(view... | How to make a ckeck of user permissions in disnake or discord.py | I've got a code with permissions. I need to check a member permissions and if member don`t have such permissions send a message
Main code:
@commands.slash_command(name = "addrole", description="Додати користувачу роль")
@commands.has_permissions(view_audit_log=True)
async def addrole(self, ctx, member: disnake.Member, ... | [
"I think you are not getting what you want because you are trying to integrate both at once. From what I can see from your description and code, the easiest solution I could provide you is removing @commands.has_permissions(view_audit_log=True) from your \"what I want to have\" section of code. However, if you don'... | [
0
] | [] | [] | [
"discord",
"discord.py",
"disnake",
"python"
] | stackoverflow_0074589128_discord_discord.py_disnake_python.txt |
Q:
Python how to read cropped Word with CV2 and convert to gray?
I'm trying to make letter segmentation and I'm using WordDetector to crop words as this code
def contours_words(image_file):
im3 = image_file.copy()
img = prepare_img(image_file, 50)
detections = detect(img,
kernel_si... | Python how to read cropped Word with CV2 and convert to gray? | I'm trying to make letter segmentation and I'm using WordDetector to crop words as this code
def contours_words(image_file):
im3 = image_file.copy()
img = prepare_img(image_file, 50)
detections = detect(img,
kernel_size=25,
sigma=3,
the... | [
"I found the answer I need to convert it to RGB color image then I convert it to gray scale\nopencvImage = cv2.cvtColor(np.array(image_file), cv2.COLOR_RGB2BGR)\ngray = cv2.cvtColor(opencvImage, cv2.COLOR_BGR2GRAY)\n\n"
] | [
0
] | [] | [] | [
"computer_vision",
"opencv",
"python"
] | stackoverflow_0074602640_computer_vision_opencv_python.txt |
Q:
How to remove lines that does not end with numbers?
I have a text file Mytext.txt that looks like this,
0 1 A
1 2 T
2 3 A
3 4 B
4 5 A
5 6
6 7 A
7 8 D
8 9 C
9 10
10 11 M
11 12 Z
12 13 H
What is the easiest way in python with which I can remove the lines that do not end with a letter? So the above becomes
0 1 A... | How to remove lines that does not end with numbers? | I have a text file Mytext.txt that looks like this,
0 1 A
1 2 T
2 3 A
3 4 B
4 5 A
5 6
6 7 A
7 8 D
8 9 C
9 10
10 11 M
11 12 Z
12 13 H
What is the easiest way in python with which I can remove the lines that do not end with a letter? So the above becomes
0 1 A
1 2 T
2 3 A
3 4 B
4 5 A
6 7 A
7 8 D
8 9 C
10 11 M
11 12 ... | [
"with open('Mytext.txt', 'r') as fin:\n with open('Newtext.txt', 'w') as fout:\n for line in fin:\n if line.rstrip()[-1].isalpha()\n fout.write(line)\n\n"
] | [
1
] | [] | [] | [
"python",
"text"
] | stackoverflow_0074602920_python_text.txt |
Q:
Web scraping doesn't iterate over entire webpage
Im trying to scrape the information of all the player names and player rating from this website:
https://www.fifaindex.com/players/?gender=0&league=1&order=desc
But i only get the information from the first player on the page.
The code im using:
from bs4 import Bea... | Web scraping doesn't iterate over entire webpage | Im trying to scrape the information of all the player names and player rating from this website:
https://www.fifaindex.com/players/?gender=0&league=1&order=desc
But i only get the information from the first player on the page.
The code im using:
from bs4 import BeautifulSoup
import requests
url = "https://www.fifaind... | [
"I tinkered around a little bit and I think I got a version that does what you want\nfrom bs4 import BeautifulSoup\nimport requests\n\npage = requests.get(\"https://www.fifaindex.com/players/? \ngender=0&league=1&order=desc\")\nsoup = BeautifulSoup(page.content, \"html.parser\")\nresults = soup.find_all(\"tr\")\n\n... | [
0,
0
] | [] | [] | [
"beautifulsoup",
"python",
"web_scraping"
] | stackoverflow_0074602709_beautifulsoup_python_web_scraping.txt |
Q:
How to improve partial 2D array filling/filtering in numpy
I'm currently reading reviewing code. I have a double loop to filter a 2D array according to a 1D array.
Here is the code:
import numpy as np
size_a = 500
size_b = 2000
a = np.random.rand(size_a)
c = np.random.rand(size_a*size_b).reshape((size... | How to improve partial 2D array filling/filtering in numpy | I'm currently reading reviewing code. I have a double loop to filter a 2D array according to a 1D array.
Here is the code:
import numpy as np
size_a = 500
size_b = 2000
a = np.random.rand(size_a)
c = np.random.rand(size_a*size_b).reshape((size_a, size_b))
d = np.random.rand(size_b)
... | [
"Let's describe what you want to do in words:\n\nYou have a matrix c of shape (size_a, size_b).\nYou have a vector a with one element per row of c\nYou have a vector d with one element per column of c\n\nIn those locations where a[i] <= d[j], you want to set c to zero.\nLet's say we have:\nsize_a = 3\nsize_b = 5\n\... | [
1
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0074602767_numpy_python.txt |
Q:
Concatenate path and filename
I have to build the full path together in python. I tried this:
filename= "myfile.odt"
subprocess.call(['C:\Program Files (x86)\LibreOffice 5\program\soffice.exe',
'--headless',
'--convert-to',
'pdf', '--outdir',
... | Concatenate path and filename | I have to build the full path together in python. I tried this:
filename= "myfile.odt"
subprocess.call(['C:\Program Files (x86)\LibreOffice 5\program\soffice.exe',
'--headless',
'--convert-to',
'pdf', '--outdir',
r'C:\Users\A\Desktop\Repo\... | [
"Try:\nimport os\nos.path.join('C:\\Users\\A\\Desktop\\Repo', filename)\n\nThe os module contains many useful methods for directory and path manipulation\n",
"Backslash character (\\) has to be escaped in string literals.\n\nThis is wrong: '\\'\nThis is correct: '\\\\' - this is a string containing one backslash\... | [
25,
7,
2,
2,
1,
0,
0
] | [] | [] | [
"filepath",
"path",
"python"
] | stackoverflow_0040596748_filepath_path_python.txt |
Q:
modifying dataframe through specifics dates
I've a timeseries that i need pass a equation in the same day and month across the years
Name | date | value | Type
player 1 | 2010/02/10 | 100 | 2
player 2 | 2011/16/15 | 200 | 3
player 3 | 2012/02/10 | 150 | 4
player 4 | 2013/11/16 | 136 | 5
player 5... | modifying dataframe through specifics dates | I've a timeseries that i need pass a equation in the same day and month across the years
Name | date | value | Type
player 1 | 2010/02/10 | 100 | 2
player 2 | 2011/16/15 | 200 | 3
player 3 | 2012/02/10 | 150 | 4
player 4 | 2013/11/16 | 136 | 5
player 5 | 2014/02/10 | 94 | 6
I need change my colum... | [
"If you have strings:\ndf.loc[df['date'].str.endswith('02/10'), 'Type'] = 2\n\nFor datetime type:\ndf.loc[df['date'].dt.strftime('%d/%m').eq('02/10'), 'Type'] = 2\n\nOutput:\n Name date value Type\n0 player 1 2010/02/10 100 2\n1 player 2 2011/16/15 200 3\n2 player 3 2012/02/10 ... | [
0
] | [] | [] | [
"numpy",
"python",
"python_3.x"
] | stackoverflow_0074602892_numpy_python_python_3.x.txt |
Q:
Djnago how to split users and customres
In my project (small online shop) I need to split registration for users and customers.
So the information what I found when somebody registered in django then his account stored in one table, in this table I can see admin user and staff and another registered accounts, and ... | Djnago how to split users and customres | In my project (small online shop) I need to split registration for users and customers.
So the information what I found when somebody registered in django then his account stored in one table, in this table I can see admin user and staff and another registered accounts, and I can sse them all in admin on Users page. Bu... | [
"As Jay said, everyone registered in the database is still a User whatever their role may be (admin, superuser, customer). What you could do is create a Profile model where everyone will have their information such as telephone, location etc, and you will also add another field clarifying their property.\nPACKAGES ... | [
2
] | [] | [] | [
"django",
"python",
"python_3.x"
] | stackoverflow_0074602189_django_python_python_3.x.txt |
Q:
Python: How to convert Timestamp which of precision 9 to datetime object?
I am fetching crypto data from the ByBit exchange which is returning the timestamp field created_at_e9 in the following format: 1663315207126761200
The standard is 11 -13 digits but here are 20 digits. How do I fetch the DateTime from it?
A... | Python: How to convert Timestamp which of precision 9 to datetime object? | I am fetching crypto data from the ByBit exchange which is returning the timestamp field created_at_e9 in the following format: 1663315207126761200
The standard is 11 -13 digits but here are 20 digits. How do I fetch the DateTime from it?
| [
"You can look at this so see how to convert a timestamp into a datetime in python. And since the timestamp presision is 1e9 you can simply multiply the value by 1e-9 or divide it by 1e9 to get the timestamp in seconds.\nfrom datetime import datetime\ndatetime.fromtimestamp(created_at_e9 * 1e-9)\n\n"
] | [
1
] | [] | [] | [
"datetime",
"python",
"unix_timestamp"
] | stackoverflow_0074602919_datetime_python_unix_timestamp.txt |
Q:
Transforming a matrix by placing its elements in the reverse order of the initial in python
im looking to solve the problem mentioned in the title without any specific functions that may or may not exist for this[]. Something along the lines of using mostly loops.
I tought about reversing each individual row using... | Transforming a matrix by placing its elements in the reverse order of the initial in python | im looking to solve the problem mentioned in the title without any specific functions that may or may not exist for this[]. Something along the lines of using mostly loops.
I tought about reversing each individual row using list.reverse() and then moving the rows around but im not sure how to implement it.
| [
"try this new realization and this will not change the original Matrix\nMatrix = [[1,2,3],[4,5,6],[7,8,9]]\nnewMatrix = []\nfor line in range(len(Matrix)):\n newMatrix.append(sorted(Matrix[line],reverse=True))\n\nnewMatrix.reverse()\nprint(newMatrix)\nprint(Matrix)\n\noutput:\n[[9, 8, 7], [6, 5, 4], [3, 2, 1]]\n... | [
-1
] | [
"Try This\nMatrix = [[1,2,3],[4,5,6],[7,8,9]]\nnewMatrix = []\nfor line in range(len(Matrix)):\n Matrix[line].reverse()\n newMatrix.append(Matrix[line])\n\nnewMatrix.reverse()\nprint(newMatrix)\n\noutput\n[[9, 8, 7], [6, 5, 4], [3, 2, 1]]\n\n"
] | [
-1
] | [
"matrix",
"python"
] | stackoverflow_0074602732_matrix_python.txt |
Q:
solve_ivp discards imaginary part of complex solution
I am computing a solution to the free basis expansion of the dirac equation for electron-positron pairproduction. For this i need to solve a system of equations that looks like this:
Equation for pairproduction, from Mocken at al.
EDIT: This has been solved by ... | solve_ivp discards imaginary part of complex solution | I am computing a solution to the free basis expansion of the dirac equation for electron-positron pairproduction. For this i need to solve a system of equations that looks like this:
Equation for pairproduction, from Mocken at al.
EDIT: This has been solved by passing y0 as complex type into the solver. As is stated in... | [
"According to the documentation, the y0 passed to solve_ivp must be of type complex in order for the integration to be over the complex domain. A robust way of ensuring this is to add the following to your code:\ndef solver(tmin, tmax,teval=None,f0=0,g0=1):\n '''solves the system.\n @tmin: starttime\n @tma... | [
0
] | [] | [] | [
"physics",
"python"
] | stackoverflow_0074602588_physics_python.txt |
Q:
Index page on FPDF. How to write to an existing page?
This question is related to this one.
I need to add an index page to the PDF and it needs to be placed after the main page.
So, the index should be on page 2 onwards.
I can add a blank page as a placeholder so that the others get the correct page number, then a... | Index page on FPDF. How to write to an existing page? | This question is related to this one.
I need to add an index page to the PDF and it needs to be placed after the main page.
So, the index should be on page 2 onwards.
I can add a blank page as a placeholder so that the others get the correct page number, then at the end when all pages are created I need to go back to t... | [
"Well, it's easier than I thought, I'll leave it here just in case someone stumbles upon the same issue.\n1 step: calculate the number of pages the index will need and add them as blank pages, not required, but will make the page numbers correct already\n2 step: before finalizing the document, use self.page = 2 to ... | [
0
] | [] | [] | [
"fpdf",
"python"
] | stackoverflow_0074465361_fpdf_python.txt |
Q:
Splitting lists into to different lists
I have a list:
list = [['X', 'Y'], 'A', 1, 2, 3]
That I want to split into:
new_list = [['X','A', 1, 2, 3] , ['Y', 'A', 1, 2, 3]]
Is this possible?
A:
Sure, take off the first element to create an outer loop, and then loop over the rest of the list to build the sub-list... | Splitting lists into to different lists | I have a list:
list = [['X', 'Y'], 'A', 1, 2, 3]
That I want to split into:
new_list = [['X','A', 1, 2, 3] , ['Y', 'A', 1, 2, 3]]
Is this possible?
| [
"Sure, take off the first element to create an outer loop, and then loop over the rest of the list to build the sub-lists:\nlst = [['X', 'Y'], 'A', 1, 2, 3]\n\nnew_list = []\n\nfor item in lst[0]:\n sub = [item]\n for sub_item in lst[1:]:\n sub.append(sub_item)\n new_list.append(sub)\n\nOr, as a com... | [
2,
2,
0,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0074603020_list_python.txt |
Q:
How to loop the maze
I'm a beginner with python. I couldn't figure out how to start new game in my maze.
I have tried various options but they all end whe with errors. What should I do? Thank you in advance.
I have tried destroy the frame_top where maze is located then create another maze with function new_game. B... | How to loop the maze | I'm a beginner with python. I couldn't figure out how to start new game in my maze.
I have tried various options but they all end whe with errors. What should I do? Thank you in advance.
I have tried destroy the frame_top where maze is located then create another maze with function new_game. But this function calls err... | [
"You use two different ways to create a new game. So it's differ from each other and you do not understand what you make wrong.One them main flow and other one is new_game method. I just merged them.\nSecond thing is you destroy your frame and your canvas inside it. So you also destroyed your canvas this is why yo ... | [
0
] | [] | [] | [
"python",
"python_3.x",
"tkinter",
"tkinter_canvas"
] | stackoverflow_0074551500_python_python_3.x_tkinter_tkinter_canvas.txt |
Q:
Generate JSON object from json-path in python
I have a list of json path-s and some values for every path, for example:
bla.[0].ble with a value: 3
and I would like to generate a json object where to output will look like this:
{
"bla": [
{
"ble": 3
}
]
}
To find the expression in the json I us... | Generate JSON object from json-path in python | I have a list of json path-s and some values for every path, for example:
bla.[0].ble with a value: 3
and I would like to generate a json object where to output will look like this:
{
"bla": [
{
"ble": 3
}
]
}
To find the expression in the json I used jsonpath-ng library, but now I want to do the ot... | [
"As a workaround my solution was to build a new dictionary using the expressions (or their hash) as keys and the values as the values:\ngenerated_json[hash(bla.[0].ble)] = 3\nSo even though the json object doesn't match the expected output format, I can use this to lookup my expressions as they describe unique path... | [
0
] | [] | [] | [
"json",
"jsonpath",
"python"
] | stackoverflow_0074562160_json_jsonpath_python.txt |
Q:
Error occuring when I try to run decorator with @ - Python
I am having a problem with the following programm.
When I try to run decorator the easier way, using @ like this
def decorator1(fun):
def wrapper():
text = '------'
return text + '\n' + fun + '\n' + text
return wrapper()
def decor... | Error occuring when I try to run decorator with @ - Python | I am having a problem with the following programm.
When I try to run decorator the easier way, using @ like this
def decorator1(fun):
def wrapper():
text = '------'
return text + '\n' + fun + '\n' + text
return wrapper()
def decorator2(fun):
def wrapper():
return fun.upper()
... | [
"First of all, a decorator is a function that accepts a function and returns a function. Thus, do not call the wrapper, but return it. Moreover, the fun method should be called.\ndef decorator1(fun):\n def wrapper():\n text = \"------\"\n return text + \"\\n\" + fun() + \"\\n\" + text\n\n return... | [
0,
0
] | [] | [] | [
"decorator",
"python"
] | stackoverflow_0074603169_decorator_python.txt |
Q:
I want to insert an audio at a certain time on the video using moviepy.editor
I want to insert an audio at a certain time on the video using moviepy.editor, how do I do it?, or do you have another way? please show me.
Examples like this:enter image description here
I was expecting someone to answer me, because I s... | I want to insert an audio at a certain time on the video using moviepy.editor | I want to insert an audio at a certain time on the video using moviepy.editor, how do I do it?, or do you have another way? please show me.
Examples like this:enter image description here
I was expecting someone to answer me, because I searched for a long time but couldn't.
| [
"you could use this :\nclip.set_audio(CompositeAudioClip([audioclip.set_start(3)]))\nand start your audio wherever you want\n"
] | [
0
] | [] | [] | [
"ffmpeg",
"moviepy",
"python"
] | stackoverflow_0074553269_ffmpeg_moviepy_python.txt |
Q:
Multiply list by all elements of the list except at it's own index
I'm trying to build a function that given a list will return a list with the elements multiplied together, excluding the element that was at the same index. For example for the list [1,2,3,4] it would return [2*3*4,1*3*4,1*2*3].
This is what I trie... | Multiply list by all elements of the list except at it's own index | I'm trying to build a function that given a list will return a list with the elements multiplied together, excluding the element that was at the same index. For example for the list [1,2,3,4] it would return [2*3*4,1*3*4,1*2*3].
This is what I tried
import numpy as np
def my_function(ints):
products = np.ones(len(ints)... | [
"with numpy this is easy:\nimport numpy as np\ndef fun(input):\n arr = np.array(input)\n return arr.prod() / arr\n\n",
"Taking from @interjay's comment:\nfrom operator import mul\n\ntotal = reduce(mul, ints)\nmultiplied = [total/y for y in ints]\n\n",
"Solution with enumerate:\ndef my_function(ints):\n ... | [
5,
3,
2,
1,
1,
1,
0,
0,
0
] | [] | [] | [
"list",
"numpy",
"python"
] | stackoverflow_0036288124_list_numpy_python.txt |
Q:
How to pass dynamic strings to pydantic fields
I have this code in my framework on Python 3.10 + Pydantic
class DataInclude(BaseModel):
currencyAccount: Literal["CNY счет", "AMD счет", "RUB счет", "USD счет", "EUR счет", "GBP счет", "CHF счет"]
I want to learn how to do it right to use dynamic parameters in a... | How to pass dynamic strings to pydantic fields | I have this code in my framework on Python 3.10 + Pydantic
class DataInclude(BaseModel):
currencyAccount: Literal["CNY счет", "AMD счет", "RUB счет", "USD счет", "EUR счет", "GBP счет", "CHF счет"]
I want to learn how to do it right to use dynamic parameters in a string
name = (CNY, AMD, RUB, USD, EUR, GBP, CHF)
c... | [
"As I mentioned in my comment already, you cannot dynamically specify a typing.Literal type.\nInstead of doing that, you could just create your own enum.Enum to represent the valid currency options. Pydantic plays nicely with those. And the Enum functional API allows you to set it up dynamically.\nfrom enum import ... | [
2
] | [] | [] | [
"pydantic",
"python"
] | stackoverflow_0074602819_pydantic_python.txt |
Q:
Python imports: module not found from same level module
In the terminal
> python mod1/script1.py
>> ModuleNotFoundError: No module named 'mod2'
I have followed the guide about imports and numerous other stack overflows about htis very basic problem, and I don't get why it's not working. Pylance is able to resolv... | Python imports: module not found from same level module |
In the terminal
> python mod1/script1.py
>> ModuleNotFoundError: No module named 'mod2'
I have followed the guide about imports and numerous other stack overflows about htis very basic problem, and I don't get why it's not working. Pylance is able to resolve the modules. - Using Python 3.10.7 64-bit.
Every module ha... | [
"you want to import a module from a different directory , am I understood correctly?\nso python will only look for the files & modules in its current directory and\nyou cannot refer to another directory simply by putting the folder name before the module name\n\nyou must import the path of a different directory , u... | [
0
] | [] | [] | [
"import",
"python"
] | stackoverflow_0074602687_import_python.txt |
Q:
Wagtail - How to set rich text value in nested block (StreamField->StructBlock->RichTextBlock)
I have the following structure:
`class ParagraphWithRelatedLinkBlock(blocks.StructBlock):
text = blocks.RichTextBlock()
related_link = blocks.ListBlock(blocks.URLBlock())
class BlogPageSF(Page):
body = Strea... | Wagtail - How to set rich text value in nested block (StreamField->StructBlock->RichTextBlock) | I have the following structure:
`class ParagraphWithRelatedLinkBlock(blocks.StructBlock):
text = blocks.RichTextBlock()
related_link = blocks.ListBlock(blocks.URLBlock())
class BlogPageSF(Page):
body = StreamField(
[
("paragraph", ParagraphWithRelatedLinkBlock(),
], use_json_fie... | [
"The values you insert into StreamField data should not be instances of the Block class - block instances are only used as part of the stream definition (for example, when you write text = blocks.RichTextBlock(), you're creating an instance of RichTextBlock that forms part of the ParagraphWithRelatedLinkBlock defin... | [
0
] | [] | [] | [
"django",
"python",
"wagtail"
] | stackoverflow_0074601679_django_python_wagtail.txt |
Q:
Python::Not reading data correctly from the file in S3
Requirement: To read data from S3 to pass into API
Error: "error": {"code": "ModelStateInvalid", "message": "The request has exceeded the maximum number of validation errors.", "target": "HttpRequest"
When I pass data directly in the code as below document , i... | Python::Not reading data correctly from the file in S3 | Requirement: To read data from S3 to pass into API
Error: "error": {"code": "ModelStateInvalid", "message": "The request has exceeded the maximum number of validation errors.", "target": "HttpRequest"
When I pass data directly in the code as below document , it works fine as below
def create_doc(self,client):
s... | [
"Checking the source code:\ndef read_key(self, key, bucket_name=None):\n \"\"\"\n Reads a key from S3\n\n :param key: S3 key that will point to the file\n :type key: str\n :param bucket_name: Name of the bucket in which the file is stored\n :type bucket_name: str\n \"\"\"\n\n obj = self.get_... | [
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074603235_python_python_3.x.txt |
Q:
How to pass Python's time function to Jinja2 template using FastAPI?
I send a time.time() variable t0 to my template from FastAPI, which is the time update was triggered:
return templates.TemplateResponse("jobs.html", {
"request": request, "jobs": sorted(out, key=lambda d: d['id'], reverse=True),
"project_id... | How to pass Python's time function to Jinja2 template using FastAPI? | I send a time.time() variable t0 to my template from FastAPI, which is the time update was triggered:
return templates.TemplateResponse("jobs.html", {
"request": request, "jobs": sorted(out, key=lambda d: d['id'], reverse=True),
"project_ids": ','.join([str(id) for id in myids]),
"sorted_collumn": 'id',
"fi... | [
"Looking at the source code of Starlette (i.e., startlette/templating.py)\nYou can see the following line:\nenv.globals[\"url_for\"] = url_for in:\nSo adding the line:\ntemplates.env.globals[\"now\"] = time.time\n\nbefore the return template above fixes it, and adding the below to jobs.html template:\ntime: {{ \"{0... | [
1
] | [] | [] | [
"fastapi",
"jinja2",
"python"
] | stackoverflow_0074602664_fastapi_jinja2_python.txt |
Q:
'ffmpeg' is not recognized as an internal or external command,
I have to convert a .TS file to MP4 File and for that I am using subprocess to convert it.
for this I have written a python file.
import subprocess
infile = 'vidl.ts'
subprocess.run(['ffmpeg', '-i', infile, 'out.mp4'])
I have also added ffmpeg to envi... | 'ffmpeg' is not recognized as an internal or external command, | I have to convert a .TS file to MP4 File and for that I am using subprocess to convert it.
for this I have written a python file.
import subprocess
infile = 'vidl.ts'
subprocess.run(['ffmpeg', '-i', infile, 'out.mp4'])
I have also added ffmpeg to environment variables path.
also when I type ffmpeg in cmd it shows the ... | [
"As @tripleee noted in the comment, you need to look into your system PATH setting. If you'd like to try an easier fix, you can try my ffmpeg-downloader package.\nTwo lines of commands in command window (then close and reopen the python window) should do the job for you:\npip install ffmpeg-downloader\n\nffdl insta... | [
0
] | [] | [] | [
"ffmpeg",
"mp4",
"python",
"videoconverter"
] | stackoverflow_0074598999_ffmpeg_mp4_python_videoconverter.txt |
Q:
BeautifulSoup object looks totally different from what I see in Chrome
I am in my first attempt in scraping react-based dynamic website - Booking.com search result page. I want to collect the current price of specific hotels under the same conditions.
This site was easy to scrape data with simple CSS selector befo... | BeautifulSoup object looks totally different from what I see in Chrome | I am in my first attempt in scraping react-based dynamic website - Booking.com search result page. I want to collect the current price of specific hotels under the same conditions.
This site was easy to scrape data with simple CSS selector before, but now they changed how to code and every elements what I want is descr... | [
"The below code is producing the exact output what the browser displayed\nimport time\nfrom bs4 import BeautifulSoup\nimport pandas as pd\nfrom selenium.webdriver.chrome.service import Service\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\n\n\nwebdriver_service = Service(\"./chromedri... | [
1
] | [] | [] | [
"beautifulsoup",
"python",
"python_3.x",
"selenium",
"web_scraping"
] | stackoverflow_0074601834_beautifulsoup_python_python_3.x_selenium_web_scraping.txt |
Q:
ns3, Python3 has no module named 'ns'
I am using a virtual box to build network simulator 3(ns3), Ubuntu version: Linux Server 20.04 LTS
the Linux command that I had executed are
sudo apt-get update
sudo apt-get upgrade
sudo apt-get install gcc g++ python python3 -y
sudo apt-get install python3-setuptools git merc... | ns3, Python3 has no module named 'ns' | I am using a virtual box to build network simulator 3(ns3), Ubuntu version: Linux Server 20.04 LTS
the Linux command that I had executed are
sudo apt-get update
sudo apt-get upgrade
sudo apt-get install gcc g++ python python3 -y
sudo apt-get install python3-setuptools git mercurial -y
sudo apt-get install zip unzip
a... | [
"The problem\n\"import ns.applications\"\nModuleNotFoundError: No module named 'ns'\nis because there is a problem with the ns-3 installation and it is not able to do python binding itself and you need to manually configure it.\nIn my case, I have python 2.7 also installed\nGo to \n-> cd [PATH-to-your-ns3.29]\n-> ... | [
0,
0
] | [] | [] | [
"ns_3",
"python",
"python_3.x",
"ubuntu",
"waf"
] | stackoverflow_0061670851_ns_3_python_python_3.x_ubuntu_waf.txt |
Q:
How can I solve the error "AttributeError: 'bool' object has no attribute 'items'" when I print graphs?
I'm trying to make a program able to print wafermaps and histograms for each value selected.
To achieve that, I've made one button to show the graphics of the next parameter selected from the list.
The histogram... | How can I solve the error "AttributeError: 'bool' object has no attribute 'items'" when I print graphs? | I'm trying to make a program able to print wafermaps and histograms for each value selected.
To achieve that, I've made one button to show the graphics of the next parameter selected from the list.
The histogram is shown as I want for every parameter, but it doesn't work for the wafermap graph and it shows this error.
... | [
"Not sure where in your code this comes up but it sounds like you have some variable that is a boolean and you tried to access it like\nsomebool.items and Python is telling you that somebool has no attribute items\n"
] | [
0
] | [] | [] | [
"boolean",
"graph",
"pyqt",
"pyqt6",
"python"
] | stackoverflow_0074559026_boolean_graph_pyqt_pyqt6_python.txt |
Q:
How would I find the longest string per row in a data frame and print the row number if it exceeds a certain amount
I want to write a program which searches through a data frame and if any of the items in it are above 50 characters long, print the row number and ask if you want to continue through the data frame.
... | How would I find the longest string per row in a data frame and print the row number if it exceeds a certain amount | I want to write a program which searches through a data frame and if any of the items in it are above 50 characters long, print the row number and ask if you want to continue through the data frame.
threshold = 50
mask = (df.drop(columns=exclude, errors='ignore')
.apply(lambda s: s.str.len().ge(threshold))
... | [
"You can use:\nexclude = []\nthreshold = 30\n\nmask = (df.drop(columns=exclude, errors='ignore')\n .apply(lambda s: s.str.len().ge(threshold))\n )\n\ns = mask.any(axis=1)\n\nfor idx in s[s].index:\n print(f'row {idx} is above the {threshold}-character limit.')\n s2 = mask.loc[idx]\n for str... | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074603152_dataframe_pandas_python.txt |
Q:
Make Alexa Skill play audio
I've tried very hard to figure out how to make my Alexa skill to play audio but I cannot find a solution. I emailed the amazon developer support and they sent me the following code. I would love it if someone could explain to me the logic behind this code. Also, how would I make this co... | Make Alexa Skill play audio | I've tried very hard to figure out how to make my Alexa skill to play audio but I cannot find a solution. I emailed the amazon developer support and they sent me the following code. I would love it if someone could explain to me the logic behind this code. Also, how would I make this code into a fully functional Alexa ... | [
"I understand you are trying to play a streaming music station, if this is the case, this will be implemented using AudioPlayer interface, please find more information on the link below:\nhttps://developer.amazon.com/en-US/docs/alexa/custom-skills/audioplayer-interface-reference.html\nThere is an AudioPlayer sample... | [
0
] | [] | [] | [
"alexa_app",
"alexa_skill",
"python",
"python_3.x"
] | stackoverflow_0061902502_alexa_app_alexa_skill_python_python_3.x.txt |
Q:
I need to copy data from json file to Postgress
I need to copy data from json file to Postgresql database. I have a json file that have 9000 users with information about them, that looks like this:
"name": "Kathryn", "time_created": 1665335716, "gender": "female", "age": 38, "last_name": "Smith", "ip": "192.168.0.... | I need to copy data from json file to Postgress | I need to copy data from json file to Postgresql database. I have a json file that have 9000 users with information about them, that looks like this:
"name": "Kathryn", "time_created": 1665335716, "gender": "female", "age": 38, "last_name": "Smith", "ip": "192.168.0.110", "city": "NY", "premium": null, "birth_day": "0... | [
"@George Rybojchuk\ncheck complete sql :\ndrop table if exists sample_json;\ndrop table if exists target;\ncreate table sample_json(record json not null);\ncreate table target(name varchar(20),time_created varchar(20));\ninsert into sample_json(record) values('{\"name\": \"Kathryn\", \"time_created\": 1665335716, \... | [
0
] | [] | [] | [
"json",
"postgresql",
"python",
"python_3.x",
"sql"
] | stackoverflow_0074603117_json_postgresql_python_python_3.x_sql.txt |
Q:
Numpy: Average of values corresponding to unique coordinate positions
So, I have been browsing stackoverflow for quite some time now, but I can't seem to find the solution for my problem
Consider this
import numpy as np
coo = np.array([[1, 2], [2, 3], [3, 4], [3, 4], [1, 2], [5, 6], [1, 2]])
values = np.array([1, ... | Numpy: Average of values corresponding to unique coordinate positions | So, I have been browsing stackoverflow for quite some time now, but I can't seem to find the solution for my problem
Consider this
import numpy as np
coo = np.array([[1, 2], [2, 3], [3, 4], [3, 4], [1, 2], [5, 6], [1, 2]])
values = np.array([1, 2, 4, 2, 1, 6, 1])
The coo array contains the (x, y) coordinate positions
... | [
"You can sort coo with np.lexsort to bring the duplicate ones in succession. Then run np.diff along the rows to get a mask of starts of unique XY's in the sorted version. Using that mask, you can create an ID array that would have the same ID for the duplicates. The ID array can then be used with np.bincount to get... | [
7,
2,
1,
1,
0
] | [] | [] | [
"arrays",
"numpy",
"python"
] | stackoverflow_0031878240_arrays_numpy_python.txt |
Q:
Python: Class method that references today's date, unless class is __init__ with something else
I am probably overengineering this - but I was hoping some can help me understand why this isn't working. My goal was to build a class that primarily uses classmethods, except in the case where a user creates an instan... | Python: Class method that references today's date, unless class is __init__ with something else | I am probably overengineering this - but I was hoping some can help me understand why this isn't working. My goal was to build a class that primarily uses classmethods, except in the case where a user creates an instance of the class so that they can change the assumed internal date.
import datetime as dt
class Examp... | [
"Here's how I would implement the behaviour that you want.\nclass Example():\n ref_date = dt.date.today()\n \n def __init__(self, ref_date=None):\n if ref_date:\n self.ref_date = ref_date\n\n>>> Example.ref_date\ndatetime.date(2022, 11, 28)\n>>> example_instance = Example(dt.date(2021,6,1... | [
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0074603379_python.txt |
Q:
Bash alias is not detected despite updating .bashrc with alias
I'm trying to set an alias for python to python3, and so far in .bashrc I have set the following:
.bashrc
alias python=python3
Following which, I ran: source ~/.bashrc. However, when I execute which python, it still points to /usr/bin/python, while w... | Bash alias is not detected despite updating .bashrc with alias | I'm trying to set an alias for python to python3, and so far in .bashrc I have set the following:
.bashrc
alias python=python3
Following which, I ran: source ~/.bashrc. However, when I execute which python, it still points to /usr/bin/python, while which python3 returns /user/bin/python3.
I'm currently using bash she... | [
"by definition, \"which\" will always show the full path of your shell commands, in your case, which python will show /usr/bin/python and for python3 /usr/bin/python3.SO what your system is doing is correct.\nAn alias definition provides a string value that replaces a command name when the command is read. The alia... | [
0
] | [] | [] | [
"bash",
"python",
"python_3.x"
] | stackoverflow_0074601847_bash_python_python_3.x.txt |
Q:
Pipeline must be list Airflow
writing a DAG in airflow to extract sum of balance but getting error
import logging
import json
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
from datetime import datetime
from airflow import DAG
from airflow.operators.python import PythonOperator
from ... | Pipeline must be list Airflow | writing a DAG in airflow to extract sum of balance but getting error
import logging
import json
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
from datetime import datetime
from airflow import DAG
from airflow.operators.python import PythonOperator
from airflow import AirflowException
# C... | [
"my best guess of where your error lies is in either of the two 'aggregate' calls. That is, one/both of these lines has a bug:\n query = db.wallets.aggregate([{'$group': {'_id': None, 'count': {'$sum': '$balance.value'}}}])\n \n wallets_collection = db.aggregate(\"wallets\", query=query)\n\nI googled your err... | [
0
] | [] | [] | [
"airflow",
"list",
"mongodb",
"python"
] | stackoverflow_0074600095_airflow_list_mongodb_python.txt |
Q:
twine not found (-bash: twine: command not found)
I am trying to use twine to publish my first python package on pypi (of course will add on test-pypi first).
I followed the official guideline on https://packaging.python.org/tutorials/packaging-projects/.
But for some reason, twine is not found or not properly i... | twine not found (-bash: twine: command not found) | I am trying to use twine to publish my first python package on pypi (of course will add on test-pypi first).
I followed the official guideline on https://packaging.python.org/tutorials/packaging-projects/.
But for some reason, twine is not found or not properly installed.
I installed twine using:
pip install twine
... | [
"Use python3 -m twine upload --repository-url https://test.pypi.org/legacy/ dist/*\n",
"Based on @hoefling comments run\npip show twine\n\nThat will list all files that belong to the twine package. It will output something like this:\n\nName: twine\nVersion: 1.12.1\nSummary: Collection of utilities for publishing... | [
27,
2,
0
] | [] | [] | [
"pip",
"pypi",
"python",
"twine"
] | stackoverflow_0051451966_pip_pypi_python_twine.txt |
Q:
Filling data in one column if there are matching values in another column
I have a DF with parent/child items and I need to associate a time for the parent to all the children items. The time is only listed when the parent matches the child and I need that time to populate on all the children.
This is a simple ex... | Filling data in one column if there are matching values in another column | I have a DF with parent/child items and I need to associate a time for the parent to all the children items. The time is only listed when the parent matches the child and I need that time to populate on all the children.
This is a simple example.
data = {
'Parent' : ['a123', 'a123', 'a123', 'a123', 'a234', 'a234... | [
"If time is positive for the parent, or null, you can use a simple groupby.transform('max'):\ndf['Time'] = df.groupby('Parent')['Time'].transform('max')\n\nElse, you can use:\ndf['Time'] = (df['Time']\n .where(df['Parent'].eq(df['Child']))\n .groupby(df['Parent']).transform('first')\n .convert_dtypes()\n)\n\nOutput... | [
-1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074603334_dataframe_pandas_python.txt |
Q:
How to automatically save text file after specific time in python?
This is my keylogger code:
import pynput
from pynput.keyboard import Key, Listener
from datetime import datetime, timedelta, time
import time
start = time.time()
now=datetime.now()
dt=now.strftime('%d%m%Y-%H%M%S')
keys=[]
def on_press(key):
... | How to automatically save text file after specific time in python? | This is my keylogger code:
import pynput
from pynput.keyboard import Key, Listener
from datetime import datetime, timedelta, time
import time
start = time.time()
now=datetime.now()
dt=now.strftime('%d%m%Y-%H%M%S')
keys=[]
def on_press(key):
keys.append(key)
write_file(keys)
try:
print(key.char)
... | [
"The most important problem is that you did not reset the timer. After f.close(), end_time should be transferred into start_time.\nAlso, since you call write() for every event, there is no reason to accumulate into keys[].\nAlso, you never empty keys[].\n",
"I executed your program and found 2 problems.\nThe firs... | [
1,
0,
0
] | [] | [] | [
"keylogger",
"python"
] | stackoverflow_0074534026_keylogger_python.txt |
Q:
Dataset for a python application
I am working on an application to predict a disease from it's symptoms, I have some trouble making a dataset.
If someone has a dataset on this, please link it to drive and share it here.
Also I have a question on a good model for this(sklearn only). I am currently using decision tr... | Dataset for a python application | I am working on an application to predict a disease from it's symptoms, I have some trouble making a dataset.
If someone has a dataset on this, please link it to drive and share it here.
Also I have a question on a good model for this(sklearn only). I am currently using decision tree classifier as my model for the proj... | [
"You can make your own from this csv template:\n\nSickness, Symptom1, Symptom2, Symptom4\nCovid-19, Cough, Loss of taste, Fever, Chills\nCommon Cold, Sneezing, Cough, Runny Nose, Headache\n\nignore bullet points, just for formatting. then use pandas read csv to read the data. if u need more help @mention me\n",
"... | [
0,
0
] | [] | [] | [
"data_science",
"dataset",
"machine_learning",
"python",
"scikit_learn"
] | stackoverflow_0074603450_data_science_dataset_machine_learning_python_scikit_learn.txt |
Q:
TKinter app - not showing frames in oop approach
Something must have gone wrong in my TKinter project when I restructured the code to conform to the OOP paradigm.
The MainFrame is no longer displayed. I would expect a red frame after running the code below, but it just shows a blank window.
import tkinter as tk
fr... | TKinter app - not showing frames in oop approach | Something must have gone wrong in my TKinter project when I restructured the code to conform to the OOP paradigm.
The MainFrame is no longer displayed. I would expect a red frame after running the code below, but it just shows a blank window.
import tkinter as tk
from tkinter import ttk
class App(tk.Tk):
def __ini... | [
"You should also manage the geometry of your MainFrame inside the App, for example by packing it:\nimport tkinter as tk\nfrom tkinter import ttk\n\nclass App(tk.Tk):\n def __init__(self):\n super().__init__()\n self.title(\"App\")\n self.geometry(\"800x600\")\n\n main_frame = MainFram... | [
1
] | [] | [] | [
"python",
"tkinter",
"user_interface"
] | stackoverflow_0074602995_python_tkinter_user_interface.txt |
Q:
How to convert CSV to parquet file without RLE_DICTIONARY encoding?
I've already test three ways of converting a csv file to a parquet file. You can find them below. All the three created the parquet file. I've tried to view the contents of the parquet file using "APACHE PARQUET VIEWER" on Windows and I always got... | How to convert CSV to parquet file without RLE_DICTIONARY encoding? | I've already test three ways of converting a csv file to a parquet file. You can find them below. All the three created the parquet file. I've tried to view the contents of the parquet file using "APACHE PARQUET VIEWER" on Windows and I always got the following error message:
"encoding RLE_DICTIONARY is not supported"... | [
"You should set use_dictionary to False:\nimport pandas as pd\ndf = pd.read_csv(\"filename.csv\")\ndf.to_parquet(\"filename.parquet\", use_dictionary=False)\n\n"
] | [
0
] | [] | [] | [
"csv",
"parquet",
"python"
] | stackoverflow_0073572870_csv_parquet_python.txt |
Q:
does the @property decorator function as a getter?
i am new to python and i'm trying to understand the use of the 'getter'. it's use case is not obvious to me.
if i use a property decorator on a method and im able to return a certain value, what exactly would i use 'getter' for.
class Person:
def __init__(sel... | does the @property decorator function as a getter? | i am new to python and i'm trying to understand the use of the 'getter'. it's use case is not obvious to me.
if i use a property decorator on a method and im able to return a certain value, what exactly would i use 'getter' for.
class Person:
def __init__(self,name, age):
self._name = name
self._ag... | [
"The @property decorator adds a default getter on a given field in a Python class\nthat triggers a function call upon accessing a property.\nThe @property decorator turns the age() method into a “getter” for a read-only attribute with the same name. If want a “setter” then add @age.setter as you did in your questio... | [
2,
1
] | [] | [] | [
"getter",
"properties",
"python",
"python_decorators"
] | stackoverflow_0074603360_getter_properties_python_python_decorators.txt |
Q:
How can i fix the gas price issue in Thirdweb Python SDK Goerli TestNet
Im working with the Thirdweb Python SDK API. The code below sometimes work and sometimes throws a gasprice issue. I think it could be a network issue, because it works sometimes and generates the NFT but not always.
And when i got an error it ... | How can i fix the gas price issue in Thirdweb Python SDK Goerli TestNet | Im working with the Thirdweb Python SDK API. The code below sometimes work and sometimes throws a gasprice issue. I think it could be a network issue, because it works sometimes and generates the NFT but not always.
And when i got an error it is about gasprice. But in the Thirdweb API doesnt appear a gasprice argument ... | [
"What network are you seeing this issue on? We can add in a method to manually overwrite gas limits in the SDK.\n"
] | [
1
] | [] | [] | [
"price",
"python",
"sdk",
"thirdweb"
] | stackoverflow_0074447448_price_python_sdk_thirdweb.txt |
Q:
How to get UTC time in Python?
How do I get the UTC time, i.e. milliseconds since Unix epoch on Jan 1, 1970?
A:
For Python 2 code, use datetime.utcnow():
from datetime import datetime
datetime.utcnow()
For Python 3, use datetime.now(timezone.utc) (the 2.x solution will technically work, but has a giant warning ... | How to get UTC time in Python? | How do I get the UTC time, i.e. milliseconds since Unix epoch on Jan 1, 1970?
| [
"For Python 2 code, use datetime.utcnow():\nfrom datetime import datetime\ndatetime.utcnow()\n\nFor Python 3, use datetime.now(timezone.utc) (the 2.x solution will technically work, but has a giant warning in the 3.x docs):\nfrom datetime import datetime, timezone\ndatetime.now(timezone.utc)\n\nFor your purposes wh... | [
279,
169,
47,
22,
15,
10,
6,
4
] | [
"To be correct, UTC format needs at least the T letter:\n>>> a=(datetime.datetime.now(timezone.utc))\n>>> a.strftime(\"%Y-%m-%dT%H:%M:%SZ\")\n'2022-11-28T16:42:17Z'\n\n"
] | [
-2
] | [
"datetime",
"python"
] | stackoverflow_0015940280_datetime_python.txt |
Q:
Pyhton requests library passing Authorization header with single token, still getting 403
Code-
HEADER= {
'Authorization': f'Token {TOKEN}'
}
resp= requests.request(
"GET",
url,
headers=HEADER
)
Error message-
{'detail': 'Authentication credentials were not provided.'}
resp.request.headers outpu... | Pyhton requests library passing Authorization header with single token, still getting 403 | Code-
HEADER= {
'Authorization': f'Token {TOKEN}'
}
resp= requests.request(
"GET",
url,
headers=HEADER
)
Error message-
{'detail': 'Authentication credentials were not provided.'}
resp.request.headers output
{'User-Agent': 'python-requests/2.28.1', 'Accept-Encoding': 'gzip, deflate', 'Accept': 'appli... | [
"'Authentication credentials were not provided.' should be 401, and, 403 means you don't have the permission, maybe you should talk to the api provider.\n"
] | [
0
] | [] | [] | [
"api",
"python",
"python_requests"
] | stackoverflow_0074603592_api_python_python_requests.txt |
Q:
Reading array returned by c function in ctypes
I've got some C code, which I'm trying to access from ctypes in python. A particular function looks something like this:
float *foo(void) {
static float bar[2];
// Populate bar
return bar;
}
I know this isn't an ideal way to write C, but it does the job ... | Reading array returned by c function in ctypes | I've got some C code, which I'm trying to access from ctypes in python. A particular function looks something like this:
float *foo(void) {
static float bar[2];
// Populate bar
return bar;
}
I know this isn't an ideal way to write C, but it does the job in this case. I'm struggling to write the python to... | [
"Specify restypes as [POINTER][1](c_float):\nimport ctypes\n\nlibfoo = ctypes.cdll.LoadLibrary('./foo.so')\nfoo = libfoo.foo\nfoo.argtypes = ()\nfoo.restype = ctypes.POINTER(ctypes.c_float)\nresult = foo()\nprint(result[0], result[1])\n\n",
"Thanks to @falsetru, believe I found a somehow better solution, which ta... | [
11,
0
] | [] | [] | [
"c",
"ctypes",
"python"
] | stackoverflow_0018044468_c_ctypes_python.txt |
Q:
Shift error bars in seaborn barplot with two categories?
I am trying to plot some error bars on tope of a seaborn bar plot made with catplot as below. DF output from .to_clipboard(sep=',', index=True).
Melted DF:
,Parameter,Output,Sobol index,Value
0,$μ_{max}$,P,Total-effect,0.956747485
1,$μ_{max}$,D,Total-effect,... | Shift error bars in seaborn barplot with two categories? | I am trying to plot some error bars on tope of a seaborn bar plot made with catplot as below. DF output from .to_clipboard(sep=',', index=True).
Melted DF:
,Parameter,Output,Sobol index,Value
0,$μ_{max}$,P,Total-effect,0.956747485
1,$μ_{max}$,D,Total-effect,-3.08778755e-08
2,$μ_{max}$,I,Total-effect,0.18009523
3,$μ_{ma... | [
"You plot categorical values (the x values are strings), the x positions of the (center of the) bar groups and the error bars the way you plotted them are range(n) where n is the number of parameters. These x positions can also be retrieved by ax.xaxis.get_majorticklocs().\nTo put the error bars in the middle of th... | [
2
] | [] | [] | [
"bar_chart",
"matplotlib",
"python",
"seaborn"
] | stackoverflow_0074540942_bar_chart_matplotlib_python_seaborn.txt |
Q:
TypeError: 'bool' object is not callable in python module tinydb
I have error TypeError: 'bool' object is not callable, when try to use function search in tinydb
My code:
from tinydb import TinyDB, Query
db = TinyDB('db.json')
User = Query()
db.insert({'test': 'signs', 'age': 34})
res = db.search(User.test == 'sig... | TypeError: 'bool' object is not callable in python module tinydb | I have error TypeError: 'bool' object is not callable, when try to use function search in tinydb
My code:
from tinydb import TinyDB, Query
db = TinyDB('db.json')
User = Query()
db.insert({'test': 'signs', 'age': 34})
res = db.search(User.test == 'signs')
print(res)
`
| [
"It appears that \"test\" is a built-in function for a Query object.\nChanging test to name or anything else will fix issue.\nfrom tinydb import TinyDB, Query\ndb = TinyDB('db.json')\nUser = Query()\ndb.insert({'name': 'signs', 'age': 34})\nres = db.search(User.name == \"signs\")\nprint(f\"the search: {res}\")\npri... | [
0
] | [] | [] | [
"database",
"python"
] | stackoverflow_0074603001_database_python.txt |
Q:
my own python package - problem with path to model
I published python package on pypi.org structure looks like this:
/my_package_name-0.0.1
-- README LICENSE ETC..
-- /my_package_name
-- __init__.py
-- train_model.py
-- predict.py
-- /saved_models
-- november_model
In predict.py I have function ... | my own python package - problem with path to model | I published python package on pypi.org structure looks like this:
/my_package_name-0.0.1
-- README LICENSE ETC..
-- /my_package_name
-- __init__.py
-- train_model.py
-- predict.py
-- /saved_models
-- november_model
In predict.py I have function that loads model:
def my_function():
(some code...)
... | [
"The solution was to use importlib.resources in predict.py:\ntry:\n import importlib.resources as pkg_resources\nexcept ImportError:\n # Try backported to PY<37 `importlib_resources`.\n import importlib_resources as pkg_resources\nfrom my_package import saved_models\n\nand instead of:\nnet.load_model('save... | [
1
] | [] | [] | [
"pypi",
"python"
] | stackoverflow_0074577307_pypi_python.txt |
Q:
API can't find my API key in header even though i included it
I'm trying to use the tequila API to retrieve flight prices but the server keeps returning this error:
Traceback (most recent call last):
File "C:\Users\Senna\Downloads\flight-deals-step-2-solution\flight-deals-step-2-solution\main.py", line 37, in <m... | API can't find my API key in header even though i included it | I'm trying to use the tequila API to retrieve flight prices but the server keeps returning this error:
Traceback (most recent call last):
File "C:\Users\Senna\Downloads\flight-deals-step-2-solution\flight-deals-step-2-solution\main.py", line 37, in <module>
flight = flight_search.check_flights(
File "C:\Users\S... | [
"Im also doing the course and got absolutely trainwrecked on the header not being recognized.\nAfter 2 hours of trying every possible solution to make the header reach the API I recognized that I forgot to format date_to in the correct string format.\nSo despite the API is giving me header not found the issue was w... | [
0
] | [
"class FlightSearch:\n def __init__(self):\n self.code = {}\n\n def get_destination_code(self, city_name):\n location_endpoint = f\"{TEQUILA_ENDPOINT}/locations/query\"\n headers = {\"apikey\": TEQUILA_API_KEY}\n query = {\"term\": city_name, \"location_types\": \"city\"}\n ... | [
-1
] | [
"api",
"python"
] | stackoverflow_0068785225_api_python.txt |
Q:
Unable to get the price of a product on Amazon when using Beautiful Soup in python
I was trying to track the price of a product using beautiful soup but whenever I try to run this code, I get a 6 digit code which I assume has something to do with recaptcha. I have tried numerous times, checked the headers, the ur... | Unable to get the price of a product on Amazon when using Beautiful Soup in python | I was trying to track the price of a product using beautiful soup but whenever I try to run this code, I get a 6 digit code which I assume has something to do with recaptcha. I have tried numerous times, checked the headers, the url and the tags but nothing seems to work.
from bs4 import BeautifulSoup
import requests
... | [
"The \"a-price-whole\" class in inside the tags so BS4 is not able to find it. This solution worked for me, I just changed your \"find\" to a \"find_all\" and made it scan through all of the spans until you find the class you are searching for then used the iterator.get_text() to print the price. Hope this helps!\... | [
0
] | [] | [] | [
"amazon",
"bots",
"python",
"tracker",
"web_scraping"
] | stackoverflow_0074603033_amazon_bots_python_tracker_web_scraping.txt |
Q:
Why does super().__dict__ raise an AttributeError?
Why is this raising an AttributeError?
class A:
def f(self):
print(super().__dict__)
A().f() # raises AttributeError: 'super' object has no attribute '__dict__'
A:
super() delegates attribute access to the next class in MRO. In this case, object is... | Why does super().__dict__ raise an AttributeError? | Why is this raising an AttributeError?
class A:
def f(self):
print(super().__dict__)
A().f() # raises AttributeError: 'super' object has no attribute '__dict__'
| [
"super() delegates attribute access to the next class in MRO. In this case, object is an implicit parent class. Instances of object class do not contain the __dict__ attribute:\nobject().__dict__ # raises AttributeError\n\nHowever, instances of empty classes do contain the __dict__ attribute, so if A inherits from... | [
0
] | [
"I think attribute error comes many times with no reason , it happened with me so many times ....\nThe Only solution is that this method is no longer usable try to go though docs or use another one .\n"
] | [
-3
] | [
"magic_methods",
"python",
"python_descriptors"
] | stackoverflow_0074603550_magic_methods_python_python_descriptors.txt |
Q:
Trajectory plalnification
I have a program that generates circles and lines, where the circles can not collide with each other and the lines can not collide with the circles, the problem is that it only draws a line but not the others, it does not mark any error and as much as I think the reason I do not understan... | Trajectory plalnification | I have a program that generates circles and lines, where the circles can not collide with each other and the lines can not collide with the circles, the problem is that it only draws a line but not the others, it does not mark any error and as much as I think the reason I do not understand why, (I'm new to python, so e... | [
"You need to implement the colisionC and colisionL methods in Linea and Circulo. See Problem with calculating line intersections for the line-line intersection algorithm. When checking for collisions between lines and circles, in addition to checking for collisions between circles and endless lines, you must also c... | [
1
] | [] | [] | [
"class",
"pygame",
"python"
] | stackoverflow_0074595968_class_pygame_python.txt |
Q:
Filling a vector with a varying amount of variables
Hey currently I'm trying to program a quadratic programming algorithm with Python.
My goal:
I want to program a function where the given parameters are one vector c, and a matrix G. They are connected through the function Phi = 0.5 *(x^T * G * x) + c^T *x (x^T in... | Filling a vector with a varying amount of variables | Hey currently I'm trying to program a quadratic programming algorithm with Python.
My goal:
I want to program a function where the given parameters are one vector c, and a matrix G. They are connected through the function Phi = 0.5 *(x^T * G * x) + c^T *x (x^T in this context means vector x transposed). The goal of the... | [
"Sounds like an x y problem, because I don't understand how you are going to initialize those variables. If you provide more context I will update my answer.\nIf you want to have your list to contain variables or \"symbols\" on which you do algebraic operations, then the standard library doesn't have that, but you ... | [
1,
0
] | [] | [] | [
"arrays",
"python",
"variables"
] | stackoverflow_0074590267_arrays_python_variables.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.