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
⌀
78,044,016
850,781
Fill Na in pandas with averages per another column
<p>I have a dataframe</p> <pre><code>df = pd.DataFrame({ &quot;species&quot;:[&quot;cat&quot;,&quot;dog&quot;,&quot;dog&quot;,&quot;cat&quot;,&quot;cat&quot;], &quot;weight&quot;:[5,4,3,7,None], &quot;length&quot;:[12,None,13,14,15], }) species weight length 0 cat 5.0 12.0 1 dog 4....
<python><pandas><dataframe><fillna>
2024-02-22 21:08:54
1
60,468
sds
78,043,846
5,036,476
How to prevent socket exhaustion on http requests?
<p>I'm a .NET developer writing a python client which needs to do multiple HTTP requests in a short amount of time.</p> <p>In .NET, when you use HttpClient to make a request, it opens a socket connection to make the request and get the response. When you're done with the HttpClient and dispose it, the socket isn't imme...
<python><http>
2024-02-22 20:27:45
0
1,748
Tobias von Falkenhayn
78,043,661
2,641,242
How to find out if wandb is initialized?
<p>At the start of my application, I initialize a connection to WeightsAndBiases via</p> <pre class="lang-py prettyprint-override"><code>run = wandb.init(project=&quot;...&quot;) </code></pre> <p>Later on, I would like to check if a <code>wandb</code> run has been initialized. Is there a way to do this without passing ...
<python><machine-learning><wandb>
2024-02-22 19:47:13
1
3,997
jraufeisen
78,043,476
1,115,716
Split string, preserve quoted substring
<p>I have a string that I'm trying to split such that the quoted substring stays preserved. Based on another thread here, I tried using <code>shlex</code>:</p> <pre><code>import shlex shlex.split('“COBRA COMMANDER” Section 4Q/C') </code></pre> <p>However, the result isn't what I expected:</p> <pre><code>['“COBRA', 'COM...
<python>
2024-02-22 19:04:27
1
1,842
easythrees
78,043,415
3,423,825
How to debug memory leak on DigitalOcean App Platform
<p>My Django application run perfectly fine on my local machine, memory usage fluctuate between 700MB and 800MB, but when I execute the exact same code on DigitalOcean App Platform the memory usage is constantly increasing until it reach 100%. Then the application reboot.</p> <p>What could cause the issue and how to fi...
<python><django><digital-ocean>
2024-02-22 18:51:37
0
1,948
Florent
78,043,310
5,344,240
Abstract @property - instantiating a "partially implemented" class?
<p>I read <a href="https://pymotw.com/3/abc/" rel="nofollow noreferrer">this</a> very nice documentation on abstract class <code>abc.ABC</code>. It has this example (shortened by me for the purpose of this question):</p> <pre><code>import abc class Base(abc.ABC): @property @abc.abstractmethod def value(sel...
<python><inheritance><abstract-class><python-decorators>
2024-02-22 18:29:52
1
455
Andras Vanyolos
78,043,285
13,086,128
df.drop_duplicates() in polars?
<pre><code>import polars as pl df = pl.DataFrame( { &quot;X&quot;: [4, 2, 3, 4], &quot;Y&quot;: [&quot;p&quot;, &quot;p&quot;, &quot;p&quot;, &quot;p&quot;], &quot;Z&quot;: [&quot;b&quot;, &quot;b&quot;, &quot;b&quot;, &quot;b&quot;], } ) </code></pre> <p>We know the equivalent of <a hr...
<python><python-3.x><dataframe><unique><python-polars>
2024-02-22 18:26:18
1
30,560
Talha Tayyab
78,043,284
146,780
Removing the for loops for mean calculation with batch with pytorch
<pre><code>B = spec_x.size(0) H = spec_x.size(1) T = spec_x.size(2) # Initialize x tensor with zeros z = torch.zeros(B, 256, H).to(pitch.device) # Iterate over each batch element for b in range(B): # Iterate over each pitch index for i in range(256): # Mask spec_x where pitch equals i masked_s...
<python><pytorch>
2024-02-22 18:26:13
1
54,489
jmasterx
78,043,216
10,007,302
xlwings not reading config file information
<p>I'm attempting to automate an install for my team that requires the use of xlwings.</p> <p>My understanding is that is that if you go to the ribbon within Excel and leave the Interpreter and PYTHONPATH fields blank, xlwings will then look for a config file that's saved in the home directory in a folder called .xlwin...
<python><excel><xlwings>
2024-02-22 18:12:44
1
1,281
novawaly
78,043,002
19,077,881
Selecting a range of columns from names in Polars
<p>I have a many-column DF from which I need to process various ranges of columns.</p> <p>In Pandas I could use an expression along the lines of : df.loc[:, 'first_name': 'last_name'] to obtain the required columns between the two end-points. Is there an equivalent in Polars which does not involve listing all the numer...
<python><dataframe><python-polars>
2024-02-22 17:33:06
2
5,579
user19077881
78,042,886
4,992,248
On the 2nd iteration of loop Python throws error "RuntimeWarning: coroutine 'to_thread' was never awaited"
<p>I have one &quot;parent&quot; sync function and one &quot;child&quot; sync function. I want to run few &quot;child&quot; functions as a result I convert them to coroutine. Child functions/coroutines I run inside loop - for some reason the 1st loop returns result, but the 2nd one throws <code>RuntimeWarning: coroutin...
<python><python-asyncio>
2024-02-22 17:12:47
1
5,204
TitanFighter
78,042,758
68,304
Finding conan package folder from conanfile.py
<p>We're using <code>conan v1.59</code> in our project (forced to as that's client's setup). It's a project in C, the build tool is <code>CMake</code>. This project has several dependencies. We're utilizing <code>conanfile.py</code> for building and packaging artifacts.</p> <p>Let's say, <code>ch-common</code> is a req...
<python><cmake><conan>
2024-02-22 16:51:47
0
13,045
Donotalo
78,042,672
1,773,592
In polars how do I name a column that is created using group_by and n_unique?
<p>I am trying to replace some pandas with polars. I am new to polars.</p> <p>Original code:</p> <pre><code>return pd.DataFrame( data.groupby([list_of_fields]).size(), columns=[&quot;Count&quot;], ).reset_index() </code></pre> <p>I am stuck on how to name the column &quot;Count&quot;. So far I have tried:</p> <...
<python><dataframe><python-polars>
2024-02-22 16:38:32
1
3,391
schoon
78,042,596
2,473,382
How to use different module in the parent class depending on the child?
<p>I am trying to have a parent class which will do the same thing for 2 child databases (Hana and Oracle in my example).</p> <p>I would like to properly type the parent class.</p> <p>The example I would like is as follows. It works at runtime, but typing gets crazy for multiple reasons:</p> <ul> <li>Module cannot be u...
<python><python-3.x><python-typing>
2024-02-22 16:28:31
1
3,081
Guillaume
78,042,589
4,659,530
pip requirements for relative packages
<p>I have following structure</p> <pre class="lang-bash prettyprint-override"><code>libs/lib_1/pyproject.toml libs/lib_2/pyproject.toml -&gt; uses lib_1 service/service_1/pyproject.toml -&gt; uses lib_2 </code></pre> <p>In <code>service_1/pyproject.toml</code></p> <p>I am using <code>lib_2</code> and imported it as</p>...
<python><pip><python-packaging><uv>
2024-02-22 16:27:07
0
2,405
Rahul Kumar
78,042,588
2,013,056
LIst in Python is empty but not empty - Selenium
<p>I am trying to extract path of the files changed in gitee. I can see there is only one file present in the files changed section but when I try to get it, 2 empty blocks comes along with the file. I checked everything but not sure why this is happening. Following is my code. The URL I am trying to extract fixed file...
<python><python-3.x><selenium-webdriver>
2024-02-22 16:26:57
1
649
Mano Haran
78,042,398
10,448,070
Getting 403 status code with GET request on Azure Function
<p>I'm encountering an issue with a Python script deployed as an Azure Function, which performs GET requests to URLs. The script works as expected for most URLs I've tested, but for certain ones, such as <a href="https://nationworldnews.com/mercedes-benz-improves-driver-experience-with-azure-openai-service/#:%7E:text=M...
<python><azure><http><server><python-requests>
2024-02-22 16:02:32
1
340
Coder_H
78,042,058
16,815,358
How to update cell output of a jupyter notebook which is hosted on a network IP
<p>I have a problem with a jupyter notebook that I have on a raspberry pi and am hosting on our IP address.</p> <p>To do this, I used <code>jupyter notebook --generate-config</code> to generate the configuration file, where I then edited the <code>c.NotebookApp.ip = 'localhost'</code> to the IP address of our network. ...
<python><jupyter-notebook><raspberry-pi><remote-access>
2024-02-22 15:11:17
1
2,784
Tino D
78,042,035
11,101,156
Langsmith is incorrectly tracing tokens
<p>I have a simple langgraph chain in place and I noticed that the counting of tokens is oddly off in langsmith in comperison to OpenAI online tokenizer or Python tokenizer:</p> <p>Langsmith tokens (2,067): <a href="https://i.sstatic.net/MnAoG.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/MnAoG.png" al...
<python><openai-api><langchain><langsmith>
2024-02-22 15:08:41
0
2,152
Jakub Szlaur
78,041,881
7,133,942
How to reduce the x-axis ticks in matplotlib and still spread them over the whole x-axis
<p>I have the following code to plot 6 subfigures with a common x-axis in matplotlib (the first subfigure contains many diagrams):</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt file_path = r&quot;C:\Users\wi9632\Desktop\Results_End_MultiOpt\Load_Profile_Figure\Combined_Table.csv&quot; df = pd.re...
<python><matplotlib>
2024-02-22 14:47:41
2
902
PeterBe
78,041,844
1,862,861
How can I differentiate between a PyTorch Tensor and a nested tensor?
<p>Recently, PyTorch introduced the <a href="https://pytorch.org/docs/stable/nested.html" rel="nofollow noreferrer">nested tensor</a>. However, if I create a nested tensor, e.g.,</p> <pre class="lang-py prettyprint-override"><code>import torch a = torch.randn(20, 128) nt = torch.nested.nested_tensor([a, a], dtype=torc...
<python><pytorch><tensor>
2024-02-22 14:41:10
1
7,300
Matt Pitkin
78,041,833
9,582,542
Click on svg label that has changing class
<p>The tag below has a changing class value so that can not be used to reference the tag. How to locate this tag and preform a click action</p> <pre><code>&lt;div class=&quot;x6s0dn4 x78zum5 x1q0g3np xs83m0k&quot;&gt;&lt;svg aria-label=&quot;Options&quot; class=&quot;x1lliihq x1n2onr6 x5n08af&quot; fill=&quot;currentCo...
<python><selenium-webdriver>
2024-02-22 14:40:08
2
690
Leo Torres
78,041,796
1,062,645
sklearn ridgeCV versus ElasticNetCV
<p>When setting <code>l1_ratio = 0</code>, the elastic net reduces to Ridge regression. However, I am unable to match the results obtained from sklearn's <code>ridgeCV</code> versus <code>ElasticNetCV</code>. They appear to produce very different optimal alpha values:</p> <pre><code>import numpy as np from sklearn.line...
<python><lasso-regression>
2024-02-22 14:34:19
1
378
Markus Loecher
78,041,738
81,444
Left join of 2 exploded polars columns
<h4>Considering</h4> <pre><code>import polars as pl df = pl.DataFrame({&quot;a&quot;: [ [1, 2], [3]], &quot;b&quot;: [ [{&quot;id&quot;: 1, &quot;x&quot;: 1}, {&quot;id&quot;: 3, &quot;x&quot;: 3}], [{&quot;id&quot;: 3, &quot;x&quot;: 4}]]}) </code></pre> <p>That looks like:</p> <pre><code>...
<python><left-join><python-polars><pandas-explode>
2024-02-22 14:27:08
2
8,163
Filippo Vitale
78,041,728
4,118,756
Plot facet normals in trimesh from the facet center
<p>For this sample torus mesh in <code>trimesh</code>, I've managed to plot the normals to facets:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np import trimesh mesh = trimesh.creation.torus(9, 3) # adapted from https://github.com/mikedh/trimesh/issues/549 vec = np.column_stack((mesh.facets_orig...
<python><numpy><mesh><trimesh>
2024-02-22 14:25:41
1
3,923
Vlas Sokolov
78,041,666
8,276,908
Implement an OR relationship for items that can occur in a JSON schema
<p>I am using jsonschema 4.17.3 with Python 3.7 to validate a JSON file. In this project I am facing a challenge, where I need to implement an OR relationship. This means in my case, that I require from 2 items that, either one of them is present, or both. This can be best explained with the JSON snippets below. Here, ...
<python><json><python-3.x><jsonschema>
2024-02-22 14:15:18
0
1,071
user8276908
78,041,555
6,394,617
Python development dependencies
<p>I'm familiar with installing dependencies using a <code>requirements.txt</code> or <code>environment.yml</code>, but I've only ever seen syntax in those files like <code>some_package&gt;=1.2.3</code>.</p> <p>What does it mean when dependencies are listed with curly braces, as in:</p> <pre><code>pytest = &quot;^6.2.5...
<python><dependency-management>
2024-02-22 13:58:42
1
913
Joe
78,041,062
14,282,714
At least one of TensorFlow 2.0 or PyTorch should be installed
<p>I would like to use this Image to text model from <a href="https://huggingface.co/llava-hf/llava-1.5-7b-hf" rel="nofollow noreferrer">HuggingFace</a>. When I run the code from the example I get an error:</p> <pre><code>from transformers import pipeline from PIL import Image import requests model_id = &quot;llav...
<python><tensorflow><huggingface-transformers>
2024-02-22 12:50:58
0
42,724
Quinten
78,040,964
10,333,905
How to properly pass dictionary to custom operator in Apache Airflow?
<p>I have created a custom operator which takes some parameters and ultimately triggers a glue job. Here's how it looks -</p> <pre class="lang-py prettyprint-override"><code>task = MyCustomOperator( task_id=&quot;my_op&quot;, custom_property=False, r_params = { &quot;run_date&quot;: &quot;{{ ds }}&q...
<python><airflow>
2024-02-22 12:34:39
1
499
Dark Matter
78,040,908
1,714,692
Is it possible in a multiindexed Pandas dataframe to have a column whose values refer to a higher level index?
<p>Suppose I have such a dataframe in Pandas:</p> <pre><code>df = pd.DataFrame({'a':[4,4,8,8],'b':[4,5,6,5], 'd':[0,1,2,1]}) multi_idx = pd.MultiIndex.from_arrays([[0,0,1,1],[0,1,0,1]]) df.index= multi_idx </code></pre> <p>which outputs this shape:</p> <pre><code> a b d 0 0 4 4 0 1 4 5 1 1 0 8 6 2 1 ...
<python><pandas><dataframe><multi-index>
2024-02-22 12:27:34
1
9,606
roschach
78,040,873
9,313,033
Type hints for mixins that reference attributes of a third-party base class
<p>I'm trying to add type hints to a mixin class that is to be used alongside an external, third-party class. That is, the mixin relies on members of the third-party class.</p> <p>For example, a mixin for a Django form:</p> <pre class="lang-py prettyprint-override"><code># mixin_typing.py from django import forms cla...
<python><django><mypy><python-typing>
2024-02-22 12:21:07
0
2,941
CoffeeBasedLifeform
78,040,774
1,567,264
I need a highly accurate simultaneous equation solver for Python
<p><code>np.linalg.solve(X,Y)</code> just isn't accurate enough. The code below solves a relatively small system of 5 equations:</p> <pre><code>import numpy as np n=5 Y = np.random.rand(n) X = np.tile(np.array(range(1,n+1)),n) X = X.reshape((n,n),order='F') for c in range(n) : X[:,c] = X[:,c]**c A = np.linalg.s...
<python><numpy><solver>
2024-02-22 12:02:52
1
361
Mas
78,040,430
464,277
Fitting model in hmmlearn
<p>I'm not sure I get how <a href="https://hmmlearn.readthedocs.io/en/stable/" rel="nofollow noreferrer">hmmlearn</a> expects the input data. Below is a modified example from the tutorial.</p> <pre><code>import numpy as np from hmmlearn import hmm states = ['up', 'down'] start_probs = np.array([0.6, 0.4]) vocabulary ...
<python><numpy><machine-learning><hmmlearn>
2024-02-22 11:08:22
0
10,181
zzzbbx
78,040,248
23,461,455
Visualize Nodes and their Connections as Clusters via networkx
<p>I have a list of Connections between two nodes describing links of entries in a Dataset.</p> <p>I'm thinking of vizualising the Entries and their connections to show that there are clusters of very similar entries.</p> <p>Each tuple stands for a pair of linked nodes. I've chosen weight as 1 for all of them since it'...
<python><matplotlib><graph><visualization><networkx>
2024-02-22 10:38:17
3
1,284
Bending Rodriguez
78,040,051
15,369
Why does importing a Python class instantiate it?
<p>A somewhat cut down example here from some PyTest unit tests that never exit. If I stick a break point on <code>DataListener.__init__</code> I see it getting called from the <code>from controller import Controller</code> statement in <code>test_controller.py</code> which was a bit of a suprise to me; Why does import...
<python><pytest><python-import>
2024-02-22 10:08:04
1
37,756
Jon Cage
78,039,918
13,086,128
How to use `isin` in Polars DataFrame?
<p>I have a polars DataFrame:</p> <pre><code>import polars as pl import numpy as np df = pl.DataFrame({'A': ['red', 'blue', 'green', np.nan, 'orange']}) my_list = ['red','orange'] </code></pre> <p>I want to know which colors are present in <code>my_list</code>.</p> <p>In pandas, I would do something like:</p> <pre><co...
<python><python-3.x><dataframe><python-polars>
2024-02-22 09:48:32
2
30,560
Talha Tayyab
78,039,906
21,049,944
Polars: Is there a procedure that ensures zero copy when calling df.to_numpy()?
<p>For some time now I am failing to call <code>df.to_numpy(allow_copy = True)</code>. Is there a procedure that transforms any given dataset into &quot;zero_copy suitable&quot; one?</p> <p>For list-like values I tried</p> <pre><code>data = pl.DataFrame(dict( points=np.random.sample((N, 3)), color=np.random.sam...
<python><numpy><python-polars><zero-copy>
2024-02-22 09:47:25
2
388
Galedon
78,039,802
9,506,773
How do I set up the default LLM_RAG_CRACK_AND_CHUNK_AND_EMBED setup for my existing services from a python script?
<p>I see that there is a default setup for this <a href="https://github.com/Azure/azure-sdk-for-python/blob/7afd09de107b91364b0d460c07a2ee198f64a2e9/sdk/ai/azure-ai-resources/azure/ai/resources/_index/_dataindex/constants/_component.py#L17" rel="nofollow noreferrer">here</a>. How can I set this up for my existing servi...
<python><azure><azure-cognitive-services><azure-sdk-python>
2024-02-22 09:34:40
1
3,629
Mike B
78,039,683
5,696,601
How to split layout and plot code into two files
<p>I would like to split the code for <a href="https://dash-example-index.herokuapp.com/bar-charts" rel="nofollow noreferrer">this</a> dashboard into two files namely <code>main.py</code> and <code>./folder/plot.py</code>. Actually, the plot is displayed correctly, but two <code>ID not found in layout</code> errors are...
<python><plotly-dash>
2024-02-22 09:17:31
1
1,023
Stücke
78,039,639
1,335,606
Multithreading implementation using python does not work
<p>I want to process multiple lists using multiprocessing. i have implemented this way. but its not working. could somebody help on this? main_list has one iteration,</p> <blockquote> <p>range(len(np_optimization))</p> </blockquote> <p>using this iterating again, i thing due to this multiprocessing not working.</p> <pr...
<python><multithreading>
2024-02-22 09:12:40
0
503
user1335606
78,039,598
4,828,720
Why is the child QObject still accessible when the parent is deleted?
<p>Trying to learn more about PyQt I wrote a small script that:</p> <ul> <li>Creates an <code>QObject</code> <code>a</code></li> <li>Creates an <code>QObject</code> <code>b</code> with <code>a</code> as its parent</li> <li>Deletes <code>a</code></li> </ul> <p>At this point I expect the object to which the name <code>b<...
<python><qt><pyqt><pyqt5><ownership>
2024-02-22 09:04:56
1
1,190
bugmenot123
78,039,596
23,461,455
How can I extract structure and content from a MariaDB SQL dump?
<p>I have an SQL dump file containing an entire MariaDB which is multiple gigabytes big. I don't have access to a local database installation due to company security restrictions. Can I execute my dump via Python in SQLite or extract its data so I can analyze it?</p> <p>I iterate my dump for table names to get an overv...
<python><sql><sqlite><mariadb>
2024-02-22 09:04:38
2
1,284
Bending Rodriguez
78,039,573
1,415,325
hexbin by matplotlib : get points in each hexagon?
<p>I am writting an app to interactively analyze 2D scatter plots with millions of points. To reduce the number of points to plot and prevent reinventing the wheel, I use 2D hexagonal binning from matplotlib. (density plot)</p> <p>The classical usage is:</p> <pre class="lang-py prettyprint-override"><code>import numpy ...
<python><matplotlib><binning>
2024-02-22 09:00:22
0
1,429
sweetdream
78,039,427
5,868,293
How to apply custom function with many parameters in a pandas column
<p>I have the following function</p> <pre><code>import math def f(k,a,x): return (1/(1+math.exp(-k*x))^a) </code></pre> <p>And the following pandas dataframe</p> <pre><code>import pandas as pd df = pd.DataFrame({'x': list(range(1,100))}) </code></pre> <p>How can I apply the above <code>function</code> on the <code>...
<python><pandas>
2024-02-22 08:35:20
1
4,512
quant
78,039,353
14,348,748
Why does slots not work with final dataclass attribute?
<p>I have a dataclass with <code>slots=True</code> and a final class variable/constant that is used as version identifier. For some reason that does not work as expected. I either need to remove the slots or change <code>Final</code> to <code>ClassVar</code>.</p> <p>Here is a minimal example:</p> <pre class="lang-py pr...
<python><python-3.x><python-typing>
2024-02-22 08:22:16
1
1,181
NicoHood
78,038,874
7,396,306
Plot bar and line y columns with vastly different scales and the and the same x axis using pandas DataFrame.plot() on a single figure
<p>I am making a little program to track weight loss and calorie intake.</p> <p>I am trying to plot two different columns from a single <code>DataFrame</code>. Each column is a different set of y variables and they are to be plotted on the same figure using the same x axis (which is a time series). One y variable is fo...
<python><pandas><matplotlib><plot>
2024-02-22 06:47:52
1
859
DrakeMurdoch
78,038,857
5,658,291
deep linking in react native using custom scheme link
<p>Hi I have done deeplinking in react native, Initially for testing purpose i have create on html page with hyper link if i click on that link if app is installed app is opening. I have been stuck on one thing where i am trying to put the same link in email template but that link is not clickable. Using Interakt for m...
<python><android><reactjs><react-native><deep-linking>
2024-02-22 06:42:47
1
579
Sudhir
78,038,847
185,977
Python how to mock a function that's returned by a higher-order function
<p>I'd like to mock the Pandas function <code>read_csv</code>, which in my code is returned dynamically by a higher-order function, but it seems the pytest <code>patch</code> doesn't really allow it.</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd format_read_func_mapping = {&quot;csv&quot;: pd...
<python><pytest><python-unittest>
2024-02-22 06:40:40
2
1,638
Sapience
78,038,534
1,806,998
PytestBDD target_fixture - PytestDeprecationWarning
<p>When I run <code>pytest</code> on the following code:</p> <pre><code>import requests from pytest_bdd import scenario, given, when, then @scenario('../features/user.feature', 'Create a new user') def test_create_user(): pass @given('a valid user payload') def valid_user_payload(): return { &quot;us...
<python><pytest><pytest-bdd>
2024-02-22 05:06:23
1
2,243
jerney
78,038,473
1,056,563
Getting "AttributeError: 'DefaultAzureCredential' object has no attribute 'signed_session'" using the azure.identity python package
<p>My code to read from the <code>Log Analytics Workspace</code> fails with the titular error.</p> <pre><code>from azure.identity import DefaultAzureCredential from azure.loganalytics import LogAnalyticsDataClient from azure.loganalytics.models import QueryBody from IPython.core.debugger import set_trace # Replace the...
<python><azure><azure-web-app-service><azure-sdk-python>
2024-02-22 04:46:30
1
63,891
WestCoastProjects
78,038,277
7,583,953
How is it possible to memoize longest divisible subset using only the length (and end position)?
<p>The goal is to find the largest divisible subset. A divisible subset is a subset s.t. for every pair of elements i, j, either i is divisible by j or j is divisible by i. The general approach to solve this is to sort the numbers and realize that if a is divisible by b and b by c, that a must also be divisible by c. H...
<python><algorithm><recursion><dynamic-programming><memoization>
2024-02-22 03:33:56
1
9,733
Alec
78,037,891
1,397,061
How to capture a DLL's stdout/stderr in Python?
<p>How can you capture a DLL's stdout and/or stderr in Python on Windows? For example, this prints <code>&quot;hello&quot;</code> to stderr, but it should be possible to capture the <code>&quot;hello&quot;</code> as a string instead of printing it:</p> <pre><code>import ctypes string = b'hello\n' ctypes.cdll.msvcrt._wr...
<python><windows><dll><msvcrt><kernel32>
2024-02-22 01:03:13
2
27,225
1''
78,037,775
12,884,304
Cannot find implementation or library stub for module named
<p>I have <code>mypy</code> pre-commit hook</p> <pre class="lang-yaml prettyprint-override"><code> - repo: https://github.com/pre-commit/mirrors-mypy rev: v1.8.0 hooks: - id: mypy args: - --config-file=./.styleconfigs/mypy.ini additional_dependencies: [ &qu...
<python><mypy><pre-commit-hook><python-3.11><pre-commit.com>
2024-02-22 00:11:41
1
331
unknown
78,037,765
19,556,055
Fitting a label to the size of text in Python with kivy
<p>I'm creating labels based on information that I'm drawing from a database, and I would like to left align it in the grid. For this, I'm trying to wrap the label tightly around the text so I can left align the label in an AnchorLayout. Because the text in my label and the number of these grids with labels are dynamic...
<python><kivy>
2024-02-22 00:09:14
2
338
MKJ
78,037,700
2,459,855
Image embedded in email also becomes an attachment
<p>A script that is correctly embedding inline images in HTML emails, is also adding the images as attachments. How can I eliminate this second copy of each image?</p> <p>If any intended attachments are included, they're processing correctly. With or without attachments, all images appear in the body of the message, an...
<python><email><html-email><email-attachments><mime>
2024-02-21 23:44:50
1
1,127
JAC
78,037,639
1,226,676
How to properly scope validator function in parent class for use in child class
<p>I'm trying to use validators, but I'm having a mysterious issue with using validators in a parent/child class.</p> <p>Right now I've created a base class for all media in my project; all media in this model need a name and a thumbnail:</p> <pre><code>class BaseMedia(BaseModel): def validate_thumbnail(image_obj):...
<python><django><django-models>
2024-02-21 23:23:56
1
5,568
nathan lachenmyer
78,037,554
2,084,503
CVXPY returning `Strict inequalities are not allowed.` with no strict inequalities
<p>I've got a script</p> <pre class="lang-py prettyprint-override"><code>import cvxpy x, y = cvxpy.Variable(), cvxpy.Variable() prob = cvxpy.Problem(cvxpy.Minimize( cvxpy.norm2(1, cvxpy.quad_over_lin(x, cvxpy.sqrt(y))) ), [y &gt;= 0]) print(prob.is_dcp()) </code></pre> <p>When I run this, I get</p> <pre><cod...
<python><cvxpy>
2024-02-21 23:01:34
1
1,266
Pavel Komarov
78,037,459
1,487,288
Selenium ChromeDriver / Flask Gunicorn, working in normal mode but failing in daemon mode
<p>I have a simple Flask app and the ChromeDriver is instantiated as such</p> <pre><code>options = webdriver.ChromeOptions() options.add_argument('--no-sandbox') options.add_argument(&quot;--headless&quot;) options.add_argument('--disable-dev-shm-usage') driver = webdriver.Chrome(service=Service(ChromeDriverManager()....
<python><selenium-webdriver><flask><selenium-chromedriver><gunicorn>
2024-02-21 22:35:53
0
1,442
elixir
78,037,427
2,364,295
iPython paste limit of one screen?
<p>I often like to debug by pasting hunks of code into my ipython terminal by just highlighting and middle clicking it (linux environment). Just now I'm noticing a limitation where it will only take in one screen full of code (one terminal with no scrolling). It's really weird because it doesn't truncate the code at t...
<python><linux><ipython>
2024-02-21 22:24:50
1
2,270
Mastiff
78,037,380
9,403,794
How to fill numpy array between two specific values
<p>I have to fill np array in row 2 with values from row 0. Array looks like that:</p> <pre><code>[[3. 4. 5. 6. 7. 8. 9. 8. 7. 6.] [0. 0. 1. 0. 0. 1. 0. 0. 0. 0.] [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]] </code></pre> <p>Finally it should looks like bellow</p> <pre><code>[[3. 4. 5. 6. 7. 8. 9. 8. 7. 6.] [0. 0. 1. 0. 0. 1. ...
<python><numpy>
2024-02-21 22:13:59
3
309
luki
78,037,358
7,100,546
Pandas df.shape not outputting anything?
<p>I have two similar sets (Same Columns, Different Row Count, Possibly different data in some rows) of data from two different databases, and I'm trying to run comparison via Pandas. I'm exporting both datasets to xlsx and then importing into jupyter lab as so:</p> <pre><code>df1 = pd.read_excel(&quot;Downloads/file1....
<python><pandas><dataframe><jupyter-lab>
2024-02-21 22:08:43
1
427
Rob
78,037,335
16,912,844
Execution Hang or Deadlock During `pytest` Using `asyncio.Queue` and `TaskGroup`
<p>I am new to async programming, I am trying to understand how <code>TaskGroup</code> can be used with <code>asyncio.Queue</code>. I have the below module with test, but when executing <code>pytest</code>, it prints out the queue item, but then it just hangs / deadlocks? Any suggestion on what I am doing wrong?</p> <p...
<python><pytest><python-asyncio><pytest-asyncio>
2024-02-21 22:03:59
1
317
YTKme
78,037,267
4,268,602
matplotlib: combining hatching with pcolormesh
<pre><code>colors = ['darkgreen', 'darkred', 'red', 'green', 'lightgray'] to_plot = np.swapaxes(all_channel_maps, 0, 1) # to_plot = all_channel_maps plt.pcolormesh(to_plot, edgecolors='k', linewidth=0.1, cmap=ListedColormap(colors)) ax = plt.gca() # ax.invert_yaxis() ax.set_aspect('equal') print(ax.pcolor) plt.show() <...
<python><matplotlib>
2024-02-21 21:46:31
1
4,156
Daniel Paczuski Bak
78,037,265
7,874,547
python pptx: How to check if text in two placeholders overlap
<p>I'm using python-pptx to create a presentation.</p> <p>I have a slide with 2 Text placeholders, the 1st above the 2nd (the same x-coord (shape.left)). When I put the text in both, the text in the 1st shape is long and overlap the text in the shape below. If I find out that there is the overlap, I can move the 1st sh...
<python><python-pptx>
2024-02-21 21:46:14
0
320
martin-voj
78,037,174
4,119,262
Why is function within main function in python always returning "none" when it should return a float?
<p>In order to learn python, I am trying to take a string from the user, convert this string in a float. I need to convert the minutes in a decimal number. This is what the &quot;convert&quot; function intends to do.</p> <p>But I always get &quot;none&quot; as output. What is wrong?</p> <pre><code> def main(): ...
<python><function><type-conversion><minute>
2024-02-21 21:23:47
3
447
Elvino Michel
78,037,028
4,706,711
How I can prevent ‘connection reset by peer’ in curl caused by server closing the socket
<p>I made a basic http server (I am developing my own because I want to do low level http analysis &amp; manipulation in a later stage):</p> <pre><code>import socket import threading import queue import time class SocketServer: &quot;&quot;&quot; Basic Socket Server in python &quot;&quot;&quot; de...
<python><python-3.x><sockets><curl>
2024-02-21 20:55:58
1
10,444
Dimitrios Desyllas
78,036,962
2,545,680
Which virtualenv tool is used by PyChart to create virtual envs
<p>PyChart has a configuration window to configure virtual env:</p> <p><a href="https://i.sstatic.net/1J8Oi.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/1J8Oi.png" alt="enter image description here" /></a></p> <p>Does anybody know what tool does it use to create those virtualenvs, e.g. venv or virtual...
<python><pip><pycharm>
2024-02-21 20:42:03
0
106,269
Max Koretskyi
78,036,895
5,790,653
python inline append to list and create a variable
<p>I have syntax error in this line:</p> <pre class="lang-py prettyprint-override"><code>data = [{'name': project['name'], 'id': project['id']} for projects in api.all_projects() project = projects.to_dict() if project['name'].startswith('name')] </code></pre> <p>I'm not sure where's the problem.</p> <p>Error message w...
<python>
2024-02-21 20:31:24
3
4,175
Saeed
78,036,766
2,868,322
Python/SQLModel; nice syntax to add a method call to `__init__` and `update`?
<p>I'm experimenting with SQLModel as an ORM. A few of my models have custom validation, calculated fields, or just things that I want to happen when they're created or changed. I end up using the following boilerplate a lot:</p> <pre><code>class MyModel(SqlModel): def __init__(self, **kwargs): super().__in...
<python><sqlalchemy><python-decorators><sqlmodel>
2024-02-21 20:03:13
1
887
charrison
78,036,731
11,144,121
save method or post_save signal is not being called while through model instance of a ManyToManyField is getting created
<p>I have a <code>Post</code> model in my Django app. It has a many-to-many relationship with <code>User</code> model through the <code>UserTag</code> model named <code>user_tags</code>.</p> <pre class="lang-py prettyprint-override"><code>class Post(models.Model): id = models.UUIDField(default=uuid.uuid4, editable=...
<python><django><django-signals>
2024-02-21 19:54:16
1
387
Tanvir Ahmed
78,036,552
2,013,056
Selenium code to extract text from project issue description
<p>I am trying to extract issue content from gitee using selenium in Python. But It gives blank when I try to extract the text. Here is the inspect element:</p> <p><a href="https://i.sstatic.net/5aulV.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/5aulV.png" alt="enter image description here" /></a></p>...
<python><python-3.x><selenium-webdriver>
2024-02-21 19:18:20
2
649
Mano Haran
78,036,516
11,748,924
pylance giving false negative import error in vscode
<p>I succesfully connect jupyter notebook in <em>external server linux</em> in my organization <code>http://100.96.0.29:8888/?token=...</code> through vscode in my <em>laptop windows</em>.</p> <p>I also succesfully installed some dependencies such as cupy through first cell <code>%pip install cupy</code>.</p> <p>I also...
<python><visual-studio-code><jupyter-notebook><pylance>
2024-02-21 19:08:55
2
1,252
Muhammad Ikhwan Perwira
78,036,426
12,274,651
Lookup values with sos1 in gekko
<p>The optimizer needs to select the appropriate discrete option to maximize an objective. It uses a lookup to correlate the option (0-5) to associated values that can then be used in the optimization definition. Here is a simplified version that demonstrates the issue:</p> <p><strong>Data</strong></p> <pre class="lang...
<python><mathematical-optimization><gekko>
2024-02-21 18:51:29
1
744
TexasEngineer
78,036,376
12,252,679
How to activate python environment in ZSH using VSCode terminal
<p>I have a folder called <code>src</code> where there is a python environment called <code>venv</code>.</p> <p>When <code>src</code> is open in VSCode, I need this environment to be activated as soon as I launch a terminal.</p> <p>In <code>src/.vscode/settings.json</code> I have set</p> <pre><code>&quot;python.termina...
<python><visual-studio-code><virtualenv><zsh><oh-my-zsh>
2024-02-21 18:40:23
1
482
Dj0ulo
78,036,351
104,910
ubuntu version of pip installs package_data to purelib
<p>I am trying to understand why a wheel created by Python 3.10 on <code>Ubuntu 22.04</code> is placing my <code>package_data</code> into a <code>purelib</code> directory while <code>Anaconda</code> (python 3.12) and <code>manylinux2014</code> (python 3.11 is not).</p> <p>My <code>setup.py</code>:</p> <pre><code>from s...
<python><ubuntu><pip><python-wheel>
2024-02-21 18:34:33
0
3,813
Juan
78,036,340
7,702,354
ansible get the last character of a fact
<p>I would like to have the last character of a fact. My playbook looks like this:</p> <pre><code>- name: sf set_fact: root_dev: &quot;{{ ansible_mounts|json_query('[?mount == `/`].device') }}&quot; - name: e debug: msg: &quot;{{ root_dev[:-1] }}&quot; </code></pre> <p>The problem is the output in this cas...
<python><string><ansible><slice>
2024-02-21 18:32:14
2
359
Darwick
78,036,302
265,521
Deadlock with Python async processes and semaphore
<p>Why does this deadlock?</p> <pre><code>#!/usr/bin/env python3 import asyncio async def _stream_subprocess(id: int, command: &quot;list[str]&quot;): proc = await asyncio.create_subprocess_exec(*command, stdout=asyncio.subprocess.PIPE) await proc.wait() print(f&quot;{id}: Done&quot;) async def run(id: ...
<python><python-asyncio><deadlock>
2024-02-21 18:26:20
1
98,971
Timmmm
78,036,062
18,964,988
How to get the status of a build on GithHub through PyGitHub
<p>I have a text file with a list of repos. I wanted to use pygithub to iterate through the list and tell me for each repo on whether the last build was successful or failure on dev or master branch depending on which one exists. This is what I have</p> <pre><code>from github import Github g = Github(base_url=&quot;ht...
<python><github><github-actions><github-api><pygithub>
2024-02-21 17:42:25
1
489
DevopitionBro
78,036,050
2,707,864
Sympy: Get the solutions of an ODE as Function objects
<p>As a follow-up of <a href="https://stackoverflow.com/questions/78031336/sympy-extract-the-two-functions-solutions-of-a-homogeneous-second-order-linear">Extract the two functions solutions of a homogeneous second order linear ODE</a>, I want to get <code>u1</code> and <code>u2</code> as Function objects. This way, I ...
<python><sympy><differentiation><symbolic-integration>
2024-02-21 17:40:21
0
15,820
sancho.s ReinstateMonicaCellio
78,035,957
9,443,671
How can I extract the duration and offset from a numpy array representing audio?
<p>I'm currently running a script where I take an entire audio file and save it using the <code>audiofile</code> library (which, in-turn, uses the <code>soundfile</code> library) in Python.</p> <p>I'm trying to mimic the behavior of <code>audiofile.read()</code> where I give it an offset and duration (in seconds) and o...
<python><numpy><audio><signal-processing><soundfile>
2024-02-21 17:24:50
1
687
skidjoe
78,035,952
728,286
Can MatPlotlib make charts with a deviation from zero?
<p>I'm trying to make a chart like this:</p> <p><a href="https://i.sstatic.net/AOBr9.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/AOBr9.png" alt="enter image description here" /></a></p> <p>or this:</p> <p><a href="https://i.sstatic.net/YGTdr.png" rel="nofollow noreferrer"><img src="https://i.sstatic....
<python><matplotlib><charts>
2024-02-21 17:24:34
0
4,914
Alex S
78,035,937
7,169,895
How do I adjust the QDateTimeAxis so the first and last points are not on the edges without shifting the values?
<p>I am trying to add padding to the QDateTimeAxis so the first and last points on not on the edge of the graph. I am trying to add a padding of about a month. I then graph some financial points of whether a company achieved a certain number EPS (a financial goal) that quarter.</p> <p>Here is what my graph looks like: ...
<python><pyside6>
2024-02-21 17:21:40
0
786
David Frick
78,035,781
15,341,457
Tkinter - winfo_height() always returns 1
<p>I have a function that gets called by clicking a button called <em>expand_keyword</em>. This function expands a row of a table to show more data. The data is contained in multiple frames called <em>single_cve_frame</em>.</p> <p>I'm trying to get the height of those frames by using the function <code>winfo_height()</...
<python><user-interface><tkinter><widget><height>
2024-02-21 16:58:53
0
332
Rodolfo
78,035,674
6,067,528
Why does collecting inbound and outbound audio create distorted audio?
<p>I'm trying to stream audio bytes into a shared buffer, and pass this through a transcription model. The audio's coming from a websocket sampled at 8kHz and mu-law encoded. I've managed to play a few seconds of audio to myself fine if I stream into separate separate audio buffers (<code>ibuffer</code> and <code>obuff...
<python><audio><twilio>
2024-02-21 16:42:48
2
1,313
Sam Comber
78,035,520
18,346,591
Draw grid lines behind text reportlab pdf
<p>I want to create a grid like this. On top of this grid would be behind some texts or images. I have already created the text and images on the pdf, but I do not know how to create this grid behind them.</p> <p>Any point in the right direction would be very helpful. A small complete solution would be more helpful. <a...
<python><pdf><reportlab>
2024-02-21 16:19:30
1
662
Alexander Obidiegwu
78,035,378
23,260,297
Read multiple sections of data in file with pandas
<p>I have an excel file that has data in multiple table-like format (not formatted as an excel table though) and I need to read this data into a singular dataframe.</p> <p>the spreadsheet looks something like this, with one table of data on top of the other:</p> <pre><code>Commodities Cashflows Heating Oil Counterpart...
<python><pandas>
2024-02-21 16:00:16
1
2,185
iBeMeltin
78,035,371
850,781
Temporarily change logging level - safely
<p>According to <a href="https://stackoverflow.com/q/19617355/850781">Dynamically changing log level without restarting the application</a> I can temporarily change logging level:</p> <pre><code>logger_level = my_logger.level my_logger.setLevel(logging.DEBUG) a = do_something_with_higher_logging1() b,c = do_something_w...
<python><logging><error-handling><python-logging>
2024-02-21 15:59:12
1
60,468
sds
78,035,329
1,714,692
Is it possible in a pandas dataframe to have some multiindexed columns and some singleindexed columns?
<p>In pandas I would like to have a dataframe whose some columns have a multi index, some don't.</p> <p>Visually I would like something like this:</p> <pre><code> | c | | |--------| d | | a | b | | ================| | 1 | 4 | 0 | | 2 | 5 | 1 | | 3 | 6 | 2 | </code></pre> <p>In pandas I can...
<python><pandas><dataframe><multi-index>
2024-02-21 15:53:41
2
9,606
roschach
78,035,296
7,008,416
How to check with mypy that types are *not* compatible
<p>Imagine I am writing a little Python library with one (nonsense) function:</p> <pre><code>def takes_a_str(x: str) -&gt; str: if x.startswith(&quot;.&quot;): raise RuntimeError(&quot;Must not start with '.'&quot;) return x + &quot;;&quot; </code></pre> <p>For runtime tests of the functionality, I can ...
<python><mypy><python-typing><pyright>
2024-02-21 15:50:25
2
10,152
Arthur Tacca
78,035,030
8,760,028
How to convert a of string to an array of object
<p>I have a string which contains values in some format (it is the output of an sql query). The string format is like this : <code>'enable id \n =============\nf avc-qwqwq\nt abd-rrtrtr\n f rec-yyuyu \n')</code></p> <p>So, the first 2 values are the column names of the sql and the rows are inside the \n values. So, I...
<python>
2024-02-21 15:00:51
2
1,435
pranami
78,034,888
1,232,660
Is string a valid type for annotation Sequence[Sequence[str]]?
<p>This is a typical example of a value that can be annotated by <code>Sequence[Sequence[str]]</code>:</p> <pre class="lang-py prettyprint-override"><code>[ ['This', 'is', 'the', 'first', 'tokenized', 'sentence', '.'], ['And', 'this', 'is', 'the', 'second', 'one', '.'], ] </code></pre> <p>I have learned that <a...
<python><string><python-typing>
2024-02-21 14:42:31
2
3,558
Jeyekomon
78,034,772
4,688,190
Seleniumbase: Intercept HTTP requests
<p>With Selenium Wire, you can intercept your requests like this:</p> <pre><code>from seleniumwire import webdriver def intercept_response(request, response): print(request.headers) driver = webdriver.Chrome() driver.response_interceptor = intercept_response </code></pre> <p>This prints a continuous stre...
<python><selenium-chromedriver><seleniumbase>
2024-02-21 14:26:33
1
678
Ned Hulton
78,034,721
2,249,312
Converting excel bloomberg function to python
<p>I m trying to convert this excel formula into python:</p> <pre><code>=@BDH(&quot;MZBZ4C 75.00 Comdty&quot;,&quot;Trade,Settle&quot;,&quot;2024-02-20 09:00:00&quot;,&quot;&quot;,&quot;Dir=V&quot;,&quot;IntrRw=true&quot;,&quot;Headers=Y&quot;,&quot;Dts=S&quot;,&quot;QRM=S&quot;,&quot;cols=4;rows=4&quot;) </code></pre...
<python><bloomberg>
2024-02-21 14:18:51
1
1,816
nik
78,034,551
14,897,644
Why my LSTM Model forecasts almost straight line on validation set?
<p>I trained a BI-LSTM model on stock prices. For this model, I did 2 approaches of backtesting :</p> <ol> <li>Applying the predict function for the whole validation set and then compare predictions to real data</li> <li>Predict the whole validation set based on the prediction of each day and then using it to predict t...
<python><tensorflow><keras><deep-learning><time-series>
2024-02-21 13:51:48
1
417
Rgrvkfer
78,034,483
539,490
Python type of generic Enum class of str
<p>Is there a generic <code>type</code> of enum that is possible for the following function <code>format_enum_as_list_with_quotes</code>:</p> <pre class="lang-py prettyprint-override"><code>from enum import Enum, EnumMeta class Demo(str, Enum): one = &quot;one&quot; two = &quot;two&quot; three = &quot;thr...
<python><enums><python-typing>
2024-02-21 13:42:07
1
29,009
AJP
78,034,468
7,002,816
Decoupling of models from flask-sqlalchemy
<p>Usually, I develop web-apps with ASP .Net Core but recently I had to create a python flask app using ORM with sqlalchemy. First, everything worked quite well. The trouble started when I tried to clean up the design and decouple the packages in order to be testable in unit-tests.</p> <p>I ran into the problem, that a...
<python><flask><sqlalchemy>
2024-02-21 13:39:46
1
342
LosWochos
78,034,110
12,696,223
Are Python C extensions faster than Numba JIT?
<p>I am testing the performance of the Numba JIT vs Python C extensions. It seems the C extension is about 3-4 times faster than the Numba equivalent for a for-loop-based function to calculate the sum of all the elements in a 2d array.</p> <h3>Update:</h3> <p>Based on valuable comments, I realized a mistake that I shou...
<python><c><pandas><numpy><numba>
2024-02-21 12:43:41
2
990
Momo
78,034,052
2,516,892
"UNKNOWN" project name and version number for my own pip-package
<p>I successfully built my first Python-Package using a <code>pyproject.toml</code> with <code>setuptools</code>. I am able to install it and use it in Python, however I wonder the name of the project is &quot;<code>UNKNOWN</code>&quot; and the version <code>0.0.0</code>, despite set differently in the configuration.</...
<python><setuptools><python-packaging>
2024-02-21 12:33:29
1
1,661
Qohelet
78,034,030
16,425,408
How to keep the Python script running continuously on a GCP VM
<p>Recently, I developed a Python script that runs on a GCP VM. This script takes user input and generates the corresponding output based on that input.</p> <p>When I attempted to run it on a GCP VM, it executed without any problems, and the script performed perfect. However, after a couple of hours, the script complet...
<python><google-cloud-platform><server><automation><google-compute-engine>
2024-02-21 12:30:36
1
838
Nani
78,033,906
5,561,649
Is there a way to let mypy check multiple import paths while looking for an object?
<p>I'm working on a project where we've created a module that wraps around a third-party module (containing several submodules). The wrapper module is designed to handle certain functions internally, but also call functions from the third-party module when necessary.</p> <p>I'd like to find a way to help static analysi...
<python><mypy><python-typing>
2024-02-21 12:13:27
0
550
LoneCodeRanger