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,862,962
4,826,074
Exception thrown when using python in for-loop in C++-script
<p>I have a C++ script that I run in Visual studio 2022 on windows 10 and where I include the python module. In the code I import numpy in a for-loop. The code executes fine the first round, but in the second round and exception is thrown as soon as the code tries to execute the import statement. I have googled for the...
<python><c++><cpython>
2022-12-20 12:16:31
0
380
Johan hvn
74,862,947
3,461,321
Animating plot + image subplots synchronously in matplotlib
<p>I have a figure that contains both a curve plot and a corresponding image. I'd like for the two of them to shift in sync with one another -- so that the white region of the image follows the location in the curve where all three curves match up. (For the curious, this is intended as a simple simulation of a multiwav...
<python><matplotlib><animation>
2022-12-20 12:15:31
1
1,685
nzh
74,862,928
3,521,180
why am I not able to convert string type column to date format in pyspark?
<p>I have a column which is in the &quot;20130623&quot; format. I am trying to convert it into dd-mm-YYYY. I have seen various post online including here. But I only got one solution as below</p> <pre><code>from datetime import datetime df = df2.withColumn(&quot;col_name&quot;, datetime.utcfromtimestamp(int(&quot;col_n...
<python><python-3.x><pyspark>
2022-12-20 12:13:56
1
1,150
user3521180
74,862,859
13,227,420
How to efficiently reorder rows based on condition?
<p>My dataframe:</p> <pre><code>df = pd.DataFrame({'col_1': [10, 20, 10, 20, 10, 10, 20, 20], 'col_2': ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']}) col_1 col_2 0 10 a 1 20 b 2 10 c 3 20 d 4 10 e 5 10 f 6 20 g 7 20 h </code></pre> <p>I don't...
<python><pandas>
2022-12-20 12:07:05
1
394
sierra_papa
74,862,840
6,368,217
How to validate Keycloak webhook request?
<p>I'm implementing an endpoint to receive events from Keycloak using a webhook, but I don't know how to validate this request.</p> <p>I see that the request contains a header &quot;X-Keycloak-Signature&quot;. Also, I set a WEBHOOK_SECRET. It seems I somehow need to generate this signature from the request and the secr...
<python><flask><request><keycloak><webhooks>
2022-12-20 12:05:15
1
991
Alexander Shpindler
74,862,829
5,574,107
Sum with rows from two dataframes
<p>I have two dataframes. One has months 1-5 and a value for each month, which are the same for ever ID, the other has an ID and a unique multiplier e.g.:</p> <pre><code>data = [['m', 10], ['a', 15], ['c', 14]] # Create the pandas DataFrame df = pd.DataFrame(data, columns=['ID', 'Unique']) data2=[[1,0.2],[2,0.3],[3,...
<python><pandas><dataframe>
2022-12-20 12:03:59
1
453
user13948
74,862,575
8,708,364
`df.select_dtypes` works with `float` but not `int`
<p>I just came across this strange behaviour of <code>pd.DataFrame.select_dtypes</code>.</p> <p>My <code>pd.DataFrame</code> is:</p> <pre><code>df = pd.DataFrame({'a': [1, 2, 3, 4], 'b': ['a', 'b', 'c', 'd'], 'c': [1.2, 3.4, 5.6, 7.8]}) </code></pre> <p>Now if I want to select the numeric columns, I would do:</p> <pre>...
<python><pandas><dataframe>
2022-12-20 11:41:25
1
71,788
U13-Forward
74,862,252
9,172,344
redis lrange prefix fetching way
<p>I have list type data in redis, there're so many keys which can't be fetched all one time. I tried to use python redis Lrange function to get in batch style, such as 1000 a time, but it seems not work as it always return empty. Lrange regard <code>*</code> as a character, how should I do it?</p> <pre><code>conn.Lran...
<python><redis>
2022-12-20 11:14:24
1
1,037
Frank
74,862,222
4,169,571
matplotlib: labeling of curves
<p>When I create a plot with many curves it would be convenient to be able to label each curve at the right where it ends.</p> <p>The result of <code>plt.legend</code> produces too many similar colors and the legend is overlapping the plot.</p> <p>As one can see in the example below the use of <code>plt.legend</code> i...
<python><matplotlib><legend>
2022-12-20 11:12:04
1
817
len
74,862,107
20,574,508
Is the CSRF token correctly implemented in Flask / WTF?
<p>I don't know a lot about CSRF but I'd like to know if it is correctly implemented.</p> <p>I have a simple signin form using the following code:</p> <p>The CSRF protection is activated:</p> <pre><code>from flask_wtf.csrf import CSRFProtect csrf = CSRFProtect() csrf.init_app(app) </code></pre> <p>In forms.py:</p> <pr...
<python><flask><csrf><flask-wtforms>
2022-12-20 11:04:00
1
351
Nicolas-Fractal
74,862,082
12,930,958
How to accept an ascii character with python re (regex)
<p>I have a regex that controls a password so that it contains an upper case, a lower case, a number, a special character and minimum 8 characters.</p> <p>regex is:</p> <pre class="lang-py prettyprint-override"><code>regex_password = r&quot;^(?=.*[a-z])(?=.*[A-Z])(?=.*[\W]).{8,}$&quot; </code></pre> <p>I use in this fu...
<python><python-3.x><regex><python-re>
2022-12-20 11:02:07
1
2,729
fchancel
74,861,953
4,671,162
extract part of a date and put them into a dataframe
<p>I would like to know how from a dataframe with a column dedicated to the date how to extract each part of a date (at once instead of <em>df[&quot;_Date&quot;].str.match(pattern)</em> for each part) and put them in a dataframe for example:</p> <pre><code>import pandas as pd # date: str mm/dd/yyyy df = pd.DataFrame(d...
<python><pandas>
2022-12-20 10:53:31
1
891
problème0123
74,861,849
8,551,737
How to fix the batch size in keras subclassing model?
<p>In tf.keras functional API, I can fix the batch size like below:</p> <pre><code>import tensorflow as tf inputs = tf.keras.Input(shape=(64, 64, 3), batch_size=1) # I can fix batch size like this x = tf.keras.layers.Conv2DTranspose(3, 3, strides=2, padding=&quot;same&quot;, activation=&quot;relu&quot;)(inputs) out...
<python><tensorflow><keras><tensorflow2.0>
2022-12-20 10:44:52
1
455
YeongHwa Jin
74,861,844
10,576,322
Dependencies packages and subpackages
<p>I am really new to python packaging. It already is a confusing topic with recommended ways and options that only a minority seems to apply. But to make it worse, I stumbled over this problem.</p> <p>I started with the intention to write a rather small package with a really focussed purpose. My first solution include...
<python><dependencies><python-packaging>
2022-12-20 10:44:25
1
426
FordPrefect
74,861,715
6,119,375
Error when using function of imported package
<p>I am running the follwing code:</p> <pre class="lang-py prettyprint-override"><code>!pip install scikit-learn==0.24 import sklearn.metrics mape = mean_absolute_percentage_error(target_test.values, p) </code></pre> <p>but then get an error. What is the problem with this code?</p>
<python><scikit-learn>
2022-12-20 10:34:11
1
1,890
Nneka
74,861,607
2,181,056
python - add mock for requests.get without need to explicitly check it
<p>I want to add <code>requests</code> mock for python. Any call to <code>requests.get</code> in a class will call the unittest mock function instead.</p> <p>I don't want to add a call such as <code>requests.get</code> in the unittest itself, it may happen in many places in code.</p> <p>Now, changes on code - I get:</p...
<python><python-requests><mocking>
2022-12-20 10:26:44
1
1,436
Eitan
74,861,529
5,684,405
Remove overlaping tuple ranges from list leaving only the longest range
<p>For a given list of range-tuples, I need to remove overlapping rage tuples while leaving the longest range for those that overlap or if same length keep both.</p> <p>eg</p> <pre><code>input = [ [(1, 7), (2, 3), (7, 8), (9, 20)], [(4, 7), (2, 3), (7, 10)], [(1, 7), (2, 3), (7, 8)]] expected_output = [ [(1,7), (9,...
<python>
2022-12-20 10:18:30
1
2,969
mCs
74,861,480
5,355,993
Getting error: coverage.exceptions.ConfigError: File pattern can't include '**/**' while generating coverage for python project
<p>I am trying to generate code coverage for a python project. I am running the command:</p> <pre><code>pytest --cov-config=./coveragerc --cov-report html:target/coverage --cov=./ </code></pre> <p>This command should help me generate an html based coverage report, but I am getting the error:</p> <pre><code>+ pytest --c...
<python><jenkins><continuous-integration><pytest><coverage.py>
2022-12-20 10:14:52
1
690
Piyush Das
74,861,252
2,205,969
Downgrade poetry version
<p>I need to downgrade my version of <code>poetry</code> to version <code>1.2.1</code>.</p> <p>Currently, it's <code>1.2.2</code>.</p> <pre><code>&gt;&gt;&gt; poetry --version Poetry (version 1.2.2) </code></pre> <p>I use the following command:</p> <pre><code>&gt;&gt;&gt; curl -sSL https://install.python-poetry.org | P...
<python><python-poetry>
2022-12-20 09:55:13
4
3,968
Ian
74,861,186
4,295,389
Access vaiolation in PyArray_SimpleNew
<p>I have a cmake based C++ project (library) which is wrapped to python using swig. A method of the library returns a <code>std::vector&lt;int64_t&gt;</code> which is copied to a numpy array with the <code>%extend</code> keyword of swig. (see foo.i bellow)</p> <p><strong>foo.i</strong></p> <pre><code>%{ #define SWIG_F...
<python><c++><arrays><numpy><swig>
2022-12-20 09:49:24
1
538
moudi
74,861,003
1,714,692
Rescaling image to get values between 0 and 255
<p>A piece of code taken <a href="https://github.com/fchollet/deep-learning-with-python-notebooks/blob/master/chapter09_part03_interpreting-what-convnets-learn.ipynb" rel="nofollow noreferrer">from here</a> is trying to plot the intermediate outputs of a convolutional neural network. The outputs are taken and rescaled ...
<python><image><scale>
2022-12-20 09:34:01
2
9,606
roschach
74,860,947
12,242,085
How to find categorical data where one category (including NaN) represents at least 80% of all categories of variable in Python Pandas?
<p>I have Pandas DataFrame in Python like below:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>COL1</th> <th>COL2</th> <th>COL3</th> </tr> </thead> <tbody> <tr> <td>ABC</td> <td>11</td> <td>NaN</td> </tr> <tr> <td>NaN</td> <td>10</td> <td>NaN</td> </tr> <tr> <td>ABC</td> <td>11</td> <td>N...
<python><pandas><nan><categorical-data>
2022-12-20 09:29:27
2
2,350
dingaro
74,860,885
12,883,179
Multiply different size nested array with scalar
<p>In my python code, I have an array that has different size inside like this</p> <pre><code>arr = [ [1], [2,3], [4], [5,6,7], [8], [9,10,11] ] </code></pre> <p>I want to multiply them by 10 so it will be like this</p> <pre><code>arr = [ [10], [20,30], [40], [5...
<python><arrays><python-3.x><list><nested>
2022-12-20 09:25:08
2
492
d_frEak
74,860,881
6,014,418
group columns based on pattern pySpark
<p>I have input dataframe like this. I want to group the price and qty columns in a dictionary as shown as below.</p> <pre><code>------------------------------------------------------------------------------------- | item_name | price_1 | qty_1 | price_2 | qty_2 | price_3 | qty_3 | url | ------------------...
<python><pyspark><apache-spark-sql>
2022-12-20 09:24:37
1
3,986
Ramineni Ravi Teja
74,860,835
10,829,044
Pandas - compute previous custom quarter wise total revenue and reshape table
<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><aggregate-functions>
2022-12-20 09:20:46
1
7,793
The Great
74,860,787
8,324,092
Having a problem displaying the correct value in the edit workorder QComboBox
<p>I am trying to set the current value of the order_type_combo QComboBox 29: 'Complaint: Damage caused by sewer blockages' instead I'm getting a default value 2: 'Complaint: Sewerage Blockage'. These values are created in a table t_wo_workorders which uses another table wo_type as a dropdown.</p> <p>Here is my code:</...
<python><pyqt5>
2022-12-20 09:15:36
0
429
Gent Bytyqi
74,860,617
5,171,861
How to update read status of an email using MS Graph Api
<p>I am trying to use python and MS Graph Api to read emails from outlook. My intention is to create ticket object in our CRM application whenever any email comes. So, my application is to monitor the mailbox to see if any mails are staying unread. I am able to successfully login and read all unseen email from outlook....
<python><microsoft-graph-api>
2022-12-20 08:59:59
1
419
RatheeshTS
74,860,523
13,987,643
Regex pattern to match flight number and aircraft registration ID
<p>My dataset has Flight number and aircraft reg of the form 'xx-yyy' i.e, two alphanumeric characters 'xx' followed by a hiphen '-' followed by 3 to 5 alphanumeric characters and I want to capture them using regex in python.</p> <p>Examples:</p> <pre><code>1. pk-bkf 2. id-6236 3. ew-43950 4. 8q-iak 5. q2-274 6. pk-gjr...
<python><regex><string>
2022-12-20 08:50:44
1
569
AnonymousMe
74,860,404
3,467,698
How do I collect values into a list in Python standard regex?
<p>I have a string with repeated parts:</p> <pre><code>s = '[1][2][5] and [3][8]' </code></pre> <p>And I want to group the numbers into two lists using <code>re.match</code>. The expected result is:</p> <pre><code>{'x': ['1', '2', '5'], 'y': ['3', '8']} </code></pre> <p>I tried this expression that gives a wrong result...
<python><regex>
2022-12-20 08:41:08
2
9,971
Fomalhaut
74,860,397
10,623,444
Use three transformations (average, max, min) of pretrained embeddings to a single output layer in Pytorch
<p>I have developed a trivial Feed Forward neural network with Pytorch.</p> <p>The neural network uses GloVe pre-trained embeddings in a freezed <code>nn.Embeddings</code> layer.</p> <p>Next, the embedding layer splits into three embeddings. Each split is a different transformation applied to the initial embedding laye...
<python><machine-learning><pytorch><neural-network><word-embedding>
2022-12-20 08:40:29
1
1,589
NikSp
74,860,260
1,254,632
Reading logs from remote server over ssh
<p>I am trying to ssh to a particular port on a server and read the logs but the ssh connection to server closed after authentication immediately when we try to execute it through python subprocess.</p> <p>I am using following command to read the logs:</p> <p>sshpass -p xxxx ssh -tt -v root@xxx.xxx.xxx.xx -p 2200 | tee...
<python><bash><ssh>
2022-12-20 08:26:09
0
8,820
mrutyunjay
74,860,186
5,363,621
replace all values in all columns based on condition
<p>I have a df as below</p> <p><a href="https://i.sstatic.net/ce3aC.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/ce3aC.png" alt="enter image description here" /></a></p> <p>I want to make this df binary as follows</p> <p><a href="https://i.sstatic.net/V9oMw.png" rel="nofollow noreferrer"><img src="htt...
<python><pandas>
2022-12-20 08:18:49
3
915
deega
74,860,172
3,099,733
What's the Python equivalent to JavaScript's Promise.resolve?
<h3><code>Promise</code> in Javascript</h3> <p>As in MDN document:</p> <blockquote> <p>The Promise.resolve() method &quot;resolves&quot; a given value to a Promise. If the value is a promise, that promise is returned; if the value is a thenable, Promise.resolve() will call the then() method with two callbacks it prepar...
<python><asynchronous><concurrent.futures>
2022-12-20 08:17:44
1
1,959
link89
74,860,127
10,849,727
How to remove df rows if the timestamp is inside at least one of given time intervals?
<p>I'm given two (pandas) data frames:</p> <ul> <li><code>data</code>: with time-stamps columns <code>ts</code> and other data columns <code>val1</code>, and <code>val2</code>.</li> <li><code>intervals</code>: with two columns, <code>start</code> and <code>end</code>, that describe a series of time intervals in which <...
<python><pandas>
2022-12-20 08:12:16
2
688
Hadar
74,859,975
10,829,044
elegant way to agg and transform together in pandas groupby
<p>I have a dataframe like as below</p> <pre><code>df = pd.DataFrame( {'stud_id' : [101, 101, 101, 101, 101, 101, 101, 101], 'sub_code' : ['CSE01', 'CSE01', 'CSE01', 'CSE01', 'CSE02', 'CSE02', 'CSE02', 'CSE02'], 'ques_date' : ['13/11/2020', '10/1/2...
<python><pandas><dataframe><group-by><aggregate-functions>
2022-12-20 07:56:25
1
7,793
The Great
74,859,950
20,054,635
Extract numerical values from the String type rows from a column
<p>My Requirement is I have a column which consists of below rows.</p> <p><a href="https://i.sstatic.net/H777R.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/H777R.png" alt="enter image description here" /></a></p> <p>I want to extract only the values(numerical) which starts with $ (Ex- 1620.00 and 4,44...
<python><mysql><pyspark><apache-spark-sql><azure-databricks>
2022-12-20 07:53:32
1
369
Anonymous
74,859,912
8,010,224
Using logical operator between mixed data (include out of range data) is there any rule for this?
<p>recently I studied a lot of information and improvement from leetcode</p> <p>Usually, I prefer <strong>&amp; |</strong> operator than <strong>and or</strong> operator, because of short typo (not really big difference though).</p> <p>But some question of leetcode using logical operator and solve the question really s...
<python><bitwise-operators><logical-operators>
2022-12-20 07:48:12
0
326
Gangil Seo
74,859,403
14,488,888
Using ``exec()`` in a comprehension list
<p>I have a script that can be run independently but sometimes will be externally invoked with parameters meant to override the ones defined in the script. I got it working using <code>exec()</code> (the safety of this approach is not the point here) but I don't understand why it works in a for loop and not in a compre...
<python>
2022-12-20 06:47:20
1
741
Martí
74,859,374
5,881,884
get values of unknown hierarchy of lists and dicts
<p>So lets say I have a bunch of data that is not really known how is structured except that it is a combination of lists, dictionaries and string values. And I would like to extract only the string values (so values of a list, and values in dict and plain string values) and store them in a list.</p> <p>So it could be:...
<python><recursive-datastructures>
2022-12-20 06:43:01
1
5,125
DevB2F
74,859,250
1,942,868
How to use function for each items of multiple array
<p>I have array such as <code>[['C'],['F','D'],['B']]</code></p> <p>Now I want to use functino for each items in multiple array.</p> <p>The result I want is like this <code>[[myfunc('C')],[myfunc('F'),myfunc('D')],[myfunc('B')]]</code></p> <p>At first I tried like this. However, it did not give me the output I was expe...
<python>
2022-12-20 06:26:52
2
12,599
whitebear
74,859,216
9,468,092
ModuleNotFoundError: No module named 'psycopg2' [AWS Glue]
<p>I am using AWS Glue where I'm trying to use psycopg2 in a pyspark script. Since glue does not support psycopg2 in its execution environment, I am passing it in <code>--additional-python-moodules</code>. Which is a way of installing additional Python modules in aws glue.</p> <p>After following the steps mentioned in ...
<python><psycopg2><aws-glue>
2022-12-20 06:23:30
2
890
Dipanshu Chaubey
74,858,983
16,527,170
How to assign particular return variable in function on if/else statement in python
<p>I have two functions as below:</p> <pre><code>def abc(): i = &quot;False&quot; j = &quot;100&quot; return i,j def xyz(): if abc() == &quot;False&quot;: #I want to compare &quot;False&quot; with variable &quot;i&quot; print(&quot;Not Done&quot;) else: abc() == &quot;101&quot; #...
<python><python-3.x><function><return>
2022-12-20 05:52:20
3
1,077
Divyank
74,858,910
10,062,025
How to prevent httpx timeout in python?
<p>I am trying to scrape tokopedia here. When I use raw codes, it works and the json is returned. However when I tried to use it as a variable, it reads time out. website:<a href="https://www.tokopedia.com/samudrasembako/regal-marie-roll-230-gram?extParam=ivf%3Dfalse&amp;src=topads" rel="nofollow noreferrer">https://ww...
<python><httpx>
2022-12-20 05:41:21
1
333
Hal
74,858,843
8,124,392
Can't tweet from Python despite elevated access
<p>I have the following function:</p> <pre><code>import tweepy def tweet_message(text): # Replace these with your own API key and secret api_key = API_KEY api_secret = API_KEY_SECRET access_token = ACCESS_TOKEN access_token_secret = ACCESS_TOKEN_SECRET # Authenticate with Twitter API auth ...
<python><twitter><tweepy>
2022-12-20 05:31:03
1
3,203
mchd
74,858,669
13,016,994
How to import a function or variable from the sibling directory of Django project?
<p>I want to import some functions a constants variables from 5 levels upper of the current app of Django application.</p> <p>My problem is that the package that I want to import from, is outside of the Django application, so Django isn't aware of it.</p> <p><strong>project structure</strong>:</p> <pre><code>├── lawcra...
<python><django><import><python-import>
2022-12-20 04:56:47
0
415
Mahdi Jafari
74,858,587
12,752,172
How to extract values from a list and add them into a new list in python?
<p>I have a data list like below. I need to extra all values after &quot;:&quot; and add those values into a new list. How can I do this?</p> <p><strong>Sample data list</strong></p> <pre><code>list1= ['Company Name: PATRY PLC', 'Contact Name: Jony Deff', 'Company ID: 234567', 'CS ID: 236789', 'MI/MC:', 'Road Code:'] <...
<python><list>
2022-12-20 04:41:21
2
469
Sidath
74,858,585
9,124,950
PySpark error An error occurred while calling count caused by null pointer
<p>I'm getting <code>An error occurred while calling o19972810.count</code> while counting data that i get from JDBC:</p> <pre><code>sql_query = &quot;SELECT.... FROM.... &quot; df = spark.read.format(&quot;jdbc&quot;).option(&quot;url&quot;, con_mysql_source) \ .option(&quot;driver&quot;, &quot;com.mysql.jdbc...
<python><mysql><apache-spark><pyspark>
2022-12-20 04:41:11
0
619
Akbar Noto
74,858,565
5,562,041
Is there a chance that emails are sent in parallel and thus `mail.outbox.clear()` doesn't really clear outbox in my django tests?
<p>I have written django tests to check my outbox emails as shown below</p> <pre><code>class TestX(TestCase): def setUp(self): # Clear outbox. mail.outbox.clear() super().setUp() def tearDown(self): # Clear outbox. mail.outbox.clear() super().tearDown() </code></...
<python><django><unit-testing><python-unittest><django-unittest>
2022-12-20 04:36:19
0
2,249
E_K
74,858,554
13,326,361
ERROR: Could not install packages due to an OSError: [Errno 39] Directory not empty
<p>Dockerfile:</p> <pre class="lang-docker prettyprint-override"><code>FROM python:3.10-slim ENV PYTHONUNBUFFERED 1 WORKDIR /app COPY ./requirements.txt . RUN pip install --trusted-host mirrors.aliyun.com --no-cache-dir --upgrade -r requirements.txt </code></pre> <p>Error during build:</p> <pre class="lang-bash pre...
<python><docker><pip>
2022-12-20 04:33:26
1
2,510
Yue JIN
74,858,392
18,125,194
Efficiently identify an event that occurs between a beginning and ending time stamp
<p>I have two data frames:</p> <p>Data frame one has a timestamp, a factor(amount of power generated) and a location.</p> <p>Data frame two has an event(amount of rain), a timestamp for the beginning time of the event, a time stamp for the ending time of the event and a location.</p> <p>I want to include, in the first ...
<python><pandas><dataframe><sqlite><merge>
2022-12-20 03:58:11
1
395
Rebecca James
74,858,359
10,062,025
How to scrape static page with multiple variants using python?
<p>I am trying to scrape a shopee product display page. Currently I see that there are variants in the single product display page. I am unsure on how to get all variant items and their prices respectively. Please do help.</p> <p>Here's an example of single page with variants 'https://shopee.co.id/ACMIC-Braided-Line-Ka...
<python><selenium-chromedriver>
2022-12-20 03:50:07
2
333
Hal
74,858,280
1,033,591
Is it possible to sort queryset without hitting the db again?
<p>Is there any approach to avoid hitting db when the queryset needs to be returned in a specific order?</p> <p>If a queryset would be returned when a page is loaded</p> <pre><code>qs = Student.objects.all()[start:end] </code></pre> <p>But it also provides UI for users to view the query in ascending or descending order...
<python><django><database>
2022-12-20 03:29:08
1
2,147
Alston
74,858,198
14,488,888
Why does not isinstance() accept a set of types?
<p>It really bugs me why wouldn't <code>isinstance(value, type_or_types)</code> accept a <code>set()</code> of types if it accepts <code>tuple</code>.</p> <p>Basically why:</p> <pre><code>isinstance(1.23, (int, float, complex)) </code></pre> <p>is valid, but:</p> <p><code>isinstance(1.23, {int, float, complex})</code><...
<python>
2022-12-20 03:11:47
0
741
Martí
74,857,811
5,091,964
Python Plotly - How to change the distance between the cursor and the information (annotation) box?
<p>I am using Plotly to chart a Sine wave (see code below). I would like to increase the distance between the cursor and its information box. Any help regarding how to change the distance is appreciated.</p> <pre><code>import plotly.graph_objs as go import numpy as np # Generate data for sine wave x = np.linspace(0, 2...
<python><plotly>
2022-12-20 01:57:35
1
307
Menachem
74,857,784
12,810,223
How to add python files to a new repository in github
<p>I am trying to learn and understand basics of github. For the purpose, I created some files.</p> <ol> <li>try_catch_basics.py</li> <li>reading_from_files.py and countries.txt</li> <li>writing_in_files.py and country.txt</li> </ol> <p>Now, I had created a repository earlier with name try-catch-basics, and included th...
<python><git><github><github-for-windows>
2022-12-20 01:51:26
3
1,874
Shreyansh Sharma
74,857,767
2,280,637
Fails to save model after running GridSearchCV with a scikit pipeline
<p>I have the following toy example to replicate the issue</p> <pre class="lang-py prettyprint-override"><code>import numpy as np import xgboost as xgb from sklearn.datasets import make_regression from sklearn.pipeline import Pipeline from sklearn.model_selection import GridSearchCV X, y = make_regression(n_samples=30,...
<python><scikit-learn><gridsearchcv><scikit-learn-pipeline>
2022-12-20 01:48:17
1
1,255
Li-Pin Juan
74,857,745
8,869,570
How to use visual studio code to debug a Python & C++ program?
<p>I've looked up video tutorials on this that seems to focus just on how to debug a single file.</p> <p>I'm running a simulation code that probably goes through 100s different python and C++ source files. There's a particular spot in a python function that I want to set a breakpoint for. I have set the breakpoint.</p>...
<python><visual-studio-code><visual-studio-debugging>
2022-12-20 01:45:19
1
2,328
24n8
74,857,743
6,488,953
SparkException: Exception thrown in awaitResult for EMR
<p>I tried running my Spark application from EMR, which right now is just the pi calculation in the tutorial doc: <a href="https://docs.aws.amazon.com/emr/latest/ReleaseGuide/emr-spark-application.html" rel="nofollow noreferrer">https://docs.aws.amazon.com/emr/latest/ReleaseGuide/emr-spark-application.html</a></p> <p>I...
<python><apache-spark><pyspark><amazon-emr>
2022-12-20 01:44:51
1
621
Kei
74,857,614
9,668,218
How to write regular expression that covers small and capital letters of a specific word?
<p>I am trying to use regular expression to find a specific word (with small or capital letters) in a text.</p> <p>Examples are:</p> <ul> <li>none</li> <li>None</li> <li>NONE</li> </ul> <p>However, the following code doesn't find the pattern in sample texts.</p> <pre><code>import re txt_list = [&quot;None&quot; , &quo...
<python><regex><string>
2022-12-20 01:16:10
1
1,033
Mohammad
74,857,446
10,443,817
How to specify Python version range in environment.yml file?
<p>Does it make sense to specify range of allowed Python versions in environment.yml file? I got this idea while reading the <a href="https://cloud.google.com/python/docs/reference/bigquery/latest" rel="nofollow noreferrer">Google's Biq Query documentation</a></p> <pre><code>Supported Python Versions Python &gt;= 3.7, ...
<python><anaconda><conda>
2022-12-20 00:40:48
1
4,125
exan
74,857,405
942,543
How to use diffusers with custom ckpt file
<p>Currently I have the current code which runs a prompt on a model which it downloads from huggingface.</p> <pre class="lang-py prettyprint-override"><code>from diffusers import StableDiffusionPipeline, EulerDiscreteScheduler model_id = &quot;stabilityai/stable-diffusion-2&quot; # Use the Euler scheduler here instea...
<python><huggingface><stable-diffusion>
2022-12-20 00:30:15
1
1,604
Mohammad Razeghi
74,857,394
3,247,006
How to run "SELECT FOR UPDATE" for the default "Delete selected" in Django Admin Actions?
<p>I have <strong><code>Person</code> model</strong> as shown below:</p> <pre class="lang-py prettyprint-override"><code># &quot;store/models.py&quot; from django.db import models class Person(models.Model): name = models.CharField(max_length=30) </code></pre> <p>And, this is <strong><code>Person</code> admin</st...
<python><django><django-admin><django-admin-actions><select-for-update>
2022-12-20 00:27:06
1
42,516
Super Kai - Kazuya Ito
74,857,382
11,037,602
How to persist data into a One-to-Many SELF referential with SQLAlchemy?
<p>I'm trying to persist a One-To-Many <strong>self-referential</strong> relationship. My table looks something like this:</p> <pre class="lang-py prettyprint-override"><code>class Users(Base): __tablename__ = &quot;users&quot; id = Column(Integer, primary_key=True, unique=True) connected_ids = Column(Integ...
<python><python-3.x><sqlalchemy><psycopg2>
2022-12-20 00:24:28
2
2,081
Justcurious
74,857,217
7,209,826
Scrapy. Every time i yield request another function is triggered as well. Cant see why
<p>Here is my spider It is supposed to assign a list attained from google sheet to global variable <code>denied</code>. In the code this function is called just once , but in the logs it is executed as many times as post request to endpoint is executed (<code>send_to_endpoint()</code>). Where is the error?</p> <pre><co...
<python><python-3.x><function><python-requests><scrapy>
2022-12-19 23:51:27
1
1,119
JBJ
74,857,162
13,597,979
Avoiding garbage collection for Tkinter PhotoImage (Python)
<p>I'm using MacOS v 12.6 and Python v 3.9.6. Why does the code below garbage collect the image unless the commented-out line is uncommented? Isn't using <code>self.img</code> supposed to be enough to avoid garbage collection?</p> <pre class="lang-py prettyprint-override"><code>from tkinter import Tk, Label from PIL im...
<python><tkinter><tkinter-photoimage>
2022-12-19 23:42:41
1
550
TimH
74,857,133
15,239,717
How can I use Date Range with Sum and Order By in Django
<p>I am working on a project where I have an Income Model with description among other fields as shown below. The description is a choice field and I want to use Date Range to Sum by each description. i.e. I would want to sum all amount for each description and display their total in HTML Template.</p> <p>Below is what...
<python><django>
2022-12-19 23:38:25
1
323
apollos
74,857,105
1,311,704
"scalene --version" in a Makefile
<p>On Mac OS X, running <code>scalene --version</code> (a python package) on the command line works but running the same line in a Makefile gives an error.</p> <pre><code>$ scalene --version Scalene version 1.5.15 (2022.11.16) </code></pre> <p>Makefile:</p> <pre><code>check-deps: scalene --version </code></pre> <pr...
<python><makefile>
2022-12-19 23:35:12
1
1,087
offwhitelotus
74,857,095
1,551,027
How to hide the mouse pointer with pyAutoGUI?
<p>Is there a way to hide the mouse pointer with pyAutoGUI?</p> <pre class="lang-py prettyprint-override"><code>import time import pyautogui pyautogui.hidePointer() time.sleep(5) pyautogui.showPointer() </code></pre> <p>If not, is there another way to hide the mouse pointer with another library or in plain python, p...
<python><pyautogui>
2022-12-19 23:33:36
1
3,373
Dshiz
74,856,602
8,179,586
Passing a list as parameter for IN statement using named arguments
<p>How can I pass a list to an <strong>IN</strong> statement in a query using psycopg's named arguments?</p> <p>Example:</p> <pre class="lang-py prettyprint-override"><code>cur.execute(&quot;&quot;&quot; SELECT name FROM users WHERE id IN (%(ids)s) &quot;&quot;&quot;, {&quot;ids&...
<python><psycopg3>
2022-12-19 22:17:36
0
331
Leonardo Freua
74,856,584
12,242,085
How to fill NaN only in numeric variables if that variable in on list in Python Pandas?
<p>I have Pandas DataFrame like below:</p> <p>data types:</p> <ul> <li>COL1 - numeric</li> <li>COL2 - object</li> <li>COL3 - numeric</li> </ul> <p>TABLE 1</p> <pre><code>COL1 | COL2 | COL3 -----|------|------ 123 | AAA | 99 NaN | ABC | 1 111 | NaN | NaN ... | ... | ... </code></pre> <p>And I have also list of ...
<python><pandas><missing-data><numeric><fillna>
2022-12-19 22:15:23
1
2,350
dingaro
74,856,506
4,893,099
Extracting substring in cloud functions
<p>I am uploading csv files stored in google cloud storage into bigquery tables.</p> <p>this is some part of my function:</p> <pre><code>def upload_to_bq_from_gcs(event, context): filename = event['name'] input_bucket = event['bucket'] output_bucket = &quot;sales_2020&quot; </code></pre> <p>file names in th...
<python><regex><google-cloud-functions>
2022-12-19 22:03:43
1
563
Sana
74,856,449
20,793,070
How to filter df by value list with Polars?
<p>I have Polars df from a csv and I try to filter it by value list:</p> <pre class="lang-py prettyprint-override"><code>import polars as pl my_list = [1, 2, 4, 6, 48] df = ( pl.read_csv(&quot;bm.dat&quot;, separator=';', new_columns=[&quot;cid1&quot;, &quot;cid2&quot;, &quot;cid3&quot;]) .lazy() .filter(...
<python><dataframe><csv><python-polars>
2022-12-19 21:57:28
1
433
Jahspear
74,856,414
6,054,404
remove duplicate rows in a numpy array
<p>I have a numpy array:</p> <pre><code> arr = array([[991.4, 267.3, 192.3], [991.4, 267.4, 192.3], [991.4, 267.4, 192.3], ..., [993.5, 268. , 192.6], [993.5, 268. , 192.6], [993.5, 268.1, 192.6]]) </code></pre> <p>you can see th...
<python><numpy><duplicates>
2022-12-19 21:52:50
2
1,993
Spatial Digger
74,856,325
7,385,923
rename files inside another directory in python
<p>I'm working with python and I need to rename the files that I have inside a directory for example:</p> <pre><code>C:\Users\lenovo\Desktop\files\file1.txt C:\Users\lenovo\Desktop\file\file2.txt C:\Users\lenovo\Desktop\files\file3.txt </code></pre> <p>I have these 3 files inside the files folder, and I want to change ...
<python><file>
2022-12-19 21:42:40
3
1,161
FeRcHo
74,856,316
6,186,333
Add text into string between single quotes using regexp
<p>I am trying to use Python to add some escape characters into a string when I print to the terminal.</p> <pre class="lang-py prettyprint-override"><code>import re string1 = &quot;I am a test string&quot; string2 = &quot;I have some 'quoted text' to display.&quot; string3 = &quot;I have 'some quotes' plus some more t...
<python><regex>
2022-12-19 21:40:27
1
2,914
SandPiper
74,856,309
17,696,880
Why does capturing the capture group identified with this regex search pattern fail?
<pre class="lang-py prettyprint-override"><code>import re input_text_substring = &quot;durante el transcurso del mes de diciembre de 2350&quot; #example 1 #input_text_substring = &quot;durante el transcurso del mes de diciembre del año 2350&quot; #example 2 #input_text_substring = &quot;durante el transcurso del mes 1...
<python><python-3.x><regex><replace><regex-group>
2022-12-19 21:39:50
1
875
Matt095
74,856,139
15,781,591
How to add independent titles or headers to dropdown menus created using ipywidgets?
<p>I am using the following code to produce a tool in a Jupyter Notebook that allows the user to print a statement describing which coloured fruit they would like to try:</p> <pre><code>import ipywidgets as widgets from ipywidgets import interactive fruits = ['Banana', 'Apple','Lemon','Orange'] colors = ['Blue', 'Red'...
<python><jupyter-notebook><ipywidgets>
2022-12-19 21:21:57
1
641
LostinSpatialAnalysis
74,855,865
8,262,535
Python subprocess on Linux: no such file or directory
<p>I am trying to get the install location of conda. This works fine on Windows:</p> <pre><code>conda_path = subprocess.check_output('where anaconda').decode(&quot;utf-8&quot;).strip() </code></pre> <p>In a linux shell <code>whereis conda</code> works. <code>os.system(&quot;whereis conda&quot;)</code> returns zero.</p>...
<python><linux><subprocess>
2022-12-19 20:51:51
1
385
illan
74,855,810
1,245,262
How can I import an csv file into SQLite3 from within Python using subprocess
<p>I'm currently running legacy code that attempts to convert a csv file into a SQL database from within Python. The file is too big for Pandas, so the code is running sqlite3 in a Python subprocess like this:</p> <pre><code> result = subprocess.run([&quot;sqlite3&quot;, str(db_name), '-cmd', &quot;.mode csv&quot;, ...
<python><sqlite><csv>
2022-12-19 20:45:23
0
7,555
user1245262
74,855,789
4,670,369
How can I create a MARKET order with SL/TP in Bybit using CCXT?
<p>I need to make this code works for MARKET orders, I can't find how to get it.</p> <pre><code>exchange.create_order( symbol='ADA/USDT:USDT', type='market', side='sell', amount=60, params={ 'leverage': 1, 'stopLossPrice': SL_PRICE, 'takeProfitPrice': TP_PRICE, }, ) </code></pre>
<python><trading><ccxt>
2022-12-19 20:42:22
0
381
Carlos Diaz
74,855,742
1,877,002
Is itertools combinations always sorted
<p>Suppose I have <strong>sorted</strong> array from which I want to get all <code>itertools.combinations</code> of, say, 3 elements.</p> <pre><code>from itertools import combinations start = 5 end = start+4 some_pos_number = 3 inds = list(combinations(range(start,end),some_pos_number)) &gt;&gt;&gt;inds [(5, 6, 7), (5...
<python><python-3.x>
2022-12-19 20:37:12
1
2,107
Benny K
74,855,740
10,969,942
How to assign subpool (m workers) of multiprocessing pool (n workers with m < n) to some task in python?
<p>I have usecase like following: I have total <code>20</code> multiprocessing workers. I can give all resources to <code>task1</code>. However, <code>task2</code> has lower priority and I can at most give it half of total resources. How to assign subpool (m workers) of multiprocessing pool (n workers with m &lt; n) to...
<python><design-patterns><multiprocessing><python-multiprocessing>
2022-12-19 20:36:48
1
1,795
maplemaple
74,855,601
16,378,913
Creating balanced dataset for YOLO v5 with each image having multiple annotations
<p>Currently using the YOLO v5 code from this <a href="https://github.com/ultralytics/yolov5" rel="nofollow noreferrer">https://github.com/ultralytics/yolov5</a> in which each txt has a line referring to the <code>&lt;object-class&gt; &lt;x&gt; &lt;y&gt; &lt;width&gt; &lt;height&gt;</code> (image below). Each image has...
<python><object-detection><yolo><yolov5>
2022-12-19 20:17:36
0
365
maximus
74,855,444
2,301,970
Sum data inside selection in bokeh image plot
<p>I am starting with bokeh and I wonder if anyone could point me in the right direction.</p> <p>I have an image (2D array). Using the gallery example:</p> <pre><code>import numpy as np from bokeh.plotting import figure, show from bokeh.models import ColumnDataSource, RangeTool from bokeh.layouts import column x = np...
<python><plot><hyperlink><bokeh><interactive>
2022-12-19 19:59:57
1
693
Delosari
74,855,305
7,747,759
How to input a vector of arguments in a function in python?
<p>I have a function, which takes a variable number of inputs. For example, the functions may look like <code>fn(a0,a1,...)</code>. Now, I have a vector <code>A=[a0,a1,...]</code>, and I want to call <code>fn</code>, but I'm not sure how to dynamically set the number of inputs (if handling outside of the function). I d...
<python><python-3.x>
2022-12-19 19:44:18
0
511
Ralff
74,855,153
3,641,140
How to add external libraries to python project in Visual Studio
<p>My python project has dependencies on packages that exist on the local file system in folder X (i.e. not installed form the internet). I'd like to add these packages (source code) to the python environment for my project. How can this be done?</p> <p>I've add folder X to &quot;Search Paths&quot; in the Solution Expl...
<python><visual-studio>
2022-12-19 19:27:24
1
319
SuperUser01
74,854,903
8,968,801
Not Required in Pydantic's Base Models
<p>Im trying to accept data from an API and then validate the response structure with a Pydantic base model. However, I have the case where sometimes some fields will not come included in the response, while sometimes they do. The problem is, when I try to validate the structure, Pydantic starts complaining about those...
<python><python-typing><pydantic>
2022-12-19 18:58:37
1
823
Eddysanoli
74,854,871
2,094,707
Python requests redirect to GET instead of POST
<p>I am trying to call the url of a REST API for which both GET and POST requests are possible. I want to send a POST request. If I run my request through the ThunderClient plugin everything works fine. I can send a POST request and get the correct data.</p> <p>If I send my request in python like this:</p> <pre class="...
<python><http><python-requests>
2022-12-19 18:56:20
1
3,271
Stein
74,854,825
2,278,511
Raspberry Pi 4: 2x UART device + display touch; I can't see TOUCH device
<p>i have quite specific SW / HW problem probably related with serial communication...</p> <p>My project is based on Raspberry Pi 4 + 7&quot; Touch screen + ESP32 microcontroller and i have problem with screen touch function.</p> <p><strong>Project detailed architecture</strong>:</p> <ol> <li>on Raspberry Pi is running...
<python><esp32><pyserial><uart><raspberry-pi4>
2022-12-19 18:52:36
1
408
lukassliacky
74,854,786
12,060,672
Reload stylesheets in PyQT / PySide after change object name
<p>Good day, colleagues, I have a styles, example:</p> <pre><code>#button_1 { background-color: green; } #button_2 { background-color: red; } </code></pre> <p>I have 3 objects:</p> <pre><code>button_1 = QPushButton() button_2 = QPushButton() button_3 = QPushButton() </code></pre> <p>And I want after click on <code...
<python><pyqt><pyside>
2022-12-19 18:49:34
2
321
antipups
74,854,728
1,315,621
Start multiple vunicorn apps in python
<p>I need to create a Python application that handles both API (<code>fastAPI</code>) and sockets (<code>socketio</code>). I can't find a way to start both the vunicorn applications in the same python script. Note that I can replace vunicorn with any other library that would allow me to fix this. Code:</p> <pre><code>i...
<python><sockets><fastapi><uvicorn>
2022-12-19 18:43:59
1
3,412
user1315621
74,854,623
7,576,002
GSSAPI Docker Installation Issue - /bin/sh: 1: krb5-config: not found
<p>I successfully tried out GSSAPI to generate kerberos tickets in my Python app locally on my Mac. Now I am trying to package this as a Docker image.</p> <p>When I try to build the image I keep getting this error:</p> <pre><code>------ ...
<python><kerberos><gssapi>
2022-12-19 18:35:42
2
1,129
KSS
74,854,464
9,220,463
efficient way to disconnect graphs while maximising edges weight
<p>Given a connected graph and a list of N-assigned vertexes, I want to find an efficient way to create N subgraphs, each containing one of the assigned vertexes. To achieve that, we can prune the edges. However, we should prune less edge weight as possible.</p> <p>For example, let's start with the following graph. We ...
<python><r><optimization><graph><igraph>
2022-12-19 18:20:04
2
621
riccardo nizzolo
74,854,302
12,288,003
AttributeError: 'Query' object has no attribute 'is_clause_element' when joining table with query
<p><strong>AttributeError: 'Query' object has no attribute 'is_clause_element' when joining table with query</strong></p> <p>I have a query that counts the amount of keywords a company has and then sorts them by the amount of keywords they have.</p> <pre><code>query_company_ids = Session.query(enjordplatformCompanyToKe...
<python><sqlalchemy>
2022-12-19 18:04:07
1
339
user12288003
74,853,917
9,783,831
repr function in swig for python
<p>I have a Swig wrapper to use in python. For one of my class, I have created a <code>repr</code> function as follows</p> <pre><code>%module myModule %{ #include &lt;string&gt; #include &lt;sstream&gt; %} %extend myClass { std::string __repr__() { std::ostringstream ss; ss &lt;&lt; &quot;MyClass(attr1...
<python><swig>
2022-12-19 17:25:34
1
407
Thombou
74,853,835
3,849,761
How to do type casting for special datatypes in Python
<p>I'm trying to determine the type of value in a dictionary which comes from a outside of a function sth like this;</p> <pre><code>def create_new_ds(sep_labels: dict, upper_limit: int, ds: bytearray, ref_lbl: str, rnd: bool) -&gt; []: desired_lbls = sep_labels.keys() if rnd: sep_labels[ref_lbl] </code>...
<python><variables><casting>
2022-12-19 17:19:03
1
1,058
livan3li
74,853,634
4,534,466
Kedro, running inference on user input
<p>I have a pipeline with the model I want to use. Outside of the project, I have an <code>app.py</code> file where I'm going to create the UI/UX for my users to run my model. Right now I'm just using a sample string but later on, you can imagine that there will be a textbox for users to type.</p> <p>How can I pass the...
<python><kedro><mlops>
2022-12-19 16:58:13
0
1,530
João Areias
74,853,453
11,978,973
Days till year end
<p>I need to find the numbers of days left from today till the end of the year. I know I can calculate this by simply subtracting today's date from the December 31st of this year, ie:</p> <pre><code>current_year = dt.datetime.now().year days_left = dt.date(current_year, 12, 31) - dt.datetime.now().date() </code></pre> ...
<python><datetime><timedelta>
2022-12-19 16:44:01
1
364
Zephyrus
74,853,108
7,168,098
spaCy: generalize a language factory that gets a regular expression to create spans in a text
<p>Working with spaCy it is possible to define spans in a document that correspond to a regular expression matching on the text. I would like to generalize this into a language factory.</p> <p>The code to create a span could be like this:</p> <pre><code>nlp = spacy.load(&quot;en_core_web_sm&quot;) text = &quot;this is ...
<python><spacy>
2022-12-19 16:11:05
1
3,553
JFerro
74,852,879
12,366,110
Finding the average of the x component of an array of coordinates, based on the y component
<p>I have the following example array of x-y coordinate pairs:</p> <pre><code>A = np.array([[0.33703753, 3.], [0.90115394, 5.], [0.91172016, 5.], [0.93230994, 3.], [0.08084283, 3.], [0.71531777, 2.], [0.07880787, 3.], [0.0...
<python><numpy><vectorization>
2022-12-19 15:53:15
4
14,636
CDJB