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,449,324
1,405,689
Wrong matrix assigment in Python?
<p>I have this code:</p> <pre><code>#! /usr/bin/env python import sys import numpy import math inputfile = open(sys.argv[1], 'r') atoms = numpy.zeros((6, 3), dtype='float64') for line in inputfile: sline = line.split() header = sline[0] for i in range(1, 4, 1): atoms[i] = float(sline[i]) #...
<python><numpy>
2024-05-08 14:37:21
2
2,548
Another.Chemist
78,449,321
2,612,235
Seeking an Efficient Perfect Hashing Function integer keys running on a small MCU?
<p>I am developing a CANopen slave stack on a 200 MHz microcontroller and require a highly efficient lookup method to match a 16-bit object index (e.g., 0x603d) with a table index where the objects are stored. The expected range for used objects is between 200 and 400.</p> <p>Although I considered using a perfect hashi...
<python><hash><perfect-hash>
2024-05-08 14:37:06
1
29,646
nowox
78,449,301
10,639,694
Pythonic way of dumping a valid JSON string as JSON
<p>Suppose I have a valid JSON string that I want to make part of a larger JSON object. The most straightforward solution is parsing the string as dict, then dumping it again to JSON:</p> <pre class="lang-py prettyprint-override"><code>import json json_str = '{&quot;name&quot;: &quot;Alice&quot;, &quot;age&quot;: 30}'...
<python><json>
2024-05-08 14:34:15
1
989
AlexNe
78,449,229
3,204,810
Reading file, if-statement and break
<p>What I need is read a simple text file and stop to read when a certain string matches. Text file is:</p> <ul> <li>Apple</li> <li>Banana</li> <li>Watermelon</li> <li>Pear</li> <li>Apricot</li> </ul> <p>My minimal &quot;working&quot; example</p> <pre><code> with open(&quot;C:\\Python\\test.txt&quot;) as file: ...
<python>
2024-05-08 14:21:50
1
391
user3204810
78,449,183
1,208,289
sample using negated normal via numpy
<p>I have a sorted list that I need to sample from. I want to favor the items towards each end of the list. In other words, I want to sample from the list using a negated normal function such that the first and last entries of the list are chosen more frequently than items in the middle of the list. I tried this:</p> <...
<python><numpy><random>
2024-05-08 14:13:39
1
5,422
Brannon
78,449,105
1,243,247
How to extract text from ipwidgets Text widget
<p>The documentation for this is very cumbersome and time-consuming. I need a simple basic Hello World example to extract a simple text from a text box</p> <pre class="lang-py prettyprint-override"><code>from ipywidgets import interact, widgets from IPython.display import display dossier_number_widget = widgets.Text( ...
<python><jupyter-notebook><ipywidgets>
2024-05-08 13:58:50
1
16,504
João Pimentel Ferreira
78,449,045
214,296
How to combine list of objects into list of tuples (matrix style) in Python?
<p>Let's say that I have a list of tuples <code>foo</code> (object, integer) and a list of objects <code>bar</code>. The length of each of these parent lists is variable. How do I combine them into a single list of tuples, wherein each tuple is a unique combination of elements from each of the two parent lists?</p> <u...
<python><tuples>
2024-05-08 13:49:49
2
14,392
Jim Fell
78,449,042
562,697
QTreeWidget findItems always returns nothing
<p>I have a simple tree with at most 30 items and at most a depth of 2. I am trying to find a specific item in the tree that is in the second column (which is hidden from display). When I search for a string I can guarantee it in the tree, I still get a list of nothing.</p> <p>I am obviously misunderstanding the docume...
<python><pyqt6>
2024-05-08 13:49:04
0
11,961
steveo225
78,449,014
3,873,799
Slow download speed on Azure VM when installing Python library
<p>Disclaimer: I have read other similar SO questions but none of them applies to this case<sup>1,2</sup>.</p> <p>I am trying to install a Python library in my Azure Ubuntu VM. The library is <a href="https://github.com/PaddlePaddle/PaddleOCR/blob/main/doc/doc_en/quickstart_en.md#11-install-paddlepaddle" rel="nofollow ...
<python><azure><virtual-machine><throttling><download-speed>
2024-05-08 13:45:34
1
3,237
alelom
78,448,914
13,314,132
Why did my fine-tuning T5-Base Model for a sequence-to-sequence task has short incomplete generation?
<p>I am trying to fine-tune a <code>t5-base</code> model for creating appropriate question against a compliance item. Compliance iteams are paragraph of texts and my question are in the past format of them. I have trained the model, saved it and loaded it back for future usecases.</p> <p>The problem is when I am trying...
<python><huggingface-transformers><bert-language-model><nlp-question-answering>
2024-05-08 13:28:09
2
655
Daremitsu
78,448,761
18,730,707
How can I observe the intermediate process of cv2.erode()?
<p>I've been observing the results when I apply <code>cv2.erode()</code> with different <code>kernel</code> values. In the code below, it is <code>(3, 3)</code>, but it is changed to various ways such as <code>(1, 3)</code> or <code>(5, 1)</code>. The reason for this observation is to understand <code>kernel</code>.</p...
<python><opencv><image-processing><mathematical-morphology>
2024-05-08 13:05:38
2
878
na_sacc
78,448,727
223,960
How to get an Exception out of an ExceptionGroup?
<p>If I have an <code>ExceptionGroup</code> how do I get the <code>Exception</code> out of it? I happen to be using Trio.</p> <pre><code>&gt;&gt;&gt; exc &gt;&gt;&gt; ExceptionGroup('Exceptions from Trio nursery', [HTTPStatusError(&quot;Client error '400 Bad Request' for url 'https://api.fastly.com/service/xyz/acl/xyz...
<python><python-3.x><python-trio>
2024-05-08 13:01:27
3
8,190
Brian C.
78,448,698
447,426
How can I change pytest's working directory?
<p>I want to run the test if started via Visual Studio Code in the same directory as started from command line with <code>pytest tests</code>.</p> <p>The folder structure is as follows:</p> <pre><code>project-root |- .vscode - settings.json |-data-processing | |-src | |-tests </code></pre> <p>I run pytest from <code...
<python><visual-studio-code><pytest>
2024-05-08 12:57:01
1
13,125
dermoritz
78,448,694
216,575
Jupter notebook - 500 : Internal Server Error - Mac M1
<p>I am getting &quot;500 : Internal Server Error&quot; on my jupter when I click on ipynb or try to create a new one.</p> <p>In the console I see the following:</p> <pre><code>[E 22:52:50.872 NotebookApp] 500 GET /notebooks/Untitled.ipynb (::1) 73.950000ms referer=http://localhost:8888/tree [E 22:53:32.304 NotebookApp...
<python><jupyter-notebook>
2024-05-08 12:56:12
0
7,019
Ali Salehi
78,448,578
12,820,223
module has no attribute OOP in python
<p>I'm very new to OOP in python.</p> <p>I wrote a python script which takes an input file and plots some data from it. Now I want to make the same plots for several different data files, so I thought I'd make my script into a class.</p> <p>This class lives in a file called <code>TargetRunAnalyser.py</code> and goes li...
<python><class><oop>
2024-05-08 12:37:02
1
411
Beth Long
78,448,223
14,824,108
Different y-scales for barplot with multiple groups
<p>I have two groups in a barplot in <code>matplotlib</code> with measurements on different scales. I want the one on the right to have a separate y axis to not appear shrinked with respect to the one on the left. This is what I've tried so far:</p> <p>CODE:</p> <pre><code>import numpy as np import matplotlib.pyplot as...
<python><matplotlib>
2024-05-08 11:39:58
1
676
James Arten
78,448,089
17,174,267
Socket force different TCP packages
<p>I'm currently writing a few tests in Python regarding a TCP server of mine. I want to test behaviour when a message is split into multiple different packages. How can I force the OS to actually send the message and not wait for more data to avoid sending small packages? Just waiting <code>time.sleep</code> is not an...
<python><sockets>
2024-05-08 11:18:15
2
431
pqzpkaot
78,447,870
10,348,047
Why can't python httpd start a thread inside a python docker container?
<p>I'm trying to run a webserver to examine a system's behaviour under load.</p> <p>While looking at alternatives, I thought to try Python's webserver:</p> <p>If I run the following, it works as expected:</p> <pre><code>$ sh -c 'ulimit; date&gt;date.txt ; python3 -m http.server' &amp; unlimited Serving HTTP on 0.0.0.0...
<python><multithreading><docker><apache>
2024-05-08 10:40:03
1
618
Tim Baverstock
78,447,452
955,273
Coerce dataframe dtypes so dask doesn't issue a warning?
<p>I have a normal <code>pandas.DataFrame</code> which contains some string columns.</p> <pre class="lang-py prettyprint-override"><code>symbol_exch = pd.DataFrame( [ {'exchange': s['exchange'], 'symbol': s['symbol']} for s in exchange.symbols ], ) </code></pre> <p>I would like to merge this wit...
<python><pandas><dataframe><pyarrow><dask-dataframe>
2024-05-08 09:33:37
1
28,956
Steve Lorimer
78,447,289
1,320,143
How can I generate a UUID in a Pydantic BaseModel subclass?
<p>My code looks a bit like this:</p> <pre><code>class Error(BaseModel): id: uuid.UUID code: int def __init__(self, code: int) -&gt; None: self.id = uuid.uuid4() self.code = code super().__init__(id=self.id, code=code) </code></pre> <p>This errors out with:</p> <blockquote> <p>A...
<python><validation><pydantic>
2024-05-08 09:06:30
1
1,673
oblio
78,447,245
16,511,234
My function does not close the WebSocket connection
<p>I have a websocket client which connects to a real time data stream. The connection works fine and when I run <code>hello</code> it connects to the stream. Since the WebSocket server runs and sends permanently there is to much data in a really short time and I want to close the connection manually. I wrote the funct...
<python><websocket>
2024-05-08 08:58:07
1
351
Gobrel
78,447,053
7,499,018
Create multiple columns from a single column and group by pandas
<pre><code>work = pd.DataFrame({&quot;JOB&quot; : ['JOB01', 'JOB01', 'JOB02', 'JOB02', 'JOB03', 'JOB03'], &quot;STATUS&quot; : ['ON_ORDER', 'ACTIVE','TO_BE_ALLOCATED', 'ON_ORDER', 'ACTIVE','TO_BE_ALLOCATED'], &quot;PART&quot; : ['PART01', 'PART02','PART03','PART04','PART05','PART06']}) </code></pre> <p>How can I use Pa...
<python><pandas><dataframe><group-by>
2024-05-08 08:24:57
2
487
Martin Cronje
78,446,907
163,768
Loading MATLAB data in Python with h5py causes permuted dimensions
<p>I'm using the following code to load a MATLAB file into Python</p> <pre class="lang-python prettyprint-override"><code>import h5py import numpy as np filepath = 'file.mat' arrays = {} f = h5py.File(filepath) for k, v in f.items(): arrays[k] = np.array(v) a=arrays['data'] a.shape </code></pre> <p>Where in MATLA...
<python><matlab><import><hdf5><h5py>
2024-05-08 07:58:18
1
1,669
Demiurg
78,446,740
4,415,232
Normalize / flatten nested list of JSON
<p>I have this list with lots of JSON (here shortened) in it, which are very nested and I want to normalize it and bring it all to one level in the JSON.</p> <p>What I have:</p> <pre><code>[{'index': 'exp-000005', 'type': '_doc', 'id': 'jdaksjdlkj', 'score': 9.502488, 'source': {'user': {'resource_uuid': '123'}...
<python><json>
2024-05-08 07:26:05
2
1,235
threxx
78,446,556
10,308,337
Parallel computing for sequentially dependent tasks
<p>I understand that Python <a href="https://youtu.be/YOhrIov7PZA?si=3mvIr-ETh4yAjXxJ" rel="nofollow noreferrer">multi-processing</a> and <a href="https://youtu.be/3dEPY3HiPtI?si=FtSzYULS4xb-s2QJ" rel="nofollow noreferrer">multi-threading</a> can accelerate running independent tasks. However, If I have 10 tasks sequent...
<python><tensorflow><pytorch><parallel-processing>
2024-05-08 06:49:38
1
327
John
78,446,412
6,042,172
python plotly x axis dates show all ticks
<p>I'm using plotly.graph_objects to generate a html with data embedded.</p> <p>Although I am really pleased with the library, I cannot make it display all my x-axis ticks in some scenarios, as shown below.</p> <p><a href="https://i.sstatic.net/pzI2itFf.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/pzI...
<python><date><plotly>
2024-05-08 06:18:52
1
908
glezo
78,446,337
11,082,866
Merge columns with same name but one empty and another containing values
<p>I have a dataframe in which there are couple of columns with same name. How can I merge them in the same dataframe? df:</p> <pre><code>items_group quantity items_group quantity KIT1240 12 KIT1265 7 KIT1265 6 KIT1198A 6 KIT1264 ...
<python><pandas>
2024-05-08 05:56:47
1
2,506
Rahul Sharma
78,446,023
6,011,193
In colab, `ollama serve &` froze running
<p>I run following sh in colab</p> <pre><code>!ollama serve &amp; !ollama run llama3 </code></pre> <p>it out</p> <pre><code>2024/05/08 03:51:17 routes.go:989: INFO server config env=&quot;map[OLLAMA_DEBUG:false OLLAMA_LLM_LIBRARY: OLLAMA_MAX_LOADED_MODELS:1 OLLAMA_MAX_QUEUE:512 OLLAMA_MAX_VRAM:0 OLLAMA_NOPRUNE:false OL...
<python><jupyter-notebook><artificial-intelligence><google-colaboratory><ollama>
2024-05-08 03:55:01
1
4,195
chikadance
78,446,021
89,233
How to properly refresh Google Cloud Python API credentials?
<p>I'll re-formulate this question based on the feedback.</p> <p>First, a few base facts:</p> <ol> <li>I'm writing a GUI application that talks to google cloud services using the <code>google.cloud</code> Python SDK.</li> <li>I'm using google oauth <code>DeviceClient</code> flow to sign in from a GUI application.</li> ...
<python><google-cloud-storage><google-oauth><google-api-python-client><google-cloud-sdk>
2024-05-08 03:54:03
1
7,386
Jon Watte
78,446,007
9,516,820
Is it necessary to call torch.no_grad() even in evaluation mode?
<p>I am learning <code>pytorch</code>. In the code examples, the model is switched between training and testing by using the <code>model.train()</code> and <code>model.eval()</code> modes. I understand that this has to be done to deactivate training specific behaviour such as dropouts and normalisation and gradient com...
<python><pytorch>
2024-05-08 03:45:46
1
972
Sashaank
78,445,820
432,509
How to inspect the body of a function (without it's signiture)
<p>How can a function's body be inspected in Python?</p> <pre class="lang-py prettyprint-override"><code>def main(): def example_function(): x = 4 y = 3 if x + y &lt; 6: print(&quot;Test&quot;) print(&quot;Example&quot;) import inspect print(inspect.getsource(ex...
<python><introspection>
2024-05-08 02:23:13
0
49,183
ideasman42
78,445,577
14,230,633
Polars select multiple element-wise products
<p>Suppose I have the following dataframe:</p> <pre><code>the_df = pl.DataFrame({'x1': [1,1,1], 'x2': [2,2,2], 'y1': [1,1,1], 'y2': [2,2,2]}) ┌─────┬─────┬─────┬─────┐ │ x1 ┆ x2 ┆ y1 ┆ y2 │ │ --- ┆ --- ┆ --- ┆ --- │ │ i64 ┆ i64 ┆ i64 ┆ i64 │ ╞═════╪═════╪═════╪═════╡ │ 1 ┆ 2 ┆ 1 ┆ 2 │ │ 1 ┆ 2 ┆ 1 ┆ 2...
<python><dataframe><python-polars>
2024-05-08 00:15:44
1
567
dfried
78,445,534
1,606,161
ManagedIdentityCredential authentication unavailable, no managed identity found - Azure Synapse PySpark
<p>We are trying to generate token for custom rest api endpoint. We are using Azure Synapse Notebook in PySpark.</p> <pre><code>from azure.identity import DefaultAzureCredential,ManagedIdentityCredential import requests credential = ManagedIdentityCredential(client_id='xxxxxx-xxxx-xxxx-xxxx-xxxxx') </code></pre> <p>Th...
<python><pyspark><azure-synapse><azure-managed-identity><azure-identity>
2024-05-07 23:56:28
1
909
arpan desai
78,445,520
432,509
Alternative to bare except in Python?
<p>Documentation on exception handling tends to focus on using specific exception types – which is good advice in general.</p> <p>However there are times I want to run some Python code which <strong>under no circumstances</strong> throws an exception that isn't handled and stops the program from running:</p> <p>For exa...
<python><exception>
2024-05-07 23:46:27
1
49,183
ideasman42
78,445,511
11,104,068
Unable to read socket stream in Python, gets stuck at recvfrom. Works in DotNet/Terminal
<p>I have a device that converts analog audio to digital audio, and there's a way to listen to the stream in my local server through the UDP protocol.</p> <ul> <li>Working- When in my terminal, if I run <code>echo 'subscribe' | nc -u 192.168.0.194 9444</code>, I receive a response for ~15 seconds shown as below which I...
<python><.net><sockets><udp><pyaudio>
2024-05-07 23:41:09
1
5,159
Saamer
78,445,464
2,986,153
how to control size of images in quarto html report
<p>I have tried to set image size using the chunk options <code>fig.height</code> and <code>fig-height</code> but the image sizes are unaffected.</p> <pre><code>--- title: 'image size' author: 'Joseph Powers' date: 2024-05-07 format: html: toc: true toc-depth: 3 html-math-method: webtex edit...
<python><html><jupyter><quarto>
2024-05-07 23:18:57
1
3,836
Joe
78,445,434
2,192,824
How to parse the content in a file to multiple protobuf message
<p>For example, I have the following txt file, and I want to use python to parse them to two protobuf message lists. list1 contains an object of &quot;description&quot; and list2 contains two objects of &quot;msg&quot;. What would be the best way to do it? I looked into the text_format.py defined by google protobuf, an...
<python><python-3.x><protocol-buffers>
2024-05-07 23:05:04
0
417
Ames ISU
78,445,429
4,613,606
Scraping data after clicking a checkbox in python
<p>I am trying to scrape some links from this <a href="https://jobs.tjx.com/global/en/search-results?rk=l-retail-jobs" rel="nofollow noreferrer">career website</a>. Problem is, before scraping the links, I need to select a particular brand (Say Sierra). Question is how do I click on dropdowns and checkboxes to select a...
<python><html><css><selenium-webdriver><web-scraping>
2024-05-07 23:03:11
1
1,126
Gaurav Singhal
78,445,394
2,475,195
Pandas rolling min, corresponding value from other column
<p>I have an index-like column whose value I want to report for the rolling min value. Here's the code:</p> <pre><code>d = pd.DataFrame.from_dict({'ix':[0,1,2,3,4,5], 'val': [1,-2,5,4,9,6]}) d['first'] = d['val'].rolling(3).apply(lambda x: x.iloc[0] if not x.empty else None) d['min'] = d['val'].rolling(3).min() d['ix_...
<python><pandas><dataframe><rolling-computation>
2024-05-07 22:47:58
1
4,355
Baron Yugovich
78,445,374
2,561,747
How to expand dict into f-string similar to {variable=}?
<p>Is there a way to expand a dict into a f-string with a similar result to using the <code>{variable=}</code> syntax? Where each key-value pair would be treated as key=value, and items would be separated by commas?</p> <p>For example:</p> <pre><code>kwargs = dict(a=5, b=2) f'got {**kwargs=}' # results in an error: Syn...
<python>
2024-05-07 22:39:25
1
1,394
user2561747
78,445,372
18,764,592
Flask: cannot curl it from docker container
<p>Have 2 applications:</p> <ol> <li>Inside docker container</li> <li>Python Flask as http://localhost:5000. 1st application should call Python Flask.</li> </ol> <p>Yes, I know that localhost unreachable from docker container. To get localhost, I put the following lines in <code>docker-compose.yml</code>:</p> <pre clas...
<python><python-3.x><docker><flask><docker-compose>
2024-05-07 22:36:23
0
385
vbulash
78,445,310
3,746,427
Custom x-axis matplotlib
<p>I have written this python code to plot normal distribution where I am trying to modify x-axis, however, it is not appearing</p> <pre><code>import numpy as np from scipy.stats import norm from matplotlib import rcParams import matplotlib.pyplot as plt import matplotlib as mpl # make greek symbols appear on plot rcP...
<python><matplotlib>
2024-05-07 22:10:46
1
2,022
nsinghphd
78,445,270
825,227
Python defaultdict using lambda function causes error: TypeError: <lambda>() missing 1 required positional argument: 'x'
<p>Trying to map input text to associated numeric values, allowing for missing non-represented entries using a <code>defaultdict</code>.</p> <p>Running the below works, but when I add the default using a <code>lambda</code> I get an error.</p> <pre><code>z Out[216]: 0 $1,001 1 $1,001 2 $50,001 3 ...
<python><lambda><defaultdict>
2024-05-07 21:58:54
2
1,702
Chris
78,445,183
2,475,195
Pandas rolling - first value in window
<p>I have code that looks like this</p> <pre><code>d = pd.DataFrame.from_dict({'ix':[0,1,2,3,4,5], 'val': [1,-2,5,4,9,6]}) d['first'] = d['val'].rolling(3).agg(lambda rows: rows[0]) </code></pre> <p>Per the suggestion here <a href="https://stackoverflow.com/questions/60940098/taking-first-and-last-value-in-a-rolling-wi...
<python><pandas><dataframe><rolling-computation>
2024-05-07 21:34:35
1
4,355
Baron Yugovich
78,445,161
8,652,920
How to set the permissions of all files in a folder, given directory name using python?
<p>Self explanatory. But basically I'm trying to <code>shutil.rmtree</code> <code>~/.ssh</code> and a private key has restrictive read/write permissions.</p> <p>I don't want to make any assumptions about the name of the key, so I want to chmod 777 everything in <code>~/.ssh</code> and then <code>shutil.rmtree</code> it...
<python><python-3.x><chmod><shutil>
2024-05-07 21:29:15
1
4,239
notacorn
78,445,033
6,546,694
Implement frequency encoding in polars
<p>I want to replace the categories with their occurrence frequency. My dataframe is lazy and currently I cannot do it without 2 passes over the entire data and then one pass over a column to get the length of the dataframe. Here is how I am doing it:</p> <p>Input:</p> <pre><code>df = pl.DataFrame({&quot;a&quot;: [1, 8...
<python><dataframe><python-polars>
2024-05-07 21:00:23
1
5,871
figs_and_nuts
78,444,883
13,119,730
Duplicate traces in FastAPI OpenTelemetry Azure Application Insight
<p>Im currently setting up Otel for our cloud azure solution. We are using Azure WebApp and AzureAppInsights. The app is fastapi backend.</p> <p>I have set up the otel like:</p> <pre class="lang-py prettyprint-override"><code>def setup_otel(app: FastAPI): if settings.APPLICATIONINSIGHTS_CONNECTION_STRING: c...
<python><azure><fastapi><azure-application-insights><open-telemetry>
2024-05-07 20:19:20
1
387
Jakub Zilinek
78,444,814
5,693,706
Altair use multiple selections in multi-layer chart
<p>I would like to have multiple selections in a multi-layer chart. One selection should highlight the closest line and the other should highlight the point on each line closest to the current x position of the mouse.</p> <p>I can achieve this separately as shown below.</p> <p>Highlight line:</p> <pre class="lang-py pr...
<python><altair>
2024-05-07 20:01:49
0
1,038
kgoodrick
78,444,757
20,179,987
How to use the Frida Interceptor JS script from Python
<p>I'm working on a plugin for Binary Ninja where one of the features is to trace functions using Frida. The plugin is written in python (using python 3.10) but the Frida commands are in JavaScript. I am trying to load some JS code and make Frida run it (It is part of my understanding that Frida provides its own VM for...
<javascript><python><plugins><frida>
2024-05-07 19:45:19
0
322
GABRIEL R GARCIA-AVILES
78,444,497
6,817,610
Upgrading to Python 3.10, different users - python3 alias points to same binary but shows different versions
<p>In Debian 11 based docker container, I'm a bit confused as to why <code>root</code> and <code>jenkins</code> users' <code>python3</code> command is pointing to the same binary but have different versions:</p> <pre><code>sh-5.1$ whoami jenkins sh-5.1$ python3 --version Python 3.9.2 sh-5.1$ which python3 /usr/bin/pyth...
<python><linux><bash><shell><debian>
2024-05-07 18:43:39
1
953
Anton Kim
78,444,488
9,251,158
How to force x label on Matplotlib
<p>I want to add labels on the horizontal and vertical axes on Matplotlib, and I can't seem to. Here's a minimal reproducible example:</p> <pre class="lang-py prettyprint-override"><code>import matplotlib.pyplot as plt import numpy as np # generate x and y x = np.linspace(0, 1, 101) y = 1 + x + 0.4 * np.random.random(...
<python><matplotlib><axis-labels>
2024-05-07 18:39:51
0
4,642
ginjaemocoes
78,444,253
5,878,756
Autoencoders and Polar Coordinates
<p>Can an autoencoder learn the transformation into polar coordinates? If a set of 2D data lies approximately on a circle, there is a lower-dimensional manifold, parameterized by the angle, that describes the data 'best'.</p> <p>I tried various versions without success.</p> <pre><code>import matplotlib.pyplot as plt im...
<python><tensorflow><autoencoder><polar-coordinates>
2024-05-07 17:46:17
1
924
deckard
78,444,223
6,714,667
How to deal with csvs with description on top in langchain & Missing columns?
<p>I have the following csv i want to load with langchain:</p> <p><a href="https://i.sstatic.net/2fy8Hw8M.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/2fy8Hw8M.png" alt="enter image description here" /></a></p> <p>i did the following:</p> <pre><code>loader = CSVLoader(file_path='shopids.csv', encoding...
<python><csv><parsing><langchain>
2024-05-07 17:36:46
1
999
Maths12
78,444,199
2,840,125
PyQt5 - Return the value of a textbox that's next to a checkbox created via looping
<p>I'm created a PyQt5 dialog that builds a form based on a supplied pandas DataFrame. Each row of the form contains a QCheckBox with a name, a type label, and a status QLineEdit. The user is able to select/deselect rows and change the contents of the status QLineEdit. When the user clicks the OK button, I want the <co...
<python><pyqt5>
2024-05-07 17:31:33
1
477
Kes Perron
78,444,144
10,181,236
is there a way to know when stable-baselines use actor or critic net?
<p>Using stable-baselines3 I am implementing a custom feature extractor for a PPO agent. As the docs says <a href="https://stable-baselines3.readthedocs.io/en/master/guide/custom_policy.html" rel="nofollow noreferrer">here</a> the custom feature extractor net is shared between actor and critic network. I want to print ...
<python><reinforcement-learning><stable-baselines>
2024-05-07 17:20:52
0
512
JayJona
78,444,101
825,227
Footnotes causing errant match using regex in Python
<p>I'm parsing text in Python using regex that typically looks like some version of this:</p> <pre><code>JT Meta Platforms, Inc. - Class A Common Stock (META) [ST]S (partial) 02/08/2024 03/05/2024 $1,001 - $15,000 F S: New S O: Morgan Stanley - Select UMA Account # 1 JT Microsoft Corporation - Common Stock (MSFT) [ST]S...
<python><regex>
2024-05-07 17:12:40
1
1,702
Chris
78,443,992
1,075,332
Specifying custom arguments in sklear-style classes
<p>I'm trying to implement my own, sklearn-compatible classifier in Python. To that end, I inherit from <code>BaseEstimator</code> and <code>ClassifierMixin</code>, but I also define my own arguments in the constructor.</p> <p>While debugging, I noticed that invoking <code>__repr__()</code> interactively, in the IPytho...
<python><inheritance><scikit-learn><spyder>
2024-05-07 16:48:50
1
2,699
Igor F.
78,443,857
8,758,459
Python app stuck on deployment to Azure App Service via GitHub Actions
<p>I ran into an issue deploying a Python fastAPI server to an Azure App Service via GitHub Actions. I linked the code to a repository and then set up the CI pipeline to execute a deployment on new commits. The issue is that it never finishes deploying, seems to be stuck on the &quot;deploy&quot; task (waited 30+ min)....
<python><azure-web-app-service><github-actions><fastapi>
2024-05-07 16:14:18
1
395
John Szatmari
78,443,797
3,022,254
Trouble with Python Selenium Key Press
<p>I'm trying to set up some batch look-ups using the orthographic dictionary <a href="https://lcorp.ulif.org.ua/dictua/" rel="nofollow noreferrer">here</a>. Normally this requires one to type in the search box on the left and then click the &quot;пошук&quot; button beneath it:</p> <p><a href="https://i.sstatic.net/eqi...
<python><selenium-webdriver>
2024-05-07 16:03:49
1
1,372
Mackie Messer
78,443,779
11,246,056
How to check if a LazyFrame is empty?
<p>Polars dataframes have an <code>is_empty</code> attribute:</p> <pre class="lang-py prettyprint-override"><code>import polars as pl df = pl.DataFrame() df.is_empty() # True df = pl.DataFrame({&quot;a&quot;: [], &quot;b&quot;: [], &quot;c&quot;: []}) df.is_empty() # True </code></pre> <p>This is not the case for P...
<python><memory><python-polars><lazyframe>
2024-05-07 16:00:39
1
13,680
Laurent
78,443,705
11,505,680
Portable launcher for pdoc
<p>I have a Python package hosted in a private GitHub space. I want to distribute it with a batch file that launches <code>pdoc</code> (we can assume all users are on Windows). I wrote such a batch file for myself, and it's only one line:</p> <pre><code>&quot;C:\ProgramData\anaconda3\Scripts\pdoc.exe&quot; my_package <...
<python><batch-file><pdoc>
2024-05-07 15:45:56
1
645
Ilya
78,443,666
378,340
Sparse Clouds in Metashape Python Standalone Module don't match results in app with same settings
<p>I'm automating the the photogrammetry workflow for building models of objects on turntables. I have a pot, and I've taken pictures of the top and bottom. I've put these in one chunk rather than two. When I run the align photos workflow step with the following settings, I get a nice point cloud with all pictures alig...
<python><photogrammetry><metashape>
2024-05-07 15:38:53
1
1,009
Rokujolady
78,443,422
7,395,686
Tkinter UI auto enlarges after changing style
<p>So, I followed an online video, and tried to replicate the UI, while applying my own changes to fit my needs, but I ended up with a UI that keeps enlarging every time I change the theme.</p> <p>I tried commenting some parts of the code, to see where the problem lies, but to no avail, I'm pretty new to Tkinter, but I...
<python><python-3.x><tkinter>
2024-05-07 14:58:13
1
542
Amine Messabhia
78,443,220
17,388,934
Replace an element of a list with its value from a dataframe
<p>I have a data dictionary and a column_list. I want to replace the value in the column_list with its matching value from the data dictionary. I have written the below code; however, I'm unable to get the required output. Can someone please help to fix the overlapping values?</p> <pre><code>col_list = ['eff_strt_dte',...
<python><list><replace>
2024-05-07 14:28:03
2
319
be_real
78,443,142
9,302,146
Snowflake.py: RemovedInAirflow3Warning: This module is deprecated. Please use `airflow.providers.common.sql.hooks.sql`
<p>After upgrading airflow from <code>2.2.0</code> to <code>2.9.0</code> I have been getting the following warning:</p> <pre><code>snowflake.py:29 RemovedInAirflow3Warning: This module is deprecated. Please use `airflow.providers.common.sql.hooks.sql`. </code></pre> <p>However, it does not clearly state which changes I...
<python><snowflake-cloud-data-platform><airflow>
2024-05-07 14:15:33
1
429
Abe Brandsma
78,443,067
2,662,302
How make multiple when condition on polars
<p>I have a dictionary with strings as keys an polars expresions as values.</p> <p>How can I do something like this in a concise way:</p> <pre class="lang-py prettyprint-override"><code>df = df.with_columns( pl.when(condition_1) .then(pl.lit(key_1)) .when(pl.lit(condition_2)) .then(pl.lit(key_2)) .....
<python><dataframe><python-polars>
2024-05-07 14:03:47
1
505
rlartiga
78,442,790
4,415,232
python - Combine structured JSON with remaining JSON
<p>I have this structured df (json) which includes another json and I want to combine them to access all the values:</p> <pre><code>{ &quot;index&quot;: &quot;exp-000005&quot;, &quot;type&quot;: &quot;_doc&quot;, &quot;score&quot;: 9.502488, &quot;source&quot;: { &quot;verb&quot;: &quot;REPLIED&quot;, &...
<python><json>
2024-05-07 13:16:11
1
1,235
threxx
78,442,703
9,302,146
ERROR - Failed to execute task ' ti' (KeyError: ' ti' in Apache Airflow)
<p>I have been getting the following error (repeatedly) in <code>Airflow 2.9.0</code> after upgrading from <code>2.2.0</code>:</p> <pre class="lang-bash prettyprint-override"><code>2024-05-07T11:10:43.522+0000] {local_executor.py:139} ERROR - Failed to execute task ' ti'. Traceback (most recent call last): File &quo...
<python><docker><airflow>
2024-05-07 13:00:32
1
429
Abe Brandsma
78,442,635
6,763,074
Rhinoceros 8, Grasshopper and sys.path in Python IDE
<p>I work with <a href="https://www.rhino3d.com/8/new/" rel="nofollow noreferrer">Rhino 3d</a> and Grasshopper to support an engineer with some programming work in Python. The Python runtime was automatically installed to <code>C:\Users\Patrick Bucher\.rhinocode\py39-rh8</code>. The scripts work fine when executed in t...
<python><virtualenv><python.net>
2024-05-07 12:49:34
0
1,618
Patrick Bucher
78,442,459
956,424
Django 4.2 how to display deleted object failure in modeladmin page?
<p>Code used to override the delete_queryset in the modeladmin:</p> <pre><code> def get_actions(self, request): actions = super().get_actions(request) del actions['delete_selected'] return actions def really_delete_selected(self, request, queryset): ''' # 1. Update...
<python><django>
2024-05-07 12:21:59
1
1,619
user956424
78,442,162
11,922,237
How to construct a networkx graph from a dictionary with format `node: {neighbor: weight}`?
<p>I have the following dictionary that contains node-neighbor-weight pairs:</p> <pre class="lang-py prettyprint-override"><code>graph = { &quot;A&quot;: {&quot;B&quot;: 3, &quot;C&quot;: 3}, &quot;B&quot;: {&quot;A&quot;: 3, &quot;D&quot;: 3.5, &quot;E&quot;: 2.8}, &quot;C&quot;: {&quot;A&quot;: 3, &quot;E...
<python><graph><networkx><graph-theory>
2024-05-07 11:33:19
2
1,966
Bex T.
78,442,086
11,432,290
How to maintain separate sessions for diff users in llama_index chat also how can we pass previous chat messages in query for future responses?
<p>Hi I am using llama_index for indexing hundreds of docs that contain some specific details, now I want to build an API over it(in which I would get the session_id, query_text), which should be able to answer queries as per the info indexed from the docs, my implementation works for a single user, but the API would b...
<python><chatbot><openai-api><llama><llama-index>
2024-05-07 11:19:43
0
475
Yash Tandon
78,441,981
8,510,149
Groupby with condition - best practice
<p>I want to a groupby with a condition and then feed back the result to the original dataframe. In this case feature 'COl_COND' could either be 1 or 0, and the feature to be summarized is 'AMOUNT'.</p> <p>Below this is done by performing two groupby's, storing the result in pandas series and then merge back to the ori...
<python><pandas><group-by>
2024-05-07 10:59:01
3
1,255
Henri
78,441,494
21,117,677
Calling inference (ONNXRuntime) with largest-possible image size
<p>I'm using ONNX Runtime for image segmentation inference with a model converted from PyTorch. I want to run the image size as large as possible without crashing.</p> <p>Is there a method to dynamically check what image shape my graphics card can handle for a particular deep learning model?</p> <p>I call inference wit...
<python><deep-learning><onnx><inference><onnxruntime>
2024-05-07 09:31:54
0
396
rovsmor
78,441,462
3,076,544
Inconsistent Import Reordering on Save in VSCode with isort and autopep8
<p>I'm experiencing inconsistent behavior with VSCode's format on save feature, specifically with the organization of Python imports. Each time I save, the arrangement of imports alternates between two different formats.</p> <p>I'm using the Python extension along with the isort tool. My current settings are as follows...
<python><visual-studio-code><isort>
2024-05-07 09:26:39
0
993
MrT77
78,441,361
1,020,139
Is it permitted to supply a value for a TypeVar in Python?
<p>Consider the following generic type:</p> <p><code>Response(Generic[ResponseT])</code></p> <p>The type var is defined as follows:</p> <p><code>ResponseT = TypeVar(&quot;ResponseT&quot;)</code></p> <p>I have seen <code>Response[None]</code> usages without VS Code (Pylance/Pyright) complaining about type issues.</p> <p...
<python><python-typing><pyright>
2024-05-07 09:11:40
0
14,560
Shuzheng
78,441,342
16,567,918
django - is UniqueConstraint with multi fields has same effect as Index with same field?
<p>I wrote a django model that you can see below, I want to know having the <strong>UniqueConstraint</strong> is enough for <em><strong>Search and Selecting row base on user and soical type</strong></em> or I need to add the <strong>Index</strong> for them. if yes what is the different between them becuse base on my se...
<python><django><postgresql><indexing><orm>
2024-05-07 09:09:07
1
445
Nova
78,441,134
2,405,663
Translate VBA function in Python
<p>I have VBA function and I'm trying to convert this application in Python.</p> <p>Now I need to translate the following VBA code:</p> <pre><code>Dim R_SH(1 To 3, 1 To 3) As Double </code></pre> <p>in Python.</p> <p>I tried to write the following Python code but I think that is not correct:</p> <pre><code>w, h = 2, 3 ...
<python><vba>
2024-05-07 08:31:14
1
2,177
bircastri
78,441,056
16,511,234
Connect to websocket from request
<p>I want to connect to a websocket to process real time data. The URL look like this: <code>https://testsite.test.de/Interfaces</code>. When I enter it in Firefox it asks immediately for username and password. After I enter them the status codes are 200 with HTTP/1.1, 200 HTTP/2, 101 switching protocols connection upg...
<python><websocket>
2024-05-07 08:16:43
0
351
Gobrel
78,440,849
7,106,508
sqlite3.DataError: query string is too large
<p>I'm trying to analyze this wiktionary dump with is 5GB, but I'm getting the above error message in the title. Here is my code:</p> <pre class="lang-py prettyprint-override"><code> import sqlite3 conn = sqlite3.connect(':memory:') c = conn.cursor() sql_file = open(f'wiktionary_categories.sql',encoding...
<python><sql><sqlite3-python>
2024-05-07 07:35:30
1
304
bobsmith76
78,440,435
736,662
Is it possible to pick out an element in a JSON response structure based on a name in letters
<p>I am making an HTTP API call using Pytest and want to obtain a value given a name in letters. The response looks like this:</p> <pre><code> [ { &quot;hpsId&quot;: 10032, &quot;powerPlant&quot;: { &quot;name&quot;: &quot;Svartisen&quot;, &quot;id&quot;: 67302, &quot;regionId&quot;: 40, ...
<python><json>
2024-05-07 06:08:14
2
1,003
Magnus Jensen
78,440,430
2,981,639
Sorting a Polars list of structs based on a struct field value
<p>How do I use <code>polars.Expr.list.sort</code> to sort a list of structs by one of the struct values, i.e.</p> <pre class="lang-py prettyprint-override"><code>import polars as pl df = pl.DataFrame([{&quot;id&quot;: 1, &quot;data&quot;: [{&quot;key&quot;: &quot;A&quot;, &quot;value&quot;: 2}, {&quot;key&quot;: &quo...
<python><dataframe><python-polars>
2024-05-07 06:06:51
3
2,963
David Waterworth
78,440,228
2,966,723
Understanding the role of `shuffle` in np.random.Generator.choice()
<p>From the documentation for <a href="https://numpy.org/doc/stable/reference/random/generated/numpy.random.Generator.choice.html#numpy.random.Generator.choice" rel="nofollow noreferrer">numpy's <code>random.Generator.choice</code></a> function, one of the arguments is <code>shuffle</code>, which defaults to <code>True...
<python><numpy><random>
2024-05-07 05:09:02
2
24,012
Joel
78,440,162
2,023,397
How to scrape table data from HTML with BeautifulSoup?
<p>I have been trying to scrape a table from this website <a href="https://www.alphaquery.com/stock/aapl/earnings-history" rel="nofollow noreferrer">https://www.alphaquery.com/stock/aapl/earnings-history</a> but in no way I can achieve it. I can t even find the table.</p> <pre><code>import requests from bs4 import Beau...
<python><web-scraping><beautifulsoup><html-table><python-requests>
2024-05-07 04:44:49
1
397
Gloria Dalla Costa
78,440,085
1,019,455
Python packaged installed on Windows11, but not found when call
<p>I am using OSX 14.4.1 (23E224). Running parallel 18 + Windows 11. I have to run Windows because MetaTrader5(MT5) python package is not support OSX.</p> <p>Use 3.10 because it does support up to 3.10 <a href="https://stackoverflow.com/a/74346406/1019455">https://stackoverflow.com/a/74346406/1019455</a></p> <pre><code...
<python><macos><powershell><pip><windows-11>
2024-05-07 04:12:10
1
9,623
joe
78,439,955
7,085,728
Django `db_table` not renaming table
<p>This question is (surprisingly) unlike similar ones, which ask about doing this dynamically, or ask how to do it in the first place. This question regards those suggestions not working as expected.</p> <p>Brief summary of situation:</p> <ol> <li>We made a series of Django apps as part of an API used in a real web ap...
<python><django><django-migrations>
2024-05-07 03:20:40
0
689
Audiopolis
78,439,954
17,835,120
Adapt variables of recommendations from yfinance using python
<p>How do you adapt variables <a href="https://pypi.org/project/yfinance/" rel="nofollow noreferrer">recommendations</a> for consensus recs using yfinance library in python such as specified number of months, intervals and time period?</p> <p>The script below for example will provide 4 months, 1 month interval from cur...
<python><pandas><yfinance>
2024-05-07 03:20:30
1
457
MMsmithH
78,439,812
3,179,698
Using jupyterhub/jupyterhub in docker hub get error
<p>I want to use jupyterhub/jupyterhub to start a container running jupyterhub.</p> <p>So I create a Dockerfile:</p> <pre><code>FROM jupyterhub/jupyterhub RUN useradd -m test &amp;&amp; \ echo &quot;test:password&quot; | chpasswd </code></pre> <p>And using <code>docker build -t jupyterhub_test:3 .</code> to build ...
<python><docker><dockerhub><jupyterhub>
2024-05-07 02:16:22
1
1,504
cloudscomputes
78,439,806
9,129,978
Getting OSError: [Errno 86] Bad CPU type in executable when using PuLP CBC solver
<p>I am trying to use the following Python package on M3 Max Mac: <code>pydfs_lineup_optimizer</code>.</p> <p>I am using <code>Python 3.12.2</code>.</p> <p>However, I am getting the following error:</p> <pre><code>Traceback (most recent call last): File &quot;/private/tmp/test.py&quot;, line 6, in &lt;module&gt; ...
<python><linear-programming><solver><pulp>
2024-05-07 02:15:00
1
539
tera_789
78,439,733
4,613,606
Access data on EMR directory from EMR Studio: Workspaces (Notebooks)
<p>I have some data saved on s3, which I want to import while running a python script on EMR.</p> <p>To do it through a python code on EMR console: I just create the directories/file on my EMR like this <code>/home/mysource/settings</code> by copying the files from S3 to EMR and then the following code works as it shou...
<python><amazon-s3><import><amazon-emr>
2024-05-07 01:34:14
1
1,126
Gaurav Singhal
78,439,624
5,924,264
Hotkey for equal sign and colon alignment?
<p>I joined a company recently where they seem to like to align the <code>=</code> and <code>:</code> on consecutive lines in python, e.g., instead of</p> <pre><code>a = 0 bb = 2 ccc = 3 </code></pre> <p>they do</p> <pre><code>a = 0 bb = 2 ccc = 3 </code></pre> <p>and likewise for <code>:</code>. I find it very tedi...
<python><visual-studio-code><sublimetext3><text-alignment>
2024-05-07 00:40:53
1
2,502
roulette01
78,439,411
10,224
Can I install the mltable package into Anaconda?
<p>I need to use the mltable package to create mltable files for Azure Machine Learning from CSV files.</p> <p>I have Anaconda installed, but there does not seem to be a way to install the mltable package, since it is in PyPI but not anaconda.org. This seems like a common problem in general.</p> <p>What can I do here?<...
<python><package><anaconda><azure-machine-learning-service>
2024-05-06 22:40:26
1
6,804
Pittsburgh DBA
78,439,134
235,218
How to use Python's subprocess to run a 'conda list' command and pipe it to a text file
<p>My objective is to use Python's subprocess module to run the following 'conda list&gt;[fullPath_based_on_date]' command in the Anaconda prompt environment:</p> <pre><code>r'conda list&gt;z:\backup\Anaconda\conda_list_2024-05-06_13-23-45.txt' </code></pre> <p>I have not been able to find a way to get subprocess to ru...
<python><anaconda><subprocess><conda>
2024-05-06 21:09:23
3
767
Marc B. Hankin
78,438,990
6,197,439
Python3 custom pretty printer for derived class objects?
<p>I have attempted to make a pretty printer for a number of objects deriving from a class; but I have arrived at some behavior that puzzles me - I hope I can get some help to understand (and fix) it. Consider the following code:</p> <pre class="lang-python prettyprint-override"><code>from collections import OrderedDic...
<python><python-3.x><class><inheritance><pretty-print>
2024-05-06 20:26:59
0
5,938
sdbbs
78,438,946
2,675,981
ModuleNotFoundError: No module named 'argparse_formatter'
<p>I feel like I am missing something incredibly simple, but I can't, for the life of me figure out what it is.</p> <p>I am trying to run a <strong>Python3</strong> script on a <strong>Windows</strong> box, and I get the error <code>ModuleNotFoundError: No module named 'argparse_formatter'</code>. However, when I check...
<python><python-3.x><pip><argparse><formatter>
2024-05-06 20:17:41
1
885
Apolymoxic
78,438,807
4,375,983
Moving to python 3.12.2 generates PicklingError during spark dataframe creation
<p>I am not very experienced in spark, spark context elements and handling them... Please advise on the following problem:</p> <p>I used to run a test involving the creation of a mocked spark context in python <code>3.9.6</code> that worked well. Since we moved to python <code>3.12.2</code>, this code raises an Excepti...
<python><python-3.x><apache-spark><pyspark><apache-spark-sql>
2024-05-06 19:43:24
1
2,811
Imad
78,438,768
5,316,326
Dask set dtype to an array of integers
<p>With Dask I try to create a column that has type list with integers. For example:</p> <pre class="lang-py prettyprint-override"><code>import dask.dataframe as dd import pandas as pd # Have an example Dask Dataframe ddf = dd.from_pandas(pd.DataFrame({ 'id': [1, 2, 3, 4, 5], 'name': ['Alice', 'Bob', 'Charlie'...
<python><pandas><dask>
2024-05-06 19:32:37
2
4,147
Joost Döbken
78,438,685
6,606,057
Using a Mask to Insert Values from sklearn Iterative Imputer
<p>I created a set of random missing values to practice with a tree imputer. However, I'm stuck on how to overwrite the missing values into the my dataframe. My missing values look like this:</p> <p><a href="https://i.sstatic.net/erMMITvI.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/erMMITvI.png" al...
<python><pandas><sklearn-pandas><imputation>
2024-05-06 19:14:48
2
485
Englishman Bob
78,438,668
12,227,905
Generating random passphrases from sets of strings with secrets.random is not very random
<p>I have a requirement for a basic passphrase generator that uses set lists of words, one for each position in the passphrase.</p> <pre><code> def generate(self) -&gt; str: passphrase = &quot;%s-%s-%s-%s-%s%s%s&quot; % ( self.choose_word(self.verbs), self.choose_word(self.determiners), ...
<python><random><sequence><membership><secrets>
2024-05-06 19:09:45
1
2,029
Alec Joy
78,438,612
274,601
create column based on another column value in the same dataframe
<p>I have a dataframe, that looks like:</p> <div class="s-table-container"><table class="s-table"> <thead> <tr> <th>Question</th> <th>Answer</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>Category1</td> </tr> <tr> <td>1</td> <td>Category1</td> </tr> <tr> <td>1</td> <td>Not Important</td> </tr> <tr> <td>2</td> <td>Cate...
<python><pandas><dataframe>
2024-05-06 18:57:28
0
3,181
Lisa