QuestionId
int64
74.8M
79.8M
UserId
int64
56
29.4M
QuestionTitle
stringlengths
15
150
QuestionBody
stringlengths
40
40.3k
Tags
stringlengths
8
101
CreationDate
stringdate
2022-12-10 09:42:47
2025-11-01 19:08:18
AnswerCount
int64
0
44
UserExpertiseLevel
int64
301
888k
UserDisplayName
stringlengths
3
30
⌀
77,642,624
247,542
How to add translation support to Django constants?
<p>I have a Django application with some dictionaries defined in <code>constants.py</code>.</p> <p>The values in the dictionary represent user-readable labels, and I want to add translation support, so Django's i18n feature will translate them based on locale.</p> <p>I thus added to the top of my <code>constants.py</co...
<python><django><django-i18n>
2023-12-11 22:03:58
2
65,489
Cerin
77,642,342
9,457,900
unable to call blpapi function (InstrumentsListRequest) using xbbg
<p>I am trying to call the example of blpapi using xbbg</p> <pre><code>from xbbg.core import conn, process from xbbg import blp from datetime import date def allInstruments(): # Return all govts with the given ticker, matured or not req = process.create_request(service='//blp/instruments', request='instrumentList...
<python><bloomberg><quantitative-finance><blpapi>
2023-12-11 20:54:32
1
2,644
Tanjin Alam
77,642,220
706,354
Pandas: how do I restart expanding function with each new day in my time-series?
<p>I am using expanding method in my dataset. I know how to use it, for example:</p> <pre><code>data[&quot;someColumn&quot;].expanding().mean() </code></pre> <p>The challenge is that my dataset contains time series, and I need to &quot;restart&quot; expanding method when a new day starts. I.e. when new day starts expan...
<python><pandas>
2023-12-11 20:19:45
1
3,505
MiamiBeach
77,641,958
2,386,605
How to close sessions on Postgresql with sqlalchemy?
<p>In this configuration</p> <pre><code>from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine, async_sessionmaker db_engine = create_async_engine('&lt;DATABASE_URL&gt;', echo=False, future=True) async_session = async_sessionmaker(db_engine, class_=AsyncSession, expire_on_commit=False) async def get_se...
<python><postgresql><sqlalchemy><sqlmodel>
2023-12-11 19:30:15
1
879
tobias
77,641,923
5,235,665
Python GNUPG Unknown system error when loading private key
<p><strong>Please note:</strong> Even though I mention Azure Databricks here, I believe this is a Python/GNUPG problem at heart, and as such, can be answered by anybody with Python/GNUPG encryption experience.</p> <hr /> <p>I have the following Python code in my Azure Databricks notebook:</p> <pre><code>%python from p...
<python><encryption><azure-databricks><gnupg><pgp>
2023-12-11 19:24:18
2
845
hotmeatballsoup
77,641,455
1,467,552
How to limit memory usage while scanning parquet from S3 and join using Polars?
<p>As a follow-up question to <a href="https://stackoverflow.com/questions/76770890/using-scan-parquet-and-scan-pyarrow-dataset-on-s3-loads-entire-dataset-into-memo">this question</a>, I would like to find a way to limit the memory usage when scanning, filtering and joining a large dataframe saved in S3 cloud, with a t...
<python><python-polars><pyarrow>
2023-12-11 17:52:27
1
1,170
barak1412
77,641,146
3,737,186
Extract response data from custom LLM in langchain through callbacks?
<p>When writing an integration for <a href="https://python.langchain.com/docs/modules/model_io/llms/custom_llm" rel="nofollow noreferrer">a custom LLM</a> in langchain. Is it possible to add support for collecting information from the actually requests through means of the <a href="https://python.langchain.com/docs/mod...
<python><langchain><py-langchain>
2023-12-11 16:50:44
0
3,508
Sjoerd222888
77,641,145
11,517,893
How to prevent race condition while working with sessions?
<p>I’m working on an e-commerce website with a cart and products. A product’s primary key is added to the user’s session data in a dictionary <code>'cart_content'</code>. This dictionary hold product’s primary key as key and amount of the given product as value.</p> <p>I successfully reproduced a race condition bug by ...
<javascript><python><django><race-condition>
2023-12-11 16:50:36
2
363
Zatigem
77,641,139
22,466,650
How to parse an html table with a fixed shape?
<p>I receive an html table that have always the same shape. Only the values differ in each time.</p> <pre><code>html = ''' &lt;table align=&quot;center&quot;&gt; &lt;tr&gt; &lt;th&gt;Name&lt;/th&gt; &lt;td&gt;NAME A&lt;/td&gt; &lt;th&gt;Status&lt;/th&gt; &lt;td class=&quot;IN PROGRES...
<python><web-scraping><beautifulsoup><html-table><python-requests>
2023-12-11 16:49:14
2
1,085
VERBOSE
77,641,087
2,386,113
FFT values computed using Python and MATLAB don't match?
<p>I have a super simple test code to compute FFT in MATLAB, which I am trying to convert to Python but the computed values do not match.</p> <p><strong>MATLAB Code:</strong></p> <pre class="lang-matlab prettyprint-override"><code>rect=zeros(100,1); ffrect=zeros(100,1); for j=45:55 rect(j,1)=1; end frect=fft(rect)...
<python><matlab><fft>
2023-12-11 16:42:04
1
5,777
skm
77,640,899
15,453,560
Not seeing column names when reading csv from s3 in pandas
<p>I am using the following bit of code to read the iris dataset from an s3 bucket.</p> <pre><code>import pandas as pd import s3fs s3_path = 's3://h2o-public-test-data/smalldata/iris/iris.csv' s3 = s3fs.S3FileSystem(anon=True) with s3.open(s3_path, 'rb') as f: df = pd.read_csv(f, header = True) </code></pre> <p>H...
<python><pandas><amazon-web-services><amazon-s3><read-csv>
2023-12-11 16:11:49
2
657
Muhammad Kamil
77,640,864
22,466,650
How to avoid redundant printings when using a decorator on nested functions?
<p>I have two functions <code>func1</code> and <code>func2</code> on which I'm applying a basic timer decorator <code>@time_elapsed</code>. The problem is that <code>func1</code> is called within <code>func2</code> which cause the print of its timing too.</p> <p>How can I structure my code to apply the decorator only o...
<python><decorator>
2023-12-11 16:07:17
2
1,085
VERBOSE
77,640,840
8,839,068
Catch RateLimitError in calls to OpenAI API with python and tenacity's @retry
<p>I am using python to query the OpenAI API.</p> <p>I have queries in a list of dictionaries that contain the parameters for each query (a 'system_message' with the instruction and a 'user_message' with the query-specific input.</p> <p>I define a function <code>complete_prompt_with_backoff</code> using <code>tenacity<...
<python><python-3.x><async-await><python-asyncio><openai-api>
2023-12-11 16:03:25
1
4,240
Ivo
77,640,717
18,618,577
problem on sys.stdout used with the buffer
<p>on an old code on github that I used to use, the devs seems to plan a python 3 version but it seem that something doesn't work anymore. Here the piece of code (don't know if it's enought) :</p> <pre><code># --------- # Specifics # --------- if is_py2: if is_py26: from logging import Handler cla...
<python><buffer><stdout>
2023-12-11 15:42:06
0
305
BenjiBoy
77,640,695
363,796
"post" keyword in Python source distribution filenames
<p>Can someone explain the following behavior to me?</p> <pre class="lang-none prettyprint-override"><code>$ python setup.py sdist ......... $ls -l dist/ -rw-r--r--. 1 zenzic users 5.8K Oct 17 17:00 my_prog-3.0.3-20231017.tar.gz -rw-r--r--. 1 zenzic users 6.0K Dec 9 19:48 my_prog-3.0.4.post20231209.tar.gz -rw-r--r--....
<python><setuptools>
2023-12-11 15:38:15
0
1,653
zenzic
77,640,569
8,030,746
How to insert scraped data using flask_sqlalchemy models?
<p>To be able to easily use flask-paginate, I switched to Flask-SQLAlchemy in my Flask app. However, this is my first time using something like this, and I'm having some issues understanding what it is I need to do to insert scraped content into my database now.</p> <p>Previously, I appended scraped content, and then u...
<python><flask>
2023-12-11 15:14:52
1
851
hemoglobin
77,640,551
9,974,205
Looking for alternative to nested loops in Python
<p>I have developed the following code to check if groups of three people are conected at the same time</p> <pre><code>import pandas as pd from itertools import combinations data = { 'User': ['Esther','Jonh', 'Ann', 'Alex', 'Jonh', 'Alex', 'Ann', 'Beatrix'], 'InitialTime': ['01/01/2023 00:00:00','01/01/2023 ...
<python><pandas><for-loop><combinations><scalability>
2023-12-11 15:13:05
1
503
slow_learner
77,640,549
9,404,261
What is the correct numba decorator to return an array of different size than the parameter passed?
<p>I want to use numba to vectorize a function to count the occurrences of unique values. The function receives a numpy array of any length, and returns a numpy array of length 257.</p> <p>But I do not understand how to specify the decorator. It doesn't' even compile. I read the documentation <a href="https://numba.re...
<python><vectorization><numba>
2023-12-11 15:12:33
1
609
tutizeri
77,640,419
5,170,442
How to have parent method accept additional arguments compared to child method without linting issues
<p>I have a data structure where different objects are considered &quot;equivalent&quot; if certain parameters/arguments match. I want to implement a method in the parent class that does some of the checks that must apply to all children in order to make them equivalent. In addition, depending on the child class, some ...
<python><inheritance><pylint>
2023-12-11 14:52:36
0
653
db_
77,640,168
3,917,215
Decode hierarchical data structure using Pandas
<p>I have a Pandas dataframe with a sample hierarchical data as below</p> <pre><code>df1 = pd.DataFrame({'Level': ['0','1','2','2','3','2','3','1','2','3','3','4'], 'Type': ['P','U','D','I','D','PR','D','U','U','D','PR','D'], 'ID': ['P1','U1','D1','I1','D2','PR1','D3','U4','U8','DB...
<python><pandas><dataframe>
2023-12-11 14:08:23
1
353
Osceria
77,640,020
9,284,651
Data Frame- Remove all after year but keep information about year
<p>My DF looks like below:</p> <pre><code>id date 1 21 July 2023 (abcd) 2 22 July 2023 00:00:01 3 23 July 2023 -abcda </code></pre> <p>I need to remove all after year (2023) but I want to keep it. So the result should be:</p> <pre><code>id date 1 21 July 2023 2 22 July 2023 3 23 July 2023 </code></pre> <p>I used ...
<python><pandas><dataframe><date><split>
2023-12-11 13:43:09
2
403
Tmiskiewicz
77,639,975
11,064,604
Rearranging LGBMClassifier predict_proba outputs columns
<p>I am training an <code>LGBMClassifier</code> for the purpose of using its <code>predict_proba</code> method. The target has 3 classes: <strong>a, b, and c</strong>. I want to ensure that the model <code>predict_proba</code> outputs the probabilities of the columns in order <strong>b, a, c</strong>.<br /> <em>Is th...
<python><machine-learning><lightgbm>
2023-12-11 13:35:28
1
353
Ottpocket
77,639,943
10,333,668
Tkinter theme is slow
<p>I'm using <a href="https://github.com/rdbende/Azure-ttk-theme" rel="nofollow noreferrer">this</a> them in py tkinter program. My problem is that I make like 20 buttonst, it becomes very slow. I know that this is beacuse all the buttons have images. I alredy get a suggestion, that use OpenCV instead of tkinter to loa...
<python><tkinter><tcl><ttk><ttkthemes>
2023-12-11 13:29:53
2
377
Bálint Cséfalvay
77,639,922
18,649,992
Discrete Difference on Sharded JAX Arrays
<p>It is possible to speed-up discrete difference calculations on sharded (across CPU cores) JAX arrays?</p> <p>The following is an attempt to follow the documentation of JAX automatic parallelism. It uses AOT compilation of essentially a JAX NumPy API call for different sharded arrays. Several device meshes are used t...
<python><jax><spmd>
2023-12-11 13:27:35
1
440
DavidJ
77,639,750
2,583,346
python plotly - arranging odd number of subplots
<p>Toy example:</p> <pre><code>import plotly.graph_objects as go from plotly.subplots import make_subplots fig = make_subplots(rows=2, cols=3, shared_yaxes=True, horizontal_spacing=0.02) fig.add_scatter(x=[1,2,3],y=[1,2,3], row=1, col=1) fig.add_scatter(x=[1,2,3],y=[1,2,3], row=...
<python><plotly><subplot>
2023-12-11 12:54:09
1
1,278
soungalo
77,639,418
9,915,864
How can I pass data back and forth between Flask template and Python code (context_processor)?
<p>I'll preface with stating I'm still pretty new to Flask. I setup my <code>app.py</code> file to import calls from a <code>view.py</code> file using the <code>add_url_rule()</code>. I'm stuck on how to pass data back and forth between my HTML Template and the Python code.</p> <p>GOAL: Display HTML snippets based on u...
<python><html><flask>
2023-12-11 12:01:00
0
341
Meghan M.
77,639,348
3,898,523
delta-rs package incurs high costs on GCS
<p>I'm using the <a href="https://github.com/delta-io/delta-rs" rel="nofollow noreferrer">delta-rs package</a> to store files on the Google Cloud Storage dual-region bucket. I use the following code to store the data:</p> <pre><code> def save_data(self, df: Generator[pa.RecordBatch, Any, None]): write_deltal...
<python><google-cloud-storage><delta-lake><cost-management><delta-rs>
2023-12-11 11:48:08
1
305
gregorp
77,639,326
19,363,912
Nested dictionary with class and instance attributes
<p>I store some configuration details across several class attributes and one main class which references each of them. E.g.</p> <pre><code>class A: a = 1 class B: b = 2 def __init__(self): self.a_ = A() x = B() </code></pre> <p>I would like to display all class (and instance) attributes in a d...
<python>
2023-12-11 11:43:59
2
447
aeiou
77,639,286
583,464
3d numpy array calculate mean of columns with nans
<p>I have this 3d array:</p> <pre><code>import numpy as np import numpy.ma as ma a = np.array([[[1,2,3],[4,np.nan,6], [7,8,9]], [[11,12,13],[14,np.nan,16], [17,18,19]]]) a.shape (2, 3, 3) array([[[ 1., 2., 3.], [ 4., nan, 6.], [ 7., 8., 9.]], [[11., 12., 13.], [14., ...
<python><numpy>
2023-12-11 11:38:17
1
5,751
George
77,638,814
13,023,647
Searching a list by an undefined value
<p>There is a certain list that I get after parsing a certain html page:</p> <p>Could you tell me please, how can I do a search for a specific value?</p> <p>Let's say I specify only part of the value <code>KES_</code> and the search should give me the entire value <code>KES_2023.z</code>.</p> <p>Thank you very much!</p...
<python><python-3.x><list><find>
2023-12-11 10:09:19
3
374
Alex Rebell
77,638,147
11,046,379
Pivot Pandas dataframe and take missed values from other dataframe
<p>There are two dataframes:</p> <pre><code>table1 id | time | status ----------------------- 1 | 10:00 | conn | 1 | 10:01 | disconn | 2 | 10:02 | conn | 2 | 10:03 | disconn | 3 | 10:04 | conn | table2 id | time | ------------ 3 | 10:05 | </code></pre> <p>If there is no disconn time valu...
<python><pandas><dataframe>
2023-12-11 08:01:46
1
1,658
harp1814
77,637,697
5,865,448
Given set of points, how to approximate a rectangle using opencv?
<p>I have a set of points as shown in the image attached. How can i approximate a rectange or draw a rectangle using these points?</p> <p>The easiest will be to get min(x) and min(y) as top left and max(x), max(y) as bottom right, but that wont solve for any anamolous point. here is sample data to try with:</p> <pre><c...
<python><opencv>
2023-12-11 05:55:49
1
337
Ali Waqas
77,637,675
2,780,906
np.vectorize and relativedelta returning "relativedelta only diffs datetime/date"
<p>I have a pandas dataframe with two datetime64[ns] columns (&quot;d1&quot; and &quot;d2&quot;) representing dates. I would like to create a third column calculated as the difference between these two dates. I can't use a simple days/365 style calculation, so I am requiring relativedelta.</p> <p>Using relativedelta ...
<python><pandas><date><vectorization>
2023-12-11 05:46:58
1
397
Tim
77,637,562
10,027,592
How does assignment to another assignment(adding an element in a dictionary) work?
<p>Let's imagine a dictionary and we want to get some kind of a &quot;reference&quot; to a value that hasn't been populated yet.</p> <pre><code>&gt;&gt;&gt; d = {} # This dictionary may have a huge number of elements. &gt;&gt;&gt; a = d['John'] = {} # I hope 'a' works as if some reference to the empty value. &gt;&gt;&g...
<python><python-3.x><variable-assignment>
2023-12-11 05:04:42
0
4,226
starriet 차주녕
77,637,539
9,108,781
Why BeautifulSoup can't find this supposed-to-be xbrl related "ix" tag?
<p>It turns out that the tag name should be: &quot;ix:nonfraction&quot;</p> <p>This does not work. No &quot;xi&quot; tag is found.</p> <pre><code>from bs4 import BeautifulSoup text = &quot;&quot;&quot; &lt;td style=&quot;BORDER-BOTTOM:0.75pt solid #7f7f7f;white-space:nowrap;vertical-align:bottom;text-align:right;&quot...
<python><beautifulsoup>
2023-12-11 04:57:25
2
943
Victor Wang
77,637,307
8,523,868
How to print all links from the website in robot framwok
<p>Thank you so much in advance for answering my question. Below I tried to print all the links name in the console. I could able to get no of count of links but could not able to print the name of the links. Please help me to solve the query.</p> <pre><code>*** Settings *** Library SeleniumLibrary *** Variables *** ...
<python><automation><robotframework>
2023-12-11 03:15:33
3
911
vivek rajagopalan
77,636,915
235,472
How to find out if a symbolic link points to a missing directory?
<p>I have a symbolic link to a directory that does not exist:</p> <pre><code>~/ramdisk -&gt; /dev/shm/mydir </code></pre> <p>When running my Python code, I get the error:</p> <blockquote> <p>FileNotFoundError: [Errno 2] No such file or directory: '~/ramdisk'</p> </blockquote> <p>How can I avoid this error, detecting be...
<python><python-3.x><symlink>
2023-12-11 00:06:52
1
13,528
Pietro
77,636,721
609,782
How to get a certain value from enum?
<p>I have the following class:</p> <pre><code>class YesOrNn(enum.Enum): YES = &quot;Y&quot; NO = &quot;N&quot; </code></pre> <p>I am getting my inputs such as <code>YesOrNo(&quot;true&quot;)</code> or <code>YesOrNo(&quot;false&quot;)</code>,</p> <p>To make this work, I think I need to change the class to:</p> <pre>...
<python><enums>
2023-12-10 22:46:33
1
5,792
Darpan
77,636,586
3,608,005
Extracting titles from PDFs based on formatting via classification
<p>I have about 20000 pdfs with probably 100 different layouts. Unfortunately, not all PDFs contain clean metadata. People are often lazy and did not always provide the title with it or sometimes a very short one or even worse just the file name as title.</p> <p>Because of the number of documents, I started with PyMuPD...
<python><pdf><nlp>
2023-12-10 21:51:00
2
5,448
Moritz
77,636,518
539,251
Python for .NET - python lambda parameter in function definition called from C#
<p>I have the following code I want to convert to Python for .NET (so I want to embed Python in C#)</p> <pre><code>import numpy as np from scipy.optimize import curve_fit x = np.array([4, 3, 2, 1]) y = np.array([1.43, 1.84, 1.36, 1.08]) model = lambda t, a, b: a * np.exp(-b * t) params = curve_fit(model, x, y) </code><...
<python><c#><.net><embed><python.net>
2023-12-10 21:25:26
1
1,545
BigChief
77,636,346
7,391,480
Pandas table reshape puzzle - list all items and fill in blanks with NaN or 0
<p>I have a table I'm trying to reshape in a particular way.</p> <pre><code>import pandas as pd df = pd.DataFrame({'race': ['one', 'one', 'one', 'two', 'two', 'two'], 'type': ['D', 'K', 'G', 'D', 'D', 'K'], 'item': ['x', 'y', 'z', 'q', 'x', 'y'], 'level': [1, 2, 1, 6, 2,...
<python><pandas><dataframe><pivot><pivot-table>
2023-12-10 20:34:29
2
1,364
edge-case
77,636,251
2,813,606
Create a dictionary from Pandas column conditioned on values from another column
<p>I have a tennis dataset that looks like the following:</p> <pre><code>tourney_id = ['French Open 2018','French Open 2018','Wimbledon 2018','Wimbledon 2018','Australian Open 2019','Australian Open 2019','US Open 2019','US Open 2019'] player_name = ['Novak Djokovic','Roger Federer','Andy Murray','Rafael Nadal','John I...
<python><pandas><list><dictionary><python-zip>
2023-12-10 20:07:47
5
921
user2813606
77,636,213
6,619,979
Is it possible to avoid encoding padding when creating a sequence data encoder in PyTorch?
<p>I am attempting to make an observation history encoder, where my goal is for a model that takes in as input a variable length sequence of dimension [Time, Batch, Features] (where sequences are padded to fit a fixed Time length) and outputs a variable of dimension [Batch, New_Features]. My concern is that when I’m do...
<python><deep-learning><pytorch><reinforcement-learning><autoencoder>
2023-12-10 19:56:25
1
833
Yuerno
77,636,192
1,743,551
`AttributeError: 'Series' object has no attribute 'iteritems'` in simple custom Pyfolio example
<p>I try to get a custom Pyfolio example running in a Jupyter Notebook on OSx. But I either get</p> <p><code>AttributeError: 'Series' object has no attribute 'iteritems'</code> with the Pandas &gt; 2.0.0 or</p> <p><code>IndexError: index -1 is out of bounds for axis 0 with size 0</code> with the Pandas &lt; 2.0.0.</p> ...
<python><pandas><pyfolio>
2023-12-10 19:51:10
1
1,855
Sandro
77,636,125
13,492,584
Python PyCharm - cannot install contextily
<p>I am using <strong>Python</strong> with <strong>PyCharm</strong> and I am trying to run this code that I found <a href="https://networkx.org/documentation/stable/auto_examples/geospatial/plot_points.html" rel="nofollow noreferrer">here</a>:</p> <pre><code>from libpysal import weights, examples from contextily import...
<python><pip><networkx><geospatial><contextily>
2023-12-10 19:27:59
1
644
hellomynameisA
77,636,095
8,030,746
How to scrape a very nested element on a page with Selenium?
<p>I'm scraping <a href="https://higher.gs.com/results?&amp;page=1&amp;sort=RELEVANCE" rel="nofollow noreferrer">this page</a> for jobs. However, I'm having some trouble properly getting and scraping an element describing job positions (Analyst, Vice President, Associate, etc.).</p> <p>To get to the job card, I'm using...
<python><selenium-webdriver><web-scraping>
2023-12-10 19:15:52
1
851
hemoglobin
77,635,789
1,914,781
reshape dataframe according to duration
<p>I would like to re-shape a dataframe to a dataframe with below rules:</p> <ol> <li>Add a row under current ts with ts + dur,copy other columns</li> <li>Add a None row to the next row.</li> </ol> <p>example:</p> <pre><code>import pandas as pd import itertools def segments(df): start = df['ts'] end = start + ...
<python><pandas><dataframe>
2023-12-10 17:42:28
2
9,011
lucky1928
77,635,741
5,377,910
Pyarmor ModuleNotFoundError: No module named 'pyarmor_runtime_000000'
<p>I'm trying to obfuscate my project but got error ModuleNotFoundError: No module named 'pyarmor_runtime_000000', So I tried to obfuscate a very simple folder containing only 2 files as follows</p> <pre><code>test ├── __init__.py ├── test2.py └── test.py </code></pre> <p>the content of each file is simply a print stat...
<python><obfuscation><pyarmor>
2023-12-10 17:28:03
2
401
shrouk mansour
77,635,685
957,052
Getting amplitude value of mp3 file played in Python on Raspberry Pi
<p>I am playing an mp3 file with Python on a Raspberry Pi:</p> <pre><code>output_file = &quot;sound.mp3&quot; pygame.mixer.init() pygame.mixer.music.load(output_file) pygame.mixer.music.play() while pygame.mixer.music.get_busy(): pass sleep(0.2) </code></pre> <p>Now while the mp3 file is playing, I would like to ge...
<python><audio>
2023-12-10 17:13:00
3
1,542
Reto
77,635,659
19,694,624
Can't reply to a message discord py slash command using cogs
<p>I am struggling with sending a basic reply in discord.py with a cog. The problem is that the bot keeps pending and eventually breaks.</p> <p>The problem:</p> <p><a href="https://i.sstatic.net/6D53c.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/6D53c.png" alt="enter image description here" /></a></p>...
<python><python-3.x><discord><discord.py>
2023-12-10 17:04:13
2
303
syrok
77,635,629
7,563,454
Python: Set object property from a string name
<p>I want a class that can be initialized with a dictionary, attributing each entry in this dictionary to itself. I wrote the following which I expected to just work:</p> <pre><code>class dat: def __init__(self, data: dict): for d in data: self[d] = data[d] </code></pre> <p>But that produces the...
<python><python-3.x>
2023-12-10 16:57:01
1
1,161
MirceaKitsune
77,635,607
827,927
How to draw a two-dimensional function whose domain is a triangle?
<p>I would like to plot a function f(x,y) = x^2 + y^2 defind on all pairs x,y such that x + y ≤ 1, x ≥ 0, y ≥ 0. Currently, I use <code>imshow</code>:</p> <pre><code>x = np.arange(0, 1, 0.01) y = np.arange(0, 1, 0.01) Z = compute_function(x, y) # evaluation of the function on the grid imshow(Z, cmap=cm.RdBu, extent=(mi...
<python><matplotlib>
2023-12-10 16:51:49
1
37,410
Erel Segal-Halevi
77,635,495
10,452,700
How can plot errorbar style using scatter plot for min & max values instead of mean & std over time within dataframe in python?
<p>Let's say I have the following datafarme:</p> <pre class="lang-none prettyprint-override"><code>+-------------------+--------+--------+--------+ |timestamp |average |min |max | +-------------------+--------+--------+--------+ |2021-08-11 04:05:06|2.0 |1.8 |2.2 | |2021-08-11 04:15:06|2.3 ...
<python><pandas><matplotlib><seaborn><plotly-express>
2023-12-10 16:16:47
2
2,056
Mario
77,635,481
10,620,003
colorize the background of different parts of the graph based on the event
<p>I have a code which create two subplot. I want to colorized the figure based on the values of the black curve. I want to use three color for the graph. Every where which the values of the black curve is one, one index befor that to the start should be one color, during that period color 2, and two index after that s...
<python><pandas><numpy><matplotlib>
2023-12-10 16:12:25
1
730
Sadcow
77,635,238
13,135,901
Filter rows based on max/min value in a group in Pandas
<p>I have a dataframe:</p> <pre><code>mydict = [ {'HH': True, 'LL': False, 'High': 10, 'Low': 1}, {'HH': False, 'LL': True, 'High': 100, 'Low': 20}, {'HH': True, 'LL': False, 'High': 32, 'Low': 1}, {'HH': True, 'LL': False, 'High': 30, 'Low': 1}, {'HH': True, 'LL': False, 'High':...
<python><pandas>
2023-12-10 14:54:21
1
491
Viktor
77,635,111
13,285,779
Error building the ONNX library from scratch Ubuntu 22.04.2
<p>I'm trying to build the ONNX library from source going step by step according to <a href="https://github.com/onnx/onnx/tree/main" rel="nofollow noreferrer">the official manual</a>. When I reach the final step of executing the <code>pip install -e .</code> command, I encounter some errors. As I understand, the librar...
<python><linux><pip><onnx>
2023-12-10 14:09:24
1
1,359
CuriousPan
77,635,009
7,453,683
Python extract only exceptions from traceback
<p>I have nested python exceptions. I wan't to extract all of them into a list from a traceback while discarding everything else, i.e. files, code lines, etc.</p> <p>The code below extracts everything from a traceback as a list of strings</p> <pre class="lang-py prettyprint-override"><code>import traceback import reque...
<python><python-3.x><exception><traceback>
2023-12-10 13:37:17
1
861
Superbman
77,634,955
12,671,057
Why is the simpler loop slower?
<p>Called with <code>n = 10**8</code>, the simple loop is consistently significantly slower for me than the complex one, and I don't see why:</p> <pre><code>def simple(n): while n: n -= 1 def complex(n): while True: if not n: break n -= 1 </code></pre> <p>Some times in secon...
<python><performance><cpython><python-internals><python-3.11>
2023-12-10 13:17:37
1
27,959
Kelly Bundy
77,634,823
334,155
Download Python packages with correct dependencies for offline install
<p>I am trying to install Apache Airflow 2.7.3 offline. I have read about <code>pip download</code>, requirement file, constraint file but still not able to do this.</p> <p>Below is my full script to demonstrate the problem.</p> <pre><code>AIRFLOW_VERSION=2.7.3 PYTHON_VERSION=&quot;$(python --version | cut -d &quot; &q...
<python><pip><airflow>
2023-12-10 12:41:02
0
619
zaidwaqi
77,634,768
200,160
SQLalchemy can't communicate to MySQL server upon app start
<p>I'm have troubles with SQLalchemy in Flask app first minute after the app start (or restart). It looks like logger exceptions of a sort:</p> <blockquote> <p>sqlalchemy.exc.OperationalError: (MySQLdb._exceptions.OperationalError) (2006, 'MySQL server has gone away') &lt;---- most often one</p> </blockquote> <blockquo...
<python><sqlalchemy><flask-sqlalchemy><uwsgi>
2023-12-10 12:19:08
1
825
Ralfeus
77,634,718
2,996,797
Server for saving TCP packets from routers
<p>Asking for advice here.</p> <p>So I have a business that sells a specific kind of routers. One of the features is to monitor the activity of the router (i.e. making sure it's &quot;live&quot;). I asked the manufacturer of the routers to program them to send a TCP &quot;ping&quot; packet to my server IP address, to a...
<python><logging><server><network-programming>
2023-12-10 12:05:39
1
530
Cauthon
77,634,487
3,433,875
Improve Tesseract Accuracy on my book images, for Google Books API
<p>I am trying to upload my library to goodreads, so I am taking a picture to get the details of each book and then I use Google books api to get the isbn number.</p> <p>Unfortunately, pytesseract is not detecting the text properly.</p> <p>Here is one image: <a href="https://i.sstatic.net/kFQVA.jpg" rel="nofollow noref...
<python><ocr><tesseract><python-tesseract><google-books-api>
2023-12-10 10:50:46
0
363
ruthpozuelo
77,634,437
1,815,047
Flask-WTF reCAPTCHA ERROR for site owner: Invalid site key
<p>I'm using Flask 2.2.5 and Flask-WTF 1.1.1. <br />I want to use a Recaptcha field and, get <strong>ERROR for site owner: Invalid site key</strong> printed on the widget.</p> <p><a href="https://i.sstatic.net/U4a37.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/U4a37.png" alt="enter image description h...
<python><recaptcha>
2023-12-10 10:30:15
1
734
Ahadu Tsegaye Abebe
77,634,338
19,041,863
Histogram unequal number on the Y axis
<p>I want to plot a histogram in a Matplotlib subplot. I have the code</p> <pre><code>import pandas as pd import numpy as np import matplotlib.pyplot as plt from scipy.stats import norm def plot_Diff(data): fig = plt.figure(figsize=(10, 10)) ax =fig.add_subplot(423) x= dfe['O18ad'] bins=[-20, -19, -1...
<python><matplotlib><histogram>
2023-12-10 09:50:51
1
303
Weiss
77,634,299
2,573,075
I try to build a basic Odoo 15 module but gives error at inheritance
<p>I'm trying to create a graphical reporting module but gives error at inheritance. I start basic by inheritance the crm modules to manage them. My modules is:</p> <pre><code>class XPFReporting(models.Model): &quot;&quot;&quot; This is the reporting system that will take all data from crm to further filter and...
<python><xml><module><odoo><odoo-15>
2023-12-10 09:33:44
1
633
Claudiu
77,633,752
10,455,471
Python Setuptools / pyproject.toml - Console Scripts Can't Import Main Package Name: ModuleNotFoundError
<h2>Issue</h2> <p>I'm making a python template which is supposed to be able to be run in 3 different ways:</p> <ol> <li>Run <code>python python3-template.py</code> in the main directory (just imports the directory-based package <code>python3_template</code> and runs <code>python3_template.run()</code>)</li> <li>Build a...
<python><python-3.x><setuptools><importerror><pyproject.toml>
2023-12-10 05:14:57
1
648
Ella Jameson
77,633,722
15,209,066
How to make pypdf2 Annotations printable
<p>I'm Using the <code>PyPDF2</code> Library to do some annotations to a pdf. Here's the code that I'm using</p> <pre><code>from PyPDF2 import PdfReader, PdfWriter from PyPDF2.generic import AnnotationBuilder reader = PdfReader(&quot;Example.pdf&quot;) page = reader.pages[0] writer = PdfWriter() writer.add_page(page...
<python><pdf><acrobat><pypdf>
2023-12-10 04:57:13
0
377
rav2001
77,633,675
10,620,003
Build a df from two other df based on 0,1 in the df1 and the values in df2
<p>I have two dfs. one df has only 1 and 0 <strong>(df_one_zero</strong>). and another one has the different values <strong>df_value_total</strong>. These two has thousand rows and columns!</p> <p>The first column of each df is the id and we dont want to change that at all.</p> <p>I want to move with sliding window of ...
<python><pandas><dataframe>
2023-12-10 04:28:32
1
730
Sadcow
77,633,472
3,884,713
A Simple Toy ML problem that surprisingly fails to learn anything
<p>This is a much simplified network from a real problem that, to me, has a surprising <strong>INability</strong> to learn a simple task via backprop, ie, it can't overfit or learn at all. This simple version has come at the cost of many gray hairs, and much simplification, and I truly ignored the option that something...
<python><machine-learning><pytorch><neural-network><cosine-similarity>
2023-12-10 02:00:35
0
3,806
Josh.F
77,633,368
1,434,495
How come using np.linalg.norm introduces unseen numerical inequality but writing it out does not?
<p>Let's say I have these two variables:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np a = np.array([[ 0, 1, 10, 2, 5]]) b = np.array([[ 0, 1, 18, 15, 5], [13, 9, 23, 3, 22], [ 2, 10, 17, 4, 8]]) </code></pre> <p><strong>Method 1</strong></p> <pre class="la...
<python><numpy><linear-algebra>
2023-12-10 00:55:17
2
2,957
Flair
77,633,295
16,844,801
Warning when using Hugging Face model
<p>When I am using HF I keep getting this warning and the models seem to keep hallucinating:</p> <pre><code>from transformers import AutoModelForCausalLM, AutoTokenizer tokenizer = AutoTokenizer.from_pretrained(&quot;microsoft/DialoGPT-medium&quot;) model = AutoModelForCausalLM.from_pretrained(&quot;microsoft/DialoGPT...
<python><huggingface-transformers>
2023-12-10 00:09:38
2
434
Baraa Zaid
77,633,279
13,135,901
Vectorize an algorithm with numpy
<p>I have an two arrays of 1's and 0's:</p> <pre><code>a = [1 0 0 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0] b = [0 1 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 1] </code></pre> <p>I want to make sure that the &quot;1&quot; always &quot;jumps&quot; the array as I go from left to right never appearing in the same array twice in a row be...
<python><pandas><numpy>
2023-12-10 00:00:00
1
491
Viktor
77,632,945
2,474,008
tk.TopLevel is making two windows appear, but why?
<p>The code below generates my main program (frmMain), which sometimes opens forms. But each time I open a form, the code below makes TWO forms open, the proper form, and one extra one, which is blank. The standard top-right close button only works on the proper form, and, the extra one is invulerable. But why does it ...
<python><tk-toolkit>
2023-12-09 21:18:10
2
369
Vexen Crabtree
77,632,886
1,165,727
mypy doesn't recognize the latest version of attrs?
<p>Is some special setup needed to help <code>mypy</code> recognize standard <code>attrs</code> usage?</p> <pre><code>somefile.py:7: error: Cannot find implementation or library stub for module named &quot;attr&quot; [import-not-found] </code></pre> <p>(followed by a bunch on errors due to mypy unable to understand th...
<python><mypy><python-attrs>
2023-12-09 21:03:02
1
997
Y123
77,632,539
15,520,615
How to suppress Error: SyntaxWarning: "is" with a literal. Did you mean "=="?
<p>On my Databricks Community Edition the code <code>if len(crValue) is 0:</code> results with the error:</p> <pre class="lang-none prettyprint-override"><code>Error: SyntaxWarning: &quot;is&quot; with a literal. Did you mean &quot;==&quot;? </code></pre> <p>Is it possible to suppress the error so as not to have the ch...
<python><databricks><azure-databricks>
2023-12-09 19:04:32
1
3,011
Patterson
77,632,195
11,530,571
Custom optimizer for TensorFlow
<p>I'm trying to experiment with custom optimization algorithms for neural networks on TensorFlow, but I'm stuck with the lack of information on the topic. What I need is some code that will get me at each iteration a vector x (current point) and a vector g (gradient at x), then I'll update x, and then some code to set...
<python><tensorflow><machine-learning><keras>
2023-12-09 17:23:42
1
456
guest
77,632,015
10,934,417
Create list of items repeated N times without repeating itself
<p>I would like to repeat a list N times but without repeating an item itself. For example,</p> <pre><code>from itertools import * items = [ _ for _ in range(3)] # repeat each item twice row = sorted(list(chain(*repeat(items, 2)))) row [0, 0, 1, 1, 2, 2] </code></pre> <p>BUT, I would like to create another list (col)...
<python><numpy><adjacency-matrix>
2023-12-09 16:33:06
2
641
DaCard
77,631,847
15,520,615
Unable to create ConnectionString variable to connect to Azure Event Hub: Error: JavaPackage' object is not callable
<p>I am trying to generate dummy to our Event Hub using Python Library <strong>dbldatagen</strong> using the following Python code in databricks</p> <pre><code>import dbldatagen as dg from pyspark.sql.types import IntegerType, StringType, FloatType import json from pyspark.sql.types import StructType, StructField, Inte...
<python><databricks><azure-databricks>
2023-12-09 15:38:41
1
3,011
Patterson
77,631,672
8,030,794
Connect to remote vps server postgres?
<p>I have vps server with postresql. I change settings to enable remote connections</p> <ol> <li>listen_addresses = *</li> <li>host all all 0.0.0.0/0 md5</li> <li>sudo ufw allow 5432/tcp</li> </ol> <p>Then i need to connect in python with psycopg2</p> <pre><code>conn = psycopg2.con...
<python><postgresql>
2023-12-09 14:43:57
0
465
Fresto
77,631,627
13,985,175
Most efficient way to replace elements based on first 3 characters of every original element in very large dataframe for over 20,000 selected columns
<p>I am trying to replace entire elements in an array based upon the first 3 characters of all original elements in specific columns of a large dataframe (where applicable based on a dictionary). This process needs to be repeated many times. Given that there are over 20,000 selected columns, the for-loop below is very ...
<python><pandas><dataframe><performance>
2023-12-09 14:30:50
5
331
AIBball
77,631,580
10,570,372
Understanding Mypy Error Reporting with Default `--follow-imports=normal`
<p>I'm currently working with <code>mypy</code> for type checking in a Python project and have encountered a behavior that I'd like to understand better regarding how <code>mypy</code> reports errors, especially under the default <code>--follow-imports=normal</code> setting.</p> <p>Consider a scenario where I have thre...
<python><mypy>
2023-12-09 14:16:32
0
1,043
ilovewt
77,631,531
9,607,072
How to connect to google cloud docker service using python in cloud run
<p>I would like to connect to a docker service from a cloud run serverless with python. For example when I run this inside a cloud run service:</p> <pre><code>import docker client = docker.from_env() </code></pre> <p>I get this error: <code>docker.errors.DockerException: Error while fetching server API version: ('Conne...
<python><docker><google-cloud-platform>
2023-12-09 14:00:46
0
1,243
Kevin
77,631,428
13,130,804
How to enforce to https in Streamlit?
<p>Hi I have an application hosted with Heroku. I have a custom domain and I acquired an automated SSL certificate with Heroku. It works fine with no issue. My problem is that I would like to enforce the url to be always redirected to the https version. In other app's that I have done with Flask, I was able to enforce ...
<python><heroku><ssl-certificate><streamlit>
2023-12-09 13:26:16
0
446
Miguel Gonzalez
77,631,410
264,136
module 'pexpect' has no attribute 'spawn'
<p>OS: WIndows 10</p> <pre><code>ssh_command = f&quot;ssh {ssh_username}@{ssh_address} -p {ssh_port}&quot; ssh_session = pexpect.spawn(ssh_command, encoding='utf-8') </code></pre> <p>Error:</p> <pre><code>(Python310_Services_VENV) C:\UPScripts&gt;python test.py Trying to establish SSH connection. Traceback (most recent...
<python>
2023-12-09 13:20:38
1
5,538
Akshay J
77,631,385
6,089,311
How to add data into hover in Hvplot (bokeh) candlestick without missing-date gaps
<p>I have an simple example, run in jupyter notebook:</p> <ul> <li>hvplot.ohlc without missing-date gaps</li> <li>wanted to fix Hover (add Date in the right format, and add Volume info)</li> </ul> <p>packages:</p> <p>python 3.12<br /> bokeh 3.3.2<br /> hvplot 0.9.0<br /> holoviews 1.18.1</p> <pre class="lang-py prettyp...
<python><bokeh><holoviews><candlestick-chart><hvplot>
2023-12-09 13:09:17
1
586
Jan
77,631,313
11,341,498
Python root logger handlers do not get named loggers records?
<p>I have the following setup:</p> <ul> <li>root logger to log everywhere</li> <li>my programm adds a new handler after startup via an callback (for example a database) with <code>CallbackHandler</code></li> <li>named logger in my modules do not call into the root-logger</li> </ul> <p><a href="https://www.online-python...
<python><logging>
2023-12-09 12:46:24
2
323
nonsensation
77,631,275
18,756,733
How to free up memory every time, condition is met in loop?
<p>I am scraping YouTube comments using the following code:</p> <pre><code>i=0 while True: load_more_comments=driver.find_element(By.CSS_SELECTOR,'main[class=&quot;container-xl&quot;] button[id=&quot;showMoreBtn&quot;]') driver.execute_script(&quot;arguments[0].click();&quot;, load_more_comments) driver.ex...
<python><selenium-webdriver><web-scraping><memory>
2023-12-09 12:34:27
0
426
beridzeg45
77,631,051
7,658,051
line 158, in get_app_config return self.app_configs[app_label] KeyError: 'account'
<p>I am developing a django project, the main directory/project name is <code>django-basic-ecommerce</code>.</p> <p>One of the apps name is <code>accounts</code> (note that it has the final &quot;s&quot;).</p> <p>as I run</p> <pre><code>python manage.py makemigrations </code></pre> <p>I get</p> <pre><code>Traceback (mo...
<python><django><django-models><django-migrations>
2023-12-09 11:14:01
1
4,389
Tms91
77,630,934
1,234,434
python regex match for non-fraction and fractions
<p>I have the following text in a pandas column that I'm trying to create a regular expression to sort into individual columns</p> <pre><code>2 Table $75 5 Chairs 875 Teabags 9/10 gel 125 Dishwasher tablets </code></pre> <p>My first attempt works for the first line of text and some of the last line but not the middle l...
<python><regex>
2023-12-09 10:27:31
1
1,033
Dan
77,630,908
2,722,968
Discover tests in sub-package
<p>I have a package with several hundred tests organized in modules, and I'm in the process of moving some of those tests into their own sub-package for ease of maintenance. My question is how to organize the files so Python's std <code>unittest</code> module can discover <em>and</em> isolate them if I only want to exe...
<python><python-3.x>
2023-12-09 10:15:59
0
17,346
user2722968
77,630,854
20,176,161
Groupy by: TypeError: sequence item 0: expected str instance, float found
<p>I am trying to do a groupby in the following dataframe.</p> <p><a href="https://i.sstatic.net/w3Agf.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/w3Agf.png" alt="enter image description here" /></a></p> <p>I am looking for a unique combination of <code>ville</code>, <code>arrondissement</code>, <cod...
<python><dataframe><group-by>
2023-12-09 09:57:16
2
419
bravopapa
77,630,719
12,276,279
From a pandas dataframe containing net exports between any two countries, how can I get second dataframe containing net exports for each country?
<p>I have a dataframe <code>df</code> containing net exports between any two countries in column <code>From</code> and <code>To</code> respectively.</p> <p><code>df.to_dict()</code> returns</p> <pre><code>{'From': {0: 'A', 1: 'A', 2: 'B', 3: 'C', 4: 'D'}, 'To': {0: 'B', 1: 'C', 2: 'C', 3: 'D', 4: 'A'}, 'Net exports':...
<python><pandas><dataframe><math><group-by>
2023-12-09 09:06:36
4
1,810
hbstha123
77,630,640
9,640,238
gspread numberFormat is not applied for a date
<p>With gspread, I'm trying to apply date formatting for a column, but it doesn't see to work. Here's a minimal example:</p> <pre class="lang-py prettyprint-override"><code>sh = gc.create(&quot;new&quot;) ws = sh.get_worksheet(0) ws.update(&quot;A1&quot;, &quot;20/10/2023&quot;) ws.format( &quot;A1&quot;, { ...
<python><formatting><gspread>
2023-12-09 08:34:45
1
2,690
mrgou
77,630,569
1,696,434
Making a common DB for one app across multiple django projects
<p>I have 3 distinct Django projects (or instances) running on the same Ubuntu server (for the same user) in different folders. Lets call these instances (D1, D2, D3). All the 3 projects use sqlite3 as DB.</p> <p>All the 3 projects aside from their inherent differences also have a single common django Model called &quo...
<python><django><sqlite><django-models>
2023-12-09 08:03:26
1
359
Krishna
77,630,410
8,176,763
fastapi swagger interface showing operation level options override server options
<p>I have been recently finding a popup that tells me some operation level options override the global server options:</p> <p>As per image:</p> <p><a href="https://i.sstatic.net/hxem3.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/hxem3.png" alt="enter image description here" /></a></p> <p>I do not unde...
<python><swagger><fastapi>
2023-12-09 06:53:44
1
2,459
moth
77,630,159
6,533,037
Get string typed in input after screen reset
<p>I have a websocket chat-application. The user can send and receive messages simultaneously. The problem I had however is that because it is a CLI application the input-line of the user got messed up with the incoming messages.</p> <p>You would have something like:</p> <pre><code>Message: Hello Type message: Hi Messa...
<python><websocket>
2023-12-09 04:44:34
1
1,683
O'Niel
77,630,116
3,486,773
How to stop tkinter thread but keep window open?
<p>I have a button that when pressed starts a new thread:</p> <pre><code>import tkinter as tk import threading db = tk.Button(root, text='Download!', height=2, width=30, background='light blue',command=lambda: threading.Thread(target=runYtAction) .start()).grid( row=22, column=0, sticky=tk.W, padx=120, pady=...
<python><multithreading><tkinter>
2023-12-09 04:22:41
1
1,278
user3486773
77,630,091
4,225,430
How to modify subsetting and datetime handling with .loc[] to avoid warning?
<p>I try to practice time series with real data. The difficulty is in data wrangling.</p> <p>This exercise is to show the local passenger departure trend of one of the borders in Hong Kong in 2023.</p> <p>Jupyter warned me twice about subsetting and datetime handling, but I do not know how to change accordingly and why...
<python><pandas><datetime><pandas-loc>
2023-12-09 04:08:04
0
393
ronzenith
77,629,977
8,497,844
What is named this structure?
<p>Some days ago I saw this Python <code>string</code> structure:</p> <pre><code>str = ( 'this is a very' 'long string too' 'for sure ...' ) </code></pre> <p>I'm interested how is named this structure? It's not <code>list</code> or <code>tuple</code>.</p> <p>Sorry for maybe simple question but I tried to found in offic...
<python>
2023-12-09 02:57:49
0
727
Pro
77,629,929
1,945,925
python lxml xpath query fails on hardcoded url but works on a bytes string
<p>I am trying to extract an xml attribute <code>parsable-cite</code> from the <code>text</code> tag. I am parsing an xml from the url &quot;https://www.congress.gov/118/bills/hr61/BILLS-118hr61ih.xml&quot;.</p> <p>The code I'm using is the following (Replit here <a href="https://replit.com/join/ohhztxpqdr-aam88" rel="...
<python><xml><xpath><lxml>
2023-12-09 02:24:15
1
552
Andre Marin