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
76,167,810
13,039,962
Get the dates of the start and end of consecutive values with a condition
<p>I have this df:</p> <pre><code> DATE CODE QUARTER PP 0 1964-01-01 100007 1964Q1 NaN 1 1964-01-02 100007 1964Q1 NaN 2 1964-01-03 100007 1964Q1 NaN 3 1964-01-04 100007 1964Q1 NaN 4 1964-01-05 100007 1964Q1 NaN ... ... ...
<python><pandas>
2023-05-03 20:40:21
1
523
Javier
76,167,779
12,369,569
SyntaxError in python script that creates a qiime2 manifest file
<p>My script creates a manifest document that contains the filepaths of my fastq data for upload into qiime2. The input is a text file of the sample names and a directory that contains the fastq files. I then run the shell file using <code>python ./manifest_single.py --input-dir seqs</code>. Input text file example:</p...
<python><manifest><fastq><qiime>
2023-05-03 20:32:50
0
474
Geomicro
76,167,739
18,572,509
Make Flask pass "self" arguments to server functions?
<p>I have Flask server wrapped in a class that looks something like this:</p> <pre class="lang-py prettyprint-override"><code>from flask import Flask, Response, render_template, request class Server: def __init__(self, host, port): # Initialize Flask: self.app = Flask(__name__) self.host =...
<python><python-3.x><flask>
2023-05-03 20:26:35
1
765
TheTridentGuy supports Ukraine
76,167,560
5,731,101
Colcon build fails following docs without clear error or traceback
<p>I'm taking my first baby-steps with ROS2 and following the beginner tutorials in the docs to familiarise myself with the workflows.</p> <p>On the section about paramaters it shows you how to use launch-files. <a href="https://docs.ros.org/en/humble/Tutorials/Beginner-Client-Libraries/Using-Parameters-In-A-Class-Pyth...
<python><ros2><colcon>
2023-05-03 19:55:51
1
2,971
S.D.
76,167,484
5,452,008
How to update table in gradio by uploading a csv file?
<p>I would like to upload a CSV file and update a table with the content and finally create a plot with the content, but I am stuck connecting all the components. I also could not find any good documentation of this.</p> <pre><code>import gradio as gr default_csv = &quot;Phase,Activity,Start date,End date\n\&quot;Mapp...
<python><csv><gradio>
2023-05-03 19:43:08
0
9,295
Soerendip
76,167,425
1,179,620
Why does using a large num for np.linspace mess up the calculation for intersection?
<p>I am attempting some calculations/graphing of two functions.</p> <p>Using</p> <pre><code>import numpy as np import matplotlib.pyplot as plt x = np.linspace(0, 35, 50) g = lambda x: 155 * (1 + (5/100)) ** (x - 1) f = lambda x: np.where(x&lt;=25, 200, 0) plt.plot(x, f(x), '-') plt.plot(x, g(x), '-') idx = np.argwhe...
<python><numpy><matplotlib>
2023-05-03 19:33:47
2
668
jesse
76,167,373
5,509,839
Deprecating Django Migrations
<p>I have a long-maintained and large Django project with hundreds and hundreds of migration files at this point. The tests are taking a really long time to run now due to just how many migrations there are to run through before tests begin.</p> <p>I'm wondering if there's a best-practice for deprecating existing migra...
<python><django>
2023-05-03 19:26:05
0
5,126
aroooo
76,167,346
3,529,833
Python - How can I annotate that a function has the same parameters as another?
<p>Context here is overwriting the method of a Class from a library</p> <pre class="lang-py prettyprint-override"><code>from mail_library import MailClient class LocalMailClient(MailClient): def send(**kwargs: KwargsFrom[MailClient.send]): print(f'Mocking email to {kwargs[&quot;recipients&quot;]}') </code><...
<python><python-3.x><python-typing>
2023-05-03 19:20:56
1
3,221
Mojimi
76,167,270
9,179,875
Tensorflow model.trainable_variables doesn't update after setting layer.trainable
<h3>Context</h3> <p>I'm creating a script which randomly modifies some parameters in a Tensorflow model. It aims to &quot;encrypt&quot; the model by recording the modifications made so that the modifications can be undone by authorised users only.</p> <p>To enable this script, <strong>I want to freeze all model layers ...
<python><tensorflow><machine-learning>
2023-05-03 19:09:33
1
385
Madhav Malhotra
76,167,213
1,023,928
How can I change the y-axis range based on a callback when the x-axis range changes in Bokeh?
<p>I would like to change the visible range of the y-axis each time when the x-axis range changes. But something does not seem to work, panning and changing the x-axis range does not seem to invoke the callback or something is wrong with the callback?</p> <pre><code>x = list(range(100)) y = list(np.random.randint(-10, ...
<python><charts><visualization><bokeh>
2023-05-03 18:58:12
1
7,316
Matt
76,167,094
11,462,274
Reverse the sequence while keeping pairs of columns in a dataframe
<p>Let's say my dataframe <code>df</code> has this sequence of columns:</p> <pre><code>['e', 'f', 'c', 'd', 'a', 'b'] </code></pre> <p>And I want to reverse the sequence while keeping pairs, resulting in this sequence:</p> <pre><code>['a', 'b', 'c', 'd', 'e', 'f'] </code></pre> <p>If the column names were always the sa...
<python><pandas>
2023-05-03 18:41:39
2
2,222
Digital Farmer
76,166,972
12,590,879
When is the task added to the event loop?
<p>I'm fairly comfortable with the asynchronous functionalities of Python (adding tasks to the event loop, <code>await</code>ing them etc). However, I've been reading more about it recently and I saw an example which confuses me:</p> <pre class="lang-py prettyprint-override"><code>import aiohttp import asyncio import t...
<python><python-asyncio><aiohttp>
2023-05-03 18:24:55
1
325
Pol
76,166,919
11,333,604
Torchvision resize not recognising second dimension of pytorch tensor input
<p>I have a pytorch tensor of shape [512,512] and want to resize it to [256,256] I tried using</p> <pre><code>resized = T.Resize(size=(256,256))(img) </code></pre> <p>But I got this error</p> <blockquote> <p>Input and output must have the same number of spatial dimensions, but got input with spatial dimensions of [51...
<python><pytorch><torchvision>
2023-05-03 18:17:52
1
303
Iliasp
76,166,910
3,181,104
"OSError: Starting path not found" when using Selenium webdriver manager for the first time in Python 3
<p>I am trying to set up Selenium 4 in Python for the first time on my Windows 10 PC. I want to be able to manipulate a browser session locally with login.</p> <ul> <li><p>I updated local Python 3 to the latest release 3.11.3</p> </li> <li><p>I installed the latest stable Selenium release 4.9.0 by downloading the files...
<python><python-3.x><windows><selenium-webdriver>
2023-05-03 18:15:45
0
10,090
Argyll
76,166,611
6,013,354
ChatGPT integration with Django for parallel connection
<p>I'm using Django framework to have multiple ChatGPT connection at same time but it's make complete code halt/down until ChatGPT response is back.</p> <p>To encounter this I'm using async with Django channels but still its block Django server to serve any other resource.</p> <p>This is command to run Django server:</...
<python><django><asynchronous><openai-api><chatgpt-api>
2023-05-03 17:34:17
1
680
Aleem
76,166,414
926,071
Unable to download PDF using chrome in python
<p>I am using selenium in python. When I click on the first PDF icon visible on the page. Instead of the PDF file being downloaded there is a page with &quot;Open&quot; button on it. I have tried clicking on the open button using ID open-button but it does not seem to work.</p> <pre><code>from selenium import webdriver...
<python><google-chrome><selenium-webdriver><pdf><download>
2023-05-03 17:03:58
2
401
Chetan
76,166,306
9,251,158
Wrong matrix size in dot product multiplication with sparse matrices
<p>I am coding a linear regression. I have issues with the <code>.dot()</code> product when used with SciPy sparse matrices. Here is a minimal reproducible example with 200 observations, 50 regressors, and 400 outputs.</p> <pre><code>import numpy as np import scipy n_row = 200 n_col = 50 n_outcomes = 400 x = np.rando...
<python><numpy><scipy>
2023-05-03 16:49:49
2
4,642
ginjaemocoes
76,166,252
12,596,824
Place labels on top of each bar
<p>I have the following data frame:</p> <pre><code>week person_counts 2023-01-23 777 2023-01-30 800 2023-02-06 890 2023-02-13 766 2023-02-20 789 </code></pre> <p>How can I plot this with labels on top of each bar?</p> <p>I have the following code: I see solutions online but most of them are solu...
<python><matplotlib>
2023-05-03 16:38:36
0
1,937
Eisen
76,166,239
2,333,496
Simpy: increase store count only if sub stores have items
<p>I'm trying to model a manufacturing line where some machines depends on specific items produced by other machines and can't start its job until previous ones put the items into their stores.</p> <p>For example:</p> <p>We have 4 Machines (A, B, C, D), <code>Machine A</code> has a <code>Store A*</code> (B,C,D Stores c...
<python><simulation><simpy>
2023-05-03 16:37:29
1
1,125
tema
76,166,230
559,827
How can a Python program determine which core it is running on?
<p>I need to debug a Python 3 program that uses the <code>multiprocessing</code> module.</p> <p>I want to keep track of which cores (of a multi-core machine) are getting used and how.</p> <p><strong>Q:</strong> I am looking for a way for the Python code to determine which core is running it.</p> <hr /> <p>The closest I...
<python><multiprocessing><python-multiprocessing>
2023-05-03 16:35:38
1
35,691
kjo
76,166,075
2,987,488
Infeasible solution to scheduling problem using ortools
<p>I'm trying to create a scheduler which assigns a set of shifts to a set of drivers for each day of the week, enforcing a minimum of 1 Day off per week. For the following input data, I'm getting an infeasible solution. Any help?</p> <p>Input data:</p> <pre><code> dow driver hub 0 Sunday 1 S 1 ...
<python><optimization><scheduling><or-tools><cp-sat>
2023-05-03 16:14:06
1
1,272
azal
76,165,970
14,775,478
How to keep only final hypertuning trial/params to recreate a model
<p>I am using hypertuning with keras. That produces many files (1 sub dir for each trial, oracle.json, tuner.json).</p> <p>I would like to run this in a docker container without a mounted volume/without writing all trial data to an external file system. But, I would still like to reuse all these trials when continuing/...
<python><keras>
2023-05-03 16:01:39
0
1,690
KingOtto
76,165,885
10,517,575
Airflow: PostgresOperator loading sql file fails due to jinja2.exceptions.TemplateNotFound
<p>I know this is an issue that keeps coming up a lot but I have read many solutions and none of them seems to solve my issue. I'm trying to execute a SQL query using <strong>PostgreOperator</strong> and a .sql file file named <strong>delete.sql</strong>. I have a git repository named <strong>external_datasources</stro...
<python><sql><airflow><jinja2>
2023-05-03 15:52:29
2
372
Zisis F
76,165,672
12,596,824
Grouping timestamps and graphing
<p>I have a dataframe like so</p> <pre><code>PersonId TimeStamp 10 2023-03-11 02:22:25 1 2023-03-30 03:02:20 26 2023-01-11 08:02:28 28 2023-02-26 09:25:01 46 2023-01-27 11:49:40 2 2023-04-01 01:32:21 </code></pre> <p>I want to plot this with the timestamp on the x-axis and c...
<python><pandas><matplotlib><time-series>
2023-05-03 15:29:52
1
1,937
Eisen
76,165,645
12,323,468
How to put X variable estimates from many statsmodels equations as columns in a dataframe
<p>The following code generates many linear regressions (all with a constant term) based on combinations of 6 explanatory variables. The regressions and the various diagnostic statistics are placed into a df:</p> <pre><code>import pandas as pd import statsmodels.api as sm import itertools from statsmodels.stats.outlie...
<python><pandas><loops>
2023-05-03 15:26:04
1
329
jack homareau
76,165,503
6,326,147
AttributeError: 'CSSMediaRule' object has no attribute 'style' in premailer
<p>I was trying to transform the following nested media query CSS with premailer.</p> <pre class="lang-css prettyprint-override"><code>&lt;style type=&quot;text/css&quot;&gt; @media (prefers-color-scheme: dark) { .textPrimary { color: #E2E2E2 !important; } @media (max-width: 630px) { ...
<python><premailer>
2023-05-03 15:12:12
1
1,073
Rijoanul Hasan Shanto
76,165,382
3,761,305
Python case insensitive efficiently check if list of strings is contained in another string
<p>I want to check if a list of string is contained in another string <strong>but ignoring the case</strong></p> <p>For example:</p> <pre><code>Input: 'Hello World', ['he', 'o w'] Output: [True, True] Input: 'Hello World', ['he', 'wol'] Output: [True, False] </code></pre> <p>I can write something like:</p> <pre><code>o...
<python><string><list><substring><case-insensitive>
2023-05-03 15:01:31
1
651
Ahsan Tarique
76,165,277
13,606,345
NameError during class creation
<p>I have the following code, and I wonder how I can prevent getting error.</p> <pre><code>class A: ...: class Numbers(Enum): ...: ONE = 1 ...: TWO = 2 ...: ODDS = (Numbers.ONE,) ...: EVENS = [number for number in Numbers if not number in ODDS] </code></pre> <p>After runn...
<python>
2023-05-03 14:52:56
1
323
Burakhan Aksoy
76,165,275
11,348,734
Received server error (500) from primary and could not load the entire response body
<p>I'm running a detectron2 instance segmention with a AWS endpoint, I used this tutorial [https://github.com/aws-samples/amazon-sagemaker-pytorch-detectron2][1] for Object Detection, and I adapted to instance segmentation and worked well, but to draw the masks and object identification I need to do it outside the endp...
<python><amazon-web-services><amazon-sagemaker><endpoint><detectron>
2023-05-03 14:52:35
0
897
Curious G.
76,165,210
10,901,843
How would you solve the Minimum Non Constructible Change problem with a Dynamic Programming Table?
<p>this is the question I'm trying to solve using a dynamic programming table:</p> <p><strong>We are given an array of positive integers, which represent the values of coins that we have in our possession. The array could have duplicates. We are asked to write a function that returns the minimum amount of change that w...
<python><algorithm><dynamic-programming>
2023-05-03 14:47:19
1
407
AI92
76,165,193
6,453,106
garbage collection in python threading
<p>When implementing a thread that is intended to periodically read from a stream, I cannot manage to make the thread stop correctly. This is only the case when the callback function that I use is implemented as a method of the agent (<code>Worker</code>). See this example (python v3.10.11):</p> <pre class="lang-py pre...
<python><multithreading><python-multithreading><weak-references>
2023-05-03 14:45:41
0
1,286
Pascal
76,165,096
814,074
Pythonic way to connect hashicorp vault using self signed certificate
<p>I am trying to connect to hvault using python with self signed cert. I wrote code something like below</p> <pre><code>client = hvac.Client(url='https://localhost:8203', cert=('hv.crt','hv.key'),verify=False) client.is_authenticated() client.secrets.kv.v2.read_secret(mount_point=&quot;secret&quot;, path='test') </cod...
<python><hashicorp-vault>
2023-05-03 14:37:25
1
3,594
Sachin
76,165,089
2,986,042
How to print float variable from Trace32 with python command?
<p>I have a simple C code which will update static variable with floating variable. Let's say I have</p> <pre><code>static float32 totalcount = 60.73f; </code></pre> <p>I want to know how to get float values from <code>Lauterbach trace32</code>. I have tried to print the <code>float</code> values using below <code>t32...
<python><python-3.x><trace32><lauterbach>
2023-05-03 14:36:39
1
1,300
user2986042
76,165,060
6,243,129
How to find a threshold number in Optical Flow in Python OpenCV
<p>Using optical flow, I am trying to detect the motion of a coil attached to a motor. When the motor starts, coil runs smoothly but sometimes it starts to vibrate. I need to detect this vibration. I am not sure if optical flow is the correct approach or not but when tested with a stable movement vs vibrations I can se...
<python><python-3.x><opencv><opticalflow>
2023-05-03 14:33:34
1
7,576
S Andrew
76,164,969
5,212,614
pip install error: The process cannot access the file because it is being used by another process
<p>I'm trying to do: <code>pip install pandas_datareader</code></p> <p>I'm getting this error.</p> <pre><code>PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'C:\\Users\\ryans\\AppData\\Local\\Temp\\tmpmyj3mha6' </code></pre> <p>I ran the pip install proces...
<python><python-3.x><anaconda>
2023-05-03 14:22:22
1
20,492
ASH
76,164,863
14,208,556
use scipy optimize minimize in a class
<p>I am cleaning up some code and want to refactor code that is currently unorganized to an individual class. The code optimizes an outflow rate to match the duration outcome with the duration target and looks as follows:</p> <pre><code>import scipy.optimize as optimize volume = 100 value = 95 discount_rates = &lt;some...
<python><class><scipy-optimize-minimize>
2023-05-03 14:11:40
1
333
t.pellegrom
76,164,842
34,935
Can I turn off profiling in a portion of python code when invoking cProfile as a script?
<p>I want to profile my code, but exclude startup.</p> <p>Python docs <a href="https://docs.python.org/3/library/profile.html#module-cProfile" rel="nofollow noreferrer">describe</a> how to run cProfile as a script:</p> <pre><code>python -m cProfile [-o output_file] [-s sort_order] (-m module | myscript.py) </code></pre...
<python><profiling><cprofile>
2023-05-03 14:09:03
1
21,683
dfrankow
76,164,803
534,238
Is there a python library for generating fake data using data properties
<p>I use <a href="https://hypothesis.readthedocs.io/en/latest/quickstart.html" rel="nofollow noreferrer"><em>hypothesis</em></a> for testing.</p> <p>Now I find myself in need of exactly the same capability, but for generating fake data instead of for testing across many parameters.</p> <h1>Question</h1> <ul> <li>Is the...
<python><code-generation>
2023-05-03 14:05:13
1
3,558
Mike Williamson
76,164,760
13,039,962
Calculate the cumulative values grouping by 2 columns
<p>I have this df called df_normales:</p> <pre><code> CODE MONTH NORMAL_PP 0 000261 January 111.4 1 000253 January 46.5 2 000375 January 86.5 3 000229 January 203.6 4 152204 January 52.6 ... ......
<python><pandas>
2023-05-03 14:01:06
0
523
Javier
76,164,757
4,699,294
Using python package from specific path when different versions are installed in the environment at different paths
<p>I have got two different versions of paramiko package in my PYTHONPATH environment coming from two different sets of dependencies installed. I can't change the order in which two different packages installation paths are setup due to various other dependencies and I can't uninstall any one of it either. When importe...
<python>
2023-05-03 14:00:45
0
862
Dinesh Maurya
76,164,749
769,449
Use python, AutoGPT and ChatGPT to extract data from downloaded HTML page
<p>Note: If you're downvoting at least share why. I put in a lot of effort to write this question, shared my code and did my own research first, so not sure what else I could add.</p> <p>I already use Scrapy to crawl websites successfully. I extract specific data from a webpage using CSS selectors. However, it's time c...
<python><openai-api><chatgpt-api><autogpt>
2023-05-03 13:59:44
1
6,241
Adam
76,164,593
1,189,783
Pydantic can't validate the nested model
<p>I expect to get the response as as a list, e.g.:</p> <pre><code>{orders: [{'id': 111, 'info': {'dt': '2023-05-11'}}, ...]} </code></pre> <p>Schemas:</p> <pre><code>class OrderInfo(BaseModel): dt: date class Order(BaseModel): id: int info: OrderInfo class Orders(BaseModel): orders: List[Order] </cod...
<python><pydantic>
2023-05-03 13:43:29
0
533
Alex
76,164,528
1,497,139
addEdge with python gremling GLV - how to get syntax correct
<p>The error:</p> <pre><code>TypeError: The child traversal of [['addV']] was not spawned anonymously - use the __ class rather than a TraversalSource to construct the child traversal </code></pre> <p>appears when trying to run the following code with python GLV</p> <pre class="lang-py prettyprint-override"><code>a = g...
<python><gremlin><gremlinpython>
2023-05-03 13:37:41
1
15,707
Wolfgang Fahl
76,164,441
10,083,382
Identify duplicates and assign similar index in Pandas DataFrame
<p>Suppose that I have a sample data set that can be generated using code below</p> <pre><code># Sample DataFrame with duplicate rows data = {'A': [1, 2, 1, 3, 1, 2, 3, 2], 'B': [4, 5, 4, 6, 4, 5, 6, 5], 'C': [1, 2, 3, 4, 5, 6, 7, 8]} df = pd.DataFrame(data) </code></pre> <p>In above dataframe I want to...
<python><pandas><dataframe><indexing><duplicates>
2023-05-03 13:29:14
1
394
Lopez
76,164,346
6,423,456
How do I use a dict to translate ArrayAgg values for an annotation in Django?
<p>I'm using Django 4 with Postgres.</p> <p>Say I have two related models like this:</p> <pre class="lang-py prettyprint-override"><code>class Company(Model): ... class Address(Model): city = CharField(...) companies = ManyToManyField( Company, through=ThroughCompanyAddress, related...
<python><django>
2023-05-03 13:19:49
0
2,774
John
76,164,227
3,507,584
Pandas keep square brackets in to_latex output
<p>I have a dataframe that I need to pass to a LaTeX document. The dataframe index are strings with square brackets that I would like to keep.</p> <p>MWE:</p> <pre><code>data = { &quot;calories&quot;: [420, 380, 390], &quot;duration&quot;: [50, 40, 45] } df = pd.DataFrame(data = data, index = ['[1] Row 1', '[2] Ro...
<python><pandas><latex>
2023-05-03 13:09:11
0
3,689
User981636
76,164,198
6,195,489
Use str.split() to set value of column in dataframe, but only for some rows
<p>I have a dataframe like e.g.:</p> <pre><code>id some_string 1. blah,count=1,blah 2. blah,blah 3 blah,count=4,blah 4. blah,blah 5 blah,count=4,blah 6. blah,count=3,blah </code></pre> <p>I would like to use split to set a separate column with the value of count to get:</p> <pre><code>id some_string count 1 ...
<python><pandas><dataframe>
2023-05-03 13:06:28
2
849
abinitio
76,164,132
3,575,623
Efficiently attribute group to each ID in a melted DataFrame
<p>I have a melted DataFrame that contains measurements for different sampleIDs and experimental conditions:</p> <pre><code> expcond variable value 0 0 Sample1 0.001620 1 1 Sample1 -0.351960 2 2 Sample1 -0.002644 3 3 Sample1 0.000633 4 4 Sample1 0.011253...
<python><pandas><dataframe>
2023-05-03 12:59:49
0
507
Whitehot
76,164,083
5,858,752
Is `engine` a Python keyword?
<p>I tried googling &quot;Python engine keyword&quot; or &quot;python engine&quot; but nothing useful is showing up.</p> <p>In the codebase I am working with, I see the following:</p> <pre><code> with engine(database_url).connect() as conn: </code></pre> <p>I did not <code>engine</code> imported, and I also did not se...
<python>
2023-05-03 12:56:03
2
699
h8n2
76,163,832
7,253,901
Pandas-on-spark throwing java.lang.StackOverFlowError
<p>I am using pandas-on-spark in combination with regex to remove some abbreviations from a column in a dataframe. In pandas this all works fine, but I have the task to migrate this code to a production workload on our spark cluster, and therefore decided to use pandas-on-spark. However, I am running into a weird error...
<python><pandas><apache-spark><pyspark><pyspark-pandas>
2023-05-03 12:28:30
1
2,825
Psychotechnopath
76,163,761
8,510,149
Transform a pandas series, new mean and stddev
<p>If you have a series, like this:</p> <pre><code>import pandas as pd pd.series = [1.01, 2, 1.2, 3.1, 4.32, 1.23, 8.21, 4.2, 1.3, 2.3, 3.3, 5.2, 4.8, 4.2, 5.98, 6.1, 2.9, 4.12, 4.78, 5.56, 5.21] </code></pre> <p>What if want to force a transformation on this series, to have a mean of 10 and a std dev of 2.</p> <p>Ho...
<python>
2023-05-03 12:20:50
1
1,255
Henri
76,163,412
694,360
Split a 2D polyline defined through segments and arcs with Python
<p>I'm looking for a library (preferably in pure Python) or an algorithm able to split, with an arbitrary line, a 2D polyline made of segments and arcs.</p> <p>The polyline is a sequence of</p> <ul> <li>segments <code>[(x1,y1),(x2,y2)]</code></li> <li>and arcs <code>[(cx,cy),radius,start_angle,end_angle)]</code>, where...
<python><computational-geometry>
2023-05-03 11:42:53
0
5,750
mmj
76,163,192
10,311,672
elevenlabs-python package vs. google_speech: setting storage path, and limit for characters read-outs
<p>I'm using an python package to play voices known as elevenlabs - here is the link <a href="https://github.com/elevenlabs/elevenlabs-python" rel="nofollow noreferrer">https://github.com/elevenlabs/elevenlabs-python</a></p> <p>This package uses mpv to play its audio files,</p> <p>such that , a script like that will be...
<python><mpv>
2023-05-03 11:17:48
1
336
Waly
76,163,173
14,535,309
Why is Django looking for font in the wrong place and by the wrong name? TTFError at*
<p>I'm trying to render my html page to pdf using django with these functions while also using a <strong>Cyrillic</strong> font:</p> <pre><code>def fetch_resources(uri, rel): if settings.STATIC_URL and uri.startswith(settings.STATIC_URL): path = os.path.join(STATIC_ROOT, uri.replace(settings.STATIC_URL, &qu...
<python><django><pdf><django-staticfiles>
2023-05-03 11:15:28
0
2,202
SLDem
76,163,104
1,856,922
How do I make two parallel, asynchronous calls using jQuery/FastAPI so that neither waits on the other?
<p>I have a simple chat application written using FastAPI in Python and jQuery. The user enters a question into form, and a response is returned from the server. However, I also need to send the user message to a separate process that takes a long time (say, querying a database). I don't want the user to have to wai...
<javascript><python><ajax><fastapi>
2023-05-03 11:07:30
0
4,732
Craig
76,162,791
9,985,032
OpenCV getWindowImageRect returning size not matching resolution
<p>I'm trying to get the screen position of my window using opencv</p> <pre><code> cv2.imshow('test', img) print(cv2.getWindowImageRect('test')) </code></pre> <p>When I move my window to the bottom right corner to the screen it outputs <code>(1484, 895, 500, 500)</code> so it looks like it thinks that my screen ...
<python><windows><opencv><dpi>
2023-05-03 10:26:17
0
596
SzymonO
76,162,732
2,726,900
How to convert a JIRA task to a subtask from Atlassian Python API?
<p>I'm trying to convert a JIRA issue to a subtask</p> <p>That's what I'm doing:</p> <pre><code>converted_to_subtask = jira.update_issue_field( &quot;FSTORE-326&quot;, { &quot;issuetype&quot;: {&quot;name&quot;: &quot;Sub-task&quot;}, &quot;parent&quot;: {&quot;key&quot;: &quot;FSTORE-324&quot;} }) </co...
<python><jira><atlassian-python-api>
2023-05-03 10:18:14
1
3,669
Felix
76,162,691
6,528,055
How does the word2vec produce embeddings for the unseen words?
<p>I'm using an <strong>unlabeled</strong> news corpus to fine-tune the Word2Vec model. After that I'm using those embeddings to generate embeddings for words present in a new <strong>labeled</strong> dataset. These new embeddings were fed to an RNN as initial weights. I've shared the code for generating the embedding ...
<python><nlp><word2vec><word-embedding>
2023-05-03 10:13:42
1
969
Debbie
76,162,648
12,404,524
How to deal with AttributeError in dataclass subclass initialization?
<p>I have a dataclass <code>Walk</code> with the attribute <code>vertex_list</code> and a method <code>add</code>. I want to make a subclass <code>Path</code> that inherits from <code>Walk</code> and has a different implementation for the <code>add</code> method.</p> <p>These are my two classes:</p> <p><code>Walk.py</c...
<python><inheritance><python-dataclasses>
2023-05-03 10:08:10
0
1,006
amkhrjee
76,162,566
15,593,152
Extract number of days from an sql query using pandas, and write the result in a new column of the dataframe
<p>I have a dataframe where one column (called &quot;sql&quot;) is an sql query string (that have at least two dates inside it). I need to compute the number of days between the two dates, and store it in a new column of the df.</p> <p>Example &quot;sql&quot; column <code>df['sql'].iloc[0]</code> of my dataframe:</p> <...
<python><pandas><dataframe>
2023-05-03 09:58:20
1
397
ElTitoFranki
76,162,459
6,583,606
Jupyter notebook ImportError: attempted relative import with no known parent package
<h1>Summary</h1> <p>I've a repository with the following structure:</p> <pre><code>phd-notebooks ├── notebooks | ├── resources | | └── utils.py | ├── notebooks-group-1 | | ├── notebook1.ipynb | | └── notebook2.ipynb | └── notebooks-group-2 | ├── notebook1.ipynb | └── notebook2.ipynb ├── .g...
<python><import><jupyter-notebook><jupyter><importerror>
2023-05-03 09:46:49
2
319
fma
76,162,435
14,494,483
Why use .execute in Gmail API discovery in python
<p>I have a query in regards to accessing gmail api using python. Below, I have the discovery build <code>service</code>, then using <a href="https://developers.google.com/gmail/api/reference/rest" rel="nofollow noreferrer">gmail api documentation</a>, we can access different REST resources, for example, accessing labe...
<python><gmail-api>
2023-05-03 09:42:46
1
474
Subaru Spirit
76,162,427
1,423,259
Argument of type "dict[str, str]" cannot be assigned to parameter "data" of type "Type[empty]"
<p>I have a very small serializer for the initial user registration:</p> <pre class="lang-py prettyprint-override"><code>class UserRegistrationSerializer(serializers.ModelSerializer): class Meta: model = User fields = [ &quot;email&quot;, &quot;password&quot;, ] ...
<python><django><django-rest-framework>
2023-05-03 09:41:47
1
2,526
tommueller
76,162,375
2,107,667
`No module named...` while deploying an AWS Lambda using Serverless Framework, poetry, python3.10 and fastapi
<h2>EDIT</h2> <p>Il looks like theproblem comes from the Serverless plugin, <code>serverless-python-requirements</code>.</p> <p>When packaging with <code>$ sls package</code>, when having <code>python = &quot;^3.9&quot;</code> the dependencies are in the zip, but having <code>python = &quot;^3.10&quot;</code> they are ...
<python><amazon-web-services><aws-lambda><serverless-framework><python-poetry>
2023-05-03 09:34:17
1
3,039
Costin
76,162,262
5,383,733
Use Pandas UDF to calculate Cosine Similarity of two vectors in PySpark
<p>I want to calculate the cosine similarity of 2 vectors using Pandas UDF. I implemented it with Spark UDF, which works fine with the following script.</p> <pre><code>import numpy as np from pyspark.sql.functions import udf from pyspark.sql.types import FloatType # Create dataframe df = spark.createDataFrame([(&quot;...
<python><pandas><apache-spark><pyspark><pandas-udf>
2023-05-03 09:20:21
1
876
Haritha Thilakarathne
76,162,244
5,773,890
Linear interpolation along rows - single value per row - using pandas/scipy
<p>Supose I have the following pandas DataFrame</p> <pre><code>&gt;&gt;&gt; df = pd.DataFrame([[-10, -5, 0, 10], [17, 10, 16, 20], [40, 30, 10, -6]], columns=[0, 10, 20, 30]) &gt;&gt;&gt; df.values array([[-10, -5, 0, 10], [ 17, 10, 16, 20], [ 40, 30, 10, -6]]) &gt;&gt;&gt; df.columns Int64Ind...
<python><pandas><scipy><interpolation>
2023-05-03 09:17:35
1
415
Mark.R
76,161,924
15,070,331
Folium Map not displaying in PDF output
<p>I am trying to generate a PDF file from a Folium map using the weasyprint package in Python. I have the following code:</p> <pre><code>import folium from weasyprint import HTML def generate_map_html(lat: float, lon: float): &quot;&quot;&quot; Generate a map HTML &quot;&quot;&quot; # Generate map ...
<python><pdf><folium><weasyprint>
2023-05-03 08:36:44
0
395
Saad Mrabet
76,161,889
1,112,283
How do I specify a Python version constraint for a dependency specifically for a platform?
<p>My Python package requires Python &gt;= 3.8 (defined in <code>setup.cfg</code> or <code>pyproject.toml</code>):</p> <pre><code>python_requires = &gt;=3.8 </code></pre> <p>However, it also has the following <em>optional</em> dependency :</p> <pre><code>tensorflow&gt;=2.7.0 </code></pre> <p>If optional dependencies ar...
<python><setuptools><python-packaging>
2023-05-03 08:32:43
1
1,821
cbrnr
76,161,882
7,386,830
Line plot with Seaborn
<p>I have the following code sample, where I need to draw a green line, as shown inside the plot below:</p> <pre><code>fig = plt.figure(figsize = (12,6)) plt.scatter((y - y_pred), y_pred , color = 'red') plt.axhline(y=0, color='r', linestyle=':') plt.ylim(0,50) plt.xlim(-4,6) p = sns.lineplot([-4,6],[25,25],color='g') ...
<python><plot><seaborn><visualization>
2023-05-03 08:31:32
1
754
Dinesh
76,161,826
10,232,932
Pandas read excel: XLRDError: Excel xlsx file; not supported
<p>Also there existing already several questions on this topic with solutions:</p> <p><a href="https://stackoverflow.com/questions/65250207/pandas-cannot-open-an-excel-xlsx-file">Pandas cannot open an Excel (.xlsx) file</a></p> <p><a href="https://stackoverflow.com/questions/65254535/xlrd-biffh-xlrderror-excel-xlsx-fil...
<python><pandas><excel>
2023-05-03 08:25:14
1
6,338
PV8
76,161,798
4,862,162
How to force-reload a Python module after pip upgrade?
<p>In practical applications, certain Python packages need to be upgraded dynamically during runtime. And to avoid service interruption, the main Python process shall not be terminated and relaunched due to individual module upgrade. To re-import the upgraded module, we typically use <code>importlib.reload()</code>. Ho...
<python><module><reload><python-importlib>
2023-05-03 08:20:47
0
1,615
xuancong84
76,161,594
10,027,592
Setting display width for OpenAI Gym (now Gymnasium)
<p>I'm trying to print out some values in Gymnasium (previously OpenAI Gym), such as:</p> <pre><code>import gymnasium as gym env = gym.make(&quot;LunarLander-v2&quot;, render_mode=&quot;human&quot;) observation, info = env.reset() print(f'env.observation_space: {env.observation_space}') print(f'obs: {observation}') </...
<python><reinforcement-learning><openai-gym>
2023-05-03 07:55:29
2
4,226
starriet 차주녕
76,161,562
4,469,930
How to properly attach a file to a PDF using PyPDF2?
<p>I'm trying to attach a file to a PDF file, but I'm running into some issues. I'm not sure if I'm doing something wrong or if there's a bug in PyPDF2. I'm using Python 3.10.2 for this and I downloaded the newest package for PyPDF2 through pip.</p> <p>These are 3 versions of code that I tried using, but each has its o...
<python><pdf><attachment><pypdf>
2023-05-03 07:51:37
1
728
bblizzard
76,161,461
14,224,948
sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) could not translate host name to address: Unknown server error
<p>while doing this tutorial: <a href="https://auth0.com/blog/using-python-flask-and-angular-to-build-modern-apps-part-1/" rel="nofollow noreferrer">https://auth0.com/blog/using-python-flask-and-angular-to-build-modern-apps-part-1/</a></p> <p>I bumped on an error that wasn't described anywhere on Stack.</p> <p>The prob...
<python><angular><flask><sqlalchemy><psycopg2>
2023-05-03 07:38:29
1
1,086
Swantewit
76,161,237
1,055,817
Tensorflow 2.11.0 on Mac crashes when setting the seed for generating random tensors
<p>I am trying to learn tensorflow. I installed tf on my Mac (M1 Chip) running 13.2.1.</p> <p>I created a conda env with tensorflow.</p> <p>I am trying to generate random tensors by setting the seed and my kernel crashes. Here is the output when I tried to do this.</p> <p><a href="https://i.sstatic.net/doq3U.png" rel="...
<python><tensorflow>
2023-05-03 07:07:30
2
1,942
siva82kb
76,161,108
1,954,677
How to simplify a logical expression based on additional logical constraints using sympy
<p><strong>Question</strong></p> <p>Is there a way to use <code>sympy</code> to simplify (in the usual vaguely defined sense) a logical <em>target expression</em> based on some logical <em>constraint expressions</em>? Both the target expression and the constraints can have an arbitrary form in a set of symbols <code>A,...
<python><logic><sympy><logical-operators><symbolic-math>
2023-05-03 06:47:12
1
3,916
flonk
76,160,833
6,758,739
Search for the username and change the password in the space-separated file using python
<p>The code below reads the files and stores it to an array:</p> <pre><code>import sys import logging def file_to_array(): file_info=&quot;/application/files/Password.txt&quot; with open (file_info,'rt') ass fh: pw_lines = [x.strip() for x in fh.readlines() if not x.startswith('#')] #ignore comments ...
<python>
2023-05-03 05:59:23
0
992
LearningCpp
76,160,728
6,539,586
Pandas months between function, np.timedelta does not work
<p>There are a million results for how to find number of months between two columns in a pandas dataframe, and they nearly all say to use this:</p> <pre><code>(date_end - date_start) / np.timedelta64(1, &quot;M&quot;) </code></pre> <p>This doesn't work in some instances though, I'm not sure if this is a bug or what, bu...
<python><pandas><numpy><date><datetime>
2023-05-03 05:38:21
0
730
zachvac
76,160,542
2,604,247
What Actually Triggers the Asyncio Tasks?
<p>Trying to understand python <code>asyncio</code> coming from some background on multithreading with <code>concurrent.futures</code>. Here is the sample script</p> <pre class="lang-py prettyprint-override"><code>#!/usr/bin/env python3 # encoding: utf-8 &quot;&quot;&quot;Sample script to test asyncio functionality.&qu...
<python><multithreading><subprocess><python-asyncio>
2023-05-03 04:56:06
2
1,720
Della
76,160,534
651,174
Find if a sub-structure is in a structure
<p>A way to find if an object is a sub-object of another?</p> <p>Is there an operator or built-in function in python where I can do something like the following?</p> <pre><code>&gt;&gt;&gt; needle={&quot;age&quot;: 10, &quot;name&quot;: &quot;peter&quot;} &gt;&gt;&gt; haystack={&quot;age&quot;:10, &quot;name&quot;: &qu...
<python><python-3.x><dictionary>
2023-05-03 04:53:47
2
112,064
David542
76,160,529
5,942,100
Tricky normalize a specific column within a dataframe using a calculated field logic (Pandas)
<p>Take the delta between ['rounded_sum'] and ['rounded_sum_2']. Once found, subtract or add this delta to the ['Q4 28'] column. Making sure the sum of columns [Q1 28 - Q4 28] is equivalent to the ['rounded_sum'] column.</p> <p><strong>Data</strong></p> <pre><code>Location range type Q1 28 Q2 28 Q3 28 Q4...
<python><pandas><numpy>
2023-05-03 04:52:40
2
4,428
Lynn
76,160,478
3,931,214
Numpy "put_along_axis", but add to existing values rather than just put (similar to scatter_add in PyTorch)
<p>Is there a way to use <code>np.put_along_axis</code> but have it add to the existing values rather than replace?</p> <p>For example, in PyTorch this could be implemented as:</p> <pre><code>import torch frame = torch.zeros(3,2, dtype=torch.double) updates = torch.tensor([[5,5], [10,10], [3,3]], dtype=torch.double) in...
<python><numpy><pytorch>
2023-05-03 04:39:01
1
843
Craig
76,160,437
8,283,848
Aggrgate JSON key value of JSONField Django PostgreSQL
<p>I have a simple model setup as below,</p> <pre class="lang-py prettyprint-override"><code>import random import string from django.db import models def random_default(): random_str = &quot;&quot;.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(10)) return {&quot;random&quot;: rando...
<python><django><postgresql><django-orm><django-3.0>
2023-05-03 04:27:42
2
89,380
JPG
76,160,382
3,199,553
Why can't I modify DataFrame in place by selecting some columns when iterating through list of DataFrames?
<pre><code>dfl = [pd.DataFrame( { &quot;A&quot;: 1.0, &quot;B&quot;: pd.Timestamp(&quot;20130102&quot;), &quot;C&quot;: pd.Series(1, index=list(range(4)), dtype=&quot;float32&quot;), &quot;D&quot;: &quot;foo&quot;, } )] for df in dfl: df = df[[&quot;A&quot;, &quot;B&quot;]]...
<python><pandas><dataframe>
2023-05-03 04:12:57
3
1,497
stanleyli
76,160,077
21,784,274
How to get rid of daylight saving time (DST) in Django? (Because in my country it's not being used anymore!)
<p>In my country, daylight saving time (DST) is not being applied anymore, but Django is still taking it into account. So when I choose my region in <code>TIME_ZONE</code> inside the <code>settings.py</code> file, the time is stored wrong (1-hour offset) inside the database.</p> <p><strong>Is there any possible way to ...
<python><django><timezone><dst>
2023-05-03 02:34:01
1
947
Mohawo
76,160,048
10,655,190
XGBoost DataFrame.dtypes for data must be int, float or bool
<p><strong>Context</strong>: Trying to fit my XGBoost model but getting a ValueError Msg. I've looked at similar posts but the difference is that ALL my columns are either Int or Float. I have no object, categorical columns.</p> <p>X_train.info() yields:</p> <p><a href="https://i.sstatic.net/P6RnN.png" rel="nofollow no...
<python><machine-learning><xgboost>
2023-05-03 02:25:07
1
1,624
Roger Steinberg
76,159,980
1,023,928
Can't get 'autorange' for the y-axis to work in Plotly for Python
<p>I created 4 subplots that are stacked vertically with their x-axes synchronized. My problem is that when I zoom in on one chart then the other chart's x-axis range is adjusted as desired, however, the y-axis is not adjusted. I want the y-axis range to rescale automatically so that the max value in the visible range ...
<python><plotly>
2023-05-03 02:04:22
0
7,316
Matt
76,159,932
412,655
With a Python decorator that adds a named argument, is it possible to provide a correct type annotation?
<p>Suppose I have this decorator <code>wrap_with_id</code> and use it on <code>func</code>:</p> <pre class="lang-py prettyprint-override"><code>P = ParamSpec(&quot;P&quot;) R = TypeVar(&quot;R&quot;) def wrap_with_id(fn: Callable[P, R]): def wrapper(id: str, *args: P.args, **kwargs: P.kwargs) -&gt; R: all_...
<python><types>
2023-05-03 01:46:38
2
4,147
wch
76,159,813
1,035,279
With python, I am using a requirements.txt file, how can I find the module specified in that file that installed a particular dependency?
<p>The requirements.txt file is large and investigating it module by module is not practical.</p>
<python><python-3.x><pip>
2023-05-03 01:03:38
1
16,671
Paul Whipp
76,159,708
4,419,845
How to disable Authentication in FastAPI based on environment?
<p>I have a FastAPI application for which I enable <code>Authentication</code> by injecting a dependency function.</p> <p>controller.py</p> <pre class="lang-py prettyprint-override"><code>router = APIRouter( prefix=&quot;/v2/test&quot;, tags=[&quot;helloWorld&quot;], dependencies=[Depends(api_key)], res...
<python><authorization><fastapi><swagger-ui><openapi>
2023-05-03 00:25:33
1
508
Waqar ul islam
76,159,644
1,185,242
How do you test a class that reads from multiple files with pytest?
<p>I'm trying to write a test for the following class which has a method that reads from two different files?</p> <pre><code># example.py class Example def __init__(self): pass def load(self): p = open('p.txt').read() q = open('q.txt').read() return p + q </code></pre> <p>I woul...
<python><mocking><pytest>
2023-05-03 00:02:46
1
26,004
nickponline
76,159,625
4,447,540
how to avoid lock or release metadata lock in sqlalchemy using mysql
<p>I'm using sqlalchemy 2.0 with a MySQL database. If I create some table definitions in my <code>Metadata()</code> object (<code>meta</code>) using <code>meta.create_all()</code> and then immediately drop them using <code>meta.drop_all()</code> there is no problem -- tables are correctly created and dropped without ...
<python><mysql><sqlalchemy>
2023-05-02 23:58:04
1
25,296
langtang
76,159,612
3,380,902
GeoPandas GeoDataFrame polygon geometry - calculate area
<p>I have a geopandas GeoDataFrame with Polygon geometry and I am calculating the area of the polygon, however, I am not sure what the unit is for the area.</p> <pre><code>import geopandas as gpd from shapely.geometry import Polygon # create two dummy polygons poly1 = Polygon([(0,0), (1,0), (1,1), (0,1)]) poly2 = P...
<python><geospatial><geopandas>
2023-05-02 23:52:24
1
2,022
kms
76,159,601
3,438,507
Pandas DataFrame dtype switches when row is inserted using .loc
<p><strong>Aim</strong><br /> I am trying to append a row to a pandas data frame with replacement, where maintaining data type (dtype) is crucial.</p> <p><strong>Question</strong><br /> Why, when inserting <code>row</code> into <code>data_frame</code>, does the dtype switch to <code>object</code>, while neither object ...
<python><pandas><dataframe><concatenation>
2023-05-02 23:50:04
1
1,155
M.G.Poirot
76,159,540
6,326,429
Matrix comprising columns of identity
<p>I want to implement the following in python. Given a vector v of length N with each entry taking values in the set of integers 0,1,2,...,d, I want to create a new vector w of length d, that stores in the ith location the number of occurrences of the digit i in v. I assume knowledge of d, N and v.</p> <p>As an exampl...
<python><numpy>
2023-05-02 23:37:13
1
901
sixtyTonneAngel
76,159,509
16,527,596
How to call an attribute from one class into another in python
<p>I have some code like:</p> <pre><code>class Digital_signal_information: def __init__(self, signal_power :float, noise_power :float, n_bit_mod:int): self.signal_power=signal_power # The attribute i want to use self.noise_power=noise_power self.n_bit_mod=n_bit_mod class Line(Digital_signa...
<python><oop>
2023-05-02 23:29:39
1
385
Severjan Lici
76,159,471
11,146,276
Correct regex not matching anything
<pre><code>import re pattern = r&quot;/destination=(-?\d+\.\d+),(-?\d+\.\d+)/&quot; url = &quot;https://www.google.com/maps/dir/?api=1&amp;destination=12.1234567890,-12.1234567890&quot; result = re.search(pattern, url) latitude = result.group(1) longitude = result.group(2) </code></pre> <p>I expect to receive the lati...
<python><regex>
2023-05-02 23:19:51
1
428
Firefly
76,159,434
1,204,749
Python3 scripts in "venv" imports matplotlib from Python2.7 rather Python3 site packages
<p>I’m having a deployment problem/Import Error with Python3 scripts that are running inside “venv” virtual env, one of the scripts that imports “matplotlib” &amp; “numpy” seems to be incorrectly referring to python2.7 site packages rather than python3 site-packages.</p> <p>Background: The project was to migrate some P...
<python><python-3.x><numpy><matplotlib><python-venv>
2023-05-02 23:05:07
0
3,034
cyber101
76,159,412
2,769,240
Issue with Relative Import
<p>I am having error in importing both via relative and absolute import. Something I have done many times in the past and it used to work.</p> <p>here's my folder structure:</p> <pre><code>project ├── src │ └── notebook.ipynb |_____ test.py └── __init__.py </code></pre> <p>So basically within src folder (whi...
<python>
2023-05-02 22:59:01
1
7,580
Baktaawar
76,159,376
3,889,954
RequestsDependencyWarning: urllib3 (2.0.1) or chardet (5.1.0)/charset_normalizer (3.1.0) doesn't match a supported version
<p>My script was running fine before, but now it is giving me this error:</p> <pre><code>RequestsDependencyWarning: urllib3 (2.0.1) or chardet (5.1.0)/charset_normalizer (3.1.0) doesn't match a supported version </code></pre> <p>I have read existing posting and tried the following, but they did not work:</p> <pre><code...
<python>
2023-05-02 22:48:42
0
629
Cinji18