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,846,512
12,750,353
Cannot record with a Gradio audio input using dynamic layout
<p>I want to create an interface with <code>gradio</code> where I have an initially hidden audio input, that after some steps, e.g. receiving instructions, the user can record audio. But when I make the audio input visible it is unable to record.</p> <pre class="lang-py prettyprint-override"><code>import gradio with g...
<python><jupyter-notebook><gradio>
2023-03-26 07:52:33
1
14,764
Bob
75,846,414
1,581,090
How to test the python backend of a flask application?
<p>I have a draft of a flask application with a html/javascript frontend and a python backend, to which the frontend communicates through the flask API.</p> <p>I want to test the python backend using the API using python only (no javascript etc involved in the testing). I found <a href="https://circleci.com/blog/testin...
<python><flask>
2023-03-26 07:24:31
3
45,023
Alex
75,846,194
15,155,978
How to download Google Drive files to a Jupyter notebook using the Google Drive Python API?
<p>I'm trying to download my Google Drive files to a Jupyter notebook using the Google Drive Python API. Thus, I'm following this <a href="https://medium.com/@umdfirecoml/a-step-by-step-guide-on-how-to-download-your-google-drive-data-to-your-jupyter-notebook-using-the-52f4ce63c66c" rel="nofollow noreferrer">post</a>. B...
<python><jupyter-notebook><google-drive-api>
2023-03-26 06:23:10
3
922
0x55b1E06FF
75,845,973
523,612
What causes `None` results from BeautifulSoup functions? How can I avoid "AttributeError: 'NoneType' object has no attribute..." with BeautifulSoup?
<p>Often when I try using BeautifulSoup to parse a web page, I get a <code>None</code> result from the BeautifulSoup function, or else an <code>AttributeError</code> is raised.</p> <p>Here are some self-contained (i.e., no internet access is required as the data is hard-coded) examples, based off an example in the <a h...
<python><beautifulsoup><attributeerror><nonetype>
2023-03-26 05:06:12
2
61,352
Karl Knechtel
75,845,952
5,513,260
python udf iterator -> iterator giving outputted more rows error
<p>Have dataframe with text column CALL_TRANSCRIPT (string format) and pii_allmethods column (array of string). Trying to search Call_Transcripts for strings in array &amp; mask using pyspark pandas udf. Getting outputted more than input rows errors. Tried couple of ways to troubleshoot , but not able to resolve.</p> <...
<python><pyspark><pandas-udf>
2023-03-26 04:57:01
1
421
Mohan Rayapuvari
75,845,867
417,896
Arrow Julia to Python - Read Record Batch Stream
<p>I am trying to read an arrow file that I wrote as a sequence of record batches in python. For some reason I am only getting the first struct entry. I have verified the files are bigger than one item and of expected size.</p> <pre><code>with pa.OSFile(input_filepath, 'rb') as source: with pa.ipc.open_stream(sou...
<python><julia><apache-arrow>
2023-03-26 04:32:12
1
17,480
BAR
75,845,842
3,810,748
Is the default `Trainer` class in HuggingFace transformers using PyTorch or TensorFlow under the hood?
<h2>Question</h2> <p>According to the <a href="https://huggingface.co/docs/transformers/v4.27.2/en/main_classes/trainer" rel="nofollow noreferrer">official documentation</a>, the <code>Trainer</code> class &quot;provides an API for feature-complete training in PyTorch for most standard use cases&quot;.</p> <p>However, ...
<python><tensorflow><pytorch><huggingface-transformers>
2023-03-26 04:19:32
2
6,155
AlanSTACK
75,845,832
9,729,023
AWS Lambda : How Can We Pass the Event by Lambda Test Event, Instead Of Transformer In Event Bridge?
<p>We have the sceduled job to count and export several tables by Lambda Function. We usually pass the timestamp and table name to Lambda Function by transformer in Event Bridge.</p> <p>We'd like to run Lambda Function manually by Lambda Test Event, when we need to run only specific table as trouble shooting. I set the...
<python><aws-lambda><aws-event-bridge>
2023-03-26 04:16:42
1
964
Sachiko
75,845,668
6,296,626
How to sniff network traffic while on VPN?
<p>Using <code>scapy</code> I am able to sniff the UDP network traffic between port 10 and 20 like shown in this simple code example:</p> <pre class="lang-py prettyprint-override"><code>from scapy.all import * def capture_traffic(packet): if packet.haslayer(IP) and packet.haslayer(UDP): if 10 &lt;= packet[...
<python><network-programming><vpn><scapy><packet-sniffers>
2023-03-26 03:09:14
0
1,479
Programer Beginner
75,845,492
12,902,027
Raising exception in init causes SystemError: returned a result with an error set in Python C API
<p>I am using pytest to test my own Python C extension module. I am trying to check if the <code>TypeError</code> occurs properly when an argument of invalid type is input to the <code>__init__</code> method. The method implementation is something like</p> <pre class="lang-c prettyprint-override"><code>PyObject * myObj...
<python><error-handling><pytest><cpython><python-c-api>
2023-03-26 01:54:57
2
301
agongji
75,845,280
10,044,690
Constraining equation that includes multiple variables at a boundary using GEKKO
<p>I have a system of differential equations that I'm trying to perform some optimal control on, using Gekko. In particular, I have a point-mass orbiting a planet and would simply like to raise its orbit using modelled thrusters as control inputs. In order to set the final radial position and velocity at the new raised...
<python><gekko>
2023-03-26 00:29:52
1
493
indigoblue
75,845,142
13,566,716
aioredis.exceptions.ConnectionError: Connection closed by server
<p>I get this error randomly with redis on heroku.</p> <pre><code>aioredis.exceptions.ConnectionError: Connection closed by server. </code></pre> <p>this is the full trace:</p> <pre><code>2023-03-25T23:34:34.116795+00:00 app[web.1]: There was an exception checking if the field exists in the hashmap: await wasn't used w...
<python><python-3.x><redis><python-asyncio><redis-py>
2023-03-25 23:41:14
1
369
3awny
75,845,010
7,587,176
NY Times API -- Comments not being returned
<p>I have code below that is intended to first try NY Times API &amp; then bs4 for scraping with the goal of creating a data set of each comment on an article that I pass in via a link. In turn outputting some NLP data anlaysis. I am very close but also a bit conufused as my input returns the first pargraph of the arti...
<python><web-scraping>
2023-03-25 23:02:24
1
1,260
0004
75,845,000
15,255,487
Pydantic schemas throws error although in payload needed properties exists
<p>In my flask + react project I use pydantic for validation of front-end payload. I have properties of payload coded as below:</p> <pre><code>class PersonsSchema(BaseModel): id = str name: Optional[str] lastName: Optional[str] class TagSchema(BaseModel): name: Optional[str] id: str class Update...
<python><flask><backend><pydantic>
2023-03-25 23:01:03
1
912
marcinb1986
75,844,984
788,153
Get the groupby column back in pandas
<p>I am doing a groupby on column <code>a</code> followed by <code>ffill</code>, but after groupby the column <code>a</code> is gone. The result df will have only column <code>b</code> and <code>c</code>. Is there a way to get the column <code>a</code> back after groupby and ffill? I am assuming that the values will sh...
<python><pandas>
2023-03-25 22:55:10
3
2,762
learner
75,844,951
4,627,565
how to efficiently unzip large datasets in our local folder in google Colab?
<p>What is the fastest way to unzip folders with large datasets for model training?</p> <pre><code> from zipfile import ZipFile # import training dataset output='/dataset' zf = ZipFile('/content/train_data.zip', 'r') # read input zip file zf.extractall(output) # extract to the output_dir in this case /content/sam...
<python><google-colaboratory><unzip>
2023-03-25 22:47:49
0
2,359
Bionix1441
75,844,912
357,024
Python asyncio sleep forever
<p>In some test code I simulate a request handler coroutine that never returns a response. Below works by calling <code>sleep</code> with a sufficiently large value, but a better choice would be something like <code>await asyncio.sleep_forever()</code>. Is there anything built into python asyncio that can do this?</p> ...
<python><python-asyncio>
2023-03-25 22:35:52
1
61,290
Mike
75,844,871
3,629,654
Clean way to open/close an optional file in python?
<p>My code:</p> <pre><code>fh = None if args.optional_input_file_path is not None: fh = open(args.optional_input_file_path) my_function(foo, bar, fh) if args.optional_input_file_path is not None: fh.close() </code></pre> <p>I don't like how I need to write <code>if args.optional_input_file is not None:</code>...
<python><file-handling>
2023-03-25 22:28:05
3
841
Tan Wang
75,844,751
608,576
Better way of checking query string parmeter in Django
<p>I have quite some integer query string params that I convert this way. Is there built in better way in python to handle this ?</p> <pre><code>current_page = request.GET.get('page') if current_page is not None and current_page.isnumeric(): current_page = int(current_page ) else current_page = 0 </code></pr...
<python><django>
2023-03-25 21:56:15
1
9,830
Pit Digger
75,844,604
8,372,455
algorithm to save frames from a video file
<p>Is it possible to save a desired amount of images (<code>DESIRED_FRAMES_TO_SAVE</code>) from a video file spread-out evenly throughout the entire video file footage?</p> <p>Hopefully this makes sense I have a video file that is 8 seconds in length and I would like to save 60 Frames of the video file in sequential or...
<python><opencv>
2023-03-25 21:25:25
2
3,564
bbartling
75,844,527
12,760,550
Replace column values using another pandas dataframe mapping
<p>Imagine I have the following dirty data of employee information of their contracts across countries (<code>df1</code>):</p> <pre><code>ID Country Name Job Date Grade 1 CZ John Office 2021-01-01 Senior 1 SK John . 2021-01-01 Assistant 2 AE Peter ...
<python><pandas><apply><group>
2023-03-25 21:09:40
1
619
Paulo Cortez
75,844,524
11,141,816
Compute matrix inverse with decimal object
<p>There's a related questions <a href="https://stackoverflow.com/questions/32685280/matrix-inverse-with-decimal-type-numpy">Matrix inverse with Decimal type NumPy</a> 2015 a while ago which did not have a definite answer. There's a second question from me <a href="https://stackoverflow.com/questions/75656846/is-there-...
<python><numpy><decimal><matrix-inverse>
2023-03-25 21:09:16
0
593
ShoutOutAndCalculate
75,844,488
6,850,351
Why pyperclip.copy function works only when there is breakpoint in code?
<p>If there is no break point - text not copied over to clipboard. If its present - it is. I am on fedora 37, debugging with vs code.</p> <p>File and repo: <a href="https://github.com/kha-white/manga-ocr/blob/master/manga_ocr/ocr.py" rel="nofollow noreferrer">https://github.com/kha-white/manga-ocr/blob/master/manga_ocr...
<python><pyperclip>
2023-03-25 20:58:57
1
362
Cute pumpkin
75,844,357
1,035,897
Error passing globals to Jinja2Templates constructor with FastAPI
<p>According to the <a href="https://github.com/encode/starlette/blob/62b5b6042a39289ed561580c251c233250c3c088/starlette/templating.py#L71ls" rel="nofollow noreferrer">starlette sources</a>, it seems the correct way to set up globals is simply to pass them to the constructor of <code>fastapi.templating.Jinja2Templates<...
<python><templates><jinja2><fastapi>
2023-03-25 20:31:34
1
9,788
Mr. Developerdude
75,844,119
7,800,760
Python: finding partial names of people
<p>I have a list of people extracted from a news article as a list of strings. Example follows:</p> <pre><code>persons = [ &quot;John Doe&quot;, &quot;John&quot;, &quot;Johnson&quot;, &quot;Murray Gell-Mann&quot;, &quot;Mann&quot;, &quot;Murray&quot;, &quot;M&quot;, ] def is_not_substring(...
<python>
2023-03-25 19:39:05
1
1,231
Robert Alexander
75,844,027
6,357,916
Adding date column to pandas dataframe with 200000 rows
<p>I run following code to add date column to dataframe <code>df1</code> of shape <code>(200000, 115)</code>starting from today:</p> <pre><code>df1 = pd.DataFrame(index=range(200000),columns=range(115)) # create dummy data frame start_date = datetime.date.today() end_date = start_date + datetime.timedelta(days=200000) ...
<python><pandas><dataframe>
2023-03-25 19:22:12
0
3,029
MsA
75,844,008
1,482,566
Connect to Sharepoint using Python
<p>Using the clientid, client_secret and Tenant ID I'm able to connect using Postman service. But I'm trying to write a Python script and connect to Sharepoint using the below code. But I'm getting an invalid request error.</p> <pre><code>from office365.runtime.auth.authentication_context import AuthenticationContext f...
<python><sharepoint><sharepoint-api>
2023-03-25 19:17:17
0
3,342
shockwave
75,843,631
1,233,751
bazel: Cycle in the workspace file detected. This indicates that a repository is used prior to being defined
<p>I have the following files and try to compile simple python app using bazel 6.1.1 and getting error.</p> <p>my files:</p> <pre class="lang-bash prettyprint-override"><code>➜ tree . ├── BUILD ├── main.py └── WORKSPACE </code></pre> <p><strong>the error</strong>:</p> <pre><code>➜ bazel bu...
<python><bazel><bazel-rules>
2023-03-25 18:06:36
1
10,514
DmitrySemenov
75,843,630
14,645,415
Set line character limit for emphasize-lines (code-block directive)
<p>When I currently do this</p> <pre><code>.. code-block:: python :emphasize-lines: 3,5 def some_function(): interesting = False # 116 characters line print('This line is highlighted. but we exceeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeed line limit') print('This one is not......
<python><documentation><python-sphinx>
2023-03-25 18:06:28
0
854
Ibrahim
75,843,431
1,087,836
How to install Python debug symbols and libraries via miniconda?
<p>I have created a new Python 3.8 environment using:</p> <pre><code>conda create -n myproj python=3.8 </code></pre> <p>But the installed Python version has no debug symbols and libraries for CPython included. I know how to install them with the normal installer but is there any way to install them via miniconda? Right...
<python><anaconda><cpython>
2023-03-25 17:32:30
0
363
Aragok
75,843,297
382,912
Specify max_bandwidth or TransferConfig for boto3 s3 upload_part
<p>The <code>upload_file</code> method allows you to specify <code>max_bandwidth</code> using the <code>boto3.s3.transfer.TransferConfig</code> object: <a href="https://boto3.amazonaws.com/v1/documentation/api/latest/guide/s3.html" rel="nofollow noreferrer">https://boto3.amazonaws.com/v1/documentation/api/latest/guide/...
<python><amazon-s3><boto3>
2023-03-25 17:10:44
1
6,151
kortina
75,843,045
15,233,108
compare if substring exists within an existing list of files but with a different trailing name
<p>I have 2 lists of filenames that I am comparing.</p> <p>The first list is the full list of files in the directory, and the 2nd list is the list of files I've extracted from the directory with a specific filename format. I want to use this 2nd list, to find files in the full list that are slightly different in naming...
<python><python-3.x><file><io>
2023-03-25 16:28:24
0
582
Megan Darcy
75,842,720
13,682,080
Python module shared between docker services
<p>I have a project structure like this:</p> <pre><code>stack-example/service1 ├── Dockerfile └── main.py stack-example/service2 ├── Dockerfile └── main.py stack-example/shared_module ├── __init__.py └── utils.py stack-example/docker-compose.yml </code></pre> <p>Both <em>service1</em> and <em>service2</em> use <em>shar...
<python><docker><microservices>
2023-03-25 15:31:28
1
542
eightlay
75,842,358
15,159,198
How to create a multiline tripple quote `ast` node string in python?
<p>Is there a way of creating an <code>ast</code> node of a tripple quote multiline python string (like in <code>docstrings</code>)? I am creating a python module to use the OpenAI API for auto-generating docstrings with GTP and inserting them directly into the python file. A simplified version of what I have is:</p> <...
<python><abstract-syntax-tree>
2023-03-25 14:30:28
0
483
Clerni
75,842,242
9,152,984
Using aler9/rtsp-simple-server, able to stream HLS from file but not from ffmpeg's stdin
<p><strong>UPD:</strong> hehe, it actially works, but in chrome, not mozilla</p> <p>I want to display programmatically generated stream on a webpage in real time. For this I have <a href="https://github.com/aler9/rtsp-simple-server" rel="nofollow noreferrer">rtsp-simple-server</a> with RTSP and HLS enabled. I managed t...
<python><ffmpeg><http-live-streaming><rtsp>
2023-03-25 14:08:51
1
775
Powercoder
75,842,202
4,772,565
How to save multiple figures from bokeh html file as separate png figures but download just as one zip file?
<p>This question is based on <a href="https://stackoverflow.com/questions/75768412/how-to-save-the-multiple-figures-in-a-bokeh-gridplot-into-separate-png-files">How to save the multiple figures in a bokeh gridplot into separate png files?</a>, where the accepted answer already provides working code to save the multiple...
<python><bokeh>
2023-03-25 13:59:58
1
539
aura
75,842,180
310,370
How can I convert this Gradio file upload code into folder path taking one?
<p>There is this gradio code that allows you to upload images. I prefer entering folder path as a text input.</p> <p>It works but instead of this one, I want to convert it into a directory path taking one</p> <pre><code> reference_imgs = gr.UploadButton(label=&quot;Upload Guide Frames&quot;, file_types = ['.png','.jpg...
<python><huggingface><gradio>
2023-03-25 13:56:37
0
23,982
Furkan Gözükara
75,842,155
15,637,435
How to use Selenium with chromedriver in apache-airflow in docker?
<h2>Problem</h2> <p>I have a scraper with selenium that I want to run with airflow inside docker. I'm able to create the container and run the related dag of the scraper in airflow. However, whenever the selenium driver gets initiated, I get an error. <code>('Service' object has no attribute 'process'; 90)</code>. Whic...
<python><docker><selenium-webdriver><web-scraping><airflow>
2023-03-25 13:52:35
1
396
Elodin
75,842,117
11,720,066
Pydantic - apply validator on all fields of specific type
<p>In my project, all <code>pydantic</code> models inherit from a custom &quot;base model&quot; called <code>GeneralModel</code>.</p> <p>This enables to configure the same behavior for the entire project in one place.</p> <p>Let's assume the following implementation:</p> <pre><code>from pydantic import BaseModel clas...
<python><validation><pydantic><code-duplication>
2023-03-25 13:46:19
2
613
localhost
75,841,971
1,469,465
ResourceWarning: unclosed socket after removing Docker container with Python SDK
<p>I have Docker Desktop installed on my MacBook and I am using Docker Python SDK (<a href="https://github.com/docker/docker-py" rel="nofollow noreferrer">https://github.com/docker/docker-py</a>) version 6.0.1 (but same issue appears in 5.0.3). For a test case, I create a local container and store this container in a v...
<python><docker>
2023-03-25 13:18:47
0
6,938
physicalattraction
75,841,918
1,972,356
Vectorizing multivariate normal distribution calculation
<p>I have n points in 3D space, each with a corresponding guess and certainty attached to it. I want to calculate the multivariate normal distribution for each point given its guess and certainty. Currently, I'm using an iterative approach and the <code>Scipy.stats</code> <code>multivariate_normal</code> function, as s...
<python><scipy><vectorization><distribution>
2023-03-25 13:09:41
1
1,373
NicolaiF
75,841,894
13,955,154
Progress bar in a for in os.listdir() with model.predict() inside the loop
<p>I have a simple for loop that works in this way:</p> <pre><code>for filename in tqdm(os.listdir('train')): path = os.path.join('train', filename) for i in range(9): features = model.predict(some_array) </code></pre> <p>Where model is a keras model used for feature extraction, so model.predict() is th...
<python><for-loop><progress-bar><tqdm>
2023-03-25 13:06:35
0
720
Lorenzo Cutrupi
75,841,722
3,257,191
Efficiently editing large input file based on simple lookup with python dataframes
<p>I have a very large txt file (currently 6Gb, 50m rows) with a structure like this...</p> <pre><code>**id amount batch transaction sequence** a2asd 12.6 123456 12394891237124 0 bs9dj 0.6 123456 12394891237124 1 etc... </code></pre> <p>I read the file like this...</p> <pre><code>inputFileDf = pd.read_csv(filename, hea...
<python><pandas><dataframe><bigdata>
2023-03-25 12:35:12
1
1,317
d3wannabe
75,841,624
1,116,675
Problem to process visually identical looking characters (umlauts)
<p>This may probably be a more general issue related to character encoding, but since I came across the issue while coding an outer join of two dataframes, I post it with a Python code example.</p> <p><strong>On the bottom line the question is: why is <code>ö</code> technically not the identical character as <code>ö</...
<python><character-encoding><utf>
2023-03-25 12:17:02
3
938
Madamadam
75,841,470
2,386,605
Scalars method in Postgresql does return only first of joines tables
<p>For sqlalchemy, I am running something like</p> <pre><code>res.scalars().all() </code></pre> <p>However, I just get a list of <code>Foo</code> items and not <code>(Foo, Bar)</code>.</p> <p>Do you know how to fix that?</p>
<python><sql><python-3.x><postgresql><sqlalchemy>
2023-03-25 11:43:53
0
879
tobias
75,841,428
16,175,571
Populate Django Model with for-loop
<p>I have a model <code>Task</code> which I want to populate with a for loop. In a list I have the tasks that should be passed into the model.</p> <p>My model has actually more than three tasks (Below I have shown only three). The list will also have varying number of entries. The list can also have only one task.</p> ...
<python><django><django-models>
2023-03-25 11:34:05
1
337
GCMeccariello
75,841,217
5,558,021
Folium Choropleth doesn't change colors on tiles
<pre><code>DF = pd.DataFrame({'REGION_ID':list(range(0,88)), 'share': list(map(lambda x: x* 5.3, list(range(0,88))))}) m = folium.Map(location=[63.391522, 96.328125], zoom_start=3) rel_ = folium.Choropleth( geo_data = './admin_level_4.geojson', name = Имя', data = DF, columns=['REGION_ID'...
<python><gis><geospatial><folium><choropleth>
2023-03-25 10:56:53
1
1,383
Dmitry Sokolov
75,841,155
673,600
Making a Pandas DataFrame allowable for an update by reference after a filter
<p>I'm filtering a df as follows with a function named <code>sell_shares</code>:</p> <pre><code>def sell_shares(df_company, number_shares, date_end): df_filtered = df_company.copy()[(df_company['Date'] &lt;= date_end)] df_filtered['Date'] = pd.to_datetime(df_filtered['Date'], dayfirst=True) emaining_shares ...
<python><pandas>
2023-03-25 10:44:06
0
6,026
disruptive
75,841,120
5,868,293
For every row keep only the non-nas and then concatenate while ignoring index, pandas
<p>I have the following pandas dataframe:</p> <pre><code>import numpy as np import pandas as pd df = pd.DataFrame({'col1': [1, np.nan, np.nan], 'results': ['Sub', 'Sub', 'Sub'], 'group': ['a', 'a', 'a'], 'seed': [6, 6, 6], 'col2': [np.nan, 2, ...
<python><pandas>
2023-03-25 10:39:27
1
4,512
quant
75,841,032
9,391,359
Can't connect to MySQL server on 'localhost:3306'
<p>I have simple docker file for micro app</p> <pre><code>FROM python:3.8.16-slim RUN apt-get update &amp;&amp; DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends make build-essential libssl-dev \ zlib1g-dev libbz2-dev libreadline-dev libsqlite3-dev wget curl llvm libncurses5-dev xz-utils ...
<python><mysql><docker>
2023-03-25 10:25:13
1
941
Alex Nikitin
75,840,827
7,251,207
How to properly generate a documentation with Swagger for Flask
<p>I would like to ask how to generate a proper documentation with Swagger for Flask. I have tried many libraries like flasgger, apispec, marshmallow, flask_apispec, etc but I didn't find the best one.</p> <p>So I have a function here:</p> <pre class="lang-py prettyprint-override"><code>@app.route('/test', methods=['PO...
<python><flask><swagger><openapi>
2023-03-25 09:43:55
1
305
juliussin
75,840,780
288,201
Convert singular values into lists when parsing Pydantic fields
<p>I have an application that needs to parse some configuration. These structures often contain fields that can be either a string, or an array of strings, e.g. in YAML:</p> <pre class="lang-yaml prettyprint-override"><code>fruit: apple vegetable: - tomato - cucumber </code></pre> <p>However, internally I'd like to...
<python><pydantic>
2023-03-25 09:31:38
1
8,287
Koterpillar
75,840,710
14,729,820
How to rename images with specific pattern?
<p>I have this image folder as shown below that has repated charchter name <code>A</code> I want only keep one letter <code>A</code> with rest of <code>numbers + ext</code> the input :</p> <pre><code>input_folder --| |--- imgs -- |-- A_0.jpg |-- A_A_A_1.jpg ...
<python><regex><operating-system><glob>
2023-03-25 09:17:03
1
366
Mohammed
75,840,467
12,189,799
flask send base 64 encoded pdf string without saving
<p>I have a flask application. I am using selenium cdp commands to generate pdfs. I get a base64 encoded string from selenium. Before sending the response as a pdf I save the file in my filesystem.</p> <pre><code>file.write(base64.b64decode(pdf_string['data']) </code></pre> <p>And the response is just <code>send_file('...
<python><flask><selenium-webdriver><pdf><http-headers>
2023-03-25 08:25:18
1
371
Alan Dsilva
75,840,283
4,442,753
Select line in current python script and run them in python interpreter?
<p>I am new to SpaceVim and would like to use it to develop in python. I am actually new to non GUI IDE, which is why I am starting with SpaceVim instead of vanilla NeoVim.</p> <p>This said, I would like to run part of a script (only part of it) into a terminal to check if the code is working as intended. Should I open...
<python><spacevim>
2023-03-25 07:44:06
0
1,003
pierre_j
75,840,240
9,403,794
Why this code take more than 5 second if execute first time and when repeat takes less then 0.2s
<p>I begin from a question:</p> <p>Why first time execution is taking longer time then usual. Should I be worried about malware or similar?</p> <p>I have code snippets below. I have pickled numpy ndarray in file. I tried to read all and generate total ndarray.</p> <p>I registered a strange behavior.</p> <p>Execution ti...
<python><python-3.x>
2023-03-25 07:32:44
1
309
luki
75,839,980
6,225,526
How to split the groups and apply a function in Pandas based on condition
<p>Lets say I have a dataframe defined as below</p> <pre><code>df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar', 'foo', 'bar','foo', 'bar'], 'B' : [1, 2, 3, 4, 5, 6, 7, 8], 'C' : ['mean', 'halfmean', 'mean', 'halfmean', 'mean', 'halfmean', 'mean', 'halfmean']}) </code></pre> <p...
<python><pandas>
2023-03-25 06:23:18
4
1,161
Selva
75,839,927
16,728,255
How does `mypy` know the signature of the pydantic model?
<p>How does <code>mypy</code> know the signature of the <code>pydantic</code> model in this manner?</p> <pre class="lang-py prettyprint-override"><code>from pydantic import BaseModel class Model(BaseModel): a: int Model(a='asd') # error: Argument &quot;a&quot; to &quot;Model&quot; has incompatible type &quot;str...
<python><python-typing><mypy><pydantic>
2023-03-25 06:08:35
1
372
Karen Petrosyan
75,839,831
10,313,194
Django cannot add null data from url to database
<p>I create model like this which it should recieve null value without error</p> <pre><code>class ReceiveData(models.Model): api_key=models.ForeignKey(DeviceKey,on_delete=models.CASCADE) field1= models.FloatField(null=True) field2= models.FloatField(null=True) field3= models.FloatField(null=True) </code...
<python><django><django-views>
2023-03-25 05:41:55
1
639
user58519
75,839,825
8,391,698
How to prevent transformer generate function to produce certain words?
<p>I have the following <a href="https://huggingface.co/docs/transformers/model_doc/t5#inference" rel="nofollow noreferrer">code</a>:</p> <pre><code>from transformers import T5Tokenizer, T5ForConditionalGeneration tokenizer = T5Tokenizer.from_pretrained(&quot;t5-small&quot;) model = T5ForConditionalGeneration.from_pre...
<python><nlp><huggingface-transformers><generative-pretrained-transformer>
2023-03-25 05:39:59
1
5,189
littleworth
75,839,562
1,056,563
"ModuleNotFoundError: No module named 'azure'" even though azure-cli-core was installed
<p>The various <code>azure-cli</code>* modules were installed via <code>pip3.10</code>:</p> <pre><code>python3.10 -m pip list 2023-03-24T23:57:52.8637926Z azure-cli 2.46.0 2023-03-24T23:57:52.8638330Z azure-cli-core 2.46.0 2023-03-24T23:57:52.8638523Z azure-cli-te...
<python><pip><azure-cli>
2023-03-25 03:51:30
0
63,891
WestCoastProjects
75,839,431
17,101,330
How to scale two timeseries to match cumulative pct change but keep initial values of one of them
<p>I have two timeseries like this:</p> <pre><code>import pandas as pd df = pd.DataFrame({ 'A': [1, 3, 2, 5, 2, 8, 3], 'B': [10, 33, 22, 39, 30, 66, 34], }) df.A.plot(color=&quot;blue&quot;) df.B.plot(color=&quot;orange&quot;) </code></pre> <p><a href="https://i.sstatic.net/VzCOY.jpg" rel="nofollow noreferrer...
<python><pandas><numpy><time-series><scale>
2023-03-25 02:55:51
1
530
jamesB
75,839,379
7,267,480
SCIPY minimization using L-BFGS_B, error "TOTAL NO. of f AND g EVALUATIONS EXCEEDS LIMIT"
<p>Trying to optimize one function using scipy minimize using <a href="https://docs.scipy.org/doc/scipy/reference/optimize.minimize-lbfgsb.html" rel="nofollow noreferrer">L-BFGS-B method</a></p> <p>I have a simple code snippet to catch some errors and messages from minimize function:</p> <pre><code>result = minimize(fu...
<python><scipy><scipy-optimize-minimize>
2023-03-25 02:35:13
1
496
twistfire
75,839,281
6,727,914
What is the difference between grid[index] VS grid[index, :] in python
<p>In this <a href="https://colab.research.google.com/drive/1gS2aJo711XJodqqPIVIbzgX1ktZzS8d8?usp=sharing" rel="nofollow noreferrer">https://colab.research.google.com/drive/1gS2aJo711XJodqqPIVIbzgX1ktZzS8d8?usp=sharing</a> , they used <code>np.max(qtable[new_state, :])</code></p> <p>But I did an experiment and I don't ...
<python><arrays><list><numpy><q-learning>
2023-03-25 01:56:46
1
21,427
TSR
75,839,133
8,475,638
MPI block other ranks to execute until rank 0's task is finished
<p>I am new in MPI, Here is the code structure I am implementing right now:</p> <pre><code>import time def A(): //some simple codes here to execute. Lets say print('Hello World from A') time.sleep(5) def B(): //some simple codes here to execute.Lets say print('Hello World from B') time.sleep(5) ...
<python><c++><c><parallel-processing><mpi>
2023-03-25 01:05:23
0
2,336
Ankur Lahiry
75,839,069
630,544
How to DRY up this psycopg connection pool boilerplate code with a reusable async function or generator?
<p>I'm using <code>psycopg</code> to connect to a PostgreSQL database using a connection pool. It works great, but any function that needs to run SQL in a transaction gets three extra layers of nesting:</p> <p><code>/app/db.py</code></p> <pre class="lang-py prettyprint-override"><code>from os import getenv from psycopg...
<python><python-asyncio><generator><contextmanager><psycopg3>
2023-03-25 00:47:29
1
4,007
Shaun Scovil
75,839,037
6,296,626
How to capture/sniff network traffic of certain process (executable) in Python?
<p>I am trying to listen and capture network traffic (packets) of certain process (.exe executable on Windows) using Python.</p> <p>So far using <code>scapy</code> I am able to sniff the network...</p> <p>Here for example I am sniffing all UDP packet in between port 10 to 20 and print out the remote IP address and port...
<python><network-programming><scapy><packet><packet-sniffers>
2023-03-25 00:36:45
1
1,479
Programer Beginner
75,839,017
1,806,124
How to run Python module with PM2 ecosystem file?
<p>I can run a Python script with PM2 with the following ecosystem file:</p> <pre class="lang-json prettyprint-override"><code>{ &quot;apps&quot;: [{ &quot;name&quot;: &quot;my_app&quot;, &quot;script&quot;: &quot;script.py&quot;, &quot;instances&quot;: &quot;1&quot;, &quot;wait_read...
<python><python-3.x><pm2>
2023-03-25 00:30:57
1
661
Endogen
75,838,706
10,791,262
CentOS Apache(httpd) deploying of flask occurs 503 error
<p>I faced 503 error while deploying my flask app on godaddy centos vm, port is 5002 for flask app.</p> <p>And httpd config in etc/httpd/conf.d/default-site.conf is following.</p> <pre><code>&lt;VirtualHost *:80&gt; servername domain.com serveralias domain.com serveralias domain.com ProxyPreserveHost O...
<python><flask><devops>
2023-03-24 22:58:43
0
311
Alex
75,838,661
14,509,475
Overload unary operator as binary operator
<p>In Python, is it possible to override a unary operator (such as <code>~</code>) so that it acts as a binary one?</p> <p>The result would be that <code>a ~ b</code> would become a meaningful expression.</p>
<python><python-3.x><operator-overloading>
2023-03-24 22:50:40
0
496
trivicious
75,838,658
15,392,319
Certain Characters in Foreign Languages Cause Lambda Post Invocation Errors
<p>When I query data from certain countries, namely Belarus, Bangladesh and Kazakhstan, I get this error:</p> <pre><code>[ERROR] [1679697735190] LAMBDA_RUNTIME Failed to post handler success response. Http response code: 413. Traceback (most recent call last): File &quot;/var/runtime/bootstrap.py&quot;, line 480, in &...
<python><amazon-web-services><aws-lambda><invocation>
2023-03-24 22:50:17
0
428
cmcnphp
75,838,609
17,639,970
Is it possible to add json info to a OSM file in julia?
<p>I'm trying to extract set of public transit nodes from open street map. After reading wikis and documentation, it seems Overpass-turbo gives nodes and edges related to public trasit. So, I did this query on <a href="https://overpass-turbo.eu/" rel="nofollow noreferrer">NYC</a> and once trying to export it give an op...
<python><julia><openstreetmap>
2023-03-24 22:41:35
0
301
Rainbow
75,838,573
843,036
How to upload recorded audio blob to server without method='post' in Javascript
<p>I am trying to create a voice recorder in flask that takes the voice recording and then further processes the audio file.</p> <p>For the voice recorder I am using the recorder code in this github repo: <a href="https://github.com/addpipe/simple-recorderjs-demo" rel="nofollow noreferrer">https://github.com/addpipe/si...
<javascript><python><flask>
2023-03-24 22:34:56
1
2,699
StuckInPhDNoMore
75,838,499
355,931
Pandas read_csv: Data is not being read from text file (open() reads hex chars)
<p>I'm trying to read a text file with <code>pandas.read_csv</code>, but data is not being loaded (only a dataframe with <code>NA</code> values. The text file contains valid data (I can open it with excel). When I try to read it with <code>pathlib.Path.open()</code> it shows lines with Hex codes.</p> <p>Let me show you...
<python><pandas><character-encoding><text-files>
2023-03-24 22:19:04
1
21,147
Barranka
75,838,473
12,309,386
python ray pid unavailable in RayTaskError
<p>I am running a function as number of ray tasks, collecting the object ids in a list called <code>futures</code>.</p> <p>I then have a try/except block within which I attempt to get the results. My function throws a <code>RuntimeError</code>. My understanding is that ray wraps this within a <code>RayTaskError</code...
<python><ray>
2023-03-24 22:14:41
0
927
teejay
75,838,452
10,997,438
Python parallel execution slower than serial, even with batches
<p>I have a txt file with several hundreds of thousands of strings, each on a new line.<br /> I need to create a list with an element for each string. Each of these elements must be a list that contains ordered substrings of the original string. The length of the substrings is a k given.<br /> For example with the foll...
<python><performance><parallel-processing><multiprocessing><python-multiprocessing>
2023-03-24 22:09:00
1
389
CrystalSpider
75,838,347
8,318,946
Issue with complex signal in Django
<p>Below are my Django models. I'd like to write signal that will do the following:</p> <ol> <li>User updates project that contains let's say 3 Spider objects.</li> <li>Each Spider object contains config_file so signal should get list of all Spider objects and update group from all config files from the list.</li> <li>...
<python><django>
2023-03-24 21:48:40
1
917
Adrian
75,838,234
20,589,631
how do i show a widget from a diffrent widget?
<p>i have two widgets, one of them is a main widget (even though it uses Qwidgets.Qwidget), and the other one is a side widget that is supposed to appear from the main widget. i tried to use a button, and that onclick, the side widget would show. but instead the app crashes after a sec.</p> <p>here's the code for the m...
<python><pyqt5><qwidget>
2023-03-24 21:26:32
1
391
ori raisfeld
75,838,200
11,141,816
What's the simple way to get the return value of a function passed to multiprocessing.Process without using too many functions?
<p>In this post <a href="https://stackoverflow.com/questions/10415028/how-to-get-the-return-value-of-a-function-passed-to-multiprocessing-process?answertab=scoredesc#tab-top">How to get the return value of a function passed to multiprocessing.Process?</a> there were manny solutions to get a value from the multiprocessi...
<python><python-multiprocessing>
2023-03-24 21:20:54
1
593
ShoutOutAndCalculate
75,838,144
7,175,213
Create a graph in Python (with pygraphviz) when the number of nodes is huge
<p>I am trying, in Python, to create a graph from lists where I can see the merge and ramifications of my lists. I am sure the first item of the list is always the same for all lists.</p> <p>For these three example lists:</p> <pre><code>list1 = [&quot;w&quot;, &quot;a&quot;, &quot;b&quot;, &quot;c&quot;, &quot;d&quot;]...
<python><graph><pygraphviz>
2023-03-24 21:10:02
1
1,148
Catarina Nogueira
75,838,141
5,094,261
Stream large XML file directly from GridFS to xmltodict parsing
<p>I am using <a href="https://motor.readthedocs.io/en/stable/index.html" rel="nofollow noreferrer">Motor</a> for async MongoDB operations. I have a <a href="https://motor.readthedocs.io/en/stable/api-asyncio/asyncio_gridfs.html?highlight=gridfs" rel="nofollow noreferrer">gridfs</a> storage where I store large XML file...
<python><mongodb><python-asyncio><gridfs><xmltodict>
2023-03-24 21:09:26
1
1,273
Shiladitya Bose
75,838,115
2,085,454
How to re-trigger Airflow pipeline within a DAG
<p>Our company's internal airflow2 platform has some issue, it can show &quot;success&quot; even if we didn't get any output from the pipeline, sometimes. To avoid this happen, we hope to have automated code to check whether there's output after Airflow pipeline finished, if not, then re-run the pipeline automatically....
<python><automation><airflow><airflow-2.x>
2023-03-24 21:06:27
1
4,104
Cherry Wu
75,837,897
9,291,575
Dask worker has different imports than main thread
<p>I have a dask delayed function that uses some options defined in another submodule. There's also a third module that modifies these options when imported.</p> <p>If the imports happen after <code>__name__ == '__main__'</code> (in a notebook, for example), running the function in a distributed client ignores the mod...
<python><dask><dask-distributed>
2023-03-24 20:28:45
1
708
Aule Mahal
75,837,806
6,865,112
How to change the name of the column that is based on a Model in FastAPI?
<p>In FastAPI the database is generated automatically and it was created based on the models I had in the moment. After the database creation I changed a model's property name from &quot;owner_id&quot; to &quot;user_id&quot; but after re-runing the API it does not upgraded the Database.</p> <p>How can I trigger the dat...
<python><sqlalchemy><fastapi><alembic>
2023-03-24 20:14:48
1
749
Almeida Cavalcante
75,837,715
13,321,451
How to format labels in scientific notation for bar_label
<p>I am plotting data in a seaborn barplot. I want to label something from my pandas dataframe into the bar. I have gotten the labeling part figured out (see code to replicate below), but I still want to convert it to scientific notation.</p> <pre><code>import pandas as pd d = {'name': ['experiment1','experiment2'], 'r...
<python><pandas><matplotlib><seaborn><bar-chart>
2023-03-24 19:59:39
2
342
Oll
75,837,694
11,925,464
multiprocess loop (python)
<p>i have a dataframe which i'm trying to use multiprocess to use the available cores more efficiently for loops. There is an example <a href="https://stackoverflow.com/questions/74185743/multiprocessing-a-loop">here</a>, however, i can't work out how 'pool' is applied.</p> <p>sample df code:</p> <pre><code>df = pd.Dat...
<python><pandas><multiprocessing>
2023-03-24 19:56:45
0
597
ManOnTheMoon
75,837,570
6,656,081
Why is the regex quantifier {n,} more greedy than + (in Python)?
<p>I tried to use regexes for finding max-length sequences formed from repeated doubled letters, like <code>AABB</code> in the string <code>xAAABBBBy</code>.</p> <p>As described in the <a href="https://docs.python.org/3/library/re.html" rel="nofollow noreferrer">official documentation</a>:</p> <blockquote> <p>The <code...
<python><regex><regex-greedy>
2023-03-24 19:39:36
1
2,602
Anton Ganichev
75,837,501
5,032,387
How to change values in matrix to corresponding row value in vector based on condition
<p>I'm interested in whether it's possible do the following with pure numpy. Let's say I have a matrix a and a vector b. I want to fill whatever values meet the condition to the left of the equal sign with the value from the vector b correponding to the row in matrix a.</p> <pre><code>import numpy as np a = np.arange(...
<python><numpy>
2023-03-24 19:30:15
2
3,080
matsuo_basho
75,837,422
4,391,249
Is there a Python container that acts like a dictionary but doesn't need both key and value?
<p>Say I have:</p> <pre class="lang-py prettyprint-override"><code>@dataclass class Foo: foo_id: int # Other interesting fields. def __hash__(self): return self.foo_id.__hash__() </code></pre> <p>And I make a <code>foos_set = {Foo(i) for i in range(10)}</code>. I had always assumed that <code>set.remove</cod...
<python>
2023-03-24 19:16:03
1
3,347
Alexander Soare
75,837,305
11,050,535
Extract Embedded CSV/Excel File from PDF
<p>I have been trying to Extract embedded CSV/Excel from PDF Files, I need to extract the Embedded Files from PDF and store to separate Folder, I am not getting the way to perform this activity, I tried using PyPDF2, PDFSharp, but no Success.</p> <p>Here the below code i have been trying to use, Any Suggestion</p> <pre...
<python><pypdf>
2023-03-24 18:58:59
1
605
Manz
75,837,242
8,713,442
Adding data from dictionary to RDD row
<p>I have data frame and dictionary as shown below :</p> <p>I am converting this to RDD and then to each row I need to copy the data from dictionary result to each Row .</p> <p>THis is just an example , I am having more than 15 keys in dictionary( which is coming as a result of some logic) which needs to get copied...
<python><apache-spark><pyspark><rdd>
2023-03-24 18:49:59
1
464
pbh
75,837,155
3,402,296
Parent class attribute does not persist in scope
<p>I have an abstract class</p> <pre class="lang-py prettyprint-override"><code>from abc import ABC class StandardClass(ABC): _my_table = None @classmethod def __init__(cls): if cls._my_table is not None: return cls._my_table = pd.read_sql(_my_table_query(), cls._connection) ...
<python><oop><inheritance>
2023-03-24 18:40:30
0
576
RDGuida
75,837,023
688,191
SQL code that runs on Azure via GUI fails silently via pyodbc
<p><strong>Background</strong>: I am building a complex data analysis tool, and part of the process is to run some pretty deep and complex SQL from python. I am using <code>pyodbc</code> to connect to a SQL server instance hosted on Azure. This code has a loop containing a lot of calculation and row creation.</p> <p>Wh...
<python><sql-server><azure>
2023-03-24 18:21:25
1
351
bengreene
75,836,912
1,139,286
Scipy installation error when installing openai['embeddings'] dependencies with pip
<p>When attempting to install openai['embeddings'] with pip, I receive an error when pip attempts to install the scipy dependency. I am trying to avoid using Conda, as I am much more familiar with pip. Please could you tell me how to fix this error?</p> <p>I am running</p> <ul> <li>pyenv 2.3.14</li> <li>Python 3.10.6</...
<python><pip><scipy><openai-api>
2023-03-24 18:05:28
1
691
Thomas Hopkins
75,836,828
7,975,785
Run tests of another module with pytest
<p>I wrote two modules, packageA and packageB. Both have their own battery of tests, but packageB depends on packageA, so I would like to run packageA's tests when I run packageB's.</p> <p>I can use <code>pytest.main(['--pyargs' ,'package_A.tests.tests_A'])</code> in packageB, and it seems to work. However, if there ar...
<python><unit-testing><pytest>
2023-03-24 17:54:15
1
1,576
Zep
75,836,799
12,596,824
Duplicating index of pandas dataframe and adjusting age column randomly from 0.5-1 years
<p>I have the following code where I am duplicating each row in the original dataframe anywhere from 1-3 times. I want to update the age though with each duplication to be some random age between 0.5-1 years away but always increasing from the last age with the same id. How can I do this?</p> <pre><code>import numpy as...
<python><pandas>
2023-03-24 17:51:07
4
1,937
Eisen
75,836,730
234,593
Paramiko fails connecting /w "Private key file is encrypted" when upgrading to 2.9.0+
<p>The following works fine using paramiko 2.8.1, but fails with any 2.9.0+:</p> <pre class="lang-py prettyprint-override"><code> pkey = paramiko.RSAKey.from_private_key(pkey_str) ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.WarningPolicy()) ssh.connect(host, port=int(port), usern...
<python><paramiko><ssh-keys>
2023-03-24 17:40:44
1
17,007
Kache
75,836,583
1,656,343
python asyncio parallel processing with a dynamic tasks queue
<p>I'm new to <code>asyncio</code>. Most <code>asyncio</code> code examples show parallel processing with a fixed number of tasks:</p> <pre class="lang-py prettyprint-override"><code>tasks = [asyncio.ensure_future(download_one(url)) for url in urls] await asyncio.gather(*tasks) </code></pre> <p>I need to download a lar...
<python><asynchronous><python-asyncio><threadpool><aiohttp>
2023-03-24 17:20:39
2
10,192
masroore
75,836,118
5,881,882
PyTorch: Interpolate - Input and output must have the same number of spatial dimensions, but got input with spatial dimensions
<p>I am following a U-Net tutorial and I am currently stuck with some interpolation. My x comes as <code>[256, 16384]</code>. Which is a batch of 256 with 1 channel and the 128x128 is flatten to 16384. Thus, I reshape x to <code>[256, 1, 128, 128].</code> Then I go for some transformations and my out prior to a reshape...
<python><pytorch>
2023-03-24 16:28:15
0
388
Alex
75,835,942
3,261,292
Python BeautifulSoup issue in extracting direct text in a given html tag
<p>I am trying to extract direct text in a given HTML tag. Simply, for <code>&lt;p&gt; Hello! &lt;/p&gt;</code>, the direct text is <code>Hello!</code>. The code works well except with the case below.</p> <pre><code>from bs4 import BeautifulSoup soup = BeautifulSoup('&lt;div&gt; &lt;i&gt; &lt;/i&gt; FF Services &lt;/di...
<python><html><beautifulsoup><text-extraction>
2023-03-24 16:09:32
2
5,527
Minions