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,323,839
2,814,378
Write ORC using Pandas with all values of sequence None
<p>I want to write a simple dataframe as an ORC file. The only sequence is of an integer type. If I set all values to <code>None</code>, an exception is raised on <code>to_orc</code>.</p> <p>I understand that <code>pyarrow</code> cannot infer datatype from <code>None</code> values but what can I do to fix the datatype ...
<python><pandas><pyarrow><orc>
2023-02-02 13:24:04
1
2,380
Blaf
75,323,826
20,443,541
How to upload a image to google-lens using python?
<p>I'm trying to scrape <strong><a href="https://images.google.com/" rel="nofollow noreferrer">google-lens</a></strong> with python <code>requests</code> but can't find the request where it uploads the image or how it is decoded.</p> <p>The request (which the answer is the image-analysis) is as following:</p> <pre clas...
<python><encryption><cryptography><binary><base64>
2023-02-02 13:23:16
1
1,159
kaliiiiiiiii
75,323,747
1,901,071
Polars looping through the rows in a dataset
<p>I am trying to loop through a Polars recordset using the following code:</p> <pre class="lang-py prettyprint-override"><code>import polars as pl df = pl.DataFrame({ &quot;start_date&quot;: [&quot;2020-01-02&quot;, &quot;2020-01-03&quot;, &quot;2020-01-04&quot;], &quot;Name&quot;: [&quot;John&quot;, &quot;Jo...
<python><dataframe><loops><python-polars>
2023-02-02 13:15:45
3
2,946
John Smith
75,323,597
3,575,623
Reorder dataframe groupby medians following custom order
<p>I have a dataset containing a bunch of data in the columns <code>params</code> and <code>value</code>. I'd like to count how many values each <code>params</code> contains (to use as labels in a boxplot), so I use <code>mydf['params'].value_counts()</code> to show this:</p> <pre><code>slidingwindow_250 11574 hots...
<python><pandas>
2023-02-02 13:02:58
1
507
Whitehot
75,323,511
14,351,788
how to call class properties in function with Python
<p>Here is an example:</p> <p>I have a student class like this</p> <pre><code>class student(): def __init__(self, x, y, z): self.name = x self.age = y self.ID = z </code></pre> <p>and a function to print the corresponding property:</p> <pre><code>def printer(student, parameter_name): pri...
<python><class>
2023-02-02 12:55:02
1
437
Carlos
75,323,510
3,423,825
How to sort querysets from different models based on two fields?
<p>I have querysets from different models which have only two fields in common: <code>datetime</code> and <code>dt_created</code>, and I would like to sort the objects first on <code>datetime</code> and then on <code>dt_created</code>, so that objects with the same <code>datetime</code> are sorted based on field <code>...
<python><django>
2023-02-02 12:54:54
2
1,948
Florent
75,323,506
9,182,743
seaborn stop figure from being visualized
<p>A figure generated with seaborn is being visualized, even without f.show().</p> <p>I want the figure to be only visualized when i call it.</p> <pre class="lang-py prettyprint-override"><code>import numpy as np import matplotlib.pyplot as plt import seaborn as sns def plot_kde_x (x): sns.set(style=&quot;ticks&qu...
<python><seaborn>
2023-02-02 12:54:39
2
1,168
Leo
75,323,400
15,934,951
Squared Error Relevance Area (SERA) implementation in Python as custom evaluation metric
<p>I'm facing an imbalanced regression problem and I've already tried several ways to solve this problem. Eventually I came a cross this new metric called SERA (Squared Error Relevance Area) as a custom scoring function for imbalanced regression as mentioned in this paper. <a href="https://link.springer.com/article/10....
<python><machine-learning><metrics><loss-function><catboost>
2023-02-02 12:45:25
1
517
Daniel Aben-Athar Bemerguy
75,323,383
7,599,292
How to deal with DataCollator and DataLoaders in Huggingface?
<p>I have issues combining a DataLoader and DataCollator. The following code with DataCollatorWithPadding results in a <code>ValueError: Unable to create tensor, you should probably activate truncation and/or padding with 'padding=True' 'truncation=True' to have batched tensors with the same length.</code> when I want ...
<python><pytorch><huggingface-transformers><dataloader><huggingface-datasets>
2023-02-02 12:43:53
1
396
3r1c
75,323,365
1,581,090
Is there a python package - import mapping available?
<p>When I run a python code and it imports a library that is missing an error is printed out that this library cannot be imported, for example</p> <pre><code>import cv2 import PIL </code></pre> <p>for order to install these two example packages, however, you have to install them as follows</p> <pre><code>pip install op...
<python><pypi>
2023-02-02 12:41:38
0
45,023
Alex
75,323,297
6,256,859
Django form not populating with POST data
<p><strong>Problem:</strong> Django form is populating with list of <strong>objects</strong> rather than <strong>values</strong></p> <p><strong>Summary:</strong> I have 2 models <em>Entities</em> and <em>Breaks</em>. <em>Breaks</em> has a FK relationship to the <em>entity_id</em> (not the PK) on the <em>Entities</em> m...
<python><django><django-models><django-views><django-forms>
2023-02-02 12:36:43
2
1,080
Andy
75,323,079
19,079,397
How to extract coordinates falling in a bbox from a geopandas data frame?
<p>I have a geopandas dataframe with coordinates and long with data frame I have a bbox. Now I want to apply the bbox on the data frame and extract the coordinates that's falling in that bbox. I tried using <code>gpd.clip</code> to extract but it is returning an empty data frame. What is the best way to extract the coo...
<python><mask><geopandas><bounding-box><clip>
2023-02-02 12:19:00
2
615
data en
75,322,989
4,753,897
Getting NameError in unittests for testing a parameter from argparse
<p>I normally use Python for scripts but I am trying to write a unit test and am having a lot of issues. I would like to test a method that creates a parameter <code>--users</code>. The value is how many occurred.</p> <pre><code>count_users(df, args.metrics) </code></pre> <p>It is a spark dataframe and the metrics are ...
<python><python-3.x>
2023-02-02 12:12:02
1
12,145
Mike3355
75,322,860
6,805,754
Executing commands incorrectly in Jenkins pipeline shell script
<p>I set pyenv to an enabled state. And if there is no python version corresponding to the pipfile through pipenv, I tried to install the corresponding python version automatically through pyenv.</p> <blockquote> <p>[Reference] Automatically install required Python version when pyenv is available. at <a href="https://p...
<python><jenkins><jenkins-pipeline><pipenv><pyenv>
2023-02-02 11:59:52
0
611
S.Kang
75,322,509
3,394,021
Convert Blocking python function to async function
<p>So currently I have 4 api requests which are called in synchronous method using a third_party lib which is synchronous. What i want is to run them in parallel. So that my total time to call all 4 apis is reduced.</p> <p>I am using fastapi as micro framework.</p> <p>utilities.py</p> <pre><code>async def get_api_1_dat...
<python><asynchronous><async-await><python-asyncio><fastapi>
2023-02-02 11:28:46
1
995
Abhishek Sachan
75,322,357
648,044
How to run unittest tests from multiple directories
<p>I have 2 directories containing tests:</p> <pre><code>project/ | |-- test/ | | | |-- __init__.py | |-- test_1.py | |-- my_submodule/ | |-- test/ | |-- __init__.py |-- test_2.py </code></pre> <p>How can I run all tests?</p> <p><code>python -m unittest discover .</code...
<python><unit-testing><python-unittest>
2023-02-02 11:16:43
2
2,561
Guglie
75,322,244
11,714,087
Appending python dictionary values to a python list
<p>I am trying to process my api result string the result string format is given below. My goal is to add these values to a list where each element of list will be a dictionary.</p> <pre><code>result_str = '['{&quot;abc.xyz&quot;: &quot;80983098429842&quot;,&quot;dev.uvw&quot;: 898420920},' \ '{&quot;a...
<python><python-3.x>
2023-02-02 11:05:51
1
377
palamuGuy
75,322,177
7,422,352
ERROR: Failed building wheel for sentencepiece while installing flair on python 3.10
<p>While installing <code>flair</code> using <code>pip install flair</code> in python 3.10 virtual environment on <code>mac-os</code> Ventura, I get the following error:</p> <p><code>ERROR: Failed building wheel for sentencepiece</code></p> <p>Seperately installing <code>sentencepeice</code> using <code>pip install se...
<python><python-3.x><flair>
2023-02-02 11:00:08
6
5,381
Deepak Tatyaji Ahire
75,322,169
859,227
Decreasing column values with Pandas
<p>I would like to decrease values in a column. The following code</p> <pre><code>df['ID'] = df.index df.loc[df['ID'].astype(int)] -= 1 </code></pre> <p>Should convert</p> <pre><code> ID Process ID Name Time 0 0 NaN NaN msecond 1 1 32434.0 X1 1.4 2 2 32434.0 X2 1.3 </code></...
<python><python-3.x><pandas>
2023-02-02 10:59:36
1
25,175
mahmood
75,322,094
10,795,473
SQLAlchemy relationship fields name constructor
<p>I'm using SQLAlchemy 1.4 to build my database models (posgresql).</p> <p>I've stablished relationships between my models, which I follow using the different SQLAlchemy capabilities. When doing so, the fields of the related models get aliases which don't work for me.</p> <p>Here's an example of one of my models:</p> ...
<python><postgresql><sqlalchemy>
2023-02-02 10:52:36
2
309
aarcas
75,322,024
4,199,496
How set a C char** pointer in Python
<p>I want to set a C <code>char**</code> pointer, called <code>results</code>, in Python. The variable is in a dll I have loaded. I want to set results so that it points to a string in Python. I want to get the string I created in Python (or at least a copy of it since ctypes does a lot of copying) to be pointed to by ...
<python><c><dll><ctypes>
2023-02-02 10:47:31
1
302
drlolly
75,321,840
14,291,703
How to update PySpark df on the basis of other PySpark df?
<pre><code>df1 +------------------------------------------------------ |ID| NAME|ADDRESS|DELETE_FLAG|INSERT_DATE|UPDATE_DATE| +------------------------------------------------------ | 1|sravan|delhi |false |25/01/2023 |25/01/2023| | 2|ojasvi|patna |false |25/01/2023 |25/01/2023| | 3|rohith|jaipur |false ...
<python><pyspark>
2023-02-02 10:33:42
1
512
royalewithcheese
75,321,833
6,629,309
how to add new tag value to a exiting yaml file using python
<p>I want to add additional tag value to below yaml contents.</p> <p><strong>Base Yaml</strong></p> <pre><code>infra: etcd: container: replica_count: 3 resource: limit_memory: 1000Mi limit_cpu: 1000m requests_memory: 1000Mi requests_cpu: 1000m volume: storageC...
<python><python-3.x><yaml>
2023-02-02 10:33:21
1
345
samir
75,321,775
7,800,760
Python and pylint: conflicting errors
<p>My <strong>rssita.py</strong> python code has the following lines:</p> <pre><code>from feeds import RSS_FEEDS from termcolors import PC </code></pre> <p>and this is the corresponding directory tree:</p> <pre><code>(rssita-py3.10) (base) bob@Roberts-Mac-mini rssita % tree . ├── README.md ├── poetry.lock ├── pyproject...
<python><pylint><pre-commit-hook><pre-commit>
2023-02-02 10:28:41
0
1,231
Robert Alexander
75,321,652
1,045,755
Remove duplicated rows based on a Series of lists in which item order doesn't matter
<p>I have a data frame with a lot of columns. But one column has values/lists that look like this:</p> <pre><code>df = val1 --------------- 0 [&quot;hej&quot;, &quot;hello&quot;] 1 [&quot;mus&quot;, &quot;mouse&quot;] 2 [&quot;hest&quot;, &quot;horse&quot;] 3 [&quot;hello&quot;, &quot;hej&quot;] 4 [&quot;mo...
<python><pandas>
2023-02-02 10:19:38
1
2,615
Denver Dang
75,321,543
13,174,189
Why is my hungarian algorithm application function not working?
<p>I want to solve this combinatorial optimization task using Hungarian algorithm:</p> <p>Different teams of the same company may have employees in different cities. If employees have the same position, we can swap them. And the goal is to distribute employees to teams in such a way as to maximize the number of teams t...
<python><python-3.x><algorithm><function><hungarian-algorithm>
2023-02-02 10:11:01
0
1,199
french_fries
75,321,526
12,193,952
How to pass arguments to function (FastAPI endpoint) loaded from JSON?
<p>I have a FastAPI endpoint which takes up to 70 parameters and they are often added or removed. I have also list of arguments sent to this API stored in <code>JSON</code> format (extracted using <code>json.dumps(locals())</code>), so I can easily reproduce the API call in the future.</p> <p>I would like to call EP <c...
<python><json><arguments><fastapi>
2023-02-02 10:09:42
1
873
FN_
75,321,353
6,218,501
Searching string among 5Gb of text files
<p>I have several CSV files (~25k in total) with a total size of ~5Gb. This files are in a network path and I need to search for several strings inside all these files and to save the files' names (in an output file for example) where these strings are found.</p> <p>I've already tried two things:</p> <ol> <li>With Wind...
<python><powershell><batch-file>
2023-02-02 09:55:50
2
461
Ralk
75,321,312
5,868,293
Create an indicator column if a column contains many string values in pandas
<p>I have a pandas dataframe that looks like this:</p> <pre><code>import pandas as pd pd.DataFrame({'id': [1,1,1,2,2,3,3,3], 'col': ['a','a','a','a','b','c','b','a']}) id col 0 1 a 1 1 a 2 1 a 3 2 a 4 2 b 5 3 c 6 3 b 7 3 a </code></pre> <p>I would like to create an indica...
<python><pandas>
2023-02-02 09:50:58
2
4,512
quant
75,321,159
7,522,285
Google Auth sign in - Redirect URI Mismatch
<p>I am trying to add Google OAuth login/register to my app, first testing it locally then on the web.</p> <p>Google OAuth has been set up. Redirect URLs as below: <a href="https://i.sstatic.net/zfOX9.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/zfOX9.png" alt="enter image description here" /></a></p>...
<python><flask><google-cloud-platform><google-oauth>
2023-02-02 09:38:46
1
1,359
TimothyAURA
75,321,138
12,928,363
How to allow 'filter' query parameter Django REST Framework JSON API?
<p>I am using Django REST Framework with <code>djangorestframework-jsonapi</code></p> <p>When I query with <code>filter[name]=THEOS</code> DRF raise an error into my browser. I tried to query with this URL</p> <pre><code>http://localhost:8000/api/space_objects/?filter[name]=THEOS </code></pre> <p>THe other parameter fr...
<python><json><django><django-rest-framework><json-api>
2023-02-02 09:37:16
1
377
Paweenwat Maneechai
75,321,022
5,336,651
Efficient way of requiring that a certain portion of elements from a Hypothesis strategy must be unique
<p>What is the most efficient way of requiring rather than that all elements generated according to a <code>hypothesis</code> strategy are unique, at least a certain portion are unique?</p> <p>Strategies such as the following appear to be inefficient when multiply composed partly because of the <code>unique=True</code>...
<python><pytest><python-hypothesis>
2023-02-02 09:26:14
0
401
curlew77
75,320,937
14,193,797
Why doesn't float() throw an exception when the argument is outside the range of a Python float?
<p>I'm using <code>Python 3.10</code> and I have:</p> <pre class="lang-py prettyprint-override"><code>a = int(2 ** 1023 * (1 + (1 - 2 ** -52))) </code></pre> <p>Now, the value of <code>a</code> is the biggest integer value in <a href="https://en.wikipedia.org/wiki/Double-precision_floating-point_format" rel="nofollow n...
<python><floating-point>
2023-02-02 09:17:23
1
4,663
justANewb stands with Ukraine
75,320,562
5,775,358
Python polars speed issue
<p>I have python code that runs fast on my laptop, but terrible slow on a desktop. The desktop is new with a better cpu and more ram. Why is the same code slower?</p> <p>I use polars and this is my code:</p> <pre><code>def remove_timezone(df: pl.DataFrame, col: str = 't'): return df.with_column( pl.col(col)...
<python><pandas><datetime><python-polars>
2023-02-02 08:44:25
0
2,406
3dSpatialUser
75,320,508
2,642,356
Apply `torch.nn.MultiheadAttention`’s heads to same input
<p>My question surely has a simple answer, but I couldn't find it. I wish to apply <code>MultiheadAttention</code> to the same sequence without copying the sequence. My data is temporal data with dimensions (batch, time, channels). I treat the &quot;channels&quot; dimension as the embedding, and the time dimension as t...
<python><deep-learning><pytorch><nlp><attention-model>
2023-02-02 08:39:06
0
1,864
EZLearner
75,320,399
2,919,052
Qml, Reference error <signalName> is not defined when signal defined
<p>I have a very simple qml+python app to play and test signal/slot communication.</p> <p>All works fine so far, but when I run the app, a <code>ReferenceError</code> is reported on the QML side.</p> <p>However, all works fine, it is so simple code:</p> <p><strong>QML:</strong></p> <pre><code>import QtQuick 2.0 import ...
<python><qt><qml><pyside6>
2023-02-02 08:29:04
1
5,778
codeKiller
75,320,243
419,399
conda disappeared, command not found - corrupted .zshrc
<p>All of the sudden, my terminal stopped recognizing the 'conda'. Also the VS Code stopped seeing my environments.</p> <p>All the folders, with my precious environments are there (<code>/opt/anaconda3</code>), but when I type conda I get:</p> <pre><code>conda zsh: command not found: conda </code></pre> <p>I ...
<python><macos><conda>
2023-02-02 08:11:22
3
1,230
Intelligent-Infrastructure
75,320,160
18,273,129
pytest-html extras customizing code understanding
<p>I'm trying to customize report.html of pytest using pytest-html plugin.</p> <p>I searched up many sites(including pytest-html documentation) and found that the code below is commonly used.(The code is in conftest.py)</p> <p>(<a href="https://pytest-html.readthedocs.io/en/latest/user_guide.html#extra-content" rel="no...
<python><pytest><pytest-html><pytest-html-reporter>
2023-02-02 08:02:18
1
341
jaemmin
75,320,104
75,612
svgwrite rotate issues causes spiral result
<p>Im trying to create canvas filed with triangles with random rotation and size but as soon as I try rotation everything gets out of wack. If rotation is turned off the resulting svg looks like expected</p> <p><a href="https://i.sstatic.net/XViPH.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/XViPH.png...
<python><svgwrite>
2023-02-02 07:54:39
0
494
NccWarp9
75,320,065
19,556,055
How do I quickly drop rows based on the max value in a groupby?
<p>I have a large dataframe containing information on people and their job change history. Sometimes, someone had multiple changes to their record on one day, each of which is assigned a transaction sequence number. I just want to keep the rows with the highest transaction sequence number of that day. Currently, I'm us...
<python><pandas><group-by>
2023-02-02 07:50:46
1
338
MKJ
75,320,011
2,091,247
Point out of curve
<p>I have the secp256k1 elliptic curve and I would like to print a Dot on that curve. However, the dot is out of curve and I can not see why.</p> <ul> <li><p>python 3.10.7</p> </li> <li><p>manim 0.17.2</p> </li> </ul> <p>Thanks for any help.</p> <pre><code>from manim import * class eliptic_curves(MovingCameraScene): ...
<python><manim>
2023-02-02 07:44:08
1
10,731
Radim Bača
75,319,944
2,385,132
How are keras tensors connected to layers that create them
<p>In the book &quot;Machine Learning with scikit-learn and Tensorflow&quot; there's a code fragment I can't wrap my head around. Until that chapter, their models were only explicitly using layers - be it in a sequential fashion, or functional. But in the chapter 16, there's this:</p> <pre><code>import tensorflow_addon...
<python><tensorflow><keras>
2023-02-02 07:37:01
1
3,930
Marek M.
75,319,924
10,689,857
Switching PyCharm project between Python versions
<p>I have a project in pycharm which I am currently running in python 3.9 However, I want to compare how would it behave under python 3.11</p> <p>I have tried File-Settings-Python Interpreter - Add Interpreter- Add Local Interpreter and tried adding 3.11 from there but it says &quot;Environment location directory is no...
<python><pycharm>
2023-02-02 07:33:08
2
854
Javi Torre
75,319,803
806,160
how Install the Delta Lake package on the on-premise environment?
<p>I want make a data lake for my self without using any cloud service. I now have an Debian server and I want create this data lake with Databricks solution, Delta Lake.</p> <p>As I search all sample for stablish Delta Lake in could service.</p> <p>How can I do this in my own server?</p> <p>Maybe I want create an clus...
<python><pyspark><debian><delta-lake><data-lake>
2023-02-02 07:17:03
1
1,423
Tavakoli
75,319,736
20,646,427
How to check user for 2 fields from another model with ManyToMany fields
<p>How am i suppose to check request.user for 2 fields in the same time</p> <p>I want to show different pages in header if user is customer or contractor by another many to many field or if he is contractor and customer in same time show both pages</p> <p>Im not sure how am i suppose to do that</p> <p>Models.py:</p> <p...
<python><django>
2023-02-02 07:09:11
1
524
Zesshi
75,319,170
1,896,222
azure log analytics InsufficientAccessError
<p>I am trying to read log analytics in python. Here is my code:</p> <pre><code>AZURE_CLIENT_ID = '' AZURE_CLIENT_SECRET = '' AZURE_TENANT_ID = '' workspace_id = '' from azure.identity import ClientSecretCredential from datetime import datetime from azure.monitor.query import LogsQueryClient, LogsQueryStatus start_ti...
<python><azure><azure-log-analytics>
2023-02-02 05:52:43
1
10,564
max
75,319,159
18,758,062
Get Cloudflare R2 Public URL after uploading file using boto3
<p>Is there a way to upload a file to Cloudflare R2 storage using <code>boto3</code> in Python, and get the public URL that it can be accessed at?</p> <p>The files are being uploaded by doing</p> <pre><code>s3 = boto3.resource( &quot;s3&quot;, endpoint_url=endpoint_url, aws_access_key_id=aws_access_key_id, ...
<python><amazon-s3><boto3><cloudflare><cloudflare-r2>
2023-02-02 05:51:11
0
1,623
gameveloster
75,319,024
10,844,937
How to merge dataframe faster?
<p>I have a <code>df</code> as following</p> <pre><code>import pandas as pd df = pd.DataFrame( {'number_1': ['1', '2', None, None, '5', '6', '7', '8'], 'fruit_1': ['apple', 'banana', None, None, 'watermelon', 'peach', 'orange', 'lemon'], 'name_1': ['tom', 'jerry', None, None, 'paul', 'edward', 'reggie', ...
<python><pandas>
2023-02-02 05:29:34
1
783
haojie
75,318,798
7,218,871
In a 2D Numpy Array find max streak of consecutive 1's
<p>I have a 2d numpy array like so. I want to find the maximum consecutive streak of 1's for every row.</p> <pre><code>a = np.array([[1, 1, 1, 1, 1], [1, 0, 1, 0, 1], [1, 1, 0, 1, 0], [0, 0, 0, 0, 0], [1, 1, 1, 0, 1], [1, 0, 0, 0, 0], [...
<python><arrays><numpy>
2023-02-02 04:50:20
1
620
Abhishek Jain
75,318,347
7,946,143
Updating an 2d array created using 2 * operator produces unexpected side effect in python
<p>I tried making a 2d array using 2 approaches in python. Why does approach 1 provide an unexpected side effect where all the rows get updated?</p> <pre><code>dp1 = [ [0] * 5 ] * 8 dp1[2][2] = dp1[1][1] + 1 print(&quot;DP1&quot;) for dp in dp1: print(dp) dp2 = [[0] * 5 for _ in range(8)] dp2[2][2] = dp2[1][1] + 1 p...
<python><arrays><matrix>
2023-02-02 03:21:19
0
3,110
Dracula
75,318,191
2,655,127
How to select dropdown in the dynamic table Selenium webdriver
<p>I have HTML tables like</p> <pre><code>&lt;table id='table1'&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td colspan='2'&gt;Food&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Burger&lt;/td&gt; &lt;td&gt; &lt;select class=&quot;form-control input-sm&quot; id=&quot;xx2&quot; onchange=...
<python><python-3.x><selenium><selenium-webdriver><xpath>
2023-02-02 02:51:25
4
853
jack
75,317,985
7,188,929
problem in lists content in DNN work by python
<p>i have three list [weights,n,org_weigths] in the code below It is assumed that only List [n] changes, but when viewing the other lists, we find that they are changing with the same change in List [n]</p> <pre><code>for i in range(size): for j in range(len(weights[i])): print(&quot;the index is [&quot;,i,...
<python><list><deep-learning><artificial-intelligence>
2023-02-02 02:06:28
1
321
maath frman
75,317,799
14,291,703
How to update a delta table with the missing row using PySpark?
<p>I need to update delta table on the basis of update delta table rows.</p> <pre><code>Update table (source_df) +---------------------------------------------------------- |ID| NAME|ADDRESS|DELETE_FLAG|INSERT_DATE|UPDATE_DATE| +---------------------------------------------------------- | 1|sravan|delhi |false |...
<python><pyspark><databricks><delta-lake><databricks-sql>
2023-02-02 01:25:00
0
512
royalewithcheese
75,317,762
6,498,757
Pandas: find interval distance from N consecutive to M consecutive
<h1>TLDR version:</h1> <p>I have a column like below,</p> <pre><code>[2, 2, 0, 0, 0, 2, 2, 0, 3, 3, 3, 0, 0, 2, 2, 0, 0, 0, 0, 2, 2, 0, 0, 0, 3, 3, 3] # There is the probability that has more sequences, like 4, 5, 6, 7, 8... </code></pre> <p>I need a function that has parameters n,m, if I use n=2, m=3, I will get a dis...
<python><pandas><dataframe>
2023-02-02 01:16:51
1
351
Yiffany
75,317,640
10,270,590
How to save down Django user's updated social media post?
<h2>Goal</h2> <ul> <li>A user can edit the post that that specific user made. Bly clicking edit than editing than pressing save.</li> </ul> <h2>Problem</h2> <ul> <li>When I edit the social media post it does not get saved</li> </ul> <h2>Description</h2> <ul> <li>I can make a mew post like in social media</li> <li>Post ...
<javascript><python><html><css><django>
2023-02-02 00:49:50
1
3,146
sogu
75,317,584
11,501,160
pypdf gives output with incorrect PDF format
<p>I am using the following code to resize pages in a PDF:</p> <pre><code>from pypdf import PdfReader, PdfWriter, Transformation, PageObject, PaperSize from pypdf.generic import RectangleObject reader = PdfReader(&quot;input.pdf&quot;) writer = PdfWriter() for page in reader.pages: A4_w = PaperSize.A4.width A4...
<python><pypdf>
2023-02-02 00:33:24
2
305
Zain Khaishagi
75,317,575
1,470,373
read keyboard/stdin asynchronously
<p>I have a loop where I would like to do something until a key is pressed. Is there a way to read input from stdin in another thread until a specific key is pressed? Is there a better way to do this?</p> <pre><code>def capture_loop(dev_path, breakout_key=&quot;a&quot;): captured_devs = [] capture = True d...
<python><multithreading><stdin>
2023-02-02 00:29:52
1
1,592
Rusty Weber
75,317,356
8,222,791
Unable to share global variable between threads with flask
<h2>Context</h2> <p>I'm trying to write a python flask server that answers a simple request. The data to be returned in the response is queried from a backend service. Since this query may take some time to complete, I don't want to do it synchronously, I want to have it run periodically, in a background thread, where ...
<python><multithreading><flask><module>
2023-02-01 23:44:54
1
2,303
joao
75,317,209
16,011,842
AccessDenied when calling Boto3 assume_role from EC2 even with service principal
<p>I'm running into an issue when trying to have a Python script running on an EC2 instance assume a role to perform S3 tasks. Here's what I have done.</p> <ol> <li>Created a IAM role with <code>AmazonS3FullAccess</code> permissions and got the following <code>ARN</code>:</li> </ol> <p><code>arn:aws:iam::&lt;account_n...
<python><amazon-web-services><amazon-ec2><boto3>
2023-02-01 23:21:25
1
329
barneyAgumble
75,317,183
17,553,278
How to display code as code with color using python django
<p>Context: I'm developing a web application using Python Django, and I want to display code snippets in the browser with syntax highlighting. For example, I would like to display the following code with different colors:</p> <pre><code>if True: print(&quot;Hello World&quot;) </code></pre> <p>I want to achieve this...
<python><html><css><django><colors>
2023-02-01 23:15:25
2
325
Baboucarr Badjie
75,317,104
15,724,084
Python pandas lower data AttributeError: 'Series' object has no attribute 'lower'
<p>I want to lower data taken from pandas sheet and trim all spaces then to look for an equality.</p> <pre><code>df['ColumnA'].loc[lambda x: x.lower().replace(&quot; &quot;, &quot;&quot;) == var_name] </code></pre> <p>Code is above. It says pandas series has no lower method. But I need to search for data inside column ...
<python><pandas>
2023-02-01 23:02:50
1
741
xlmaster
75,316,866
9,235,704
Get partial output from nbconvert.preprocessors.ExecutePreprocessor
<p>Is there a way to get partial output from nbconvert.preprocessors.ExecutePreprocessor? Currently, I use the ExecutePreprocessor to execute my Jupyter notebook programmatically, and it returns the output after executing the entire notebook. However, it would be great to be able to get and save the partial results and...
<python><jupyter-notebook><jupyter><ipython>
2023-02-01 22:28:17
1
2,090
Julian Chu
75,316,822
12,574,341
Python annotate type as difference of two TypedDicts
<p>In set theory you can subtract set B from set A to derive a new set consisting of members that are in A but not in B.</p> <pre><code>A = {x,y,z} B = {z} C = A - B = {x,y} </code></pre> <p>I want to achieve this in Python by subtracting two <code>TypedDicts</code> to derive a new type annotation</p> <pre class="lang-...
<python><python-typing>
2023-02-01 22:22:46
0
1,459
Michael Moreno
75,316,811
1,231,560
How can I parse a row's column value passed to a UDF when mapping a column?
<p>I have a dataframe like this, for the sake of simplicity i'm just showing 2 columns both columns are <code>string</code>, but in real life it will have more columns each of different types other than <code>string</code>:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: ...
<python><sql><apache-spark><pyspark>
2023-02-01 22:21:44
1
826
Jose R
75,316,741
10,007,302
AttributeError: 'Engine' object has no attribute 'execute' when trying to run sqlalchemy in python to manage my SQL database
<p>I have the following line of code that keeps giving me an error that Engine object has no object execute. I think I have everything right but no idea what keeps happening. It seemed others had this issue and restarting their notebooks worked. I'm using Pycharm and have restarted that without any resolution. Any help...
<python><mysql><sql><sqlalchemy>
2023-02-01 22:11:04
3
1,281
novawaly
75,316,580
12,821,675
Django - FileField - PDF vs octet-stream - AWS S3
<p>I have a model with a file field like so:</p> <pre class="lang-py prettyprint-override"><code>class Document(models.Model): file = models.FileField(...) </code></pre> <p>Elsewhere in my application, I am trying to download a pdf file from an external url and upload it to the file field:</p> <pre class="lang-py p...
<python><django><amazon-web-services>
2023-02-01 21:51:44
1
3,537
Daniel
75,316,579
12,436,050
Explode pandas dataframe column values to separate rows
<p>I have following pandas dataframe:</p> <pre><code>id term code 2445 | 2716 abcd | efgh 2345 1287 hgtz 6567 </code></pre> <p>I would like to explode <code>id</code> and <code>term</code> column. How can I explode multiple columns to keep the values across the columns <code>id...
<python><pandas><dataframe>
2023-02-01 21:51:37
2
1,495
rshar
75,316,508
7,158,458
Access to XMLHttpRequest has been blocked by CORS even though CORS set up in backend
<p>I have a flask backend and a React frontend. I am trying to do a POST request to my backend but get the error:</p> <pre><code>Access to XMLHttpRequest at 'http://127.0.0.1:5000/predict' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control chec...
<javascript><python><reactjs><flask>
2023-02-01 21:42:53
1
2,515
Emm
75,316,353
1,839,674
tf.data.datasets set each batch (prefetch)
<p>I am looking for help thinking through this.</p> <p>I have a function (that is not a generator) that will give me any number of samples. Let's say that getting all the data I want to train (1000 samples) can't fit into memory. So I want to call this function 10 times to get smaller number of samples that fit into me...
<python><python-3.x><tensorflow><tf.data.dataset><tf.dataset>
2023-02-01 21:25:30
1
620
lr100
75,316,207
12,574,341
Python equivalent to `as` type assertion in TypeScript
<p>In TypeScript you can override type inferences with the <code>as</code> keyword</p> <pre class="lang-none prettyprint-override"><code>const canvas = document.querySelector('canvas') as HTMLCanvasElement; </code></pre> <p>Are there similar techniques in Python3.x typing without involving runtime casting? I want to do...
<python><python-typing>
2023-02-01 21:08:23
2
1,459
Michael Moreno
75,316,073
10,400,238
How to format numerical labels into datetime labels on a plotly xaxis in python?
<p>I have a plotly scatter plot like this example:</p> <pre><code>x = [1,2,3,4,5] y = [3,2,3,5,6] fig = go.Figure() fig.add_trace(go.Scatter(x=x, y=y)) fig.show() </code></pre> <p>Now I want to label the x-axis numbers as dates with this dates for example:</p> <pre><code>dates = pd.date_range('2022-01-01', periods=len...
<python><datetime><plotly><axis-labels><x-axis>
2023-02-01 20:53:16
1
488
till Kadabra
75,315,828
3,937,811
How to resolve ModuleNotFoundError: No module named 'gluonts.torch.modules.distribution_output'?
<p>I am working on a project and I am trying to run the code from this repository: <a href="https://github.com/jc-audet/WOODS" rel="nofollow noreferrer">https://github.com/jc-audet/WOODS</a></p> <p>I was able to get past this step:</p> <pre><code>python3 -m woods.scripts.download_datasets {dataset} \ --data_pat...
<python><machine-learning><pytorch><gluonts>
2023-02-01 20:25:31
1
2,066
Evan Gertis
75,315,827
4,385,647
Read concatenation of json file in python
<p>I have a text file containing multiple valid json texts, something like this</p> <pre><code>{ &quot;items&quot;: [ { &quot;id&quot;: &quot;someID&quot;, &quot;vale&quot;: &quot;someValue&quot; }, { &quot;id&quot;: &quot;otherID&quot;, &quot;...
<python><json>
2023-02-01 20:25:23
0
3,855
Dirk Horsten
75,315,788
12,282,349
Response model as list of strings instead of objects
<p>I am trying to return a list of items in FastAPI via a Pydantic model.</p> <p>Currently I have the route:</p> <pre class="lang-py prettyprint-override"><code>from typing import List from fastapi import Depends from sqlalchemy.orm.session import Session ... @router.get('/search-job-types', response_model=List[JobT...
<python><sqlalchemy><fastapi><pydantic>
2023-02-01 20:22:20
2
513
Tomas Am
75,315,748
9,235,704
How do I build something similar to a jupyter notebook code cell with rich outputs
<p>How do I construct a script such that given a code block, it will return and display rich output like that of a cell of a Jupyter notebook? For example, is there a way to get the output section of the ipynb file given the code for the cell?</p> <p><a href="https://i.sstatic.net/1MgSx.png" rel="nofollow noreferrer"><...
<javascript><python><html><jupyter-notebook><ipython>
2023-02-01 20:18:28
1
2,090
Julian Chu
75,315,701
7,267,480
linear Interpolation between points of dataframe using nearest points of dataframe
<p>I need a quick solution to interpolate between the nearest points of a data frame without adding new points to a data frame if there is a lot of data - millions of points (without NANs). The dataframe is sorted using x vlaues.</p> <p>E.g. I have a dataframe with the next columns:</p> <pre><code>x | y ----- 0 | 1 1 |...
<python><pandas><interpolation>
2023-02-01 20:13:51
1
496
twistfire
75,315,505
7,320,048
Removing Duplicate Domain URLs From the Text File Using Bash
<p>Text file</p> <pre><code>https://www.google.com/1/ https://www.google.com/2/ https://www.google.com https://www.bing.com https://www.bing.com/2/ https://www.bing.com/3/ </code></pre> <p>Expected Output:</p> <pre><code>https://www.google.com/1/ https://www.bing.com </code></pre> <p>What I Tried</p> <pre><code>awk -F'...
<python><bash><awk>
2023-02-01 19:53:47
2
959
Praveen Kumar
75,315,492
1,114,453
subprocess to print stderr and stdout in real-time
<p>Say I have this program <code>printer.py</code>:</p> <pre><code>#!/usr/bin/env python3 import sys import time sys.stdout.write(&quot;STDOUT 1\n&quot;) time.sleep(1) sys.stderr.write(&quot;STDERR 2\n&quot;) time.sleep(1) sys.stdout.write(&quot;STDOUT 3\n&quot;) time.sleep(1) sys.stderr.write(&quot;STDERR 4\n&quot;)...
<python><subprocess><stdout><real-time><stderr>
2023-02-01 19:53:07
1
9,102
dariober
75,315,443
17,696,880
How to capture all the substrings inside a string that start with an element of a list and end with another element of another list?
<pre class="lang-py prettyprint-override"><code>import re #input string capture_where_capsule = &quot;alrededor ((NOUN)del auto rojizo, algo grande y completamente veloz). Luego dentro del baúl rápidamente abajo de una caja por sobre ello vimos una caña.&quot; #list of adverbs indicating the start of the capture list...
<python><python-3.x><regex><replace><regex-group>
2023-02-01 19:48:59
0
875
Matt095
75,315,390
3,286,743
Construct date column from year, month and day in Polars
<p>Consider the following Polars dataframe:</p> <pre class="lang-py prettyprint-override"><code>import polars as pl df = pl.DataFrame({'year': [2023], 'month': [2], 'day': [1]}) </code></pre> <p>I want to construct a date column from <code>year</code>, <code>month</code> and <code>day</code>. I know this can be done by...
<python><python-polars>
2023-02-01 19:43:07
1
1,177
robertdj
75,315,365
2,458,922
With Pandas Calculate Diff , but with different columns
<p>Give Data As</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame({&quot;Start&quot;: [1, 4, 8, 12], &quot;Stop&quot;: [2, 6, 9, 13]}) # Calculate df['lag'] = Previous[Stop] - This[Start] </code></pre> <p>Lag = NA for first Row. Else Lag = Current Row Start - Previous Row Stop</p> <p>Output:</p> ...
<python><pandas>
2023-02-01 19:40:39
1
1,731
user2458922
75,314,899
5,520,444
pytorch's augmented assignment and requires_grad
<p>Why does:</p> <pre><code>with torch.no_grad(): w = w - lr*w.grad print(w) </code></pre> <p>results in:</p> <pre><code>tensor(0.9871) </code></pre> <p>and</p> <pre><code>with torch.no_grad(): w -= lr*w.grad print(w) </code></pre> <p>results in:</p> <pre><code>tensor(0.9871, requires_grad=True) </c...
<python><pytorch><augmented-assignment>
2023-02-01 18:54:33
1
1,228
Tony Power
75,314,891
5,243,291
Python MYSql update Syntax error using dynamic variables
<p>I am trying to update a MySQL table with dynamic column name and value. I m always getting a syntax Error when I m doing the update. I have similar INSERT and SELECT statements which work as expected. I have already tried different variants of the query to get the right syntax</p> <pre><code> cursor.execute(&quot;&...
<python><mysql><python-3.x>
2023-02-01 18:53:51
0
2,144
Vini
75,314,866
3,486,773
How to convert string into list of integers in Python?
<p>I have this:</p> <pre><code> &quot;1,2,3,4,5,6,7,8,9,0&quot; </code></pre> <p>And need this:</p> <pre><code> [1,2,3,4,5,6,7,8,9,0] </code></pre> <p>Everything I search for has the example where the string is a list of strings like this:</p> <pre><code> &quot;'1','2','3'...&quot; </code></pre> <p>those solutions...
<python><string><list>
2023-02-01 18:51:53
3
1,278
user3486773
75,314,863
3,357,935
How do I safely iterate over an optional list in Python?
<p>I have a function which compares a file path against two lists of folder paths. It returns true if the start of the path matches any folder from list A (<code>include</code>) but doesn't match an optional list B (<code>exclude</code>).</p> <pre><code>from typing import List, Optional def match(file: str, include: L...
<python>
2023-02-01 18:51:43
3
27,724
Stevoisiak
75,314,836
2,030,532
How to "tell" the decorator function that the return type is the same as the wrapped function in Python?
<p>I have a decorator whose return type is the same as the wrapped function return type. Here is a simple example. The code works as it stands, however, it does not provide type hinting for the output value <code>res</code>. Is there a way to specify that <code>my_decorator</code> return the same type as the wrapped f...
<python><types><pycharm>
2023-02-01 18:49:01
1
3,874
motam79
75,314,822
10,386,434
In Python, io.StringIO codec writer gets string in input but gives "TypeError: string argument expected, got 'bytes'"
<p>Simple example</p> <pre><code>import codecs import io buffer = io.StringIO() writer = codecs.getwriter('UTF-8') buffer_writer = writer(buffer) buffer_writer.write('[]') </code></pre> <p>output</p> <pre><code>Traceback (most recent call last): File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt; File &quot;/...
<python><io>
2023-02-01 18:47:11
0
451
vinicius de novaes
75,314,658
3,557,485
Can a bug in a Python library produce a ModuleNotFoundError?
<p>I have to run a simple code snippet which uses the <a href="https://pypi.org/project/mexc-sdk/0.0.1/#description" rel="nofollow noreferrer">mexc_sdk</a> library. I installed it properly, it is in the proper folder, but somehow I get the <code>ModuleNotFoundError: No module named 'mexc_sdk'</code> message when I run ...
<python>
2023-02-01 18:33:36
1
3,360
rihekopo
75,314,624
4,784,683
PyQt QTreeView - simulate selection of new item without using Squish
<p>I have existing PySide6 code.</p> <p>My class <code>PyProto</code> inherits <code>QTreeView</code> and implements <code>currentChanged()</code>.</p> <p>I am doing automated testing and I need to move the focus to any item in the <code>QTreeView</code>.</p> <p>When I put a breakpoint on <code>PyProto.currentChanged()...
<python><qt><pyqt>
2023-02-01 18:29:42
0
5,180
Bob
75,314,508
4,856,421
Disable pylint missing docstring warning for protected classes
<p>Is it possible to disable pylint warnings related to missing docstring within a module for protected (starting with underscore character) classes only? There is a possibility to disable warnings for method or classes that fulfill a certain regex precondition(by default everything which starts with _ is omited) but w...
<python><pylint>
2023-02-01 18:18:40
0
781
Mati
75,314,436
13,359,498
Can't concatinate texture_features and resnet50_features
<p>I have extracted resnet features(array) and texture features(list) of my image dataset. My idea is to concatinating both of the features and then use the merged feature to fit the model. Code snippet:</p> <pre><code># Extract features from the dataset using ResNet50 resnet50_features = ResNet50.predict(X_test) for c...
<python><keras><deep-learning><tensor><feature-extraction>
2023-02-01 18:10:02
0
578
Rezuana Haque
75,314,435
5,769,814
Combining flags in argparse
<p>I have the following subclass that extends <code>argparse.ArgumentParser</code> with some helper methods for adding common argument types:</p> <pre><code>import argparse class ArgParser(argparse.ArgumentParser): def add_bool_arg(self, default, help, *flags, **kw): &quot;&quot;&quot; Add a boolean argum...
<python><command-line-arguments><argparse>
2023-02-01 18:09:58
1
1,324
Mate de Vita
75,314,250
5,991,368
Python WeakKeyDictionary for unhashable types
<p>As raised in <a href="https://github.com/python/cpython/issues/88306" rel="nofollow noreferrer">cpython issue 88306</a>, python <a href="https://docs.python.org/3/library/weakref.html#weakref.WeakKeyDictionary" rel="nofollow noreferrer">WeakKeyDictionary</a> fails for non hashable types. According to the discussion ...
<python>
2023-02-01 17:53:04
1
661
Peter Barmettler
75,314,234
5,469,184
How to convert list of JSON object to PySpark DataFrame?
<p>I want to convert a JSON string in variable to PySpark DataFrame on Databricks.</p> <p>I have a payload coming from API. It is a list of JSON objects hold on a variable called <code>response_list</code>. The variable is JSON object with type of <code>class 'str'&gt;</code>:</p> <pre class="lang-json prettyprint-over...
<python><json><pyspark><databricks><azure-databricks>
2023-02-01 17:51:45
1
434
mmustafaicer
75,314,154
19,155,645
YOLOv7 segmentation: error with using pre-trained weights
<p>I would like to use YOLOv7 for segmentation on my custom dataset and custom classes. <br> I am already able to run the 'normal' YOLO version with my data and using the <code>yolov7.pt</code> weights.<br> But when I am using the <code>yolov7-mask.pt</code> weights, I end up having an error:</p> <pre><code>Traceback (...
<python><deep-learning><computer-vision><image-segmentation><yolo>
2023-02-01 17:44:46
0
512
ArieAI
75,314,041
169,947
Check whether timezone is dateutil.tz instance
<p>There are several Python packages that implement the <code>datetime.tzinfo</code> interface, including <code>pytz</code> and <code>dateutil</code>. If someone hands me a timezone object and wants me to apply it to a datetime, the procedure is different depending on what kind of timezone object it is:</p> <pre class...
<python><timezone><pytz><python-dateutil>
2023-02-01 17:35:07
2
24,277
Ken Williams
75,314,032
1,096,660
How to grab video frames fast?
<p>For my project I want to extract frames from a video to make thumbnails. However every method i find is super slow going through the entere video. Here is what I have tried:</p> <pre><code>with iio.imopen(v.file.path, &quot;r&quot;) as vObj: metadata = iio.immeta(v.file.path, exclude_applied=False) frame_num...
<python><python-3.8><python-imageio>
2023-02-01 17:34:15
1
2,629
JasonTS
75,313,984
3,120,129
pywin32 alternative in C# for SAP GUI automation?
<p>I have got Python and Visual Basic working. I am struggling to find a working solution for C# although I understand that it should be available and relatively similar to Visual Basic, right? I don't have SAP GUI DLL's on my development machine, so I can't just add reference to it.</p> <p>So in Python this is working...
<python><c#><vba><vb.net><sap-gui>
2023-02-01 17:28:50
1
2,422
10101
75,313,920
3,798,897
How can I accelerate the matrix multiplication XAX^T when A is sparse?
<p>Suppose <code>X</code> has <code>r</code> rows and <code>c</code> columns, so that <code>A</code> is a <code>c</code> by <code>c</code> matrix. If the total count of non-zero elements in <code>A</code> (call it <code>z</code>) is small then the following Python/pseudocode is plenty fast enough. If <code>c</code> is ...
<python><sparse-matrix><matrix-multiplication>
2023-02-01 17:22:11
0
7,191
Hans Musgrave
75,313,835
10,976,654
What is the difference between creating tox environment for linting and using pre-commit hooks
<p>I am learning CI/CD for Python packages and have worked through the text and examples in Dane Hillards's new Book <a href="https://www.manning.com/books/publishing-python-packages" rel="nofollow noreferrer">Publishing Python Packages</a>. I know there are a lot of different tools and approaches, but I am new to this...
<python><continuous-integration><github-actions><pre-commit-hook><pre-commit.com>
2023-02-01 17:14:33
0
3,476
a11