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
74,927,662
13,219,123
Pandas groupby, resample, return NaN not 0
<p>I have the following dataframe:</p> <pre><code>data = {&quot;timestamp&quot;: [&quot;2022-12-15 22:00:00&quot;, &quot;2022-12-15 22:00:30&quot;, &quot;2022-12-15 22:00:47&quot;, &quot;2022-12-15 22:00:03&quot;, &quot;2022-12-15 22:00:30&quot;, &quot;2022-12-15 22:00:43&quot;, ...
<python><pandas>
2022-12-27 09:31:42
3
353
andKaae
74,927,506
4,953,759
how to get active REPL block in PyScript and copy whatever code written in it?
<p>I have multiple code blocks in pyscript repl which were created dynamically on button click. I want to know which code block is active. I know library adds <code>cm-activeLine</code> class when line is active but that changes when I click some other button to get the class.. I want to change order of code blocks on...
<python><react-typescript><pyscript><pyodide>
2022-12-27 09:15:55
1
708
Jamshaid Tariq
74,927,469
15,852,600
How do I improve the python function for boxcox transformation?
<p>I created a function giving a fair evaluation of lambda coefficient for a given series/list of data, however it takes lot of time when the input has a long size, is there some tips to speed it up ?</p> <p>This is my code:</p> <pre><code>from scipy.stats import norm, pearsonr def get_lambda_coef(series): x=[seri...
<python><function><normal-distribution>
2022-12-27 09:11:13
1
921
Khaled DELLAL
74,927,174
7,800,760
Networkx: select nodes only if they have a given attribute
<p>Here is a sample graph based on the code of a previous question (&quot;How can I select nodes with a given attribute value&quot;):</p> <pre><code>import networkx as nx P = nx.Graph() P.add_node(&quot;node1&quot;, at=5) P.add_node(&quot;node2&quot;, at=5) P.add_node(&quot;node3&quot;, at=6) # You can select like th...
<python><networkx>
2022-12-27 08:34:00
1
1,231
Robert Alexander
74,927,085
11,591,931
AWS Forecast on Jupyter Notebook - Credentials error
<p>I'm following the <a href="https://github.com/aws-samples/amazon-forecast-samples/blob/main/notebooks/basic/Getting_Started/Amazon_Forecast_Quick_Start_Guide.ipynb" rel="nofollow noreferrer">Quick Start Guide</a> Jupyter Notebook from AWS in order to make AWS Forecast run with Python.</p> <p>For the following cell, ...
<python><amazon-web-services><jupyter-notebook><amazon-forecast>
2022-12-27 08:23:14
1
1,327
Alex Dana
74,926,850
10,204,719
How to solve ModuleNotFoundError: No module named 'openpyxl.cell._writer'?
<p>I am trying to build an exe file for the GUI that I created using python POyqt5. After completing the process, I try to launch the UI and I get the following error:</p> <pre><code>Traceback (most recent call last): File &quot;main_3.py&quot;, line 14, in &lt;module&gt; import openpyxl File &quot;PyInstaller\...
<python><pyinstaller><openpyxl>
2022-12-27 07:52:21
2
344
sumitpal0593
74,926,735
8,124,392
The training function is throwing an "index out of range in self" error
<p>This is my code:</p> <pre><code># Extract input and target sequences from data list input_sequences = [] target_sequences = [] BATCH_SIZE = 64 data = read_csv('gpt-j-data.csv') for query, rephrases in data: input_sequences.append(query) target_sequences.append(rephrases) # Load the tokenizer tokenizer = GP...
<python><machine-learning><pytorch>
2022-12-27 07:36:25
1
3,203
mchd
74,926,714
17,582,019
Getting the HTML element using Selenium WebDriver
<p>I'm trying to get price of a product on amazon using Selenium:</p> <pre><code>from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.common.by import By url = \ &quot;https://www.amazon.in/Celevida-Kesar-Elaichi-Flavor-Metal/dp/B081WJ6536/ref=sr_1_5?crid=3NRZERQ...
<python><selenium-webdriver><css-selectors><selenium-chromedriver><webdriverwait>
2022-12-27 07:33:03
2
790
Deepak
74,926,364
13,000,378
Detect objects in a video using a yolo model
<p>Ive created a simple object detection model using yolo v3 pre-trained model that detects objects in a single image.Below is the python code for the model,</p> <pre><code>import cv2 import numpy as np # Load Yolo net = cv2.dnn.readNet(&quot;yolov3.weights&quot;, &quot;yolov3.cfg&quot;) classes = [] with open(&quot;c...
<python><opencv><machine-learning><object-detection><yolo>
2022-12-27 06:39:52
1
661
Kavishka Rajapakshe
74,926,354
3,671,056
botot3 with sqs: the address 'QueueUrl' is not valid for this endpoint
<p>I am trying to the get queue url from a SQS queue. I have read about other posts <a href="https://stackoverflow.com/questions/36666494/set-the-endpoint-for-boto3-sqs">Set the endpoint for boto3 SQS</a> and <a href="https://stackoverflow.com/questions/65663622/boto3-sqs-incorrect-url-when-not-specified-endpoint-url">...
<python><amazon-web-services><aws-lambda><boto3><amazon-sqs>
2022-12-27 06:38:11
1
412
Sri
74,926,328
219,976
Troubleshooting k8s readiness probe failure
<p>I'm trying to run my django rest framework application in k8s environment but readiness probe fails. I wonder how to get what is wrong.<br /> When I look at pod logs the app seems to be running. It has unapplied migrations, but it is ok:</p> <pre><code>C:\Users\user&gt;kubectl logs test-bbdccbc76-8cwg9 Watching for ...
<python><django><kubernetes><django-rest-framework><kubernetes-helm>
2022-12-27 06:33:13
0
6,657
StuffHappens
74,926,252
8,124,392
How to replace the tokenize() and pad_sequence() functions from transformers?
<p>I got the following imports:</p> <pre><code>import torch, csv, transformers, random import torch.nn as nn from torch.utils.data import Dataset import torch.optim as optim import pandas as pd from transformers import GPT2Tokenizer, GPT2LMHeadModel, tokenize, pad_squences </code></pre> <p>And I'm getting this error:</...
<python><huggingface-transformers><huggingface-tokenizers><gpt-2>
2022-12-27 06:19:42
1
3,203
mchd
74,925,849
3,713,236
In Pandas, what is the correct dtype for binary (dummy) variables?
<p>In Pandas, what is the correct dtype for binary (dummy) variables?</p> <p>There are obviously lots of dtypes in Pandas, some of which are: <code>float64</code>, <code>int64</code>, <code>category</code>, or simply <code>object</code>. To me, these all seem like correct dtypes for binary (dummy) variables. Which one ...
<python><pandas><binary-data><dummy-variable>
2022-12-27 05:04:05
0
9,075
Katsu
74,925,843
1,056,563
Is there any way to check if the declared type of a method parameter were consistent with the declared generic type?
<p>Consider a <code>generic type</code> baseclass:</p> <pre><code>from abc import ABC, abstractmethod class Reader(ABC, Generic[S]): @abstractmethod def get_resource(self) -&gt; S: pass </code></pre> <p>Also let's set up some dummy classes for trying this out:</p> <pre><code> class ResourceA(): def...
<python><generics>
2022-12-27 05:03:19
0
63,891
WestCoastProjects
74,925,822
2,882,380
How to shorten the command when filtering data-frame in Python
<p>In Python, a common way to filter a data frame is like this</p> <pre><code>df.loc[(df['field 1'] == 'a') &amp; (df['field 2'] == 'b'), 'field 3']... </code></pre> <p>When <code>df</code> name is long, or when there are more filter conditions (only two in the above), the above line will be long naturally. Moreover, i...
<python>
2022-12-27 04:56:58
3
1,231
LaTeXFan
74,925,536
499,363
How to make Github app connect after approval
<p>We have a GitHub app that can be installed on a repository. This works using the <a href="https://docs.github.com/en/developers/apps/building-github-apps/identifying-and-authorizing-users-for-github-apps#web-application-flow" rel="nofollow noreferrer">GitHub app authorization flow</a> that returns back an installati...
<python><authentication><github-api><github-app>
2022-12-27 03:45:11
1
4,840
Ankit
74,925,359
16,906,826
Access elements of Python tuple in Matlab
<p>I want to run and access the output of a Python function in Matlab. Please find below function. The python function returns a Python tuple as output in Matlab. Can I access elements of tuple in Matlab? I do not want to export output as .mat file and import it in Matlab, which will be computationally expensive for my...
<python><matlab><tuples><iterable-unpacking>
2022-12-27 02:53:09
1
303
Husnain
74,925,285
472,485
Django form validation
<p>Is there an easier way to write validation for each item in a form? Maybe embed them in model declaration itself?</p> <pre><code>class InfoUpdateForm(forms.ModelForm): class Meta: model = Profile fields = [ 'first_name', 'middle_name', 'la...
<python><django><django-forms>
2022-12-27 02:28:00
1
22,975
Jean
74,925,119
1,391,466
Run N processes but never reuse the same process
<p>I like to run a bunch of processes concurrently but never want to reuse an already existing process. So, basically once a process is finished I like to create a new one. But at all times the number of processes should not exceed N.</p> <p>I don't think I can use multiprocessing.Pool for this since it reuses processe...
<python><python-3.x><multiprocessing><python-multiprocessing>
2022-12-27 01:40:56
1
2,087
chhenning
74,925,074
7,796,211
How do I equally divide an iterator into N chunks?
<p>I want to divide an iterator into N equal chunks. The chunks themselves need to be iterators.</p> <p>Here's some examples of what I want to achieve:</p> <pre class="lang-py prettyprint-override"><code>iter1 = iter(range(10)) chunks = split_n(iter1, n=2) outputs iterator: [[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]] iter2 = ...
<python>
2022-12-27 01:23:39
0
418
Thegerdfather
74,925,057
3,905,546
How to redirect the user to another webpage without using JavaScript in a Jinja2 HTML template?
<p>I'm using a Jinja2 Template with FastAPI. All I want to know is how to implement a <code>redirect</code> action in Jinja2 template <strong>without using JavaScrpit</strong>?</p> <p>If the variable I set exists, I would like to force a page redirection.</p> <pre><code>{% if my_var %} // What value should I enter ...
<python><html><http-redirect><jinja2><fastapi>
2022-12-27 01:21:14
1
351
Richard
74,925,053
14,159,985
How to cache data into Pyspark before using multiple sql.write functions properly
<p>I'm new to pyspark, and I'm trying to create a Insert Update component.</p> <p>Basically I got a dataframe, &quot;df&quot;, with a column named &quot;action&quot;, where I can filter the actions between &quot;insert&quot; and &quot;update&quot;. The code looks something like that:</p> <pre><code>df_to_insert = df.fi...
<python><apache-spark><caching><pyspark>
2022-12-27 01:19:40
0
338
fernando fincatti
74,925,007
7,874,234
Python, package exists on PyPi but cant install it via pip
<p>The package <code>PyAudioWPatch</code> is shown as available on PyPi with a big old green check mark. <a href="https://pypi.org/project/PyAudioWPatch/" rel="nofollow noreferrer">https://pypi.org/project/PyAudioWPatch/</a></p> <p>However when I try to install it, I am getting the following error:</p> <pre><code>% pip...
<python><pip><pypi>
2022-12-27 01:02:38
1
800
Peter Toth
74,924,901
7,317,408
Pandas TA lib not working when using group_by
<p>I have some OHLC 5m data like so:</p> <pre><code> timestamp open high ... symbol volume_10_day last_high_volume_high 0 2022-09-09 11:20:00+00:00 1.4000 1.4000 ... AMAM NaN 0.50 1 2022-09-09 13:30:00+00:00 1.4100 1.4100 ... AMAM ...
<python><pandas><ta-lib>
2022-12-27 00:29:37
1
3,436
a7dc
74,924,677
3,321,579
Is there a way to convert a non zero padded time string into a datetime?
<p>I am looking a the <a href="https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior" rel="nofollow noreferrer">strptime</a> docs. It only specifies that it can read formatted times with zero padded strings like '01:00pm'. Is there a way I can read a time like '1:00am' using the strptime functi...
<python><datetime>
2022-12-26 23:27:43
2
1,947
Scorb
74,924,632
5,404,647
Appending to a list with multithreading ThreadPoolExecutor and map
<p>I have the following code</p> <pre><code>import random import csv from concurrent.futures import ThreadPoolExecutor from concurrent.futures import ProcessPoolExecutor import pandas as pd def generate_username(id, job_location): number = &quot;{:03d}&quot;.format(random.randrange(1, 999)) return &quot;&quot;...
<python><multithreading><python-multithreading>
2022-12-26 23:16:56
1
622
Norhther
74,924,400
651,174
Case-insensitive section of a pattern
<p>Does Python have something like vim where it allows inlining a portion of the pattern that may have flags, for example being case-insensitive? Here would be an example:</p> <pre><code>re.search(r'he\cllo', string) </code></pre> <p><code>\c</code> being the case-insensitive inline indicator. Or is it an all or nothin...
<python><regex>
2022-12-26 22:25:22
1
112,064
David542
74,924,277
17,945,841
How to set seed in python
<p>I want to draw the same exact samples from the data, two times, in order to run a different analysis each time. To do so I did</p> <pre><code>random.seed(10) data.sample(n = 1000) </code></pre> <p>But this is not working, I get different samples each time. I searched for a built-in parameter in the <code>sample()</c...
<python><random-seed>
2022-12-26 22:03:09
0
1,352
Programming Noob
74,923,932
10,779,391
stable_baselines3 best observation space for custom environment
<p>I'm newbie in RL and I'm learning stable_baselines3. I've create simple 2d game, where we want't to catch as many as possible falling apples. If we don't catch apple, apple disappears and we loose a point, else we gain 1 point. We can move only left or right. I thought that AI will learn faster when I give him raw d...
<python><artificial-intelligence><reinforcement-learning><openai-gym><stable-baselines>
2022-12-26 20:57:31
0
313
Rozrewolwerowany rewolwer
74,923,866
14,104,321
How to make a class return a value?
<p>Consider the following example:</p> <pre><code>import numpy as np class Vector: def __init__(self, x, y, z): self._vector = np.array([x, y, z]) self._magnitude = np.linalg.norm(self._vector) self._direction = self._vector/self._magnitude @property def magnitude(self) -&gt; float...
<python><class>
2022-12-26 20:46:30
2
582
mauro
74,923,841
881,603
asyncio try to acquire a lock without waiting on it
<p>I'm converting some threaded code to asyncio.</p> <p>In the threaded code, I'm calling threading.RLock.acquire( blocking = False, timeout = 0 )</p> <p>There doesn't seem to be a way to try to aquire an asyncio.Lock without also waiting on it. Is there a way to do this and if so, what am I missing?</p> <p>In case it ...
<python><multithreading><locking><python-asyncio>
2022-12-26 20:42:26
2
1,492
royce3
74,923,838
8,372,455
pydantic models to reference another class
<p>Is it possible on a pydantic model to reference another class? For example below in the <code>ReadRequestModel</code> in <code>point_type</code> I am trying to figure out if its possible reference that only these &quot;types of points&quot; in a <em><strong>string</strong></em> format can be chosen:</p> <pre><code>#...
<python><pydantic>
2022-12-26 20:42:06
2
3,564
bbartling
74,923,647
7,895,542
Automatic GUI for python script with command line arguments?
<p>Is there any software that auto generates GUI wrappers around python scripts?</p> <p>My specific scenario is that i wrote a simple script for my father in law to bulk download some stuff from a given url.</p> <p>Normally you just run the script via</p> <p><code>python my_script.py --url https://test.com --dir C:\Dow...
<python><user-interface><exe>
2022-12-26 20:05:39
2
360
J.N.
74,923,479
1,497,139
How to get syncify / asyncify syntactic sugar for python
<p>It seems there is a general need in some use cases that async and non async code according to <a href="https://peps.python.org/pep-0492/" rel="nofollow noreferrer">https://peps.python.org/pep-0492/</a> in python should be able to work together in a straightforward way.</p> <p>It should be possible:</p> <ol> <li>To c...
<python><asynchronous><async-await>
2022-12-26 19:37:50
0
15,707
Wolfgang Fahl
74,923,420
6,147,428
VS Code - How to add folders to the search path in a Python project?
<p>I've recently switched from Spyder to VS Code to code my Python projects. Spyder is great for me because it uses IPython, i.e., it is based on a REPL (interactive environment), but it still lacks some useful features as code refactoring. In turn, VS Code is superb because it provides a more sophisticated editor, but...
<python><visual-studio-code><anaconda><pythonpath>
2022-12-26 19:28:01
1
613
Humberto Fioravante Ferro
74,923,377
7,788,402
Python library import fails when executed with 'pOpen' sub process from another Python script
<p>I have a Python service that needs to run another Python script (<em>in a completely different folder path</em>) using &quot;pOpen&quot;. That file needs to import multiple classes in different folders. 'pOpen' fails to run the script with an error message that import fails as follows :</p> <pre><code>Traceback (mos...
<python><import><popen>
2022-12-26 19:19:43
0
2,301
PCG
74,923,308
1,842,491
How can I keep poetry and commitizen versions synced?
<p>I have a <code>pyproject.toml</code> with</p> <pre><code>[tool.poetry] name = &quot;my-project&quot; version = &quot;0.1.0&quot; [tool.commitizen] name = &quot;cz_conventional_commits&quot; version = &quot;0.1.0&quot; </code></pre> <p>I add a new feature and commit with commit message</p> <pre><code>feat: add param...
<python><python-poetry><commitizen>
2022-12-26 19:09:05
1
1,509
Shay
74,923,172
2,365,595
Spotify /authorize endpoint
<p>I would like to know which is the /authorize endpoint, after some search I see that it's <a href="https://accounts.spotify.com/authorize?client_ID" rel="nofollow noreferrer">https://accounts.spotify.com/authorize?client_ID</a>, but why? where is the documentation about it? I don't see any endpoints list and the guid...
<python><web-applications><spotify><webapi><spotify-app>
2022-12-26 18:50:35
0
575
Aidoru
74,923,140
15,649,230
Matplotlib memory leak using FigureCanvasTkAgg
<p>is there any way to clear matplotlib memory usage from a tkinter application, the following code is taken from <a href="https://matplotlib.org/stable/gallery/user_interfaces/embedding_in_tk_sgskip.html" rel="nofollow noreferrer">Embedding in Tk</a>, i just put it in a loop to make the memory leak more clear.</p> <pr...
<python><matplotlib><tkinter><memory-leaks>
2022-12-26 18:46:22
1
23,158
Ahmed AEK
74,923,076
4,898,127
Check constraint noninfringement in PuLP
<p>I have just created a model in PuLP, though its result seems to have violated its constraints. Is there a quick way to check the value of each constraint?</p>
<python><linear-programming><pulp>
2022-12-26 18:36:12
0
351
Incognito
74,923,024
15,875,806
proper way to communicate between more than two processes in pyqt5 python
<p>I currently have two processes, one is my pyqt5 MainWindow (parent process) and a child process. I mainly use Pipe to communicate between the two. As per my research, a Pipe can have only two end-points which in my case, it has already been given to the two end-points above. But I now am in need of a temporary third...
<python><pyqt5><multiprocessing>
2022-12-26 18:29:21
0
305
hashy
74,922,991
1,907,765
Can you specify a bidirectional edge in a NetworkX digraph?
<p>I'd like to be able to draw a NetworkX graph connecting characters from the movie &quot;Love, Actually&quot; (because it's that time of the year in this country), and specifying how each character &quot;relates&quot; to the other in the story.</p> <p>Certain relationships between characters are unidirectional - e.g....
<python><networkx><digraphs><pyvis>
2022-12-26 18:24:17
1
2,527
Lou
74,922,987
3,247,006
What is "django_admin_log" used for in Django Admin?
<p>When adding data (I use PostgreSQL):</p> <p><a href="https://i.sstatic.net/uBW7q.png" rel="noreferrer"><img src="https://i.sstatic.net/uBW7q.png" alt="enter image description here" /></a></p> <p><strong>&quot;django_admin_log&quot;</strong> is inserted as shown below. *These below are <strong>the PostgreSQL query lo...
<python><python-3.x><django><logging><django-admin>
2022-12-26 18:24:06
1
42,516
Super Kai - Kazuya Ito
74,922,979
17,658,327
Defined attributes that are seemingly not used at all for instance objects of some loss classes
<p>I will try to explain my question using an example. Consider the <a href="https://github.com/keras-team/keras/blob/e6784e4302c7b8cd116b74a784f4b78d60e83c26/keras/losses.py#L576" rel="nofollow noreferrer">definition of the BinaryCrossentropy loss class</a> as shown in the following.</p> <pre><code>@keras_export(&quot...
<python><tensorflow>
2022-12-26 18:22:48
0
626
learner
74,922,913
17,696,880
Why does this capture limit set with regex fail by modifying substrings that it shouldn't?
<pre class="lang-py prettyprint-override"><code>import re def date_to_internal_stored_format(input_text, identify_only_4_digit_years = False, limit_numbers_immediately_after_date = True): #grupo de captura para fechas en donde el año tiene si o si 4 digitos if (identify_only_4_digit_years == True): i...
<python><python-3.x><regex><replace><regex-group>
2022-12-26 18:13:04
0
875
Matt095
74,922,897
14,584,978
Apply str.contains for different in strings on pandas dataframe or groupby object in pandas or dask
<p>I would like to preform str.contains() elementwise with some format like:</p> <pre><code>df['superstring'].str.contains(df['substring']) </code></pre>
<python><pandas><string><dataframe><dask>
2022-12-26 18:09:54
1
374
Isaacnfairplay
74,922,780
18,059,131
How to get list of amplitude values from a wave file in python
<p>How could I get a list of the amplitudes of each frame in a wave file using python (in the dB unit)?</p> <p>So far I have this:</p> <pre><code>samplerate, data = wavfile.read(patternPath) print(max((data[:, 1]).tolist()))) </code></pre> <p>but that prints out <code>0.7856917381286621</code>, which doesn't make much ...
<python><audio>
2022-12-26 17:53:57
2
318
prodohsamuel
74,922,758
580,937
SnowparkFetchDataException: (1406): Failed to fetch a Pandas Dataframe. The error is: Found non-unique column index
<p>While running some code like this:</p> <pre class="lang-py prettyprint-override"><code> session = ... return session.table([DB,SCHEMA, MANUAL_METRICS_BY_SIZE]).select(&quot;TECHNOLOGY&quot;,&quot;OBJECTTYPE&quot;,&quot;OBJECTTYPE&quot;,&quot;SIZE&quot;,&quot;EFFORT&quot;).to_pandas() </code></pre> <p>I got this...
<python><pandas><snowflake-cloud-data-platform>
2022-12-26 17:50:08
1
2,758
orellabac
74,922,725
3,074,348
Can't add "list:xxxxxxxxxxx" StreamRule to StreamingClient of Twitter API v2
<p>I can't add &quot;list:XXXXXXXXXX&quot; to my rules (I can add other rules though and they work). What I'm missing?</p> <pre><code>import tweepy class TweetPrinter(tweepy.StreamingClient): def on_tweet(self, tweet): print(tweet) printer = TweetPrinter(bearer_token) printer.add_rules(tweepy.StreamRule...
<python><tweepy><twitterapi-python><twitter-api-v2><sttwitterapi>
2022-12-26 17:45:35
0
342
arthur
74,922,611
6,594,089
Stripe payment failing after trial period
<p>I'm attempting to create a monthly subscription with free 7 day trial, but after the trial period the payment fails.</p> <p>EDIT: It appears to fail because the customer has no default payment method, so despite the payment method being attached to customer, it is not set to default. I can not figure out how to set ...
<javascript><python><stripe-payments><subscription>
2022-12-26 17:31:09
0
459
LBJ33
74,922,542
4,645,982
Update record in DynamoDB for reserved Keyword
<p>Following data mapped in DynamoDB for record_id 7, I want to update customer with new value</p> <pre><code>&quot;customer&quot;: { &quot;value&quot;: &quot;id2&quot;, &quot;label&quot;: &quot;Customer2&quot; } </code></pre> <p>However, dyanamoDB does not allow to update because of &q...
<python><python-3.x><amazon-web-services><amazon-dynamodb><boto3>
2022-12-26 17:21:37
2
2,676
Neelabh Singh
74,922,497
1,245,659
post action drops part of the url in django app
<p>I'm building my first ecommerce app, while attempting to gain more skills in Django. I have a form problem, where I am either adding a product, or editing one, using the same Template. My problem is where the action call drops part of the url when submitting POST back to the server ( right now, it's just the <code...
<python><django><django-views><django-forms>
2022-12-26 17:14:38
3
305
arcee123
74,922,314
2,216,953
yield from vs yield in for-loop
<p>My understanding of <code>yield from</code> is that it is similar to <code>yield</code>ing every item from an iterable. Yet, I observe the different behavior in the following example.</p> <p>I have <code>Class1</code></p> <pre><code>class Class1: def __init__(self, gen): self.gen = gen def _...
<python><generator><yield><python-internals><yield-from>
2022-12-26 16:48:14
2
628
erzya
74,922,197
7,333,766
Can I safely remove all u-strings from a project that will only use python 3?
<p>I work on a project that includes many <code>u&quot;string&quot;</code> in its codebase,</p> <p>I want to know if I can safely remove the <code>u</code> in front of all those strings knowing that the project will only use Python 3 from now on (it used to use both python 2 and 3)</p> <p>I have only <a href="https://b...
<python><python-3.x>
2022-12-26 16:30:52
3
2,215
Eli O.
74,922,075
20,054,635
How to specify wildcard filenames for .Zip type files in Python Variables
<p>My requirement is</p> <p>I'm calling a function to extract files/folders from a .Zip file</p> <pre><code>files_extract_with_structure(file_source, file_dest) </code></pre> <p><code>file_source</code> and <code>file_dest</code> are the variables I'm passing to the above function and the value of the <code>file_source...
<python><pyspark><azure-databricks>
2022-12-26 16:13:36
1
369
Anonymous
74,921,877
13,707,795
Url with umlaut (non ascii), dashes and brackets is not parseable by requests
<p>I am trying to get the HTML content of a page with requests, but it results in <code>UnicodeDecodeError</code>. The reproducible code:</p> <pre class="lang-py prettyprint-override"><code>import requests import urllib url = &quot;https://www.unique.nl/vacature/coördinator-facilitair-(v2037635)&quot; </code></pre> <p...
<python><web-scraping><unicode><python-requests><urllib>
2022-12-26 15:47:36
1
975
Zal
74,921,871
12,242,085
When import package to use it in Jupyter Notebook with function saved in .py file in Python?
<p>I have in Jupyter Lab functions.py file with function which I wrote which use package statsmodels as sm like below:</p> <pre><code>def my_fk(): x = sm.Logit() ... </code></pre> <p>Then I import function from my file in Jupyter Notebook like below and I import needed package statsmodels:</p> <pre><code>import fun...
<python><function><import><python-import>
2022-12-26 15:47:12
1
2,350
dingaro
74,921,717
4,015,352
Keeping the dimensions when using torch.diff on a tensor in pytorch
<p>Suppose the following code:</p> <pre><code>a=torch.rand(size=(3,3,3), dtype=torch.float32) a_diff=torch.diff(a, n=1, dim= 1, prepend=None, append=None).shape print(a_diff) torch.Size([3, 2, 3]) </code></pre> <p>I would like to keep the dimensions like the original a with (3,3,3). How can I append 0 to the beginni...
<python><pytorch><diff><tensor>
2022-12-26 15:27:38
1
391
freak11
74,921,568
2,636,579
Script doesn't execute when wrapped inside of a function
<p>When I execute the script below with <code>python3 ocr-test.py</code>, it runs correctly:</p> <pre class="lang-py prettyprint-override"><code>from PIL import Image import pytesseract # If you don't have tesseract executable in your PATH, include the following: pytesseract.pytesseract.tesseract_cmd = r'/opt/homebrew/...
<python><tesseract>
2022-12-26 15:09:17
2
1,034
reallymemorable
74,921,547
9,244,323
How to parse a date column as datetimes, not objects in Pandas?
<p>I'd like to create DataFrame from a csv with one datetime-typed column.</p> <p>Follow <a href="https://towardsdatascience.com/4-tricks-you-should-know-to-parse-date-columns-with-pandas-read-csv-27355bb2ad0e" rel="nofollow noreferrer">the article</a>, the code should create needed DateFrame:</p> <pre><code>df = pd.re...
<python><pandas>
2022-12-26 15:06:59
1
316
Sergey Kazantsev
74,921,335
13,118,338
How to pass argument to docker-compose
<pre><code>import argparse parser = argparse.ArgumentParser() parser.add_argument( '--strat', type=str, ) args = parser.parse_args() strat = args.strat </code></pre> <p>I would like to right my docker-compose.yml file such as I would just pass my argument from there. I did</p> <pre><code>version: &quot;3.3&q...
<python><python-3.x><docker><docker-compose><dockerfile>
2022-12-26 14:39:33
2
481
Nicolas Rey
74,921,232
12,863,331
Download a file that's linked to a button on a website
<p>I'm looking for a way to get files such as the one in <a href="https://biobank.ndph.ox.ac.uk/showcase/coding.cgi?id=9" rel="nofollow noreferrer">this link</a>, which can be downloaded by clicking a &quot;download&quot; button. I couldn't find a way despite reading many posts that seemed to be relevant.</p> <p>The co...
<python><beautifulsoup><python-requests>
2022-12-26 14:25:50
1
304
random
74,921,183
498,504
numpy.float64 object is not callable error on concrete dataset
<p>I'm writing a simple Regression Model in Keras for predicting Strength.</p> <p>This is my code:</p> <pre><code>epochs_number = 50 mean_squared_errors = [] number_of_reapeat = 50 for i in range(0, number_of_reapeat): print(i) X_train, X_test, y_train, y_test = train_test_split(predictors, target, test_size=0...
<python><keras>
2022-12-26 14:18:18
1
6,614
Ahmad Badpey
74,921,132
17,176,270
How to populate DB from fixture before test
<p>I have a FastAPI app and I need to populate a testing DB with some data needed for testing using pyTest.</p> <p>This is my code for testing DB in conftest.py:</p> <pre><code>SQLALCHEMY_DATABASE_URL = &quot;sqlite:///./test.db&quot; engine = create_engine( SQLALCHEMY_DATABASE_URL, connect_args={&quot;check_same_...
<python><pytest><fastapi><fixtures>
2022-12-26 14:13:03
2
780
Vitalii Mytenko
74,921,129
13,576,164
Web Scraping Table from 'Dune.com' with Python3 and bs4
<p>I am trying to web scrape table data from Dune.com (<a href="https://dune.com/queries/1144723" rel="nofollow noreferrer">https://dune.com/queries/1144723</a>). When I 'inspect' the web page, I am able to clearly see the <code>&lt;table&gt;&lt;/table&gt;</code> element, but when I run the following code I am returned...
<python><html><beautifulsoup><python-requests>
2022-12-26 14:12:40
1
338
spal
74,921,104
34,935
How to properly specify argument type accepting dictionary values?
<p>Here are a couple of functions:</p> <pre class="lang-py prettyprint-override"><code>from typing import Sequence def avg(vals: Sequence[float]): return sum(val for val in vals) / len(vals) def foo(): the_dict = {'a': 1., 'b': 2.} return avg(the_dict.values()) </code></pre> <p>PyCharm 2022.3 warns about ...
<python><pycharm><python-typing>
2022-12-26 14:09:51
2
21,683
dfrankow
74,920,923
5,161,197
Python2 vs Python3 : Exception variable not defined
<p>I wrote this small snippet in python2 (2.7.18) to catch the exception in a variable and it works</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; ex = None &gt;&gt;&gt; try: ... raise Exception(&quot;test&quot;) ... except Exception as ex: ... print(ex) ... test &gt;&gt;&gt; ex Exception('test',)...
<python><python-3.x><python-2.7><exception>
2022-12-26 13:47:01
1
363
likecs
74,920,881
607,846
Clipping a datatime series along the y-axis
<p>I have a list of tuples, where each tuple is a datetime and float. I wish to clip the float values so that they are all above a threshold value. For example if I have:</p> <pre><code>a = [ (datetime.datetime(2021, 11, 1, 0, 0, tzinfo=tzutc()), 100), (datetime.datetime(2021, 11, 1, 1, 0, tzinfo=tzutc()), 9.0...
<python><pandas><numpy><scipy>
2022-12-26 13:41:49
1
13,283
Baz
74,920,856
4,645,982
Invalid UpdateExpression: Attribute name is a reserved keyword; reserved keyword: value
<p>I am trying to update the record in dynamodb using following dictData, I have <strong>RESERVER_KEYWORDS</strong> array which has reserved keyword in dynamoDB. Please check code segment which I am trying to replace with the reserve keyword. Main issue that <code>customer.value</code> and <code>action.value</code> typ...
<python><python-3.x><amazon-web-services><amazon-dynamodb><boto3>
2022-12-26 13:38:59
1
2,676
Neelabh Singh
74,920,765
15,144,596
How to know which line in a python library raised an exception?
<p>I have a program which runs fine but when I use uvicorn, my program raises an <code>asyncio.exceptions.CancelledError</code> when I call <code>asyncio.gather(*tasks)</code>. The problem is I don't know which line in the library (uvicorn or some other library) is rasing that exception.</p> <p>How can I know which lin...
<python><python-3.x><python-asyncio><uvicorn>
2022-12-26 13:24:41
0
549
Shakir
74,920,750
19,838,445
Difference between Callable and FunctionType
<p>I am trying to properly type hint my code and encountered both <a href="https://docs.python.org/3/library/typing.html#typing.Callable" rel="nofollow noreferrer">Callable</a> and <a href="https://docs.python.org/3/library/types.html?highlight=functiontype#types.FunctionType" rel="nofollow noreferrer">FunctionType</a>...
<python><python-3.x><python-typing><callable-object>
2022-12-26 13:22:43
1
720
GopherM
74,920,749
4,822,772
Pandas cumsum by chunk
<p>In dataset, I have two columns</p> <ul> <li>N: ID number to identify each row</li> <li>Indicator: it is either 0 or 1.</li> </ul> <p>What I would like to obtain:</p> <ul> <li>Cumsum: calculate the cumulative cum of the column Indicator, but only to successive values of 1.</li> <li>Total: then for each chunk of non-n...
<python><pandas><cumsum>
2022-12-26 13:22:39
2
1,718
John Smith
74,920,637
19,826,650
Insert from python to mysql
<p>How to insert data from code below? I have a code below</p> <pre><code>latitude1 = -6.208470935786019 longitude1 = 106.81796891087399 new_data = [[latitude1, longitude1]] preds = model.predict(new_data) preds arr = [latitude1,longitude1] arrcon = np.concatenate((arr,preds)) print(arrcon) #[-6.208470935786019 106.81...
<python><mysql>
2022-12-26 13:08:55
1
377
Jessen Jie
74,920,558
9,385,568
Lengths must match to compare
<p>I'm trying to map values of one dataframe to another. My dataframes are as follows:</p> <pre><code>df2.head() ext_id credit_debit_indicator index_name business_date trench_tag trench_tag_l2 0 4SL19N2YQLCU62TY C ib-prodfulltext-t24-transhist-202208 2022-07-31 XXX9999999 XXX99 1 1EXHR74Y2YXBN4A...
<python><pandas><numpy>
2022-12-26 13:00:02
1
873
Stanislav Jirak
74,920,470
7,806,269
PyQt6 program crashes when using two TreeView delegates
<p>I've prepared a minimal reproducible example of this problem. There are two <code>TreeView</code> delegates: one for checkboxes and one for progress bars. If I add any one of these delegates, but not the other one, the program doesn't crash. But if I add both, it crashes (upon trying to show the rows and the delegat...
<python><segmentation-fault><crash><delegates><pyqt6>
2022-12-26 12:51:09
0
862
sequence
74,920,459
4,033,876
How to retain datetime column in pandas grouper and group by?
<p>I have a pandas dataframe that has a structure as shown in this question <a href="https://stackoverflow.com/questions/74412513/parsing-json-with-number-as-key-usng-pandas">Parsing JSON with number as key usng pandas</a>-</p> <pre><code> Date Time InverterVoltage Invertercurrent 20...
<python><pandas><python-3.8>
2022-12-26 12:50:20
1
1,194
gansub
74,920,369
12,725,674
Replace substring with exception
<p>I want to replace certain characters in file name of pdf files. My code so far:</p> <pre><code>for file in files: file_ed = file replace = [&quot;,&quot;,&quot;-&quot;, &quot;The &quot;,&quot; &quot;] for item in replace: file_ed = file_ed.replace(item,&quot;&quot;) </code></pre> <p>In addition I...
<python><string><replace>
2022-12-26 12:37:36
5
367
xxgaryxx
74,920,349
8,794,019
Gateway Time-out with StreamingResponse and custom Middleware fastapi
<p>I wrote a simple custom Middleware as below:</p> <pre><code>class LoggingMiddleware(BaseHTTPMiddleware): def __init__(self, app): super().__init__(app) async def dispatch(self, request, call_next): user_token = request.headers.get(&quot;x-token&quot;) req_id = time_ns() try: ...
<python><fastapi>
2022-12-26 12:35:44
0
705
Emad Helmi
74,919,802
12,544,460
Parse a Text file to a table using Python or SQL
<p>I have a text file like this</p> <pre><code>{u'Product_id': u'1234567', u'Product_name': u'Apple', u'Product_code': u'2.4.14'} {u'Product_id': u'1234123', u'Product_name': u'Orange', u'Product_code': u'2.4.20'} </code></pre> <p>I have searched it on google but not know yet what kind of string is this, it's not json ...
<python><sql><parsing>
2022-12-26 11:20:50
1
362
Tom Tom
74,919,353
13,038,144
Setting same frame width in matplotlib subplots with external colorbar element
<p>I want to produce two subplots that contain a lot of curves, so I defined a function that produces a colorbar, to avoid having a super long legend that is not readable. This is the function to create the colorbar:</p> <pre class="lang-py prettyprint-override"><code>import matplotlib as mpl, matplotlib.pyplot as plt ...
<python><matplotlib><plot>
2022-12-26 10:21:03
2
458
gioarma
74,919,257
12,085,129
Convert a CRON expression from local TZ to UTC in Python
<p>I'm building an application in which some tasks are scheduled by using CRON like jobs (with <a href="https://docs.celeryq.dev/en/stable/" rel="nofollow noreferrer">celery</a>). Through an interface, jobs are saved as celery jobs with <a href="https://django-celery-beat.readthedocs.io/en/latest/" rel="nofollow norefe...
<python><cron><django-celery-beat>
2022-12-26 10:08:21
1
1,259
lbris
74,919,028
19,716,381
Center the coordinate system of python pillow
<p>I would like to create images using mathematical equations / functions and python pillow. For example,</p> <p>pseudo code:</p> <pre><code>iterate through pixels if x^2 + y^2 &lt;= 25, pixel_color = green. Draws a solid circle of radius 5 </code></pre> <p>I am aware python pillow has inbuilt functions to draw circles...
<python><python-imaging-library>
2022-12-26 09:38:13
0
484
berinaniesh
74,918,706
8,437,546
Efficient way to perform rolling operations on tensor with Pytorch
<p>I would like to write a function to perform some forward rolling operations over a tensor slice with PyTorch. Is there a way to do efficiently this?</p> <p>For example, the RollingSum function should take a tensor and add up all values across the specified axis within the rolling slice/window.</p> <pre><code>X = np....
<python><pytorch><rolling-computation>
2022-12-26 08:54:42
1
1,962
ProteinGuy
74,918,633
1,115,237
AWS Glue - Getting partition information into a dynamic frame column
<p>I am writing a Glue ETL job that takes an array of paths as an argument to create a DynamicFrame. The job will read data from the specified paths and create a DynamicFrame for further processing.</p> <p>Having the following s3 folder structure:</p> <pre><code>s3://my_bucket/root/dt=2022-24-12/file.parquet s3://my_bu...
<python><amazon-s3><pyspark><aws-glue><partition>
2022-12-26 08:46:05
0
8,953
Shlomi Schwartz
74,917,986
13,000,378
Getting curl-L invalid syntax when running on jupyter notebook
<p>I'm trying to create a object detection module using YOLO V5 following this tutorial <a href="https://www.youtube.com/watch?v=Ciy1J97dbY0&amp;t=352s" rel="nofollow noreferrer">YT Link</a></p> <p>In this they have used google colab but I want to create it on jupyter note book. <a href="https://i.sstatic.net/skK8L.png...
<python><python-3.x><jupyter-notebook><google-colaboratory><yolo>
2022-12-26 07:08:41
1
661
Kavishka Rajapakshe
74,917,863
13,738,079
FastAPI - Unable to get auth token from middleware's Request object
<p>Following <a href="https://www.starlette.io/requests/" rel="nofollow noreferrer">Starlette documentation</a> (FastAPI uses Starlette for middlewares), <code>response.headers[&quot;Authorization&quot;]</code> should allow me to get the bearer token, but I get a <code>KeyError</code> saying no such attribute exists.</...
<python><rest><authentication><fastapi>
2022-12-26 06:49:32
1
1,170
Jpark9061
74,917,836
17,696,880
Why does this replace function fail inside this lambda function but not outside it?
<pre class="lang-py prettyprint-override"><code>import re input_text = &quot;el dia 2022-12-23 o sino el dia 2022-09-23 10000-08-23&quot; #example date_capture_pattern = r&quot;([12]\d*-[01]\d-[0-3]\d)(\D*?)&quot; #input_text = re.sub(date_capture_pattern , lambda m: print(repr(m[1])) , input_text) input_text = re....
<python><python-3.x><regex><lambda><replace>
2022-12-26 06:44:29
3
875
Matt095
74,917,772
7,339,624
How to make an empty tensor in Pytorch?
<p>In python, we can make an empty list easily by doing <code>a = []</code>. I want to do a similar thing but with Pytorch tensors.</p> <p>If you want to know why I need that, I want to get all of the data inside a given dataloader (to create another customer dataloader). Having an empty tensor can help me gather all o...
<python><pytorch><tensor>
2022-12-26 06:30:47
2
4,337
Peyman
74,917,608
3,878,377
How to know what commands you can write in DockerFile?
<p>I have been looking at many DockerFile in the docker hub( This is one example: <a href="https://hub.docker.com/layers/library/python/latest/images/sha256-dcd0251df5efeb39af10af998b45d21436d85e2b9facf12a8800e34ad3d84c91?context=explore" rel="nofollow noreferrer">https://hub.docker.com/layers/library/python/latest/ima...
<python><docker><dockerfile>
2022-12-26 05:53:36
1
1,013
user59419
74,917,596
661,716
dataframe fill in a value where there is no data
<p>I have a data like below.</p> <p>I need to fill in the 'value' column where where there is no data for each month/name.</p> <p>The month values are the unique values of df['month']</p> <pre><code>import pandas as pd a = [['2020-01',1,'a'], ['2020-02',2,'a']] b = [['2020-01',1,'b'], ['2020-03',4,'b']] a.extend(b) d...
<python><pandas><dataframe>
2022-12-26 05:51:05
2
1,226
tompal18
74,917,588
12,101,201
Error code 215 when authenticating Twitter API 2.0 in Python using Authlib and OAuth2
<p>I've seen lots of related questions to this one, but none of the answers have helped me.</p> <p>First, I went to the <a href="https://developer.twitter.com/en/portal/" rel="nofollow noreferrer">Twitter Developer Portal</a> and set up my OAuth2.0 Client ID and Secret:</p> <p><a href="https://i.sstatic.net/VYe13.png" ...
<python><twitter><oauth-2.0><python-requests><authlib>
2022-12-26 05:49:44
1
1,485
Ben Myers
74,917,543
3,878,377
Obtain version of packages installed from docker image/container
<p>Assume I pull a docker image using <code>docker pull image1</code>. The image is for a python application and its dependencies. I can run a container from this image, and everything works well. I am interested in finding the list of all installed packages and their dependencies from the running container or pulled i...
<python><docker><pip><package><dockerfile>
2022-12-26 05:41:20
0
1,013
user59419
74,917,459
1,843,011
How to add two derived fields in a single statement?
<p>I have a dataframe, and based on certain condition, I need to add two calculated fields to the dataframe. I can do this in two statements, each one at a time. Is there a way to add more than one fields at the same time? Is there any performance difference in these two approaches?</p> <pre><code>import pandas as pd ...
<python><pandas><dataframe><numpy>
2022-12-26 05:21:40
2
3,582
Remis Haroon - رامز
74,917,455
11,332,693
Remove space between string after comma in python dataframe column
<p>df1</p> <pre><code>ID Col 1 new york, london school of economics, america 2 california &amp; washington, harvard university, america </code></pre> <p>Expected output is :</p> <p>df1</p> <pre><code>ID Col 1 new york,london school of economics,america 2 ...
<python><pandas><string><text>
2022-12-26 05:21:08
4
417
AB14
74,917,247
13,097,857
Can someone explain why this function returns None?
<p>I've been trying to figure out why this function is returning None every time I run it, I would appreciate a lot if someone could explain my why.</p> <pre><code>x = set([1,2,3]) def inserta(multiconjunto, elemento): a = multiconjunto.add(elemento) return a mc1 = inserta(x, 2) print(mc1) </code></pre...
<python><arrays><list><function><set>
2022-12-26 04:22:59
1
302
Sebastian Nin
74,917,129
10,829,044
Pandas - compute and pivot to get revenue from previous two years
<p>I have a dataframe like as below</p> <pre><code>df = pd.DataFrame( {'stud_id' : [101, 101, 101, 101, 101, 102, 102, 102], 'sub_code' : ['CSE01', 'CSE01', 'CSE01', 'CSE01', 'CSE02', 'CSE02', 'CSE02', 'CSE02'], 'ques_date' : ['10/11/2022', '06/06/...
<python><pandas><dataframe><group-by><pivot-table>
2022-12-26 03:44:11
1
7,793
The Great
74,917,051
3,250,829
Tensorflow Error on Macbook M1 Pro - NotFoundError: Graph execution error
<p>I've installed Tensorflow on a Macbook Pro M1 Max Pro by first using Anaconda to install the dependencies:</p> <pre><code>conda install -c apple tensorflow-deps </code></pre> <p>Then after, I install the Tensorflow distribution that is specific for the M1 architecture and additionally a toolkit that works with the M...
<python><macos><tensorflow><deep-learning><metal>
2022-12-26 03:15:11
1
104,825
rayryeng
74,917,035
817,659
Don't truncate columns output
<p>I am setting the <code>options</code> like this</p> <pre><code>pd.options.display.max_columns = None </code></pre> <p>When I try to print the <code>DataFrame</code>, I get truncated columns:</p> <pre><code>&lt;class 'pandas.core.frame.DataFrame'&gt; Index(['contractSymbol', 'strike', 'currency', 'lastPrice', 'change...
<python><pandas>
2022-12-26 03:11:34
3
7,836
Ivan
74,916,881
11,860,883
slicing assignment numpy does not work as expected
<pre><code>import numpy as np array = np.random.uniform(0.0, 1.0, (100, 2)) array[(array[:, 1:2] &lt; 3.0).flatten()][:][1:2] = 4.0 </code></pre> <p>I want to change the second value of the rows who is less than 3.0 to 4.0, but the above code does not work. I tried to search a little bit, it appears that fancy slicing ...
<python><numpy>
2022-12-26 02:14:18
1
361
Adam
74,916,803
5,945,518
Update programmatically "value" and "delta" attributes of Indicators using Plotly gauge charts
<p>From the examples illustrated in <a href="https://plotly.com/python/indicator/" rel="nofollow noreferrer"><strong>How to make gauge charts in Python with Plotly</strong></a>, I wonder whether it is possible to programmatically update the fields, hereinafter:</p> <ul> <li><code>value</code></li> <li><code>delta</code...
<python><plotly-dash><plotly>
2022-12-26 01:52:01
1
685
dark.vador