QuestionId
int64
74.8M
79.8M
UserId
int64
56
29.4M
QuestionTitle
stringlengths
15
150
QuestionBody
stringlengths
40
40.3k
Tags
stringlengths
8
101
CreationDate
stringdate
2022-12-10 09:42:47
2025-11-01 19:08:18
AnswerCount
int64
0
44
UserExpertiseLevel
int64
301
888k
UserDisplayName
stringlengths
3
30
⌀
77,063,506
459,745
Curses does not print output
<p>I am new to curses so am a little confused why I don't see any output from this little &quot;hello world&quot;:</p> <pre class="lang-py prettyprint-override"><code>import curses import time def main(window: curses.window): window.addstr(1, 1, &quot;Hello, world&quot;) time.sleep(3) if __name__ == &quot;_...
<python><python-curses>
2023-09-08 00:32:19
1
41,381
Hai Vu
77,063,487
6,421,708
How do I always return the value from an enum as a string
<p>I am using Python 3.9.6. I am trying to write more readable code by using enums. The enums are being used for REST API output. In the example below the output from the enum MUST be a string and look like MON. In all caps. So in short I always want the output from the enum to be the value of the enum and be retu...
<python><python-3.x><enums>
2023-09-08 00:21:58
1
5,191
Keith
77,063,327
258,418
Python typehinting class decorator
<p>I am trying to implement the equivalent of the <code>@contextlib.contextmanager</code> decorator for classes. When I researched this topic, it became apparent that I was not the first needing these and used the approach from <a href="https://discuss.python.org/t/yield-based-contextmanager-for-classes/8453" rel="nofo...
<python><python-typing><mypy><pyright>
2023-09-07 23:14:11
0
5,003
ted
77,063,308
13,968,392
Equivalent of pandas .append() method, which allows method chaining
<p>Now that <code>append()</code> is removed in pandas 2.0, what is a short alternative to <code>append()</code> allowing method chaining? The <a href="https://pandas.pydata.org/docs/whatsnew/v2.0.0.html" rel="nofollow noreferrer">&quot;What’s new in 2.0.0&quot;</a> section of pandas says:</p> <blockquote> <p>Removed d...
<python><pandas><method-chaining>
2023-09-07 23:07:39
1
2,117
mouwsy
77,063,265
915,989
Credential and location issues with bigquery_datatransfer Python APIs
<p>I am an Owner of a GCP project. As such, in the BigQuery UI, it is trivially simple for me to copy a dataset (as a one-time operation) in the <code>us</code> multi-region as a new dataset with a different name that's also in the <code>us</code> multi-region.</p> <p>However, after scouring the docs, when I try to app...
<python><google-bigquery>
2023-09-07 22:51:58
0
1,193
aec
77,063,081
2,153,235
Does importing a namespace package also import the modules in the directory?
<p><a href="https://chrisyeh96.github.io/2017/08/08/definitive-guide-python-imports.html#importing-packages" rel="nofollow noreferrer">This</a> explanation of package imports says that importing a package <code>packB</code> without an <code>__init__.py</code> file doesn't do anything because <code>__init__.py</code> te...
<python><namespace-package>
2023-09-07 21:58:29
1
1,265
user2153235
77,063,075
1,199,464
How to avoid pytest mocked data conflicting between tests
<p>I have two commands (django management commands) which load data from an API, then do something based on the data they collect. So certain function names are the same for consistency, like <code>get_api_data</code> to gather data and <code>get_specific_event</code> to get an event from the data.</p> <p>In the test m...
<python><pytest><pytest-mock>
2023-09-07 21:57:17
0
12,944
markwalker_
77,063,027
2,192,824
How to convert the hour difference in timezone info to the abbreviated timezone name
<p>This is a followup question to</p> <p><a href="https://stackoverflow.com/questions/77056774/how-can-i-convert-the-time-stamp-with-timezone-info-to-utc-time-in-python/77056831#77056831">How can I convert the time stamp with timezone info to utc time in python</a></p> <p>I was able to get the time string like this &qu...
<python><timezone><timestamp-with-timezone>
2023-09-07 21:45:33
1
417
Ames ISU
77,062,958
7,169,895
Python QStyledItemDelegate - How do I properly align the text
<p>This question is almost identical to <a href="https://stackoverflow.com/questions/15778029/qstyleditemdelegatepaint-why-is-my-text-not-properly-aligned">this</a> question. However, the solution did not work for me and the question is an older version of Qt. I am using a <code>QStyledItemDelegate</code> to color cert...
<python><pyside6>
2023-09-07 21:27:18
1
786
David Frick
77,062,953
20,591,261
Exclude datetime from GroupBy sum
<p>I'm looking a way to use groupby on a dataframe that contains datetime64 format on some columns. But im having this error:</p> <pre><code> dfsum = df.groupby(['City']).sum() TypeError: datetime64 type does not support sum operations </code></pre> <p>I tried using:</p> <pre><code>desired = df.select_dtypes(include...
<python><pandas><dataframe><datetime>
2023-09-07 21:26:11
2
1,195
Simon
77,062,830
4,904,821
Fastest way to update a few million JSON values in postgres
<p>I have a Postgres table <code>User</code>. User has many attributes, including <code>settings</code>, a JSON (JSONB) dictionary.</p> <p>I have a CSV file with a few million user IDs, every one of which needs to update the dictionary with the following query:</p> <pre><code> UPDATE &quot;User&quot; SET...
<python><database><postgresql><database-performance>
2023-09-07 21:03:00
1
2,355
David Ferris
77,062,828
5,769,814
Shapely for pixel geometry
<p>I'm using the <code>shapely</code> library to handle my geometry-based computation. However, I'm working with integer geometry (such as pixels), which unfortunately means the <code>shapely</code> computations are off-by-one. For instance, normally this is the expected result:</p> <pre><code>&gt;&gt;&gt; import shape...
<python><python-3.x><properties><shapely>
2023-09-07 21:02:44
1
1,324
Mate de Vita
77,062,266
12,708,740
Pivot df without introducing NaNs
<p>I have a dataframe that I am trying to pivot. However, I am accidentally introducing NaNs in my rows.</p> <p>Code:</p> <pre><code>category = ['animal', 'animal', 'animal', 'fruit', 'fruit', 'fruit', 'veggie', 'veggie', 'veggie'] obj = ['animal_1', 'animal_2', 'animal_3', 'fruit_1', 'fruit_2', 'fruit_3', 'veggie_1', ...
<python><pandas><dataframe>
2023-09-07 19:12:26
1
675
psychcoder
77,062,239
835,523
Pandas read_csv skiprows=1 skips entire file
<p>I am calling pandas <code>read_csv(... skiprows=1)</code> and instead of skipping the first row it's skipping every line. I suspect it's because there's an issue with the line ending character it expects vs what is there.</p> <p>Does anyone know how to make this more robust?</p> <p>&lt;EDIT&gt; My file uses \r\n, bu...
<python><pandas>
2023-09-07 19:06:59
1
4,741
Steve
77,062,121
11,069,811
download with gdown a file in a folder with original name
<p>i am trying to download a file called file.zip from google drive with gdown in colab</p> <pre><code>!gdown url -O /out </code></pre> <p>When checking the out folder the file name is something like zips2dkqipb0ntmp instead of file.zip also try with</p> <pre><code>gdown.download(url, &quot;/out&quot;) </code></pre> <p...
<python><google-colaboratory>
2023-09-07 18:42:21
0
407
molo32
77,062,103
7,347,774
How to remove double quotes in all Snowpark DataFrame column names?
<p>I'm trying to save my Pandas DataFrame into Snowpark DataFrame with this code:</p> <blockquote> <pre><code>pdf = pd.DataFrame(...) pdf.columns = pdf.columns.str.replace(' ', '') sdf = session.createDataFrame(pdf) sdf.write.saveAsTable('MY_TABLE_NAME', mode=&quot;overwrite&quot;) </code></pre> </blockquote> <p>Column...
<python><pandas><snowflake-cloud-data-platform>
2023-09-07 18:39:37
1
1,055
Piotr K
77,062,080
1,996,760
Can't make Python Stockfish weaker
<p>I’ve written a chess software in Python which use Stockfish via this library: <a href="https://pypi.org/project/stockfish/" rel="nofollow noreferrer">https://pypi.org/project/stockfish/</a></p> <p>The software works and plays well. Too well actually…</p> <p>Mi idea was the app can offer a level / ELO choice, but I j...
<python><pypi><chess><python-chess><stockfish>
2023-09-07 18:35:08
3
305
igoemon
77,062,058
8,834,335
How to fill in a dataframe piecemeal in Python
<p>I have a dataframe Results with columns ID and Prediction, and a subfunction Calc that returns a dataframe of ID, pred for some subset of the IDs at a time. I would like to fill in Results as predictions come in. In R, this would be simply:</p> <pre><code>for x in cycles temp = Calc(x) Results[temp, on=&quot...
<python><pandas><merge>
2023-09-07 18:30:15
1
468
Sinnombre
77,061,999
2,550,810
Reducing augmented matrices in SymPy
<p>A common task in Linear Algebra (101) is to row-reduce an &quot;augmented matrix&quot; <code>[A | b]</code> where <code>b</code> is the right hand side of the linear system <code>Ax=b</code>. Often, we want to row reduce using symbolic variables for <code>b</code>. The entries in the row-reduced <code>b</code> wil...
<python><matrix><sympy>
2023-09-07 18:20:22
4
1,610
Donna
77,061,994
12,708,740
Generate combination of subset N from multiple lists
<p>I have 4 lists of elements and am trying to generate combinations of elements from those lists. Specifically, I'd like each combination to have 1 element from each list. However, I would only like each combination to have 3 elements in it. I would also like to record which elements are left out.</p> <p>Example lists...
<python><combinations><permutation>
2023-09-07 18:19:20
1
675
psychcoder
77,061,913
425,871
Why does quadratic interpolation on four points produce a cubic plot?
<p>Consider the following Python program:</p> <pre><code>import numpy as np from scipy.interpolate import interp1d import matplotlib.pyplot as plt # Define your four data points x = np.array([0, 1, 2, 3]) # x-coordinates of the points y = np.array([0, 1, 0, 1]) # y-coordinates of the points # Create the interpolati...
<python><scipy><interpolation>
2023-09-07 18:04:04
1
6,464
Steve
77,061,900
10,461,632
How to convert a dataframe into a tree data structure
<p>I have a pandas dataframe that I want to convert into a tree data structure so that I can then use something like <a href="https://mui.com/x/react-tree-view/" rel="nofollow noreferrer">TreeView</a> to show the tree structure in my application.</p> <p>Preferably, I want to use recursion to build the data structure. I...
<python><recursion>
2023-09-07 18:02:11
1
788
Simon1
77,061,724
1,471,980
how do you style data frame in Pandas
<p>I have this data frame:</p> <pre><code>df Server Env. Model Percent_Utilized server123 Prod Cisco. 50 server567. Prod Cisco. 80 serverabc. Prod IBM. 100 serverdwc. Prod IBM. 45 servercc. Prod Hitachi. 25 Avg ...
<python><pandas><pandas-styles>
2023-09-07 17:32:54
1
10,714
user1471980
77,061,446
630,544
Why does Python unittest auto-discovery not work when running in a subprocess?
<p>I'd like to be able to run Python's <code>unittest</code> module programmatically via a subprocess (e.g. <code>subprocess.Popen()</code>, <code>subprocess.run()</code>, <code>asyncio.create_subprocess_exec()</code>) and have it auto-discover tests.</p> <p>I do not want to run the tests by importing the <code>unittes...
<python><python-3.x><subprocess><python-unittest><autodiscovery>
2023-09-07 16:42:51
2
4,007
Shaun Scovil
77,061,416
9,271,275
groupby and compare timestamps in each group pandas
<p>i have the following pandas dataframe:</p> <pre class="lang-none prettyprint-override"><code>id | start | end | ---|---------------------|--------------------| TA | 2022-05-20 06:30:36 | 2022-05-20 09:58:52| TA | 2022-05-20 08:47:13 | 2022-05-20 08:57:47| TA | 2022-05-20 08:44:11 | 2022-...
<python><pandas><group-by>
2023-09-07 16:38:19
2
407
Hanif
77,061,401
4,299,527
How to properly use Modulo in Rabin Karp algorithm?
<p>I am trying to solve leetcode problem <a href="https://leetcode.com/problems/repeated-dna-sequences/description/" rel="nofollow noreferrer">187. Repeated DNA Sequences</a> using Rabin Karp algorithm with rolling hash approach. At first, I solved the problem without using any MOD operations like below.</p> <pre><code...
<python><hash><modulo><rabin-karp>
2023-09-07 16:36:08
1
12,152
Setu Kumar Basak
77,061,276
5,287,011
Dataframe filtering with multiple conditions
<p>I have a data frame (transfers) that I need to filter based on its comparison with another data frame (make_costs).</p> <p>transfers: <a href="https://i.sstatic.net/H8mCN.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/H8mCN.png" alt="enter image description here" /></a></p> <p>make_costs:</p> <p><a h...
<python><dataframe><filtering>
2023-09-07 16:14:58
1
3,209
Toly
77,061,268
7,169,895
Is there a way to access the WebExtension's history to access browser history (not session history)
<p>I saw <a href="https://stackoverflow.com/questions/22414735/save-and-load-browser-history-for-selenium">this</a> question which navigates the session history. It links to the WebExtension history object <a href="https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/history" rel="nofollow norefer...
<python><selenium-webdriver>
2023-09-07 16:13:44
0
786
David Frick
77,061,230
217,844
Python / asyncio: How to test GraphQL subscriptions?
<p>I have created a GraphQL API on AWS AppSync and I need to run tests to verify things work as expected.</p> <p>I have implemented a command line API client in Python with <a href="https://pypi.org/project/gql" rel="nofollow noreferrer"><code>gql</code></a> to interact with the API:</p> <ul> <li>I can run queries ✅</l...
<python><asynchronous><concurrency><graphql><python-asyncio>
2023-09-07 16:08:59
1
9,959
ssc
77,061,105
17,873,096
ValueError: The 'ydata_profiling' package was not installed in a way that PackageLoader understands
<p>i compiled an APP use <code>**Pyinstaller**</code> and got this error popup when open the compiled .exe file:</p> <pre><code>Traceback (most recent call last): File &quot;myuniverse.py&quot;, line 133, in &lt;module&gt; File &quot;&lt;frozen importlib._bootstrap&gt;&quot;, line 1176, in _find_and_load File &qu...
<python><jinja2><pyinstaller>
2023-09-07 15:50:06
1
366
vERISBABY.
77,061,093
3,246,693
Effeciently merging dataframe rows based on multiple columns and substrings
<p>I am working on analyzing sudo logs from a large number of *nix systems. One issue I've run into is that every now and then someone runs a massively long command(typically a bunch of concatenated commands) and sudo logs it as multiple events in syslog due to event size limiations in both sudo and syslog, so I am tr...
<python><python-3.x><pandas><dataframe>
2023-09-07 15:48:21
1
803
user3246693
77,060,997
4,877,683
Dynamic Image Ouputs in Gradio
<p>I want to create a Gradio Application which takes in a query as the input and displays image content in text outputs and corresponding Images in image outputs. You can assume there will always be 4 results to output.</p> <p>My code looks like this:</p> <pre><code> def gradio_fn(query): content, image_pat...
<python><image><visualization><huggingface><gradio>
2023-09-07 15:34:35
0
703
Danish Zahid Malik
77,060,949
850,781
Marking unused parameters in functions passed as arguments
<p>I have a higher order function:</p> <pre><code>def mymap(f,...): ... x = f(a, logger) ... </code></pre> <p>and I need to pass to it <code>f</code> that <em>needs</em> only one argument:</p> <pre><code>def bigfun(...): ... def f(a, logger): return a mymap(f, ...) ... </code></pre> ...
<python><pylint><optional-parameters><unused-variables>
2023-09-07 15:26:14
1
60,468
sds
77,060,929
5,274,291
Cognito not running custom auth challenge
<p>I have created in Cognito the following custom challenge triggers in Python. They are identical to the AWS ones but written in Python.</p> <p>Define auth challenge:</p> <pre class="lang-py prettyprint-override"><code>def lambda_handler(event, context): if (len(event['request']['session']) == 1 and event['request...
<python><boto3><amazon-cognito>
2023-09-07 15:23:06
1
1,578
João Pedro Schmitt
77,060,927
1,164,246
Selenium: getting the latest HTML code after external modification to the web page
<p>I have a web page that is modified externally. For example, new text is written to text boxes, checkmarks are checked, etc. I would imagine that these changes are reflected in the HTML code of the web page. If so, I would like to use <code>Selenium</code> to retrieve the most modified HTML of the web page that encom...
<python><html><selenium-webdriver>
2023-09-07 15:22:56
0
6,057
Daniel
77,060,689
1,354,517
how to ensure tensorflow gpu version is in use with docker image?
<p>I am using tensorflow 2.13 with help of docker file available within tensorflow models/research/object_detection/dockerfiles folder.</p> <p>The Docker file contents are</p> <pre><code>FROM tensorflow/tensorflow:latest-gpu ARG DEBIAN_FRONTEND=noninteractive # Install apt dependencies RUN apt-get update &amp;&amp; a...
<python><python-3.x><docker><tensorflow><tensorflow2.0>
2023-09-07 14:52:42
1
1,117
Gautam
77,060,452
12,730,406
color bar chart if by condition if values exist?
<p>I have this dataframe:</p> <pre><code>df = pd.DataFrame({ 'year': [2022,2022,2022,2022,2022,2023,2023], 'source': ['youtube', 'youtube', 'facebook', 'facebook', 'facebook', 'google', 'google'], 'score': [10,20,100,200,300,90,70], 'rating': ['small', 'large', 'small', 'medium', 'la...
<python><pandas><matplotlib>
2023-09-07 14:22:15
1
1,121
Beans On Toast
77,060,395
8,030,794
Get column based on changing bool values
<p>I have df like this</p> <pre><code>id bool 0 1 1 1 2 1 3 0 4 0 5 1 </code></pre> <p>And then i need to get сolumn with id and new bool value, where the value of bool changes. Like this :</p> <pre><code>id bool 0 1 3 0 5 1 </code></pre> <p>I can do this by using for, but is there an easier way to d...
<python><pandas><dataframe>
2023-09-07 14:13:21
1
465
Fresto
77,060,380
447,738
Find how many times a DataFrame cell value appears in another DataFrame, with a tolerance
<p>Given two DataFrames with the same columns.</p> <p>dfA</p> <pre> Index Price 0 10.21 1 12.21 </pre> <p>dfB</p> <pre> Index Price 0 10.21 1 10.24 2 11.32 3 12.21 </pre> <p>I want to add a column to dfA with the times that each value appears in dfB, but with a tolerance of, let's say, 1%.</p> <...
<python><pandas>
2023-09-07 14:11:13
4
2,357
cksrc
77,060,367
678,321
How can I use a Quarto variable to include a code block?
<p>I am trying to de-clutter a Quarto markdown document, using variables to include code blocks. I've created a <code>_variables.yml</code> file with</p> <pre><code>view: arvores: | {python} #| echo: false #| label: tbl-test #| tbl-cap: Volumes Markdown(tabulate(data,headers=data.columns,showind...
<python><yaml><markdown><quarto>
2023-09-07 14:09:33
1
1,708
Hugo
77,060,363
1,162,465
Adding OAuth2 token based authentication in my fast api code and swagger
<p>I am having a fastapi python application with a few get requests. I am having a ping-sso based identity provider. Now in all the apis in header Bearer token is being passed. How to do authentication and authorization(not required but will be informational) with the bearer token passed in the header.</p> <pre><code>f...
<python><oauth-2.0><swagger><fastapi>
2023-09-07 14:09:02
0
537
slaveCoder
77,060,310
10,440,076
About the inputs of the Wasserstein Distance W1
<p><strong>NOTE: I wrote the same question on <a href="https://math.stackexchange.com/questions/4765025/about-the-inputs-of-the-wasserstein-distance-w-1">https://math.stackexchange.com/questions/4765025/about-the-inputs-of-the-wasserstein-distance-w-1</a>, and since I did not get any comment or answer, I post it here, ...
<python><scipy><probability-distribution>
2023-09-07 14:02:05
1
305
Ommo
77,060,299
6,937,465
Join elements of a nested list based on condition
<p>I have a nested array called <code>element_text</code> in the form of for example:</p> <pre class="lang-py prettyprint-override"><code>[[1, 'the'], [1, 'quick brown'], [2, 'fox jumped'], [2, 'over'], [2, 'the'], [3, 'lazy goat']] </code></pre> <p>And would like to concatenate the elements in the array and return a ...
<python><arrays>
2023-09-07 14:00:58
5
426
Carolina Karoullas
77,060,140
16,253,390
Pandas pivot + date slicing: group by periods of time with partial overlap
<p>I am trying to find a way to 'pivot' my pandas dataframe, but keeping my index by sliced dates. The end goal is to create a range for each index in which each attributes and their values are matched.</p> <p>I reached the expected output using for loops and other non-vectorized ways, but I would be looking for a vect...
<python><pandas><group-by><python-datetime><pandas-explode>
2023-09-07 13:40:55
1
375
Odhian
77,060,066
7,656,163
return an error page from a subthread if the subthread fails
<p>As you can see from my below simplified code/flask app, I am starting a new thread, which calls a sagemaker endpoint, then the old thread redirects to a static page &quot;/completed&quot;, which says something like &quot;currently loading&quot;. If the sagemaker endpoint works correctly without error, were good to g...
<python><flask>
2023-09-07 13:28:51
0
326
bnicholl
77,060,037
4,957,620
Connection to Neo4j is failing with BoltSecurityError: [SSLCertVerificationError]
<p>I have a python script with the following code:</p> <pre><code>from neo4j import GraphDatabase from neo4j.debug import watch watch(&quot;neo4j&quot;) uri = &quot;neo4j+s://XXX.databases.neo4j.io:7687&quot; driver = GraphDatabase.driver(uri, auth=(&quot;neo4j&quot;, &quot;password&quot;)) </code></pre> <p>I run the ...
<python><python-3.x><neo4j><graph-databases>
2023-09-07 13:25:38
1
2,882
chris
77,059,938
22,466,650
What's the logic behind "cumsum" to make flags, compute counts and form groups?
<p>Without further ado, my input (s1) &amp; expected-output (df) are below :</p> <pre><code>#INPUT s1 = pd.Series(['a', np.nan, 'b', 'c', np.nan, np.nan, 'd', np.nan]).rename('col1') #EXPECTED-OUTPUT s2 = pd.Series([1, 2, 3, 3, 4, 4, 5, 6]).rename('col2') # flag the transition null&gt;notnull or vice-versa s3 = pd.Ser...
<python><pandas>
2023-09-07 13:12:28
1
1,085
VERBOSE
77,059,740
12,458,212
PySpark - How to 'sc.parallelize' a function that yields a generator (Pickling Error)?
<p>My specific use case is quite different, but this simple example is able to replicate my issue.</p> <pre><code>def foo(inp): yield 2*inp def bar(result): x = next(result) return x inp = range(0,10000) results = [] for f in inp: results.append(foo(f)) rdd_sim = sc.parallelize(results, numSlices=4) resu...
<python><apache-spark><pyspark><databricks>
2023-09-07 12:45:31
1
695
chicagobeast12
77,059,737
22,496,572
Adding tensors rows to a tensor given possibly repeating row indices
<p>In PyTorch, is there a batch version of the following (in-place) operations?</p> <pre><code># v is a tensor of shape (n, m) # w is a tensor of shape (k, m) # indices is a tensor of shape (k, ) def f_sum(v, w, indices): for i, w0 in zip(indices, w): v[i] += w0 def f_average(v, w, indices): for i, w0 in ...
<python><pytorch>
2023-09-07 12:44:35
1
371
Sasha
77,059,654
8,256,981
In numpy genfromtxt, how to use `names = True`?
<p>This is a follow up question to my previous question:</p> <p><a href="https://stackoverflow.com/questions/77053670/in-numpy-genfromtxt-missing-values-filling-values-excludelist-deletechars-an">In numpy genfromtxt, missing_values, filling_values, excludelist, deletechars and replace_space are not working properly</a>...
<python><numpy>
2023-09-07 12:33:19
2
491
maxloo
77,059,630
16,420,204
Python Polars: Conditional Join by Date Range
<p>First of all, there seem to be some similar questions answered already. However, I couldn't find this specific case, where the conditional columns are also part of the join columns:</p> <p>I have two dataframes:</p> <pre><code>df1 = pl.DataFrame({&quot;timestamp&quot;: ['2023-01-01 00:00:00', '2023-05-01 00:00:00', ...
<python><join><python-polars>
2023-09-07 12:29:06
4
1,029
OliverHennhoefer
77,059,569
11,325,478
WSGI vs ASGI server with hybrid sync/async Django app
<p>I have a Django app with multiple async views doing some http requests, but some part are still synchronous like most of the middlewares. So there will always be a small performance penalty with the sync/async switch when handling incoming requests.</p> <p>It is possible to run this app on both WSGI or ASGI gunicorn...
<python><django><asynchronous><gunicorn><asgi>
2023-09-07 12:20:57
0
338
Grum
77,059,419
10,232,932
split up column value into empty column values in a dataframe
<p>I am having a dataframe <code>df</code>:</p> <pre><code>columnA columnB columnC A A 10 A B NaN A C 20 B A 30 B C NaN A D NaN D C 15 </code></pre> <p>How can I fill the <code>NaN</code>values in that case, that the next...
<python><pandas>
2023-09-07 11:59:53
2
6,338
PV8
77,059,354
3,801,530
Pydantic with a field of type ENUM
<p>I want to transform to lowercase, the value that comes to the model of a field that is of type ENUM, before it is assigned.</p> <p>I show an example.</p> <pre class="lang-py prettyprint-override"><code>class DeviceType(str, Enum): BASIC = &quot;basic&quot; PROFESIONAL = &quot;profesional&quot; class Device...
<python><pydantic>
2023-09-07 11:51:02
2
890
RodriKing
77,059,083
11,790,979
Unexpected behaviour when re-organising directory (python, shutil)
<p>I have a function that reorganises a directory of locally saved data, but its behaving in an unexpected way. There are 3 folders, <code>current</code>, <code>previous</code> and <code>tma</code> (two months ago) and with the function below I am expecting that it will delete the existing <code>tma</code>, rename <cod...
<python><shutil>
2023-09-07 11:12:06
1
713
nos codemos
77,059,057
257,742
Adding multiple LoRa safetensors to my HuggingFace model in Python
<p>Suppose I use this script to load one fine-tuned model: (example taken from <a href="https://towardsdatascience.com/hugging-face-diffusers-can-correctly-load-lora-now-a332501342a3" rel="nofollow noreferrer">https://towardsdatascience.com/hugging-face-diffusers-can-correctly-load-lora-now-a332501342a3</a>)</p> <pre><...
<python><model><safe-tensors><diffusers>
2023-09-07 11:09:29
2
1,960
D.Giunchi
77,058,992
17,561,414
alternative of koalas in pyspark? use dataframe in sql statement databricks
<p>My goal is to use the <code>df</code> in the SQL statement like below</p> <p>creating <code>df</code></p> <pre><code> df = spark.readStream.format(&quot;delta&quot;) \ .option(&quot;readChangeFeed&quot;, &quot;true&quot;) \ .table(&quot;mdp_prd.bronze.nrq_customerassetproperty_autoloader_nodups&quot;) </...
<python><apache-spark><pyspark><databricks>
2023-09-07 11:01:50
0
735
Greencolor
77,058,822
8,511,822
How to specify the Python version such that it is added to the wheel file name?
<p>I have this in my pyproject.toml file:</p> <pre class="lang-ini prettyprint-override"><code>requires-python = &quot;&gt;=3.8.1,&lt;3.9&quot; </code></pre> <p>I know this does not specify what Python version is added to the wheel file name, but I cannot figure out how to do it using <a href="https://hatch.pypa.io/lat...
<python><hatch>
2023-09-07 10:39:34
0
1,642
rchitect-of-info
77,058,608
7,657,658
Disable Automatic Code Suggestion in Jupyter for magic and path
<p>Whenever I write a code in Jupyter Lab (or Notebook), it prompts annoying suggestions regarding magics and paths, even without pressing TAB. Example:</p> <p><a href="https://i.sstatic.net/0zaST.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/0zaST.png" alt="annoying prompt" /></a></p> <p>This usually ...
<python><jupyter-notebook><jupyter><jedi>
2023-09-07 10:07:04
0
1,156
MCMZL
77,058,582
2,912,349
Reversibly disconnect matplotlib's own key press handling
<p>I am trying to temporarily and reversibly disconnect matplotlib's own key press events, i.e. the keyboard shortcuts (&quot;s&quot; -&gt; save, &quot;q&quot; -&gt; quit, etc).</p> <p>This used to be the way to do this:</p> <pre class="lang-py prettyprint-override"><code>fig.canvas.mpl_disconnect(fig.canvas.manager.ke...
<python><matplotlib>
2023-09-07 10:03:52
1
12,703
Paul Brodersen
77,058,441
765,269
pass memoryview to win32.ReadFile for Pyserial readinto() function
<p>I want to create a proper readinto function for the pyserial package (for windows). pyserial implements readinto() by calling read() which defeats the purpose of readinto. Adapting the <a href="https://github.com/pyserial/pyserial/blob/master/serial/serialwin32.py" rel="nofollow noreferrer">existing read() function<...
<python><pyserial>
2023-09-07 09:44:43
1
422
user765269
77,058,416
471,478
An argument that can be a combination of enum.IntFlag
<p>Given an <code>enum.IntFlag</code>:</p> <pre><code>class Flag(enum.IntFlag): FOO = 1 BAR = 2 QUX = 4 </code></pre> <p>Can I express a type that says &quot;Flag or any combination of Flags&quot;?</p> <pre><code>def func(accepts: CombinationOf[Flag]): ... </code></pre> <p>such that all these would be v...
<python><enums><python-typing>
2023-09-07 09:41:36
1
12,364
scravy
77,058,049
951,139
Random integer generation performance optimization
<p>I am looking to generate random integers on the interval [0, n) as fast as possible:</p> <pre><code>from random import Random rand = Random(123) def rand_func(max: int, random: Random): return int(random.random() * max) for a in range(10_000_000): # perf_counter 9.7s ax = rand_func(456, ra...
<python><random>
2023-09-07 08:54:31
1
2,742
TVOHM
77,057,967
4,530,214
How to enable Legend picking with a scatter plot
<p>The following example <a href="https://matplotlib.org/stable/gallery/event_handling/legend_picking.html" rel="nofollow noreferrer">from the matplotlib doc</a> shows how to make a legend &quot;pickable&quot;, such that you can toggle the lines visibility by clicking on their legend:</p> <pre class="lang-py prettyprin...
<python><matplotlib><legend>
2023-09-07 08:43:54
0
546
mocquin
77,057,836
16,648,033
Reason to return updated stack along with top element from pop() method
<p><a href="https://github.com/google/jax/blob/fae98733aa08d407ce678d6034f4a888171fa1c5/jax/_src/lax/stack.py#L63" rel="nofollow noreferrer">This</a>:</p> <pre><code> def pop(self) -&gt; tuple[Any, Stack]: &quot;&quot;&quot;Pops from the stack, returning an (elem, updated stack) pair.&quot;&quot;&quot; </code></pr...
<python><stack><jax>
2023-09-07 08:24:09
1
409
vtm11
77,057,832
17,561,414
readstream display dataframe does nto work
<p>I have loaded the delta bronze table using autoloader in databricks.</p> <p>now I want to read this table and display it to see. But Im not I get the error when <code>display(df)</code> runs.</p> <p>my code:</p> <pre><code>df= spark.readStream.format(&quot;delta&quot;) \ .option(&quot;readChangeFeed&quot;, &quot;t...
<python><apache-spark><pyspark><azure-databricks>
2023-09-07 08:23:53
1
735
Greencolor
77,057,794
10,232,932
conditional line color results in ValueError
<p>I am trying to plot a linegraph with matplotlib.pytplot and have a dataframe df with the shape <code>(42,7)</code>. The dataframe has the following structur (only showing relevant columns):</p> <pre><code>timepoint value point 2021-01-01 10 0 2021-02-01 20 0 .... 2021-11-01 10 0 2021-12-01 ...
<python><pandas><matplotlib><colors><valueerror>
2023-09-07 08:17:30
2
6,338
PV8
77,057,654
1,725,871
Add Content-Type header to Very simple SimpleHTTPRequestHandler without extending the class
<p>I have an extremely simple http server setup for local testing:</p> <pre class="lang-py prettyprint-override"><code>#!/usr/bin/env python from functools import partial from http.server import SimpleHTTPRequestHandler, test import os HTTP_DIR = os.getcwd() SimpleHTTPRequestHandler.extensions_map = {k: v + ';charset=...
<python><simplehttpserver><simplehttprequesthandler>
2023-09-07 07:55:35
1
3,442
JoSSte
77,057,463
967,501
How do I get the amount of bandwidth used during the execution of a Linux program?
<p>I need to understand how much bandwidth is used by a program which I execute from a shell on Linux, via subprocess.run in Python.</p> <p>Maybe a solution already exists, something similar to <code>time</code>?</p> <pre><code>petur@petur:~$ time foobar foobar 0.00s user 0.00s system 80% cpu 0.003 total </code></pre>...
<python><c><python-3.x><linux>
2023-09-07 07:32:17
1
4,503
Pétur Ingi Egilsson
77,057,444
3,104,974
Plot sklearn's DecisionBoundaryDisplay for Classifier With More Than 2 Features
<h2>Observation</h2> <p>There are <a href="https://stackoverflow.com/questions/76876844/color-regions-in-a-scatter-plot/76877301#76877301">examples</a> using the <a href="https://scikit-learn.org/stable/auto_examples/datasets/plot_iris_dataset.html" rel="nofollow noreferrer">iris dataset</a> of how to plot decision bou...
<python><plot><scikit-learn><classification>
2023-09-07 07:29:27
0
6,315
ascripter
77,057,362
350,685
Python code stops updating Mysql database randomly
<p>I am trying to learn Python by building myself a trading bot kind of application. This also uses a mysql database. I have a class for handling all database operations. The class is structured like so:</p> <pre><code>class BotDB: def __init__(self, dbUsername, dbPassword): print(&quot;Initializing database.&...
<python><mysql>
2023-09-07 07:16:27
0
10,638
Sriram
77,057,081
5,563,977
In a Python Poetry project, what's the difference between {include = "b", from = "a"} and {include = "a/b"} in the packages section?
<p>I'm trying to build a Python package using Poetry and have some sub-packages I need to include.</p> <p>Using the <code>include</code> directive in pyproject.toml, I'm struggling to understand what's the difference between this:</p> <pre class="lang-ini prettyprint-override"><code>[tool.poetry] ... packages = [ {...
<python><python-3.x><python-packaging><python-poetry>
2023-09-07 06:31:03
0
1,085
MatanRubin
77,056,859
464,618
How do I create a dataset with a file resource on the Humanitarian Data Exchange (HDX) using the HDX Python API library?
<p>I would like to create a dataset the <a href="https://data.humdata.org/" rel="nofollow noreferrer">Humanitarian Data Exchange</a> (HDX) with a single resource, a csv file. I would like to use the <a href="https://github.com/OCHA-DAP/hdx-python-api" rel="nofollow noreferrer">HDX Python API</a>. I have looked at the <...
<python><dataset><hdx>
2023-09-07 05:39:07
1
1,352
mcarans
77,056,770
2,216,718
Pandas Convert a column in the format "yyyy-MM-ddTHH:mm:ss.SSSZ" to datetime object
<p>I have a dataframe which has a column containing strings of the format &quot;yyyy-MM-ddTHH:mm:ss.SSSZ&quot;</p> <p>When I do the following operation</p> <pre><code>df[&quot;updatedTimeDateTime&quot;] = pd.to_datetime(df[&quot;last_update_date_time&quot;], format='%Y-%m-%dT%H:%M:%S.%fZ') </code></pre> <p>I get the fo...
<python><pandas><datetime>
2023-09-07 05:15:20
2
862
Mohit Shah
77,056,731
13,060,649
Django istartswith performance
<p>I have a model with column &quot;name&quot; and I am running query with istartswith and I am using postgresql. I have added <code>django.db.models.Index</code> with Postgresql opclass</p> <pre><code>Index(fields=('name',), name=&quot;partial_name_pat_idx&quot;, opclasses=(&quot;varchar_pattern_ops&quot;,), conditio...
<python><django><postgresql><django-models><indexing>
2023-09-07 05:04:09
1
928
suvodipMondal
77,056,468
7,035,448
Numba Dispatch error when Number of keyword args > 3 for nested numba calls
<p>This error happens when defining function <code>*</code> is used. I can start with three function definition cases, The first two cases are passed, and the third one which is a minor modification of the second test case fails. Maybe * are not supported however the error is interesting would like to understand the ca...
<python><debugging><numba><python-typing>
2023-09-07 03:35:00
0
1,845
eroot163pi
77,056,398
5,179,643
List comprehension to create a Pandas dataframe column based on values of 4 other other columns
<p>I have a Pandas dataframe that looks like this:</p> <pre><code>df = pd.DataFrame({ 'company_1': ['McDonalds', 'Mercedes', 'Apple'], 'company_2': ['Wendys', 'BWM', 'Microsoft'], 'company_1_price' : [3, 1, 4], 'company_2_price' : [2, 8, 3] }) </code></pre> <p>I'd like to add a column to this <code>df</...
<python><pandas>
2023-09-07 03:16:00
1
2,533
equanimity
77,056,341
1,471,980
how do you modify styled data frame in Pandas
<p>I have this data frame:</p> <pre><code>df Server Env. Model Percent_Utilized server123 Prod Cisco. 50 server567. Prod Cisco. 80 serverabc. Prod IBM. 100 serverdwc. Prod IBM. 45 servercc. Prod Hitachi. 25 Avg ...
<python><pandas><pandas-styles>
2023-09-07 02:58:38
1
10,714
user1471980
77,056,176
11,124,121
How to use with_columns in LazyGroupBy object in polars?
<p>I am trying to calculate the difference of lag variable group by <code>id</code> variable. However,</p> <p>when I tried to run the following code:</p> <pre><code>ad.v2.group_by('id').with_columns( diff = pl.col('Movement_Time_clear') - pl.col('Movement_Time_clear').diff() ) </code></pre> <p>A warning was popp...
<python><python-polars>
2023-09-07 02:02:04
1
853
doraemon
77,056,099
5,179,643
How to get the max count of groups using Pandas groupby, using alphabetical order to break any ties
<p>I have a Pandas dataframe that looks like this:</p> <pre><code>import pandas as pd df = pd.DataFrame({ 'person': ['Mike', 'Mike', 'Mike', 'Bob', 'Bob', 'Bob', 'Susan', 'Cindy', 'Paul', 'Paul', 'Jon', 'Larry', 'Cindy', 'Larry', 'Larry', 'David', 'David', 'David', 'Eric', 'Cindy', 'Paul'], 'city': ['New York'...
<python><pandas><group-by>
2023-09-07 01:37:52
3
2,533
equanimity
77,056,061
1,522,308
Problem implementing delays using elapsed time (timestamps)?
<p>My use case requirements:</p> <ul> <li>Requirement 1: Loop through Task A, Task B, Task C</li> <li>Requirement 2: Skip Task A if performed within the last 5 minutes.</li> <li>Requirement 3: If Task A not performed within the last 5 minutes, do not skip during the next loop (or add Task A to a queue?)</li> </ul> <p>I...
<python><delay><sleep>
2023-09-07 01:24:23
0
342
torpedo51
77,056,035
5,319,180
Why would you want to create more than one event loops in asyncio?
<p>Why not just use the default one always? are there any usecases for creating multiple event loops?</p>
<python><asynchronous><python-asyncio>
2023-09-07 01:11:18
2
429
D.B.K
77,056,021
8,869,570
How to get the most recent dated file (filename of the form YYYY-MM-DD-filename.txt) in a directory
<p>Inside a directory <code>dir2search</code>, I have many files of the form</p> <pre><code>YYYY-MM-DD-orders.txt </code></pre> <p>where YYYY is the 4 digit year, MM is the 2 digit month (01 for January, 02 for February, etc..) and DD is the 2 digit day of the month (01 for the first, 02 for the second, etc..).</p> <p>...
<python>
2023-09-07 01:08:51
2
2,328
24n8
77,056,014
5,437,918
How to import entire own module in Python as an alias?
<p>I have a directory structure like the following:</p> <pre><code>my-package/ config/ __init__.py constants.py logging.py app.py </code></pre> <p>From within <code>config/__init__.py</code>, I'd like to do an import along the lines of:</p> <pre class="lang-py prettyprint-override"><code...
<python><python-import><relative-import>
2023-09-07 01:06:51
1
1,070
Jethro Cao
77,055,917
5,319,180
Why use SQS/AMQ in python when you can just use asyncio.create_task?
<p>Given the downside that you're now unable to independently scale your API service and workers, you still do have the upside of lesser network latencies since nothing needs to be enqueued into the task queue, and nothing needs to be polled from a remote task queue.</p> <p>Are there any notable reasons to still use SQ...
<python><asynchronous><celery><python-asyncio><amazon-sqs>
2023-09-07 00:24:52
0
429
D.B.K
77,055,702
5,179,643
How to add non grouped column to the output of Pandas groupby()
<p>I have a Pandas dataframe df that looks like this:</p> <pre><code>import pandas as pd df = pd.DataFrame({ 'student': ['Bob', 'Sally', 'Rich', 'Melissa', 'Len', 'Sue', 'Jon', 'Sandy', 'William', 'Sara'], 'year': [2020, 2020, 2020, 2021, 2021, 2021, 2021, 2022, 2022, 2022], 'gpa': [2.9, 3....
<python><pandas><group-by>
2023-09-06 23:03:38
3
2,533
equanimity
77,055,665
15,491,705
plt.show adds extra legend labelspacing between rows if there are subscripts, but fig.savefig does not?
<p>When I plot a figure and legend using the following code</p> <pre><code>import matplotlib.pyplot as plt # Create sample data x = [1, 2, 3, 4] y1 = [1, 2, 3, 4] y2 = [4, 3, 2, 1] y3 = [2, 3, 2, 1] # Create the main figure fig, ax = plt.subplots() # Plot the lines line1, = ax.plot(x, y1, label='$\\mathdefault{H_...
<python><matplotlib>
2023-09-06 22:51:42
1
321
Maurits Houck
77,055,261
12,415,855
Python - Email-Sending with smtplib for yahoo not possible?
<p>i try to send an email using the following code -</p> <pre><code>from email.mime.text import MIMEText import smtplib from dotenv import load_dotenv import os import sys if __name__ == '__main__': path = os.path.abspath(os.path.dirname(sys.argv[0])) fn = os.path.join(path, &quot;.env&quot;) load_dotenv(fn) ...
<python><email><smtplib>
2023-09-06 20:59:35
0
1,515
Rapid1898
77,055,222
3,832,377
How do I "wrap" a Python function without losing type information?
<p>I'm trying to provide some higher level logic to a Python function that calls an external library, e.g:</p> <pre class="lang-py prettyprint-override"><code>class Example(): def my_func(self, *args, **kwargs): return library.func(*args, **kwargs) </code></pre> <p>Depending on the result of the Python library, w...
<python><types>
2023-09-06 20:52:21
0
8,977
Alexander Craggs
77,055,063
2,058,333
PostgreSQL changes table name to lowercase
<p>I am running this command with <code>sqlalchemy==1.4.31</code>.</p> <pre><code>with get_postgres_db() as postgres_session: r = postgres_session.execute(&quot;SELECT * FROM shop.Clients;&quot;) </code></pre> <p>and it fails with</p> <pre><code>ProgrammingError: (psycopg2.errors.UndefinedTable) relation &quot;sh...
<python><postgresql><sqlalchemy>
2023-09-06 20:19:19
0
5,698
El Dude
77,054,882
2,225,895
Changing color of tkinter button
<p>I want to update the background color of a button when I have clicked on it. But nothing happens. Instead I tried this minimal code snippet, but only the foreground is changed, not the background:</p> <pre><code>from tkinter import * def demoColorChange(): button1.configure(bg='red', fg='blue') parent = Tk() par...
<python><tkinter>
2023-09-06 19:49:21
0
1,916
El_Loco
77,054,769
5,091,329
SQLAlchemy 1:1 mapping
<p>Using python and SQLAlchemy 2.0 with PostgreSQL, I am trying to create a simple one to one mapping between two tables. The code is:</p> <pre><code>class Base(orm.DeclarativeBase): pk: orm.Mapped[uuid.UUID] = orm.mapped_column( primary_key=True, default=uuid.uuid4, ) class AAA(Base): __tablenam...
<python><sqlalchemy>
2023-09-06 19:32:34
0
1,437
Jim Archer
77,054,713
10,225,070
Need help making a 3D surface plot a 4D surface plot with color as separate dimension
<p>As the title says. I have tried so many different ways of doing this. I have 4 vectors of length 48.</p> <pre><code>X: [ 25 25 25 25 25 25 50 50 50 50 50 50 75 75 75 75 75 75 100 100 100 100 100 100 125 125 125 125 125 125 150 150 150 150 150 150 175 175 175 175 175 175 200 200 200 200 200 200] Y:...
<python><matplotlib><surface><matplotlib-3d><4d>
2023-09-06 19:18:37
1
413
darrahts
77,054,593
1,311,449
File manipulation through Microsoft Graph API
<p>I have an Excel inside a Sharepoint which I'm perfectly able to read making a call to Graph API from Python using msal library. I'm stuck in trying to update this file. I gave the application the <code>Files.ReadWrite.All</code> permission and I can see it decoding the token through <a href="https://jwt.ms" rel="no...
<python><microsoft-graph-api><azure-ad-msal>
2023-09-06 18:55:11
1
656
Mark
77,054,449
3,158,876
Connecting to MongoDB with requests library
<p>I have a situation where I need to pass some data to MongoDB but am limited in the libraries I can access and so can only use requests. This is what I have so far, but it's always throwing a 'No connection adapters were found' error. I've confirmed that I have manual access to the server. I've also tried this bot...
<python><mongodb><python-requests>
2023-09-06 18:31:07
0
315
Benjamin Brannon
77,054,430
1,471,980
How do I change the background color of a cell in Pandas?
<p>I have this DataFrame:</p> <pre><code>Server Env. Model Percent_Utilized server123 Prod Cisco. 50 server567. Prod Cisco. 80 serverabc. Prod IBM. 100 serverdwc. Prod IBM. 45 servercc. Prod Hitachi. 25 Avg 6...
<python><pandas>
2023-09-06 18:27:32
3
10,714
user1471980
77,054,285
11,748,924
convert pip requirements.txt to conda requirements
<p>For <code>pip</code>, required libraries is stored in <code>requirements.txt</code>.</p> <p>But at same workspace, I'm using <code>conda virtual environtment</code>.</p> <p>Here is my <code>requirements.txt</code></p> <pre><code>flask werkzeug Jinja2 watchdog mongoengine pyjwt opencv-stubs facenet-pytorch Pillow num...
<python><pip><conda>
2023-09-06 18:02:52
1
1,252
Muhammad Ikhwan Perwira
77,054,224
5,437,090
Pandas vs Dask sort columns and index of string and number
<p><strong>Given</strong>:</p> <p>Small sample pandas dataframe:</p> <pre><code>import pandas as pd import numpy as np import dask.dataframe as dd df = pd.DataFrame({&quot;usr&quot;: [&quot;ip1&quot;, &quot;ip7&quot;, &quot;ip12&quot;, &quot;ip4&quot;], &quot;colB&quot;: [1, 2, 3, 0], &quot;ColA&quot;: [3, np.nan, 7, ...
<python><pandas><dask>
2023-09-06 17:51:02
1
1,621
farid
77,054,156
13,350,341
Render forms conditionally on checked radio button - Jinja2 templates - FastAPI
<p>I'm pretty new to both <em>Jinja templating</em> and <em>javascript</em>; I'm trying to build an application in FastAPI which renders some Jinja templates.</p> <p>I have added a pair of radio buttons to my template and I would like one of the two to trigger the rendering of a couple of <em>forms</em>.</p> <p>Followi...
<javascript><python><jinja2><fastapi>
2023-09-06 17:39:01
1
3,157
amiola
77,054,031
595,305
Sending data in both directions between Python and lengthy Rust module?
<p>Pleasantly surprised at the ease of integrating Rust modules into a calling Python app using PyO3.</p> <p>But the next thing I want to understand is whether it's possible to exchange data between a potentially long-running Rust module and the Python code. A typical case would be where Python is handling the GUI (e.g...
<python><multithreading><rust><signals><pyo3>
2023-09-06 17:12:26
1
16,076
mike rodent