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,983,664
17,696,880
Failure to identify and concatenate using a capture group identified with regex as reference
<pre class="lang-py prettyprint-override"><code>import re input_text = 'desde las 15:00 del 2002-11-01 hasta las 16 hs' #example </code></pre> <p>I have placed the pattern <code>(?:(?&lt;=\s)|^)</code> in front so that it only detects if it is the beginning of the string or if there are one or more whitespaces in fron...
<python><python-3.x><regex><replace><regex-group>
2023-01-02 14:35:23
1
875
Matt095
74,983,650
5,359,846
Playwright - how to find input that will contain a value?
<p>I have an Input element with value like '123 456'.</p> <p>How can I validate that the Input element contains '123' using an Expect?</p> <pre><code>input_locator = 'input[id=&quot;edition&quot;]' expect(self.page.locator(input_locator).first). to_have_value('123', timeout=20 * 1000) </code></pre> <p>I got this error:...
<python><playwright><playwright-python>
2023-01-02 14:33:23
1
1,838
Tal Angel
74,983,580
1,930,543
connected multiselect filters in streamlit
<p>I would like to connect the selection options for streamlit multiselect.</p> <p>Lets assume I have the following dataframe</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Name</th> <th>Color</th> </tr> </thead> <tbody> <tr> <td>A</td> <td>red</td> </tr> <tr> <td>A</td> <td>blue</td> </tr...
<python><streamlit>
2023-01-02 14:27:33
2
5,951
dimitris_ps
74,983,222
18,313,588
Convert dictionaries in pandas dataframe to list
<p>I have a dataframe</p> <pre><code>fruit1 fruit2 [banana,apple,orange] [apple,nuts,strawberry] [apple,mango,grape] [apple,mango,grape,guava] </code></pre> <p>My code for adding the two additional columns is</p> <pre><code> df[&quot;fruits_added&quot;] = df.apply(lambda row: set(row.fruit2...
<python><python-3.x><pandas><dataframe>
2023-01-02 13:51:24
2
493
nerd
74,983,206
11,885,361
can't replace duplicate values with new values in xlsx with pandas
<p>I have an <code>xlsx</code> file containing too much data. however the data contains <code>duplicate</code> values in column named <code>UniversalIDS</code> which I wanted to replace it with a randomly generated <code>IDS</code> with <code>Pandas</code>.</p> <p>So far I've tried different scenarios which I googled b...
<python><python-3.x><excel><pandas><dataframe>
2023-01-02 13:49:03
2
630
hanan
74,983,103
2,520,186
Networkx: Replacing labels of nodes
<p>I have the following minimal code:</p> <pre><code>import networkx as nx import matplotlib.pyplot as plt G = nx.DiGraph() #G = nx.Graph() #G = nx.path_graph(4) pos1 = {0: (0, 0), 1: (2, 1), 2: (2, 0), 3: (2,-1)} G.add_edge(0, 1) G.add_edge(0, 3) G.add_edge(1, 2) G.add_edge(2, 3) # First Network plt.figure(0) nx.dr...
<python><python-3.x><matplotlib><graph><networkx>
2023-01-02 13:38:08
2
2,394
hbaromega
74,983,081
2,410,376
How do I mock an AWS lambda start_execution in Python?
<p>I am testing a function whose very last line of code starts the execution of an AWS lambda. This part is not relevant to my test, so I want to mock the call to <code>client.start_execution()</code> so that instead of actually triggering AWS it returns None.</p> <p>Is there a way to use pytest mocks to simply replac...
<python><amazon-web-services><lambda><pytest>
2023-01-02 13:35:39
2
510
A R
74,982,962
4,454,635
Read image alt text with pandas.read_html
<p>Is there a way using <code>pandas.read_html</code> to get the <code>img alt</code> text from an image ? The page I am scrapping just replaced some texts with pictures, and the old text is now the <code>alt</code> text for those images. Here is an example:</p> <pre><code>&lt;td&gt; &lt;div&gt;... &lt;a href=&quot;/in...
<python><html><pandas>
2023-01-02 13:23:29
2
3,186
horace_vr
74,982,808
1,947,542
Is it possible to perform sparse - dense matrix multiplication in Tensorflow for rank 3 matrices?
<p>I am trying to perform sparse matrix - dense matrix multiplication in TensorFlow, where both matrices have a leading batch dimension (i.e., rank 3). I am aware that TensorFlow provides the tf.sparse.sparse_dense_matmul function for rank 2 matrices, but I am looking for a method to handle rank 3 matrices. Is there a ...
<python><tensorflow><sparse-matrix>
2023-01-02 13:07:59
1
441
Mustafa Orkun Acar
74,982,743
3,668,129
How to hide (or show) some of plotly colors
<p>I have simple dataframe with 3 plots:</p> <pre><code>import plotly.express as px import pandas as pd import numpy as np N = 100 random_x = np.linspace(0, 1, N) random_y0 = np.random.randn(N) + 5 random_y1 = np.random.randn(N) random_y2 = np.random.randn(N) - 5 df_all = pd.DataFrame() df = pd.Data...
<python><python-3.x><plotly><plotly-dash>
2023-01-02 13:02:13
1
4,880
user3668129
74,982,401
17,267,064
How to add data in Pandas Dataframe dynamically using Python?
<p>I wish to extract the data from a txt file which is given below and store in to a pandas Dataframe that has 8 columns.</p> <pre><code>Lorem | Ipsum | is | simply | dummy text | of | the | printing | and typesetting | industry. | Lorem more | recently | with | desktop | publishing | software | like | Aldus Ipsum | ha...
<python><pandas><dataframe>
2023-01-02 12:24:55
4
346
Mohit Aswani
74,982,353
8,510,149
Problems with version control for dictionaries inside a python class
<p>I'm doing something wrong in the code below. I have a method (update_dictonary) that changes a value or values in a dictionary based on what is specificed in a tuple (new_points).</p> <p>Before I update the dictionary, I want to save that version in a list (history) in order to be able to access previous versions. ...
<python><dictionary><python-class>
2023-01-02 12:19:29
1
1,255
Henri
74,982,325
1,807,163
Poetry clean/remove package from env after removing from toml file
<p>I installed a package with <code>poetry add X</code>, and so now it shows up in the toml file and in the venv (mine's at <code>.venv/lib/python3.10/site-packages/</code>).</p> <p>Now to remove that package, I could use <code>poetry remove X</code> and I know that would work properly. But sometimes, it's easier to ju...
<python><python-poetry>
2023-01-02 12:16:37
1
5,201
rasen58
74,981,810
6,346,482
Pandas: Transform with custom maximum function
<p>I know that I can use transform for transforming every element in a group in a dataframe into the minimum value. This is done with something like</p> <pre><code>df.groupby(level=0).transform('min') </code></pre> <p>My problem is, that all of my cells are strings, in fact tuplelike strings with floats inside, like &q...
<python><python-3.x><pandas><transform>
2023-01-02 11:24:05
2
804
Hemmelig
74,981,801
6,263,000
python-oracledb thin client returns DPY-6000
<p>I'm trying to run a Python app packaged in a Docker container on an OCI <code>Ampere</code> node.</p> <p>Environment:</p> <ul> <li>base image: <code>python:3.10.9-slim</code> built using <code>buildx</code> for <code>arm64</code></li> <li>client library: <code>oracledb==1.2.1</code></li> <li>Docker version: <code>20...
<python><docker><arm64><oracle-cloud-infrastructure><oracle-autonomous-db>
2023-01-02 11:23:07
1
609
Babak Tourani
74,981,728
19,238,204
Check Whether my Plot of Bounded Region and Its Revolution toward x-axis and toward y-axis are correct
<p>I have tried this code to be able to plot a bounded region, between y=6x and y= 6x^{2}</p> <p>Please check whether it is correct or not...</p> <ol> <li><p>I want the bounded region to be revolved around x axis and y axis, become solid of revolution.</p> </li> <li><p>I want to add a legend so people will know the blu...
<python><numpy><matplotlib>
2023-01-02 11:14:56
1
435
Freya the Goddess
74,981,726
11,349,966
How to insert image blob in openpyxl
<p>In my web app I'am using openpyxl to create or modify excels and there's a part of my web that i need to insert image with a blob or base64 ?, I dont see anything related in how to inserting image in openpyxl except in a method where i need to pass a relative or absolute path of the image. i don't want to save the i...
<python><flask><openpyxl>
2023-01-02 11:14:42
1
1,114
Mark Anthony Libres
74,981,656
12,752,172
How to pass list data into insert statement in SQL server using python?
<p>I'm new to python and creating a python app to insert data into the SQL server table. I'm trying it in the following way but it gives me an error.</p> <p><strong>This is my code</strong></p> <pre><code>import pyodbc conn = pyodbc.connect('Driver={SQL Server};' 'Server=.\SQLEXPRESS;' ...
<python><list>
2023-01-02 11:08:02
1
469
Sidath
74,981,572
979,974
Python train convolutional neural network on csv numpy error input shape
<p>I would like to train a convolutional neural network autoencoder on a csv file. The csv file contains pixel neighborhood position of an original image of 1024x1024. When I try to train it, I have the following error that I don't manage to resolve. <code>ValueError: Input 0 of layer max_pooling2d is incompatible with...
<python><keras><conv-neural-network>
2023-01-02 10:59:35
1
953
user979974
74,981,558
6,799,513
Error Updating Python3 pip AttributeError: module 'lib' has no attribute 'OpenSSL_add_all_algorithms'
<p>I'm having an error when installing/updating any pip module in python3. Purging and reinstalling <code>pip</code> and every package I can thing of hasn't helped. Here's the error that I get in response to running <code>python -m pip install --upgrade pip</code> specifically (but the error is the same for attempting ...
<python><ubuntu><pip><windows-subsystem-for-linux>
2023-01-02 10:57:36
4
1,225
patrick
74,981,514
10,695,613
Most efficient way to read a huge parquet file into memory in Python
<p>Ideally, I would like to have the data in a dictionary. I am not even sure if a dictionary is better than a dataframe in this context. After a bit of research, I found the following ways to read a parquet file into memory:</p> <ul> <li>Pyarrow (Python API of Apache Arrow):</li> </ul> <p>With pyarrow, I can read a pa...
<python><pandas><dictionary><parquet><pyarrow>
2023-01-02 10:53:12
0
405
BovineScatologist
74,981,481
6,387,095
DRF .as_viewset on {'post': 'list'} return attribute error?
<p>I am trying to send some text: example: &quot;Hello World&quot; to DRF end-point.</p> <p>This endpoint on receiving this text is to send me a e-mail with the text.</p> <p>When I hit the end-point with Postman, I get the error:</p> <blockquote> <p>Internal Server Error: /api/errors Traceback (most recent call last): ...
<python><django><django-rest-framework>
2023-01-02 10:48:56
1
4,075
Sid
74,981,145
2,245,136
Handle KeyError exception and get dictionary name which caused the trouble
<p><code>KeyError</code> exception object contains <code>args</code> attribute. This is a list and it contains a key name which user tries to access within a dictionary. Is it possible to figure out dictionary name which does not contain that key and which caused an exception while trying to access the key within it?<...
<python><exception><keyerror>
2023-01-02 10:14:03
1
372
VIPPER
74,981,113
18,972,785
Is it good to use Python garbage collecter inside the program?
<p>I have written an NLP GUI program with python. Everything works well and there is no problem. Since the program should process large corpus and make graphs, in order to free memory and let the processes to fit inside the RAM, i have used <code>gc.collect()</code> in several parts to delete some big variables. My que...
<python><garbage-collection>
2023-01-02 10:10:58
0
505
Orca
74,981,011
12,690,313
T5 model generates short output
<p>I have fine-tuned the T5-base model (from hugging face) on a new task where each input and target are sentences of 256 words. The loss is converging to low values however when I use the <code>generate</code> method the output is always too short. I tried giving minimal and maximal length values to the method but it ...
<python><pytorch><huggingface-transformers><huggingface-tokenizers>
2023-01-02 10:00:42
1
1,341
Tamir
74,980,841
516,268
What is the idiomatic way to write pandas groupby result to DataFrame?
<p>Source df as like:</p> <pre><code>EventType User Item View A 1 View B 1 Like C 2 View C 2 Buy A 1 </code></pre> <p>We have 5 users: A B C D E</p> <p>We have 6 Items: 1 2 3 4 5 6</p> <p>I would like to generate new df like</p> <pre><code>Event_Type Event_...
<python><pandas>
2023-01-02 09:40:19
1
1,327
l4rmbr
74,980,790
17,530,552
How to correctly plot a linear regression on a log10 scale?
<p>I am plotting two lists of data against each other, namely <code>freq</code> and <code>data</code>. Freq stands for frequency, and data are the numeric observations for each frequency.</p> <p>In the next step, I apply the ordinary linear least-squared regression between <code>freq</code> and <code>data</code>, using...
<python><matplotlib><linear-regression>
2023-01-02 09:35:15
2
415
Philipp
74,980,768
7,713,770
How to communicate django api with frontend react native?
<p>I have a django application and I have a react native app. I am running the android emulator from android studio.</p> <p>And now I try to connect the backend with the frontend. I studied the example from: <code> https://reactnative.dev/docs/network</code></p> <p>And the example url: <a href="https://reactnative.dev/...
<python><django><react-native><android-studio>
2023-01-02 09:33:00
2
3,991
mightycode Newton
74,980,748
10,829,044
pandas groupby and do categorical ordering to drop duplicates
<p>I have a dataframe like as below</p> <pre><code>df = pd.DataFrame({ &quot;Name&quot;: [&quot;Tim&quot;, &quot;Tim&quot;, &quot;Tim&quot;, &quot;Tim&quot;, &quot;Tim&quot;,'Jack','Jack','Jack'], &quot;Status&quot;: [&quot;A1&quot;, &quot;E1&quot;, &quot;B3&quot;, &quot;D4&quot;, &quot;C90&quot;,&quot;...
<python><pandas><list><dataframe><group-by>
2023-01-02 09:30:09
2
7,793
The Great
74,980,738
13,987,643
Get last n elements of list from current index
<p>I have a list like this : <code>[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]</code> and I want to extract the previous 'n' elements from a particular index.</p> <p>For eg: If I take index 7, I have the element 8 in it. And for <code>n = 3</code>, I want to get the previous 3 elements starting backwards from index 7. The result w...
<python><list>
2023-01-02 09:29:24
1
569
AnonymousMe
74,980,682
16,698,040
"Document interning" in Mongo
<p>I a lot of documents which I know will rarely change and are very similar to each other, specifically I know they have a nested field in the document that is always the same (for some of them)</p> <pre class="lang-json prettyprint-override"><code>{ &quot;docid&quot;: 1 &quot;nested_field_that_will_always_be_the_...
<python><mongodb><pymongo>
2023-01-02 09:21:47
1
475
Stack Overflow
74,980,665
8,037,521
Plotly non-interactive image with sliders
<p>I have managed to make a plotly graph based on this code sample from Plotly documentation:</p> <pre><code>import plotly.graph_objects as go import numpy as np # Create figure fig = go.Figure() # Add traces, one for each slider step for step in np.arange(0, 5, 0.1): fig.add_trace( go.Scatter( ...
<python><plotly>
2023-01-02 09:20:02
0
1,277
Valeria
74,980,645
13,709,317
Python equivalent of C struct for writing bytes to a file
<p>What could be the simplest Python equivalent to the following C code?</p> <pre class="lang-c prettyprint-override"><code>#include &lt;stdio.h&gt; int main(void) { struct dog { char breed[16]; char name[16]; }; struct person { char name[16]; int age; struct dog pet...
<python><file><struct>
2023-01-02 09:18:13
1
801
First User
74,980,509
2,998,077
Iteration in a dictionary with lists as values
<p>A dictionary with lists as values and ascending dates as keys, that I want to understand how many times M in the total past times P, cover some of the current numbers.</p> <p>For example, for L19981120: [2, 3, 5]: 2 numbers in the [2, 3, 5], appeared 3 times in the past 9 times.</p> <p>The code looks verbose, and on...
<python><loops><iteration>
2023-01-02 08:58:59
2
9,496
Mark K
74,980,332
6,057,371
Python get num occurrences of elements in each of several lists
<p>I have a 4 corpuses:</p> <pre><code>C1 = ['hello','good','good','desk'] C2 = ['nice','good','desk','paper'] C3 = ['red','blue','green'] C4 = ['good'] </code></pre> <p>I want to define a list of words, and for each - get the occurances per corpus. so if</p> <blockquote> <p>l= ['good','blue']</p> </blockquote> <p>I wi...
<python><pandas><list><dataframe><collections>
2023-01-02 08:35:35
3
2,050
Cranjis
74,980,251
126,833
redirect_uri is always localhost when json and console have it as a proper domain of localhost
<p>I went through <a href="https://stackoverflow.com/questions/11485271/google-oauth-2-authorization-error-redirect-uri-mismatch">11485271</a> but not avail.</p> <p>I see</p> <p><a href="https://i.sstatic.net/fWUX3.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/fWUX3.png" alt="enter image description he...
<python><oauth-2.0><google-developers-console><google-client><google-client-login>
2023-01-02 08:23:34
0
4,291
anjanesh
74,980,150
1,737,830
Imported function fails to save output to a file; succeeds when called in-place
<p>I'm trying to save output processed by Python to a text file. I started with approach #1 described below. It didn't work (details below), so I tried to isolate the failing function and launch it with predefined array to be processed (approach #2). It didn't work either. So, I tried to completely extract the code and...
<python><windows-subsystem-for-linux>
2023-01-02 08:08:46
1
2,368
AbreQueVoy
74,980,004
507,974
Output video with same settings as input video python OpenCV
<p>I have a video I read in to detect opbjects and generate an video that will at a later time be used as an monotone alpha channel for the original video.</p> <p>I get the current input video with:</p> <pre><code>cap = cv2.VideoCapture('file.mp4') </code></pre> <p>From here you are supposed to create a VideoWriter to ...
<python><opencv><video><video-processing>
2023-01-02 07:47:34
1
420
Skyler
74,979,976
2,092,445
Dynamodb query using FilterExpression involving nested attributes with boto3
<p>I have below data in my dynamodb table with <em>name</em> as partition-key.</p> <pre><code>{ &quot;name&quot;:&quot;some-name&quot;, &quot;age&quot;: 30, &quot;addresses&quot;:[ &quot;addr-1&quot;, &quot;addr-2&quot; ], &quot;status&quot;:&quot;active&quot; } </code></pre> <p>I ha...
<python><amazon-dynamodb><boto3><dynamodb-queries>
2023-01-02 07:43:32
1
2,264
Naxi
74,979,873
9,407,941
Consistently getting `None` for the `gdb.Field.name` for a C++ function's parameters
<p>I'm trying to use <code>gdb</code>'s Python API to extract C++'s function parameters' names, and am consistently getting <code>None</code> when I query the <code>name</code> attribute of function parameters as <code>gdb.Field</code> objects.</p> <p>On a higher level, I need to distinguish between named and anonymous...
<python><c++><gdb><trace>
2023-01-02 07:28:35
0
4,168
dROOOze
74,979,760
10,748,412
How to not save into database if document upload is failed
<p>When a user uploads a document and clicks submit the file is stored in a folder and a database entry is created along with bunch of other details. What I am looking for is to avoid the save if the document doesn't get uploaded into the specific location.</p> <p>serializer.py</p> <pre><code>class DocumentSerializer(s...
<python><django><database><postgresql><django-rest-framework>
2023-01-02 07:10:26
1
365
ReaL_HyDRA
74,979,653
10,045,509
Null/duplicate check in a column based on another column filter
<p>I am working on pandas with the below requierment</p> <p><a href="https://i.sstatic.net/U82vq.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/U82vq.png" alt="enter image description here" /></a></p> <p>I need to check the below conditions if criteria is A, then m shouldn't be null if criteria is B the...
<python><python-3.x><pandas>
2023-01-02 06:51:36
1
313
RSK Rao
74,979,626
275,002
How to access multiple return values in restype?
<p>I am writing a Go program like the below:</p> <pre><code>package main import ( &quot;C&quot; ) //export getData func getData(symbol string, day string, month string, year string) (string, string) { return &quot;A&quot;, &quot;B&quot; } func main() { } </code></pre> <p>In Python, I am doing this:</p> <pre...
<python><go><ctypes>
2023-01-02 06:47:04
1
15,089
Volatil3
74,979,602
15,887,240
How to take dynamic input from flask and pass it to other function?
<p>How can I take input from url in flask from the parameter?</p> <pre><code>@app.route('/&lt;id&gt;') def give_id(id): return id </code></pre> <p>I need to take the above Id from input and pass it to other function without again needing to write <code>&quot;id&quot;</code></p> <pre><code>def some_function(): ...
<python><flask>
2023-01-02 06:43:35
1
314
DholuBholu
74,979,588
12,097,553
django: foreign key issues when creating a model object
<p>I am trying to write a row to database, with data gathered in a form. I need to work with two foreign keys and one of them is causing the creating to fail, although I am unable to figure out why:</p> <p>here is my model:</p> <pre><code>def upload_path(instance,file): file_dir = Path(file).stem print('usr',in...
<python><django>
2023-01-02 06:41:44
1
1,005
Murcielago
74,979,542
12,696,223
How to get Telegram audio (music) album cover using Telethon API client
<p>I want to get the URL or bytes of the Telegram audio documents (music) album cover using MTProto API and <code>Telethon</code> Python lib, but I could not find such a thing by checking audio message properties. There was a <code>thumbs</code> property for the message attached <code>media</code> property that was nul...
<python><telegram><telethon>
2023-01-02 06:34:03
1
990
Momo
74,979,497
3,026,206
animation loop only cares about first item in list
<p>In a simple pygame zero 2D game, I have a list of Actors that I'm looping through to ensure that they don't run off the side of the screen. However, going right, only the leftmost item in the list (the first one) is triggering the direction change--the rest run off the screen. Strangely, it works fine when they're m...
<python><pgzero>
2023-01-02 06:26:19
1
3,560
beachCode
74,979,430
14,122,835
how to create a new column based on string from different columns
<p>I have a dataframe look like this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>type</th> <th>city</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>dki jakarta</td> </tr> <tr> <td>2</td> <td>jawa barat</td> </tr> <tr> <td>3</td> <td>jawa tengah</td> </tr> <tr> <td>4</td> <td>jawa timur...
<python><pandas><string><conditional-statements>
2023-01-02 06:14:57
1
531
yangyang
74,979,300
8,820,616
Python: Can We SSL wrap any http server to https server?
<p>This is a simple HTTPS python server (not for production use)</p> <pre><code># libraries needed: from http.server import HTTPServer, SimpleHTTPRequestHandler import ssl , socket # address set server_ip = '0.0.0.0' server_port = 3389 # configuring HTTP -&gt; HTTPS httpd = HTTPServer((server_ip, server_port), Simpl...
<python><python-3.x><http><ssl><https>
2023-01-02 05:45:21
0
694
Pradeep Padmanaban C
74,979,106
7,347,925
How to identify one column with continuous number and same value of another column?
<p>I have a DataFrame with two columns <code>A</code> and <code>B</code>.</p> <p>I want to create a new column named <code>C</code> to identify the continuous <code>A</code> with the same <code>B</code> value.</p> <p>Here's an example</p> <pre><code>import pandas as pd df = pd.DataFrame({'A':[1,2,3,5,6,10,11,12,13,18]...
<python><pandas>
2023-01-02 04:59:32
2
1,039
zxdawn
74,979,003
11,199,298
How to intercept request with mitmproxy before response is streamed?
<p>The request I am trying to intercept and modify is a get request with only one parameter and I try to modify it:</p> <pre><code>from mitmproxy import http def request(flow: http.HTTPFlow) -&gt; None: if flow.request.pretty_url.startswith(BASE_URL): flow.request.url = BASE_URL.replace('abc', 'def') </cod...
<python><request><mitmproxy>
2023-01-02 04:31:09
0
2,211
Tugay
74,978,815
2,882,380
Pivot table not showing row total Python
<p>I tested the following codes and set <code>margins</code> to be true. However, the result only shows sum of each column but not sum of each row. How to do that, please?</p> <pre><code>import pandas as pd test = pd.DataFrame( [['a1', 1, 1, 11], ['a1', 2, 3, 12], ['a1', 3, 5, 13], ['a2', 4, 7, 14],...
<python><pandas><dataframe>
2023-01-02 03:36:42
0
1,231
LaTeXFan
74,978,707
3,466,818
Optimizing a puzzle solver
<p>Over the holidays, I was gifted a game called &quot;Kanoodle Extreme&quot;. The details of the game are somewhat important, but I think I've managed to abstract them away. The 2D variant of the game (which is what I'm focusing on) has a number of pieces that can be flipped/rotated/etc. A given puzzle will give yo...
<python><algorithm><recursion><optimization><combinatorics>
2023-01-02 02:59:23
3
706
Helpful
74,978,585
9,855,588
is this a bad approach to creating a global logger, how can I improve it
<p>Given my code, I would create a root logger instance <code>logger = GlobalLogger(level=10).logger</code> in <code>__init__.py</code> and include it in submodules where I need logging. Is there a better way to create this class instead of calling the attribute <code>.logger</code> to get the root logging class, or a ...
<python><python-3.x>
2023-01-02 02:22:41
1
3,221
dataviews
74,978,418
1,229,531
How to include xelatex in a mamba environment?
<p>Running a particular Python program within my environment tries to produce PDF output, which requires &quot;xelatex&quot;. I tried adding &quot;xelatex&quot; to the environment creation command:</p> <pre><code>mamba create -n notebook_rapidsai_env ... python jupyter xelatex </code></pre> <p>but this produced the fo...
<python><conda><xelatex><mamba>
2023-01-02 01:31:31
1
599
Mark Bower
74,978,154
10,788,239
Why does adding multiprocessing prevent python from finding my compiled c program?
<p>I am currently looking to speed up my code using the power of multiprocessing. However I am encountering some issues when it comes to calling the compiled code from python, as it seems that the compiled file disappears from the code's view when it includes any form of multiprocessing.</p> <p>For instance, with the f...
<python><c><multiprocessing><ctypes><file-not-found>
2023-01-02 00:09:03
2
438
Arkleseisure
74,978,130
3,313,834
pytest a script using stdin from argparse
<p>I have an argparse script using stdin:</p> <pre class="lang-py prettyprint-override"><code>$ tree . ├── go.py └── mypytest.py $ $ cat go.py # echo '[{&quot;k&quot;: [&quot;1&quot;, &quot;2&quot;]}]' | python go.py - import argparse, json parser = argparse.ArgumentParser() parser.add_argument('json', nargs='?', typ...
<python><pytest><pytest-mock>
2023-01-02 00:01:46
0
7,917
user3313834
74,978,089
13,677,853
How to tick-level backtest the spot grid trading strategy?
<p>Is there a Python library with which I could tick-level backtest the famous Spot Grid Trading crypto strategy? I already did the tick data download part from <a href="https://data.binance.vision/?prefix=data/spot/daily/trades/" rel="nofollow noreferrer">data.binance.vision</a>, although in my attempt I have used <a ...
<python><pandas><back-testing>
2023-01-01 23:49:50
0
6,607
nop
74,978,038
10,200,497
How to create orders for multiple api keys asynchronously in binance?
<p>I want to create multiple orders for multiple users asynchronously in binance api using python. I know how to a create a single order for a pair of api key and api secret.</p> <pre><code>from binance.client import Client as BinanceClient from binance.enums import * binance_api_key = 'api_key' binance_api_secret = '...
<python><binance><binance-api-client>
2023-01-01 23:35:27
1
2,679
AmirX
74,977,869
7,599,215
Custom built opencv 4..7.0 python import problem
<p>I built opencv 4.7.0 from source</p> <p>I have a folder <code>cv2</code> with <code>cv2.so</code> in it</p> <p>If I call <code>import cv2</code> within the folder -- all ok</p> <p>If I call from without <code>from cv2 import cv2</code> or similar stuff, nothing will work with error:</p> <pre><code>Traceback (most re...
<python><opencv><python-import>
2023-01-01 22:54:54
0
2,563
banderlog013
74,977,786
19,321,677
How to save model with cloudpickle to databricks DBFS folder and load it?
<p>I built a model and my goal is to save the model as a pickle and load it later for scoring. Right now, I am using this code:</p> <pre><code> #save model as pickle import cloudpickle pickled = cloudpickle.dumps(final_model) #load model cloudpickle.loads(pickled) Output: &lt;econml.dml.caus...
<python><machine-learning><model><databricks><pickle>
2023-01-01 22:33:31
1
365
titutubs
74,977,549
3,142,472
Abstract Data Type definition in Python
<p>Consider the following <a href="https://wiki.haskell.org/Abstract_data_type" rel="nofollow noreferrer">Abstract Data Type</a> (using Haskell syntax):</p> <pre class="lang-hs prettyprint-override"><code>data Expr = Literal String | Symbol String | And [Expr] | Or [Expr] </code></pre> <p>In Python, one can make use of...
<python><metaprogramming><language-design><abstract-data-type>
2023-01-01 21:42:01
2
1,315
Alexandru Dinu
74,977,357
16,748,931
ModuleNotFoundError: No module named 'pygame_menu'
<p>I'm trying to make a game using <code>pygame</code> and <code>pygame_menu</code>. When I try to install <code>pygame_menu</code> I get this error:</p> <pre><code>Traceback (most recent call last): File &quot;D:\Game\main.py&quot;, line 7, in &lt;module&gt; import pygame_menu ModuleNotFoundError: No module name...
<python><pip><pygame-menu>
2023-01-01 20:57:31
2
570
ProGamer2711
74,977,340
249,341
Matching everything except for a character followed by a newline
<p>This seems like a simple match, but I'm unable to figure out how to match all text that starts with a known block of text and ends with a semicolon + newline. What I have right now mostly works:</p> <pre><code>pattern = r'''[ ]+(value \w+\n)([^;]+)''' </code></pre> <p>For an example section of text that allows me to...
<python><regex>
2023-01-01 20:53:45
1
88,818
Hooked
74,977,313
14,670,370
How to use pd.json_normalize on a list of dictionaries in Pandas?
<p>I am trying to use the pd.json_normalize() function from the Pandas library on the following data:</p> <pre><code> data = { &quot;examples&quot;: [ { &quot;website&quot;: &quot;info&quot;, &quot;df&quot;: [ { &quot;Question&quot;: &quot;What?...
<python><json><pandas><dataframe>
2023-01-01 20:48:21
1
354
Serkan Gün
74,977,307
4,031,604
How to intercept running python script and execute command within its context?
<p>Here is the situation (as an example) - I ran a ML learning python script (which I wrote) for a long time but I didn't add functionality to save its weights.</p> <p>My question in this situation is if it's possible to somehow intercept the running python interpreter and execute a command within the program context.<...
<python><debugging><cpython><intercept>
2023-01-01 20:47:31
0
3,998
AnArrayOfFunctions
74,977,186
12,140,406
.loc into multindex pandas df on not-level zero with sorted order
<p>say I have a multi index pandas data frame and I want to slice into the whole data frame on the not-zeroth level of the data frame and get a dataframe back in the order of the sliced list.</p> <p>this happens automatically using <code>.loc</code> on the zeroth level of the multi index, but apparently not-so for oth...
<python><pandas><dataframe><multi-index>
2023-01-01 20:25:06
0
365
wiscoYogi
74,977,046
11,611,632
Django RequestFactory; TypeError: get() missing 1 required positional argument;
<p>In attempting to test the context of a view <code>PostedQuestionPage</code> with RequestFactory, the following error is being raised when running the test:</p> <pre><code> File &quot;C:\Users\..\django\test\testcases.py&quot;, line 1201, in setUpClass cls.setUpTestData() Fi..\posts\test\test_views.py&quot;, l...
<python><django><django-tests>
2023-01-01 19:55:15
0
739
binny
74,977,008
10,430,394
Extract bezier curve info from a TTF file (ttfquery won't install)
<p>I saw this post: <a href="https://stackoverflow.com/questions/40437308/retrieving-bounding-box-and-bezier-curve-data-for-all-glyphs-in-a-ttf-font-file">Retrieving bounding box and bezier curve data for all glyphs in a .ttf font file in python</a></p> <p>about how to retrieve the bezier curve data from a TTF file. Th...
<python><truetype>
2023-01-01 19:47:03
0
534
J.Doe
74,976,963
14,584,978
Windows Authentication for polars connectorx SQL Server
<p><a href="https://stackoverflow.com/questions/74967574/connect-python-polars-to-sql-server-no-support-currently">Can we connect to SQL server using polars and connectorx? YES</a></p> <p>The username I used in SQL Server Management Studio right after the below test without issue.</p> <pre><code>conn = 'mssql+pyodbc://...
<python><sql-server><windows-authentication><python-polars>
2023-01-01 19:39:23
1
374
Isaacnfairplay
74,976,749
9,649,681
How to scrape multi page website with python?
<p>I need to scrape the following table: <a href="https://haexpeditions.com/advice/list-of-mount-everest-climbers/" rel="nofollow noreferrer">https://haexpeditions.com/advice/list-of-mount-everest-climbers/</a></p> <p>How to do it with python?</p>
<python><web-scraping>
2023-01-01 18:58:03
1
686
juststuck
74,976,733
9,855,588
easy way to change logger name for each logger instance
<p>I have a root logging class that I created, which I'd like to use for each micro-service function that I'm deploying.</p> <p>Example output log: <code>[2023-01-01 13:46:26] - INFO - [utils.logger.&lt;module&gt;:5] - testaaaaa</code> The logger is defined in <code>utils.logger</code> so that's why it's showing that i...
<python><python-3.x><python-logging>
2023-01-01 18:54:05
1
3,221
dataviews
74,976,655
8,524,178
Cairo Remove Faint Line Between to Adjacent Paths / Combine Paths in Cairo
<p>Is there a way to combine two closed paths in Cairo, so the group of paths is filled as a single solid shape, instead of two shapes sitting next to each other?</p> <p>If I draw two paths next to each other, there is a faint blank line visible between the two shapes. For example, the below script draws a square and a...
<python><svg><2d><cairo><pycairo>
2023-01-01 18:42:39
0
1,764
The Matt
74,976,605
8,799,471
Run excel macro (locked) using python
<p>It isn't duplicate. Others suggest to crack the password but that's not something we are planning to do. Don't way any legal issues. Macro models are locked. Can't execute programmatically</p> <p>So we have an excel where we fill some data. Click on the given button. It performs some calculations (using macros proba...
<python><excel><vba><libreoffice>
2023-01-01 18:33:04
2
1,827
targhs
74,976,538
17,795,398
Python session kept open after closing tkinter window with a matplotlib graph
<p>I want to put a <code>matplotlib</code> figure in a <code>tkinter</code> user interface. This is my code, based on the <code>matplotlib</code> documentation:</p> <pre><code>import tkinter as tk import matplotlib.pyplot as plt from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk impor...
<python><matplotlib><tkinter>
2023-01-01 18:20:54
1
472
Abel Gutiérrez
74,976,337
6,057,371
pandas how to get all rows with specific count of values
<p>I have a dataframe</p> <pre><code>df = C1 C2 a. 2 d. 8 d. 5 d. 5 b. 3 b. 4 c. 5 a. 6 b. 7 </code></pre> <p>I want to take all the rows, in which the count of the value in C1 is &lt;= 2, and add a new col that is low, and keep the original value otherwise. So t...
<python><pandas><dataframe><group-by>
2023-01-01 17:49:30
1
2,050
Cranjis
74,976,313
317,797
Possible to Stringize a Polars Expression?
<p>Is it possible to stringize a Polars expression and vice-versa?</p> <p>For example, convert <code>df.filter(pl.col('a')&lt;10)</code> to a string of <code>&quot;df.filter(pl.col('a')&lt;10)&quot;</code>.</p> <p>Is roundtripping possible e.g. <code>eval(&quot;df.filter(pl.col('a')&lt;10)&quot;)</code> for user input ...
<python><sql><string><expression><python-polars>
2023-01-01 17:46:34
1
9,061
BSalita
74,976,269
11,300,553
TypeError: 'NoneType' object is not subscriptable even though checking the var with an if condition and setting it to a static value otherwise
<p>I am trying to write a prototype for web scraping. My problem is that I get the error in the title when <code>duetpartner = track['duet']['handle'] </code> is null or of NoneType.</p> <p>The thing is I already made a check for it and I set it to a static value if it is None:</p> <pre><code>def create_song_list(track...
<python><python-3.x><list><loops><python-requests>
2023-01-01 17:42:05
2
321
Sir Muffington
74,976,204
552,563
Which objects are not destroyed upon Python interpreter exit?
<p>According to <a href="https://docs.python.org/3/reference/datamodel.html#object.__del__" rel="noreferrer">Python documentation</a>:</p> <blockquote> <p>It is not guaranteed that <code>__del__()</code> methods are called for objects that still exist when the interpreter exits.</p> </blockquote> <p>I know that in olde...
<python><garbage-collection>
2023-01-01 17:28:45
3
3,011
Alex Bochkarev
74,976,152
713,200
How to get twitter profile name using python BeautifulSoup module?
<p>I'm trying to get twitter profile name using profile url with beautifulsoup in python, but whatever html tags I use, I'm not able to get the name. What html tags can I use to get the profile name from twitter user page ?</p> <pre><code>url = 'https://twitter.com/twitterID' html = requests.get(url).text soup = Beauti...
<python><html><beautifulsoup><html-parser>
2023-01-01 17:21:18
1
950
mac
74,976,151
18,002,913
how to get value from a web site using beautifulsoap in python?
<p>Im trying to get words with headers from web site with beautifulsoap in python but I couldnt do it. I'm trying to make a german dictionary.</p> <p>Here is the site</p> <p><strong><a href="https://almancakonulari.com/a1-seviye-almanca-kelimeler/#gsc.tab=0" rel="nofollow noreferrer">https://almancakonulari.com/a1-sevi...
<python>
2023-01-01 17:21:15
0
1,298
NewPartizal
74,976,075
815,612
How do I horizontally center a fixed-size widget inside a VBox?
<p>This code draws a window with some buttons in it:</p> <pre><code>import gi gi.require_version(&quot;Gtk&quot;, &quot;3.0&quot;) from gi.repository import Gtk window = Gtk.Window() box = Gtk.VBox() window.add(box) button1 = Gtk.Button(label=&quot;Hello&quot;) box.pack_start(button1, False, False, 10) button2 = Gt...
<python><gtk><pygtk>
2023-01-01 17:10:18
1
6,464
Jack M
74,975,991
1,734,990
shutil.copyfile PermissionError or FileNotFoundError Error
<p>If I use the following code to copy a file (based on the zillion of examples online):</p> <pre><code>import os import shutil from pathlib import Path DATA_DIR = Path.cwd() / 'sourceFolder' files = os.listdir(DATA_DIR) shutil.copyfile(os.path.join('sourceFolder', files[0]), '/destFolder') </code></pre> <p>I receive ...
<python><python-3.x>
2023-01-01 16:55:37
1
859
JF0001
74,975,921
7,800,760
Fuzzy search of users to retrieve associated data
<p>I am building an application which identifies <strong>people mentioned in free text (order of magnitude of a million)</strong> and stores their names as keys with one or more (for handling people with the same name) <strong>associated URIs</strong> pointing to a <strong>SPARQL based knowledge graph node</strong> whi...
<python><redis><sparql>
2023-01-01 16:43:49
0
1,231
Robert Alexander
74,975,854
1,556,875
JSON wrapped in NULL?
<p>I'm using the API of an affiliate network (Sovrn), expecting to retrieve a product's specification using the URL.</p> <p>As per their documentation, I use:</p> <pre><code>url = 'URL-goes-here' headers = { &quot;accept&quot;: &quot;application/json&quot;, &quot;authorization&quot;: &quot;VERY-HARD-TO-GUESS&q...
<python><json>
2023-01-01 16:32:30
2
533
Zsolt Balla
74,975,689
19,838,445
Set property on a function object
<p>Is it possible to assign property on a function object the similar way we assign it on class instances. My desired behaviour is like this</p> <pre class="lang-py prettyprint-override"><code>def prop(): print(&quot;I am a property&quot;) def my_func(): print(&quot;Just a function call&quot;) my_func.prop =...
<python><function><properties><getattr><python-descriptors>
2023-01-01 16:04:08
1
720
GopherM
74,975,596
8,549,456
Matplotlib's show function triggering unwanted output
<p>Whenever I have any Python code executed via Python v3.10.4 with or without debugging in Visual Studio Code v1.74.2, I get output looking like the following in the Debug Console window in addition to the normal output of the code. Otherwise, all of my Python programs work correctly and as intended at this time.</p> ...
<python><macos><matplotlib><visual-studio-code><vscode-debugger>
2023-01-01 15:50:36
3
337
Alper
74,975,489
2,179,057
Finding the minimum supported Python version for a package
<p>I've just made a Python package and to help me in managing it, I'm using some relatively new features in Python for typings. Given that this is just typings, will my package work for lower versions?</p> <p>Here's an example of the package:</p> <pre class="lang-py prettyprint-override"><code>from __future__ import an...
<python><pypi>
2023-01-01 15:30:59
1
4,510
Spedwards
74,975,291
2,707,864
Dataframe with column of type list: Append to selected rows
<p>I have two dataframes (created with code below) as</p> <pre><code>df1 Fecha Vals 0 2001-01-01 [] 1 2001-01-02 [] 2 2001-01-03 [] 3 2001-01-04 [] 4 2001-01-05 [] 5 2001-01-06 [] 6 2001-01-07 [] 7 2001-01-08 [] 8 2001-01-09 [] df2 Fecha Vals 0 2001-01-01 0.0 1 2001-01-03 1.0 2 200...
<python><pandas><list><dataframe>
2023-01-01 14:52:28
2
15,820
sancho.s ReinstateMonicaCellio
74,975,284
1,800,459
Regular expression to find all the image urls in a string
<p>I am trying to construct a regular expression that finds all image urls from a string. An image url can be either absolute path or relative.</p> <p>All these should be valid matches:</p> <pre><code> ../example/test.png https://www.test.com/abc.jpg images/test.webp </code></pre> <p>For example: if we define...
<python><regex>
2023-01-01 14:50:14
2
1,134
AJ222
74,975,275
13,505,957
Web scraping Google Maps with Selenium uses too much data
<p>I am scraping travel times from Google Maps. The below code scrapes travel times between 1 million random points in Tehran, which works perfectly fine. I also use multiprocessing to get travel times simultaneously. The results are fully replicable, feel free to run the code in a terminal (but not in an interactive s...
<python><html><selenium><webdriver>
2023-01-01 14:48:44
1
1,107
ali bakhtiari
74,975,192
14,670,370
Filtering empty elements in a nested list in pandas dataframe
<p>I have a list inside a pandas dataframe and I want to filter it. For example, I have a dataframe like this:</p> <pre><code>{ &quot;examples&quot;: [ { &quot;website&quot;: &quot;info&quot;, &quot;df&quot;: [ { &quot;Question&quot;: &quot;What?...
<python><pandas><dataframe><filtering><nested-lists>
2023-01-01 14:32:36
1
354
Serkan Gün
74,975,100
18,002,913
How to get value inside of h3 tag with beautifulsoup in python?
<p>I 'm trying to get value inside of <code>h3</code> <code>tag</code> but there is a problem that I dont figure out. I m stuck in a problem.</p> <p><strong>this is the data which I want to get. I want to get</strong> <code>Zahlen</code> word between <code>span</code> <code>classes</code> inside <code>h3</code> <code>t...
<python><beautifulsoup>
2023-01-01 14:12:46
1
1,298
NewPartizal
74,975,098
6,460
Does type hinting class members shadow previously defined or built-in variables?
<p>With type-hinting, defining a class in Python goes from</p> <pre><code>class SomeClass: def __init__(self): self.id = 5 </code></pre> <p>to something like this</p> <pre><code>class SomeClass: id: int def __init__(self) -&gt; None: self.id = 5 </code></pre> <p>However, a linter like <code...
<python><python-typing><shadowing>
2023-01-01 14:12:34
1
8,833
Nikolai Prokoschenko
74,975,009
2,474,025
plotly interactive tooltip / hover text / popup
<p>Tooltips of a figure are only displayed while hovering over the data point: <a href="https://plotly.com/python/hover-text-and-formatting" rel="nofollow noreferrer">https://plotly.com/python/hover-text-and-formatting</a></p> <p>I'd like to have an easy way to customize the duration the tooltip is displayed after hove...
<python><plotly><tooltip>
2023-01-01 13:54:08
2
1,033
phobic
74,974,901
10,016,858
How to understand empty second parameter to pandas DataFrame.loc
<p>Hi I am looking for help to understand the behaviour caused by not having/having an empty second parameter to pandas <code>DataFrame.loc</code> method</p> <p>Consider the following:</p> <pre><code>df=pd.DataFrame(index=pd.MultiIndex.from_tuples([('a', 1, 'x'),('a', 2, 'y'),('b', 1, 'x')]), data={'col_1':[1, 2, 3]}) ...
<python><pandas><multi-index>
2023-01-01 13:33:09
1
1,241
JohnnieL
74,974,733
4,451,521
Pytesting a script that is not a library
<p>I have the following directory structure</p> <pre><code>| |---test | |----test1.py | |----test2.py | |---alibrary | |--thelib.py | | |--main.py </code></pre> <p>In <code>test1.py</code> I tested the functions in <code>thelib.py</code>. To do this, the script started like this</p> <pre><code>import alibrary....
<python><pytest>
2023-01-01 12:58:52
0
10,576
KansaiRobot
74,974,685
922,130
How to perform single- and complete-linkage clustering based on selected pairwise compairsons?
<p>Let's say I have 8 objects.</p> <pre class="lang-py prettyprint-override"><code>all_objects = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'] </code></pre> <p>I performed all pairwise comparisons (8 x 7) using a custom method. As a result, I got pairs that meet a certain similarity criterion.</p> <pre class="lang-py pretty...
<python><scipy><statistics><cluster-analysis><hierarchical-clustering>
2023-01-01 12:47:00
1
909
sherlock85
74,974,409
17,696,880
How to extract specific information with capture groups from an input string, rearrange and replace back inside this string using re.sub() function?
<pre class="lang-py prettyprint-override"><code>import re input_text = &quot;estoy segura que empezaria desde las 15:00 pm del 2002_-_11_-_01 hasta las 16:00 hs pm&quot; #example 1 input_text = &quot;estoy segura que empezara desde las 15:00 pm h.s. del 2002_-_11_-_(01_--_15) hasta las 16:10 pm hs, aunque no se cuando...
<python><python-3.x><regex><replace><regex-group>
2023-01-01 11:45:12
1
875
Matt095
74,974,132
11,555,352
Efficient way to restructure pandas dataframe from row to resampled column structure
<p>I have a pandas dataframe structured as follows:</p> <pre><code>TimeStamp 2022-12-30 10:31:58.483700+00:00 1 FixType 4 4.000000e+00 2022-12-30 10:31:58.483700+00:00 1 Satellites 11 1.100000e+0...
<python><pandas><dataframe>
2023-01-01 10:33:15
1
1,611
mfcss