QuestionId
int64
74.8M
79.8M
UserId
int64
56
29.4M
QuestionTitle
stringlengths
15
150
QuestionBody
stringlengths
40
40.3k
Tags
stringlengths
8
101
CreationDate
stringdate
2022-12-10 09:42:47
2025-11-01 19:08:18
AnswerCount
int64
0
44
UserExpertiseLevel
int64
301
888k
UserDisplayName
stringlengths
3
30
βŒ€
75,453,802
6,032,140
Unique string to Python Dictonary and then dump as yaml
<ol> <li><p>The following output string is from a specific program and gets dumped in a text file. This more or less looks like python dictionary but isn't. [BTW. this is just a basic example but it might complex with multi layer dict]</p> <pre><code>p_d: '{a:3, what:3.6864e-05, s:&quot;lion&quot;, sst:'{c:-20, b:6, p:...
<python><json><python-3.x><yaml>
2023-02-14 22:23:33
1
1,163
Vimo
75,453,728
603,136
Round-trip HTML using Python xml.etree.ElementTree or lxml.ElementTree
<p>I have code that creates and saves XML fragments. Now I would like to handle HTML as well. ElementTree.write() has a method=&quot;html&quot; parameter that suppresses end tags for &quot;area&quot;, &quot;base&quot;, &quot;basefont&quot;, &quot;br&quot;, &quot;col&quot;, &quot;frame&quot;, &quot;hr&quot;, &quot;img...
<python><html><lxml><elementtree>
2023-02-14 22:13:15
0
2,996
samwyse
75,453,722
1,118,576
What does "domain" mean in Python's tracemalloc?
<p>Python's <a href="https://docs.python.org/3.10/library/tracemalloc.html" rel="nofollow noreferrer">tracemalloc documentation</a> defines &quot;domain&quot; as an &quot;address space of a memory block&quot; and identifies a domain using an integer. It also says:</p> <blockquote> <p>tracemalloc uses the domain 0 to t...
<python><python-3.x><memory-management>
2023-02-14 22:12:01
1
885
Mike Placentra
75,453,656
436,025
Run event loop until all tasks are blocked in python
<p>I am writing code that has some long-running coroutines that interact with each other. These coroutines can be blocked on <code>await</code> until something external happens. I want to be able to drive these coroutines in a unittest. The regular way of doing <code>await</code> on the coroutine doesn't work, because ...
<python><python-asyncio><python-3.9><python-3.10>
2023-02-14 22:00:34
5
4,256
Alexander Kondratskiy
75,453,620
6,679,011
How to extract the binary string from the string
<p>I have a tricky question of how to process a string. I need to process a payload from the link, the payload is a encrypted binary string looks like this:</p> <pre class="lang-py prettyprint-override"><code>payload=b'F4ChGNL/Pemxy8l6cCR......' </code></pre> <p>AS you can see, it is a bytes. However, when I try to fet...
<python><pycrypto>
2023-02-14 21:54:55
1
469
Yang L
75,453,563
19,871,699
Why do function attributes (setattr ones) only become available after assigning it as a property to a class and instantiating it?
<p>I apologize if I'm butchering the terminology. I'm trying to understand the code in <a href="https://stackoverflow.com/questions/59651935/how-to-add-custom-method-to-pyspark-dataframe-class-by-inheritance">this example</a> on how to chain a custom function onto a PySpark dataframe. I'd really want to understand exac...
<python><oop><pyspark>
2023-02-14 21:46:35
2
728
jonathan-dufault-kr
75,453,530
3,672,883
Are there any alternative to this overload case in python with typing?
<p>currently I am implementing a lot of subclasses that should implement a function, this is a minimal example of the current project.</p> <p>In this case, I have a function that needs to call, to the login of a user, but depending of the implementation injected previously the application will use <code>UserUP</code> o...
<python><mypy>
2023-02-14 21:41:20
1
5,342
Tlaloc-ES
75,453,502
2,474,876
caching python class instances
<p>I have a memory heavy class, say a type representing a high-resolution resource (ie: media, models, data, etc), that can be instantiated multiple times with identical parameters, such as same filename of the resource loaded multiple times.</p> <p>I'd like to implement some sort of unbounded <code>caching</code> on o...
<python><caching><singleton><multiple-instances><object-pooling>
2023-02-14 21:37:08
3
417
eliangius
75,453,379
4,085,019
Flask Mutating Request Path
<h2>Problem Statement</h2> <p>When path contains <code>%25</code>, flask seems to be mutating the incoming path to treat <code>%25</code> as <code>%</code> instead of preserving the original request path. Here are the request and path variable:</p> <ul> <li>Request: : <code>GET http://localhost:5000/Files/dir %a/test %...
<python><flask><request><special-characters>
2023-02-14 21:19:11
1
6,049
PseudoAj
75,453,277
3,122,657
staticmethod vs classmethod for factory pattern when using pydantic
<p>Reading most questions with <em>@classmethod vs @staticmethod</em>, replies state that static is almost useless in python except to logically group functions, but module can do the work.</p> <p>But I ended up with a factory pattern, using pydantic, where I cannot see how we can replace the static method with a class...
<python><design-patterns><static><pydantic>
2023-02-14 21:07:03
1
3,374
comte
75,453,197
1,284,415
How to generate RSA private key using Fernet
<p>This should be simple (famous last words)</p> <p>In the terminal, i can run this command:</p> <p>winpty openssl genrsa -des3 -out my_rsa_key_pair 2048</p> <p>How can I do the exact same thing using <a href="https://cryptography.io/en/latest/" rel="nofollow noreferrer">pyca/cryptography</a> ?</p>
<python><cryptography><fernet>
2023-02-14 20:56:08
1
6,008
Dallas Caley
75,453,175
1,818,713
Use list comprehension for expression functions
<p>Let's say I want to make a list of functions, ie <code>aggs=['sum','std','mean','min','max']</code></p> <p>then if I have an arbitrary df</p> <pre><code>df=pl.DataFrame({'a':[1,2,3], 'b':[2,3,4]}) </code></pre> <p>I want to be able to do something like (this obviously doesn't work)</p> <pre><code>df.with_columns([pl...
<python><list-comprehension><python-polars>
2023-02-14 20:53:54
1
19,938
Dean MacGregor
75,452,969
7,981,821
Errno 111 Connection refused error, between flask server and raspberry pi over ethernet
<p>I am trying to send data through an http request with the python <code>requests</code> library froma raspberry pi to my local computer connected by an ethernet cable. When trying to send data from the raspberry pi I get an <code>Failed to establish a new connection: [Errno 111] Connection refused'))</code> error. I...
<python><python-requests><raspberry-pi><ethernet>
2023-02-14 20:27:11
1
1,033
Josh Zwiebel
75,452,962
9,983,652
how to stop jupyter-dash from running in vscode?
<p>I am using jupyter-dash in VSCode. I have a big iteration. sometime I'd like to stop running.</p> <p>I tried few options in the below link and they never work.</p> <p><a href="https://stackoverflow.com/questions/58230077/vscode-python-interactive-window-how-to-stop-jupyter-server#:%7E:text=You%20can%20stop%20it%20u...
<python><visual-studio-code><jupyterdash>
2023-02-14 20:26:19
1
4,338
roudan
75,452,958
16,332,690
How to write a DataFrame to csv while ingesting data via an API with asyncio and aiohttp
<p>I built an API wrapper module in Python with <code>aiohttp</code> that allows me to significantly speed up the process of making multiple GET requests and retrieving data. Every data response is turned into a pandas DataFrame.</p> <p>Using <code>asyncio</code> I do something that looks like this:</p> <pre class="lan...
<python><pandas><python-asyncio><aiohttp>
2023-02-14 20:25:56
2
308
brokkoo
75,452,941
563,130
In Python how to call Parent class function as if I were Parent object
<p>I have a Parent and a Child class, both should execute their own fct in <strong>init</strong> but Child have to execute first the Parent fct :</p> <pre><code>class Parent(object): def __init__(self): self.fct() def fct(self): # do some basic stuff class Child(Parent): def __init...
<python><class><inheritance>
2023-02-14 20:23:30
1
2,739
Patrick
75,452,926
10,007,302
Error executing cursor.execute when quotes are required
<p>fairly new to SQL in general. I'm currently trying to bolster my general understanding of how to pass commands via <code>cursor.execute()</code>. I'm currently trying to grab a column from a table and rename it to something different.</p> <pre><code>import mysql.connector user = 'root' pw = 'test!*' host = 'localh...
<python><mysql><mysql-connector>
2023-02-14 20:21:52
2
1,281
novawaly
75,452,897
7,254,750
Adding generic typing to function signature with pandas Series results in 'type' object is not subscriptable error
<p><code>Mypy</code> is correctly telling me that the following is missing the generic arg for <code>pd.Series</code></p> <pre class="lang-py prettyprint-override"><code>def foo(x : pd.Series) -&gt; None: pass </code></pre> <p>When I add the arg like so</p> <pre class="lang-py prettyprint-override"><code>from typi...
<python><pandas><mypy><python-typing>
2023-02-14 20:18:35
1
341
MilesConn
75,452,801
5,858,752
Is abc.ABC available in python 2.7.16?
<p>Based on <a href="https://docs.python.org/2/library/abc.html" rel="nofollow noreferrer">https://docs.python.org/2/library/abc.html</a>, it seems abstract classes are available starting in version 2.6 (the top says &quot;New in version 2.6.&quot;)</p> <p>However, I cannot <code>from abc import ABC, abstractmethod</co...
<python><python-2.7><abc>
2023-02-14 20:07:37
0
699
h8n2
75,452,643
10,904,328
z3 fails to solve problem with square root
<p>I'm trying to solve simple problem which involves calculating square root, yet for some reason z3 throws an error like <code>failed to solve</code> or <code>z3types.Z3Exception: model is not available</code></p> <pre><code>from z3 import * x = Int('x') y = Int('y') solve(x &gt; 0, y &gt; x, y ** 0.5 == x) </code><...
<python><z3><z3py>
2023-02-14 19:49:53
1
813
tezzly
75,452,550
18,384,775
Best way to merge multiple csv files starting with different timestamps using pandas concat
<h4>The dataset:</h4> <p>I have a collection csv files inside a folder with each csv file with title: <code>timestamp</code> and <code>close</code>. Each file is saved as <code>{symbol}.csv</code> where symbols range from a list of symbols eg: <code>['ADAUSDT', 'MAGICUSDT', 'LUNCUSDT', 'LINAUSDT', 'LEVERUSDT', 'BUSDUSD...
<python><pandas><dataframe><csv>
2023-02-14 19:39:11
1
318
Royce Anton Jose
75,452,493
3,763,616
Split a dataframe into n dataframes by column value in polars
<p>I have a large Polars dataframe that I'd like to split into n number of dataframes given the size. Like take dataframe and split it into 2 or 3 or 5 dataframes.</p> <p>There are several observations that will show up for each column and would like to choose splitting into a chosen number of dataframes. A simple exam...
<python><python-polars>
2023-02-14 19:31:50
1
489
Drthm1456
75,452,354
12,082,289
Paramiko RSAKey "private key file is encrypted"
<p>I'm trying to use Paramiko to connect to an SFTP site.</p> <pre><code>&quot;paramiko&quot;: { &quot;hashes&quot;: [ &quot;sha256:6bef55b882c9d130f8015b9a26f4bd93f710e90fe7478b9dcc810304e79b3cd8&quot;, &quot;sha256:fedc9b1dd43bc1d45f67f1ceca10bc336605427a46dcdf8dec6bfea3edf...
<python><ssh><ftp><sftp><paramiko>
2023-02-14 19:17:23
1
565
Jeremy Farmer
75,452,155
8,941,248
xlabel of DataFrame.plot appears on the y-axis
<p>I'm creating a stacked bar plot via the code below:</p> <pre><code>ax = df.plot( kind=&quot;barh&quot;, stacked=True, width=0.9, figsize=(10, 11), colormap=&quot;RdYlGn&quot;, xlabel='% Respondents' ); </code></pre> <p>But the label for the x-axis appears on the y-axis! If I change <code>xlab...
<python><pandas><matplotlib>
2023-02-14 18:53:52
1
521
mdrishan
75,452,080
9,983,652
how to print at same line using end parameter?
<p>I'd like to print at same line for print statement inside a for loop using end= parameter. not sure which end parameter i can use.</p> <p>For example, in below, for each time's print, only need to change str(i) and str(result), everything is the same.</p> <pre><code>for i in range(10): result=i**2 print('itera...
<python>
2023-02-14 18:47:26
1
4,338
roudan
75,452,067
7,531,433
How can I set a seed for random array creation in dask?
<p>In dask we can create a random array for example like this.</p> <pre class="lang-py prettyprint-override"><code>import dask.array as da rand = da.random.random((100, 100)) </code></pre> <p>For reproducibility I would like to set a random seed, such that <code>rand</code> will always have the same content. How can I...
<python><dask>
2023-02-14 18:46:03
1
709
tierriminator
75,451,880
422,005
Convert string with "_" to int?
<p>I have a function which takes a string input, tries to convert it to integer and then proceeds with two alternative paths depending on whether the conversion succeeded or not:</p> <pre><code>def make_int(arg): try: int_value = int(arg) except ValueError: str_value = arg </code></pre> <p>I now w...
<python>
2023-02-14 18:27:52
2
2,081
user422005
75,451,668
6,804,439
Fixed ylabel space (aligned y-axis) across multiple figures
<p>I'm using code much like:</p> <pre class="lang-py prettyprint-override"><code>import matplotlib.pyplot as plt labels = ['AAA', 'BBBBBBBBBBBBB', 'CCCCCC', 'DDDDDDDDDD'] values = [0, 2, 2, 5] fig, ax = plt.subplots(figsize=(8, 0.07 + 0.25 * len(values))) bars = ax.barh(labels, values, color=colors) </code></pre> <p>t...
<python><matplotlib><visualization>
2023-02-14 18:09:15
1
320
Minty
75,451,613
496,289
openpyxl and MS Excel: Problem with content, recover as much as we can
<p>I have an excel with a named/excel-table (<code>B22:O25</code>) in it with header row + 3 rows of empty data-cells. I make a copy of this file, then open the copy using <code>openpyxl.open()</code>, insert 17 more rows (<code>ws.insert_rows(idx=23, amount=17)</code>), update <code>table.ref</code> (+copy formats, up...
<python><excel><ms-office><openpyxl>
2023-02-14 18:03:44
1
17,945
Kashyap
75,451,402
5,449,789
Addressing Saddle Points in Keras Model Training
<p>My keras model seems to have to hit a saddle point in it's training. Of course this is just an assumption; I'm not really sure. In any case, the loss stops at .0025 and nothing I have tried has worked to reduce the loss any further.</p> <p>What I have tried so far is:</p> <ol> <li><p>Using Adam and RMSProp with and ...
<python><keras><trainingloss>
2023-02-14 17:38:27
0
461
junfanbl
75,451,399
1,815,739
Swap trade in Uniswap fails using uniswap-python standard functions
<p>I am trying to do a simple trade using uniswap-python and it doesn't work.</p> <p><strong>Sample code:</strong></p> <pre><code>from uniswap import Uniswap provider = &quot;https://polygon-mainnet.infura.io/v3/&quot;+INFURA_API_KEY uniswap = Uniswap(address, private_key, version = 3, provider) result = uniswap.make_t...
<python><polygon><swap><uniswap>
2023-02-14 17:38:09
1
496
The Dare Guy
75,451,378
2,038,360
Modify a bar plot into a staked plot keeping the original values
<p>I have a pandas DataFrame containing the percentage of students that have a certain skill in each subject stratified according to their gender</p> <pre><code>iterables = [['Above basic','Basic','Low'], ['Female','Male']] index = pd.MultiIndex.from_product(iterables, names=[&quot;Skills&quot;, &quot;Gender&quot;]) df...
<python><pandas><matplotlib><bar-chart><plot-annotations>
2023-02-14 17:35:33
1
5,589
gabboshow
75,451,278
4,875,022
How to sample groups by a condition a subset of each group's data should satisfy using pandas
<p>I am wondering if there is a better way to solve the following problem.</p> <p>I have a dataset that tracks the price of products over time (using a relative time index centered around some event date (t=0)):*</p> <pre><code>df = pd.DataFrame({'id': [1,1,1,1,1,2,2,2,2,2], 'time': [-2,-1,0,1,2,-2,...
<python><pandas>
2023-02-14 17:25:52
1
397
greyBag
75,451,248
2,394,694
Use Dask Dataframe On delayed function
<p>I have three sources and a Dask Dataframe for each of them. I need to apply a function that computes an operation that combines data from the three sources. The operation requires a state to be calculated ( I can't change that).</p> <p>The three sources are in parquet format and I read the data using <code>read_parq...
<python><dask><dask-distributed><dask-dataframe><dask-delayed>
2023-02-14 17:23:20
1
1,549
theShadow89
75,451,239
7,483,211
How to reference input in params section of snakemake rule?
<p>I need to process my input file values, turning them into a comma-separated string (instead of white space) in order to pass them to a CLI program. To do this, I want to run the input files through a Python function. How can I reference the input files of a rule in the params section of the same rule?</p> <p>This is...
<python><snakemake>
2023-02-14 17:22:23
1
10,272
Cornelius Roemer
75,451,197
5,105,118
How to run multiple julia functions from python multiprocessing pool using juliacall
<p>I want to run julia functions/scripts from within python. I managed to call julia scripts via the library <code>juliacall</code>. Now I want to parallelize this. Therefore I created a python multiprocessing Pool and call the julia script from each worker. However this fails with the following message:</p> <pre><code...
<python><julia><python-multiprocessing><juliacall>
2023-02-14 17:18:38
0
1,765
v.tralala
75,451,064
4,707,978
weird error all the sudden: source code string cannot contain null bytes
<p>Really weird error when running with docker-compose dockerfile:</p> <pre><code>FROM tiangolo/uvicorn-gunicorn:python3.10-slim COPY . /app WORKDIR /app RUN pip install -r requirements.txt CMD celery worker -B --app=worker.worker.celery --loglevel=debug </code></pre> <p>Error:</p> <pre><code>momo-api-worker-1 | Du...
<python>
2023-02-14 17:04:12
0
3,431
Dirk
75,451,056
10,404,281
Two data frame Name mapping and replace a values base on condition
<p>I have two data frames (df) one equally divided into weeks by count of the week for the month(February 4 weeks March 5 weeks). The other one has actual data.</p> <p>equally divided df</p> <pre class="lang-py prettyprint-override"><code>Name Feb_1 Feb_2 Feb_3 Feb_4 Mar_5 Mar_6 Mar_7 Mar_8 Mar_9...
<python><pandas><dataframe>
2023-02-14 17:03:19
2
819
rra
75,450,874
2,395,382
ModuleNotFoundError when import package from src folder
<p>What is wrong with this python structure? I have read multiple docs and forums on this issue i just can't seem to get it solved.</p> <pre class="lang-bash prettyprint-override"><code>. └── src β”œβ”€β”€ __init__.py β”œβ”€β”€ lib β”‚ β”œβ”€β”€ hello.py β”‚ └── __init__.py β”œβ”€β”€ libtwo β”‚ β”œβ”€β”€ __init__.py β”‚ ...
<python><python-3.x><python-import><python-module>
2023-02-14 16:48:10
3
2,421
Fanna1119
75,450,844
6,290,211
How to get performance_metrics() on weekly frequency in facebook-prophet?
<p><a href="https://facebook.github.io/prophet/" rel="nofollow noreferrer">I am working with <code>prophet</code></a> library for educational purpose on a classic dataset: the <a href="https://www.kaggle.com/datasets/yasserh/air-passengers-forecast-dataset" rel="nofollow noreferrer">air passenger dataset available on K...
<python><time-series><facebook-prophet>
2023-02-14 16:45:06
0
389
Andrea Ciufo
75,450,525
5,858,752
What is the purpose of using tz_localize after tz_convert to convert to local time zone?
<p>In a codebase I am looking at, I see the following</p> <pre><code>local_timezone = get_local_timezone() df1[&quot;start_time&quot;] = df1.start_time.dt.tz_convert(local_timezone) # pandas dataframe df_merged = pd.merge(df1, df2, left_on=[&quot;start_time&quot;]) df_merged[&quot;start_time&quot;] = df_merged[&quot;...
<python><pandas><datetime><timezone>
2023-02-14 16:16:20
1
699
h8n2
75,450,403
12,242,625
Width of bars according to associated group
<p>We have a dataframe that contains various values of a broadcast medium.</p> <pre><code>+----+-------+--------+------+-------------+ | | MHz | Slot | dB | dB_median | |----+-------+--------+------+-------------| | 0 | 10 | Slot1 | 20 | 20.5 | | 1 | 20 | Slot1 | 21 | 20.5 | | 2 ...
<python><matplotlib><seaborn>
2023-02-14 16:05:09
1
3,304
Marco_CH
75,450,088
2,725,742
Get tkinter Entry to validate final state, skip intermediary deletions?
<p>So if I want to restrict a value to be between 100 and 200...</p> <pre><code>import tkinter as tk master = tk.Tk() def validatePLZ(index, value_if_allowed): print(&quot;validatePLZ with index:%s and proposed value:%s&quot; % (index, value_if_allowed)) if int(index) &gt; 3 or len(value_if_allowed) &gt; 3: ...
<python><validation><tkinter><tkinter-entry>
2023-02-14 15:37:15
1
448
fm_user8
75,449,953
5,959,685
Split a pandas dataframe into equal of multiple dataframe and convert to json
<p>Part of my program needs a certain kind of input. So I need to split a pandas dataframe into n multiple dataframes and convert to json without header for that input. E.g. I have a dataframe like this</p> <pre><code>`import pandas as pd myDf = pd.DataFrame(['banana', 'apple', 'watermelon','grapes','cherry', 'blueberr...
<python><json><pandas>
2023-02-14 15:23:40
1
423
Dutt
75,449,889
2,263,683
Check if request is coming from Swagger UI
<p>Using <code>Python</code> and <code>Starlette</code> or <code>FastAPI</code>, How can I know if the request is coming from the Swagger UI or anywhere else (Postman, Frontend app)?</p> <p>I tried to see if there's something in <code>Request</code> object which I can use:</p> <pre><code>from fastapi import Request @a...
<python><request><fastapi><starlette>
2023-02-14 15:18:49
1
15,775
Ghasem
75,449,820
18,883,443
ValueError: cannot reshape array of size 777600 into shape (720,1080,5)
<p>The following lines:</p> <pre><code>currentImageClip = ImageClip(r'path/to/image') imageClipWithCaption = CompositeVideoClip([ColorClip(size=(1080, 720), color='black'), currentImageClip]) </code></pre> <p>gives me the following error:</p> <pre><code>Traceback (most recent call last): File &quot;C:\Users\samlb\Doc...
<python><moviepy>
2023-02-14 15:12:38
0
634
THEMOUNTAINSANDTHESKIES
75,449,742
4,495,790
How to visualize boxplot for full column and per categories
<p>I want to have a multiple boxplot for my Pandas DataFrame with different boxes for <code>num_column</code> per each category levels in <code>cat_column</code> AND one box for the entire <code>num_column</code>. So far the best that I could do is double subplots (one for the entire column and one for the per category...
<python><matplotlib><seaborn><visualization>
2023-02-14 15:06:15
1
459
Fredrik
75,449,717
1,736,294
Fastapi Dependency Injection with CLI Arguments
<p>I want my fastapi routes to include a dependency injection formed from the parameters of a CLI.</p> <p>In the skeleton code below, a, b and c are the CLI parameters, Consort is the DI and the fastapi class is King.</p> <p>How can this be achieved?</p> <pre><code>import charles, william, george #program modules from...
<python><dependencies><singleton><fastapi>
2023-02-14 15:04:16
1
4,617
Henry Thornton
75,449,595
13,176,896
wxpython combobox value is not changed once selected
<p>I have wxpython code (wxpython version: 4.2.0). It has two Comboboxes to select value of x and y, and list of values for y is determined by x.</p> <pre><code>self.x = wx.ComboBox( self, wx.ID_ANY, &quot;x&quot;, wx.Point( 60, 43 ), (220, 30), x_choices, 0 ) self.x.Bind(wx.EVT_COMBOBOX, self.update_y) def update_y(s...
<python><combobox><window><wxpython>
2023-02-14 14:54:47
1
2,642
Gilseung Ahn
75,449,454
7,074,969
Image has 3 channels but it's in a grayscale color. If I change it to 1 channel, it goes into RGB
<p>I started doing some image-processing in python and I've stumbled upon an issue which is kind of confusing from a beginner's perspective. I have a dataset of 1131 np arrays (images) of MRI on knee. The shape of the images is kind of weird, it is <code>(44, 256, 256)</code> meaning that one array has 44 images with s...
<python><matplotlib>
2023-02-14 14:44:20
2
1,013
anthino12
75,449,407
9,195,600
How to sort boundary boxes from right to left and top to bottom
<p>I have a use case where I want to sort boundary boxes from the top right to the bottom left.</p> <blockquote> <p>args: dt_boxes(array): detected text boxes with shape [4, 2] return: sorted boxes(array) with shape [4, 2]</p> </blockquote> <p><strong>Example 1:</strong></p> <pre><code>[[[258.0, 52.0], [329.0, 46.0], [...
<python><sorting><bounding-box>
2023-02-14 14:40:16
1
633
ahmed osama
75,449,378
15,358,800
Pad middle values based on previouse and next values
<p>Let's say I've df Like this</p> <pre><code> col col2 0 0 Repeat1 1 3 Repeat2 2 5 Repeat3 3 7 Repeat4 4 9 Repeat5 </code></pre> <p>Reproducable</p> <pre><code>L= [0,3,5,7,9] L2 = ['Repeat1','Repeat2','Repeat3','Repeat4','Repeat5'] import pandas as pd df = pd.DataFrame({'col':L}) df['col2']=...
<python><pandas>
2023-02-14 14:37:47
3
4,891
Bhargav
75,449,296
11,586,490
Unable to find element that looks like it's dynamically generated
<p>I'm trying to find the email address text located in the below URL. You can clearly see the email address but I believe the text is generated dynamically through Javascript/React. When I copy the XPATH or CSS Selector and try to find the element like I would any other element I just get an error saying the element c...
<python><selenium-webdriver><selenium-chromedriver>
2023-02-14 14:30:58
2
351
Callum
75,448,985
1,018,861
Create duplicates of rows based on values in another column
<p>I'm trying to build a histogram of some data in polars. As part of my histogram code, I need to duplicate some rows. I've got a column of values, where each row also has a weight that says how many times the row should be added to the histogram.</p> <p>How can I duplicate my <code>value</code> rows according to the ...
<python><dataframe><python-polars>
2023-02-14 14:06:11
2
3,252
TomNorway
75,448,714
4,025,404
Writing a DataFrame to an excel file where items in a list are put into separate cells
<p>Consider a dataframe like <code>pivoted</code>, where replicates of some data are given as lists in a dataframe:</p> <pre><code> d = {'Compound': ['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C', 'C'], 'Conc': [1, 0.5, 0.1, 1, 0.5, 0.1, 2, 1, 0.5, 0.1], 'Data': [[100, 90, 80], [50, 40, 30], [10, 9.7, 8], ...
<python><excel><pandas><dataframe>
2023-02-14 13:42:50
2
957
John Crow
75,448,340
5,740,397
Python and ETL: Job and workflow/task mamangent trigger and other concepts
<p>i am writing a very simple ETL(T) pipline currently:</p> <ul> <li>look at ftp if new csv files exist</li> <li>if yes than donwload them</li> <li>Some initial Transformations</li> <li>bulk insert the individual CSVs into a MS sql DB</li> <li>Some additional Transformations</li> </ul> <p>There can be alot of csv files...
<python><etl><workflow><pipeline>
2023-02-14 13:10:52
1
565
NorrinRadd
75,448,320
3,617,165
Py4JJavaError when invoke pyspark distinct
<p>I am running a spark script in a course with Jupyter Notebook in Windows 10. I create my session with no problems and invoke the collect for an rdd that we tested.</p> <p>But when I try to run it with a distinct, I get the following error and I can't figure out how to fix it.</p> <pre><code>import findspark findspar...
<python><windows><apache-spark><pyspark><jupyter-notebook>
2023-02-14 13:09:33
0
368
alejomarchan
75,448,242
4,470,126
Databricks DLT pipeline with for..loop reports error "AnalysisException: Cannot redefine dataset"
<p>I have the following code which works fine for a single table. But when I try to use a for..loop() to process all the tables in my database, I am getting the error, <code>&quot;AnalysisException: Cannot redefine dataset 'source_ds',Map(),Map(),List(),List(),Map())&quot;</code>.</p> <p>I need to pass the table name ...
<python><pyspark><databricks><azure-databricks><delta-live-tables>
2023-02-14 13:02:47
1
3,213
Yuva
75,448,239
33,404
Quickbase Pipelines: How to extract nested JSON array, using Jinja, into Multi-Select Text field?
<p>I am using <a href="https://www.quickbase.com/" rel="nofollow noreferrer">Quickbase</a> <a href="https://helpv2.quickbase.com/hc/en-us/articles/4570257915924-About-Quickbase-Pipelines-" rel="nofollow noreferrer">Pipelines</a> to pull data from a REST API and save it into a table. The flow of the pipeline is:</p> <pr...
<python><json><jinja2><quickbase>
2023-02-14 13:02:29
2
16,911
urig
75,448,230
3,067,485
Filtering site with specific tags in Django while keeping all site tags aggregated in annotation field
<p>Let's say I have the following django model:</p> <pre><code>class Tag(models.Model): key = models.CharField(max_length=64, unique=True) class Site(models.Model): key = models.CharField(max_length=64, unique=True) tags = models.ManyToManyField(Tag, through='SiteTag') class SiteTag(models.Model): ...
<python><django><postgresql><filter><array-agg>
2023-02-14 13:01:57
1
11,564
jlandercy
75,448,227
14,471,688
Remove redundant tuples from dictionary based on the score
<p>I wonder if there is a fast way to remove redundant tuples from dictionary. Suppose I have a dictionary as below:</p> <pre><code>a = { 'trans': [('pickup', 1.0), ('boat', 1.0), ('plane', 1.0), ('walking', 1.0), ('foot', 1.0), ('train', 0.7455259731472191), ('trailer', 0.7227749512667475), ('car', 0.7759192750865...
<python><dictionary><tuples><redundancy>
2023-02-14 13:01:53
2
381
Erwin
75,448,200
6,372,189
How to read dbf file in python and convert it to dataframe
<p>I am trying to read a dbf file using <code>simpledbf</code> library and convert to to dataframe for further processing.</p> <pre><code>from simpledbf import Dbf5 dbf = Dbf5(r&quot;C:\Users\Prashant.kumar\Downloads\dbf\F1_1.DBF&quot;) df1 = dbf.to_dataframe() </code></pre> <p>Unfortunately, I am getting the following...
<python><pandas><dbf>
2023-02-14 13:00:27
1
701
Prashant Kumar
75,448,154
8,406,122
Extracting Named Entity from Input Utterance in python using regex
<p>Say I have some strings</p> <pre><code>&quot;Open Youtube&quot; &quot;Install PlayStore App&quot; &quot;Go to Call of Duty app&quot; </code></pre> <p>Now I have a <code>rules.list</code> file which contains all the rules in it to extract the named entity out of the above commands.</p> <p>Say the contents of rules.li...
<python><regex>
2023-02-14 12:56:01
1
377
Turing101
75,448,050
6,610
In Python, how to specify that a Protocol implementer has a specific constructor signature?
<p>Is it possible to define that a class needs a specific constructor?</p> <pre class="lang-py prettyprint-override"><code>class Constructible(Protocol): def __init__(self, i: int): # how do I do this? raise NotImplementedError def get_value(self): raise NotImplementedError def map_is(cs: Iterable[Const...
<python><constructor><protocols>
2023-02-14 12:46:09
1
41,708
xtofl
75,447,934
14,353,779
Partial String map from pandas dictionary
<p>I have a mapping dictionary written this way. How can I do a partial string search for the same? For e.g even if its <code>East South Central Division Conv</code> in text I need to map to 1,21,28,47 states. Also I need to match irrerspective of case ans spaces.</p> <p><code>state_code</code> is a column I have in <c...
<python><pandas><dataframe><dictionary>
2023-02-14 12:36:17
0
789
Scope
75,447,884
1,878,788
How to use seaborn kdeplot legend from one suplots axis for whole figure legend?
<p>I'm using seaborn to plot kdeplots on axes of subplots, and I want to have one global figure legend instead of one legend on each subplot.</p> <p>However, the axes I pass to <code>sns.kdeplot</code> or get from <code>sns.kdeplot</code> seem to have empty lists of handles and labels when I use <code>get_legend_handle...
<python><matplotlib><seaborn>
2023-02-14 12:32:07
0
8,294
bli
75,447,776
3,489,155
Trustpilot: how can I get reviews data via the API with a simple python starter script
<p>Ok, it just took me quite some time to figure out how to get (private) reviews data from the Trustpilot API using python.</p> <p>Yes, they have docs:<br /> <a href="https://developers.trustpilot.com/" rel="nofollow noreferrer">https://developers.trustpilot.com/</a><br /> <a href="https://developers.trustpilot.com/au...
<python><trustpilot>
2023-02-14 12:23:18
1
13,022
Sander van den Oord
75,447,775
10,760,601
Index matrix but return a list of lists Pytorch
<p>I have a 2-dimensional tensor and I would like to index it so that the result is a list of lists. For example:</p> <pre><code>R = torch.tensor([[1,2,3], [4,5,6]]) mask = torch.tensor([[1,0,0],[1,1,1]], dtype=torch.bool) output = R[mask] </code></pre> <p>This makes <code>output</code> as <code>tensor([1, 4, 5, 6])</c...
<python><performance><indexing><pytorch>
2023-02-14 12:23:14
1
346
Josemi
75,447,720
19,318,120
speech brain with voxlingua107 is not working properly
<p>I'm using voxlingua107 to detect language from audio first it works fine but after a while I tried downloading an audio file with Spanish but it detects English !</p> <pre><code>class AudioMixin: def detect_language(self, path) -&gt; str: language_id = EncoderClassifier.from_hparams(source=&quot;TalTechN...
<python><speech-recognition>
2023-02-14 12:17:34
1
484
mohamed naser
75,447,618
16,459,035
Unable to connect to mysql using docker-compose
<p>I am trying to connect to MySql DB using a python script ingested via docker. I have the following compose file:</p> <pre class="lang-yaml prettyprint-override"><code>version: '3.9' services: mysql_db: image: mysql:latest restart: unless-stopped environment: MYSQL_DATABASE: ${MY_SQL_DATABASE} ...
<python><docker>
2023-02-14 12:07:09
2
671
OdiumPura
75,447,466
19,189,069
How to remove any non-Persian character in a string in python?
<p>I want to remove any non-Persian character in a string in python. For example if I have a string like this:</p> <pre><code>00Ψ³Ω„Ψ§Ω…abc </code></pre> <p>I have the Persian characters and the result becomes like this:</p> <pre><code>Ψ³Ω„Ψ§Ω… </code></pre> <p>I know that it is possible that I can extract just Persian charact...
<python>
2023-02-14 11:54:19
1
385
HosseinSedghian
75,447,445
3,939,193
Python: Force Virtual Environments to use system certificate store on Windows
<p>My company uses a VPN, which does not work with the PIP certificate check out of the box. When I install a package with <code>pip install asyncio</code>, it gives me the following error:</p> <blockquote> <p>Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSL...
<python><pip><python-venv>
2023-02-14 11:52:28
1
904
DrDonut
75,447,371
3,225,420
Bokeh ColumnDataSource Error when identifying as source - why?
<p>I'm getting error messages when identifying ColumnDataSource as my source, want to do it right.</p> <p>Let me show the errors.</p> <p>First, I generate some random data in a DataFrame and put it into the ColumnDataSource:</p> <pre><code>col_list = ['ob1','ob2','ob3','ob4','ob5'] df = pd.DataFrame(np.random.uniform(7...
<python><bokeh>
2023-02-14 11:45:46
1
1,689
Python_Learner
75,447,361
24,334
reading csv with values with international numbers
<p>I am trying to read a CSV which contains numbers in a European manner for instance:</p> <pre><code>&quot;COL_A&quot;, &quot;COL_B&quot; &quot;ID_A&quot;, &quot;47,37&quot; </code></pre> <p>I am reading it with a code like:</p> <pre><code>pl.read_csv(inputfile, dtypes={COL_B:float}, infer_schema_length=200) </code></...
<python><dataframe><csv><python-polars>
2023-02-14 11:45:03
2
1,767
call me Steve
75,447,336
13,629,335
CTRL KeyPress event is fired trough scrolling with TouchPad
<p>I'm trying to track the control-key when it's pressed and released.<br /> While everything seemed fine in the beginning, but when scrolling with my touch-pad on my HP laptop on Windows 11 the KeyPress event is fired automatically.</p> <p>Is this a Windows thing and is <em>normal behavior</em> or is it a <em>bug</em>...
<python><tkinter><tcl><tk-toolkit><gesture>
2023-02-14 11:42:55
1
8,142
Thingamabobs
75,447,077
6,751,456
python athena calculate total number of output rows
<p>I need to get total number of output rows returned by Athena.</p> <pre><code> status = 'RUNNING' while status in ['QUEUED', 'RUNNING']: response_get_query_details = athena.get_query_execution( QueryExecutionId=query_execution_id ) status = ( response_get_query_...
<python><amazon-web-services><boto3><amazon-athena>
2023-02-14 11:20:25
1
4,161
Azima
75,447,018
10,811,647
Return several values inside for loop
<p>I have a function that must return several values using a for loop. I do not wish to store the values inside a list or a dict. Because of the use of the <code>return</code>, I only get the first value. How can I return all values successively? I tried using generators and <code>yield</code> but I'm not sure how to u...
<python><return><generator><plotly-dash><yield>
2023-02-14 11:14:31
2
397
The Governor
75,446,974
4,427,375
How to frame a simple Factorio/Dyson Sphere factory problem in linear programming using `scipy.optimize`
<p>I'm trying to frame a Linear Programming problem from the game Dyson Sphere (a Factorio clone) and then use <code>scipy</code> to optimize for it. The problem is as follows:</p> <p>The problem is as follows: I have a copper mine which produces 150 copper per minute. I can build multiple copper plate factories each o...
<python><scipy><mathematical-optimization><linear-programming><scipy-optimize>
2023-02-14 11:11:00
0
1,873
Grant Curell
75,446,886
5,197,034
Selecting columns based on a condition in Polars
<p>I want to select columns in a Polars DataFrame based on a condition. In my case, I want to select all string columns that have less than 100 unique values. Naively I tried:</p> <pre><code>df.select((pl.col(pl.String)) &amp; (pl.all().n_unique() &lt; 100)) </code></pre> <p>which gave me an error, which is probably du...
<python><dataframe><python-polars>
2023-02-14 11:01:50
2
2,603
pietz
75,446,862
1,441,998
How do I get Python to talk to the portmidi c library on Windows 11/64
<p>I'm trying to get <a href="https://github.com/PortMidi/portmidi" rel="nofollow noreferrer">portmidi</a> working with Python on Windows 11/64.Β  I'm able to compile the dll/lib in MSVS without errors, without specifying any changes or options.Β  I'm new to this, so I don't know how to tell the system about the librarie...
<python><windows><cython><ctypes><pyportmidi>
2023-02-14 10:59:35
0
459
user1441998
75,446,780
17,160,160
Extracting items from array using variable sliding window in Python
<p>I have an array of digits: <code>array = [1.0, 1.0, 2.0, 4.0, 1.0]</code></p> <p>I would like to create a function that extracts sequences of digits from the input array and appends to one of two lists depending on defined conditions being met</p> <p>The first condition <code>f</code> specifies the number of places ...
<python>
2023-02-14 10:50:58
1
609
r0bt
75,446,597
14,494,483
Understanding streamlit data flow and how to submit form in a sequential way
<p>Below is a simple reproducible example that works to illustrate the problem in its simple form. You can jump to the code and expected behaviour as the problem description can be long.</p> <h2>The main concept</h2> <p>There are 3 dataframes stored in a list, and a form on the sidebar shows the <code>supplier_name</co...
<python><streamlit>
2023-02-14 10:34:41
2
474
Subaru Spirit
75,446,455
3,299,347
Mock psycopg2 database insertion in Python
<p>My unit test does not mock the database insertion because I do see in the logs and in the database that the record id <code>42</code> had been inserted in the database, see logs:</p> <pre><code>./tests/test_requesthandler.py::TestRequestHandler::test_handle_post_coordinates Failed: [undefined]AssertionError: {'id': ...
<python><python-3.x><unit-testing><mocking><psycopg2>
2023-02-14 10:23:56
2
1,279
superkytoz
75,446,132
5,722,359
How to convert Path("/home/user/mypic.jpg").stat().st_ctime to human-readable datetime format?
<p>I got the creation time of a file using this command:</p> <pre><code>ctime = Path(&quot;/home/user/mypic.jpg&quot;).stat().st_ctime </code></pre> <p>How do I convert this info to a <code>datetime.datatime</code> object that is human-readable? I tried this <a href="https://stackoverflow.com/a/10256141/5722359">answer...
<python>
2023-02-14 09:56:30
1
8,499
Sun Bear
75,446,122
7,183,388
Python: How to annotate a variable number of iterable attributes?
<p>I have a class family for which I need to be able to iterate through attributes of type: <code>Metric</code>.</p> <p>The family consists of an abstract base class parent and child classes. The child classes will all have varying number of class attributes of type Metric, and they inherit an <code>__iter__</code> met...
<python><python-typing>
2023-02-14 09:55:27
1
353
Archie
75,446,087
12,242,085
How to avoid overfitting on multiclass classification OvR Xgboost model / class_weight in Python?
<p>I try to build multiclass classification model in Python using XGBoost OvR (OneVsRest) like below:</p> <pre><code>from xgboost import XGBClassifier from sklearn.multiclass import OneVsRestClassifier from sklearn.metrics import roc_auc_score X_train, X_test, y_train, y_test = train_test_split(abt.drop(&quot;TARGET&q...
<python><scikit-learn><xgboost><multiclass-classification><overfitting-underfitting>
2023-02-14 09:52:20
1
2,350
dingaro
75,445,810
12,932,447
How to implement a "Citation" table? (using SQLModel or SQLAlchemy)
<p>I'm struggling with implementing the concept of &quot;scientific paper citation&quot; in SQL.</p> <p>I have a table of <code>Paper</code>s. Each <code>Paper</code> can <em><strong>cite</strong></em> many other <code>Paper</code>s and, vice-versa, it can <em><strong>be cited</strong></em> by many other more.</p> <p>H...
<python><sqlalchemy><foreign-keys><sqlmodel>
2023-02-14 09:28:50
1
875
ychiucco
75,445,290
778,508
Poetry No File/Folder for Package
<p>I have a simple project layout</p> <pre><code>myproject on ξ‚  main [$!?] is πŸ“¦ v1.0.0 via  v18.14.0 via 🐍 v3.10.9 ❯ tree -L 1 . β”œβ”€β”€ build β”œβ”€β”€ deploy β”œβ”€β”€ Dockerfile β”œβ”€β”€ poetry.lock β”œβ”€β”€ pyproject.toml β”œβ”€β”€ README.md β”œβ”€β”€ scripts.py └── src </code></pre> <p>The <code>pyproject.toml</code> is:</p> <pre><code>[tool.poetr...
<python><python-poetry>
2023-02-14 08:46:42
6
8,046
gdm
75,445,200
6,357,916
googlesearch package in colab
<p>I can do following in google colab:</p> <pre><code>import googlesearch as g urls = list(g.search(search_string, stop=results_count, lang='en')) </code></pre> <p>But I am guessing which package is this <code>googlesearch</code>?</p> <p>I checked <a href="https://pypi.org/project/googlesearch-python/" rel="nofollow no...
<python><pip><google-colaboratory><pypi>
2023-02-14 08:38:42
1
3,029
MsA
75,445,186
11,809,811
force Toplevel Widget on top of root widget
<p>I have a tkinter app with a Toplevel widget that I want to create when the window is starting. The issue I have is that the Toplevel window always ends up behind the main window. Is there a way to force it in front of the root window?</p>
<python><tkinter><customtkinter>
2023-02-14 08:37:38
1
830
Another_coder
75,445,030
11,998,382
Lazily transpose dimensions 0 and 2 in iterator model
<p>Given an iterable of an iterable of an iterable <code>it_it_it</code> (i.e. a lazy representation of 3d array) you can lazily transpose dimensions <code>0</code> and <code>1</code> by <code>zip(*it_it_it)</code> and dimensions <code>1</code> and <code>2</code> by <code>map(lambda it_it: zip(*it_it), it_it_it)</code>...
<python><iterator>
2023-02-14 08:20:09
3
3,685
Tom Huntington
75,445,025
283,538
get centroid latitude and longitude of h3 hexagon
<p>I know ho to get h3 hexagon ids for various resolutions and add them to a pandas dataframe containing latitudes and longitudes. Is it possible to get the centroid latitude and longitude of each h3 hexagon given its id? I saw function but do not know how to use it in this context cell_to_latlng. Any pointers would be...
<python><h3>
2023-02-14 08:19:53
2
17,568
cs0815
75,444,625
13,874,745
How to update the weights of a composite model composed of pytorch and torch-geometric?
<p>I made a composite model <code>MainModel</code> which consist of a <code>GinEncoder</code> and a <code>MainModel</code> which containing some <code>Linear</code> layers, and the <code>GinEncoder</code> made by the package <code>torch-geometric</code>, show as following codes :</p> <pre class="lang-py prettyprint-ove...
<python><pytorch><neural-network><pytorch-geometric><graph-neural-network>
2023-02-14 07:31:07
1
451
theabc50111
75,444,464
5,028,320
Automated ML Scheduled Pipeline Not Triggerring Automatically
<p>I have 2 pipelines:</p> <ol> <li>Uploading data from a blob storage to the datastore (to update the data asset)</li> <li>Training model</li> </ol> <p>I also have 2 schedules:</p> <ol> <li>Triggers every 10 minutes to call the pipeline 1</li> <li>Triggers when there is a new data in datastore</li> </ol> <p>I used <a ...
<python><azure><machine-learning><pipeline><automl>
2023-02-14 07:10:59
0
716
Ashyam
75,444,303
1,640,005
Clicking on button in discord channel does not execute the code in on_button_click
<p>The purpose of this code is to</p> <ol> <li>create the channel if it doesnt exist (this works) and write a welcome message in it (this works)</li> <li>when you type in !open_ticket it should create a button and display it along with a message (this works)</li> <li>click the button and it will create a new channel wi...
<python><discord><discord.py>
2023-02-14 06:47:17
1
799
zoonosis
75,444,216
4,470,126
Databricks DLT reading a table from one schema(bronze), process CDC data and store to another schema (processed)
<p>I am developing an ETL pipeline using databricks DLT pipelines for CDC data that I recieve from kafka. I have created 2 pipelines successfully for landing, and raw zone. The raw one will have operation flag, a sequence column, and I would like to process the CDC and store the clean data in processed layer (SCD 1 ty...
<python><databricks><azure-databricks><delta-live-tables>
2023-02-14 06:32:27
1
3,213
Yuva
75,444,215
16,853,253
Unable to display image in html flask
<p>I'm trying to render an image in html in flask, the path is pointing to the correct file but its not rendering some how.</p> <p>#VIEWS</p> <pre><code>@inventory_bp.route(&quot;/show&quot;) def show_image(): id = 3 image = Images.query.get(id) upload_folder = app.config['UPLOAD_FOLDER'] image_path = o...
<python><flask>
2023-02-14 06:32:26
1
387
Sins97
75,444,181
9,609,843
pathlib.Path.exists returns False for broken symlink
<p>Consider this setup in a command line:</p> <pre><code>touch test.txt ln -s test.txt test.lnk rm test.txt </code></pre> <p>So we have a broken symlink that points to deleted file. Now in Python:</p> <pre class="lang-py prettyprint-override"><code>import pathlib p = pathlib.Path('test.lnk') p.is_symlink() # True p.ex...
<python><linux><symlink>
2023-02-14 06:28:41
3
8,600
sanyassh
75,444,036
194,547
DRF: API root view doesn't list my APIs for some reasons
<p>I have the following <code>urls.py</code> for an app named <code>service</code> where I register API endpoints:</p> <pre><code>from .views import AccessViewSet, CheckViewSet app_name = &quot;api&quot; router = DefaultRouter() router.register(r&quot;access/(?P&lt;endpoint&gt;.+)&quot;, AccessViewSet, basename=&quo...
<python><django><regex><routes><django-rest-framework>
2023-02-14 06:06:47
1
2,595
varnie
75,443,943
15,793,575
Efficiently replacing values in each row of pandas dataframe based on condition
<p>I would like to work with a pandas data frame to get a strange yet desired output dataframe. For each row, I'd like any values of 0.0 to be replaced with an empty string (''), and all values of 1.0 to be replaced with the value of the index. Any given value on a row can only be 1.0 or 0.0.</p> <p>Here's some example...
<python><pandas>
2023-02-14 05:50:37
3
393
frustrated_bioinformatician