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,270,101
1,088,076
Default to a derived unit on output in python pint
<p>Is it possible to default the output if a unit with pint to a derived unit? For example, if I compute a pressure by dividing a force and area, I would like it to display in &quot;psi&quot; by default.</p> <pre><code>import pint ureg = pint.UnitRegistry() ureg.default_format = &quot;.1f~&quot; s = 42*ureg.pound_force...
<python><pint>
2023-10-11 03:39:44
1
1,911
slaughter98
77,269,970
8,734,514
How to classify segments of time series data
<p>I have time series data being captured from the accelerometer of an android phone. I have added a class column so that I can label the class of the data. The data has a binary classification, 0 for false, and 1 for true. The time series data has continuous segments where the entire segment together should be classif...
<python><tensorflow><keras><neural-network><lstm>
2023-10-11 02:51:31
1
656
Kevin Gardenhire
77,269,875
395,857
How can I change some properties of a textbox when created with gr.Interface?
<p>I'm following the basic Gradio interface from the <a href="https://www.gradio.app/docs/interface" rel="nofollow noreferrer">Gradio documentation</a>:</p> <pre><code>import gradio as gr def greet(name): return &quot;Hello &quot; + name + &quot;!&quot; #demo = gr.Interface(fn=greet, inputs=&quot;text&quot;, outp...
<python><gradio>
2023-10-11 02:15:58
1
84,585
Franck Dernoncourt
77,269,865
13,635,877
Using SLSQP for finding the maximum sharpe ratio portfolio, getting nan as portfolio volatility
<p>I don't really understand what SLSQP is doing when I run this, the denominator of the objective function is always nan (as seen in the callback). When I plug in x0 into the denominator, I get an actual number so I don't understand why its nan in the callback right off the bat?</p> <pre><code>from scipy.optimize impo...
<python><optimization><scikit-learn><minimize>
2023-10-11 02:10:31
1
452
lara_toff
77,269,857
21,575,627
What is a more optimal algorithm for this problem?
<p>Suppose you have an array <code>A</code> of <code>N</code> integers. In one round, you make changes as follows (based on the array snapshot at the beginning of the round):</p> <ul> <li>-= 1 if greater than both adjacent (on both sides)</li> <li>+= 1 if less than both adjacent (on both sides)</li> </ul> <p>The one on...
<python><algorithm><performance><data-structures><time-complexity>
2023-10-11 02:07:52
0
1,279
user129393192
77,269,753
360,869
passing `apify_api_token` as a named parameter
<p>I am new to python, I am trying to pass the API key to apifywrapper here in the notebook. I am getting this error:</p> <blockquote> <p>ValidationError Traceback (most recent call last) in &lt;cell line: 9&gt;() 7 api_token = userdata.get(&quot;apify&quot;) 8 ----&gt; 9 apify = ApifyWrapper...
<python><google-colaboratory><apify>
2023-10-11 01:25:21
1
457
ilteris
77,269,618
19,123,103
Why does an operation on a large integer silently overflow?
<p>I have a list that contains very large integers and I want to cast it into a pandas column with a specific dtype. As an example, if the list contains <code>2**31</code>, which is outside the limit of int32 dtype, casting it into dtype int32 throws an Overflow Error, which lets me know to use another dtype or handle ...
<python><pandas><long-integer>
2023-10-11 00:35:19
5
25,331
cottontail
77,269,443
1,410,221
How to add custom attributes to a Python list?
<p>I'm trying to associate additional data with a Python list. Ideally, I'd like to add custom attributes to a list object, similar to how you'd add attributes to a custom class. For example:</p> <pre class="lang-py prettyprint-override"><code>a = [1, 2, 4, 8] a.x = &quot;Hey!&quot; # I'd like this to work without err...
<python><list><setattr><python-builtins>
2023-10-10 23:15:29
0
4,193
HappyFace
77,269,418
525,916
Update data assigned to global variable (outside callback) once a day
<p>I am creating a read-only Plotly Dash dashboard that uses a lot of data. It involves a lot of database reads and transformations which usually takes up to 1 minute. To avoid user waiting this long on every interaction, I am performing these steps outside the callbacks and assign the data to a global variable. These ...
<python><plotly-dash>
2023-10-10 23:07:03
1
4,099
Shankze
77,269,319
1,394,336
Why are distinct multiprocessing.Value objects pointing to the same value?
<p>In the following program, two processes are created. Each receives <em>it's own</em> <code>multiprocessing.Value</code> object. Somehow, the two processes still influence each other. Why?</p> <p>I would expect the two processes to deadlock: The first process can increment the counter once (it's initially 0) but then...
<python><multiprocessing><python-multiprocessing>
2023-10-10 22:36:46
1
2,057
Christopher
77,269,228
6,814,713
SQLAlchemy query distinct values from filtered many to many relationship
<p>I have been struggling to put together the correct query for this and need some help. I have two tables with a many-to-many relationship. I would like to put together a performant query for all distinct values in table B using the filtered values from table A:</p> <pre class="lang-py prettyprint-override"><code>asso...
<python><sqlalchemy><orm><many-to-many>
2023-10-10 22:10:45
1
2,124
Brendan
77,269,168
678,572
Inconsistent behavior of Sklearn's precision_score when manual cross-validation is performed vs. cross_val_score
<p>I'm trying to use <code>precision_score</code> with <code>np.nan</code> for the <code>zero_division</code>. It's not working with <code>cross_val_score</code> but working when I do manual cross-validation with the same pairs.</p> <p>Here's the data files to reproduce: <a href="https://github.com/scikit-learn/scikit...
<python><numpy><machine-learning><scikit-learn><nan>
2023-10-10 21:56:09
1
30,977
O.rka
77,269,011
13,860,719
How to get the callable function defined by exec() in Python?
<p>Say I want to have a function <code>exec_myfunc</code> that can execute any user-defined function with an input value of 10. The user is supposed to define the function by a <strong>string</strong> as shown below:</p> <pre><code>func1_str = &quot;&quot;&quot; def myfunc1(x): return x &quot;&quot;&quot; func2_st...
<python><python-3.x><string><function><exec>
2023-10-10 21:17:27
2
2,963
Shaun Han
77,268,984
7,542,939
Search for jobs with Cloud Talent Solution API in Python
<p>I cannot find any useful documentation whatsoever on how to use the Google Cloud Talent Solution API in Python to perform even a basic query. Right now I am trying:</p> <pre><code>from google.cloud import talent credential_path = &quot;creds_path/creds.json&quot; os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = crede...
<python><google-cloud-platform><google-cloud-talent-solution>
2023-10-10 21:10:44
1
1,831
snapcrack
77,268,954
2,733,436
Using prefix sum to calculate scores of 2 robots in a 2d array
<p><strong>Background</strong></p> <p>I am trying to solve the following <a href="https://leetcode.com/problems/grid-game/description/" rel="nofollow noreferrer">leetcode problem</a>. I have written the below function and it seems to be passing the sample test cases.</p> <p><strong>My Code</strong></p> <pre><code>def g...
<python><arrays><algorithm><data-structures>
2023-10-10 21:06:34
1
1,658
user1010101
77,268,908
468,455
Updating Google Sheet with API & Python with less rows than original
<p>I'm building a script that writes a deployment log for all our products. I have a Google sheet that holds the data. The first sheet of that spreadsheet is titled &quot;Recent Releases&quot; and as it says, holds the most recent releases (as of when the script runs). Most times there will be more or less rows than th...
<python><google-sheets><google-sheets-api>
2023-10-10 20:56:32
1
6,396
PruitIgoe
77,268,899
8,521,346
Strange Roundrobin Style Sorting Algorithem Name
<p>I have been using the more_itertools <code>roundrobin</code> function to &quot;fairly&quot; distribute to workers. (literal ones, not Celery)</p> <p>which would look like this.</p> <p><code>list(roundrobin('AAA', 'BB', 'CC')) == ['A', 'B', 'C', 'A', 'B', 'C', 'A']</code></p> <p>This all looks well and good to me, bu...
<python>
2023-10-10 20:53:55
0
2,198
Bigbob556677
77,268,771
22,466,650
How to make a cluster of items based on membership?
<p>I need like a magnet effect to form a cluster within a list of unique items.</p> <p>My input is this :</p> <pre><code>lst1 = ['ah', 'ab', 'c', None, 'xo', 'i', 'b', 'lji', 'z', 'bel', 'oyb'] </code></pre> <p>So based on a given item (a string that could be of any length), we need to move from left and right (towards...
<python><list>
2023-10-10 20:26:42
4
1,085
VERBOSE
77,268,753
4,701,426
Creating a column based on values of another column
<p>Please consider this dataframe:</p> <pre><code>import pandas as pd import numpy as np values = [0, 22, 30, 0, 20, 22, 11, 0, 13] index = pd.date_range(start = '2023-10-1', periods = len(values)) df = pd.DataFrame({'values':values }, index = index) df values 2023-10-01 0 2023-10-02 22 2023-10-03 30 2...
<python><pandas><numpy><vectorization>
2023-10-10 20:21:47
1
2,151
Saeed
77,268,678
2,708,215
Databricks: "Numba needs NumPy 1.22" when updating numpy
<p>I'm using Azure Databricks with Python. Among other things, I'm using the umap and numpy modules. When I try <code>import umap.umap_ as umap</code>, I get this error:</p> <p>ImportError: Numba needs NumPy 1.22 or greater. Got NumPy 1.21.</p> <p>Ok, so just update numpy, right? I ran <code>!{sys.executable} -m pip...
<python><azure-databricks>
2023-10-10 20:04:52
1
503
Andrew
77,268,484
5,397,214
Opentelemetry: Unable to Link spans with trace in a straightforward/clean way
<p>When trying to add span links in a span, the straightforward way<br /> I have read in the documentation does not work. I always get <code>AttributeError: 'Context' object has no attribute 'trace_id'</code></p> <h3>My latest attempt</h3> <h3>Simplified code to reproduce issue</h3> <pre class="lang-py prettyprint-over...
<python><open-telemetry>
2023-10-10 19:22:24
2
469
kchawla-pi
77,268,235
3,204,212
Why isn't my locally pip-installed package importable?
<p>I'm trying to create and install a Python package, but no matter what I try, I cannot get it to be importable. I've followed the tutorial on the official website and in both of my books and on three different websites to the letter and cannot get it going, nor to produce an error I can understand or find helpful Goo...
<python><pip>
2023-10-10 18:38:00
1
2,480
GreenTriangle
77,268,171
8,260,569
In a dataframe column of ints, replace every repeated occurence of n to floats between n and n+1
<p>Suppose I have a df with a column <code>a</code> that looks like so:</p> <pre><code>a - 1 2 2 3 3 3 3 2 4 4 5 </code></pre> <p>I'm looking for an efficient way to &quot;de-duplicate&quot; the values by converting them to intermediate floats. So the expected output can be either of the two shown below</p> <pre><code>...
<python><pandas><dataframe>
2023-10-10 18:26:31
3
304
Shirish
77,268,049
11,235,680
lambda_handler not found in lamba_function
<p>I'm trying to deploy an AWS lamba. Here's my folder architecture:</p> <p><a href="https://i.sstatic.net/tEYEb.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/tEYEb.png" alt="enter image description here" /></a></p> <p>and my function seems to be well defined:</p> <pre><code>import psycopg2 def lambda...
<python><amazon-web-services><aws-lambda>
2023-10-10 18:04:17
1
316
Bouji
77,267,931
489,088
How to vectorize a function with numpy so that it can be applied to a 3d array, given this function needs to access certain cells of the array?
<p>I have a computation that in which I need go through items of a 3d numpy array and add them to the values in the second dimension of the array (skipping the values in that dimension). It is analogous to this canonical mimimal reproduction example:</p> <pre><code>import numpy as np data = np.array([ [[1, 1, 1],...
<python><arrays><python-3.x><numpy><vectorization>
2023-10-10 17:42:45
2
6,306
Edy Bourne
77,267,893
7,231,968
flask to respond immediately on node await
<p>I have two services, service A (node) and service B (flask) there is an endpoint on serivce A which calls endpoint of service B like this:</p> <pre><code>const response = await axios.get( endpoint_url, { params: { library_id: req.query.library_id, ...
<javascript><python><node.js><multithreading><flask>
2023-10-10 17:34:21
2
323
SunAns
77,267,769
2,386,113
Optimizing Vectorized Transformation on NumPy Arrays
<p>I have a function that performs a matrix transformation on a NumPy array, and I'm interested in optimizing its performance by eliminating a loop and taking full advantage of NumPy's vectorized operations. The function <code>transformation(current_tuple)</code> takes a 1D tuple <code>current_tuple</code> and returns ...
<python><arrays><numpy>
2023-10-10 17:13:49
1
5,777
skm
77,267,714
2,727,278
Colab and Bigquery: endless 403 errors
<p>My goal is to access my BigQuery data in a Colab notebook, but despite this being what seems like a fairly straightforward task I'm getting endless 403 errors.</p> <p>I've added a service worker to my project and permission it the following ways:</p> <pre><code>BigQuery Admin BigQuery Data Editor BigQuery Data Viewe...
<python><google-bigquery><google-api><google-colaboratory>
2023-10-10 17:00:42
2
312
ike
77,267,713
11,626,909
extracting first digit of a float64 variable
<p>I imported a <code>.xlsb</code> file into python (pycharm IDE) by using <code>pd.read_excel()</code> function; however, before importing the <code>.xlsb</code> file, I convert it into <code>.xlsx</code> format and then import it. Please note that I did not use <code>.xlsb</code> because I faced issues regarding the ...
<python><pandas><string>
2023-10-10 17:00:08
2
401
Sharif
77,267,596
720,877
mypy type stubs for AWS lambda function
<p>Are there maintained mypy types published for AWS Lambda functions?</p> <p>I'm talking here about defining a function to handle an HTTP request (from a lambda URL or API Gateway). I'm not talking about other AWS Lambda-related APIs such as are exposed for example by boto3. Here's a example of the kind of function ...
<python><aws-lambda><mypy>
2023-10-10 16:40:00
1
2,820
Croad Langshan
77,267,532
1,671,319
How do I use pytest-mock with modules and correct import order
<p>I am totally new to <code>pytest-mock</code>. My project layout looks like this:</p> <pre><code>src pull app.py utils sftp.py tests test_pull.py </code></pre> <p>In <code>app.py</code> I have this:</p> <pre><code>from src.utils.sftp import list_files def handler(): response = list_files() </code><...
<python><pytest><pytest-mock>
2023-10-10 16:32:05
1
3,074
reikje
77,267,346
21,395,742
Error while installing python package: llama-cpp-python
<p>I am using Llama to create an application. Previously I used openai but am looking for a free alternative. Based on my limited research, this library provides openai-like api access making it quite easy to add into my prexisting code. However this library has errors while downloading. I tried installing cmake which ...
<python><llama><llama-cpp-python>
2023-10-10 16:02:20
7
845
hehe
77,267,314
4,504,877
FastAPI - how to feed values into a function?
<p>I'm trying to use FastAPI to take some values and then paste out a result from a predefined function. In reality my function is a bit more complicated than this and needs to be wrapped in a function. The follow that I'm trying gives an error:</p> <pre><code>from fastapi import FastAPI from pydantic import BaseModel ...
<python><fastapi>
2023-10-10 15:57:33
1
566
user33484
77,267,290
1,418,090
Masking `nan` on tensorflow efficiently
<p>Suppose I want to run a simple deep-learning classification model. Here is a data example:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd import numpy as np X = pd.DataFrame({ 'v1': [1, 2, 3, 4, np.nan, 6], 'v2': [0.3119080, 0.9352281, 0.2509079, 0.8880956, -1.1892642, np.nan], ...
<python><pandas><numpy><tensorflow><masking>
2023-10-10 15:54:35
0
438
Umberto Mignozzetti
77,267,289
11,145,822
Connection issue while connecting to DB2 instance
<p>I'm trying to connect to DB2 instance from my local MacOS. I tried with 2 python modules, but I'm getting the below errors for both modules. Any idea/suggestions how I can resolve this.</p> <p>Tried many things after searching in google and checking in ChatGPT, but no success. Any light here will be much appreciated...
<python><python-3.x><db2>
2023-10-10 15:54:24
1
731
Sandeep
77,267,232
9,544,507
pytest.raises() doesn't catch custom exception
<p>It seems that pytest.raises(CustomException) is failing, when the class raises it:</p> <p>I have a project folder like this:</p> <pre><code>root: pytest.ini models: my_model.py custom_exceptions.py test: test_one.py </code></pre> <p>my_model.py:</p> <pre class="lang-py prettyprint...
<python><python-3.x><pytest>
2023-10-10 15:45:35
1
333
Wolfeius
77,267,060
2,547,403
Possibility of using python method in C++ project
<p>Python has a very useful optimization library called <code>nevergrad</code>, which I wanted to try using in a project written in C++. A simple test case on <code>nevergrad</code>:</p> <pre><code>import nevergrad as ng # optimization function def square(x): return sum((x - 0.5) ** 2) # solve method def solve()...
<python><c++><boost>
2023-10-10 15:22:33
2
369
DiA
77,267,052
15,965,186
FastAPI Jinja: `url_for` not working inside macros
<p>Using <code>url_for</code> in a macro defined in another file in a template raises a KeyError for 'request'.</p> <p>Considering the following tree</p> <pre><code>. |-- app.py |-- static | |-- css | | `-- style.css | |-- img | | `-- logo.png | `-- js | |-- script.js `-- templates |-- base.html...
<python><jinja2><fastapi>
2023-10-10 15:21:46
1
1,101
Krapp
77,266,962
12,691,575
python unittesting - functions depending on other modules
<p>Is there a &quot;correct&quot; way to write unit tests for functions that rely on non-local functions (multi-module dependency tests). e.g.</p> <pre><code>. ├── src │   ├── main1.py │   └── main2.py ├── tests │   └── tests_main.py </code></pre> <pre class="lang-py prettyprint-override"><code># /src/main1.py import m...
<python><python-3.x><unit-testing><testing>
2023-10-10 15:08:24
1
337
joegrammer
77,266,908
6,059,213
Error connecting to SQL Server from Python using pyodbc on CentOS 8
<p>I am having trouble connecting to SQL Server from a Python environment using pyodbc on a CentOS 8 system.</p> <p><strong>Environment:</strong></p> <ul> <li>CentOS 8</li> <li>Python version: 3.11.2</li> <li>pyodbc version: 4.0.39</li> <li>ODBC Driver: ODBC Driver 17 for SQL Server</li> </ul> <p><strong>Error:</strong...
<python><sql-server><odbc><pyodbc>
2023-10-10 14:59:44
0
374
Tom Leung
77,266,754
7,190,575
S3 – Images sometimes showing up with wrong rotations
<p>I run a web service where users are allowed to upload images.</p> <p>I've noticed that sometimes, the uploaded image on S3 shows up rotated – as I came to learn due to exif metadata.</p> <p>Taking a sample of some of the images, and opening them in GIMP, it yields a prompt where I have to decide whether to keep or s...
<python><django>
2023-10-10 14:39:02
1
6,949
OhMad
77,266,671
2,135,504
Polars - drop duplicate row based on column subset but keep first
<p>Given the following table, I'd like to remove the duplicates based on the column subset <code>col1,col2</code>. I'd like to keep the first row of the duplicates though:</p> <pre class="lang-py prettyprint-override"><code>data = { 'col1': [1, 2, 3, 1, 1], 'col2': [7, 8, 9, 7, 7], 'col3': [3, 4, 5, 6, 8] }...
<python><pandas><python-polars>
2023-10-10 14:26:26
2
2,749
gebbissimo
77,266,623
10,574,250
Assign pyspark column based upon other column values using groupby average
<p>I have a pyspark dataframe hat looks as such:</p> <pre><code> identifier numbers_to_sum dog 5 cat 4 dog 3 parrot 2 cat 7 </code></pre> <p>What I want is to assign a new column with the values based upon a groupby average of numbers_to_sum related to the specifi...
<python><pyspark>
2023-10-10 14:20:21
1
1,555
geds133
77,266,318
3,829,437
Defining an Annotated[str] with constraints in Pydantic v2
<p>Suppose I want a validator for checksums that I can reuse throughout an application. The Python type-hint system has changed a lot in 3.9+ and that is adding to my confusion. In pydantic v1, I subclassed <code>str</code> and implement <code>__get_pydantic_core_schema__</code> and <code>__get_validators__</code> cla...
<python><python-typing><pydantic>
2023-10-10 13:39:58
1
413
nerdstrike
77,266,124
13,558,699
icicidirect breeze_connect websocket is closing instantly on startup
<p>I am using the direct code snippet from icicidirect breeze_connect api documentation. It is instantly getting closed after subscription of data feed is successful. I am facing this issue in Pycharm and aws cloud9 IDE. The code is running fine and callback function returning the expected data in Jupyter notebook. Th...
<python><python-3.x><websocket><pycharm><aws-cloud9>
2023-10-10 13:15:51
2
313
Yogendra Kumar
77,266,110
156,458
How can I find out the number of tabs at the beginning of each line in a text file?
<p>I have a text file, where each line may start with a number of tabs, including no tabs. For example, the first line starts with no tab, the second line with 1 tab, and the third line with 2 tabs:</p> <pre><code>Chapter 1 1 1.1 Chapter 2 1 1.1 </code></pre> <p>Is it possible to get the number...
<python><text-processing>
2023-10-10 13:14:03
3
100,686
Tim
77,266,095
728,795
How to create a process in a new Linux namespace
<p>I am trying to create a child process with Python under a new <a href="https://man7.org/linux/man-pages/man7/namespaces.7.html" rel="nofollow noreferrer">Linux namespace</a>. But checking the <a href="https://docs.python.org/3/library/subprocess.html" rel="nofollow noreferrer">subprocess documentation</a> it does no...
<python><linux-namespaces>
2023-10-10 13:11:56
1
56,836
Andrei
77,266,032
17,835,656
how can i solve the problem in the language's direction in FPDF2?
<p>I am working on a project to print words in arabic on a PDF file using FPDF2 in python.</p> <p>but i have faced a lot of problems in showing the language in its original direction.</p> <p>FPDF2 shows everything language in english direction.</p> <p>this is how you read english :</p> <p><a href="https://i.sstatic.net...
<python><python-3.x><pdf><fpdf><fpdf2>
2023-10-10 13:03:42
1
721
Mohammed almalki
77,265,938
5,942,907
cargo rustc failed with code 101 - Could not build wheels for tokenizers, which is required to install pyproject.toml-based projects
<p>I have a project with Python 3.11.4. Until now I was able to build my docker image without issues with the next libraries (just mentioning the important ones related to the issue):</p> <p>transformers 4.8.2</p> <p>tokenizers 0.10.3</p> <p>In the Dockerfile the rust compiler is installed by executing the next:</p> <p...
<python><docker><pip><python-wheel>
2023-10-10 12:48:44
3
389
sylvinho81
77,265,766
17,267,064
Spark job fails in AWS Glue | "An error occurred while calling o86.getSink. The connection attempt failed."
<p>I attempted to migrate data from a csv file from an S3 storage to a table in my Redshift cluster. I took reference from an autogenerated code which came after I built blocks using Visual mode in AWS Glue. This job ran successfully.</p> <p>I copied that code and changed basic details such as variable and table name i...
<python><pyspark><amazon-redshift><aws-glue>
2023-10-10 12:25:01
0
346
Mohit Aswani
77,265,677
2,386,605
Autocompletion with OpenAI API or Langchain
<p>Assume I have some sort of text like</p> <p>&quot;This is a&quot;</p> <p>and now I want to use the OpenAI package for Python or even better Langchain to complete this statement, such that something like</p> <p>&quot;This is a question in Stackoverflow&quot;</p> <p>arises. How would I do that?</p>
<python><openai-api><langchain><py-langchain><azure-openai>
2023-10-10 12:13:31
1
879
tobias
77,265,609
22,466,650
How to recursively look for sub classes and at the same time aggregate their values?
<p>Please find my dataframe this :</p> <pre><code>df = pd.DataFrame({'class': ['class_b', 'class_a', 'class_c', 'class_d'], 'sub_class': ['class_d', None, 'class_e', 'class_a'], 'entities': [5, 1, 7, 6]}) print(df) class sub_class entities 0 class_b class_d 5 1 class_a None 1 2 class_c ...
<python><pandas>
2023-10-10 12:04:29
1
1,085
VERBOSE
77,265,591
5,513,253
Coming from Perl/DBI to Python
<p>From an absolute Python n00b:</p> <p>Years after falling in love with Perl's DBI <code>fetchall_hashref()</code> I've come to Python to do some similar db work.</p> <p>What I found so far is that <code>res.fetchall()</code> returns a row in which the columns are not indexed with the column name. I have to use row[0]...
<python><database>
2023-10-10 12:01:31
0
366
Peter
77,265,534
3,532,367
Django How to use proxy models instead of parent
<p>My code:</p> <pre><code>from django.db import models class Animal(models.Model): type = models.CharField(max_length=100) class Dog(Animal): class Meta: proxy = True class Cat(Animal): class Meta: proxy = True </code></pre> <p>I want to do:</p> <pre><code>animals = Animal.objects.all() </code></...
<python><django><model>
2023-10-10 11:53:26
3
369
Mariusz
77,265,239
5,743,194
In a pydantic model, how do I define the type of property which is a decorated method?
<p>Consider this code snippet:</p> <pre class="lang-py prettyprint-override"><code>from pydantic import BaseModel class SomeModel(BaseModel): property_1: str property_2: Dict[str, str] property_3: int = 12 @property def property_4(self) -&gt; int: response = external_call() # returns '22....
<python><model><pydantic>
2023-10-10 11:06:39
1
1,065
Artur
77,265,129
1,420,050
Imports in Python editable local project installs
<p>I have a Python project (the parent project) that should use two other local Python projects (the library projects) via editable installs as dependencies (see the corresponding <a href="https://peps.python.org/pep-0660/" rel="nofollow noreferrer">PEP</a>, <a href="https://pip.pypa.io/en/stable/topics/local-project-i...
<python><pip><dependencies><python-poetry>
2023-10-10 10:50:13
0
465
Till S
77,265,055
7,366,600
Python send to Twilio websocket in x-audio/mulaw 8kHz
<p>I am trying to send media back to twilio websocket but twilio is not playing the audio, I am using gTTS for text to speach.</p> <p>Here is my code for text to speach</p> <pre><code>def text_to_mp3(self, f_path :str , f_key: str, text: str) -&gt; str: tmp_fn = os.path.join(f_path, f_key + &quot;.mp3&quot;)) ...
<python><twilio>
2023-10-10 10:39:39
1
718
Stacy Thompson
77,264,996
2,300,597
Is there still maxfev parameter in curve_fit? If not, how can we control the number of iterations performed?
<p>As of today, is there still this <code>maxfev</code> parameter in <code>curve_fit</code>?</p> <p>If not, how to control the number of iterations that are performed while fitting?</p> <p>I tried passing it in but seems it's just ignored.</p> <p>I wonder if this parameter was removed and if so in which version?! And ...
<python><scipy><curve-fitting>
2023-10-10 10:32:24
0
39,631
peter.petrov
77,264,885
10,909,217
Parallelizing independent creation of Dataframes
<p>I have a general question about parallelizing Dataframe operations.</p> <p>Let's say I have an operation like this in mind (pseudo-Code, <code>df</code>, <code>df1</code> and <code>df2</code> are DataFrames)</p> <pre><code>df1 = pandas_operations(df, arg1, arg2) df2 = pandas_operations(df, arg3, arg4) result = pd.co...
<python><pandas><numpy><multiprocessing>
2023-10-10 10:17:32
1
1,290
actual_panda
77,264,776
1,715,185
How to make generic class inheriting from TypeVar in Python?
<p>How can I create a Generic class in Python, that has the TypeVar as a base class?</p> <p>The minimum example is this:</p> <pre><code>from typing import TypeVar, Generic T = TypeVar(&quot;T&quot;) class A(T, Generic[T]): pass </code></pre> <p>Unfortunately, it gives me the following error:</p> <pre><code>TypeEr...
<python><generics><fastapi><multiple-inheritance><metaclass>
2023-10-10 10:03:15
1
508
Petr
77,264,725
10,027,628
Python Bigquery import fails on Windows
<p>I'm trying to use <code>from google.cloud import bigquery</code> in my Python script, but it fails with the following error:</p> <pre><code>Script failed to evaluate(): 'NoneType' object has no attribute 'message_types_by_name' Traceback (most recent call last): File &quot;Python Script&quot;, line 4, in &lt;modu...
<python><windows><google-bigquery>
2023-10-10 09:56:44
1
377
Christoph H.
77,264,606
21,404,794
Plotting BoTorch Synthetic functions
<p>I'm trying to plot the <a href="https://botorch.org/api/test_functions.html#botorch.test_functions.synthetic.Ackley" rel="nofollow noreferrer">Ackley synthetic function</a> from botorch (mainly to understand how it works and why if I feed it 2 tensors it only returns 1 value), and I'm facing a bunch of different pro...
<python><pytorch><botorch>
2023-10-10 09:40:03
2
530
David Siret Marqués
77,264,491
2,876,079
How to loop over all documents and get meta information about existing directives in Sphinx?
<p>I would like to create a custom Sphinx extension, that shows a list of all figures. Also see related question <a href="https://stackoverflow.com/questions/77259971/how-to-create-list-of-all-figures-tables-in-sphinx">How to create list of all figures (tables) in Sphinx?</a></p> <p>In the Sphinx documentation there is...
<python><python-sphinx><docutils>
2023-10-10 09:26:20
0
12,756
Stefan
77,264,168
11,747,148
ImportError: <PKG_NAME> not found in importing a Julia package in Python using PyJulia
<p>I tried to import a registered Julia package into Python to use it but I got an error (I followed <a href="https://blog.esciencecenter.nl/how-to-call-julia-code-from-python-8589a56a98f2" rel="nofollow noreferrer">this turorial</a>):</p> <pre><code>$ pip install julia </code></pre> <pre class="lang-py prettyprint-ove...
<python><julia>
2023-10-10 08:40:04
0
6,682
Shayan
77,263,913
219,153
Is there a multicore option to compress a NumPy array?
<p>I'm using <code>np.savez_compressed()</code> to compress and save a single large 4D NumPy array, but it uses only one CPU core. Is there an alternative, which can use many cores? Preferably something simple without need to code array split and compression of its pieces in multiple processes.</p>
<python><compression><numpy-ndarray><multicore>
2023-10-10 08:00:12
0
8,585
Paul Jurczak
77,263,880
15,320,579
Process python dictionary based on previous, current and next value
<p>I have a python dictionary as follows:</p> <pre><code>ip_dict = {'GLArch': {'GLArch-0.png': ['OTHER', 'Figure 28 TAC '], 'GLArch-1.png': ['DCDFP', 'This insurance '], 'GLArch-2.png': ['DCDNP', 'Item 3'], 'GLArch-3.png': ['OTHER', 'SCHEDULE OF'], ...
<python><python-3.x><dictionary><data-processing>
2023-10-10 07:55:26
2
787
spectre
77,263,766
583,464
select the max element in an increasing (and restarting over) list
<p>I have this list:</p> <pre><code>mylist = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3] </code></pre> <p>The length of the list is : <code>38</code>.</p> <p>I want a new list with length: <code>32</code>.</p> <p>My new list will be:</p> ...
<python><list>
2023-10-10 07:39:19
2
5,751
George
77,263,314
10,639,382
Not signed in Earth Enine or Project is not Registered
<p>Hi I am attempting to use the Python API to access google earth engine from VsCode.</p> <p>When I enter,</p> <pre><code>import ee ee.Authenticate() ee.Initialize() </code></pre> <p>I get the following error for <code>ee.Initialize()</code> step - &quot;ee.ee_exception.EEException: Not signed up for Earth Engine or ...
<python><authentication><google-earth-engine>
2023-10-10 06:19:16
2
3,878
imantha
77,263,279
5,055,577
Beautifulsoup python issue when looping through multiple pages
<p>I'm trying to learn some basic webscraping using python beautiful soup. Intent for below code is to loop through 32 NFL team pages and return the Wins / Loses for each team. However whenever the code gets to the second iteration of the dataframe, I get the error returned below.</p> <pre><code>`import requests from ...
<python><web-scraping><beautifulsoup><python-requests>
2023-10-10 06:11:18
1
2,094
Jesse
77,263,248
5,273,308
C++ Cython Map operations returns {b'a': 2} rather than {'a': 2}
<p>Why does the following code print {b'a': 2} rather than {'a': 2}. And how can I fix it:</p> <p>File1: parameters.pyx</p> <pre><code># parameters.pyx from libcpp.map cimport map from libcpp.string cimport string cdef class Parameters: cdef map[string,int] data cdef int myVal def __init__(self): ...
<python><c++><cython><stdmap>
2023-10-10 06:03:06
1
1,633
user58925
77,263,124
2,192,824
Where is the python interpreter installed when ssh to a remote machine
<p>I'm a little confused with this scenario about which python interpreter is used:</p> <p>I use vscode to ssh to the python codes in a remote machine, and then I installed the python interpreter as VScode suggests. I was wondering which machine is the python interpreter installed. The remote machine or my local machin...
<python><visual-studio-code>
2023-10-10 05:27:52
2
417
Ames ISU
77,263,051
9,989,308
Azure Log Analytics: How to send custom python pandas DataFrames into LAW
<p>I have a Python script that I want to run daily that produces a Pandas dataframe.</p> <p>I want this dataframe to be added daily to my log analytics workspace.</p> <p>I have a Windows server that I can use to run my Python script.</p> <p>What do I need to do to make this work? Is there a way to go from DataFrames to...
<python><azure><syslog><azure-log-analytics>
2023-10-10 05:01:23
1
868
HarriS
77,262,974
1,395,266
Pass variablle value as parametrs to python fromJupyter notebook
<p><a href="https://stackoverflow.com/questions/51551056/running-a-python-script-in-jupyter-notebook-with-arguments-passing">Running a Python script in Jupyter Notebook, with arguments passing</a></p> <pre><code>a = 3 b = 5 !ipython two_digits.py a b </code></pre> <p>Why this is not working ? How to pass parameters fro...
<python><jupyter><ipython>
2023-10-10 04:37:34
1
6,220
sudhansu63
77,262,913
19,238,204
Integral with Piecewise Resulting into Different 3D Wireframe Plot using SymPy and Python
<p>I am trying to use <code>piecewise</code> to integrate function that change at certain domain.</p> <p>The result of the 3D wireframe plot (with spb) is different than when using manual way of computing integral one by one. The correct plot is the one that is using manual way.</p> <p>If you are wondering, why there i...
<python><numpy><sympy>
2023-10-10 04:21:21
1
435
Freya the Goddess
77,262,819
5,273,308
Calling Cython cdef function from another file
<p>I would like to call a cdef function defined in one file, from another file. I do not want to change cdef function to a cpdef, but I am willing to change the second file.</p> <p>File1 parameters.pyx</p> <pre><code>cdef class Parameters: cdef int myVal def __init__(self): self.myVal = 0 cdef cha...
<python><cython>
2023-10-10 03:44:22
1
1,633
user58925
77,262,771
22,643,255
Sharepoint Rest API office365 library 403 Client Error
<p>I am trying to access a Sharepoint folder and retrieve the files within.</p> <p>With the following code:</p> <pre><code># Import libraries from office365.sharepoint.client_context import ClientContext from office365.runtime.auth.client_credential import ClientCredential # Config for Sharepoint (to be stored in env ...
<python><sharepoint><azure-active-directory><azure-ad-graph-api><sharepoint-rest-api>
2023-10-10 03:28:21
1
315
ooalgomaniac
77,262,625
8,523,868
Memory error while trying to get list of files from the directory and storing it in the spreadsheet
<p>I have downloaded the code from Google bard to get the list of files from the directory and sub directory to store it in a spreadsheet.</p> <p>I am getting a memory error.</p> <p>My question: write a program in python to list of files in the directory and sub directory and store the file names in the spreadsheet wit...
<python>
2023-10-10 02:27:44
4
911
vivek rajagopalan
77,262,518
7,009,988
How to install Python into Windows Docker container
<p>I want to create a docker container using base image <code>mcr.microsoft.com/dotnet/framework/runtime:4.8.1</code> but I also need Python on here. Unfortunately the official Python images only use <code>windowsservercore</code>. What do I put in my Dockerfile to make this happen? All the documentation I see are eith...
<python><docker>
2023-10-10 01:41:27
2
1,643
wheeeee
77,262,501
10,565,820
How to alter cipher suite used with Python requests?
<p>This is part of a larger program I'm working on, but I've got it pinpointed down to the exact problem. When I use Python <code>requests</code> module in some environments it works but not others and it seems to be related to the cipher suite being used by SSL. When I run the following command in Python, it gives an ...
<python><ssl><encryption><python-requests><openssl>
2023-10-10 01:33:55
1
644
geckels1
77,262,318
498,201
Python NLTK text dispersion plot has y vertical axis is in backwards / reversed order
<p>Since last month NLTK dispersion_plot seems to have y (vertical) axis in reversed order on my machine. This is likely something about my versions of software (I am on a school virtual machine).</p> <p>versions: nltk 3.8.1 matplotlib 3.7.2 Python 3.9.13</p> <p>code:</p> <pre><code>from nltk.draw.dispersion import dis...
<python><nltk><text-mining>
2023-10-10 00:05:07
2
2,650
drpawelo
77,262,213
4,807,043
rsync doesn't work in Python script: rsync: change_dir failed: No such file or directory (2)
<p>I need to transfer a directory (and all its content in it) to a remote host using <code>rsync</code> and I need to use it inside a python script but I got this following error:</p> <pre><code>building file list ... rsync: change_dir &quot;/home/xxxx//xxxx/xxxx/ root@xx.xx.xx.xx:/opt/customized&quot; failed: No such...
<python><linux><rsync>
2023-10-09 23:22:01
1
3,250
Henry
77,262,037
9,795,817
Read range of parquet files in PySpark
<p>I have a ton of daily files stored in an HDFS where the partitions are stored in YYYY-MM-DD format.</p> <p>For example:</p> <pre class="lang-bash prettyprint-override"><code>$ hdfs dfs -ls /my/path/here &lt;some stuff here&gt; /my/path/here/cutoff_date=2023-10-02 &lt;some stuff here&gt; /my/path/here/cutoff_date=202...
<python><apache-spark><pyspark><apache-spark-sql><hdfs>
2023-10-09 22:13:30
3
6,421
Arturo Sbr
77,262,031
363,796
Line length limit in SMTP emails [Was: Message length limit sending HTML email with smtplib]
<p>Here's a simple test that demonstrates the problem I'm seeing:</p> <pre><code>import smtplib from email.message import EmailMessage my_addr = 'my_email@my_domain.com' str = '' for i in range(500): str += f'{i}: &lt;a href=&quot;https://google.com&quot;&gt;https://google.com&lt;/a&gt;&lt;br&gt;' msg = EmailMes...
<python><smtp><smtplib>
2023-10-09 22:11:38
1
1,653
zenzic
77,261,986
7,106,915
Remove padding in sidebar, Streamlit
<p>How to remove the top vertical padding in the default Streamlit sidebar?</p> <p>Posting the solution below.</p>
<python><css><user-interface><streamlit>
2023-10-09 21:58:39
1
3,007
Rexcirus
77,261,948
489,088
Processing all cells in a 2d DataFrame is very slow - what am I missing?
<p>I have a dataframe that comes from a csv file. I pivot this dataframe by two columns, and then attempt to process each cell.</p> <p>In my actual code, which is of course much more complicated, there is some processing for each value. But I notice it is extremely slow. I then created a canonical example here to illus...
<python><python-3.x><pandas><dataframe><performance>
2023-10-09 21:49:08
1
6,306
Edy Bourne
77,261,768
10,859,585
Python Monday.com Create new board
<p>I've read through the monday.com API documentation, but have been unsuccessful of creating a new board within a given workspace. The code runs and gives a <code>status_code == 200</code>, however there is no new board created within that workspace. Is this because no data has been added to it?</p> <pre class="lang-p...
<python><post><monday.com>
2023-10-09 21:03:58
1
414
Binx
77,261,622
13,067,389
Merging Top Two Rows of a dataframe and editing the result
<p>I have a dataframe:</p> <pre><code>df = pd.DataFrame({ '0': ['FY18', 'Q1', 1500, 1200, 950, 2200], '1': ['FY18', 'Q2', 2340, 1234, 2000, 1230], '2': ['FY18', 'Q3', 2130, 2200, 2190, 2210], '3': ['FY18', 'YearTotal', 1000, 1900, 1500, 1800], }) </code></pre> <p>I wish to merge the top two rows o...
<python><pandas><merge>
2023-10-09 20:30:51
2
681
postcolonialist
77,261,523
5,987
Why does struct.unpack need 2 extra bytes?
<p>I have the following <code>struct.unpack</code> call that fails:</p> <pre><code>struct.unpack('14x4x2i2xh8x2i', b'\0'*46) Traceback (most recent call last): File &quot;&lt;pyshell#88&gt;&quot;, line 1, in &lt;module&gt; struct.unpack('14x4x2i2xh8x2i', b'\0'*46) struct.error: unpack requires a buffer of 48 byt...
<python><struct>
2023-10-09 20:12:10
1
309,773
Mark Ransom
77,261,425
9,983,652
How to run Python using Docker?
<p>I don't know Docker at all. I just use VS code or jupyter notebook to run notebook. I just bought a book and went to Github page of the authors trying to download the notebooks. It said I have to run docker. It is really annoying. I am wondering if I can download all these notebooks from the Docker using some sort o...
<python><docker>
2023-10-09 19:50:57
0
4,338
roudan
77,261,423
388,520
Python: import the actual module object for the containing package, without naming it
<p>This question or a close relative has been asked at least three times before (<a href="https://stackoverflow.com/questions/436497/python-import-the-containing-package">1</a>, <a href="https://stackoverflow.com/questions/73437382/python-relatively-import-the-containing-package">2</a>, <a href="https://stackoverflow.c...
<python><python-3.x>
2023-10-09 19:50:35
1
142,389
zwol
77,261,415
11,278,478
Convert Horizontal text file to vertical CSV file using Python
<p>I have a text file which has each column as a row and a header to represent start of new record. I need to convert this to a vertical CSV using Python.</p> <p>Not all columns apply to each records so I can set them up either blank or 0.</p> <p>Please see example below:</p> <pre><code>WERF this is vendor1 data this...
<python><python-3.x><pandas><dataframe><csv>
2023-10-09 19:47:36
4
434
PythonDeveloper
77,261,325
13,613,776
How can I optimize this SQLAlchemy delete query for the Match table, which deletes rows where both user_id and partner_id match a specific user_id?
<p>Here's my current code:</p> <pre><code>async def delete_match(user_id): async with session_pool() as session: delete_stmt = delete(Match).where(Match.user_id == user_id) delete_stmt = delete(Match).where(Match.partner_id == user_id) await session.execute(delete_stmt) await session...
<python><sqlalchemy><flask-sqlalchemy>
2023-10-09 19:26:04
0
448
Rishu Pandey
77,261,135
3,825,948
Make Connection/Pool Available Outside Main
<p>Using the following code from <a href="https://pypi.org/project/cloud-sql-python-connector/" rel="nofollow noreferrer">https://pypi.org/project/cloud-sql-python-connector/</a>:</p> <pre><code>import asyncio import asyncpg import sqlalchemy from sqlalchemy.ext.asyncio import AsyncEngine, create_async_engine from go...
<python><database><sqlalchemy><connector><asyncpg>
2023-10-09 18:41:30
0
937
Foobar
77,261,129
5,830,492
How to create a Frame/Canvas using class in Python and use it many times with different widgets inside it?
<p>I am new in Python. I am developing a program which actually is a small shell for phpMyAdmin. In my program I need in some Windows (which is created by TKinter) draw a scrolled canvas. I've written a class like this to create a Scrolled Canvas. It's working great when I use it in every where but problem is I need d...
<python><class><tkinter><subclass>
2023-10-09 18:40:24
1
388
Saleh
77,261,119
353,337
Manually escaping URL query string
<p>I have a URL string</p> <pre><code>https://example.com/search?'=$&amp;(=/&amp;)=! </code></pre> <p>that I'd like to transform into its escaped form</p> <pre><code>https://example.com/search?%28=%2F&amp;%29=%21&amp;%27=%24 </code></pre> <p>as reported by <code>res.request.path_url</code> using Python.</p> <p>I've pla...
<python><url><python-requests>
2023-10-09 18:38:51
1
59,565
Nico Schlömer
77,261,097
7,638,876
Filter data in long format using dropdown menu with plotly
<p>I am trying to filter data, which is in a long format, using dropdown menu in plotly. However, I might be misunderstanding something as I am not getting the proper results. I want to combine this with faceting, but that is not shown in the code below. I tried two ways that did not work (they fail in different ways) ...
<python><plotly>
2023-10-09 18:35:55
1
995
student
77,260,935
1,147,321
Python evaluating "eval" windows paths wrongly
<p>I am trying to use eval to convert a string representing a list of file paths to an actual list.</p> <p>However, it seems to me that eval ruins that path. See the following code:</p> <p><em>Code executed in Pycharm Python console</em></p> <pre><code>&gt;&gt;&gt; _path = '[&quot;c:\\path\\to\\knowwhere&quot;]' &gt;&...
<python><python-3.x><windows><eval>
2023-10-09 18:04:54
1
2,167
Ephreal
77,260,861
4,966,317
Solve University Courses Constraint satisfaction problem with Pandas
<p>I have a dataframe that contains some university courses.</p> <ul> <li>Each course has <code>pre-requisites</code> and <code>co-requisites</code> where <code>pre-requisites</code> are the courses that should be passed <strong>before</strong> being able to register a specific course.</li> <li><code>Co-requisites</cod...
<python><python-3.x><pandas><dataframe>
2023-10-09 17:48:58
1
2,643
Ambitions
77,260,842
335,427
Place equally grouped members into same buckets
<p>I am looking for an optimal algorithm to to the following</p> <p>I have a list of groups like so</p> <pre><code>groups = [ ['A', 'B', 'C'], ['D', 'A', 'E'], ['X', 'Y', 'Z'], ['X', 'A', 'W'], ['AA', 'BB', 'CC'], ] </code></pre> <p>I want to put them into buckets where, if there is no bucket, creat...
<python><algorithm>
2023-10-09 17:45:50
1
3,735
Chris
77,260,839
1,874,170
Dependency injection with CFFI?
<p>I'm trying to make a toy/proof-of-concept <a href="https://cffi.readthedocs.io/" rel="nofollow noreferrer">CFFI</a>-based Python library exposing the <a href="https://github.com/pqclean/PQClean" rel="nofollow noreferrer">PQClean</a> implementation of <a href="https://classic.mceliece.org/" rel="nofollow noreferrer">...
<python><dependency-injection><python-cffi>
2023-10-09 17:45:27
1
1,117
JamesTheAwesomeDude