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:
Pyspark keep only most recent timestamps that meet condition
I have the following dataset:
id col1 timestamp
1 a 01.01.2022 9:00:00
1 b 01.01.2022 9:01:00
1 c 01.01.2022 9:02:00
1 a 01.01.2022 10:00:00
1 b 01.01.2022 10:01:00
1 d 01.01.2022 10:02:00
2 a 01.01.2022 12:00:... | Pyspark keep only most recent timestamps that meet condition | I have the following dataset:
id col1 timestamp
1 a 01.01.2022 9:00:00
1 b 01.01.2022 9:01:00
1 c 01.01.2022 9:02:00
1 a 01.01.2022 10:00:00
1 b 01.01.2022 10:01:00
1 d 01.01.2022 10:02:00
2 a 01.01.2022 12:00:00
2 b 01.01.2022 12:01:00
2 a 01.01.2022 13:00:00
2 ... | [
"spark.sql(\"set spark.sql.legacy.timeParserPolicy=LEGACY\")\n\n w = Window.partitionBy('id')\n( #column cum_a =1 when col1=a else cum_a=0. Once populated, calculate the cumulative sum of cum_a for every id ordered by timestamp\n df.withColumn('cum_a', sum(when(col('col1')=='a',1).otherwise(0)).over(w.orderBy(to_... | [
1
] | [] | [] | [
"group_by",
"pyspark",
"python"
] | stackoverflow_0074644247_group_by_pyspark_python.txt |
Q:
add slice of data from a dataframe to a time series dataframe based on multiple criteria
I have two Pandas dataframes. df1 is a time series with 6 columns of values, one of which is column 'name'. df2 is a list of rows each with a unique string in the 'name' column and a the same date in each row of the 'date' col... | add slice of data from a dataframe to a time series dataframe based on multiple criteria | I have two Pandas dataframes. df1 is a time series with 6 columns of values, one of which is column 'name'. df2 is a list of rows each with a unique string in the 'name' column and a the same date in each row of the 'date' column---all rows have the same date value from an observation that occurred on same date.
df1-->... | [
"try this:\ndf3 = pd.merge(df1,df2, how='left', left_on=['Date','name'], right_on=['Date','name'])\n\n",
"\ndf1 = df1.merge(df2, how='left', on=['Date', 'name']) # what this line does is it merges df1 and df2 based on the 'Date' and 'name' columns. The resulting df1 has the 'pick' column from df2 appended to it.\... | [
1,
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074648487_dataframe_pandas_python.txt |
Q:
problem with certain inputs in password checker
Recently, I have been building a password checker for a project I have been working on but for some reason certain inputs cause errors to occur and I cant figure out what it's from. If anyone can help that would be great as I have been searching for quite a while.
im... | problem with certain inputs in password checker | Recently, I have been building a password checker for a project I have been working on but for some reason certain inputs cause errors to occur and I cant figure out what it's from. If anyone can help that would be great as I have been searching for quite a while.
import re
exit = False
allowed_char = "abcdefghijklmnop... | [
"You are looking to see if 3 character extents in the password match 3 character rows from the keyboard using re.search:\nre.search(self.password[i:i+3], row1)\n\nBut that's the problem. If your password contains a regex control character, re will try to use it. In your example \"aSD7V^&*gS77+\", you'll try the seq... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074648485_python.txt |
Q:
Celery worker concurrency
I have made a scraper to scan around 150 links.
Each link has around 5k sub links to get info from.
I am using Celery to run the scraper in background and store data on a Django ORM. I use BeautifulSoup for scrap URL .
When i running the celery using this command
celery worker -A ... --c... | Celery worker concurrency | I have made a scraper to scan around 150 links.
Each link has around 5k sub links to get info from.
I am using Celery to run the scraper in background and store data on a Django ORM. I use BeautifulSoup for scrap URL .
When i running the celery using this command
celery worker -A ... --concurrency=50
everything workin... | [
"First of all that command will not start 50 workers, but 1 worker with 50 processes. I'd also recommend to just use as many processes as you have cores available. (Let's say 8 for the rest of my answer.)\nMy guess here is that the other processes are idle because you only perform one task. If you want to do concur... | [
4,
0
] | [] | [] | [
"celery",
"django",
"python"
] | stackoverflow_0047953643_celery_django_python.txt |
Q:
Calculating net wins for football teams
As part of a machine learning architecture I'm building I need to parallelise a certain calculation in pytorch. For simplicity I'm going state a modified version of the problem and use numpy so it's easier to understand.
Suppose I have a collection of football teams (say 10)... | Calculating net wins for football teams | As part of a machine learning architecture I'm building I need to parallelise a certain calculation in pytorch. For simplicity I'm going state a modified version of the problem and use numpy so it's easier to understand.
Suppose I have a collection of football teams (say 10) and they play a collection of matches (say 2... | [
"For anyone who sees this, I figured out a solution using 'scatter' in pytorch however it is a bit ad-hoc. Here is the equivalent code for numpy.\noutcome = np.concatenate((outcome, -outcome), axis=1)\ntemp = np.put_along_axis(np.zeros((20, 10)), match, outcomes, 1)\nscores = np.sum(temp, axis=0)\n\n"
] | [
0
] | [] | [] | [
"data_science",
"machine_learning",
"numpy",
"python",
"pytorch"
] | stackoverflow_0074643176_data_science_machine_learning_numpy_python_pytorch.txt |
Q:
How to webscrape from a selected tab with an embedded table on a website?
I am trying to scrape data from https://www.onthesnow.com/alberta/lake-louise/historical-snowfall however the default script only shows the monthly totals and not the annual totals. There is a tab you have to select 'Annual' on the webpage t... | How to webscrape from a selected tab with an embedded table on a website? | I am trying to scrape data from https://www.onthesnow.com/alberta/lake-louise/historical-snowfall however the default script only shows the monthly totals and not the annual totals. There is a tab you have to select 'Annual' on the webpage to show the annual totals. website source code showing the table I can successfu... | [
"You can use the Json data embedded inside the HTML page to get the annual info:\nimport json\nimport requests\nimport pandas as pd\nfrom bs4 import BeautifulSoup\n\n\nurl = \"https://www.onthesnow.com/alberta/lake-louise/historical-snowfall\"\n\nsoup = BeautifulSoup(requests.get(url).content, \"html.parser\")\n\nd... | [
1,
1,
1
] | [] | [] | [
"beautifulsoup",
"python",
"web_scraping"
] | stackoverflow_0074648506_beautifulsoup_python_web_scraping.txt |
Q:
How to sort angles in the range 0 to +Pi to -Pi to 0 as a linear range?
I am trying to solve a problem of sorting angles in the range of 0 to +Pi radians and +Pi to -Pi to 0 radians as one continuous range. I know this might be difficult to understand. Let me quote an example below.
The following are examples of t... | How to sort angles in the range 0 to +Pi to -Pi to 0 as a linear range? | I am trying to solve a problem of sorting angles in the range of 0 to +Pi radians and +Pi to -Pi to 0 radians as one continuous range. I know this might be difficult to understand. Let me quote an example below.
The following are examples of the final range I would like to get after sorting a list of jumbled angles:
Ex... | [
"Create a custom compare function and pass it to sort/sorted using functools.cmp_to_key:\ndef angle_compare(a, b):\n def cmp(a, b):\n return (a > b) - (b > a)\n\n if (a < 0) == (b < 0): # both positive or both negative\n return cmp(a, b)\n return cmp(b, a)\n\n>>> Pi = 3.14\n>>> l1 = [Pi... | [
1
] | [] | [] | [
"angle",
"geometry",
"python",
"range",
"sorting"
] | stackoverflow_0074648516_angle_geometry_python_range_sorting.txt |
Q:
Pip error when trying to install zlib
I'm new to Python and programming and am having trouble installing zlib through pip, I keep having the issue below:
pip install zlib
Collecting zlib
Could not find a version that satisfies the requirement zlib (from versions: )
No matching distribution found for zlib
A:
zlib... | Pip error when trying to install zlib | I'm new to Python and programming and am having trouble installing zlib through pip, I keep having the issue below:
pip install zlib
Collecting zlib
Could not find a version that satisfies the requirement zlib (from versions: )
No matching distribution found for zlib
| [
"zlib is not a python package, you can try yum/apt-get install zlib-devel or yum/apt-get install zlib. \n",
"For Ubuntu:\n sudo apt-get install zlib1g-dev\n",
"On mac using homebrew:\nbrew install zlib\n\n"
] | [
3,
3,
0
] | [] | [] | [
"pip",
"python",
"zlib"
] | stackoverflow_0047403874_pip_python_zlib.txt |
Q:
How To Read a CSV File Using Pandas
I am having trouble running my code. I want to load the "Forest Fires" dataset by calling the pandas method read_csv() with the name of the csv file "forestfires.csv" (docs) and store the result in a variable forestfire_df.
The interpreter keeps throwing this error
name 'forestf... | How To Read a CSV File Using Pandas | I am having trouble running my code. I want to load the "Forest Fires" dataset by calling the pandas method read_csv() with the name of the csv file "forestfires.csv" (docs) and store the result in a variable forestfire_df.
The interpreter keeps throwing this error
name 'forestfire_df' is not defined".
Here is my code... | [
"forestfire_df will have to be defined before it is displayed, for example with a line like:\nforestfire_df = pd.read_csv(\"forestfires.csv\")\n\n"
] | [
0
] | [] | [] | [
"google_colaboratory",
"python"
] | stackoverflow_0074648703_google_colaboratory_python.txt |
Q:
How to retrieve Python list data from a separate HTML file using bottle
I am creating a web-based python program using the Bottle framework built into PythonAnywhere. I have an HTML file that gets information about restaurants in a given area using an API. In this file, I take the received data and set it to a lis... | How to retrieve Python list data from a separate HTML file using bottle | I am creating a web-based python program using the Bottle framework built into PythonAnywhere. I have an HTML file that gets information about restaurants in a given area using an API. In this file, I take the received data and set it to a list with the name y. This all works well inside this file however I am working ... | [
"Since HTML essentially forgets all of Python after it is initially executed I was unable to find an obvious way to transfer this data without using a database.\nWhat I resorted to instead was using HTML input element with type set to hidden to pass the necessary data to the next form and then retrieve it there usi... | [
0
] | [] | [] | [
"bottle",
"list",
"python",
"web_based"
] | stackoverflow_0074636492_bottle_list_python_web_based.txt |
Q:
Python - How to create dataFrame from this result
How to create a DataFrame from the result of this print?
for teste2 in Vagas:
on_click = teste2.get('onclick')
print(on_click)
print(on_click) returns me several of these strings below, I want to insert them into a csv file.
<input id="ctl00_ctl00_Conten... | Python - How to create dataFrame from this result | How to create a DataFrame from the result of this print?
for teste2 in Vagas:
on_click = teste2.get('onclick')
print(on_click)
print(on_click) returns me several of these strings below, I want to insert them into a csv file.
<input id="ctl00_ctl00_Content_Content_rpt_turno_4_ctl01_imb_vaga_1" name="ctl00$ctl... | [
"You don't need a dataframe\nwith open('test.csv', 'a') as f:\n for item in Vagas:\n on_click = teste2.get('onclick')\n f.write(on_click+'\\n')\n\nor with a dataframe:\ntemp=[]\nfor i in Vagas:\n on_click = teste2.get('onclick')\n temp.append(on_click)\n\ndf = pd.DataFrame(temp)\ndf.to_csv('t... | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python",
"selenium",
"web_scraping"
] | stackoverflow_0074648508_dataframe_pandas_python_selenium_web_scraping.txt |
Q:
Wrong inflection points
I want to come up with a plot that shows the inflection points of a curve as follows:
I have a somewhat similar curve and I want to compute somehow the inflection points by using python. My curve looks as follows:
I am using the following code to compute the inflection points:
def find_in... | Wrong inflection points | I want to come up with a plot that shows the inflection points of a curve as follows:
I have a somewhat similar curve and I want to compute somehow the inflection points by using python. My curve looks as follows:
I am using the following code to compute the inflection points:
def find_inflection_points(df, n=1):
... | [
"So, strictly speaking, inflection point is indeed a change of sign of curvature. Which, for a 3 times differenciable function, is a point at which there is a change of sign of the 2nd derivative (the second derivative is 0, and the third derivative is not).\nIn your case, since the data are very discrete (only 24 ... | [
1
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0074643194_numpy_python.txt |
Q:
How to fix ssl.SSLError: [SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:1056)?
I am trying to send an email with python, but it keeps saying ssl.SSLError: [SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:1056). Here is my code:
server = smtplib.SMTP_SSL('smtp.mail.com', 587)
server.login("somethi... | How to fix ssl.SSLError: [SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:1056)? | I am trying to send an email with python, but it keeps saying ssl.SSLError: [SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:1056). Here is my code:
server = smtplib.SMTP_SSL('smtp.mail.com', 587)
server.login("something0@mail.com", "password")
server.sendmail(
"something0@mail.com",
"something@mail.com",
"em... | [
"The port for SSL is 465 and not 587, however when I used SSL the mail arrived to the junk mail.\nFor me the thing that worked was to use TLS over regular SMTP instead of SMTP_SSL.\nNote that this is a secure method as TLS is also a cryptographic protocol (like SSL).\nimport smtplib, ssl\n\nport = 587 # For startt... | [
64,
1,
1,
0,
0
] | [] | [] | [
"python",
"smtplib",
"ssl"
] | stackoverflow_0057715289_python_smtplib_ssl.txt |
Q:
Using Python for data cleanup, looping over rows to find unique records
I have a file with about 2 million rows. On any given day, around 7,000 active rows should exist. The current SQL job is checking for active rows and inserting that data into a table (with a column for that specific date)
How can I use Python ... | Using Python for data cleanup, looping over rows to find unique records | I have a file with about 2 million rows. On any given day, around 7,000 active rows should exist. The current SQL job is checking for active rows and inserting that data into a table (with a column for that specific date)
How can I use Python to iterate over the rows using a date index, and if there is a change, that r... | [] | [] | [
"If the data is too big then you can read the CSV in chunks with the pandas library fairly easily.\nHere's a link to the documentation: https://pandas.pydata.org/docs/reference/api/pandas.read_csv.html\nAnd a stack overflow that shows how to do it: https://stackoverflow.com/a/25962187/4719158\nTo filter and process... | [
-1
] | [
"dataframe",
"python"
] | stackoverflow_0074648568_dataframe_python.txt |
Q:
Is it possible to iterate through dates on a PySpark data frame given a date range?
I am not sure if I am going the right way on this, but I am trying to see if it's possible to output multiple dates object such as dates_1, dates_2, dates_3 or even an array if that works that each has 7 days? so dates_1 = ("2022-0... | Is it possible to iterate through dates on a PySpark data frame given a date range? | I am not sure if I am going the right way on this, but I am trying to see if it's possible to output multiple dates object such as dates_1, dates_2, dates_3 or even an array if that works that each has 7 days? so dates_1 = ("2022-08-20", "2022-08-27") dates_2 = ("2022-08-28", "2022-09-04") dates_3 = ("2022-09-05", "... | [
"To output multiple date objects with ranges of 7 days, you can use a loop to generate the date ranges and then apply the same filtering logic to your DataFrame for each range. Here is an example of how you might do this:\nfrom pyspark.sql.functions import col, to_date, asc\nfrom pyspark.sql.types import TimestampT... | [
0
] | [] | [] | [
"apache_spark_sql",
"datetime",
"pyspark",
"python"
] | stackoverflow_0074648827_apache_spark_sql_datetime_pyspark_python.txt |
Q:
GTK+: How can I add a Gtk.CheckButton to a Gtk.FileChooserDialog?
I want to present a folder chooser to users, and allow them to specify whether that folder should be processed recursively. I tried
do_recursion = False
def enable_recurse(widget, data=None):
nonlocal do_recursion
do_recursi... | GTK+: How can I add a Gtk.CheckButton to a Gtk.FileChooserDialog? | I want to present a folder chooser to users, and allow them to specify whether that folder should be processed recursively. I tried
do_recursion = False
def enable_recurse(widget, data=None):
nonlocal do_recursion
do_recursion = widget.get_active()
choose_file_dialog = Gtk.FileChooserDialo... | [
"As noted above, an answer is to use set_extra_widget instead of add\n check_box_1 = Gtk.CheckButton(label=\"Recurse source directory\")\n check_box_1.connect(\"toggled\", enable_recurse)\n choose_file_dialog.set_extra_widget(check_box_1)\n\nBut I do not like the placement of the checkbox in th... | [
0
] | [] | [] | [
"gtk",
"python"
] | stackoverflow_0074648765_gtk_python.txt |
Q:
crop frames of a video using opencv
i want to crop each of the frames of this video and save all the cropped images to use them as input for a focus stacking software but my approach:
cap = cv2.VideoCapture(r"C:\Users\HP\Downloads\VID_20221128_112556.mp4")
ret, frames = cap.read()
count=0
for img in frames:
st... | crop frames of a video using opencv | i want to crop each of the frames of this video and save all the cropped images to use them as input for a focus stacking software but my approach:
cap = cv2.VideoCapture(r"C:\Users\HP\Downloads\VID_20221128_112556.mp4")
ret, frames = cap.read()
count=0
for img in frames:
stops.append(img)
cv2.imwrite("../stack... | [
"If you take the frames variable with for loop it will give you the image on the y-axis.if you use while loop and read the next frame, the code will work. You can try the example below.\ncap = cv2.VideoCapture(r\"C:\\Users\\HP\\Downloads\\VID_20221128_112556.mp4\")\nret, frame = cap.read()\ncount=0\nwhile(ret):\n ... | [
3
] | [] | [] | [
"image_processing",
"opencv",
"python",
"video_processing"
] | stackoverflow_0074648745_image_processing_opencv_python_video_processing.txt |
Q:
How do you calculate a satellite's position in GCRF from an RA/DEC measurement in Skyfield?
I have a measurement of the RA and Dec for an Earth orbiting satellite, as measured from a sensor on the Earth's surface. I'm trying to calculate the satellite's position vector in the GCRF reference frame (so a vector from... | How do you calculate a satellite's position in GCRF from an RA/DEC measurement in Skyfield? | I have a measurement of the RA and Dec for an Earth orbiting satellite, as measured from a sensor on the Earth's surface. I'm trying to calculate the satellite's position vector in the GCRF reference frame (so a vector from the centre of the earth).
Since the object is in earth orbit, I can't assume that the RA/Dec is ... | [
"I think I've found a workaround.\nsensor.at(t) + satellite\ndoes not work, but it looks like:\n-(-sensor.at(t)-satellite) does work, and gives the required GCRF vector for the satellite.\nThis seems a bit hacky though, surely there's a more 'correct' method. I won't mark this as the accepted answer just yet, but I... | [
2
] | [] | [] | [
"python",
"skyfield"
] | stackoverflow_0074646447_python_skyfield.txt |
Q:
Jupyter - widget to play audio with playhead on graph
Is there any Jupyter widget for visualizing audio synced with a playhead on a time-series plot?
I would like to visualize data derived from an audio sample (e.g. spectrogram and various computed signals), listening to the audio sample while seeing the playhead ... | Jupyter - widget to play audio with playhead on graph | Is there any Jupyter widget for visualizing audio synced with a playhead on a time-series plot?
I would like to visualize data derived from an audio sample (e.g. spectrogram and various computed signals), listening to the audio sample while seeing the playhead move across the plots.
I found this old gist https://gist.g... | [
"You can now :). It took me about 10 minutes to put together a demo using Jupyter proxy widget to load a wavesurfer control into a notebook. It works in Chrome but I haven't tested it anywhere else. It should work anywhere wavesurfer and Jupyter work.\nHere is a screenshot\n\nSee the pastable text from the notebo... | [
4,
0
] | [] | [] | [
"audio",
"jupyter",
"python",
"signal_processing",
"visualization"
] | stackoverflow_0059641390_audio_jupyter_python_signal_processing_visualization.txt |
Q:
Force array of arrays when using numpy genfromtext
Sample text input file:
35.6 45.1
21.2 34.1
30.3 29.3
When you use numpy.genfromtxt(input_file, delimiter=' '), it loads the text file as an array of arrays
[[35.6 45.1]
[21.2 34.1]
[30.3 29.3]]
If there is only one entry or row of data in the input file, then... | Force array of arrays when using numpy genfromtext | Sample text input file:
35.6 45.1
21.2 34.1
30.3 29.3
When you use numpy.genfromtxt(input_file, delimiter=' '), it loads the text file as an array of arrays
[[35.6 45.1]
[21.2 34.1]
[30.3 29.3]]
If there is only one entry or row of data in the input file, then it loads the input file as a 1d array
[35.6 45.1] inste... | [
"Use the ndmin argument (new in 1.23.0):\nnumpy.genfromtxt(input_file, ndmin=2)\n\nIf you're on a version before 1.23.0, you'll have to do something else. If you don't have missing data, you can use numpy.loadtxt, which supports ndmin since 1.16.0:\nnumpy.loadtxt(input_file, ndmin=2)\n\nOr if you know that your inp... | [
1
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0074648907_numpy_python.txt |
Q:
Python how to only accept numbers as a input
mark= eval(raw_input("What is your mark?"))
try:
int(mark)
except ValueError:
try:
float(mark)
except ValueError:
print "This is not a number"
So I need to make a python program that looks at your mark and gives you varying responses dependi... | Python how to only accept numbers as a input | mark= eval(raw_input("What is your mark?"))
try:
int(mark)
except ValueError:
try:
float(mark)
except ValueError:
print "This is not a number"
So I need to make a python program that looks at your mark and gives you varying responses depending on what it is.
However I also need to add a wa... | [
"remove eval and your code is correct:\nmark = raw_input(\"What is your mark?\")\ntry:\n int(mark)\nexcept ValueError:\n try:\n float(mark)\n except ValueError:\n print(\"This is not a number\")\n\nJust checking for a float will work fine:\ntry:\n float(mark)\nexcept ValueError:\n print... | [
10,
4,
0,
0,
0,
0
] | [
"Actually if you going to use eval() you have to define more things.\nacceptables=[1,2,3,4,5,6,7,8,9,0,\"+\",\"*\",\"/\",\"-\"]\ntry:\n mark= eval(int(raw_input(\"What is your mark?\")))\nexcept ValueError:\n print (\"It's not a number!\")\nif mark not in acceptables:\n print (\"You cant do anything but ar... | [
-1
] | [
"python",
"python_2.x"
] | stackoverflow_0027516093_python_python_2.x.txt |
Q:
How do I install pandas into visual studios code?
I want to read an excel csv file, and after researching, I realized I need to import pandas as pd. Is there a way to install it into the visual studio code? I have tried typing import pandas as pd, but it shows a red line. I'm still new to python.
Thank you
A:
As... | How do I install pandas into visual studios code? | I want to read an excel csv file, and after researching, I realized I need to import pandas as pd. Is there a way to install it into the visual studio code? I have tried typing import pandas as pd, but it shows a red line. I'm still new to python.
Thank you
| [
"As pandas is a Python library, you can install it using pip - the Python's package management system. If you are using Python 2 >=2.7.9 or Python 3 >=3.4, pip is already installed with your Python. Ensure that Python has been added to PATH\nThen, to install pandas, just simply do:\n$ pip install pandas\n\n",
"I ... | [
6,
6,
3,
3,
0,
0
] | [
"You need to start off by installing Anaconda in order to create an environment for Pandas; you can manage this environment with Anaconda.\nGo to your terminal then run conda create -n myenv python=3.9 pandas jupyter seaborn scikit-learn keras tensorflow. It will create environments for all of the libraries mention... | [
-1
] | [
"python",
"visual_studio_code"
] | stackoverflow_0067946868_python_visual_studio_code.txt |
Q:
Password Generator performance : Python vs Javascript (Google apps script)
I created a random code generator script via Google apps script. My goal is to generate 6000 uniques random codes (in spreadsheet) as fast as possible.
The following javascript code crashes with Google spreadsheet + apps script --> too long... | Password Generator performance : Python vs Javascript (Google apps script) | I created a random code generator script via Google apps script. My goal is to generate 6000 uniques random codes (in spreadsheet) as fast as possible.
The following javascript code crashes with Google spreadsheet + apps script --> too long to execute and the same code under python generates 20,000 random codes in less... | [
"Performance-wise, the main difference between the Apps Script and Python versions is that the Apps Script code logs about 20,000 values in the Apps Script console, which is slow, while the Python code outputs 1 value.\nThe Apps Script code has several syntactical and semantical errors, including:\n\nverify_unique(... | [
2,
1,
0
] | [] | [] | [
"algorithm",
"generator",
"google_apps_script",
"javascript",
"python"
] | stackoverflow_0074626387_algorithm_generator_google_apps_script_javascript_python.txt |
Q:
Selenium Python XML parsing
I need to parse XML with Selenium, but the XML is not a file, it is on the web.
Here is the site https://www.thetutorsdirectory.com/usa/sitemap/sitemap_l1.xml and I need to get all the links for example this one
<url>
<loc>https://www.thetutorsdirectory.com/usa/location/private-tutor-an... | Selenium Python XML parsing | I need to parse XML with Selenium, but the XML is not a file, it is on the web.
Here is the site https://www.thetutorsdirectory.com/usa/sitemap/sitemap_l1.xml and I need to get all the links for example this one
<url>
<loc>https://www.thetutorsdirectory.com/usa/location/private-tutor-anaheim</loc>
<changefreq>weekly</c... | [
"A solution with beautifulsoup:\nimport requests\nfrom bs4 import BeautifulSoup\n\nurl = \"https://www.thetutorsdirectory.com/usa/sitemap/sitemap_l1.xml\"\n\nheaders = {\n \"User-Agent\": \"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:107.0) Gecko/20100101 Firefox/107.0\"\n}\n\nsoup = BeautifulSoup(requests.get(ur... | [
1
] | [] | [] | [
"parsing",
"python",
"selenium",
"xml"
] | stackoverflow_0074648860_parsing_python_selenium_xml.txt |
Q:
Removing all non-numeric characters from string in Python
How do we remove all non-numeric characters from a string in Python?
A:
>>> import re
>>> re.sub("[^0-9]", "", "sdkjh987978asd098as0980a98sd")
'987978098098098'
A:
Not sure if this is the most efficient way, but:
>>> ''.join(c for c in "abc123def456" if... | Removing all non-numeric characters from string in Python | How do we remove all non-numeric characters from a string in Python?
| [
">>> import re\n>>> re.sub(\"[^0-9]\", \"\", \"sdkjh987978asd098as0980a98sd\")\n'987978098098098'\n\n",
"Not sure if this is the most efficient way, but:\n>>> ''.join(c for c in \"abc123def456\" if c.isdigit())\n'123456'\n\nThe ''.join part means to combine all the resulting characters together without any charac... | [
376,
127,
23,
18,
10,
8,
5,
2,
0
] | [] | [] | [
"numbers",
"python"
] | stackoverflow_0001249388_numbers_python.txt |
Q:
How to import a python function from a sibling folder
This question has been asked before. Even though I couldn't get an answer that solves this issue.
I have the following directory and subdirectories:
I have a function hello() in test1.py that I want to import in test2.py.
test1.py:
def hello():
print("hello"... | How to import a python function from a sibling folder | This question has been asked before. Even though I couldn't get an answer that solves this issue.
I have the following directory and subdirectories:
I have a function hello() in test1.py that I want to import in test2.py.
test1.py:
def hello():
print("hello")
test2.py:
import demoA.test1 as test1
test1.hello()
Ou... | [
"You need to add demoA to the list of paths used for import.\nimport sys\nsys.path.append('..')\n\nimport demoA.test1 as test1\n\ntest1.hello()\n\n"
] | [
0
] | [] | [] | [
"import",
"python"
] | stackoverflow_0074647907_import_python.txt |
Q:
How do I Check for an item in multiple lists and keep it simplified?
I'm doing connect 4 for the semester final in my high school coding class. I've got everything to work, but I cannot get the game to recognize when there is 4 in a row. I don't even know where to start. I should mention that turtles are a require... | How do I Check for an item in multiple lists and keep it simplified? | I'm doing connect 4 for the semester final in my high school coding class. I've got everything to work, but I cannot get the game to recognize when there is 4 in a row. I don't even know where to start. I should mention that turtles are a requirement for the assignment. all my checkers are turtles.
note that I refer to... | [] | [] | [
"Instead of writing thousands of lines of code for all the possible permutations, better approach would be to use recursive functions.\nFor example you give your function your 2d array and then the function recursively moves till the end of line and then into the next line checking if checker is placed on the curre... | [
-1
] | [
"multidimensional_array",
"python",
"python_3.x",
"python_turtle"
] | stackoverflow_0074648896_multidimensional_array_python_python_3.x_python_turtle.txt |
Q:
Numpy array with different mean and standard deviation per column
i would like to get an numpy array , shape 1000 row and 2 column.
1st column will contain - Gaussian distributed variables with standard deviation 2 and mean 1.
2nd column will contain Gaussian distributed variables with mean -1 and standard devia... | Numpy array with different mean and standard deviation per column | i would like to get an numpy array , shape 1000 row and 2 column.
1st column will contain - Gaussian distributed variables with standard deviation 2 and mean 1.
2nd column will contain Gaussian distributed variables with mean -1 and standard deviation 0.5.
How to create the array using define value of mean and std?
| [
"You can use numpy's random generators.\nimport numpy as np\n\n# as per kwinkunks suggestion\nrng = np.random.default_rng()\n\narr1 = rng.normal(1, 2, 1000).reshape(1000, 1)\narr2 = rng.normal(-1, 0.5, 1000).reshape(1000, 1)\n\narr1[:5]\n\narray([[-2.8428678 ],\n [ 2.52213097],\n [-0.98329961],\n ... | [
1,
1,
0
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0074646236_numpy_python.txt |
Q:
Pandas KeyError: value not in index
I have the following code,
df = pd.read_csv(CsvFileName)
p = df.pivot_table(index=['Hour'], columns='DOW', values='Changes', aggfunc=np.mean).round(0)
p.fillna(0, inplace=True)
p[["1Sun", "2Mon", "3Tue", "4Wed", "5Thu", "6Fri", "7Sat"]] = p[["1Sun", "2Mon", "3Tue", "4Wed", "5... | Pandas KeyError: value not in index | I have the following code,
df = pd.read_csv(CsvFileName)
p = df.pivot_table(index=['Hour'], columns='DOW', values='Changes', aggfunc=np.mean).round(0)
p.fillna(0, inplace=True)
p[["1Sun", "2Mon", "3Tue", "4Wed", "5Thu", "6Fri", "7Sat"]] = p[["1Sun", "2Mon", "3Tue", "4Wed", "5Thu", "6Fri", "7Sat"]].astype(int)
It ha... | [
"Use reindex to get all columns you need. It'll preserve the ones that are already there and put in empty columns otherwise.\np = p.reindex(columns=['1Sun', '2Mon', '3Tue', '4Wed', '5Thu', '6Fri', '7Sat'])\n\nSo, your entire code example should look like this:\ndf = pd.read_csv(CsvFileName)\n\np = df.pivot_table(i... | [
46,
28,
2,
0
] | [
"I had a some extra space in csv file ahead of Thermal_Rating\nso i just removed the space and saved the csv file, rerun the df, and it worked\n"
] | [
-1
] | [
"dataframe",
"indexing",
"pandas",
"python"
] | stackoverflow_0038462920_dataframe_indexing_pandas_python.txt |
Q:
How to add/append new lists to an already existing zip?
I am programming a grocery list by using dictionaries and functions (i am a beginner) and all of my codes are not here. I have made a zip av 2 lists (an integer asking about the price and one string asking about the item the user want to add). I am using a wh... | How to add/append new lists to an already existing zip? | I am programming a grocery list by using dictionaries and functions (i am a beginner) and all of my codes are not here. I have made a zip av 2 lists (an integer asking about the price and one string asking about the item the user want to add). I am using a while loop that allow the user to add items and their prices to... | [
"zip isn't supposed to be used like that. zip returns a one-off iterator, not designed to be useful beyond the context of a single loop. If you want to loop over the items of two lists (or other iterables) together, you call zip and iterate over the iterator it gives you. If you want to iterate again, you call zip ... | [
2
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074649191_python_python_3.x.txt |
Q:
Error happend when import torch (pytorch)
Try to use pytorch, when I do
import torch
---------------------------------------------------------------------------
OSError Traceback (most recent call last)
<ipython-input-2-eb42ca6e4af3> in <module>
----> 1 import torch
C:\Big_Data_a... | Error happend when import torch (pytorch) | Try to use pytorch, when I do
import torch
---------------------------------------------------------------------------
OSError Traceback (most recent call last)
<ipython-input-2-eb42ca6e4af3> in <module>
----> 1 import torch
C:\Big_Data_app\Anaconda3\lib\site-packages\torch\__init__.p... | [
"I solved the problem.\nJust reinstall your Anaconda.\n!!Warning!!: you will lose your lib.\nReferring solution:\nProblem with Torch 1.11\n",
"The version may not be exactly as same as yours, but maybe this question asked on 2020-09-04 helps.\n",
"My problem was solved by creating a new conda environment and in... | [
1,
0,
0,
0
] | [] | [] | [
"deep_learning",
"python",
"pytorch",
"windows"
] | stackoverflow_0073098560_deep_learning_python_pytorch_windows.txt |
Q:
Execute dynamically created function in another scope
I have got dynamically created funcion which accesses variable from another scope. For example:
def dynamically_generated_function():
print(x) # x is not defined in scope visible to this function
I would like to execute that funcion, but variable x comes ... | Execute dynamically created function in another scope | I have got dynamically created funcion which accesses variable from another scope. For example:
def dynamically_generated_function():
print(x) # x is not defined in scope visible to this function
I would like to execute that funcion, but variable x comes from diffrent place. I have got access to scope of that pla... | [
"I have managed to solve the problem via different approach (executing code directLy instead of function creation from it). Thanks @chepner for inspiration!\n"
] | [
0
] | [] | [] | [
"code_generation",
"code_inspection",
"python"
] | stackoverflow_0074631814_code_generation_code_inspection_python.txt |
Q:
How can i get refreshed value of flask variable with JS and show in HTML template every 30 seconds?
This is a parking app which refresh the available parking slots every 30 seconds WITHOUT refreshing page.
This is my .py with the route and render template
@views.route('/')
def home():
while True:
try:
... | How can i get refreshed value of flask variable with JS and show in HTML template every 30 seconds? | This is a parking app which refresh the available parking slots every 30 seconds WITHOUT refreshing page.
This is my .py with the route and render template
@views.route('/')
def home():
while True:
try:
token=getToken()
if(token!='null' or token!=''):
plazas=getInfo(t... | [
"Your problem seems to be updating the rendered DOM periodically.\nYou'll probably need JavaScript to handle that.\nThere are plenty of frameworks that can enable this efficiently.\nConsider looking for popular solutions, like ReactJS or VueJS.\n",
"A simple solution would be to get the data by fetching it from j... | [
0,
0
] | [] | [] | [
"flask",
"html",
"javascript",
"jinja2",
"python"
] | stackoverflow_0074641706_flask_html_javascript_jinja2_python.txt |
Q:
"import tensorflow" results in error: No module named 'tensorflow.python.eager.polymorphic_function' (Python in Jupyter Lab)
Python 3.9.12.
Windows 10.
jupyterlab 3.3.2.
Import tensorflow
When I try to import Tensorflow, I get the following 'tensorflow.python.eager.polymorphic_function' error.
-------------------... | "import tensorflow" results in error: No module named 'tensorflow.python.eager.polymorphic_function' (Python in Jupyter Lab) | Python 3.9.12.
Windows 10.
jupyterlab 3.3.2.
Import tensorflow
When I try to import Tensorflow, I get the following 'tensorflow.python.eager.polymorphic_function' error.
---------------------------------------------------------------------------
ModuleNotFoundError Traceback (most recent call las... | [
"To answer my own question:\nI created a conda environment and installed an older version of Python (3.7) in it and that seems to have fixed the problem.\nI found these links to be helpful:\nHow to downgrade the Python Version from 3.8 to 3.7 on windows?\nconda install downgrade python version\nJupyter Notebook - C... | [
0
] | [] | [] | [
"jupyter",
"object_detection_api",
"python",
"python_3.x",
"tensorflow"
] | stackoverflow_0074635830_jupyter_object_detection_api_python_python_3.x_tensorflow.txt |
Q:
Why are attributes of a tk object being 'retroactively' changed?
Personal project, I'm thinking it would be cool to be able to create a one to has many relationship between windows, so when a "parent" window is closed all of its "children" are also also closed.
So here is the window class that creates new windows ... | Why are attributes of a tk object being 'retroactively' changed? | Personal project, I'm thinking it would be cool to be able to create a one to has many relationship between windows, so when a "parent" window is closed all of its "children" are also also closed.
So here is the window class that creates new windows via the Tk() function:
from tkinter import *
class Window:
def __... | [
"The reason for the odd behavior is that in create you're redefining self.window to be the newly created window. It no longer represents the original window. So, when you print the title of what you think is the main window you actually are printing the title of the child window.\nIf you want to create a child of a... | [
0
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0074648032_python_tkinter.txt |
Q:
Recursion on odd to be front, even in the back
I am new to python.
I am writing a recusion to returns a COPY of the list with odds at front, evens in the back.
For example: [3,4,5,6] returns [3,5,6,4].
How should I break the problem into small pieces.
def oddsevens(thelist):
if thelist == []:
return []... | Recursion on odd to be front, even in the back | I am new to python.
I am writing a recusion to returns a COPY of the list with odds at front, evens in the back.
For example: [3,4,5,6] returns [3,5,6,4].
How should I break the problem into small pieces.
def oddsevens(thelist):
if thelist == []:
return []
if thelist[0] % 2 == 0:
| [
"try this:\nif thelist == []:\n return []\nif thelist[0] % 2 == 0:\n return oddsevens(thelist[1:]) + thelist[:1]\nelse:\n return thelist[:1] + oddsevens(thelist[1:])\n\nLet me know if you have any further questions!\n"
] | [
2
] | [] | [] | [
"python",
"recursion"
] | stackoverflow_0074649317_python_recursion.txt |
Q:
Tkinter: get value from entry with button and store in variable
Say that we have an entry_object, a button button_object and a global variable called score.
I want to update the score when the button is clicked and the entry has a value. I tried looking at this answer but I need something slightly different. The m... | Tkinter: get value from entry with button and store in variable | Say that we have an entry_object, a button button_object and a global variable called score.
I want to update the score when the button is clicked and the entry has a value. I tried looking at this answer but I need something slightly different. The main difference is the storing of the value in a variable.
I have a fu... | [
"#If score is a global variable then:\nscore = 0\nroot = tk.Tk()\nroot.geometry('900x700+50+50')\nentry_object = tk.Entry(root, width=40)\nentry_object.pack()\n\ndef increment():\n global score\n score += 1\n\nbutton_object = tk.Button(root, text='submit', command=increment() )\nroot.mainloop()\n\n#If it's an... | [
0
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0071945773_python_tkinter.txt |
Q:
Python pip Install failing with ModuleNotFoundError: No module named 'pyexpat' error
Complete Docker file: https://github.com/docker-library/python/blob/master/3.8/bullseye/Dockerfile
Docker file :
'''
ENV PYTHON_PIP_VERSION 22.0.4
#https://github.com/docker-library/python/issues/365
ENV PYTHON_SETUPTOOLS_VERSION ... | Python pip Install failing with ModuleNotFoundError: No module named 'pyexpat' error | Complete Docker file: https://github.com/docker-library/python/blob/master/3.8/bullseye/Dockerfile
Docker file :
'''
ENV PYTHON_PIP_VERSION 22.0.4
#https://github.com/docker-library/python/issues/365
ENV PYTHON_SETUPTOOLS_VERSION 57.5.0
#https://github.com/pypa/get-pip
ENV PYTHON_GET_PIP_URL https://github.com/pypa/get... | [
"You need to install expat-dev package before running get-pip.py\nRUN \\\n set -eu; \\\n apk update --no-cache; \\\n apk add --no-cache \\\n expat-dev \\\n ;\n\n"
] | [
0
] | [] | [] | [
"pip",
"python",
"python_3.x"
] | stackoverflow_0073332749_pip_python_python_3.x.txt |
Q:
How to write to a file from various places in the code in a pythonic and performant way
When writing to a file in python, you should typically use the using structure in order to have the file closed after writing, like so:
with open("myfile.txt", "a") as file1:
file1.write("Hello \n")
But if I, during the e... | How to write to a file from various places in the code in a pythonic and performant way | When writing to a file in python, you should typically use the using structure in order to have the file closed after writing, like so:
with open("myfile.txt", "a") as file1:
file1.write("Hello \n")
But if I, during the execution of my script, wants to write to the same file from different places in the code, I m... | [
"You can have your with statement early in your code and have all the other functions that use the file (and probably many that don't use the file but are called in between the ones that do) indented from it and pass the file to them.\nThis may not be wonderful to refactor things to this given the current code and ... | [
2,
1,
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074510331_python_python_3.x.txt |
Q:
Retry if status_code is 503
def verify_app_log_cur_day2(self, anypoint_monitoring, organization_id, int, applist, access_token):
headers = {"Authorization": f"Bearer {access_token}"}
payload = {}
log_list = []
for item in applist:
url = f"{anypoint_monitoring}/organizations/{organization_id... | Retry if status_code is 503 | def verify_app_log_cur_day2(self, anypoint_monitoring, organization_id, int, applist, access_token):
headers = {"Authorization": f"Bearer {access_token}"}
payload = {}
log_list = []
for item in applist:
url = f"{anypoint_monitoring}/organizations/{organization_id}/environments/{int}/applications... | [
"Simply do it this way\ndef verify_app_log_cur_day2(self, anypoint_monitoring, organization_id, int, applist, access_token):\n headers = {\"Authorization\": f\"Bearer {access_token}\"}\n payload = {}\n log_list = []\n for item in applist:\n url = f\"{anypoint_monitoring}/organizations/{organizati... | [
0
] | [] | [] | [
"http_status_code_503",
"python",
"python_3.x",
"rest"
] | stackoverflow_0074648886_http_status_code_503_python_python_3.x_rest.txt |
Q:
Python: Pandas pd.read_excel giving ImportError: Install xlrd >= 0.9.0 for Excel support
I am trying to read a .xlsx with pandas, but get the follwing error:
data = pd.read_excel(low_memory=False, io="DataAnalysis1/temp1.xlsx").fillna(value=0)
Traceback (most recent call last):
File "/Users/Vineeth/PycharmProj... | Python: Pandas pd.read_excel giving ImportError: Install xlrd >= 0.9.0 for Excel support | I am trying to read a .xlsx with pandas, but get the follwing error:
data = pd.read_excel(low_memory=False, io="DataAnalysis1/temp1.xlsx").fillna(value=0)
Traceback (most recent call last):
File "/Users/Vineeth/PycharmProjects/DataAnalysis1/try1.py", line 9, in <module>
data = pd.read_excel(low_memory=False, io... | [
"As @COLDSPEED so eloquently pointed out the error explicitly tells you to install xlrd.\npip install xlrd\n\nAnd you will be good to go.\n",
"Since December 2020 xlrd no longer supports xlsx-Files as explained in the official changelog. You can use openpyxl instead:\npip install openpyxl\n\nAnd in your python-fi... | [
150,
110,
37,
9,
7,
6,
3,
2,
2,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0
] | [] | [] | [
"excel",
"pandas",
"python",
"python_2.7"
] | stackoverflow_0048066517_excel_pandas_python_python_2.7.txt |
Q:
Load data from MySQL to BigQuery using Dataflow
I want to load data from MySQL to BigQuery using Cloud Dataflow. Anyone can share article or work experience about load data from MySQL to BigQuery using Cloud Dataflow with Python language?
Thank you
A:
You can use apache_beam.io.jdbc to read from your MySQL datab... | Load data from MySQL to BigQuery using Dataflow | I want to load data from MySQL to BigQuery using Cloud Dataflow. Anyone can share article or work experience about load data from MySQL to BigQuery using Cloud Dataflow with Python language?
Thank you
| [
"You can use apache_beam.io.jdbc to read from your MySQL database, and the BigQuery I/O to write on BigQuery.\nBeam knowledge is expected, so I recommend looking at Apache Beam Programming Guide first.\nIf you are looking for something pre-built, we have the JDBC to BigQuery Google-provided template, which is open-... | [
1,
0
] | [] | [] | [
"etl",
"google_bigquery",
"google_cloud_dataflow",
"mysql",
"python"
] | stackoverflow_0074611456_etl_google_bigquery_google_cloud_dataflow_mysql_python.txt |
Q:
What is the faster method?
Python:
I have to use the length of a list which is the value for a key in a dictionary. I have to use this value in FOR loop. Is it better to fetch the length of the list associated with the key every time or fetch the length from a different dictionary which has the same keys?
I am usi... | What is the faster method? | Python:
I have to use the length of a list which is the value for a key in a dictionary. I have to use this value in FOR loop. Is it better to fetch the length of the list associated with the key every time or fetch the length from a different dictionary which has the same keys?
I am using len() in the for loop as of n... | [
"len() is very fast - it runs in contant time (see Cost of len() function) so I would not build a new data structure just to cache its answer. Just use it each time you need it.\nBuilding a whole extra data structure, that would definitely be using more resources, and most likely slower. Just make sure you write yo... | [
0
] | [] | [] | [
"built_in",
"dictionary",
"for_loop",
"list",
"python"
] | stackoverflow_0074649402_built_in_dictionary_for_loop_list_python.txt |
Q:
TypeError: 'dict_keys' object is not subscriptable
I have this code that errors out in python3:
self.instance_id = get_instance_metadata(data='meta-data/instance-id').keys()[0]
TypeError: 'dict_keys' object is not subscriptable
I changed my code and I get different error (I guess I need more experience):
self.in... | TypeError: 'dict_keys' object is not subscriptable | I have this code that errors out in python3:
self.instance_id = get_instance_metadata(data='meta-data/instance-id').keys()[0]
TypeError: 'dict_keys' object is not subscriptable
I changed my code and I get different error (I guess I need more experience):
self.instance_id = get_instance_metadata(list(data='meta-data/i... | [
".keys() is a set-like view, not a sequence, and you can only index sequences.\nIf you just want the first key, you can manually create an iterator for the dict (with iter) and advance it once (with next):\nself.instance_id = next(iter(get_instance_metadata(data='meta-data/instance-id')))\n\nYour second attempt was... | [
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074649481_python_python_3.x.txt |
Q:
How to recreate tweepy OAuth2UserHandler across web requests
With OAuth2UserHandler included in the tweepy package, if you generate an authorization URL and later want to retrieve an OAuth2 bearer token, it only works if you reuse the exact OAuth2UserHandler() in memory.
Given an OAuth2UserHandler like this:
from ... | How to recreate tweepy OAuth2UserHandler across web requests | With OAuth2UserHandler included in the tweepy package, if you generate an authorization URL and later want to retrieve an OAuth2 bearer token, it only works if you reuse the exact OAuth2UserHandler() in memory.
Given an OAuth2UserHandler like this:
from tweepy import OAuth2UserHandler
def _oauth2_handler(callback_url:... | [
"My solution was to reimplement OAuth2UserHandler, exposing code_verifier and allowing the caller to store it and provide it back to the handler later.\nExample implementation (fork of tweepy's implementation):\nimport tweepy\nfrom oauthlib.oauth2 import OAuth2Error\nfrom requests.auth import HTTPBasicAuth\nfrom re... | [
0
] | [] | [] | [
"oauth_2.0",
"python",
"tweepy",
"twitter_oauth"
] | stackoverflow_0074649514_oauth_2.0_python_tweepy_twitter_oauth.txt |
Q:
6.13 LAB: Filter and sort a list
Write a program that gets a list of integers from input, and outputs non-negative integers in ascending order (lowest to highest).
Example: If the input is:
10 -7 4 39 -6 12 2
the output is:
2 4 10 12 39
My code that I came up with looks like this:
user_input = input()
numbers = us... | 6.13 LAB: Filter and sort a list | Write a program that gets a list of integers from input, and outputs non-negative integers in ascending order (lowest to highest).
Example: If the input is:
10 -7 4 39 -6 12 2
the output is:
2 4 10 12 39
My code that I came up with looks like this:
user_input = input()
numbers = user_input.split()
nums = []
for numbe... | [
"for item in nums:\n if int(item) < 0:\n nums.remove(item)\n\nproblem is probbably here, since you iterate thru a list for which you remove elements in the iterations of the for el in list loop.\nYou should just use list comprenhension to copy positive integers to a new list and return it.\nSo the return ... | [
0
] | [
"nums.sort() \nfor item in nums:\n if int(item) >= 0:\n break\n nums.remove(item)\nprint(*nums)\n\niterate only through -ve no. and remove them.\n"
] | [
-1
] | [
"filter",
"list",
"python",
"python_3.x",
"sorting"
] | stackoverflow_0074649068_filter_list_python_python_3.x_sorting.txt |
Q:
list of all docker status types
Where can I get a list of all the docker status types? e.g. Up, Exited, Created.
docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
f0771636c8ab registry:2 "/entrypoint.sh /etc…" 25 hours... | list of all docker status types | Where can I get a list of all the docker status types? e.g. Up, Exited, Created.
docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
f0771636c8ab registry:2 "/entrypoint.sh /etc…" 25 hours ago Up 3 hours 0.0.0.0:5000->500... | [
"In the Docker HTTP API, the Inspect a Container API call (GET /containers/{id}/json) includes a Stats field with OpenAPI type ContainerState. That contains a field Status. Its possible values are \"created\" \"running\" \"paused\" \"restarting\" \"removing\" \"exited\" \"dead\"\nThe higher-level Docker SDKs and ... | [
1
] | [] | [] | [
"docker",
"python"
] | stackoverflow_0074648983_docker_python.txt |
Q:
Retrying connection Paramiko - Python
Wrote a function that tries to reconnect to SSH when a disconnect happens. Basically expanded my existing function that simply saved the images, which works fine. The code runs but does not work to re-establish connectivity. Any help would be appreciated.
def get_image_id_and_... | Retrying connection Paramiko - Python | Wrote a function that tries to reconnect to SSH when a disconnect happens. Basically expanded my existing function that simply saved the images, which works fine. The code runs but does not work to re-establish connectivity. Any help would be appreciated.
def get_image_id_and_upload_folder_of_images(db_name, table_name... | [
"Your code never calls client.connect(). In fact it doesn't interact with any paramiko module at all inside the while loop.\n"
] | [
0
] | [] | [] | [
"paramiko",
"python",
"python_3.x"
] | stackoverflow_0071135803_paramiko_python_python_3.x.txt |
Q:
How to get Spyder to open python scripts (.py files) directly from Windows Explorer
I have recently installed the Anaconda distribution on Windows 7 (Anaconda 3-2.4.0-Windows-x86_64). Unlike IDLE, I can't right-click and open a py file in the Spyder IDE. I will have to open Spyder first and then navigate to the fi... | How to get Spyder to open python scripts (.py files) directly from Windows Explorer | I have recently installed the Anaconda distribution on Windows 7 (Anaconda 3-2.4.0-Windows-x86_64). Unlike IDLE, I can't right-click and open a py file in the Spyder IDE. I will have to open Spyder first and then navigate to the file or drag and drop it in the editor. Is there any way to open the file in the editor dir... | [
"With the current version of Anaconda (4.1.0) you can simply right-click on a python script in Windows File Explorer and choose \"Open with\". The first time you do this you need to select \"Choose default program\" and then browse to spyder.exe in the Script directory in your Anaconda installation. Also make sure ... | [
13,
6,
6,
2,
2,
1,
1,
1,
0,
0,
0
] | [] | [] | [
"ide",
"python",
"spyder",
"windows"
] | stackoverflow_0033817046_ide_python_spyder_windows.txt |
Q:
How do I get the position of my python flet window?
I've been working with the python flet package for a while and I'd like to know how to get my window's position. Does anyone know anything?
I googled but found nothing.
A:
I haven't used this package before, but looking at the docs it seems that window_top and ... | How do I get the position of my python flet window? | I've been working with the python flet package for a while and I'd like to know how to get my window's position. Does anyone know anything?
I googled but found nothing.
| [
"I haven't used this package before, but looking at the docs it seems that window_top and window_left on the root Page instance are what you're after (assuming this is a desktop app). See relevant docs here: https://flet.dev/docs/controls/page#window_top.\n"
] | [
0
] | [] | [] | [
"desktop_application",
"flutter",
"position",
"python"
] | stackoverflow_0074605877_desktop_application_flutter_position_python.txt |
Q:
python text conversion into Pig Latin
I need a python program for converting an input sentence into Pig Latin which has 2 rules:
If a word begins with a consonant all consonants before the first vowel are moved to the end of the word and the letters "ay" are then added to the end. e.g. "coin" becomes "oincay" and... | python text conversion into Pig Latin | I need a python program for converting an input sentence into Pig Latin which has 2 rules:
If a word begins with a consonant all consonants before the first vowel are moved to the end of the word and the letters "ay" are then added to the end. e.g. "coin" becomes "oincay" and "flute" becomes "uteflay".
If a word begin... | [
"We can try using a regex replacement with a callback function:\ninp = \"coin flute egg oak\"\noutput = re.sub(r'\\w+', lambda m: re.sub(r'([b-df-hj-np-tv-z]+)(\\w+)', r'\\2\\1ay', m.group()) if not re.search(r'^[AEIOUaeiou]', m.group()) else m.group() + 'yay', inp)\nprint(output) # oincay uteflay eggyay oakyay\n\... | [
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074636955_python.txt |
Q:
How to exchange authorization code for access token Twitter API?
I am developing an app that will read some tweets stats of my company. I want to let all the employees to connect with their twitter accounts.
I am facing the following problem: I am stuck at the "Exchange authorization code for access token".
The re... | How to exchange authorization code for access token Twitter API? | I am developing an app that will read some tweets stats of my company. I want to let all the employees to connect with their twitter accounts.
I am facing the following problem: I am stuck at the "Exchange authorization code for access token".
The response url after Authorize is: https://example/v1/browser-callback?sta... | [
"You need first to know the type of flow you are trying to implement\nFirst you need to know what is the grant type of your client_id in the twitter side, i see in the callback there is code that means you are in normal authorization code or Authorization Code Flow with Proof Key for Code (PKCE), to know that check... | [
0,
0
] | [] | [] | [
"oauth_2.0",
"python",
"twitter",
"twitter_oauth",
"twitterapi_python"
] | stackoverflow_0071465525_oauth_2.0_python_twitter_twitter_oauth_twitterapi_python.txt |
Q:
Add Python Script as a file to AWS SSM Document (YAML)
I'm trying to write a script for a SystemsManager Automation document and would like to keep the Python code in a seperate file so it's easy to invoke on my local machine. For complex scripts they can also be tested using a tool such as unittest.
Example YAML ... | Add Python Script as a file to AWS SSM Document (YAML) | I'm trying to write a script for a SystemsManager Automation document and would like to keep the Python code in a seperate file so it's easy to invoke on my local machine. For complex scripts they can also be tested using a tool such as unittest.
Example YAML syntax from my SSM Automation:
mainSteps:
- name: RunTestS... | [
"I noticed my plan output had \"'s around the code. So I tried a multiline string in Python \"\"\" and it continued to fail. Bearing in mind I assumed SSM was smart enough to strip quotes if it doesn't want them.\nAnyway, the mistake was adding quotes around the template variable:\n# Mistake\n Script: |-\n ... | [
0
] | [] | [] | [
"aws_ssm",
"python",
"terraform"
] | stackoverflow_0074648609_aws_ssm_python_terraform.txt |
Q:
Python RE, problem with optional match groups
My apologies if this has been asked before. I am parsing some law numbers from the California penal code so they can be run through an existing database to return a plain-language title of the law. For example:
PC 182(A)(1); PC 25400(A)(1); PC 25850(C)(6); PC 32310; VC... | Python RE, problem with optional match groups | My apologies if this has been asked before. I am parsing some law numbers from the California penal code so they can be run through an existing database to return a plain-language title of the law. For example:
PC 182(A)(1); PC 25400(A)(1); PC 25850(C)(6); PC 32310; VC 12500(A); VC 22517; VC 23103(A)
Each would be spli... | [
"The problem is in how you are applying the ? to make each of the subsections optional. A ? applies to just the term immediately preceding it. In your case, this is just the closing parentheses for each subsection Because of this, you are requiring the opening parentheses and the number or letter unconditionally ... | [
0
] | [] | [] | [
"match",
"option_type",
"python",
"python_re"
] | stackoverflow_0074649500_match_option_type_python_python_re.txt |
Q:
2d convolution using python and numpy
I am trying to perform a 2d convolution in python using numpy
I have a 2d array as follows with kernel H_r for the rows and H_c for the columns
data = np.zeros((nr, nc), dtype=np.float32)
#fill array with some data here then convolve
for r in range(nr):
data[r,:] = np.co... | 2d convolution using python and numpy | I am trying to perform a 2d convolution in python using numpy
I have a 2d array as follows with kernel H_r for the rows and H_c for the columns
data = np.zeros((nr, nc), dtype=np.float32)
#fill array with some data here then convolve
for r in range(nr):
data[r,:] = np.convolve(data[r,:], H_r, 'same')
for c in ra... | [
"Maybe it is not the most optimized solution, but this is an implementation I used before with numpy library for Python:\ndef convolution2d(image, kernel, bias):\n m, n = kernel.shape\n if (m == n):\n y, x = image.shape\n y = y - m + 1\n x = x - m + 1\n new_image = np.zeros((y,x))\... | [
25,
6,
5,
2,
2,
1,
0,
0,
0,
0
] | [
"This code incorrect:\nfor r in range(nr):\n data[r,:] = np.convolve(data[r,:], H_r, 'same')\n\nfor c in range(nc):\n data[:,c] = np.convolve(data[:,c], H_c, 'same')\n\nSee Nussbaumer transformation from multidimentional convolution to one dimentional.\n"
] | [
-2
] | [
"convolution",
"numpy",
"python"
] | stackoverflow_0002448015_convolution_numpy_python.txt |
Q:
Add data in the next empty row in python pandas
I'm making a small and simple program that put one name under another in an excel file, and i dont know how i can get the next empty row
I have this excel table:
Name
Carl
And i'm making a program to add new names. Here is the function:
def modifyexcel ():
... | Add data in the next empty row in python pandas | I'm making a small and simple program that put one name under another in an excel file, and i dont know how i can get the next empty row
I have this excel table:
Name
Carl
And i'm making a program to add new names. Here is the function:
def modifyexcel ():
book = openpyxl.load_workbook (r'C:\User... | [
"you can just use google colab to modify your excel !\nyou can mount your csv or excel to google drive or just load the csv to the side bar!\nand copy path and paste it to your pandas read_csv or (read_excel is the same thing)!\nhttps://colab.research.google.com/\nfrom google.colab import files\nimport pandas as pd... | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074649333_pandas_python.txt |
Q:
How to plot a differentiable function using matplotlib?
I am tryinig to plot the differential function y' = 3t-sqrt(y), but my code doesn't produce any graph output. Can someone point out my mistake please?
import sympy.plotting as sym_plot
def func(y, t):
return 3*t - np.sqrt(y)
# time points
t = np.linspac... | How to plot a differentiable function using matplotlib? | I am tryinig to plot the differential function y' = 3t-sqrt(y), but my code doesn't produce any graph output. Can someone point out my mistake please?
import sympy.plotting as sym_plot
def func(y, t):
return 3*t - np.sqrt(y)
# time points
t = np.linspace(0,5)
# initial condition
y0 = 3
# solve ODE
y = odeint(fu... | [
"Are you getting any output at all? And did you give func arguments here?\ny = odeint(func,y0,t)\n\nAlso, you are missing some important imports for your code in the question. Maybe adding them to the code snippet will help you get a better answer.\nEdit: After adding the imports and trying the code out myself, a g... | [
0
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0074649591_matplotlib_python.txt |
Q:
How to install python package on GitHub Codespaces without having to rebuild the container?
I copied a template codespace https://github.com/github/codespaces-flask and now whenever I need to add a new package pip install redis for example I have to add it to my requirements.txt and rebuild the entire codespace ag... | How to install python package on GitHub Codespaces without having to rebuild the container? | I copied a template codespace https://github.com/github/codespaces-flask and now whenever I need to add a new package pip install redis for example I have to add it to my requirements.txt and rebuild the entire codespace again.
What is the proper way of doing this?
Thank you in advance.
I tried searching GitHub codespa... | [
"Try pip install -t target_directory to install directly into a specified folder\n"
] | [
0
] | [] | [] | [
"codespaces",
"flask",
"github_codespaces",
"pip",
"python"
] | stackoverflow_0074648852_codespaces_flask_github_codespaces_pip_python.txt |
Q:
How to solve 404 error of jupyter lab
I installed Anaconda on my windows 10. and updated all packages.
now I am trying to open Jupyter lab by cmd.
when I type this command in cmd: jupyter lab
it just opens a tab in google chrome that shows:
"404 : Not Found You are requesting a page that does not exist!"
could yo... | How to solve 404 error of jupyter lab | I installed Anaconda on my windows 10. and updated all packages.
now I am trying to open Jupyter lab by cmd.
when I type this command in cmd: jupyter lab
it just opens a tab in google chrome that shows:
"404 : Not Found You are requesting a page that does not exist!"
could you please help me to solve this problem to b... | [
"I did:\njupyter serverextension enable --py jupyterlab --user\n\nand\nconda install -c conda-forge nodejs\n\nIt's running now.\n",
"If you are using Anaconda Navigator, install nodejs package within the Navigator. Once nodejs is installed, jupyterLab should be running without any error\n",
"running jupyter lab... | [
10,
1,
1,
0
] | [] | [] | [
"anaconda",
"conda",
"jupyter",
"jupyter_lab",
"python"
] | stackoverflow_0048948259_anaconda_conda_jupyter_jupyter_lab_python.txt |
Q:
Selenium loop the buttonClick
I am trying to scrape all the bikes from this page:
https://www.reconpowerbikes.com/recon-bikes/
but it only has the names without price, lets say if i want to click the number and click the "Shop Now" button from this page and go to each page to get the current price, (the bikes is s... | Selenium loop the buttonClick | I am trying to scrape all the bikes from this page:
https://www.reconpowerbikes.com/recon-bikes/
but it only has the names without price, lets say if i want to click the number and click the "Shop Now" button from this page and go to each page to get the current price, (the bikes is switching periodically). how can i d... | [
"you can try beautiful soup to extract URLs from page source or java script. following is the javascript version.\nresult = driver.execute_script('''\nallbikes=document.querySelectorAll(\".blaze-slider__description\") \nresult=[]\nfor (var i = 0; i < allbikes.length; i++) {\n let bike=allbikes[i]\n let bike_u... | [
0
] | [] | [] | [
"python",
"selenium",
"web_crawler",
"web_scraping"
] | stackoverflow_0074649391_python_selenium_web_crawler_web_scraping.txt |
Q:
Generating csv files
I want to write a program that generate N number of csv files using python and I want to add an option to add a custom schema to generate the headers and values. the csv file should have 5 columns and and N number rows. Country, Capital city, population , Square meter, Continent and each co... | Generating csv files | I want to write a program that generate N number of csv files using python and I want to add an option to add a custom schema to generate the headers and values. the csv file should have 5 columns and and N number rows. Country, Capital city, population , Square meter, Continent and each column could have have diffe... | [
"use \"pandas\" to make schema\nfrom there you can make .csv\n"
] | [
0
] | [] | [] | [
"csv",
"faker",
"python",
"python_3.x"
] | stackoverflow_0074646689_csv_faker_python_python_3.x.txt |
Q:
Find most common substring in a list of strings?
I have a Python list of string names where I would like to remove a common substring from all of the names.
And after reading this similar answer I could almost achieve the desired result using SequenceMatcher.
But only when all items have a common substring:
From ... | Find most common substring in a list of strings? | I have a Python list of string names where I would like to remove a common substring from all of the names.
And after reading this similar answer I could almost achieve the desired result using SequenceMatcher.
But only when all items have a common substring:
From List:
string 1 = myKey_apples
string 2 = myKey_applese... | [
"Given names = [\"myKey_apples\", \"myKey_appleses\", \"myKey_oranges\", \"foo\", \"myKey_Banannas\"]\nAn O(n^2) solution I can think of is to find all possible substrings and storing them in a dictionary with the number of times they occur :\nsubstring_counts={}\n\nfor i in range(0, len(names)):\n for j in rang... | [
11,
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0058585052_python.txt |
Q:
Convert loop to recursive function
I have written a python for loop iteration as show below. I was wondering if its possible to convert into a recursive function.
a = int(input("Please enter the first number: "))
b = int(input("Please enter the second number: "))
res = 0
for i in range(a,b+1):
temp = 1
... | Convert loop to recursive function | I have written a python for loop iteration as show below. I was wondering if its possible to convert into a recursive function.
a = int(input("Please enter the first number: "))
b = int(input("Please enter the second number: "))
res = 0
for i in range(a,b+1):
temp = 1
for j in range(1,i+1):
... | [
"Could be something like this, imagine dividing the problem into smaller sub-problems\ndef recursive_sum(a, b, res=0):\n if a > b:\n return res\n\n temp = 1\n for j in range(1, a+1):\n temp = temp * j\n res = res + temp\n\n return recursive_sum(a+1, b, res)\n\na = int(input(\"Please... | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074649471_python.txt |
Q:
len() shows invalid syntax when define function
def prodListePos_rec(l, len(l)):
if (len(l)>0):
if l[len(l)-1] > 0:
product = prodListePos_rec(l,len(l)) * l[len(l)-1]
else:
product = 1
return product
l = [1,-2, 5, 0, 6,-5]
prodListePos_rec(l,len(l))
I don't get why ... | len() shows invalid syntax when define function | def prodListePos_rec(l, len(l)):
if (len(l)>0):
if l[len(l)-1] > 0:
product = prodListePos_rec(l,len(l)) * l[len(l)-1]
else:
product = 1
return product
l = [1,-2, 5, 0, 6,-5]
prodListePos_rec(l,len(l))
I don't get why it shows the invalid syntax and what should I do if I... | [
"Function parameters must be identifiers, so l is fine, but len(l) is not.\nAlthough, l is a bad variable name since it looks like 1 and I; you could use lst instead.\nMore importantly, you don't actually need to pass the len() around. You can simply get it inside the function.\nHere's a fixed up version of your co... | [
2,
0,
0
] | [] | [] | [
"function",
"python",
"recursion"
] | stackoverflow_0074649522_function_python_recursion.txt |
Q:
Python TypeError: 'NoneType' object does not support item assignment
I try to get data from Yealink Management Cloud Service via API service by the Python scripts below. But I get the error "TypeError: 'NoneType' object does not support item assignment".
How to fix this issue? I'm using Python 3.10 to run the belo... | Python TypeError: 'NoneType' object does not support item assignment | I try to get data from Yealink Management Cloud Service via API service by the Python scripts below. But I get the error "TypeError: 'NoneType' object does not support item assignment".
How to fix this issue? I'm using Python 3.10 to run the below Scripts.
# -*- coding: utf-8 -*-
import hmac
import hashlib
import base6... | [
"Check that you are not at any point passing 'None' to doRequest()'s body parameter. You are trying to reassign a value to an object which is 'None', and that is what is causing your problem.\n"
] | [
0
] | [] | [] | [
"api",
"python",
"python_requests"
] | stackoverflow_0074649788_api_python_python_requests.txt |
Q:
How to update exisitng json file with Python?
I have data.json and read to data variable.
f = open("data.json", "r")
data = np.array(json.loads(f.read()))
ouput of 'data' as below.
[{
"symbol" : "NZDCHF",
"timeframe" : [
{"tf":"H4","x1":0,"y1":0,"x2":0,"y2":0},
{"tf":"H1","x1":0,"y1":0,"x2... | How to update exisitng json file with Python? | I have data.json and read to data variable.
f = open("data.json", "r")
data = np.array(json.loads(f.read()))
ouput of 'data' as below.
[{
"symbol" : "NZDCHF",
"timeframe" : [
{"tf":"H4","x1":0,"y1":0,"x2":0,"y2":0},
{"tf":"H1","x1":0,"y1":0,"x2":0,"y2":0},
{"tf":"M30","x1":0,"y1":0,"x2"... | [
"you don't need numpy here:\nwith open(\"data.json\", \"r\") as f:\n data = json.load(f)\nfor item in data:\n if item['symbol'] == 'AUDCHF':\n # same for x2 and y2\n item['timeframe'][4]['x1'] = 1\n item['timeframe'][4]['y1'] = 1\n break\nelse: # this will only trigger if the loop ... | [
1
] | [] | [] | [
"json",
"python"
] | stackoverflow_0074649746_json_python.txt |
Q:
How to find & show a specific coordinate from a plot?
I have made a plot using plt.plot(xdata,ydata)
And I would like to find the x-coordinate when y coordinate = 125.94937644205281 + 1 (chi-squared+1) from the plot.
And I would also like to show its coordinate.
Is there any method to do that?
Example plot
I have ... | How to find & show a specific coordinate from a plot? | I have made a plot using plt.plot(xdata,ydata)
And I would like to find the x-coordinate when y coordinate = 125.94937644205281 + 1 (chi-squared+1) from the plot.
And I would also like to show its coordinate.
Is there any method to do that?
Example plot
I have tried locating roots method, but it is taking ages to find ... | [
"You are in an infinite loop because you never break out of the while True loop. The break statement only breaks out of one loop at a time. See also How to break out of nested loops in python?\n"
] | [
0
] | [] | [] | [
"matplotlib",
"physics",
"python",
"statistics"
] | stackoverflow_0074649825_matplotlib_physics_python_statistics.txt |
Q:
Python: String to CamelCase
This is a question from Codewars:
Complete the method/function so that it converts dash/underscore delimited words into camel casing. The first word within the output should be capitalized only if the original word was capitalized (known as Upper Camel Case, also often referred to as Pa... | Python: String to CamelCase | This is a question from Codewars:
Complete the method/function so that it converts dash/underscore delimited words into camel casing. The first word within the output should be capitalized only if the original word was capitalized (known as Upper Camel Case, also often referred to as Pascal case).
The input test cases ... | [
"You may have a working implementation with slight errors as mentioned in your comments, but I propose that you:\n\nsplit by the delimiters\napply a capitalization for all but the first of the tokens\nrejoin the tokens\n\nMy implementation is:\ndef to_camel_case(text):\n s = text.replace(\"-\", \" \").replace(\"... | [
13,
4,
1,
1,
0
] | [] | [] | [
"python",
"string"
] | stackoverflow_0060978672_python_string.txt |
Q:
Expand pandas dataframe column of dict into dataframe columns
I have a Pandas DataFrame where one column is a Series of dicts, like this:
colA colB colC
0 7 7 {'foo': 185, 'bar': 182, 'baz': 148}
1 2 8 {'foo': 117, 'bar': 103, 'baz': 155}
2 5 10 {'foo'... | Expand pandas dataframe column of dict into dataframe columns | I have a Pandas DataFrame where one column is a Series of dicts, like this:
colA colB colC
0 7 7 {'foo': 185, 'bar': 182, 'baz': 148}
1 2 8 {'foo': 117, 'bar': 103, 'baz': 155}
2 5 10 {'foo': 165, 'bar': 184, 'baz': 170}
3 3 2 {'foo': 121, 'bar': 1... | [
"TL;DR\nBased on Carlos Horn's comment pd.json_normalize are perfect for this:\ndf_fixed = df.join(pd.json_normalize(df['colC'])).drop('colC', axis='columns')\n\nOld answer\ndf = df.drop('colC', axis=1).join(pd.DataFrame(df.colC.values.tolist()))\n\nElaborate (old) answer\nWe start by defining the DataFrame to work... | [
20,
0
] | [] | [] | [
"dataframe",
"dictionary",
"pandas",
"python",
"series"
] | stackoverflow_0054344114_dataframe_dictionary_pandas_python_series.txt |
Q:
Python Move between rooms Key Error message
rooms = {
'Great Hall': {'South': 'Bedroom'},
'Bedroom': {'North': 'Great Hall', 'East': 'Cellar'},
'Cellar': {'West': 'Bedroom'}
}
current_room = 'Great Hall'
user_move = ''
directions = ['North', 'South', 'East', 'West']
while user_move != 'ex... | Python Move between rooms Key Error message | rooms = {
'Great Hall': {'South': 'Bedroom'},
'Bedroom': {'North': 'Great Hall', 'East': 'Cellar'},
'Cellar': {'West': 'Bedroom'}
}
current_room = 'Great Hall'
user_move = ''
directions = ['North', 'South', 'East', 'West']
while user_move != 'exit':
print("You are in the", current_room)
... | [
"You need to verify that the chosen direction is valid before moving rooms.\nwhile user_move != 'exit':\n print(\"You are in the\", current_room)\n user_move = input(\"Choose a direction \")\n\n # is the move a valid choice?\n if user_move in rooms[current_room]:\n # yes it is valid, so move ther... | [
2
] | [] | [] | [
"if_statement",
"python"
] | stackoverflow_0074649771_if_statement_python.txt |
Q:
Python NumPy log2 - How to make it a negative log?
I just started working with Numpy because I want to use their log method. I am trying to do -log2(79/859) but can only see how to do log2(74/571) which outputs a negative value when it should be positive. Read the Doc but don't see how to make it a negative log?
H... | Python NumPy log2 - How to make it a negative log? | I just started working with Numpy because I want to use their log method. I am trying to do -log2(79/859) but can only see how to do log2(74/571) which outputs a negative value when it should be positive. Read the Doc but don't see how to make it a negative log?
How can I fix this?
print(np.log2(79/859))
Output
-2.947... | [
"As I posted in my comment, if you always want a positive value for your logarithm, you can use an absolute value:\nnp.abs(np.log2(74/571))\n# 2.948\n\nAlso, as suggested above, you don't need the NumPy library if you only want to use logarithms. You can accomplish the same with the math standard module and even wi... | [
1,
0
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0074649757_numpy_python.txt |
Q:
ipython: get the result of `??` (double question mark) magic command as string
The IPython builtin help system says:
Within IPython you have various way to access help:
? -> Introduction and overview of IPython's features (this screen).
object? -> Details about 'object'.
object?? -> More detailed... | ipython: get the result of `??` (double question mark) magic command as string | The IPython builtin help system says:
Within IPython you have various way to access help:
? -> Introduction and overview of IPython's features (this screen).
object? -> Details about 'object'.
object?? -> More detailed, verbose information about 'object'.
The double question mark magic command (??) t... | [
"you can use \"pinfo2\", https://ipython.readthedocs.io/en/stable/interactive/magics.html\nfor example\ndef test(a, b):\n import numpy as np\n cds = data.range(1000)\n cds = cds.random_shuffle()\n a = np.array([a])\n return a, b\n\n\nfrom IPython import get_ipython\nipython = get_ipython()\nipython.r... | [
0
] | [] | [] | [
"ipython",
"python"
] | stackoverflow_0070833723_ipython_python.txt |
Q:
AttributeError: module 'sipbuild.api' has no attribute 'prepare_metadata_for_build_wheel' for PyQt5 5.15.0
A program I am trying to install requires the installation of PyQt5 5.15.0 , which gives me this error. The odd thing is that the installation works fine for the latest version of PyQt5 (5.15.2), but this pro... | AttributeError: module 'sipbuild.api' has no attribute 'prepare_metadata_for_build_wheel' for PyQt5 5.15.0 | A program I am trying to install requires the installation of PyQt5 5.15.0 , which gives me this error. The odd thing is that the installation works fine for the latest version of PyQt5 (5.15.2), but this program requires 5.15.0 specifically.
Command Output:
Collecting PyQt5==5.15.0
Using cached PyQt5-5.15.0.tar.gz (... | [
"What helped me is upgrading pip from 20.2.3 to the latest one (in my case 21.1.1)\n",
"For Mac/Homebrew users.\nThe answer https://stackoverflow.com/a/72046110/5327611 is leading in the right direction. On a Mac with QT5 installed via Homebrew the qmake binary just needs to be added to the path. This can be achi... | [
16,
11,
7,
7,
6,
2,
1,
1,
1,
0,
0
] | [
"This can be resolved by switching to an environment with Python >= 3.8\n"
] | [
-7
] | [
"pip",
"pyqt5",
"python",
"python_3.x"
] | stackoverflow_0065447314_pip_pyqt5_python_python_3.x.txt |
Q:
When trying to run a pyglet window, I get this error: "AttributeError: 'scipy.spatial.transform._rotation.Rotation' object has no attribute 'as_dcm'"
This is all my code
import pyglet
import ratcave as rc
window = pyglet.window.Window()
pyglet.app.run()
When running this, the following shows in terminal
Traceb... | When trying to run a pyglet window, I get this error: "AttributeError: 'scipy.spatial.transform._rotation.Rotation' object has no attribute 'as_dcm'" | This is all my code
import pyglet
import ratcave as rc
window = pyglet.window.Window()
pyglet.app.run()
When running this, the following shows in terminal
Traceback (most recent call last):
File "c:\CODING\pyopengl\Mudge-David-Homework-8.py", line 14, in <module>
import ratcave as rc
File "C:\Users\David\Ap... | [
"The as_dcm() method of the Rotation class was deprecated in SciPy version 1.4.0 and removed from SciPy version 1.6.0. You'll have to use an older version of SciPy, or find out if there is a version of ratcave that works with the latest version of SciPy.\n"
] | [
0
] | [] | [] | [
"pyglet",
"python",
"ratcave",
"scipy"
] | stackoverflow_0074648836_pyglet_python_ratcave_scipy.txt |
Q:
VSCode/Jupyter interfering with Rich (log formatting library for Python) and I see an for each output
Here is what I am seeing, the sign to the left of each output
How do I make that go away? Again I am using VSCode/Python and Jupyter Notebooks
The outputs or like log.info("some text")
From what I have read so fa... | VSCode/Jupyter interfering with Rich (log formatting library for Python) and I see an for each output | Here is what I am seeing, the sign to the left of each output
How do I make that go away? Again I am using VSCode/Python and Jupyter Notebooks
The outputs or like log.info("some text")
From what I have read so far it seems to be because rich is using markup that is like HTML and then Jupyter renders this as HTLM or som... | [
"According to the answer on github.\nUnfortunately, there is currently no way to remove <\\> on vscode-jupyter.\nBecause it is a button that appears on each output. It lets you change the renderer type for that output.\nYou can use jupyter notebook if you like. This symbol <\\> does not appear in my use of jupyter ... | [
0
] | [] | [] | [
"jupyter_notebook",
"python",
"rich",
"visual_studio_code"
] | stackoverflow_0074632228_jupyter_notebook_python_rich_visual_studio_code.txt |
Q:
Python: Trying to extract a value from a list of dictionaries that is stored as a string
I am getting data from an API and storing it in json format. The data I pull is in a list of dictionaries. I am using Python. My task is to only grab the information from the dictionary that matches the ticker symbol.
This is ... | Python: Trying to extract a value from a list of dictionaries that is stored as a string | I am getting data from an API and storing it in json format. The data I pull is in a list of dictionaries. I am using Python. My task is to only grab the information from the dictionary that matches the ticker symbol.
This is the short version of my data printing using json dumps
[
{
"ticker": "BYDDF.US",
... | [
"This is a solution that I've seen divide the python community. Some say that it's a feature and \"very pythonic\"; others say that it's a bad design choice we're stuck with now, and bad practice. I'm personally not a fan, but it is a way to solve this problem, so do with it what you will. :)\nPython function loops... | [
1,
0,
0
] | [] | [] | [
"api",
"json",
"python"
] | stackoverflow_0074649029_api_json_python.txt |
Q:
How can I contour an image in opencv?
cv2.error: OpenCV(4.6.0) /io/opencv/modules/imgproc/src/contours.cpp:195: error: (-210:Unsupported format or combination of formats) [Start]FindContours supports only CV_8UC1 images when mode != CV_RETR_FLOODFILL otherwise supports CV_32SC1 images only in function 'cvStartFind... | How can I contour an image in opencv? | cv2.error: OpenCV(4.6.0) /io/opencv/modules/imgproc/src/contours.cpp:195: error: (-210:Unsupported format or combination of formats) [Start]FindContours supports only CV_8UC1 images when mode != CV_RETR_FLOODFILL otherwise supports CV_32SC1 images only in function 'cvStartFindContours_Impl'
here's my code. whats wrong?... | [
"I just tried your code in python3 and everything works normal, your code works.\nhere is the coded I tested, just remove some waitkeys.\nimport cv2 \n import numpy as np \n image = cv2.imread('1.png') \n\n gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) \n edged = cv2.Can... | [
0
] | [] | [] | [
"image_processing",
"opencv",
"python"
] | stackoverflow_0074647732_image_processing_opencv_python.txt |
Q:
Autocomplete in vscode not showing some code
some code does not appear. I have to type it manually. For example, if I want to add an upper, it does not appear
print(f'Hello {first.upper().capitalize()})
It does not complete here, but in other things it completes
Nothing works for meenter image description here
A... | Autocomplete in vscode not showing some code | some code does not appear. I have to type it manually. For example, if I want to add an upper, it does not appear
print(f'Hello {first.upper().capitalize()})
It does not complete here, but in other things it completes
Nothing works for meenter image description here
| [
"Because you have defined a variable named first, but it has no content. It can be of any type, so vscode won't provide any prompt.\nI guess that you want to define the string and first is it's content.\n\nYou can define x=\"first\", here the type of x is string, then x has the upper() method.\n"
] | [
0
] | [] | [] | [
"autocomplete",
"python",
"visual_studio_code"
] | stackoverflow_0074644119_autocomplete_python_visual_studio_code.txt |
Q:
How to fuzzy match two lists in Python
I have two lists: ref_list and inp_list. How can one make use of FuzzyWuzzy to match the input list from the reference list?
inp_list = pd.DataFrame(['ADAMS SEBASTIAN', 'HAIMBILI SEUN', 'MUTESI
JOHN', 'SHEETEKELA MATT', 'MUTESI JOHN KUTALIKA',
... | How to fuzzy match two lists in Python | I have two lists: ref_list and inp_list. How can one make use of FuzzyWuzzy to match the input list from the reference list?
inp_list = pd.DataFrame(['ADAMS SEBASTIAN', 'HAIMBILI SEUN', 'MUTESI
JOHN', 'SHEETEKELA MATT', 'MUTESI JOHN KUTALIKA',
'ADAMS SEBASTIAN HAU... | [
"You can try to vectorized the operations instead of evaluate the scores in a loop.\nMake a df where the firse col ref is ref_list and the second col inp is each name in inp_list. Then call df.apply(lambda row:process.extractOne(row['inp'], row['ref']), axis=1). Finally you'll get the best match name and score in r... | [
1,
0
] | [] | [] | [
"fuzzywuzzy",
"matching",
"python"
] | stackoverflow_0062790165_fuzzywuzzy_matching_python.txt |
Q:
Installing Python 3.11
I want to try out Python 3.11 to find out how much faster this version is than what I'm currently using (3.7.3). I am using Anaconda and Spyder, but Anaconda does not yet support Python 3.11 and additionally I regularly have problems with updating in Anaconda.
Importantly, I want to maintain... | Installing Python 3.11 | I want to try out Python 3.11 to find out how much faster this version is than what I'm currently using (3.7.3). I am using Anaconda and Spyder, but Anaconda does not yet support Python 3.11 and additionally I regularly have problems with updating in Anaconda.
Importantly, I want to maintain my Anaconda and Spyder envi... | [
"\nTry to create new env 3.10 using Anaconda, if Anaconda still doesn't have 3.11. The difference with 3.11 would be (I'm not guaranty, just a \"rumors\") ~+15%, depends...\n\nYou can build and install your version from source :\nbuild-python-from-source\n\n\nThis way you won't break anything and can to delete Pyt... | [
0
] | [
"It's not recommended to have multiple versions of Python installed on the same system, as this can cause conflicts and problems with package compatibility. Instead of installing Python 3.11 directly, you can create a new virtual environment using conda and install Python 3.11 in that environment. This will allow y... | [
-4
] | [
"anaconda",
"ide",
"performance",
"python",
"python_3.11"
] | stackoverflow_0074646486_anaconda_ide_performance_python_python_3.11.txt |
Q:
How to pull player game logs from multiple seasons using nba_api?
I am trying to get familiar with nba_api package for python. I am attempting to pull player data from the past two seasons. However, I am only able to get all of the seasons or just one season.
First, I saw I could collect the game logs from an indi... | How to pull player game logs from multiple seasons using nba_api? | I am trying to get familiar with nba_api package for python. I am attempting to pull player data from the past two seasons. However, I am only able to get all of the seasons or just one season.
First, I saw I could collect the game logs from an individual season:
from nba_api.stats.static import players
player_dict = ... | [
"You can use SeasonAll, convert to pandas df, convert datetime and finally query.\nimport pandas as pd\nfrom nba_api.stats.endpoints import playergamelog\nfrom nba_api.stats.library.parameters import SeasonAll\nfrom nba_api.stats.static import players\n\n\nluka_id = next((x for x in players.get_players() if x.get(\... | [
0
] | [] | [] | [
"dataframe",
"nba_api",
"pandas",
"python",
"web_scraping"
] | stackoverflow_0074648245_dataframe_nba_api_pandas_python_web_scraping.txt |
Q:
Difficulties using matplotlib plot method
Very recently I have been tasked with ploting a derivative using Python and matplotlib. This is my code:
x=np.linspace(-100,100,num=50)
funcion=(56*(x**3))-(38.999*(x**2))+(4.196*x-0.15)
plt.plot(x, funcion)
The resulting plot is this:
Plot generated in Python
At firs... | Difficulties using matplotlib plot method | Very recently I have been tasked with ploting a derivative using Python and matplotlib. This is my code:
x=np.linspace(-100,100,num=50)
funcion=(56*(x**3))-(38.999*(x**2))+(4.196*x-0.15)
plt.plot(x, funcion)
The resulting plot is this:
Plot generated in Python
At first sight, the graph looks okay, but is not corre... | [
"The problem is not with matplotlib, but instead the range of x values you chose. If you look at your own picture, the xvalues are ranging from around -2 to 2, so if I do the same and play with the plotting bounds I get:\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\nx=np.linspace(-2,2,101) \nfuncion=(5... | [
1
] | [] | [] | [
"calculus",
"matplotlib",
"plot",
"python"
] | stackoverflow_0074649964_calculus_matplotlib_plot_python.txt |
Q:
Visual Studio Code Venv Used Wrong Python Version
I have Python 3.4 and 3.9 installed. I chose the former through the Command Palette and then (also through the Command Palette) created a virtual environment with Venv. I create a new terminal, enter python --version, and it says 3.9 instead of 3.4.
How do I go abo... | Visual Studio Code Venv Used Wrong Python Version | I have Python 3.4 and 3.9 installed. I chose the former through the Command Palette and then (also through the Command Palette) created a virtual environment with Venv. I create a new terminal, enter python --version, and it says 3.9 instead of 3.4.
How do I go about fixing this?
| [
"There are multiple python environments on your machine, if you have created a virtual environment, you should run these commands after activation. If you execute the python command in a terminal where the virtual environment is not activated, the displayed version will be the one configured in the system environme... | [
1
] | [] | [] | [
"python",
"virtualenv",
"visual_studio_code"
] | stackoverflow_0074648847_python_virtualenv_visual_studio_code.txt |
Q:
Is there a decorator to simply cache function return values?
Consider the following:
@property
def name(self):
if not hasattr(self, '_name'):
# expensive calculation
self._name = 1 + 1
return self._name
I'm new, but I think the caching could be factored out into a decorator. Only I didn... | Is there a decorator to simply cache function return values? | Consider the following:
@property
def name(self):
if not hasattr(self, '_name'):
# expensive calculation
self._name = 1 + 1
return self._name
I'm new, but I think the caching could be factored out into a decorator. Only I didn't find one like it ;)
PS the real calculation doesn't depend on m... | [
"Starting from Python 3.2 there is a built-in decorator:\n@functools.lru_cache(maxsize=100, typed=False)\n\nDecorator to wrap a function with a memoizing callable that saves up to the maxsize most recent calls. It can save time when an expensive or I/O bound function is periodically called with the same arguments.\... | [
278,
48,
39,
30,
27,
12,
10,
8,
7,
4,
4,
4,
4,
3,
3,
2,
2,
2,
1,
0
] | [] | [] | [
"caching",
"decorator",
"memoization",
"python"
] | stackoverflow_0000815110_caching_decorator_memoization_python.txt |
Q:
Removing specific key value pairs from geoJSON object
The following is a subset of my geoJSON object which has a combination of Multipolygons and GeometryCollections in its features. The GeometryCollections include multiple types of geometries.
json_str = '{"type": "FeatureCollection",
"features": [
{"id": "0... | Removing specific key value pairs from geoJSON object | The following is a subset of my geoJSON object which has a combination of Multipolygons and GeometryCollections in its features. The GeometryCollections include multiple types of geometries.
json_str = '{"type": "FeatureCollection",
"features": [
{"id": "0",
"type": "Feature",
"properties": {"Date": "201... | [
"It's generally easier to assemble a new list that has only the items you want, instead of individually deleting the unwanted items from the old list.\nAnd then, if you like, you can replace the old list with the new list.\nA simple example of this:\nnumbers = [0,1,2,3,4,5,6,7,8,9]\n\n# replace numbers with a versi... | [
1,
1
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0074649960_dictionary_python.txt |
Q:
How can I add features from different images and merge them into a final image
I have some images, each of which may contain one or more blobs, I know how to load the image and convert it to binary but I want to be able to add all found blobs from any amount of images and paste them into a final image (which will ... | How can I add features from different images and merge them into a final image | I have some images, each of which may contain one or more blobs, I know how to load the image and convert it to binary but I want to be able to add all found blobs from any amount of images and paste them into a final image (which will start out blank).
I don't know if opencv or pillow is better for this as I have very... | [
"This has been asked before on opencv c++, there should be the same function on python3, hconcat, placing two images side by side, opencv 2.3, c++\n"
] | [
0
] | [] | [] | [
"image",
"opencv",
"python"
] | stackoverflow_0074641915_image_opencv_python.txt |
Q:
How to avoid Selenium being detected when answering captcha?
I have a Python script which login on a page (sso.acesso.gov.br) using some credentials and them usually answer a captcha using 2Captcha API.
The problem is that recently it takes an error after captcha answer, even when I answer it manually.
By the way,... | How to avoid Selenium being detected when answering captcha? | I have a Python script which login on a page (sso.acesso.gov.br) using some credentials and them usually answer a captcha using 2Captcha API.
The problem is that recently it takes an error after captcha answer, even when I answer it manually.
By the way, the error message received is different than when I forced answer... | [
"Add couple of seconds wait before you enter correct captcha first time, that might work unless its designed otherwise.\n"
] | [
0
] | [] | [] | [
"python",
"python_3.x",
"selenium",
"selenium_chromedriver",
"selenium_webdriver"
] | stackoverflow_0074606892_python_python_3.x_selenium_selenium_chromedriver_selenium_webdriver.txt |
Q:
Position bars between tick marks (and not on tick marks) in plotly
I am using Plotly and Python to chart a bar plot. On the x-axis, Plotly arranges the values from each trace around the centre of the tick mark.
This is what I am getting now:
I would like to have the data points (and labels) in between the tick ma... | Position bars between tick marks (and not on tick marks) in plotly | I am using Plotly and Python to chart a bar plot. On the x-axis, Plotly arranges the values from each trace around the centre of the tick mark.
This is what I am getting now:
I would like to have the data points (and labels) in between the tick marks. In the example chart, this would mean all the bars centered around ... | [
"Answering my own question.\nNormally setting tickon=boundaries should do the trick, but it doesn't seem to work in conjunction with tickmode=array and ticktext.\nThe solution for me was to create the labels array and provide it to the bar chart as the x parameter, something similar to this:\nfig = go.Figure(data=g... | [
0
] | [] | [] | [
"plotly",
"python"
] | stackoverflow_0074644983_plotly_python.txt |
Q:
Convert a dataframe to dictionary
I have this data like this
technologies = [
("a","2","3"),
("4","5","6"),
("7","8","9")
]
df = pd.DataFrame(technologies,columns = ['C1','C2','C3'])
print(df)
and i convert it to this df
C1 C2 C3
0 a 2 3
1 4 5 6
2 7 8 9
... | Convert a dataframe to dictionary | I have this data like this
technologies = [
("a","2","3"),
("4","5","6"),
("7","8","9")
]
df = pd.DataFrame(technologies,columns = ['C1','C2','C3'])
print(df)
and i convert it to this df
C1 C2 C3
0 a 2 3
1 4 5 6
2 7 8 9
then i convert DataFrame to Dictionary ... | [
"You can use pprint.pprint() for that. Something like this:\n>>> from pprint import pprint\n>>> d = [{'C1': 'a', 'C2': '2', 'C3': '3'}, {'C1': '4', 'C2': '5', 'C3': '6'}, {'C1': '7', 'C2': '8', 'C3': '9'}]\n>>> pprint(d, width=10)\n[{'C1': 'a',\n 'C2': '2',\n 'C3': '3'},\n {'C1': '4',\n 'C2': '5',\n 'C3': '6'},... | [
1
] | [] | [] | [
"dataframe",
"dictionary",
"pandas",
"python"
] | stackoverflow_0074650104_dataframe_dictionary_pandas_python.txt |
Q:
How do I call a function "x" amount of times in python? Using a for loop?
I have a cap.read() function where I am reading in frames from a video. The first call of the function is the zeroth frame, the second call is the 1st frame, etc... I am trying to call the function 1200 because I need to start my read-in at ... | How do I call a function "x" amount of times in python? Using a for loop? | I have a cap.read() function where I am reading in frames from a video. The first call of the function is the zeroth frame, the second call is the 1st frame, etc... I am trying to call the function 1200 because I need to start my read-in at the 1200th frame.
Right now this is what I have, but I know it is incorrect.
| [
"The direct answer to your question was answered by @Shmack in the comments. The code is simply\nfor i in range(1200):\n cap.read()\n\nGiven that your using the variable cap, I suspect that your using the OpenCV module. If that is the case, then you can simply set the frame you want to start at by using cap.set(... | [
0
] | [] | [] | [
"continuous",
"for_loop",
"function",
"python",
"repeat"
] | stackoverflow_0074650021_continuous_for_loop_function_python_repeat.txt |
Q:
How can I import all of sklearns regressors
I'm doing some predictive modeling and would like to benchmark different kinds of regressors in scikit-learn, just to see what's out there and how they perform on a given prediction task.
I got inspired to do this by this kaggle kernel in which the author essentially man... | How can I import all of sklearns regressors | I'm doing some predictive modeling and would like to benchmark different kinds of regressors in scikit-learn, just to see what's out there and how they perform on a given prediction task.
I got inspired to do this by this kaggle kernel in which the author essentially manually imports a bunch of classifiers (about 10) a... | [
"I figured out i had to use getattr on the module object:\nfrom importlib import import_module\nimport sklearn\n\ndef all_regressors():\n regressors=[]\n for module in sklearn.__all__:\n try:\n module = import_module(f'sklearn.{module}')\n regressors.extend([getattr(module,cls) fo... | [
2,
0
] | [] | [] | [
"python",
"python_import",
"scikit_learn"
] | stackoverflow_0046852222_python_python_import_scikit_learn.txt |
Q:
Why would a MySQL DELETE statement fail when the corresponding SELECT statement works?
I have a MySQL database instance hosted on GCP, and I am connecting to it using the pymysql python package. I would like to delete some rows from a database table called Basic.
The code I have written to do this is included belo... | Why would a MySQL DELETE statement fail when the corresponding SELECT statement works? | I have a MySQL database instance hosted on GCP, and I am connecting to it using the pymysql python package. I would like to delete some rows from a database table called Basic.
The code I have written to do this is included below. The variable conf contains the connection details to the database instance.
import pymysq... | [
"The code above requires the addition of the following line, in order to commit the DELETE statement.\nconnection.commit()\n\nThe commit method should be called after every transaction that modifies data, such as this one.\n"
] | [
0
] | [] | [] | [
"google_cloud_platform",
"mysql",
"pymysql",
"python"
] | stackoverflow_0074649302_google_cloud_platform_mysql_pymysql_python.txt |
Q:
The input keeps repeating itself
Hello I'm new in programming, I was coding newton's method for a uni class, and the part where the user input the f(x) in the code keeps repeating.
This is the code I was making, it works but the def f(x) keeps repeating for 2 or 3 times before the while starts
import math
import s... | The input keeps repeating itself | Hello I'm new in programming, I was coding newton's method for a uni class, and the part where the user input the f(x) in the code keeps repeating.
This is the code I was making, it works but the def f(x) keeps repeating for 2 or 3 times before the while starts
import math
import sympy as smp
from sympy import *
x = sm... | [
"You can perform the code as follows.\nCode\nfrom sympy import Symbol, diff, sympify\n\ndef newton_method(func, sym, x0, n = 10):\n diff_func = diff(func, x) # derivative of function\n \n root = x0\n for i in range(n):\n root = root - float(func.subs(x, root)/diff_func.subs(x, root))\n ... | [
0
] | [] | [] | [
"math",
"python"
] | stackoverflow_0074647327_math_python.txt |
Q:
Clearing decorator ipywidgets
I have a function which plots a graph with a couple ipywidgets as inputs:
from IPython.display import clear_output
def on_clicker(button):
clear_output()
@widgets.interact(dropdown=widgets.Dropdown(...),
datepicker=widgets.DatePicker(...)
def grapher(dropdow... | Clearing decorator ipywidgets | I have a function which plots a graph with a couple ipywidgets as inputs:
from IPython.display import clear_output
def on_clicker(button):
clear_output()
@widgets.interact(dropdown=widgets.Dropdown(...),
datepicker=widgets.DatePicker(...)
def grapher(dropdown, datepicker):
global recalc... | [
"You can use the clear_output() function to clear the output of the current cell in a Jupyter notebook. However, this will not clear the widgets that you have defined in your code. In order to clear the widgets, you will need to re-initialize them each time the on_clicker() function is called.\nOne way to do this w... | [
0
] | [] | [] | [
"ipywidgets",
"jupyter",
"python"
] | stackoverflow_0074650205_ipywidgets_jupyter_python.txt |
Q:
How to add a function with print in print
When I'm doing this:
def pencil():
print("pencil")
print("A", pencil())
Output showing:
pencil
A None
I tried some things but nothing worked.
A:
def pencil():
return "pencil"
print("A", pencil()) # A pencil
Or
def pencil():
print("pencil")
print("A") # A... | How to add a function with print in print | When I'm doing this:
def pencil():
print("pencil")
print("A", pencil())
Output showing:
pencil
A None
I tried some things but nothing worked.
| [
"def pencil():\n return \"pencil\"\n\n\nprint(\"A\", pencil()) # A pencil\n\nOr\ndef pencil():\n print(\"pencil\")\n\n\nprint(\"A\") # A\npencil() # pencil\n\n",
"When you do\nprint(\"A\", pencil())\n\nyou are basically asking python to print \"A\" and the return value of the function named pencil.\nBecau... | [
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074650214_python.txt |
Q:
How to Implement 'if' Statement for a Function to Solve a System of ODEs using solve_ivp in Python
For the time, t, from 0 to 30, z0 is a constant value of 6. For the time,t, from 30 to 100, z0 takes on the form of a time variable where z0 = 6exp(-0.5*(t-15)). I tried to implement the 'if' condition in my function... | How to Implement 'if' Statement for a Function to Solve a System of ODEs using solve_ivp in Python | For the time, t, from 0 to 30, z0 is a constant value of 6. For the time,t, from 30 to 100, z0 takes on the form of a time variable where z0 = 6exp(-0.5*(t-15)). I tried to implement the 'if' condition in my function but it does not seem to work. Is there anything I am doing wrong? Any help will be appreciated.
z0 = 6
... | [
"You should use an if/elif/else structure. You don't need to make 2 functions for the 2 different values of z0.\ndef f(t,y):\n if 0 <= t <= 30:\n z0 = 6\n elif t > 30: \n z0 = 6 * np.exp(-0.5 * (t - 15))\n else:\n return f\"t value {t} is less than zero\"\n return z0 - y[0], 3 / y[0... | [
0
] | [] | [] | [
"if_statement",
"math",
"ode",
"python"
] | stackoverflow_0074650245_if_statement_math_ode_python.txt |
Q:
Python - openpyxl - Use openpyxl to get number of rows that contain a specific value
I'm newer to Python. I'm using openpyxl for a SEO project for my brother and I'm trying to get a number of rows that contain a specific value in them.
I have a spreadsheet that looks something like this:
I want to write a program... | Python - openpyxl - Use openpyxl to get number of rows that contain a specific value | I'm newer to Python. I'm using openpyxl for a SEO project for my brother and I'm trying to get a number of rows that contain a specific value in them.
I have a spreadsheet that looks something like this:
I want to write a program that will get the keywords and parse them to a string by state, so like:
Missouri = "sear... | [
"Ok another option\nThis will create a dictionary 'state_dict' in the format per your question\n\nMissouri = \"search item 1, search item 2, search item 5, search item\n6\" \nIllinois = \"search item 3, search item 4\"\n\n...\nprint(\"\\nValue of fourth column\")\nstate_dict = {}\nfor row in sheet_object.iter_rows(... | [
1,
0,
0
] | [] | [] | [
"excel",
"loops",
"openpyxl",
"python"
] | stackoverflow_0074649003_excel_loops_openpyxl_python.txt |
Q:
How to stack capsnet (capsule neural network) properly?
Capsule neural network use convolution, primary capsule, and digit capsule layer. Meanwhile convolutional neural network using convolution and max pool layer. I want to make a comparison between convolutional neural network and capsule neural network. The tab... | How to stack capsnet (capsule neural network) properly? | Capsule neural network use convolution, primary capsule, and digit capsule layer. Meanwhile convolutional neural network using convolution and max pool layer. I want to make a comparison between convolutional neural network and capsule neural network. The table below is the architecture of my cnn model. I need to make ... | [] | [] | [
"from your question, I understand that you need to create networks that compared the input and segmentations. There are techniques to create objects segmentation by auto-encoder, see the example images divided by color shades and background you can determine initial image components.\nFor the segmentation part you ... | [
-2
] | [
"conv_neural_network",
"deep_learning",
"neural_network",
"python",
"tensorflow"
] | stackoverflow_0074649733_conv_neural_network_deep_learning_neural_network_python_tensorflow.txt |
Q:
Testing a POST that uses Flask-WTF validate_on_submit
I am stumped on testing a POST to add a category to the database where I've used Flask_WTF for validation and CSRF protection. For the CRUD operations pm my website. I've used Flask, Flask_WTF and Flask-SQLAlchemy. It is my first independent project, and I fin... | Testing a POST that uses Flask-WTF validate_on_submit | I am stumped on testing a POST to add a category to the database where I've used Flask_WTF for validation and CSRF protection. For the CRUD operations pm my website. I've used Flask, Flask_WTF and Flask-SQLAlchemy. It is my first independent project, and I find myself a little at a lost on how to test the Flask-WTForm... | [
"You should have different configurations for your app, depending if you are local / in production / executing unit tests. One configuration you can set is\nWTF_CSRF_ENABLED = False\n\nSee flask-wtforms documentation.\n",
"Using py.test and a conftest.py recommended by Delightful testing with pytest and SQLAlchem... | [
5,
2,
0
] | [] | [] | [
"flask_wtforms",
"python",
"python_2.7",
"wtforms"
] | stackoverflow_0037579411_flask_wtforms_python_python_2.7_wtforms.txt |
Q:
get tree view from a dictionary with anytree or rich, or treelib
I read the manual from https://anytree.readthedocs.io/en/latest/#, but I didn't figure out how to translate a dictionary to tree view, anyone can help?
data = {
'Marc': 'Udo',
'Lian': 'Marc',
'Dan': 'Udo',
'Jet': 'Dan',
'Jan': 'Da... | get tree view from a dictionary with anytree or rich, or treelib | I read the manual from https://anytree.readthedocs.io/en/latest/#, but I didn't figure out how to translate a dictionary to tree view, anyone can help?
data = {
'Marc': 'Udo',
'Lian': 'Marc',
'Dan': 'Udo',
'Jet': 'Dan',
'Jan': 'Dan',
'Joe': 'Dan',
}
output is
Udo
├── Marc
│ └── Lian
└── Dan
... | [
"First you need to create the tree from your dict of \"relationship\" data, there are many ways to do this but here's an example:\nfrom anytree import Node\n\nnodes = {}\nfor k, v in data.items():\n nk = nodes[k] = nodes.get(k) or Node(k)\n nv = nodes[v] = nodes.get(v) or Node(v)\n nk.parent = nv\n\nNow yo... | [
1
] | [] | [] | [
"anytree",
"python",
"rich",
"treelib"
] | stackoverflow_0074650261_anytree_python_rich_treelib.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.