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:
How do I determine which PIP library to download manually? (Parsing pypi.org json output)
I have all the details of my machine (Linux, Python 3.8). How can I determine which wheel file PIP would have downloaded without using pip install or pip download? The goal is to get the package details from (example) https:/... | How do I determine which PIP library to download manually? (Parsing pypi.org json output) | I have all the details of my machine (Linux, Python 3.8). How can I determine which wheel file PIP would have downloaded without using pip install or pip download? The goal is to get the package details from (example) https://pypi.org/pypi/pyarrow/json and then get the size of the wheel.
The json output is given, but t... | [
"Try:\nImport statements:\nimport requests\nimport re\n\nFunction to compare versions using pattern from setup.py (to best of my knowledge):\ndef compare_versions(compare_statement: str) -> bool:\n try:\n decompose = re.search(r\"(\\d+(\\.[\\d*]+)*)([^\\d*.]+)(\\d+(\\.[\\d*]+)*)\", compare_statement)\n ... | [
0
] | [] | [] | [
"pip",
"python"
] | stackoverflow_0074565967_pip_python.txt |
Q:
How to capture the output of loop through a dictionary for use outside the loop in Kivy/python using the .update() method?
I can't figure out how to print the whole output out of a loop from tested Kivy Minimal Reproducible Example below:
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
class Dat... | How to capture the output of loop through a dictionary for use outside the loop in Kivy/python using the .update() method? | I can't figure out how to print the whole output out of a loop from tested Kivy Minimal Reproducible Example below:
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
class DataTable(BoxLayout):
def __init__(self,table='', **kwargs):
super().__init__(**kwargs)
def build(self):
... | [
"From the documentation: the update method overwrites the values for the keys.\nTo keep things simple, consider only what happens to the key '1'.\nOn the first iteration the value is set to {0: 'TESTa'}. On the second iteration the value is set to {1: 'TESTa'}. Remember, the method overwrites the values it doesn't ... | [
0
] | [] | [] | [
"dictionary",
"kivy",
"loops",
"python",
"python_3.x"
] | stackoverflow_0074566425_dictionary_kivy_loops_python_python_3.x.txt |
Q:
How to make FOR run together with while?
I have the code below working until the WHILE, I needed to add the WHILE to capture all the information on the page.
However, when the code stops working, I need to know how I can make the code run after the While.
import time
from selenium import webdriver
from selenium.w... | How to make FOR run together with while? | I have the code below working until the WHILE, I needed to add the WHILE to capture all the information on the page.
However, when the code stops working, I need to know how I can make the code run after the While.
import time
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from se... | [
"for paginas_individuais in links: block not worked due to unintended indentation.\nThis block should be with the same indentation as while True: block to make it performed after the while True: block is completed.\n"
] | [
1
] | [] | [] | [
"indentation",
"python",
"selenium"
] | stackoverflow_0074566390_indentation_python_selenium.txt |
Q:
Image.open() cannot identify image file - Python?
I am running Python 2.7 in Visual Studio 2013. The code previously worked ok when in Spyder, but when I run:
import numpy as np
import scipy as sp
import math as mt
import matplotlib.pyplot as plt
import Image
import random
# (0, 1) is N
SCALE = 2.2666 # the scale... | Image.open() cannot identify image file - Python? | I am running Python 2.7 in Visual Studio 2013. The code previously worked ok when in Spyder, but when I run:
import numpy as np
import scipy as sp
import math as mt
import matplotlib.pyplot as plt
import Image
import random
# (0, 1) is N
SCALE = 2.2666 # the scale is chosen to be 1 m = 2.266666666 pixels
MIN_LENGTH = ... | [
"I had a same issue.\nfrom PIL import Image\n\ninstead of\nimport Image\n\nfixed the issue\n",
"So after struggling with this issue for quite some time, this is what could help you:\nfrom PIL import Image\n\ninstead of\nimport Image\n\nAlso, if your Image file is not loading and you're getting an error \"No file ... | [
69,
14,
12,
8,
4,
2,
2,
2,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0
] | [] | [] | [
"python",
"python_imaging_library"
] | stackoverflow_0019230991_python_python_imaging_library.txt |
Q:
force re.search to include # and $
I am trying to get a substring between two markers using re in Python, for example:
import re
test_str = "#$ -N model_simulation 2022"
# these two lines work
# the output is: model_simulation
print(re.search("-N(.*)2022",test_str).group(1))
print(re.search(" -N(.*)2022",test_str... | force re.search to include # and $ | I am trying to get a substring between two markers using re in Python, for example:
import re
test_str = "#$ -N model_simulation 2022"
# these two lines work
# the output is: model_simulation
print(re.search("-N(.*)2022",test_str).group(1))
print(re.search(" -N(.*)2022",test_str).group(1))
# these two lines give the ... | [
"You can escape both with \\, for example,\nprint(re.search(\"\\#\\$ -N(.*)2022\",test_str).group(1))\n# output model_simulation\n\n",
"You can get rid of the special meaning by using the backslash prefix: $. This way, you can match the dollar symbol in a given string\n# add backslash before # and $ \n# the outp... | [
1,
1,
1
] | [] | [] | [
"python",
"python_3.x",
"python_re"
] | stackoverflow_0074566491_python_python_3.x_python_re.txt |
Q:
ValueError: operands could not be broadcast together with shapes (2,1000) (2,)
I've created a function to define a test statistic, which I want to test in python. It resamples 1000 times from an existing sample (ex. matrix2, which is just a column) and takes the mode of these samples. Basically it bootstraps with ... | ValueError: operands could not be broadcast together with shapes (2,1000) (2,) | I've created a function to define a test statistic, which I want to test in python. It resamples 1000 times from an existing sample (ex. matrix2, which is just a column) and takes the mode of these samples. Basically it bootstraps with the mode to create a sampling distribution of modes for both matrix2 and matrix3. Th... | [
"The problem was that ks_2samp has a specific Kstest return type. If you want a numeric return type, you need to specify:\n(ks_2samp(np.array(sampleModes2), np.array(sampleModes3))).statistic\n\n"
] | [
0
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0074565459_numpy_python.txt |
Q:
Working with TIFFs (import, export) in Python using numpy
I need a python method to open and import TIFF images into numpy arrays so I can analyze and modify the pixel data and then save them as TIFFs again. (They are basically light intensity maps in greyscale, representing the respective values per pixel)
I coul... | Working with TIFFs (import, export) in Python using numpy | I need a python method to open and import TIFF images into numpy arrays so I can analyze and modify the pixel data and then save them as TIFFs again. (They are basically light intensity maps in greyscale, representing the respective values per pixel)
I couldn't find any documentation on PIL methods concerning TIFF. I t... | [
"First, I downloaded a test TIFF image from this page called a_image.tif. Then I opened with PIL like this:\n>>> from PIL import Image\n>>> im = Image.open('a_image.tif')\n>>> im.show()\n\nThis showed the rainbow image. To convert to a numpy array, it's as simple as:\n>>> import numpy\n>>> imarray = numpy.array(im)... | [
136,
65,
21,
17,
13,
9,
7,
2,
1,
0,
0
] | [
"no answers to this question did not work for me. so i found another way to view tif/tiff files:\nimport rasterio\nfrom matplotlib import pyplot as plt\nsrc = rasterio.open(\"ch4.tif\")\nplt.imshow(src.read(1), cmap='gray')\n\nthe code above will help you to view the tif files. also check below to be sure:\ntype(sr... | [
-1
] | [
"numpy",
"python",
"python_imaging_library",
"tiff"
] | stackoverflow_0007569553_numpy_python_python_imaging_library_tiff.txt |
Q:
Understanding Principal Components Analyse (PCA) for Dimension Downscaling in EEG signals
I have read dozens of scientific articles and wherever a large number of channels are used to read EEG signals, the Principal Components Analyze method is used to reduce the Dimension.
I have read the theory about Principal C... | Understanding Principal Components Analyse (PCA) for Dimension Downscaling in EEG signals | I have read dozens of scientific articles and wherever a large number of channels are used to read EEG signals, the Principal Components Analyze method is used to reduce the Dimension.
I have read the theory about Principal Components Analyze many times and think that understanding how it works, each component is a new... | [
"Note that I am no expert as it comes to using PCA for EEG signals analysis.\nPCA does decrease dimensions IF you choose to. Usually only first few components are important and you can discard all the others. How many - it depends on your needs.\nPCA creates new, independent dimensions, with first being most import... | [
0
] | [] | [] | [
"pca",
"python",
"signal_processing"
] | stackoverflow_0074566258_pca_python_signal_processing.txt |
Q:
How to insert multiple values at a time in Auto incremented column using SQLAlchemy
I am using Postgres database and sqlalchemy core. I have below table
CREATE TABLE IF NOT EXISTS id_generation (id SERIAL PRIMARY KEY)
and I am trying to insert multiple values in the id column using below query. number_of_ids can ... | How to insert multiple values at a time in Auto incremented column using SQLAlchemy | I am using Postgres database and sqlalchemy core. I have below table
CREATE TABLE IF NOT EXISTS id_generation (id SERIAL PRIMARY KEY)
and I am trying to insert multiple values in the id column using below query. number_of_ids can be in multiple of 1000.
for _ in range(number_of_ids):
conn.execute('INSERT INTO id_g... | [
"Assuming that you are using psycopg2 as the connector, you can pass a list of empty dictionaries to conn.execute, corresponding to the number of rows to be inserted, and SQLAlchemy will emit a single INSERT statement with multiple VALUES clauses.\nimport sqlalchemy as sa\n\n...\n\nvals = [{} for _ in range(100)]\n... | [
0
] | [] | [] | [
"postgresql",
"python",
"sqlalchemy"
] | stackoverflow_0074566383_postgresql_python_sqlalchemy.txt |
Q:
Groupby with brackets vs. Groupby with ".agg"?
what is the exact difference between
data_sex1= data_suicide.groupby(by=["year", "sex"])["suicides_no"].sum()
and
data_sex2 = data_suicide.groupby(by=['year', 'sex']).agg({'suicides_no': ['sum']})
?
My problem is that I have to modify both to plot them in seaborn.
T... | Groupby with brackets vs. Groupby with ".agg"? | what is the exact difference between
data_sex1= data_suicide.groupby(by=["year", "sex"])["suicides_no"].sum()
and
data_sex2 = data_suicide.groupby(by=['year', 'sex']).agg({'suicides_no': ['sum']})
?
My problem is that I have to modify both to plot them in seaborn.
The line for seaborn is this
sns.barplot(x="year", y=... | [
"You would like to use agg when you want to apply different aggregation functions for different columns:\ndf.groupby('id').agg({'x': ['mean', 'sum', 'max'], 'y': ['sum', 'min']})\n\nThe other option gives you less flexibility in terms of columns / aggregation logics to apply.\n"
] | [
1
] | [] | [] | [
"group_by",
"pandas",
"python"
] | stackoverflow_0074566528_group_by_pandas_python.txt |
Q:
How to return forms to app in method POST
I would like to send data using the form to the application. Unfortunately something is wrong. I'm still wondering if it's
name = request.form
is good because it doesn't even show me
print(name).
@app.route('/register', methods=['GET', 'POST'])
def register():
form = R... | How to return forms to app in method POST | I would like to send data using the form to the application. Unfortunately something is wrong. I'm still wondering if it's
name = request.form
is good because it doesn't even show me
print(name).
@app.route('/register', methods=['GET', 'POST'])
def register():
form = RegisterForm(request.form)
if request.method... | [
"You have made a mistake with the syntax. the form is not callable so you cannot call it using form().\nTry the following:\nname = request.form[\"name\"]\n\nor\nname = request.form.get(\"name\", fallBackValue)\n\nI hope this helps\n"
] | [
1
] | [] | [] | [
"flask",
"http",
"post",
"python"
] | stackoverflow_0074566123_flask_http_post_python.txt |
Q:
For loop not working stating the endpoint is a float
So for context, I'm working on a program that requires the Guass formula. It's used to find for example, 5 + 4 + 3 + 2 + 1, or, 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1.
The formula is (n*(n + 1))/2,
I tried to incorporate this into a for loop, but I'm getting an error sta... | For loop not working stating the endpoint is a float | So for context, I'm working on a program that requires the Guass formula. It's used to find for example, 5 + 4 + 3 + 2 + 1, or, 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1.
The formula is (n*(n + 1))/2,
I tried to incorporate this into a for loop, but I'm getting an error stating:
"'float' object cannot be interpreted as an integer"... | [
"As @ForceBru noted in his excellent comment, the problem is that the endpoint final_stop is a float, instead of an int.\nThe reason is because when computing it you used a single / instead of double.\nIf you replace\nfinal_stop = stop/2\nwith\nfinal_stop = stop//2,\nthen it should work fine.\n"
] | [
1
] | [] | [] | [
"loops",
"python"
] | stackoverflow_0074566620_loops_python.txt |
Q:
Array length does not match index when creating a Dataframe
I am constructing a dataframe from:
datetoday = (pd.to_datetime(files[-1]['file_published'], format='%d.%m.%Y %H:%M')).strftime('%Y-%m-%d')
datetoday
Out[66]: '2022-11-23'
dates = pd.Series(np.arange(1, 337, 1))
dates
Out[68]:
0 1
1 ... | Array length does not match index when creating a Dataframe | I am constructing a dataframe from:
datetoday = (pd.to_datetime(files[-1]['file_published'], format='%d.%m.%Y %H:%M')).strftime('%Y-%m-%d')
datetoday
Out[66]: '2022-11-23'
dates = pd.Series(np.arange(1, 337, 1))
dates
Out[68]:
0 1
1 2
2 3
3 4
4 5
...
... | [
"Conjecture\nThe older version of pandas you are using on Jupyter is fussing about the way you are specifying the datecreated column using a scalar value (note for the other two columns, you specified using lists/arrays).\nSolution\nThe following fix will work on any version of pandas (given that the dates and data... | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074566398_pandas_python.txt |
Q:
Appending data to empty pandas dataframe
To start, I am very new to Python and stackoverflow. I am sorry if this question has come up before, but I could not find it in the forum. Could someone please explain why this output happens when I try to append data to a Dataframe.
A B C D E F G 0 1 2 ... | Appending data to empty pandas dataframe | To start, I am very new to Python and stackoverflow. I am sorry if this question has come up before, but I could not find it in the forum. Could someone please explain why this output happens when I try to append data to a Dataframe.
A B C D E F G 0 1 2 3 4 5 6
0 NaN NaN NaN NaN NaN NaN NaN... | [
"Try this?\nimport pandas as pd\ndftest = pd.DataFrame(columns=[\"A\",\"B\",\"C\",\"D\",\"E\",\"F\",\"G\"])\ntestdata = [1,2,3,4,5,6,7]\n\n\ndftest.loc[len(dftest)] = testdata\ndftest\n\n"
] | [
0
] | [] | [] | [
"append",
"pandas",
"python"
] | stackoverflow_0074566714_append_pandas_python.txt |
Q:
WTForms Field shows up when run, but has Unbound problems
I'm new to Flask and JS, so I'm really not sure what the problem is here.
app.py
@app.route('/email', methods=["GET", "POST"])
def email():
email_form = EmailForm(csrf_enabled=False)
return render_template("email-form.html", template_form=email_fo... | WTForms Field shows up when run, but has Unbound problems | I'm new to Flask and JS, so I'm really not sure what the problem is here.
app.py
@app.route('/email', methods=["GET", "POST"])
def email():
email_form = EmailForm(csrf_enabled=False)
return render_template("email-form.html", template_form=email_form, action='/appliance2', method='POST')
forms.py (I created t... | [
"In the validators list you need to pass in an instance of class Email. So you field should read:\nfrom wtforms.validators import Email\n\nemail_input = StringField(\"email\", validators=[Email(), ...\n\nand don't forget to install the email package as Flask-WTF doesn't include anymore the Email in their validators... | [
0
] | [] | [] | [
"flask",
"flask_wtforms",
"python",
"windows",
"wtforms"
] | stackoverflow_0074565824_flask_flask_wtforms_python_windows_wtforms.txt |
Q:
how to distinguish axes between image, line plot and colorbar?
N.B.: I have edited the question as it was probably unclear: I am looking for the best method to understand the type of plot in a given axis.
QUESTION:
I am trying to make a generic function which can arrange multiple figures as subplots.
As I loop ove... | how to distinguish axes between image, line plot and colorbar? | N.B.: I have edited the question as it was probably unclear: I am looking for the best method to understand the type of plot in a given axis.
QUESTION:
I am trying to make a generic function which can arrange multiple figures as subplots.
As I loop over the subplots to set some properties (e.g. axis range) iterating ov... | [
"I have to remind you that\n\nMatplotib provides you with many different container objects,\nYou can store the Axes destination in a list, or a dictionary, when you use it — you can even say ax.ax_type = 'lineplot'.\n\nThat said, e.g.,\nfrom matplotlib.pyplot import subplots, plot\nfig, ax = subplots()\nplot((1, 2)... | [
0,
0,
0
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0074551664_matplotlib_python.txt |
Q:
DataFrame with multi-index - which team has a larger number?
After using .groupby(['match_id', 'team']).sum() I'm left with this multi-index dataframe:
visionScore
match_id team
EUW1_5671848066 blue 212
red 127
EUW1_5671858853 blue ... | DataFrame with multi-index - which team has a larger number? | After using .groupby(['match_id', 'team']).sum() I'm left with this multi-index dataframe:
visionScore
match_id team
EUW1_5671848066 blue 212
red 127
EUW1_5671858853 blue 146
red 170
EUW1_5672206092 blue ... | [
"This would work:\nimport pandas as pd\n\ndf = pd.DataFrame(\n {\"visionScore\": [212, 127, 146, 170, 82, 82]},\n index=pd.MultiIndex.from_product([[\"EUW1_5671848066\", \"EUW1_5671858853\", \"EUW1_5672206092\"], [\"blue\", \"red\"]], names=[\"match_id\", \"team\"]) \n)\n\ndf[\"winner\"] = df.groupby(\"mat... | [
2,
0
] | [] | [] | [
"multi_index",
"pandas",
"python"
] | stackoverflow_0074566302_multi_index_pandas_python.txt |
Q:
Python - Class from Serial
how do I create a class that Inheritates from serial using the python serial module?
I need to create a module so another user can import to his code and create an object by just passing the COM.
This is my module, called py232
from serial import Serial
class serialPort(Serial):
def __... | Python - Class from Serial | how do I create a class that Inheritates from serial using the python serial module?
I need to create a module so another user can import to his code and create an object by just passing the COM.
This is my module, called py232
from serial import Serial
class serialPort(Serial):
def __init__(self, COM):
serial.__... | [
"Why don't you just create an instance of serial in a function. No need to create a sub-class.\nfrom serial import Serial\n\ndef create_serial(port):\n s = Serial(\n port,\n baudrate=9600,\n bytesize=8,\n timeout=2,\n # etc\n )\n return s\n\nIt can then be used in another... | [
1
] | [] | [] | [
"python",
"serial_port"
] | stackoverflow_0074566626_python_serial_port.txt |
Q:
Is there any way to store instance variable name inside of instance string?
I'm making a Matrix class and when I pretty-print the matrix, I would like there to be the matrix name. So for example
Bob = Matrix("2&3&4@4&5&6@6&7&8")
print(Bob)
Output:
---Matrix Bob---
| 2 3 4 |
| 4 5 6 |
| 6 7 8 |
----------... | Is there any way to store instance variable name inside of instance string? | I'm making a Matrix class and when I pretty-print the matrix, I would like there to be the matrix name. So for example
Bob = Matrix("2&3&4@4&5&6@6&7&8")
print(Bob)
Output:
---Matrix Bob---
| 2 3 4 |
| 4 5 6 |
| 6 7 8 |
----------------
Is there any way to do this, without passing the name as a parameter?
I h... | [] | [] | [
"Objects aren't able to see the the variable they're assigned to\n"
] | [
-1
] | [
"class",
"python"
] | stackoverflow_0074566757_class_python.txt |
Q:
Problem with two concurrent workers accessing mysql with tornado
I have this simple program composed by two workers: Worker1 inserts records that Workers2 should read. The problem is that during execution Workers2 reads 0 records. Launched separately from CLI they work correctly. The "culprit" seems to be tornado.... | Problem with two concurrent workers accessing mysql with tornado | I have this simple program composed by two workers: Worker1 inserts records that Workers2 should read. The problem is that during execution Workers2 reads 0 records. Launched separately from CLI they work correctly. The "culprit" seems to be tornado. Any idea?
import time
import munch
from tornado import concurrent
fro... | [
"Solved by adding self.conn.commit() after self.cursor.execute(query) in Worker2.\n"
] | [
1
] | [] | [] | [
"mysql",
"python",
"python_multiprocessing",
"threadpoolexecutor",
"tornado"
] | stackoverflow_0074548959_mysql_python_python_multiprocessing_threadpoolexecutor_tornado.txt |
Q:
Finding all the prime numbers in a list in Python
I want to loop through a list and find all the numbers that are prime
arr = [1,2,3]
for i in range(len(arr)):
if arr[i] > 1:
for j in range(2, int(arr[i]/2)+1):
if (arr[i] % j) == 0:
print(arr[i], "is not prime")
el... | Finding all the prime numbers in a list in Python | I want to loop through a list and find all the numbers that are prime
arr = [1,2,3]
for i in range(len(arr)):
if arr[i] > 1:
for j in range(2, int(arr[i]/2)+1):
if (arr[i] % j) == 0:
print(arr[i], "is not prime")
else:
print(arr[i], "is prime")
else:
... | [
"The problem with your code is as follows\nint(arr[i]/2)+1) is smaller than 2, thenceforth range(2, int(arr[i]/2)+1)) has no elements. The for loop doesn't execute for 2 and 3. These two cases need to be treated apart.\nThe second problem is that for greater numbers, you're deciding for every iteration in the inner... | [
0
] | [
"arr = list(range(20))\n\ndef is_prime(n):\n if n < 2:\n return False\n for i in range(2, int(n**0.5)+1):\n if n % i == 0:\n return False\n return True\n\ndef find_primes(array):\n return list(filter(is_prime, array))\n\nprint(find_primes(arr))\n\nreturns: [2, 3, 5, 7, 11, 13, 1... | [
-1
] | [
"iteration",
"list",
"primes",
"python",
"range"
] | stackoverflow_0074566677_iteration_list_primes_python_range.txt |
Q:
how to delete rows that contain a word from a list in python
As stated in the title I have a pandas data frame with string sentences in the column "title". I know want to filter all rows, where the title column contains one of the words specified in the list "keywords".
keywords = ["Simon", "Mustermann"]
df =
Tit... | how to delete rows that contain a word from a list in python | As stated in the title I have a pandas data frame with string sentences in the column "title". I know want to filter all rows, where the title column contains one of the words specified in the list "keywords".
keywords = ["Simon", "Mustermann"]
df =
Title
Bla
Simon is a python beginner
...
Second balaola
...
... | [
"This snippet should work for you\nkeywords = [\"Simon\", \"Mustermann\"]\n\n# filter rows where column title contains one of the keywords\ndf_filtered = df[df[\"title\"].str.contains(\"|\".join(keywords))]\n\n"
] | [
1
] | [] | [] | [
"dataframe",
"list",
"list_comprehension",
"pandas",
"python"
] | stackoverflow_0074566836_dataframe_list_list_comprehension_pandas_python.txt |
Q:
Time interval calculation for consecutive days in rows
I have a dataframe that looks like this:
Path_Version commitdates Year-Month API Age api_spec_id
168 NaN 2018-10-19 2018-10 39 521
169 NaN 2018-10-19 2018-10 39 521
... | Time interval calculation for consecutive days in rows | I have a dataframe that looks like this:
Path_Version commitdates Year-Month API Age api_spec_id
168 NaN 2018-10-19 2018-10 39 521
169 NaN 2018-10-19 2018-10 39 521
170 NaN 2018-10-12 2018-10 39 ... | [
"Use pandas.to_datetime, sub, min and dt.days:\nt = pd.to_datetime(df['commitdates'])\n\ndf['Days_difference'] = t.sub(t.min()).dt.days\n\nIf you need to group per API:\nt = pd.to_datetime(df['commitdates'])\n\ndf['Days_difference'] = t.sub(t.groupby(df['api_spec_id']).transform('min')).dt.days\n\n\nOutput:\n P... | [
2
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074566819_pandas_python.txt |
Q:
No module names 'src' when importing from parent folder in jupyter notebook
I have the following folder structure in my project
my_project
notebook
|-- some_notebook.ipynb
src
|-- preprocess
|-- __init__.py
|-- some_processing.py
__init__.py
Now, inside some_notebook.ipynb I simply... | No module names 'src' when importing from parent folder in jupyter notebook | I have the following folder structure in my project
my_project
notebook
|-- some_notebook.ipynb
src
|-- preprocess
|-- __init__.py
|-- some_processing.py
__init__.py
Now, inside some_notebook.ipynb I simply want to get the methods from some_processing.py. Now we I run
from src.preproces... | [
"I found the answer. Running\nsys.path.insert(1, os.path.join(sys.path[0], '../src'))\n\nmade it possible to import anything from parent module src.\n"
] | [
0
] | [] | [] | [
"import",
"jupyter_notebook",
"python"
] | stackoverflow_0074566749_import_jupyter_notebook_python.txt |
Q:
Unpacking arrays into arrow plot
I have a strange looking function that calls the plots based on the attributes. So, if a function exists in the class then select that. Then I am trying to call it, in this example I use pyplot.arrow, however, I cannot seem to unpack all the values. It should take four parameters, ... | Unpacking arrays into arrow plot | I have a strange looking function that calls the plots based on the attributes. So, if a function exists in the class then select that. Then I am trying to call it, in this example I use pyplot.arrow, however, I cannot seem to unpack all the values. It should take four parameters, but I get the following error:
ValueE... | [
"I feel like you are doing several unnecessary things which has made it confusing.\nThe main point is you want to do ax.__getattribute__(\"arrow\")(x, y, dx, dy, **kwargs). To keep it simple:\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ntest_array = np.array([\n [1, 2],\n [5, 4],\n [5, 2],\n ... | [
0,
0
] | [] | [] | [
"matplotlib",
"numpy",
"python"
] | stackoverflow_0074508827_matplotlib_numpy_python.txt |
Q:
How to have input in Python only take in string and not number or anything else only letters
I am a beginner in Python so kindly do not use complex or advanced code.
contact = {}
def display_contact():
for name, number in sorted((k,v) for k, v in contact.items()):
print(f'Name: {name}, Number: {number... | How to have input in Python only take in string and not number or anything else only letters | I am a beginner in Python so kindly do not use complex or advanced code.
contact = {}
def display_contact():
for name, number in sorted((k,v) for k, v in contact.items()):
print(f'Name: {name}, Number: {number}')
#def display_contact():
# print("Name\t\tContact Number")
# for key in contact:
# print(... | [
"You can use a regex with re.fullmatch:\nimport re\n\nwhile True:\n name = input(\"Enter the contact name \")\n if re.fullmatch(r'[a-zA-Z]+', name):\n break\n\nOr use the case-insensitive flag: re.fullmatch(r'[a-z]+', name, flags=re.I):\n",
"As you noted that you are a beginner, I'm adding this piece... | [
4,
1
] | [
"I found this answer from another website:\nextracted_letters = \" \".join(re.findall(\"[a-zA-Z]+\", numlettersstring))\n\nFirst, import re to use the re function.\nThen let's say that numlettersstring is the string you want only the letters from.\nThis piece of code will extract the letters from numlettersstring a... | [
-1
] | [
"data_structures",
"list",
"python",
"python_3.x"
] | stackoverflow_0074566687_data_structures_list_python_python_3.x.txt |
Q:
Function that generates airflow dags dinamically not creating them
I have a function that will generate dags dinamically, from a database with the dag configs (I know, it's expensive to do that). The thing is, it only generates dags when I call this function in the same file that I define it, if I import in anothe... | Function that generates airflow dags dinamically not creating them | I have a function that will generate dags dinamically, from a database with the dag configs (I know, it's expensive to do that). The thing is, it only generates dags when I call this function in the same file that I define it, if I import in another file and execute it, it wont generate my dags.
Eg:
def generate_dags_d... | [
"Airflow will only 'see' the dag objects that are in the global namespace.\nIn order to correct your code your generate_dags_dinamically() function should return a list of dag objects and then you should add them to the global scope like so:\nfrom dags.dynamic_dags import generate_dags_dinamically\n\n\ndags_list = ... | [
1
] | [] | [] | [
"airflow",
"python",
"python_3.x"
] | stackoverflow_0074494397_airflow_python_python_3.x.txt |
Q:
How to install libraries in python without pip to make sure the integrity of their code?
I am working in a company that do not permit installing libraries without cybersecurity department permission. So I had to download the libraries for example from pypi.org, send them for authorization and install them by calli... | How to install libraries in python without pip to make sure the integrity of their code? | I am working in a company that do not permit installing libraries without cybersecurity department permission. So I had to download the libraries for example from pypi.org, send them for authorization and install them by calling setup. However, I wonder if there are better solutions/practices to guaranty the sanity of ... | [
"You can package your project with the wheel (.whl) files it needs on the platform it will be running on. That way, your IT dept. can sign off on those specific binaries and allow their installation, and you can be guaranteed they will work the same every time the software is installed.\nHowever, it does mean that ... | [
1,
0
] | [] | [] | [
"integrity",
"pip",
"python",
"security"
] | stackoverflow_0074566930_integrity_pip_python_security.txt |
Q:
how to download this zip file using python requests?
I am trying to download a zip file that is stored here:
http://e4ftl01.cr.usgs.gov/MEASURES/SRTMGL1.003/2000.02.11/N45W074.SRTMGL1.hgt.zip
If you paste this into the browser and hit enter, it will download the .zip folder.
If you inspect the browser while this ... | how to download this zip file using python requests? | I am trying to download a zip file that is stored here:
http://e4ftl01.cr.usgs.gov/MEASURES/SRTMGL1.003/2000.02.11/N45W074.SRTMGL1.hgt.zip
If you paste this into the browser and hit enter, it will download the .zip folder.
If you inspect the browser while this is happening, you will see that there is an internal redir... | [
"Change http to Https: This should work\nimport requests\n\n# download zip file from url\nurl = \"https://e4ftl01.cr.usgs.gov/MEASURES/SRTMGL1.003/2000.02.11/N45W074.SRTMGL1.hgt.zip\"\nr = requests.get(url)\nwith open(\"N45W074.SRTMGL1.hgt.zip\", \"wb\") as f:\n f.write(r.content)\n\n",
"Thanks to @cnemri for ... | [
1,
0
] | [] | [] | [
"python",
"python_requests"
] | stackoverflow_0074566535_python_python_requests.txt |
Q:
beautifulsoup get last tag from snippet, if tag exists
Here's html snippet 1:
<td class="firstleft lineupopt-name" style=""><a href="/link/link_url?id=222" title="Donald Trump" target="_blank">Trump, Donald</a> <span style="color:#666;font-size:10px;">B</span> <span style="color:#cc1100;font-size:10px;f... | beautifulsoup get last tag from snippet, if tag exists | Here's html snippet 1:
<td class="firstleft lineupopt-name" style=""><a href="/link/link_url?id=222" title="Donald Trump" target="_blank">Trump, Donald</a> <span style="color:#666;font-size:10px;">B</span> <span style="color:#cc1100;font-size:10px;font-weight:bold;">TTT</span></td>
Here's html snippet 2:
<t... | [
"BS4 now supports last-child so a possible approach could be:\nsoup.select('td span:last-child')\n\nTo get the texts out just iterat the resultset.\nExample\nfrom bs4 import BeautifulSoup\n\nhtml='''\n<td class=\"firstleft lineupopt-name\" style=\"\"><a href=\"/link/link_url?id=222\" title=\"Donald Trump\" target=\... | [
1,
0,
0,
0
] | [] | [] | [
"beautifulsoup",
"html",
"html_parsing",
"parsing",
"python"
] | stackoverflow_0031729940_beautifulsoup_html_html_parsing_parsing_python.txt |
Q:
Double iteration in for comprehension without 2d list
I would like to perform a double 'for' loop within a for-comprehension. However, I do not want to do it under the typical conditions, such as:
sentences = ['hello what are you doing?', 'trying to figure this out!']
[c for word in sentences for c in word]
Inste... | Double iteration in for comprehension without 2d list | I would like to perform a double 'for' loop within a for-comprehension. However, I do not want to do it under the typical conditions, such as:
sentences = ['hello what are you doing?', 'trying to figure this out!']
[c for word in sentences for c in word]
Instead, I would like to perform this double iteration with cond... | [
"Just figured it out, nevermind. Simply use any():\nnew = [word for word in words if any(substr in word for substr in substrings)]\n\n"
] | [
1
] | [] | [] | [
"for_comprehension",
"python"
] | stackoverflow_0074567050_for_comprehension_python.txt |
Q:
File not Found in Directory Python
Ok, I tried everythin and I´m starting to get frustrated :/
I want to open the .mp3 file and change it to a .wav.
The thing is I dont even come so far, because the code doenst find the .mp3.
At first I worked with the complete pat of the directory, but after several failed attemp... | File not Found in Directory Python | Ok, I tried everythin and I´m starting to get frustrated :/
I want to open the .mp3 file and change it to a .wav.
The thing is I dont even come so far, because the code doenst find the .mp3.
At first I worked with the complete pat of the directory, but after several failed attempts I started to use the os lib.
import o... | [
"As you've mentioned in your question, you need to add r before your path and use \\ for folders.\nHowever, you need to load and play the file within a loop:\nwith open(Src, 'rb') as f: \n sound = AudioSegment.from_file(f, format=\"mp3\")\n\n"
] | [
0
] | [] | [] | [
"operating_system",
"python"
] | stackoverflow_0074567049_operating_system_python.txt |
Q:
How to check if files are still created?
I would like to make a script to check whether or not files are still being created inside a folder. We can consider for our problem that there are no more files being created if let's say for 5 sec the list of files present in that folder remains unchanged. Can anyone help... | How to check if files are still created? | I would like to make a script to check whether or not files are still being created inside a folder. We can consider for our problem that there are no more files being created if let's say for 5 sec the list of files present in that folder remains unchanged. Can anyone help me with this issue?
| [
"You can use inotifywait to watch for events on a file or a directory.\ninotifywait -m -e create /path/to/your/dir\n\nIt will show you the events and exits if no more event happens after 5 seconds.\ninotifywait --timeout 5 -qm -e create /path/to/your/dir\n\nBy default it will use 5 seconds but you can change it by ... | [
1,
0
] | [] | [] | [
"file",
"python"
] | stackoverflow_0074566733_file_python.txt |
Q:
Removing Duplicates out of List of Np-Arrays
I am working on a project for which I am analyzing and comparing several different binary matrices which represent combinatorial objects. For this, I need to generate and analyze datasets and I have turned to python to do so.
Basically, I have list of np.arrays and I am... | Removing Duplicates out of List of Np-Arrays | I am working on a project for which I am analyzing and comparing several different binary matrices which represent combinatorial objects. For this, I need to generate and analyze datasets and I have turned to python to do so.
Basically, I have list of np.arrays and I am need to filter out duplicates, i.e. take out all ... | [
"Works with numpy arrays:\nGiven\na = np.array([[1, 2, 3],\n [1, 2, 3],\n [1, 2, 3],\n [4, 5, 6].\n [4, 5, 6]])\n\nYou can do:\nb = np.unique(a, axis=0)\n\nThis gives you a numpy array which is the same shape as a, but with all the duplicates removed. So in this e... | [
0
] | [] | [] | [
"list",
"numpy",
"python"
] | stackoverflow_0074567042_list_numpy_python.txt |
Q:
Vscode error "zsh: command not found: python" (on macOs Monterrey 12.3.1)
I have no idea on how to solve this, I've tried to
echo "alias python=/usr/bin/python3" >> ~/.zshrc
And also
brew install python
I'm new on this so I really don't know what I'm doing, if someone could explain why I'm supposed to write thos... | Vscode error "zsh: command not found: python" (on macOs Monterrey 12.3.1) | I have no idea on how to solve this, I've tried to
echo "alias python=/usr/bin/python3" >> ~/.zshrc
And also
brew install python
I'm new on this so I really don't know what I'm doing, if someone could explain why I'm supposed to write those lines on my terminal I'd be very grateful
| [
"after updating to macos Monterey 12.6.1 had similar problem.\nBefore this update, python referred to python2.7 which was removed completely in the latest Monterey versions.\nUsing following fix:\nsudo ln -s /Applications/Xcode.app/Contents/Developer/usr/bin/python3 /Applications/Xcode.app/Contents/Developer/usr/b... | [
1,
0
] | [] | [] | [
"python",
"terminal",
"visual_studio_code"
] | stackoverflow_0072045819_python_terminal_visual_studio_code.txt |
Q:
Physically Based Rendering shows discontinuity on closed surface
I added a mesh to a pyvista.Plotter() with
p.add_mesh(mesh, show_edges=True, color='linen', pbr=True, metallic=0.8, roughness=0.1, diffuse=1)
but it displays with a discontinuity (where the mesh started and ended)
Why is this junction of cells diff... | Physically Based Rendering shows discontinuity on closed surface | I added a mesh to a pyvista.Plotter() with
p.add_mesh(mesh, show_edges=True, color='linen', pbr=True, metallic=0.8, roughness=0.1, diffuse=1)
but it displays with a discontinuity (where the mesh started and ended)
Why is this junction of cells different from similar ones around this toroid?
| [
"It's probably due to how surface normals are computed, and that your mesh connectivity is off along that edge.\nThe way you often generate such closed surfaces is to parametrise with respect to some generalised coordinates, one of which in this case is the azimuthal angle. Where your azimuthal angle sweep starts (... | [
1,
0
] | [] | [] | [
"mesh",
"pbr",
"python",
"pyvista"
] | stackoverflow_0074555881_mesh_pbr_python_pyvista.txt |
Q:
I'm trying to install some dependencies, but I ran into an error
I typed in "sudo apt-get install -y wiringpi python-pigpio python3-pigpio" but got the error "Temporary failure resolving 'archive.raspberrypi.org' "
Here is a picture of the error
I set up a fixed address in sudo nano /etc/dhcpcd.conf. I tried looki... | I'm trying to install some dependencies, but I ran into an error | I typed in "sudo apt-get install -y wiringpi python-pigpio python3-pigpio" but got the error "Temporary failure resolving 'archive.raspberrypi.org' "
Here is a picture of the error
I set up a fixed address in sudo nano /etc/dhcpcd.conf. I tried looking for solutions online and have tried some of them such as changing t... | [
"I would suggest adding\nnameserver 1.1.1.1\nnameserver 1.0.0.1\n\nto /etc/resolv.conf.\nNote these are 2 DNS resolvers, which will only be used if your normal DNS (from your ISP) is not responding. They are provided by Cloudflare and are excellent.\nThen try your command again.\n"
] | [
0
] | [] | [] | [
"linux",
"python",
"raspberry_pi",
"terminal",
"ubuntu"
] | stackoverflow_0074566699_linux_python_raspberry_pi_terminal_ubuntu.txt |
Q:
Deploying a new model to a sagemaker endpoint without updating the config?
I want to deploy a new model to an existing AWS SageMaker endpoint. The model is trained by a different pipeline and stored as a mode.tar.gz in S3. The sagemaker endpoint config is pointing to this as the model data URL. Sagemaker however d... | Deploying a new model to a sagemaker endpoint without updating the config? | I want to deploy a new model to an existing AWS SageMaker endpoint. The model is trained by a different pipeline and stored as a mode.tar.gz in S3. The sagemaker endpoint config is pointing to this as the model data URL. Sagemaker however doesn't reload the model and I don't know how to convince it to do so.
I want to ... | [
"If you want to modify the model called in a SageMaker endpoint, you have to create a new model object and and new endpoint configuration. Then call update_endpoint This will not change the name of the endpoint.\ncomments on your question and SageMaker doc:\n\nthe documentation you mention (\"This documentation sug... | [
0
] | [] | [] | [
"amazon_sagemaker",
"amazon_web_services",
"boto3",
"mlops",
"python"
] | stackoverflow_0074561905_amazon_sagemaker_amazon_web_services_boto3_mlops_python.txt |
Q:
Why does my program gets stuck on the function move_down()?
I am making a moving "X in a grid" - learning the keyboard module.
For some reason, when debugging in vscode, my program won't leave the line:
while j < len(board[0]):
if board[i][j] == "X":
Are you seeing what's going on, on the left?
"Thead... | Why does my program gets stuck on the function move_down()? | I am making a moving "X in a grid" - learning the keyboard module.
For some reason, when debugging in vscode, my program won't leave the line:
while j < len(board[0]):
if board[i][j] == "X":
Are you seeing what's going on, on the left?
"Thead-8 (process) : PAUSED ON BREAKPOINT"
(next move / step-info pres... | [
"You are not changing the while condition:\nwhile j < len(board[0]):\n if board[i][j] == \"X\":\n # (...)\n\nThis is your whole loop.\nj never changes and len(board[0]) never changes, and because if statement is false. It just loops indefinitely.\nIn move_up() function, you are changing j with this line j... | [
0
] | [] | [] | [
"python",
"visual_studio_code"
] | stackoverflow_0074567063_python_visual_studio_code.txt |
Q:
NetworkX find root_node for a particular node in a directed graph
Suppose I have a directed graph G in Network X such that:
G has multiple trees in it
Every node N in G has exactly 1 or 0
parent's.
For a particular node N1, I want to find the root node of the tree it resides in (its ancestor that has a degree o... | NetworkX find root_node for a particular node in a directed graph | Suppose I have a directed graph G in Network X such that:
G has multiple trees in it
Every node N in G has exactly 1 or 0
parent's.
For a particular node N1, I want to find the root node of the tree it resides in (its ancestor that has a degree of 0). Is there an easy way to do this in network x?
I looked at:
Gettin... | [
"edit Nov 2017 note that this was written before networkx 2.0 was released. There is a migration guide for updating 1.x code into 2.0 code (and in particular making it compatible for both)\n\nHere's a simple recursive algorithm. It assumes there is at most a single parent. If something doesn't have a parent, it'... | [
5,
3,
0,
0
] | [] | [] | [
"graph_theory",
"networkx",
"python"
] | stackoverflow_0036488758_graph_theory_networkx_python.txt |
Q:
Python type annotations with TypeVar that excludes types
I'm trying to use @overload to communicate the different ways of calling a function, but what is easily communicated in the code with a simple else statement is not possible in the type annotations. Without the "else" MyPy (correctly) complains that the ove... | Python type annotations with TypeVar that excludes types | I'm trying to use @overload to communicate the different ways of calling a function, but what is easily communicated in the code with a simple else statement is not possible in the type annotations. Without the "else" MyPy (correctly) complains that the overload versions mismatch (see the snippet below for example).
e... | [
"This is the work-around that I have. It works well enough for me but I don't like it at all.\n# attempt to list all the \"other\" possible types\nAnythingElse = TypeVar(\"AnythingElse\", Set, Mapping, type, int, str, None, Callable, Set, Deque, ByteString)\nListOrTuple = TypeVar(\"ListOrTuple\", List, Tuple, Seque... | [
0,
0,
0
] | [] | [] | [
"mypy",
"python",
"python_typing"
] | stackoverflow_0060222982_mypy_python_python_typing.txt |
Q:
Returning a line of txt.-file that has a word with more than 6 characters and starts with "A" in Python
I have a task to accomplish in Python with only one sentence:
I need to return lines of my txt-file that include words which have more than 6 characters and start with the letter "A".
My code is the following:
[... | Returning a line of txt.-file that has a word with more than 6 characters and starts with "A" in Python | I have a task to accomplish in Python with only one sentence:
I need to return lines of my txt-file that include words which have more than 6 characters and start with the letter "A".
My code is the following:
[line for line in open('test.txt') if line.split().count('A') > 6]
I am not sure how to implement another com... | [
"I would split up your for loop so that it's not a list comprehension, to make it easier to understand what's going on. Once you do that, it should be clearer what you're missing so you can assemble it back into a list comprehension.\nlines = []\n\nwith open('test.txt', 'r') as f:\n for line in f: # this line ... | [
1,
1
] | [] | [] | [
"python",
"txt"
] | stackoverflow_0074567208_python_txt.txt |
Q:
Getting nested named results from pyparsing
I am modifying the pyparsing fourFn example to accept variables. Evaluation already works, now I want to be able to parse a string and output a list of required variables. Here's how I would like it to work:
from my_module.parser import FormulaParser
formula = '(x + y) ... | Getting nested named results from pyparsing | I am modifying the pyparsing fourFn example to accept variables. Evaluation already works, now I want to be able to parse a string and output a list of required variables. Here's how I would like it to work:
from my_module.parser import FormulaParser
formula = '(x + y) * z'
fp = FormulaParser()
parser.get_variables
# ... | [
"There may be a better way but scan_string sort of works:\n>>> from pyparsing import alphas, alphanums\n>>> identifier = Word(alphas, alphanums + \"_$\")\n>>> formula = '(a * sin(x + y)) / (galaxy - 3)'\n>>> myvars = [var[0][0] for var in identifier.scan_string(formula)]\n>>> myvars\n['a', 'sin', 'x', 'y', 'galaxy'... | [
0
] | [] | [] | [
"parsing",
"pyparsing",
"python"
] | stackoverflow_0074567195_parsing_pyparsing_python.txt |
Q:
How to make a dictionary from lists
I want to add this two list into a dictionary
list_id= ['2000391314791P', '2000391314715P', '2000383032443P', '2000387592776P', '2000391314760P', '2000387592813P', '2000383032511P', '2000391314784P', '2000387592738P', '2000387592806P', '2000387592769P', '2000387592790P', '200038... | How to make a dictionary from lists | I want to add this two list into a dictionary
list_id= ['2000391314791P', '2000391314715P', '2000383032443P', '2000387592776P', '2000391314760P', '2000387592813P', '2000383032511P', '2000391314784P', '2000387592738P', '2000387592806P', '2000387592769P', '2000387592790P', '2000387592752P', '2000391314746P', '20003913147... | [
"Assuming that list_id and productos are in the same order and have the same number of items, you can simply use enumerate in your dictionary comprehension:\ndatos = {id: productos[i] for i, id in enumerate(list_id)}\n\nI hope that's what you were looking for.\n"
] | [
0
] | [] | [] | [
"jupyter_notebook",
"python"
] | stackoverflow_0074567214_jupyter_notebook_python.txt |
Q:
Columnar permutations in Python
How would I can find all the permutations of just the columns in a matrix. For example - if I had a square 6x6 matrix like so:
a b c d e f
1: 75 62 82 85 91 85
2: 64 74 74 82 74 64
3: 85 81 91 83 91 62
4: 91 63 81 75 75 72
5: 81 91 74 74 91 ... | Columnar permutations in Python | How would I can find all the permutations of just the columns in a matrix. For example - if I had a square 6x6 matrix like so:
a b c d e f
1: 75 62 82 85 91 85
2: 64 74 74 82 74 64
3: 85 81 91 83 91 62
4: 91 63 81 75 75 72
5: 81 91 74 74 91 63
6: 91 72 81 64 75 72
All t... | [
"Here's how I represented your data... you seem to want rows, but the permutation you want is in columns. Here it is as a list of lists, of the rows first:\nrow_matrix = [[75, 62, 82, 85, 91, 85],\n [64, 74, 74, 82, 74, 64],\n [85, 81, 91, 83, 91, 62],\n [91, 63, 81, 75, 75, 72],\n [81, 91, 74, 74, 91, 63],\n [91, ... | [
2,
0
] | [] | [] | [
"matrix",
"multiple_columns",
"permutation",
"python"
] | stackoverflow_0066226597_matrix_multiple_columns_permutation_python.txt |
Q:
Python, overloading magic methods, multiple usage for same magic method
Is it possible to overload magic methods or get a similar result as in e.g. overloading methods in C# for magic methods in python ? or is it simply another handicap of this language and it is impossible at this moment as in the past "types" us... | Python, overloading magic methods, multiple usage for same magic method | Is it possible to overload magic methods or get a similar result as in e.g. overloading methods in C# for magic methods in python ? or is it simply another handicap of this language and it is impossible at this moment as in the past "types" used to be ;)
def __init__(self, x:float, y:float, z:float) -> None:
self.x... | [
"No, it's not possible to automatically overload, but you can check for type and proceed accordingly:\nfrom typing import Union\n\nclass Vector:\n # ...\n\n def __add__(self, other: Union['Vector', float]) -> 'Vector':\n if type(other) == Vector:\n return Vector(self.x + other.x, self.y + ot... | [
1
] | [] | [] | [
"magic_methods",
"overloading",
"overriding",
"python",
"python_3.x"
] | stackoverflow_0074567336_magic_methods_overloading_overriding_python_python_3.x.txt |
Q:
I am trying to create a dash app for a Restaurant directory the dropdown filter is work I know but map doesn't update
I have restaurant name, cusines, lat , long as columns. The map I am trying to show on the html page is not updating as per the filter , It shows all the restaurnats.
import dash
from dash import d... | I am trying to create a dash app for a Restaurant directory the dropdown filter is work I know but map doesn't update | I have restaurant name, cusines, lat , long as columns. The map I am trying to show on the html page is not updating as per the filter , It shows all the restaurnats.
import dash
from dash import dcc
from dash import html
from dash.dependencies import Input, Output
import pandas as pd
import plotly.express as px
ap... | [
"I cannot reproduce your error, but perhaps some of the steps I took in debugging might prove helpful:\nFirst, I took the first 100 rows of a restaurant dataset from kaggle, and then randomly assigned three different cuisine types to each unique restaurant name. Then when creating the fig object with px.scatter_map... | [
1
] | [] | [] | [
"dataframe",
"dropdown",
"plotly",
"plotly_dash",
"python"
] | stackoverflow_0074566463_dataframe_dropdown_plotly_plotly_dash_python.txt |
Q:
n dimensional tic tac toe finding all possible win conditions or lines in a n dimensional matrix
I am trying to implement an n-dimensional tic tac toe problem. To do this I want to be able to see if any player has won yet. If there is a n-dimensional matrix of n is there a way to check all the lines?
I've tried do... | n dimensional tic tac toe finding all possible win conditions or lines in a n dimensional matrix | I am trying to implement an n-dimensional tic tac toe problem. To do this I want to be able to see if any player has won yet. If there is a n-dimensional matrix of n is there a way to check all the lines?
I've tried doing this in 2 dimensions and 3 dimensions but don't know how to algorithmically find all the win lines... | [
"Probably done really badly, but here's a solution. Possibly modifiable to any axbxcxd.. board size.\nThe key insight is that winnability is transitive: if there is a winning sequence between A and B, and B and C, so is there between A and C.\nThus we use the disjoint set structure (this implementation is somewhat ... | [
0
] | [] | [] | [
"algorithm",
"matrix",
"python"
] | stackoverflow_0074566532_algorithm_matrix_python.txt |
Q:
How to use all GPUs in SageMaker real-time inference?
I have deployed a model on real-time inference in a single gpu instance, it works fine.
Now I want to use a multiple GPUs to decrease the inference time, what do I need to change in my inference.py to make it work?
Here is some of my code:
DEVICE = "cuda" if to... | How to use all GPUs in SageMaker real-time inference? | I have deployed a model on real-time inference in a single gpu instance, it works fine.
Now I want to use a multiple GPUs to decrease the inference time, what do I need to change in my inference.py to make it work?
Here is some of my code:
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
def model_fn(model_dir):... | [
"The answer mentioning Torch DDP and DP is not exactly appropriate since the value of those libraries is to conduct multi-GPU gradient descent (averaging the gradient inter-GPU in particular), which, as mentioned in 1., does not happen at inference. Actually, a well-done, optimized inference ideally doesn't even us... | [
1,
0
] | [] | [] | [
"amazon_sagemaker",
"machine_learning",
"python"
] | stackoverflow_0074436974_amazon_sagemaker_machine_learning_python.txt |
Q:
No module named 'graphviz' in Jupyter Notebook
I tried to draw a decision tree in Jupyter Notebook this way.
mglearn.plots.plot_animal_tree()
But I didn't make it in the right way and got the following error message.
---------------------------------------------------------------------------
ModuleNotFoundError ... | No module named 'graphviz' in Jupyter Notebook | I tried to draw a decision tree in Jupyter Notebook this way.
mglearn.plots.plot_animal_tree()
But I didn't make it in the right way and got the following error message.
---------------------------------------------------------------------------
ModuleNotFoundError Traceback (most recent call las... | [
"in Anaconda install \n\npython-graphviz\npydot\n\nThis will fix your problem\n",
"As @grrr answered above, here is the code:\nconda install -c anaconda python-graphviz\n\nconda install -c anaconda pydot\n\n",
"In case if your operation system is Ubuntu I recommend to try command: \nsudo apt-get install -y grap... | [
62,
13,
5,
0,
0
] | [] | [] | [
"graphviz",
"jupyter_notebook",
"python"
] | stackoverflow_0052566756_graphviz_jupyter_notebook_python.txt |
Q:
How to get indices of rows in a given column in which a value from a different given column appears?
I have two columns. The first one is longer and has multiple values such as:
0 'A'
1 'B'
2 'B'
3 'C'
4 'A'
5 'A'
All the values in the first column are listed in the second column:
0 'A'
1 'B'
2 'C'
The result I ... | How to get indices of rows in a given column in which a value from a different given column appears? | I have two columns. The first one is longer and has multiple values such as:
0 'A'
1 'B'
2 'B'
3 'C'
4 'A'
5 'A'
All the values in the first column are listed in the second column:
0 'A'
1 'B'
2 'C'
The result I want is to have a list/series/column whatever of indecies of the values from the first column in the secon... | [
"Working with pandas Series:\nnew_s = s1.map(dict(zip(s2, s2.index)))\n\n",
"If both columns are Dataframes:\ntry this:\nmaper = dict(df2.reset_index().values[:, ::-1])\nout = df1.assign(result=df1.replace(maper))\nprint(out)\n\n"
] | [
0,
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074567334_dataframe_pandas_python.txt |
Q:
Why are all Python packages suddenly gone?
Today I wanted to run a (self written) Python script on my OSX laptop, but all of a sudden, all the imports returned an ImportError. The script was running fine about a month ago and in the meantime I didn't change anything to Python. Furthermore I'm sure that I didn't us... | Why are all Python packages suddenly gone? | Today I wanted to run a (self written) Python script on my OSX laptop, but all of a sudden, all the imports returned an ImportError. The script was running fine about a month ago and in the meantime I didn't change anything to Python. Furthermore I'm sure that I didn't use a virtualenv back then.
So I just started rein... | [
"Ok, after a lot of messing around, I found that the folder /usr/local/Cellar/python/2.7.13_1/bin/ didn't contain a symlink called python, just python2 and python2.7. \nSo finally I solved it by creating a new symlink in /usr/local/Cellar/python/2.7.13_1/bin/ like this:\nln -s ../Frameworks/Python.framework/Version... | [
2,
0
] | [] | [] | [
"easy_install",
"opencv",
"package",
"pip",
"python"
] | stackoverflow_0045257009_easy_install_opencv_package_pip_python.txt |
Q:
Problem with Unalignable boolean Series with two columns filter
In this case I am working with 2 columns that are substracted from 2 Dataframes. The columns are ["# Externo","Nro Envio ML"]]
My target is to recieve the numbers that exist in "# Externo" but no exist in"Nro Envio ML" , only that number/ or numbers t... | Problem with Unalignable boolean Series with two columns filter | In this case I am working with 2 columns that are substracted from 2 Dataframes. The columns are ["# Externo","Nro Envio ML"]]
My target is to recieve the numbers that exist in "# Externo" but no exist in"Nro Envio ML" , only that number/ or numbers that fill to that condition.
To take a look what I am talking about:
... | [
"I think you were quite close. Does this achieve what you're trying to do?\ndfn['Externo'][~dfn['Externo'].isin(dfn['Nro Envio ML'])].dropna().tolist()\n\nIt returns all non-NaN values in the 'Externo' column that are not in the 'Nro Envio ML' column as a list.\nI think the IndexingError you received may have been... | [
1
] | [] | [] | [
"filter",
"indexing",
"multiple_columns",
"pandas",
"python"
] | stackoverflow_0074564869_filter_indexing_multiple_columns_pandas_python.txt |
Q:
ImportError: cannot import name 'bigquery'
This must be a super trivial issue, but i've updated my windows virtual machine with;
pip install --upgrade google-cloud-storage
However, when I run the script I still receive the following error;
Traceback (most recent call last):
File "file.py", line 6, in <module>
... | ImportError: cannot import name 'bigquery' | This must be a super trivial issue, but i've updated my windows virtual machine with;
pip install --upgrade google-cloud-storage
However, when I run the script I still receive the following error;
Traceback (most recent call last):
File "file.py", line 6, in <module>
from google.cloud import bigquery, storage
Im... | [
"I was facing the same problem.But applying every answer nothing was working.\nThen I noticed that pip need to be ungraded. So I upgrade pip first.\npython -m pip install --upgrade pip\n\nThen I try this solution just changing a little bit https://stackoverflow.com/a/60895009/5393858\npip install --upgrade google-c... | [
24,
10,
2,
0
] | [] | [] | [
"google_bigquery",
"python"
] | stackoverflow_0060894798_google_bigquery_python.txt |
Q:
Parsing CSV file finding specific value in list
I'm parsing a CSV file using python. I've two problem:
My list is being treated as string
Is there a way to make my parsing more "elegant"
Example CSV file
Name, Address
host1,['192.168.x.10', '127.0.0.1']
host2,['192.168.x.12', '127.0.0.1']
host3,['192.168.x.14', ... | Parsing CSV file finding specific value in list | I'm parsing a CSV file using python. I've two problem:
My list is being treated as string
Is there a way to make my parsing more "elegant"
Example CSV file
Name, Address
host1,['192.168.x.10', '127.0.0.1']
host2,['192.168.x.12', '127.0.0.1']
host3,['192.168.x.14', '127.0.0.1']
My code:
with open('myFile') as file:
... | [
"padnas should help to read your csv and ast.literal_eval should help you transform your arrays, interpreted as strings, to be arrays again. If you don't want to use pandas, simply stick to ast.literal_eval only.\nimport ast\nimport pandas as pd\n\ndf = pd.read_csv('test.csv')\ndf['Address'] = df['Address'].apply(a... | [
1,
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074566537_python_python_3.x.txt |
Q:
How do I seperate parts of a list into multiple lists, and then put them all together into one big nested list?
I have a list that holds the names and ranks of five different cards (e.g 4 of spades, 2 of Hearts, etc..)
I need to be able to collect the first and third words of each 'section' in order to use it furt... | How do I seperate parts of a list into multiple lists, and then put them all together into one big nested list? | I have a list that holds the names and ranks of five different cards (e.g 4 of spades, 2 of Hearts, etc..)
I need to be able to collect the first and third words of each 'section' in order to use it further. I had an idea to use nested lists which would keep each name and rank of a card in a list, and all 5 lists in a ... | [
"I don't know exactly what you want as an output, but based on your question here is how you would access the first and third element of every string, without a nested list:\ncards = ['King of Hearts', '4 of Clubs', '8 of Clubs', 'Queen of Clubs', '9 of Diamonds']\n\n\nfor card in cards:\n string_list = card.spl... | [
1
] | [] | [] | [
"nested",
"nested_lists",
"python"
] | stackoverflow_0074567468_nested_nested_lists_python.txt |
Q:
My write( ) function is not working, why?
So, im new to coding and im making a registration system for a fictional hospital, that gets the user name, the procedure they had and the date, after that it sum some days to it( to calculate return) and then write on a .txt file, but the write part is not working, how ca... | My write( ) function is not working, why? | So, im new to coding and im making a registration system for a fictional hospital, that gets the user name, the procedure they had and the date, after that it sum some days to it( to calculate return) and then write on a .txt file, but the write part is not working, how can i solve it? sorry that the prints and variabl... | [
"Change\na = open(arq, 'r+')\n\nto\na = open(arq, 'w+')\n\n"
] | [
0
] | [] | [] | [
"datetime",
"fopen",
"fwrite",
"python",
"python_3.x"
] | stackoverflow_0074567519_datetime_fopen_fwrite_python_python_3.x.txt |
Q:
Python Tkinter: 6x5 entry boxes accepter input which will automatically become uppercase
I am working on a wordle clone as a project to get familiar with python and tkinter. I have made a 6x5 grid of entry boxes that all accept one letter. I am trying to make it that each box will automatically convert that letter... | Python Tkinter: 6x5 entry boxes accepter input which will automatically become uppercase | I am working on a wordle clone as a project to get familiar with python and tkinter. I have made a 6x5 grid of entry boxes that all accept one letter. I am trying to make it that each box will automatically convert that letter to uppercase, but I am having issues with that. Only the very last entry will be uppercase.
d... | [
"You can pass your widget name with %W into your validation part.\nvcmd = (window.register(validate), '%P', '%W')\n\nNow let's come to validation part. There is a little problem in here. You cannot change whatever comes into validation actually. It changes only when you return True. So as you may not execute anythi... | [
0,
0
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0074562862_python_tkinter.txt |
Q:
How to pass a list as an environment variable?
I use a list as part of a Python program, and wanted to convert that to an environment variable.
So, it's like this:
list1 = ['a.1','b.2','c.3']
for items in list1:
alpha,number = items.split('.')
print(alpha,number)
which gives me, as expected:
a 1
b 2
c 3
... | How to pass a list as an environment variable? | I use a list as part of a Python program, and wanted to convert that to an environment variable.
So, it's like this:
list1 = ['a.1','b.2','c.3']
for items in list1:
alpha,number = items.split('.')
print(alpha,number)
which gives me, as expected:
a 1
b 2
c 3
But when I try to set it as an environment variable... | [
"The rationale\nI recommend using JSON if you want to have data structured in an environment variable. JSON is simple to write / read, can be written in a single line, parsers exist, developers know it.\nThe solution\nTo test, execute this in your shell:\n$ export ENV_LIST_EXAMPLE='[\"Foo\", \"bar\"]'\n\nPython cod... | [
112,
32,
27,
6,
0
] | [] | [] | [
"python",
"python_2.7"
] | stackoverflow_0031352317_python_python_2.7.txt |
Q:
How to get multiple dictionary values?
I have a dictionary in Python, and what I want to do is get some values from it as a list, but I don't know if this is supported by the implementation.
myDictionary.get('firstKey') # works fine
myDictionary.get('firstKey','secondKey')
# gives me a KeyError -> OK, get is no... | How to get multiple dictionary values? | I have a dictionary in Python, and what I want to do is get some values from it as a list, but I don't know if this is supported by the implementation.
myDictionary.get('firstKey') # works fine
myDictionary.get('firstKey','secondKey')
# gives me a KeyError -> OK, get is not defined for multiple keys
myDictionary['fi... | [
"There already exists a function for this:\nfrom operator import itemgetter\n\nmy_dict = {x: x**2 for x in range(10)}\n\nitemgetter(1, 3, 2, 5)(my_dict)\n#>>> (1, 9, 4, 25)\n\nitemgetter will return a tuple if more than one argument is passed. To pass a list to itemgetter, use\nitemgetter(*wanted_keys)(my_dict)\n\n... | [
158,
101,
52,
11,
8,
6,
5,
1,
0,
0,
0
] | [
"If the fallback keys are not too many you can do something like this\nvalue = my_dict.get('first_key') or my_dict.get('second_key')\n\n",
"def get_all_values(nested_dictionary):\n for key, val in nested_dictionary.items():\n data_list = []\n if type(val) is dict:\n for key1, val1 in v... | [
-1,
-2
] | [
"dictionary",
"python"
] | stackoverflow_0024204087_dictionary_python.txt |
Q:
How do I loop through a dictionary, and apply a function using key: value pairs as arguments
Dictionary = {File1: "location1", File2: "location2", File3: "location3"}
def fancy_function1(location, file):
df = pd.read_csv(location)
df["new_column"] = df[file]
return df
need help needed writing this f... | How do I loop through a dictionary, and apply a function using key: value pairs as arguments | Dictionary = {File1: "location1", File2: "location2", File3: "location3"}
def fancy_function1(location, file):
df = pd.read_csv(location)
df["new_column"] = df[file]
return df
need help needed writing this for loop or any other suggestions
for key in Dictionary:
##pass key value pairs into function
... | [
"I don't know if this helps.\nfor key in Dictionary:\n value = Dictionary[key]\n df = fancy_function(key, value)\n return df\n\nFor me this is strange because you are returning outside a function, if you want to create multiple data frames I suggest the following.\ndataframes = []\nfor key in Dictionary:\n... | [
0,
0
] | [] | [] | [
"dictionary",
"loops",
"pandas",
"python",
"python_3.x"
] | stackoverflow_0074567578_dictionary_loops_pandas_python_python_3.x.txt |
Q:
I have installed all the python libraries i want to use in the vscode terminal but when i call to import, it won't work
[{
"resource": "/d:/Users/Home/Desktop/Python/estudos/pratices.py",
"owner": "_generated_diagnostic_collection_name_#0",
"code": {
"value": "reportMissingModuleSource",
... | I have installed all the python libraries i want to use in the vscode terminal but when i call to import, it won't work | [{
"resource": "/d:/Users/Home/Desktop/Python/estudos/pratices.py",
"owner": "_generated_diagnostic_collection_name_#0",
"code": {
"value": "reportMissingModuleSource",
"target": {
"$mid": 1,
"external": "https://github.com/microsoft/pyright/blob/main/docs/configurati... | [
"I had a similar issue before and the solution I found is that you have to make sure the python interpreter for the current VSC window is your virtual environment instead of the system-wide python interpreter. On windows:\n\nPress F1\nSearch for \"interpreter\".\nClick the python one\nClick \"Enter interpreter path... | [
0,
0
] | [] | [] | [
"pip",
"python",
"visual_studio_code"
] | stackoverflow_0074564636_pip_python_visual_studio_code.txt |
Q:
How do I get Python and Python in Visual Studio code to output the sem when using os.getcwd()?
I wanted to make it easier to edit my code on different devices with different usernames, so I decided to change how my code knows where my files are. Instead of using the entire file path, I decided to use os.getcwd but... | How do I get Python and Python in Visual Studio code to output the sem when using os.getcwd()? | I wanted to make it easier to edit my code on different devices with different usernames, so I decided to change how my code knows where my files are. Instead of using the entire file path, I decided to use os.getcwd but when I run it in Visual Studio Code I only get C:\Users\Name while when I run it with just python I... | [
"os.getcwd() returns the directory where the running file is located if you run the file directly in the terminal or double-click.\nHowever if you run the file in vscode it should be noted that no matter where the file you are running, the cwd you get will still be the workspace instead of the folder where the file... | [
2
] | [] | [] | [
"python",
"visual_studio_code"
] | stackoverflow_0074566483_python_visual_studio_code.txt |
Q:
Trying to pass in the list of name and number from my contact python code but only save the very last input
import re
contact = {}
def display_contact():
for name, number in sorted((k,v) for k, v in contact.items()):
print(f'Name: {name}, Number: {number}')
#def display_contact():
# print("Name\t\tCo... | Trying to pass in the list of name and number from my contact python code but only save the very last input |
import re
contact = {}
def display_contact():
for name, number in sorted((k,v) for k, v in contact.items()):
print(f'Name: {name}, Number: {number}')
#def display_contact():
# print("Name\t\tContact Number")
# for key in contact:
# print("{}\t\t{}".format(key,contact.get(key)))
while True:
choice... | [
"You're looking for serialization, which is (usually) best left to libraries. The json library easily handles reading and writing dictionaries to a file.\nTo write a dictionary, take a look at json.dump():\nwith open(\"Saved_Contact_List.txt\", \"w\") as f:\n json.dump(contact, f)\n\n"
] | [
1
] | [] | [] | [
"data_structures",
"project",
"python",
"python_3.x"
] | stackoverflow_0074567668_data_structures_project_python_python_3.x.txt |
Q:
datetime json dump or load problem during writing and reading file
i have this piece of code in testing currently
from_api_response_data = [
{
"active": True,
"available": True,
"test1": True,
"test2": "Testing Only",
"test3": False,
"test_name": "Tester 1",
"id": "12345abcxyz",
"... | datetime json dump or load problem during writing and reading file | i have this piece of code in testing currently
from_api_response_data = [
{
"active": True,
"available": True,
"test1": True,
"test2": "Testing Only",
"test3": False,
"test_name": "Tester 1",
"id": "12345abcxyz",
"test_url": {
"url": "/something/others/api/v1/abc123"
}
},
... | [
"This is happening because the last dictionary this { \"last_updated_date\": \"2022-11-25T09:48:12.765296\" } doesn't contain the key 'available'. So the exception keyerror will be thrown. To get around it use get which return None when the key is not found\nfor test in test_file_json_read:\n if test.get('avail... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0074567638_python.txt |
Q:
Is it possible to create an empty csv file in Django database?
I am wondering if it is possible to create an empty csv file in Django database. Basically what I am trying to do is to allow the user to upload a text file as TextUpload model object, then run the code in the backend to process the text file and to sa... | Is it possible to create an empty csv file in Django database? | I am wondering if it is possible to create an empty csv file in Django database. Basically what I am trying to do is to allow the user to upload a text file as TextUpload model object, then run the code in the backend to process the text file and to save it as ProcessedTextToCsv model object. My views.py code looks som... | [
"There is no such thing as Django database. Django is a framework that uses several databases.\nBack to your question, yes it is possible, all steps are described in the Django tutorial for basic-file-uploads, what you want is something similar to this:\nforms.py:\nfrom django import forms\n\nclass UploadFileForm(f... | [
0
] | [] | [] | [
"csv",
"django",
"python"
] | stackoverflow_0074567609_csv_django_python.txt |
Q:
Convert Python dict into a dataframe
I have a Python dictionary like the following:
{u'2012-06-08': 388,
u'2012-06-09': 388,
u'2012-06-10': 388,
u'2012-06-11': 389,
u'2012-06-12': 389,
u'2012-06-13': 389,
u'2012-06-14': 389,
u'2012-06-15': 389,
u'2012-06-16': 389,
u'2012-06-17': 389,
u'2012-06-18': 390,
... | Convert Python dict into a dataframe | I have a Python dictionary like the following:
{u'2012-06-08': 388,
u'2012-06-09': 388,
u'2012-06-10': 388,
u'2012-06-11': 389,
u'2012-06-12': 389,
u'2012-06-13': 389,
u'2012-06-14': 389,
u'2012-06-15': 389,
u'2012-06-16': 389,
u'2012-06-17': 389,
u'2012-06-18': 390,
u'2012-06-19': 390,
u'2012-06-20': 390,
... | [
"The error here, is since calling the DataFrame constructor with scalar values (where it expects values to be a list/dict/... i.e. have multiple columns):\npd.DataFrame(d)\nValueError: If using all scalar values, you must must pass an index\n\nYou could take the items from the dictionary (i.e. the key-value pairs):... | [
782,
326,
165,
84,
56,
16,
16,
13,
9,
9,
6,
6,
5,
1,
1,
1,
0,
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0018837262_dataframe_pandas_python.txt |
Q:
How to split complex JSON file into multiple files by Python
I am currently splitting Json file.
The structure of JSON file is like this :
{
"id": 2131424,
"file": "video_2131424_1938263.mp4",
"metadata": {
"width": 3840,
"height": 2160,
"duration": 312.83,
"fps": 30,
... | How to split complex JSON file into multiple files by Python | I am currently splitting Json file.
The structure of JSON file is like this :
{
"id": 2131424,
"file": "video_2131424_1938263.mp4",
"metadata": {
"width": 3840,
"height": 2160,
"duration": 312.83,
"fps": 30,
"frames": 9385,
"created": "Sun Jan 17 17:48:52 2021... | [
"I hope I've understood your question right. To get x, y, width, height from each label (dct is your dictionary from the question):\nout = [\n [\n [\n a[\"label\"][\"x\"],\n a[\"label\"][\"y\"],\n a[\"label\"][\"width\"],\n a[\"label\"][\"height\"],\n ]\n... | [
0
] | [] | [] | [
"json",
"python"
] | stackoverflow_0074567704_json_python.txt |
Q:
how to save parsed data into two different lists
I have this code:
lokk = []
nums = 7
for _ in range(nums):
inner = driver.find_element_by_xpath(
"/html/body/div[1]/div[2]/div/div/div/div[2]/div/div/div/div[2]/div[2]/div/div/div[2]/div[5]/span[1]").get_attribute(
"innerHTML")
lokk.append(i... | how to save parsed data into two different lists | I have this code:
lokk = []
nums = 7
for _ in range(nums):
inner = driver.find_element_by_xpath(
"/html/body/div[1]/div[2]/div/div/div/div[2]/div/div/div/div[2]/div[2]/div/div/div[2]/div[5]/span[1]").get_attribute(
"innerHTML")
lokk.append(inner)
time.sleep()
print(lokk)
which provides... | [
"You can achieve this in many ways, try this:\nFor ListC:\n lok_c = []\n num_c = 13\n for _ in range(num_c):\n inner = driver.find_element_by_xpath(\"/html/body/div[1]/div[2]/div/div/div/div[2]/div/div/div/div[2]/div[2]/div/div/div[2]/div[5]/span[1]\").\nget_attribute(\"innerHTML\")\n if num_... | [
0
] | [] | [] | [
"list",
"parsing",
"python",
"selenium"
] | stackoverflow_0074566611_list_parsing_python_selenium.txt |
Q:
Order a string by number in the string - Python
I was told to solve this but I'm not having an optimum solution
Lets say I have one string. This string is something like this
string= 'House 1 - New & Painted
House 6
House 2 - Used
House 4'
Now, i have to build a function that order thi... | Order a string by number in the string - Python | I was told to solve this but I'm not having an optimum solution
Lets say I have one string. This string is something like this
string= 'House 1 - New & Painted
House 6
House 2 - Used
House 4'
Now, i have to build a function that order this string taking account the house number, so the new ... | [
"You can use .splitlines() to get list of lines and use str.split to find and convert the number to integer in key function:\ns = \"\"\"\\\nHouse 1 - New & Painted\nHouse 6\nHouse 2 - Used \nHouse 4\"\"\"\n\ns = \"\\n\".join(sorted(s.splitlines(), key=lambda v: int(v.split()[1])))\nprint(s)\n\nPrints:\nHouse 1 - Ne... | [
2
] | [] | [] | [
"python",
"sorting"
] | stackoverflow_0074567723_python_sorting.txt |
Q:
Tkinter change paste command
I'm trying to change paste command on my program. When we copy table value from excel, whether it's vertical or horizontal line, it will converted to vertical entries list. But the problem is when I only want to paste single value to the random entries line, it will always print the va... | Tkinter change paste command | I'm trying to change paste command on my program. When we copy table value from excel, whether it's vertical or horizontal line, it will converted to vertical entries list. But the problem is when I only want to paste single value to the random entries line, it will always print the value from 1st line entry and not fr... | [
"It is because the for loop always starts from the first entry box. You need to find the index of the selected entry in the entry list d and paste the clipboard data starts from it:\ndef paste(event):\n try:\n # get selected entry\n w = root.focus_get()\n # get the index of the selected ent... | [
0
] | [] | [] | [
"paste",
"python",
"tkinter"
] | stackoverflow_0074567678_paste_python_tkinter.txt |
Q:
Numpy: How to unwrap of a matrix
I am hoping to reshape matrices in such a form
A =
[[1,2,3],
[4,5,6],
[7,8,9]]
B =
[[10,11,12],
[13,14,15],
[16,17,18]]
Z = [[1, 2, 3 10, 11, 12],
[4, 5, 6, 13, 14, 15],
[7,8,9, 16, 17 ,18]]
Where A,B are a 3x3 matrices but z is a 3x6 matrix. I'd like to be able to apply it t... | Numpy: How to unwrap of a matrix | I am hoping to reshape matrices in such a form
A =
[[1,2,3],
[4,5,6],
[7,8,9]]
B =
[[10,11,12],
[13,14,15],
[16,17,18]]
Z = [[1, 2, 3 10, 11, 12],
[4, 5, 6, 13, 14, 15],
[7,8,9, 16, 17 ,18]]
Where A,B are a 3x3 matrices but z is a 3x6 matrix. I'd like to be able to apply it to higher dimensions.
np.ravel returns ... | [
"Assume A and B are always the same shape:\nnp.vstack((A, B)).reshape(len(A), -1)\n\n#array([[ 1, 2, 3, 4, 5, 6],\n# [ 7, 8, 9, 10, 11, 12],\n# [13, 14, 15, 16, 17, 18]])\n\n"
] | [
1
] | [] | [] | [
"matrix",
"numpy",
"python"
] | stackoverflow_0074567647_matrix_numpy_python.txt |
Q:
Python 3 - How to change the syntax of a "datetime.timedelta(seconds=xxx)" object?
below a simple example using the Python interpreter:
>>> import datetime
>>>
>>> time=datetime.timedelta(seconds=10)
>>> str(time)
'0:00:10'
>>>
how can I change the syntaxt of the time object when I convert it in a string? As res... | Python 3 - How to change the syntax of a "datetime.timedelta(seconds=xxx)" object? | below a simple example using the Python interpreter:
>>> import datetime
>>>
>>> time=datetime.timedelta(seconds=10)
>>> str(time)
'0:00:10'
>>>
how can I change the syntaxt of the time object when I convert it in a string? As reslt, I want to see '00:00:10' and not '0:00:10'. I really don't understand why the last z... | [
"You have to create your custom formatter to do this.\nPython3 variant of @gumption solution which is written in python2.\nThis is the link to his solution\nCustom Formatter\nfrom string import Template\n\nclass TimeDeltaTemp(Template):\n delimiter = \"%\"\n\ndef strfdtime(dtime, formats):\n day = {\"D\": dti... | [
2
] | [] | [] | [
"datetime",
"python",
"python_3.x",
"timedelta"
] | stackoverflow_0074567716_datetime_python_python_3.x_timedelta.txt |
Q:
Cannot install lightgbm==3.3.3 on Apple Silicon
Here the full log of pip3 install lightgbm==3.3.3.
me % pip3 install lightgbm==3.3.3
Collecting lightgbm==3.3.3
Using cached lightgbm-3.3.3.tar.gz (1.5 MB)
Preparing metadata (setup.py) ... done
Requirement already satisfied: wheel in /opt/homebrew/lib/python3.10... | Cannot install lightgbm==3.3.3 on Apple Silicon | Here the full log of pip3 install lightgbm==3.3.3.
me % pip3 install lightgbm==3.3.3
Collecting lightgbm==3.3.3
Using cached lightgbm-3.3.3.tar.gz (1.5 MB)
Preparing metadata (setup.py) ... done
Requirement already satisfied: wheel in /opt/homebrew/lib/python3.10/site-packages (from lightgbm==3.3.3) (0.37.1)
Collec... | [
"When you run pip install lightgbm and see this message in logs:\n\nBuilding wheels for collected packages: lightgbm\n\nit means that there is not a pre-compiled binary (i.e. wheel) available matching your platform (operating system + architecture + Python version), and that LightGBM needs to be built from source.\... | [
0
] | [] | [] | [
"apple_silicon",
"numpy",
"pip",
"python"
] | stackoverflow_0074566704_apple_silicon_numpy_pip_python.txt |
Q:
For a new Python project using the latest version of Python should I declare my types as upper or lower case
According to pep-0585 for the latest versions of Python, it appears we can use List and list interchangeably for type declarations. So which should I use?
Assume:
no requirement for backward compatibility
... | For a new Python project using the latest version of Python should I declare my types as upper or lower case | According to pep-0585 for the latest versions of Python, it appears we can use List and list interchangeably for type declarations. So which should I use?
Assume:
no requirement for backward compatibility
using the latest version of python
from typing import List
def hello_world_1(animals: list[str]) -> list[str]:
... | [
"According to the current Python docs, typing.List and similar are deprecated.\nThe docs further state\n\nThe deprecated types will be removed from the typing module in the first Python version released 5 years after the release of Python 3.9.0. See details in PEP 585—Type Hinting Generics In Standard Collections.... | [
3,
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0074567273_python.txt |
Q:
print pandas dataframe diff to new column
I have a dataframe that looks like this. There are two rows for each id. These represent a game where the row with the highest points is the winner:
id points
677 5
677 15
678 25
678 6
I would like to generate a new column 'win' in the dataframe so that the ... | print pandas dataframe diff to new column | I have a dataframe that looks like this. There are two rows for each id. These represent a game where the row with the highest points is the winner:
id points
677 5
677 15
678 25
678 6
I would like to generate a new column 'win' in the dataframe so that the row with the same id with the higher points get... | [
"Find the max points for each id and mark it as win:\ndf['win'] = (df.points.groupby(df['id']).transform('max') == df.points).astype(int)\ndf\n id points win\n0 677 5 0\n1 677 15 1\n2 678 25 1\n3 678 6 0\n\n"
] | [
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074567843_pandas_python.txt |
Q:
What model.predict() in Keras or Tensorflow is doing numerically?
What I would like to know:
I have built and trained a CNN model in keras and have been able to calculate predictions, but I would like to know the details of the process of what is happening numerically in the prediction step.
What I tried:
(1) Calc... | What model.predict() in Keras or Tensorflow is doing numerically? | What I would like to know:
I have built and trained a CNN model in keras and have been able to calculate predictions, but I would like to know the details of the process of what is happening numerically in the prediction step.
What I tried:
(1) Calculate the score with the trained Keras model.
(2) Coded my CNN and calc... | [
"I solved it by myself.\nI was mistaken and it was handled as per the text.\nIt didn't look like keras was doing anything else.\n"
] | [
0
] | [] | [] | [
"deep_learning",
"keras",
"python",
"tensorflow"
] | stackoverflow_0072300556_deep_learning_keras_python_tensorflow.txt |
Q:
String to numpy array image
I want convert string to image.
What I want is :
input = string
output = 2D or 3D numpy array image consisting of 0, 255 maybe
Is there any package or module doing this??
Thank you.
A:
you can use opencv2.putText
https://docs.opencv.org/4.x/dc/da5/tutorial_py_drawing_functions.html
op... | String to numpy array image | I want convert string to image.
What I want is :
input = string
output = 2D or 3D numpy array image consisting of 0, 255 maybe
Is there any package or module doing this??
Thank you.
| [
"you can use opencv2.putText\nhttps://docs.opencv.org/4.x/dc/da5/tutorial_py_drawing_functions.html\nopencv-python workwith numpy.ndarray\n"
] | [
1
] | [] | [] | [
"image",
"numpy",
"python",
"string",
"text"
] | stackoverflow_0074567880_image_numpy_python_string_text.txt |
Q:
How to make this sorting faster?
Task:
Submit a file containing the sort_people(people) function. It gets a list of people and returns a sorted list of people. Sort primarily by date of birth (oldest person to youngest), if there is a match by last name (ascending according to the usual Python string comparison), ... | How to make this sorting faster? | Task:
Submit a file containing the sort_people(people) function. It gets a list of people and returns a sorted list of people. Sort primarily by date of birth (oldest person to youngest), if there is a match by last name (ascending according to the usual Python string comparison), and finally by first name (also ascend... | [
"A tuple (and list) comparison compares its items in order, and returns the comparison of the first non-equal member. Thus, if you construct a key that provides a series of values to be compared in order, you can get the equivalent of your code like this:\npeople.sort(key=lambda p: (\n datetime.strptime(p1.birth... | [
0
] | [] | [] | [
"python",
"sorting"
] | stackoverflow_0074567908_python_sorting.txt |
Q:
Django Can't See Where I Typed in User ID
So I'm creating a web app in Django, and I encountered this error:
my urls.py:
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('<int:user_id>/', views.profile, name="profile"),
#path('signup/', views.... | Django Can't See Where I Typed in User ID | So I'm creating a web app in Django, and I encountered this error:
my urls.py:
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('<int:user_id>/', views.profile, name="profile"),
#path('signup/', views.signup, name="signup"),
path("signup/", vie... | [
"You need to save an object in User Model like this...\ndef signup(request):\n if request.method == \"POST\":\n form = SignUpForm(request.POST)\n if form.is_valid():\n rn = datetime.today().strftime(\"%Y-%m-%D\")\n rn2 = datetime.today\n new_user = User(username= form.cleaned_data[\"us... | [
0
] | [] | [] | [
"django",
"django_models",
"django_views",
"python",
"python_3.x"
] | stackoverflow_0074566011_django_django_models_django_views_python_python_3.x.txt |
Q:
`int('10**2')` raises `ValueError: invalid literal for int() with base 10: '10**2'` despite `type(10**2)` being ``
int('10**2') raises ValueError: invalid literal for int() with base 10: '10**2' despite type(10**2) being <class 'int'>.
I take input n as n = input(), then I do int(n). When I input 10**2, I get Valu... | `int('10**2')` raises `ValueError: invalid literal for int() with base 10: '10**2'` despite `type(10**2)` being `` | int('10**2') raises ValueError: invalid literal for int() with base 10: '10**2' despite type(10**2) being <class 'int'>.
I take input n as n = input(), then I do int(n). When I input 10**2, I get ValueError: invalid literal for int() with base 10: '10**2'.
I'm guessing the issue is that 10**2 is not a literal - it has ... | [
"Yes, 10**2 must be evaluated while 1e2 is a constant. I suggest taking a look at Evaluating a mathematical expression in a string for some options regarding parsing mathematical expressions in strings.\n"
] | [
2
] | [] | [] | [
"input",
"integer",
"literals",
"python",
"user_input"
] | stackoverflow_0074567924_input_integer_literals_python_user_input.txt |
Q:
Can I paint on the tkinter canvas twice simultaneously?
I want the cursor's x and y coordinates to be tracked by two sliding lines when the cursor is over a canvas. One on the top of the canvas constrained to x, and one at the left of the canvas constrained to y.
I have actually achieved this, almost:
import tkint... | Can I paint on the tkinter canvas twice simultaneously? | I want the cursor's x and y coordinates to be tracked by two sliding lines when the cursor is over a canvas. One on the top of the canvas constrained to x, and one at the left of the canvas constrained to y.
I have actually achieved this, almost:
import tkinter as tk
def callback(event):
draw_y_marker(event.y)
... | [
"You have only created one line item in the canvas, so how can you show two sliding lines?\nYou need to create the two sliding lines for x and y and update them in callback():\nimport tkinter as tk\n\ndef callback(event):\n draw_y_marker(event.y)\n draw_x_marker(event.x)\n\ndef draw_x_marker(x):\n paint.co... | [
1
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0074567944_python_tkinter.txt |
Q:
Converting a dataframe's datetime64[ns] index to a comparable datetime dtype
Trying to create a mask for my dataframe but can not compare the upper bound / lower bound datetimes to the index of the dataframe due to it being datetime64[ns]. I have seen the solution be to convert via pd.Timestamp - however I still g... | Converting a dataframe's datetime64[ns] index to a comparable datetime dtype | Trying to create a mask for my dataframe but can not compare the upper bound / lower bound datetimes to the index of the dataframe due to it being datetime64[ns]. I have seen the solution be to convert via pd.Timestamp - however I still get a value error.
Additionally I have tried to convert the index and am thrown the... | [
"Datetime64 Indexes can be refined to just the date by .date\ndf.index.date >= date or df.index.datetime >= datetime \n\nwould work\n",
"use numpy.datetime64\nNOTE: seem can't compare between time-aware datetime,\nuse tz_localize to remove it's timezone\nor you can just convert datetime to timestamp (int)\nimport... | [
0,
0
] | [] | [] | [
"date",
"datetime64",
"pandas",
"python"
] | stackoverflow_0074567875_date_datetime64_pandas_python.txt |
Q:
How to solve AttributeError: 'Tensor' object has no attribute 'zero_grad' in pytorch
Still working through video tutorial https://www.youtube.com/watch?v=weQ5pShEVic&list=PLbMqOoYQ3Mxw1Sl5iAAV4SJmvnAGAhFvK&index=2 about pytorch but hit another error.
lossFunc = torch.nn.MSELoss()
for i in range(epoch):
out... | How to solve AttributeError: 'Tensor' object has no attribute 'zero_grad' in pytorch | Still working through video tutorial https://www.youtube.com/watch?v=weQ5pShEVic&list=PLbMqOoYQ3Mxw1Sl5iAAV4SJmvnAGAhFvK&index=2 about pytorch but hit another error.
lossFunc = torch.nn.MSELoss()
for i in range(epoch):
output = net(x)
loss = lossFunc(output, y)
loss.zero_grad()
loss.back... | [
"You should use zero grad for your optimizer.\noptimizer = torch.optim.Adam(net.parameters(), lr=0.001)\nlossFunc = torch.nn.MSELoss()\nfor i in range(epoch):\n optimizer.zero_grad()\n output = net(x)\n loss = lossFunc(output, y)\n loss.backward()\n optimizer.step()\n\n"
] | [
2
] | [] | [] | [
"python",
"pytorch"
] | stackoverflow_0074567865_python_pytorch.txt |
Q:
Merge rows based on 2 field match
I'm trying to merge a specific column if the rows are similar, for example here "l.instagram.com" and "instagram.com" is actually the same source so I would like to merge activeUsers into instagram.com.
Give:
sessionSource dateRange activeUsers
0 snapchat.com previous... | Merge rows based on 2 field match | I'm trying to merge a specific column if the rows are similar, for example here "l.instagram.com" and "instagram.com" is actually the same source so I would like to merge activeUsers into instagram.com.
Give:
sessionSource dateRange activeUsers
0 snapchat.com previous 1
1 snapchat.com curr... | [
"Replace the value l.instagram.com'with instagram.com: df['sessionSource']=df['sessionSource'].replace('l.instagram.com','instagram.com')\nAnd then group by the columns 'sessionSource' & 'dataRange' and sum 'activeUsers':\nsum_df = df.groupby(['sessionSource','dataRange']).agg({'activeUsers': 'sum'})\n\n\nsum_df=su... | [
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074567695_dataframe_pandas_python.txt |
Q:
Is there any difference between the type of the expressions "python" and ’python’?
Is word "python" and 'python' are different expression??
I want to know the differnecce between the type of the expressions "python" and ’python’
A:
They both are same. Double quotes are typically used for string representation, ... | Is there any difference between the type of the expressions "python" and ’python’? |
Is word "python" and 'python' are different expression??
I want to know the differnecce between the type of the expressions "python" and ’python’
| [
"They both are same. Double quotes are typically used for string representation, while single quotes are used for regular expressions, dict keys, and SQL. As a result, both single quotes and double quotes represent strings in Python, but we may need to use one over the other at times.\nFor more clarity:\ntype(\"pyt... | [
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074567993_python.txt |
Q:
What is a 'NoneType' object?
I'm getting this error when I run my python script:
TypeError: cannot concatenate 'str' and 'NoneType' objects
I'm pretty sure the 'str' means string, but I dont know what a 'NoneType' object is. My script craps out on the second line, I know the first one works because the commands f... | What is a 'NoneType' object? | I'm getting this error when I run my python script:
TypeError: cannot concatenate 'str' and 'NoneType' objects
I'm pretty sure the 'str' means string, but I dont know what a 'NoneType' object is. My script craps out on the second line, I know the first one works because the commands from that line are in my asa as I w... | [
"NoneType is the type for the None object, which is an object that indicates no value. None is the return value of functions that \"don't return anything\". It is also a common default return value for functions that search for something and may or may not find it; for example, it's returned by re.search when the r... | [
111,
30,
29,
17,
9,
4,
2,
1,
1,
0,
0,
0,
0
] | [] | [] | [
"nonetype",
"null",
"python"
] | stackoverflow_0021095654_nonetype_null_python.txt |
Q:
How to get the class name of a method in Python?
Here's my problem and the code:
I try to use a decorator to reecord the time cost; but I cannot get the class name.
import functools
import time
def log_time(func):
@functools.wraps(func)
def record(*args, **kwargs):
# print(func)
# print(fu... | How to get the class name of a method in Python? | Here's my problem and the code:
I try to use a decorator to reecord the time cost; but I cannot get the class name.
import functools
import time
def log_time(func):
@functools.wraps(func)
def record(*args, **kwargs):
# print(func)
# print(func.__name__)
# print(func.__class__)
... | [
"In this particular case, you can just use the __qualname__:\nimport functools\nimport time\n\n\ndef log_time(func):\n @functools.wraps(func)\n def record(*args, **kwargs):\n func_name = func.__qualname__\n start_time = time.time()\n result = func(*args, **kwargs)\n print(f\"{func_... | [
0
] | [] | [] | [
"class",
"decorator",
"printing",
"python"
] | stackoverflow_0074568082_class_decorator_printing_python.txt |
Q:
Seaborn lineplot Y-axis values to 1 decimal place - code not working but not sure why
I have the following code.
I am trying to plot a lineplot using seaborn.
However, I want all the Y-values to be to 1 decimal place.
When I try to set all these values to 1 decimal place, this does not seem to work.
I would be so ... | Seaborn lineplot Y-axis values to 1 decimal place - code not working but not sure why | I have the following code.
I am trying to plot a lineplot using seaborn.
However, I want all the Y-values to be to 1 decimal place.
When I try to set all these values to 1 decimal place, this does not seem to work.
I would be so grateful for a helping hand!
listedvariables = ['gender']
newestdf[['distance']] = newestdf... | [
"Add these two lines (before title variable setup in your code):\nylabels = ['{:,.2f}'.format(x) for x in ax.get_yticks()]\nax.set_yticklabels(ylabels)\n\nHope this helps!\n"
] | [
1
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0074567301_matplotlib_python.txt |
Q:
Python expression differnce
What is the difference between the expressions
c = 299792458 and c = 2.99792458 * 10 ** 8 in python?
is it same or different
A:
c = 299792458 this is an integer and 2.99792458 * 10 ** 8 will evaluate to a float. So to answer your question, no they are not the same.
type(299792458)
> <... | Python expression differnce | What is the difference between the expressions
c = 299792458 and c = 2.99792458 * 10 ** 8 in python?
is it same or different
| [
"c = 299792458 this is an integer and 2.99792458 * 10 ** 8 will evaluate to a float. So to answer your question, no they are not the same.\ntype(299792458)\n> <class 'int'>\n\ntype(2.99792458 * 10 ** 8) \n> <class 'float'>\n\n\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074568067_python.txt |
Q:
Is LightGBM available for Mac M1?
My goal is to learn a notebook. It has recall 97% while I am struggling with F1 Score 'Attrited Customer' 77.9%. The problem is the notebook uses LightGBM. I am unable to install LightGBM.
What I've tried:
pip install lightgbm -> it throws error python setup.py egg_info did not r... | Is LightGBM available for Mac M1? | My goal is to learn a notebook. It has recall 97% while I am struggling with F1 Score 'Attrited Customer' 77.9%. The problem is the notebook uses LightGBM. I am unable to install LightGBM.
What I've tried:
pip install lightgbm -> it throws error python setup.py egg_info did not run successfully.
Then, I did pip instal... | [
"As of this writing, no official release of lightgbm (the Python package for LightGBM) supports the M1 Macs (which us ARM chips).\nosx-arm64 builds of lightgbm are supported by the lightgbm conda-forge feedstock, so you can install lightgbm on an M1 Mac using conda.\nconda install \\\n --yes \\\n -c conda-forge... | [
1
] | [] | [] | [
"apple_m1",
"kaggle",
"lightgbm",
"pip",
"python"
] | stackoverflow_0074568115_apple_m1_kaggle_lightgbm_pip_python.txt |
Q:
Determine most utilized location for a specific date using Pandas
I would like to find out the most utilized location for the date of 2/1/2022.
Data
ID location total marks_free marks_utilized date
1 NY 6 5 1 2/1/2022
2 NY 10 5 5 ... | Determine most utilized location for a specific date using Pandas | I would like to find out the most utilized location for the date of 2/1/2022.
Data
ID location total marks_free marks_utilized date
1 NY 6 5 1 2/1/2022
2 NY 10 5 5 2/1/2022
3 NY 2 1 1 2/1/20... | [
"just need a simple modification on your attempt, it would work.\ndf1['marks_utilized'] = df['marks_utilized'] / df['total'] * 100 should be df1['marks_utilized'] = df1['marks_utilized'] / df1['total'] * 100\nIf you only want result in 2/1/2022, you could filter the df and do groupby afterwards. Also, could use df1... | [
2,
1
] | [] | [] | [
"group_by",
"numpy",
"pandas",
"python"
] | stackoverflow_0074568063_group_by_numpy_pandas_python.txt |
Q:
Is there a way to use laptop's built-in biometric sensors in python applications?
I am trying to make an application using python that registers students' attendance. I'm planning to use my laptop's fingerprint built-in fingerprint device to identify the students and register the attendance.
I've tried some web se... | Is there a way to use laptop's built-in biometric sensors in python applications? | I am trying to make an application using python that registers students' attendance. I'm planning to use my laptop's fingerprint built-in fingerprint device to identify the students and register the attendance.
I've tried some web searches but I couldn't find anyway to use built-in fingerprint devices for applications ... | [
"This can not be done for now. The fingerprint sensor associated with laptop/mobile can be used for authentication purpose only. Means, you can add the more number of fingerprints who are eligible to access the device. Then, device will allow any one of them to unlock the device. It will not record whose fingerprin... | [
2,
0
] | [] | [] | [
"biometrics",
"fingerprint",
"hardware",
"python"
] | stackoverflow_0070875299_biometrics_fingerprint_hardware_python.txt |
Q:
Removing an empty line in a file
I have been trying to delete lines from a file without loading in memory all the file, because it's too large (~1Gb). How i do it without leaving a blank line in the file?
For example:
I want this
foo bar
this is the line to be removed
foo bar
foo bar
To this:
foo bar
foo bar
foo ... | Removing an empty line in a file | I have been trying to delete lines from a file without loading in memory all the file, because it's too large (~1Gb). How i do it without leaving a blank line in the file?
For example:
I want this
foo bar
this is the line to be removed
foo bar
foo bar
To this:
foo bar
foo bar
foo bar
But I get this:
foo bar
foo bar
... | [
"A much simpler approach to filtering a file in-place would be to open the same file twice, once for reading and another for writing, output only what needs to be kept, and truncate the output in the end. This way, none of tell or seek or any file position calculations would be needed:\nwith open('file.txt') as fil... | [
1,
0
] | [] | [] | [
"file",
"large_files",
"python"
] | stackoverflow_0074567654_file_large_files_python.txt |
Q:
Sorting a list using sorted, key and lambda
i have this list which is a z3 model:
list = [x_2 = 0, x_1 = 1, x_3 = 27, x_11 = 1, x_18 = 4, x_17 = 6, x_26 = 4, x_12 = 4, x_7 = 2, x_22 = 8, x_23 = 27, x_21 = 1, x_28 = 4,x_6 = 1, x_16 = 4, x_27 = 9, x_13 = 27, x_8 = 27, x_29 = 1, x_24 = 19, x_19 = 2, x_14 = 13, x_9 =... | Sorting a list using sorted, key and lambda | i have this list which is a z3 model:
list = [x_2 = 0, x_1 = 1, x_3 = 27, x_11 = 1, x_18 = 4, x_17 = 6, x_26 = 4, x_12 = 4, x_7 = 2, x_22 = 8, x_23 = 27, x_21 = 1, x_28 = 4,x_6 = 1, x_16 = 4, x_27 = 9, x_13 = 27, x_8 = 27, x_29 = 1, x_24 = 19, x_19 = 2, x_14 = 13, x_9 = 20, x_4 = 23, x_25 = 5, x_20 = 4, x_15 = 3, x_10... | [
"just wanted to ask.. is this working in your code.? Please let me know.\nlist = sorted ([(i, solved[i]) for i in solved], key = lambda x: int(str(x[0])[2:]))\n\nMy approach:- as all contains (x_) slicing this part (x_)-> [2:] and than sorting on the basis of integer. Just don't know is it working or not.\n"
] | [
1
] | [] | [] | [
"list",
"python",
"sorting",
"z3"
] | stackoverflow_0074567697_list_python_sorting_z3.txt |
Q:
Why only id column is shown in migration file when I create model in Python?
from django.db import models
class Town(models.Model):
name: models.CharField(max_length=70,unique=True)
country: models.CharField(max_length=30,unique=True)
class Meta:
pass
This is my model Town whith two attr... | Why only id column is shown in migration file when I create model in Python? | from django.db import models
class Town(models.Model):
name: models.CharField(max_length=70,unique=True)
country: models.CharField(max_length=30,unique=True)
class Meta:
pass
This is my model Town whith two attributes: name and country. When I create a migration in the initial_0001.py file on... | [
"The ID-Field is always automatically generated by Django when making migrations. You can specifiy your own ID field aswell, but using an auto-incremented like this is fine for your use case.\nYou also might want to get rid of the unique=True, as it would prevent adding multiple towns from the same country.\nCreate... | [
0,
0
] | [] | [] | [
"django_models",
"migration",
"python"
] | stackoverflow_0072461496_django_models_migration_python.txt |
Q:
Why is the time complexity (n*k) instead of ((n-k)*k) for this algorithm?
I am wondering why this brute force approach to a Maximum Sum Subarray of Size K problem is of time complexity nk instead of (n-k)k. Given that we are subtracting K elements from the outer most loop wouldn't the latter be more appropriate? T... | Why is the time complexity (n*k) instead of ((n-k)*k) for this algorithm? | I am wondering why this brute force approach to a Maximum Sum Subarray of Size K problem is of time complexity nk instead of (n-k)k. Given that we are subtracting K elements from the outer most loop wouldn't the latter be more appropriate? The text solution mentions nk and confuses me slightly.
I have included the shor... | [
"In the calculation of time complexity, O(n)=O(n-1)=O(n-k) ,both represent the complexity of linear growth, thus O(n-k)✖️O(k) = O(n*k). Of course, this question can be optimized to O(n) time complexity by using the sum of prefixes.\ndef max_sub_array_of_size_k(k, arr):\n s = [0]\n for i in range(len(arr)):\n ... | [
1,
0
] | [] | [] | [
"algorithm",
"arrays",
"python",
"sliding_window",
"time_complexity"
] | stackoverflow_0074567521_algorithm_arrays_python_sliding_window_time_complexity.txt |
Q:
Python Lists and Files
I need help figuring out how to output every word in a list that has whatever letter the user picks in it.
For example if my list was ["Bob", "Mary", "Jezebel"] and I ask the user to pick any letter and they pick the letter z, I want to find out how I can output Jezebel only from the list us... | Python Lists and Files | I need help figuring out how to output every word in a list that has whatever letter the user picks in it.
For example if my list was ["Bob", "Mary", "Jezebel"] and I ask the user to pick any letter and they pick the letter z, I want to find out how I can output Jezebel only from the list using a for loop.
import os.pa... | [
"As the word list contains.. [\"Bob\", \"Mary\", \"Jezebel\"]\nCode:-\nword_list=[\"Bob\", \"Mary\", \"Jezebel\"]\nletter = input(\"Pick a letter of your choosing and every word with that letter will be outputted\")\nfor word in word_list:\n if letter in word:\n print(word)\n\nOutput:-\nPick a letter of ... | [
0
] | [] | [] | [
"file",
"for_loop",
"list",
"python"
] | stackoverflow_0074568222_file_for_loop_list_python.txt |
Q:
How to convert array of specific keys to an Object python
I am writing a script in Python. The script uses pyreadstat library. From the library I am calling read_sas7bdat function it is returning dataframe. The code:
df = pyreadstat.read_sas7bdat(FILE_LOC, row_offset=START_FROM_ROW, row_limit=PAGE_SIZE)
finalList ... | How to convert array of specific keys to an Object python | I am writing a script in Python. The script uses pyreadstat library. From the library I am calling read_sas7bdat function it is returning dataframe. The code:
df = pyreadstat.read_sas7bdat(FILE_LOC, row_offset=START_FROM_ROW, row_limit=PAGE_SIZE)
finalList = []
for key in df[0]:
l = list(map(lambda x: str(x) if str... | [
"newJsonList = []\nfor i in range(5):\n aDict = {}\n for j in range(len(data)):\n aDict[ list(data[j].keys())[0] ] = list(data[j].values())[0][i]\n newJsonList.append(aDict)\nprint(json.dumps(newJsonList))\n\nBut also df.to_dict(orient='records') results the same <- Thanks @tdelaney\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074541812_python.txt |
Q:
Python: How to pre-calculate the slope of a line segment that will be on the graph in Matplotlib?
Given two points,
two_points = [(Timestamp('2022-11-25 01:15:00', freq='15T'), 0.08124),
(Timestamp('2022-11-25 02:15:00', freq='15T'), 0.08041)]
Use these two points to draw a line on a candlestick gra... | Python: How to pre-calculate the slope of a line segment that will be on the graph in Matplotlib? | Given two points,
two_points = [(Timestamp('2022-11-25 01:15:00', freq='15T'), 0.08124),
(Timestamp('2022-11-25 02:15:00', freq='15T'), 0.08041)]
Use these two points to draw a line on a candlestick graph. For instance,
candlesticks graph with a line.
I want to know the slope of this green line before I ... | [
"As you have noted, the slope is going to be \"Price Change\" divided by \"Time Change\".\nThat said, you need first to decide what units you want the slope to be in.\nLet's say, for example, that the Price is in dollars. If so, do you want to know the slope in dollars per second? dollars per minute? dollars per... | [
0
] | [] | [] | [
"matplotlib",
"mplfinance",
"python",
"quantitative_finance"
] | stackoverflow_0074568051_matplotlib_mplfinance_python_quantitative_finance.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.