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
75,634,166
16,371,459
Mel Spectogram normalization for training neural network for singing voice synthesis
<p>What are the recommended mel-spectogram normalization techniques for training a neural network aimed at singing voice synthesis? My configuration settings are <code> n_fft= 2048, hop_length= 512, n_mels = 80</code></p> <p>I have implemented normalization using the code below (taken from the whisper repo), but it is...
<python><normalization><spectrogram><mel>
2023-03-04 07:00:42
0
318
Basir Mahmood
75,634,145
121,861
How to configure pymongo to automatically marshal and unmarshal protobufs
<p>I'd like to have protobuf support in pymongo. Specifically, I want to be able to pass protobufs anywhere that I could pass a dict (such as <code>collection.insert_one()</code>) and I want to get the appropriate protobuf instance anywhere I'd otherwise get a dict (such as <code>collection.find_one()</code>).</p> <p>S...
<python><mongodb><protocol-buffers><pymongo>
2023-03-04 06:56:22
1
3,384
James S
75,633,851
5,694,144
Is there an efficient way to determine if a sum of floats will be order invariant?
<p>Due to precision limitations in floating point numbers, the order in which numbers are summed can affect the result.</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; 0.3 + 0.4 + 2.8 3.5 &gt;&gt;&gt; 2.8 + 0.4 + 0.3 3.4999999999999996 </code></pre> <p>This small error can become a bigger problem if t...
<python><algorithm><math>
2023-03-04 05:33:51
5
363
John Cole
75,633,830
16,009,435
POST request from python to nodeJS server
<p>I am trying to send a post request from python to my nodeJS server. I can successfully do it from client-side js to nodeJS server using the fetch API but how can I achieve this with python? What I tried below is sending the post request successfully but the data/body attached to it is not reaching the server. What a...
<python><node.js>
2023-03-04 05:26:43
2
1,387
seriously
75,633,823
15,239,717
Django filter Two Models for ID
<p>I am working on a Django Application where registered users can be added Deposit by staff users, and I want to know whether a user has been added Deposit in the current month. And also check in HTML on a Button url whether the user has a deposit or Not then decide whether to display the Button or Not.</p> <p>I have ...
<python><django>
2023-03-04 05:25:11
1
323
apollos
75,633,807
11,630,148
rant_category() got an unexpected keyword argument 'slug'
<p>Running into an <code>rant_category() got an unexpected keyword argument 'slug'</code> on my django project. Basically, I just need to get the slug of the <code>#category</code> in my app to show it in the url.</p> <p>Here's my code:</p> <p><code>views.py</code></p> <pre><code>class RantListView(ListView): model...
<python><django><django-models><django-views><django-templates>
2023-03-04 05:19:24
3
664
Vicente Antonio G. Reyes
75,633,662
1,601,580
How do you load a specific GPU from CUDA_AVAILABLE_DEVICES in PyTorch?
<p>I came up with this code but it's resulting in never ending bugs:</p> <pre><code>def get_device_via_env_variables(deterministic: bool = False, verbose: bool = True) -&gt; torch.device: device: torch.device = torch.device(&quot;cpu&quot;) if torch.cuda.is_available(): if 'CUDA_VISIBLE_DEVICES' not in ...
<python><machine-learning><deep-learning><pytorch>
2023-03-04 04:33:57
2
6,126
Charlie Parker
75,633,628
19,238,204
Plotting Solid of Revolution Animation that is Revolved toward y-axis Python 3 and Matplotlib
<p>I have this modified code with Python from:</p> <p><a href="https://stackoverflow.com/questions/36464982/ploting-solid-of-revolution-in-python-3-matplotlib-maybe">Ploting solid of revolution in Python 3 (matplotlib maybe)</a></p> <p>But, I want to revolve this toward <code>y</code>-axis. How?</p> <p>This is the code...
<python><numpy><matplotlib>
2023-03-04 04:22:16
1
435
Freya the Goddess
75,633,585
5,366,075
unable to install forexconnect python package
<p>I have python 3.9.6.</p> <p><code>Pip install, python3 pip install</code> none of these is able to install forexconnect(<a href="https://github.com/gehtsoft/forex-connect" rel="nofollow noreferrer">https://github.com/gehtsoft/forex-connect</a>) package</p> <pre><code>$ python3 -m pip install forexconnect ERROR: Cou...
<python><pip>
2023-03-04 04:06:55
2
1,863
usert4jju7
75,633,563
9,957,175
How to compress existing h5py file efficiently using multiprocessing
<p>I have a program that streams large amounts of data I need to save for later processing. This program is highly time sensitive, and as such I need to save the data as quickly as possible. To handle large volumes of data, I use <code>h5py</code> and do not use compression to ensure we take as little time as possible ...
<python><multiprocessing><hdf5><h5py>
2023-03-04 03:59:53
0
740
Carl H
75,633,471
1,039,860
trying to get date from a customer date picker in pything and tkinter
<p>I want to minimize the number of clicks and typing a user has to go through to select a date. This code pops up a date picker with the option of either clicking on a date or the cancel button, or hitting the ESC key. My problem is that when I click on a date, the option_changed function is called as expected, but ...
<python><tkinter><calendar>
2023-03-04 03:29:18
1
1,116
jordanthompson
75,633,334
853,113
Beautiful Soup - Get all text, and preserve link html?
<p>I am parsing multiple HTML pages using beautiful soup. Most of the scenarios work great. I want to include text along with the URL for links.</p> <p>The current syntax is:</p> <pre><code> soup = MyBeautifulSoup(''.join(body), 'html.parser') body_text = self.remove_newlines(soup.get_text()) </c...
<python><beautifulsoup>
2023-03-04 02:43:32
1
357
VV75
75,633,108
15,239,717
Django get Models ID from Zip_longest() function data on HTML
<p>I am working a Django application where I have used python zip_longest function with a the for loop for displaying both the Customer Deposits and Withdrawals in an HTML Table, and I want to get the second zipped list item ID unto a url in a button. How do I achieve this. Here is my Model:</p> <pre><code>class Witdra...
<python><django><django-views><django-templates><django-urls>
2023-03-04 01:22:43
1
323
apollos
75,633,054
19,321,677
Issues with lenght mis-match when fitting model on categorical variables using xgb classifier
<p>I trained a model which has several categorical variables which I encoded using dummies from pandas. Now, when I score the model on new/unseen data, I have lesser categorical variables than in the train dataset. Thus, I get a mis-match error.</p> <p>Instead of using pd.dummies, is there a better best practice so acc...
<python><machine-learning><scikit-learn><feature-engineering>
2023-03-04 01:07:03
1
365
titutubs
75,632,975
10,530,575
how to align rows in datafrane after pd.concat() Python pandas
<p>I have 2 single column dataframes, after perform a LEFT JOIN using pd.conca, first column value doesn't align with the second one</p> <pre><code>import pandas as pd df1 = pd.DataFrame({ 'city':['ABC','NEW','TWIN','KING']}) df2 = pd.DataFrame({ 'city':['NEW','ABC']}) </code></pre> <p><a href="https://i.sstatic.net/Ol...
<python><python-3.x><pandas><dataframe>
2023-03-04 00:45:11
2
631
PyBoss
75,632,938
11,429,035
Change coordinate of numpy array?
<p>I wonder if there is an elegant way to customize another coordinate system for numpy array? The reason I hope to change the coordinate system is I hope to avoid any potential error in my simulation process.</p> <p>For example, if I want an object move upwards, from <code>(2,2)</code> to <code>(2,3)</code> in a norma...
<python><numpy>
2023-03-04 00:35:32
1
533
Xudong
75,632,858
18,086,775
Add columns to a new level in multiindex dataframe
<p>My dataframe looks like this:</p> <pre class="lang-py prettyprint-override"><code>data = { 'WholesalerID': {0: 121, 1: 121, 2: 42, 3: 42, 4: 54, 5: 43, 6: 432, 7: 4245, 8: 4245, 9: 4245, 10: 457}, 'Brand': {0: 'Vans', 1: 'Nike', 2: 'Nike', 3: 'Vans',4: 'Vans', 5: 'Nike', 6: 'Puma', 7: 'Vans', 8: 'Nike', 9: 'Puma',...
<python><pandas><dataframe><multi-index>
2023-03-04 00:13:33
1
379
M J
75,632,776
11,824,033
Calling function from right parent class with multiple inheritance in Python
<p>I have two classes <code>A</code> and <code>B</code> and both have a method <code>get_type()</code> that returns a string and which is called in the <code>__init__()</code> of both classes to set an instance attribute <code>self.type</code>. Now there's a child class that inherits from both <code>A</code> and <code>...
<python><python-3.x><class><inheritance><multiple-inheritance>
2023-03-03 23:52:17
3
359
Pickniclas
75,632,773
505,188
Matplotlib Save Figures Write Over Each Other
<p>I have two functions that create saved graphs, but the second graph always has the first graph laid over it - here is the code to reproduce the problem. In this case graph.png will be a combination of dendo.png and what was supposed to be graph.png by itself. Is this just way Matplotlib works or is there something...
<python><matplotlib>
2023-03-03 23:51:49
1
712
Allen
75,632,764
13,014,469
How to read audio data (.wav) from azure blob storage using pyspark
<p>Hello fellow stackoverflowers.</p> <p>I am having a problem with reading <strong>audio data</strong> from blob storage using pyspark. I am using databricks in my example.</p> <p>UPDATED: I have gotten to this solution, that reads the data as raw <strong>binaries</strong>, but it seems that this solution is not optim...
<python><pandas><pyspark><azure-blob-storage><databricks>
2023-03-03 23:49:59
0
781
Vojtech Stas
75,632,754
4,790,871
Regex (?J) mode modifier in Python Regex or equival ability for named capture group from different patterns
<p>I am trying to capture from two different pattern sequences using a named capture group. <a href="https://stackoverflow.com/questions/58618907/how-to-capture-text-on-either-side-of-a-pattern-into-a-named-capture-group">This SO question</a> solves the problem in PCRE using the mode modifier <code>(?J)</code>, and <a ...
<python><regex>
2023-03-03 23:47:15
1
32,449
David Parks
75,632,726
2,893,024
SQLAlchemy Mapper Events don't get triggered
<p><strong>I can't get <a href="https://docs.sqlalchemy.org/en/14/orm/events.html#mapper-events" rel="nofollow noreferrer">Mapper Events</a> to trigger in SqlAlchemy 2.0</strong></p> <p><strong>tl;dr:</strong> I am able to perform operations but events never trigger.</p> <p>Below is the example they have in their <a hr...
<python><sql><sqlalchemy>
2023-03-03 23:39:07
1
3,576
Michael Seltenreich
75,632,612
11,546,773
Fastest way to apply histcount on an array grouped by previous bin result
<p>I have 2 large numpy arrays which I need to bin according to some bin values. The first array needs to be binned with the data1Bins values. Then the data in the second array needs to be grouped by the result of the bins on the first array. When this grouping is done, the amount of values in each bin needs to be coun...
<python><pandas><dataframe><numpy>
2023-03-03 23:12:47
1
388
Sam
75,632,596
3,861,965
GCP Billing error when Billing is enabled
<p>I have this Python code:</p> <pre><code>def upload_to_gcs(bucket_name, local_file_path, gcs_file_name): &quot;&quot;&quot; Uploads local files to Google Cloud Storage (GCS). :param bucket_name: string :param local_file_path: string :param gcs_file_name: string :return: None &quot;&quot;&...
<python><google-cloud-platform><google-cloud-billing>
2023-03-03 23:10:10
1
2,174
mcansado
75,632,469
1,185,242
Why does np.astype('uint8') give different results on Windows versus Mac?
<p>I have a <code>(1000,1000,3)</code> shaped numpy array (<code>dtype='float32'</code>) and when I cast it to <code>dtype='uint8'</code> I get different results on Windows versus Mac.</p> <p>Array is available here: <a href="https://www.dropbox.com/s/jrs4n2ayh86s0fn/image.npy?dl=0" rel="nofollow noreferrer">https://ww...
<python><numpy>
2023-03-03 22:45:44
1
26,004
nickponline
75,632,438
3,357,935
How do I read a specific line from a string in Python?
<p>How can I read a specific line from a string in Python? For example, let's say I want line 2 of the following string:</p> <pre><code>string = &quot;&quot;&quot;The quick brown fox jumps over the lazy dog.&quot;&quot;&quot; line = getLineFromString(string, 2) print(line) # jumps over the </code></pre> <p>There are ...
<python><line>
2023-03-03 22:40:49
2
27,724
Stevoisiak
75,632,012
1,039,860
How to tell which OptionMenu was changed using python and tkinter
<p>I am building a spreadsheet of sorts. One of the columns has an OptionMenu in each cell. Each OptionMenu has its own class member StringVar (in an array) associated with it. All OptionMenus use a single callback. How do I know which OptionMenu (and its associated StringVar) was selected?</p> <pre><code> self.e...
<python><tkinter><optionmenu>
2023-03-03 21:26:08
1
1,116
jordanthompson
75,631,799
2,835,670
Finding the values of neurons using keras
<p>I have a very simple neural net:</p> <pre><code>model=Sequential() model.add(Dense(units=2, activation='relu', input_dim=2) model.add(Dense(units=1, activation='sigmoid')) </code></pre> <p>Basically I have an input layer with 2 values, a hidden layer with 2 neurons, and an output layer with one.</p> <pre><code>print...
<python><keras><deep-learning><neural-network>
2023-03-03 20:56:33
0
2,111
user
75,631,703
6,077,239
Polars list.to_struct() throws "PanicException: expected known type"
<p>This is a new question/issue as a follow up to <a href="https://stackoverflow.com/questions/75516576/how-to-return-multiple-stats-as-multiple-columns-in-polars-grouby-context">How to return multiple stats as multiple columns in Polars grouby context?</a> and <a href="https://stackoverflow.com/questions/75595957/how-...
<python><python-polars>
2023-03-03 20:43:24
2
1,153
lebesgue
75,631,648
4,117,869
Confluent Kafka - Lowest read offset
<p>When consuming from a non-compacted topic, how can I determine the earliest available offset on the topic? In my case the message retention is 7 days. Low watermark does not help in this case because it is 0 and of course not what I am looking for. Is there any alternative to</p> <pre><code> get_watermark_offsets...
<python><apache-kafka><confluent-kafka-python>
2023-03-03 20:34:23
1
482
rpd
75,631,533
13,916,049
Retain data types after concatenating pandas dataframes
<p>The data type for the last column for all the dataframes is &quot;object&quot;. The remaining columns of the <code>mut</code> dataframe is binary, whereas the remaining columns of the other dataframes are float.</p> <p>In my code below, the resulting dataframe <code>df_scaled</code> has &quot;object&quot; data type ...
<python><pandas><types>
2023-03-03 20:17:29
0
1,545
Anon
75,631,514
13,083,700
Decoding XMP data read using python from .lrcat
<p>I'm reading .lrcat data using a python script and sqlite3. I have a column in the Adobe_AdditionalMetadata table called xmp with an odd encoding, probably an Adobe Lightroom encoding. Here's my chunk of code:</p> <pre><code>from libxmp import XMPFiles cursor = conn.execute('SELECT xmp FROM Adobe_AdditionalMetadata'...
<python><encoding><xmp><lightroom>
2023-03-03 20:15:36
2
470
Alex
75,631,429
1,175,496
Python str vs unicode on Windows, Python 2.7, why does 'á' become '\xa0'
<p><strong>Background</strong></p> <p>I'm using a Windows machine. I know Python 2.* is not supported anymore, but I'm still learning Python 2.7.16. I also have Python 3.7.1. I know in Python 3.* <a href="https://stackoverflow.com/a/18034409/1175496">&quot;<code>unicode</code> was renamed to <code>str</code>&quot;</a><...
<python><windows><encoding>
2023-03-03 20:03:24
1
21,588
Nate Anderson
75,631,407
12,671,057
Fast way to find max number of consecutive 1-bits in million-bit numbers
<p>For example, 123456789 in binary is <code>111010110111100110100010101</code>. The max number of consecutive 1-bits is <code>4</code>. I got interested in solving that efficiently for very large numbers (million bits or even more). I came up with this:</p> <pre><code>def onebits(n): ctr = 0 while n: n...
<python><performance><binary><biginteger>
2023-03-03 20:00:05
2
27,959
Kelly Bundy
75,631,378
3,713,236
sklearn.impute.SimpleImputer: Unable to fill in the most common value for a list of dataframe columns
<p>I have a list of columns of a dataframe that have NA's in them (below). The <code>dtype</code> of all these columns is <code>str</code>.</p> <pre><code>X_train_objects = ['HomePlanet', 'Destination', 'Name', 'Cabin_letter', 'Cabin_number', 'Cabin_letter_2'] </code></pre> <p>I would like to use <code>SimpleImput...
<python><pandas><scikit-learn><imputation>
2023-03-03 19:56:27
1
9,075
Katsu
75,631,363
7,376,511
Type-hint a nested json api response
<p>Let's say I have an api endpoint that returns a complex response.</p> <pre><code>data = requests.get(&quot;https://my.api/garbage&quot;).json() # { # &quot;a&quot;: 1, # &quot;b&quot;: &quot;asd&quot;, # &quot;c&quot;: [1,2], # &quot;d&quot;: { # &quot;e&quot;: &quot;dsa&quot;, # &quo...
<python><serialization><python-dataclasses><typeddict>
2023-03-03 19:54:10
0
797
Some Guy
75,631,315
5,212,614
Using Natural Language Processing, how can we add our own Stop Words to a list?
<p>I am testing the library below, based on this code sample:</p> <pre><code>import matplotlib.pyplot as plt from sklearn.feature_extraction.text import ENGLISH_STOP_WORDS from collections import Counter df_new = pd.DataFrame(['okay', 'yeah', 'thank', 'im']) stop_words = text.ENGLISH_STOP_WORDS.union(df_new) #stop_wor...
<python><python-3.x><nlp>
2023-03-03 19:48:20
2
20,492
ASH
75,631,259
15,915,737
Manage github Action Workflow with Prefect Cloud 2
<p>I have several GitHub action workflows to run. To manage them I want to use Prefect Cloud. I created a deployment and a GitHub block in Prefect. When I schedule a deployment to run, it stays in &quot;late&quot; state.</p> <p>My repository structure:</p> <pre><code>my_git_repo └─github/workflows └─prefect_d...
<python><deployment><github-actions><prefect>
2023-03-03 19:40:01
1
418
user15915737
75,631,221
275,002
IBKR: No security definition has been found for the request, contract:
<p>I am new in both IBKR and its API, the code given below is giving error on <code>qualifyContracts</code> method:</p> <pre><code>Error 200, reqId 308: No security definition has been found for the request, contract: Option(symbol='TSLA', lastTradeDateOrContractMonth='20230303', strike=808.33, right='C', exchange='CBO...
<python><interactive-brokers><tws><ib-insync>
2023-03-03 19:35:29
1
15,089
Volatil3
75,631,084
19,321,677
How to create stacked bar chart with given dataframe shape?
<p>I have a dataframe and would like to create a stacked bar chart by having date on the x-axis and quantity on the y-axis. This is the current dataframe:</p> <pre><code>date | product_group | quantity 2021-10-01 | A | 10 2021-10-01 | C | 10 2021-10-01 | Z | 80 2021-11-11 | A ...
<python><pandas><matplotlib><seaborn>
2023-03-03 19:19:26
2
365
titutubs
75,631,069
15,766,257
How to create file object using filename in Box
<p>I need to rename a file in Box using the Python SDK API. I know the filename, but I guess to rename it I need a file object. How do I create a file object when all I have is the name of the file? The file is located in the root folder.</p>
<python><box-api>
2023-03-03 19:18:12
1
331
Bruce Banner
75,630,999
15,781,591
How to make custom row and column labels in displot
<p>I have the following code using the <code>seaborn</code> library in python that plots a grid of histograms from data from within the <code>seaborn</code> library:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd import matplotlib.pyplot as plt import seaborn as sns, numpy as np from pylab impo...
<python><matplotlib><seaborn><facet-grid><displot>
2023-03-03 19:10:09
1
641
LostinSpatialAnalysis
75,630,851
12,470,058
How to replace character $ by using re.sub?
<p>Suppose we have the following string and list of numbers:</p> <p><code>my_string = &quot;We change $ to 10, $ to 22, $ to 120, $ to 230 and $ to 1000.&quot;</code></p> <p><code>nums = [1, 2, 3, 4, 5]</code></p> <p>By only using <code>re.sub</code>, how to replace the <code>$</code> character in <code>my_string</code...
<python><python-3.x>
2023-03-03 18:52:01
1
368
Bsh
75,630,794
12,574,341
Python venv pip is always outdated
<p>Whenever I create a fresh Python 3.11 virtual environment using <code>venv</code>, the provided <code>pip</code> always prompts me to update to the latest version, even though my base version appears to be up to date</p> <pre class="lang-bash prettyprint-override"><code>$ python3.11 -m pip --version pip 23.0.1 from ...
<python><pip><python-venv>
2023-03-03 18:44:49
1
1,459
Michael Moreno
75,630,733
1,936,752
Leetcode "Decode Ways" problem and recursion error
<p>I am trying to solve the Leetcode Decode Ways problem (<a href="https://leetcode.com/problems/decode-ways/" rel="nofollow noreferrer">https://leetcode.com/problems/decode-ways/</a>). Consider a string with upper case elements from the English alphabet represented by numbers. So <code>A</code> maps to <code>1</code>,...
<python><recursion>
2023-03-03 18:37:28
1
868
user1936752
75,630,570
21,113,865
How to avoid SSL error when using python requests in a virtual environment?
<p>So I have a python script that needs to access webpage content via 'requests'. Due to the environment this script is running in, I need to use a virtual environment. However, this results in the request failing, since it cannot find the certificate from the virtual environment.</p> <pre><code>raise SSLError(e, reque...
<python><python-3.x><ssl><python-requests><ssl-certificate>
2023-03-03 18:17:09
0
319
user21113865
75,630,544
2,146,894
Can these pairs of regexes be simplified into one?
<p>I'm trying to fetch twitter usernames from strings. My current solution looks like this</p> <pre><code>def get_username(string): p1 = re.compile(r'twitter\.com/([a-z0-9_\.\-]+)', re.IGNORECASE) p2 = re.compile(r'twitter[\s\:@]+([a-z0-9_\.\-]+)', re.IGNORECASE) match1 = re.search(p1, string) match2 = ...
<python><regex>
2023-03-03 18:12:54
4
21,881
Ben
75,630,411
346,977
Python & pandas: Batching data where difference between timestamps < set value
<p>I'm trying to create a data set in python (preferably pandas) that groups together all rows where the amount of time between the end_time of the last entry and the start_time of the subsequent one is &lt; 10 minutes.</p> <p>Example data:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>ac...
<python><pandas>
2023-03-03 17:58:16
1
12,635
PlankTon
75,630,285
10,634,126
Logging python tenacity retry_state with logger from outer scope
<p>I have a module that includes a utility function with a tenacity retry tag</p> <pre><code>from tenacity import retry, stop_after_attempt, wait_random def log_attempt_number(logger, retry_state): logger.info(f&quot;Attempt number {retry_state}&quot;) logger.info(&quot;Logger is not recognized here unless we inst...
<python><logging><python-logging><python-tenacity><tenacity>
2023-03-03 17:43:56
1
909
OJT
75,630,249
5,235,665
Pandas groupby and sum are dropping numeric columns
<p>I have the following Python/Pandas code:</p> <pre><code>standardized_df = get_somehow() standardized_df['TermDaysAmountProduct'] = standardized_df['TermDays'] * standardized_df['Amount'] standardized_df['DaysToCollectAmountProduct'] = standardized_df['DaysToCollect'] * standardized_df['Amount'] logger.info(&quot;sta...
<python><pandas>
2023-03-03 17:39:38
1
845
hotmeatballsoup
75,630,200
4,450,090
python aiokafka many consumers to many producers
<p>I use aiokafka to consume from, filter message fields and produce messages back to kafka. I run 4 async consumers which put messages to async queue. Then single process consumes that queue and produces to async output_queue. Multiple produces consume from async output_queue and send back to kafka.</p> <p>I wanted to...
<python><consumer><producer><aiokafka>
2023-03-03 17:33:29
0
2,728
Dariusz Krynicki
75,630,145
3,941,935
Initialize fsspec DirFileSystem from a URL
<p>I want to initalize a <code>fsspec</code> filesystem based on a URL - both the protocol and the root directory. E.g. I could create a filesystem from <code>gcs://my-bucket/prefix</code> that would use <code>my-bucket</code> on GCS, or <code>file:///tmp/test</code> that would use the <code>/tmp/test</code> directory ...
<python><fsspec>
2023-03-03 17:26:02
1
347
Tomasz Sodzawiczny
75,630,114
19,130,803
Multiprocessing and event, type hint issue python
<p>I have used multiprocessing module to perform a background task.</p> <pre><code># module_a.py from multiprocessing import Event from multiprocessing import Process class BackgroundWorker(Process): &quot;&quot;&quot;Create a worker background process.&quot;&quot;&quot; def __init__( self, n...
<python><multiprocessing><mypy>
2023-03-03 17:22:05
1
962
winter
75,629,948
19,482,605
Why does getrefcount increase by 2 when put inside a function?
<p>Consider the following code:</p> <pre class="lang-py prettyprint-override"><code>import sys a = [1, 2, 3] def foo(x): print(sys.getrefcount(x)) foo(a) # prints out 4 -- but why? </code></pre> <p>When we invoke <code>foo(a)</code> and when <code>print(sys.getrefcount(x))</code> executes, the array <code>[1, 2,...
<python><cpython><reference-counting>
2023-03-03 17:03:44
1
367
lamc
75,629,940
12,469,912
How to replace particular characters of a string with the elements of a list in an efficient way?
<p>There is a string:</p> <p><code>input_str = 'The substring of &quot;python&quot; from index @ to index @ inclusive is &quot;tho&quot;'</code></p> <p>and a list of indices:</p> <p><code>idx_list = [2, 4]</code></p> <p>I want to replace the character <code>@</code> in <code>str_input</code> with each element of the <c...
<python><python-3.x>
2023-03-03 17:02:45
4
599
plpm
75,629,863
12,597,387
How to check which format is date in python
<p>I'm getting the date in a string and it's not always same format, is there a way to detect what format is that date for example:</p> <p>If data comes like this 2023-12-03 I want to somehow get output like this &quot;%Y-%m-%d&quot;, so I know which format is using. This is just an example format date in the string ca...
<python><python-3.x>
2023-03-03 16:55:33
1
314
GomuGomu
75,629,852
15,176,150
Why use a superclass's __init__ to change it into a subclass?
<p>I'm working on replicating the <a href="https://github.com/slundberg/shap" rel="nofollow noreferrer">SHAP package</a> algorithm - an explainability algorithm for machine learning. I've been reading through the author's code, and I've come across a pattern I've never seen before.</p> <p>The author has created a super...
<python><design-patterns><subclass><superclass><monkeypatching>
2023-03-03 16:55:04
1
1,146
Connor
75,629,831
11,312,371
Pandas Average If Across Multiple Columns
<p>In pandas, I'd like to calculate the average age and weight for people playing each sport. I know I can loop, but was wondering what the most efficient way is.</p> <pre class="lang-py prettyprint-override"><code>df = pd.DataFrame([ [0, 1, 0, 30, 150], [1, 1, 1, 25, 200], [1, 0, 0, 20, 175] ], columns=[ ...
<python><pandas>
2023-03-03 16:52:29
2
457
Scott Guthart
75,629,813
2,532,296
signed fractional multiplication using q(4,20)
<p>I am doing a simple test to understand signed fractional multiplication in ordinary format and in Q(4,20) format (<a href="https://en.wikipedia.org/wiki/Q_(number_format)" rel="nofollow noreferrer">https://en.wikipedia.org/wiki/Q_(number_format)</a>). I am using the fxpmath library (<a href="https://github.com/franc...
<python><signal-processing><signed><fractions>
2023-03-03 16:50:58
1
848
user2532296
75,629,394
13,359,498
Why can't I show confusion matrix of ensemble model majority voting approach?
<p>I've built an ensemble model with a majority voting approach. I used pretrained models to build the model. code snippet:</p> <pre><code>from sklearn.metrics import classification_report, confusion_matrix # Make predictions using the ensemble method with max voting ensemble_predictions = [model1.predict(X_test), mod...
<python><tensorflow><keras><deep-learning>
2023-03-03 16:07:57
0
578
Rezuana Haque
75,629,388
17,194,313
How to update a Python library that is currently in use?
<p>I have a few long running processes (FastAPI, Dagster, etc...) and it's not clear to me how I should handle updates.</p> <p>I can just run <code>pip install {package} --upgrade</code>, and run it until it eventually works.</p> <p>But is this the best way to handle it?</p>
<python>
2023-03-03 16:07:25
0
3,075
MYK
75,629,102
4,451,315
"or" in pip constraint
<p>On conda-forge, <code>tzdata</code> has version numbers like:</p> <ul> <li>2022a</li> <li>2022b</li> <li>2022c</li> </ul> <p>But on PyPI, the version numbers are like:</p> <ul> <li>2022.1</li> <li>2022.2</li> <li>2022.3</li> </ul> <p>How can I set a requirement, in my <code>pyproject.toml</code> file, to require at ...
<python><pip>
2023-03-03 15:38:51
1
11,062
ignoring_gravity
75,629,071
17,696,880
Why when split a string into a list of substrings, without removing the separators, parts of this original string are lost in the splitting process?
<pre><code>import re from itertools import chain def identification_of_nominal_complements(input_text): pat_identifier_noun_with_modifiers = r&quot;((?:l[oa]s|l[oa])\s+.+?)\s*(?=\(\(VERB\))&quot; substrings_with_nouns_and_their_modifiers_list = re.findall(pat_identifier_noun_with_modifiers, input_text) se...
<python><python-3.x><regex><list><split>
2023-03-03 15:35:29
1
875
Matt095
75,629,048
1,818,059
How to calculate amount of cyclic permuations in an array (variable shift)
<p>Referring to <a href="https://stackoverflow.com/questions/22615621/how-to-calculate-cyclic-permutation-of-an-array">another question</a>, I would like to print (and count amount of) cyclic permuations of an array. My input to such function would be the array, stride and start value.</p> <p>My array does not necessa...
<python><arrays>
2023-03-03 15:33:49
2
1,176
MyICQ
75,629,006
12,082,289
Apache Airflow, Custom Trigger logs not showing up
<p>I'm learning about Apache Airflow, and have implemented a simple custom Sensor and Trigger</p> <pre><code>from datetime import timedelta from airflow.sensors.base import BaseSensorOperator from airflow.utils.decorators import apply_defaults from airflow.triggers.temporal import TimeDeltaTrigger from triggers.exampl...
<python><airflow>
2023-03-03 15:29:30
1
565
Jeremy Farmer
75,628,777
9,859,642
Reading 3-dimensional data from many files
<p>I have many text files with data written in such a structure:</p> <pre><code>#ABTMTY mdjkls 993583.17355 ebgtas 899443.47380 udenhr 717515.59788 paomen 491385.80901 gneavc 275411.91025 wesuii 119744.95306 ploppm 59145.56233 #MNTGHP mdjkls 5668781.68669 ebgtas 3852468.7...
<python><pandas><dataframe><python-xarray>
2023-03-03 15:10:49
1
632
Anavae
75,628,737
13,950,870
Best way to use a single logger in my python project, overwrite root logger or replace import everywhere?
<p>Title is a bit vague but I think my code examples make it clear. I want to start using a custom logger in a large project of mine.</p> <p>Currently, in every file that I use logging, I import logging and use that like this:</p> <pre><code># file A import logging logging.info(...) </code></pre> <p>I do this in many ...
<python><logging><python-logging>
2023-03-03 15:06:52
1
672
RogerKint
75,628,646
8,087,322
pyproject.toml in an isolated environment
<p>I am trying to use <code>pyproject.toml</code> (and specifically setuptools_scm) in an isolated environment. My minimal <code>pyproject.toml</code> is:</p> <pre class="lang-ini prettyprint-override"><code>[build-system] requires = [&quot;setuptools-scm&quot;] [tool.setuptools_scm] write_to = &quot;mypackage/version...
<python><setuptools><pyproject.toml><setuptools-scm>
2023-03-03 14:59:23
1
593
olebole
75,628,594
2,852,466
Python program to load only a certain mega bytes of an excel file into the dataframe and convert it to string
<p>I am pretty new to Python and I was going through some of the uses of the <code>pandas</code> library. However, I could not find a way to load only a partial excel file into the memory and play with it. For example, if I set the memory limit as 1MB, the program should be able to read the first 1MB from the excel fil...
<python><pandas><openpyxl>
2023-03-03 14:54:05
1
1,001
Ravi
75,628,544
19,130,803
access logger object from decorator with type hints python
<p>I have created a <code>log</code> decorator. I have put the decorator on required functions. I also want to access the <code>log</code> object inside the decorated functions.</p> <p>The code works correctly when I run the program, Later I added type hints to the code.</p> <p>On running mypy I am getting error as bel...
<python><logging><mypy><python-logging>
2023-03-03 14:49:24
0
962
winter
75,628,536
1,057,639
Spark ETL Large data transfer - how to parallelize
<p>I am looking to move a large amount of data from one db to another and I have seen that Spark is a good tool for doing this. I am trying to understand the process and the ideology behind Spark's big data ETL's. Would also appreciate if someone could explain how Spark goes about parallelizing (or splitting) the data ...
<python><pyspark><google-bigquery><aws-glue><amazon-keyspaces>
2023-03-03 14:48:12
1
26,831
Ganaraj
75,628,495
9,403,794
How to groupby numpy ndarray and return first row from each group. Now sort before
<p>I have ndarray:</p> <pre><code>[[1 1] [0 2] [0 3] [1 4] [1 5] [0 6] [1 7]] </code></pre> <p>I expect reduced result like that:</p> <pre><code>[[1 1] [0 2] [1 4] [0 6] [1 7]] </code></pre> <p>Result ndarray should contain first row from each group. I build a groups on values from column 0. This is value...
<python><pandas><numpy>
2023-03-03 14:44:02
2
309
luki
75,628,175
16,127,735
Running Python on a webserver using PHP
<p>I'm using a PHP script to execute a Python script on a localhost XAMPP web server:</p> <pre><code>&lt;?php $python_path = 'C:\Users\alona\AppData\Local\Programs\Python\Python39\python.exe'; $output = shell_exec($python_path . ' my_script.py'); echo $output; ?&gt; </code></pre> <p>When the Python script contains simp...
<python><php>
2023-03-03 14:13:48
1
1,958
Alon Alush
75,628,106
5,510,540
Python: creating plot based on observation dates (not as a time series)
<p>I have the following dataset</p> <pre><code>df id medication_date 1 2000-01-01 1 2000-01-04 1 2000-01-06 2 2000-04-01 2 2000-04-02 2 2000-04-03 </code></pre> <p>I would like to first reshape the data set into days after the first observation per patient:</p> <pre><code>id day1 day2 day3 day4 1 yes no no ...
<python><pandas><plot>
2023-03-03 14:07:01
1
1,642
Economist_Ayahuasca
75,628,095
13,349,539
Field not updating in MongoDB using FastAPI
<p>I have a document schema that looks like this:</p> <pre><code>{ &quot;_id&quot;: &quot;8a28d1fc-602b-43ba-a017-105a4fff35b3&quot;, &quot;isDeleted&quot;: false, &quot;user&quot;: { &quot;timestamp&quot;: &quot;2023-03-03&quot;, &quot;phone&quot;: &quot;+012345678912&quot;, &quot;age&quot;: 25, ...
<python><mongodb><nosql><fastapi>
2023-03-03 14:06:21
0
349
Ahmet-Salman
75,628,082
13,328,195
How to get the closest match among three numbers
<p>I have a list :</p> <pre><code>[(1, 49, 47), (11, 44, 6), (24, 16, 31), (11, 29, 47), (41, 14, 24), (40, 29, 1), (32, 49, 44), (41, 14, 14), (24, 21, 49), (19, 24, 6)] </code></pre> <p>And a tuple <code>(7,2,3)</code> I need to choose a value from this list such that every element in the tuple should be less than or...
<python><numbers>
2023-03-03 14:04:49
1
2,719
Roshin Raphel
75,627,989
618,099
git-filter-repo loses the remotes
<p>I <a href="https://stackoverflow.com/questions/74887239/git-automate-rewording-git-commit-messages-on-branch">previously</a> got this rewrite of history commit messages to work:</p> <pre class="lang-bash prettyprint-override"><code>#!/bin/bash # Create a temporary file to store the commit messages temp_file=$(mktem...
<python><bash><git><git-filter-repo>
2023-03-03 13:56:39
1
9,620
Norfeldt
75,627,943
1,387,346
Trigger visual update of CSS-specified property after Gtk3 widget state change
<p>I have a widget on which I am drawing in a python-gtk3 application, and clicking on it triggers a specific action. I want to show some visual feedback on hover, to indicate the widget is interactive. After figuring out cursors are not the way in Gtk3, I am trying to use a border, similar to what happens when hoverin...
<python><gtk3><pygobject><gobject-introspection>
2023-03-03 13:52:53
0
11,496
Cimbali
75,627,855
3,352,632
How do I mock a function that is defined within another function in python pytest with magic mock framework?
<p>Considering the following peace of code:</p> <pre><code>class X: def func_a(a): //function does somthing def func_b(b): // do something func_b(a) </code></pre> <p>How can I mock function func_b(a) in my test?</p> <pre><code>with patch('x.func_a.func_b', side_effect=mock_func_b) </code><...
<python><mocking><pytest><python-mock><pytest-mock>
2023-03-03 13:43:56
0
667
user3352632
75,627,785
19,723,806
How do I get indentation of bullet list (python-docx)
<p>I don't know what am I doing wrong. Based on the ruler in Word <code>left_indent</code> is the place where the text begins. So, I tried <code>left_indent</code> and it doesn't work, it only works on the normal text, with no bullet. Then I tried <code>first_line_indent</code>, doesn't work either.</p> <p>Btw, here's ...
<python><python-3.x><python-docx>
2023-03-03 13:37:48
0
354
Zigatronz
75,627,546
7,836,976
Jasypt equivalent for Python
<p>I'm trying to write a python application that must connect to a <code>Postgres</code> database.</p> <p>I'm trying to use <code>psycopg2</code> for this. Here's my connection:</p> <pre class="lang-py prettyprint-override"><code>connection = psycopg2.connect(user=&quot;username&quot;, password=&quot;password&quot;...
<python><database><encryption><connection-string><jasypt>
2023-03-03 13:14:25
0
7,544
runnerpaul
75,627,541
13,158,157
plotly subplots: is it possible to have one subplots occupy multiple columns or rows
<p>I am trying to have 3 plots on one figure using plotly subplots. Naturally, I could do just 3 rows but I am trying to have first two figures side-by-side and another being stretched out. Overall I am trying to get a layout on the picture (that I made with paint): <a href="https://i.sstatic.net/L3PdO.png" rel="nofoll...
<python><plotly>
2023-03-03 13:14:14
1
525
euh
75,627,463
3,861,965
Reading JSON with Terraform jsondecode failing for valid JSON file
<p>I have a JSON file in S3 which looks like this:</p> <pre><code>{ &quot;data_sources&quot;: [ { &quot;name&quot;: &quot;monzo&quot;, &quot;tables&quot;: [ &quot;transactions&quot; ], &quot;format&quot;: &quot;CSV&quot;, &quot;extension&quot;: &quot;csv&quot; } ] } </c...
<python><json><terraform>
2023-03-03 13:07:40
0
2,174
mcansado
75,627,362
260
Azure Functions Python error - no job functions
<p>I am trying to run locally my Azure Functions using python and the error message I get is the following:</p> <pre><code>[2023-03-03T11:34:59.832Z] No job functions found. Try making your job classes and methods public. If you're using binding extensions (e.g. Azure Storage, ServiceBus, Timers, etc.) make sure you've...
<python><azure><azure-functions>
2023-03-03 12:55:55
6
11,562
gyurisc
75,627,327
9,773,920
Convert text to float in redshift with same output
<p>My view returns text field output since I concatenate my field with '%' symbol. When I push this data into excel using to_excel, it inserts as text and not numbers. Is there a way to fix this problem so that my excel sheets has numbers instead of text?</p> <p>redshift code:</p> <pre><code>select concat((((&quot;repl...
<python><pandas><aws-lambda><amazon-redshift><export-to-excel>
2023-03-03 12:52:47
2
1,619
Rick
75,627,291
5,575,597
How do I change a pandas row value, for a certain column, for a certrain date (datetimeindex) in a dataframe?
<p>I have a pd like this:</p> <pre><code>DATE delivery 2020-01-01 1 2020-01-01 11 2020-01-01 10 2020-01-01 9 2020-01-01 8 .. 2023-03-02 5 2023-03-02 4 2023-03-02 3 2023-03-02 2 2023-03-02 11 </code></pre> <p>Index is DateTimeIndex but not unique. I have a list...
<python><pandas><pandas-loc>
2023-03-03 12:48:47
1
863
cJc
75,627,197
6,156,353
Alembic - how to create hypertable
<p>How to generate hypertable using Alembic? Some custom call must be added I suppose, but where? I tried event.listen but Alembic does not register it.</p>
<python><sqlalchemy><alembic><timescaledb><sqlmodel>
2023-03-03 12:40:39
2
1,371
romanzdk
75,627,164
17,316,080
Choose only one from 2 args with Python ArgumentParser
<p>I use <code>ArgumentParser</code> to parse some arguments for function.</p> <p>I want to limit that that user can use or <code>count</code> or <code>show</code>, he can't use then both.</p> <p>How can I limit that?</p> <pre><code>parser = argparse.ArgumentParser( formatter_class=argparse.RawTextHelpFormatter, ...
<python><python-3.x><arguments>
2023-03-03 12:37:06
2
363
Kokomelom
75,627,137
4,338,000
How can I subtract from subsequent column in pandas?
<p>How can I subtract from column before itself for many columns without hardcoding it? I can do it by hard coding it as shown below:</p> <pre><code>import pandas as pd df = pd.DataFrame({&quot;a&quot;:[1,2,3,4],&quot;b&quot;:[1,3,5,6],&quot;c&quot;:[6,7,8,9]}) df['a_diff'] = df['a']-16 df['b_diff'] = df['b']-df['a'] ...
<python><pandas><dataframe>
2023-03-03 12:33:42
2
1,276
Sam
75,627,124
7,019,073
Lineplot with color, line style, and marker style as data dimension
<p>I have a pandas data frame that looks like this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>time</th> <th>performance</th> <th>attr_c</th> <th>attr_s</th> <th>attr_m</th> </tr> </thead> <tbody> <tr> <td>0</td> <td>10</td> <td>C1</td> <td>S1</td> <td>M0</td> </tr> <tr> <td>1</td> <td...
<python><pandas><seaborn><line-plot>
2023-03-03 12:32:26
1
1,040
Seriously
75,627,051
4,096,572
How to use np.cumsum to replicate the output of scipy.stats.expon.cdf?
<p>For context, I'm trying to understand how to use <code>np.cumsum</code> to replicate <code>scipy.stats.expon.cdf</code> because I need to write a function compatible with <code>scipy.stats.kstest</code> which is not one of the distributions already available in <code>scipy.stats</code>.</p> <p>I am having issues wit...
<python><numpy><scipy><probability-density><probability-distribution>
2023-03-03 12:25:16
1
605
John Coxon
75,627,001
542,270
How to convert a single object or a set into a set?
<p>There's a method as follows:</p> <pre><code>def send_message( content: str, slack_conn_ids: Union[SlackConnection, Set[SlackConnection]], send_only_in_production: bool = True, ): ... if isinstance(slack_conn_ids, set): set_slack_conn_ids = slack_conn_ids elif isinstance(slack_conn_ids, Sla...
<python>
2023-03-03 12:20:24
3
85,464
Opal
75,626,691
1,618,893
Session handling with pytest and sqlalchemy
<p>For every unit test I want to rollback already commited statements using <code>pytest.fixture</code> and <code>scoped_session</code>.</p> <h3>Setup</h3> <ul> <li>python 3.11</li> <li>sqlalchemy==2.0.3</li> <li>pytest==7.2.1</li> <li>factory-boy==3.2.1</li> <li>fastapi==0.91.0</li> </ul> <h3>Implementation</h3> <h4>c...
<python><unit-testing><sqlalchemy><pytest>
2023-03-03 11:46:49
1
962
Roman Purgstaller
75,626,660
2,107,030
pandas read_table with stopping strings to delimit different dataframes to assign
<p>I have a csv file of the form :</p> <pre><code>LINE 1 to SKIP LINE 2 to SKIP 2.13999987 0.139999986 -0.398405492 1 2.61999989 6.0000062E-2 0.450082362 1 2.74000001 5.99999428E-2 1.04403841 1 2.84000015 4.00000811E-2 6.17375337E-2 1 IGN IGN IGN IGN 21.4200001 0.420000076 1.53572667 1 22.3199997 0.479999542 -0.595370...
<python><pandas><dataframe><csv>
2023-03-03 11:43:47
1
2,166
Py-ser
75,626,522
6,730,854
How to add different background colors to different selection options in ttk.Combobox?
<p>I want to add different colors to different selections in Combobox. I found questions about changing the <a href="https://stackoverflow.com/questions/64755118/how-to-change-ttk-combobox-dropdown-colors-dynamically">overall</a> background color, but not per entry.</p> <p>I'm attaching some examples below.</p> <p><a h...
<python><tkinter><combobox><ttk><ttkwidgets>
2023-03-03 11:28:43
1
472
Mike Azatov
75,626,508
11,202,401
How to improve reliability of Django-Q Schedule Tasks
<p>My project currently has about 300 scheduled tasks. Some of these run every hour on the hour and some run once a day (at midnight). The tasks make API calls to third party API's.</p> <p>This is the current set up of my Q_CLUSTER</p> <pre><code>Q_CLUSTER = { 'name': 'DataScheduler', 'workers': 3, 'timeout': 15, 'retr...
<python><django><django-q>
2023-03-03 11:27:28
0
605
nt95
75,626,439
10,634,362
Negative float type value from python (pybind11) cannot cast correctly in C++
<p>I would like to pass a negative float value from python using pybind11 to a cpp function where that negative value will be statically cast to <code>uint32_t</code> type and do further processing. There, I am facing a very weird issue that after casting the resutl returns ZERO.</p> <ul> <li>my cpp function is like as...
<python><c++><pybind11>
2023-03-03 11:21:38
0
701
karim
75,626,435
1,944,101
Common resource file in PyQt/ PySide and resource file location
<p>When a resource file is created via Qt Designer in a Form, the python code generated by the Qt Designer includes the following import statement:</p> <pre><code>import icons_rc </code></pre> <p>This import statement is same irrespective of the qrc file location (say shared location \Modules\ZA\RES\ or ui location \Mo...
<python><pyqt><pyside><qt-designer><qt-resource>
2023-03-03 11:21:17
1
410
Ajay
75,626,220
21,295,456
Why this regex is not matching the text string?
<p>I have a python code as follows:</p> <pre><code>import re string=&quot; S/O: fathersName,other details,some other details.&quot;` fathersName=re.match(r&quot;:.*?,&quot;,string).group(0) </code></pre> <p>The regex match is supposed to match the <code> fatherName</code> part of the string, but I get a attributr erro...
<python><regex><jupyter-notebook>
2023-03-03 11:00:50
1
339
akashKP
75,626,130
4,065,451
Length of pySpark is bigger than when using pandas
<p>I am experimenting with different ways to load data into dataframes. One of the frameworks I am looking into is PySpark, but when I load a CSV with 14149 Rows and return the length of the df, it returns 14153, while pandas return 14149.</p> <pre><code> #pandas df = pd.read_csv(&quot;data_file.csv&quot;) print ...
<python><pandas><pyspark>
2023-03-03 10:52:57
1
344
Raavgo