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
⌀
77,251,814
21,025,283
When running tests in Flask RuntimeError: Either 'SQLALCHEMY_DATABASE_URI' or 'SQLALCHEMY_BINDS' must be set
<p>I used SQLAlchemy for database management in Flask application, once running integration tests using pytest this error arises: <code>RuntimeError: Either 'SQLALCHEMY_DATABASE_URI' or 'SQLALCHEMY_BINDS' must be set</code>.</p> <p>I set the variable <code>SQLALCHEMY_DATABASE_URI=&quot;mysql+mysqlconnector://root:root@...
<python><flask><pytest>
2023-10-07 23:29:07
1
333
abdou_dev
77,251,711
15,781,591
How to stack multiple columns into one and fill in with column headers
<p>I have the following dataframe:</p> <pre><code> Date Blue Red Green ----------------------------------------- 1 1/1/14 55 34 34 2 1/2/14 36 35 23 3 1/3/14 23 46 43 4 1/4/14 47 34 55 </code></pre> <p>I want to &qu...
<python><pandas><stack>
2023-10-07 22:30:22
1
641
LostinSpatialAnalysis
77,251,464
8,030,794
How to merge rows with nearest values in Dataframe
<p>I have a <code>DataFrame</code> like this:</p> <pre><code>index B 0 1 1 2 2 5 3 6 4 7 5 10 </code></pre> <p>And i need to merge rows where the difference is less than or equal 2, select the line with the smaller value and set count merges</p> <p>The result should be like this :</p> <pre><code...
<python><pandas>
2023-10-07 20:45:30
2
465
Fresto
77,251,444
5,339,430
How to set field `pint.Quantity._magnitude` of existing object?
<p>Using the <a href="https://pint.readthedocs.io/en/stable/" rel="nofollow noreferrer">pint library</a>, I profiled my code and found a bottleneck is creating new <code>Quantity</code> objects using the constructor like this:</p> <pre class="lang-py prettyprint-override"><code>import pint ureg = pint.UnitRegistry() .....
<python><pint>
2023-10-07 20:39:57
0
355
Dave Doty
77,251,378
11,653,374
Observing the value and percentage change on a line graph like what Google does
<p>If you search <a href="https://en.wikipedia.org/wiki/Apple_Inc." rel="nofollow noreferrer">Apple</a> stock on Google you will be taken to <a href="https://www.google.com/search?q=apple%20stock&amp;rlz=1C1RXQR_enUS1073US1073&amp;oq=apple%20sto&amp;gs_lcrp=EgZjaHJvbWUqDAgBECMYJxidAhiKBTIGCAAQRRg5MgwIARAjGCcYnQIYigUyCQ...
<python><visualization><graph-visualization>
2023-10-07 20:17:41
1
728
Saeed
77,251,171
2,386,113
How do I pass a function pointer to cuPy Raw kernel in Python?
<p>I am using <strong>cuPy</strong> to call raw CUDA kernels in Python scripts. I am able to load the simple standalone CUDA kernels in my Python script but I don't know the syntax to use if my CUDA kernel requires a function pointer as an argument. How do I pass a function pointer to a device function?</p> <p><strong>...
<python><cuda><cupy>
2023-10-07 19:11:35
1
5,777
skm
77,250,681
8,708,364
Can't upload video over 5GB on App Engine
<p>I recently decided to move my software hosting to Google App Engine (since we believe it's serverless), but, I am coming across a problem where I cannot upload large video files. This is a big problem, since the point of the software is handling video files.</p> <p>HTML:</p> <pre class="lang-html prettyprint-overrid...
<python><flask><google-cloud-platform><google-app-engine><file-upload>
2023-10-07 16:40:10
0
71,788
U13-Forward
77,250,667
10,118,061
Web scraping through Selenium only loads the skeleton of the page and does not populate the data
<p>I am developing a python/selenium script to scrape publicly available data on a website.</p> <p>Within the website, there is &quot;Search&quot; button, when clicked should bring out 100s of search results.</p> <p>However, upon initiating a click through selenium, only the skeleton of the search results are loaded, a...
<python><selenium-webdriver><web-scraping><selenium-chromedriver>
2023-10-07 16:35:49
0
843
Kshitij Dhyani
77,250,637
8,230,132
cookiecutter conditional prompt and capture output to variable
<p>I am very much new in cookiecutter programming and trying to create an interactive program similar to below example to generate config! The requirement is to prompt for sub options conditionally if getting <code>yes</code> on one prompt and capture value into variable for later use. My desired menu is as below</p> <...
<python><python-3.x><cookiecutter>
2023-10-07 16:29:42
0
703
Rio
77,250,622
10,291,435
pyspark dataframe takes too long to filter/transform into pandas df/ filter
<p>I am havin a pyspark dataframe which has around 120k records, I am trying to do some operations on it. some operations work so fine. but when I try to write it into csv, or transform it into pandas, or try to filter like this:</p> <pre><code>state_not_equal= df_h_with_distance_order_osm_P.filter(df_h_with_distance_o...
<python><pyspark>
2023-10-07 16:26:00
0
1,699
Mee
77,250,557
4,399,016
Applying function to Pandas Data frame and getting result as a new data frame
<p>I have this code:</p> <pre><code>import yfinance as yF import datetime import pandas as pd df = pd.DataFrame({'ID':['1', '2'], 'Ticker': ['AIN', 'TILE'], 'Company':['Albany International', 'Interface']}) def get_returns(tic,com): df_Stock = yF.download(tickers = tic, period = &quot;max&quot;, interval = &quot...
<python><pandas><dataframe><apply>
2023-10-07 16:07:52
1
680
prashanth manohar
77,250,285
4,805,412
How to add Meta (Facebook) Pixel to web pages generated by Sphinx?
<p>I have obtained the <strong>Meta Pixel</strong> from Meta and I have a website made in Python documentation tool called <strong>Sphinx</strong>.</p> <p>Now I need to add the generated code of Meta Pixel in the head section of my pages, right above .</p> <p>The result should be like this:</p> <pre class="lang-html pr...
<python><html><python-sphinx>
2023-10-07 14:54:01
1
4,842
Pavel Hanpari
77,249,985
5,800,969
google.auth.exceptions.RefreshError: ('invalid_grant: Bad Request', {'error': 'invalid_grant', 'error_description': 'Bad Request'})
<p>I have generated developer_token, access_token and refresh token with googleads read permission. While using in code using google-ads-api I am getting below error.</p> <p>Code:</p> <pre><code>from google.ads.googleads.client import GoogleAdsClient googleads_client = GoogleAdsClient.load_from_storage(path=&quot;./goo...
<python><oauth-2.0><google-oauth><google-ads-api><google-ads-script>
2023-10-07 13:34:22
0
2,071
iamabhaykmr
77,249,730
206,253
Quickest way to swap 0 and 1 in a list (not numpy)
<p>What is the quickest non-numpy way of swapping 1 and 0 in a Python list?</p>
<python><list>
2023-10-07 12:17:14
2
3,144
Nick
77,249,570
5,790,653
TypeError: list indices must be integers or slices, not str over a big and merged json file
<p>This is <code>combined.json</code>:</p> <pre><code>[ { &quot;count&quot;: 1, &quot;next&quot;: null, &quot;previous&quot;: null, &quot;results&quot;: [ { &quot;id&quot;: 5883, &quot;url&quot;: &quot;https://some.api.com/api/ipam/ip-addre...
<python>
2023-10-07 11:31:48
1
4,175
Saeed
77,249,499
1,795,245
Developing and debugging AWS Lambda Function: conda -> docker image using Visual Studio Code
<p>I'm working on a project that involves developing an AWS Lambda function in Python. At the end I want to use a Docker image containing my custom code. I want to use the following steps:</p> <ol> <li>Develop and debug the code locally using a conda virtual environment - No problem</li> <li>Debug the code within the D...
<python><amazon-web-services><docker><visual-studio-code>
2023-10-07 11:06:12
1
649
Jonas
77,249,422
7,149,485
Changing django model structure produces 1054 unkown column error
<p>I am trying to change the <code>model</code> structure (column names) of an existing <code>Django</code> app that was already working and had a database.</p> <p><strong>Original Files:</strong></p> <p>The original <code>model.py</code> file was:</p> <pre><code>from django.db import models from django.core.validators...
<python><django>
2023-10-07 10:41:48
1
1,169
brb
77,249,420
11,813,880
UnicodeDecodeError when Transcribing Live Audio using Sphinx in Python
<p>I am trying to transcribe a live playing audio, but I am getting the following error when decoding,</p> <blockquote> <p>UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte</p> </blockquote> <pre><code>import pyaudio import requests from pocketsphinx import LiveSpeech def spee...
<python><cmusphinx><sphinx4>
2023-10-07 10:41:27
0
365
Abraham Arnold
77,249,378
5,790,653
how to access objects in python with for loop in different files
<p>This is my <code>file1.json</code>:</p> <pre><code>{ &quot;count&quot;: 1, &quot;next&quot;: null, &quot;previous&quot;: null, &quot;results&quot;: [ { &quot;id&quot;: 5883, &quot;url&quot;: &quot;https://some.api.com/api/ipam/ip-addresses/5883/&quot;, &quo...
<python>
2023-10-07 10:28:09
2
4,175
Saeed
77,249,164
12,942,578
How to reduce runtime of parallellizable code in python?
<p>I have a program with some parts parallelizable. I want to run it in parallel (not concurrent) to reduce runtime.</p> <p>I tried Multi-threading <code>threading.Thread</code> &amp; multi-processing <code>processing.Process</code>. But the runtime of the code is not improving. I'm fact, it's getting a little worse (s...
<python><parallel-processing>
2023-10-07 09:19:58
0
367
PhiloRobotist
77,248,988
273,344
How importing from a script works differently than importing from a module?
<p>I have a structure of files and folders like this:</p> <pre><code>package1/ p1.py package2/ p2.py </code></pre> <p>Contents of <code>package1/p1.py</code>:</p> <pre><code>def p1fun(): print(&quot;p1fun&quot;) </code></pre> <p>Contents of <code>package1/package2/p2.py</code>:</p> <pre><code>import package...
<python><python-import>
2023-10-07 08:23:46
1
4,309
Marcin
77,248,947
2,688,158
Am I missing any pre-processing step to data when doing outlier detection using Isolation-Forest for time series human sensor data?
<p>I am working on human sensor data and want to remove outliers if any from the dataset. The data is collected 50times per second. My question is do I need to some pre-processing before using the Isolation-Forest model as I don't any error as such but want to use it in the right way. I have never worked with time seri...
<python><machine-learning><time-series><outliers><isolation-forest>
2023-10-07 08:10:06
0
417
user2688158
77,248,839
8,245,814
Using a literal number with 35660 digits raises SyntaxError
<p>I'm copying and pasting 10000! from the web, and this number has 35660 digits, but I'm getting the following error:</p> <blockquote> <p>SyntaxError: Exceeds the limit (4300) for integer string conversion: value has 35660 digits; use sys.set_int_max_str_digits() to increase the limit - Consider hexadecimal for huge i...
<python><python-3.x><integer>
2023-10-07 07:36:00
5
319
Pinteco
77,248,580
6,323,080
Why/when would you use field() for a non-callable default?
<p>I'm trying to understand when it is correct to use field(default=x).</p> <p>I understand in a case where the default is callable, it is wrong not to. For instance:</p> <pre><code>@dataclass class SomeClass: obj_content: list = field(default=[]) </code></pre> <p>instead of</p> <pre><code>@dataclass class SomeClass...
<python><python-3.x><python-dataclasses>
2023-10-07 06:08:19
1
694
Zeke Arneodo
77,248,315
89,691
Automating a Delphi 2007 application with a Python script - how do I unambiguously reference controls?
<p>I have a legacy Delphi application that I need to automate for testing purposes. I'm having difficulty with directing the automation requests to the correct component. The included example demonstrates the issue (on my environment anyway). Heres a simple Delphi application I'm wanting to control:</p> <p><strong>P...
<python><delphi><ui-automation><pywinauto><delphi-2007>
2023-10-07 03:58:52
1
5,700
rossmcm
77,248,283
4,212,875
Using with open, why does 'rb' for reading json work but 'wb' for writing to a json does not?
<p>I noticed that when using <code>with open</code> to read a json, using either <code>r</code> or <code>rb</code> parameters returns identical results.</p> <pre><code>with open('something.json', 'rb') as f # 'r' returns the same thing t1 = json.load(f) </code></pre> <p>However, when I write to a json with <code>wb...
<python><json><python-3.x>
2023-10-07 03:42:23
4
411
Yandle
77,248,200
4,212,875
Correct way to use with open on xml files and ET.parse
<p>For reading in XML files with <code>with open</code> and <code>ET.parse</code>, should we use 'r', 'rb', something else, or does it not matter?</p> <pre><code>with open('something.xml', '??') as f: tree = ET.parse(f) </code></pre> <p>Edit:</p> <p>The reason I want to open this way is because the filepath I have ...
<python><python-3.x><xml><with-statement>
2023-10-07 02:55:19
1
411
Yandle
77,248,175
2,580,891
How can `from src.square import Square` be turned into `from square import Square`?
<p>In the following sample code:</p> <p><a href="https://github.com/panlex2010/sample-python-library" rel="nofollow noreferrer">sample-python-library</a></p> <p>the file containing unit tests is unable to find the class definition in the src directory.</p> <p>Executing the unittest command from the test/ and root direc...
<python>
2023-10-07 02:42:46
1
359
cppProgrammer
77,248,138
547,198
Why is Stop Iteration being raised in this code?
<p>I am trying to understand why is <code>StopIteration</code> being raised. My understanding is that when <code>nos</code> reaches <code>9</code>, the <code>if</code> statement evaluates to <code>True</code>. After that, <code>print(next(generate_nos([0, 1, …, 9])))</code> is called, which should result in <code>0</co...
<python>
2023-10-07 02:20:36
3
7,362
TimeToCodeTheRoad
77,247,941
15,587,184
Summarizing n-grams efficiently in Python on big data
<p>I have a very large dataset of roughly 6 million records, it does look like this snippet:</p> <pre><code>data = pd.DataFrame({ 'ID': ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'], 'TEXT': [ &quot;Mouthwatering BBQ ribs cheese, and coleslaw.&quot;, &quot;Delicious pizza with pepperoni and...
<python><pandas><dataframe><nlp><n-gram>
2023-10-07 00:44:48
1
809
R_Student
77,247,893
20,433,449
ModuleNotFoundError: No module named 'distutils' in Python 3.12
<p>When I try to import <code>customtkinter</code> in Python 3.12, I get the following error:</p> <pre class="lang-none prettyprint-override"><code> File &quot;c:\Users\judel\OneDrive\Documents\Python\main.py&quot;, line 1, in &lt;module&gt; import customtkinter as ttk File &quot;C:\Users\judel\AppData\Local\Pro...
<python><pip><modulenotfounderror><customtkinter><python-3.12>
2023-10-07 00:22:49
1
619
DarkPhinx
77,247,885
6,814,713
Mocking a module function and it's return
<p>I hope this is a straightforward answer, but I've been stuck trying to sort this out. I'm looking to mock out the following scenario. I previously had something like this that worked:</p> <pre class="lang-py prettyprint-override"><code># path/to/some/module.py class MyClass: # None of the methods or init should...
<python><mocking><pytest><python-unittest>
2023-10-07 00:18:32
2
2,124
Brendan
77,247,860
18,649,495
Keras weights layout confusion
<p>Recently I realized that in keras, the shape of dense layer's weight matrix is <code>(input_shpe, output_shape)</code>.</p> <p>Shouldn't it be <code>(output_shape, input_shape)</code> so when we dot weight and input together we get a length <code>output_shape</code> tensor?</p> <p>Also, why is the kernal size of con...
<python><tensorflow><keras>
2023-10-07 00:06:23
0
1,488
Fed_Dragon
77,247,820
749,434
get a portable function from Polynomial.fit()
<p>I took voltage readings from a LiPo battery discharging every 5 minutes - this gave me ~2700 data points. I pulled them into numpy with the hopes that I could find a polynomial function that would take a voltage and (based on the discharge curve) return the percentage of the battery remaining; in an ideal situation,...
<python><numpy>
2023-10-06 23:46:20
0
1,475
tmountjr
77,247,703
9,391,770
semilogy plot does not proper color y-ticks
<p>Issue is with <strong><code>semilogy</code></strong>, not with <code>twinx</code>. From next code</p> <pre><code>import numpy as np import matplotlib.pyplot as plt def plot_me(x): fig, ax1 = plt.subplots() ax1.semilogy(x, color=&quot;blue&quot;) for label in ax1.get_yticklabels(): label.set_color...
<python><matplotlib><plot><logarithm><yticks>
2023-10-06 22:56:35
1
396
Xopi García
77,247,409
4,430,968
Selecting css element on this site in scrapy (python)
<p>For some reason my CSS selector doesn't return anything on this site. Any idea why?</p> <pre><code>import scrapy class TestSpider(scrapy.Spider): name = &quot;test&quot; start_urls = [ &quot;https://www.toppstiles.co.uk/fixing-finishing/tools-accessories/mixing-drilling/drilling/rubi-drill-bit-diamo...
<python><scrapy>
2023-10-06 21:13:53
0
528
Davis
77,247,364
7,452,220
Convert a Pandas Series from Timedelta to Microseconds
<p>I have a Pandas <code>Timedelta</code> column that may be created like this:</p> <pre><code>import pandas as pd tdelta_ser = pd.date_range(start='00:00:00', periods=3, freq='700ms') - pd.date_range(start='00:00:00', periods=3, freq='500ms') tdiff_df = pd.DataFrame(tdelta_ser, columns=['TimeDiff']) print(tdiff_df) ...
<python><pandas><time-series><timestamp><timedelta>
2023-10-06 21:01:53
3
301
Gerard G
77,247,360
9,422,807
PySpark, add a tag column in union dataframe with condition
<p>I have a union dataframe from two sources. I want to add a flag column based on 'ID' and 'Source', The rule:</p> <ol> <li>If the rating is Null and from only one Source and one ID, flag N</li> <li>If the rating is not Null and from one ID, regardless the Source, flag Y; if Null, flag N</li> <li>If the rating is Null...
<python><pyspark><union-all><partition-by>
2023-10-06 21:01:32
0
413
Liu Yu
77,247,271
2,299,245
Read in sheet names only from Excel using pyspark.pandas
<p>I have about 30 Excel files that I want to read into Spark dataframes, probably using pyspark.pandas.</p> <p>I am trying to read them like this:</p> <pre><code>import pyspark.pandas as ps my_files = ps.DataFrame(dbutils.fs.ls(&quot;abfss://my_container@my_env.dfs.core.windows.net/my_files/&quot;) dataframes = [] d...
<python><apache-spark><pyspark><pyspark-pandas>
2023-10-06 20:41:55
1
949
TheRealJimShady
77,247,241
2,827,771
Pandas barh plot part of plot not showing
<p>I am using the following code to generate a barh plot with data stored in a pandas dataframe. Problem is that part of the first bar is not showing and I'm not sure how to address that. Here is the code:</p> <pre><code>fig = plt.figure(figsize = (10, 6)) ax = fig.add_subplot() ax2 = ax.twiny() import matplotlib.pyplo...
<python><pandas><plot><bar-chart>
2023-10-06 20:34:57
1
13,628
ahajib
77,247,230
656,912
How do I specify LaTeX codes in Python 3.12 f-strings?
<p>How do I put LaTeX codes in a Python 3.12 f-string?</p> <p>For example, the following <code>matplotlib</code> fragment now results in errors (<code>\</code> is a bad escape)</p> <pre class="lang-py prettyprint-override"><code>bif.set_title(f&quot;$x_n(r); , n\in {{ {bif_steps_min},\ldots,{bif_steps_min + bif_steps_s...
<python><latex><f-string><python-3.12>
2023-10-06 20:32:22
0
49,146
orome
77,247,141
4,729,764
Recursive lazy loading in async SQLAlchemy: Greenlet spawn error
<p>I'm trying to load and serialize a deeply nested model using SQLAlchemy into a json response (using pydantic <code>ParentType</code>), which seems difficult using an async engine.</p> <p>I have a <code>Parent</code> db model, which is related to a <code>Child</code>, which in turn is related to <code>GrandChild</cod...
<python><sqlalchemy><asyncpg>
2023-10-06 20:12:51
0
3,114
GRS
77,247,062
1,432,980
deserialize json array field into an object using pydantic
<p>I have an object, that has an inner object with custom serializer</p> <pre><code>class ParameterModel(BaseModel): size_x: int size_y: int @model_serializer def ser_model(self) -&gt; list: return [self.size_x, self.size_y] class ObjectModel(BaseModel): name: str parameters: Parameter...
<python><pydantic>
2023-10-06 19:53:42
1
13,485
lapots
77,247,057
10,969,942
Efficient Method for Flood Filling a Numpy Boolean Matrix: How to Replace All 'False' Values Enclosed by 'True'
<p>For a given image mask matrix of shape <code>H x W</code> containing only <code>True</code> and <code>False</code> values, I wish to convert all <code>False</code> values to <code>True</code> when they are entirely enclosed by <code>True</code> values.</p> <p>e.g.</p> <pre><code>mask = np.array([ [True, True, ...
<python><numpy><opencv><image-processing>
2023-10-06 19:51:25
1
1,795
maplemaple
77,247,053
1,222,122
Log response times for all HTTP requests from a docker container
<p>I have built a docker image that contains a pre-built application that I cannot add logging statements to. The application makes many HTTP requests as it executes, and I would like to log those requests, and in particular, the time it takes for those responses to be fulfilled. Is there something I add to my docker c...
<python><docker><httprequest><http-proxy>
2023-10-06 19:50:17
1
749
Gillfish
77,246,933
7,212,809
Handling timeouts with run-in-executor and asyncio and processPoolExecutor
<p>I'm using asyncio and ProcessPoolExecutor to run a piece of blocking code like this:</p> <pre><code>result = await loop.run_in_executor(pool, long_running_function) </code></pre> <p>I don't want long_running_function to last more than 2 seconds and I can't do proper timeout handling within it because that function c...
<python><python-3.x><asynchronous><process><python-asyncio>
2023-10-06 19:23:26
1
7,771
nz_21
77,246,875
489,088
How to get csvreader's DictReader to process one line at a time?
<p>I am unzipping a very large CSV file in a memory-constrained environment. For this reason I unzip a line at a time like so:</p> <pre><code>with zipfile.ZipFile(temp_file.name) as zip_content: filename = zip_content.namelist()[0] with zip_content.open(filename, mode=&quot;r&quot;) as content: for line...
<python><python-3.x><csv><streaming>
2023-10-06 19:13:35
2
6,306
Edy Bourne
77,246,869
3,261,292
Python reading byte string that was saved as string
<p>I have the following string that I read from a DB:</p> <pre><code>html_page = &quot;&quot;&quot;b'&lt;html lang=&quot;en&quot;&gt;&lt;body&gt; Accompagnement g\xc3\xa9n\xc3\xa9ral Droit des Affaires :&amp;lt;/strong&amp;gt;&amp;lt;/p&amp;gt;&amp;lt;ul&amp;gt; &amp;lt;li&amp;gt;D\xc3\xa9velopper la connaissance des a...
<python><mysql><string><character-encoding>
2023-10-06 19:12:19
0
5,527
Minions
77,246,782
2,696,565
Plotly Dash theme: LUX (Dark mode)
<p>I want to use the built-in bootswatch theme <a href="https://bootswatch.com/lux/" rel="nofollow noreferrer">LUX</a> but looks like only light mode is included in Dash i.e. when I use the below sample code, theme is applied in light mode. How can I have the dark mode instead? I don't care much about the ability to to...
<python><plotly><plotly-dash>
2023-10-06 18:54:07
1
629
user2696565
77,246,769
2,232,418
Output string list variable from python script to another python scrip in Azure Pipelines
<p>I've tried several articles and threads on Stackoverflow but cannot seem to find a solution the problem I'm having. This might be a simple answer but I can't wrap my head around it.</p> <p>I have two steps in my YAML pipeline script. Both call python scripts.</p> <p>In the first Python script I can making an API cal...
<python><azure-devops><azure-pipelines>
2023-10-06 18:52:07
1
2,787
Ben
77,246,508
1,791,475
How to add a prefix or suffix for unnesting in Polars
<p>I have the following code snippet where I am attempting to unnest <code>metadata</code>. However, within the <code>metadata</code>, there is a value named &quot;<code>language</code>&quot; which clashes with the existing &quot;<code>language</code>&quot; column name in the dataframe, thus causing a duplication error...
<python><dataframe><python-polars>
2023-10-06 17:53:07
3
1,112
Alireza Ghaffari
77,246,485
3,800,106
Run dash application with main function
<p>I have a dash application(.py) with running code which looks like,</p> <pre><code># whatever.py from dash import Dash, html, dcc import plotly.express as px import pandas as pd app = Dash() # assume you have a &quot;long-form&quot; data frame # see https://plotly.com/python/px-arguments/ for more options df = pd....
<python><python-3.x><plotly-dash>
2023-10-06 17:46:09
1
748
Gauraang Khurana
77,246,370
2,032,771
Creating and plotting a time-series from a multi-dimensional input
<p>I have some data like :</p> <pre><code>Timestamp, Dimension, Value t1, d1, v1 t2, d1, v2 t3, d1, v3 ... tn, d2, v4 tn+1, d2, v4 ... tm, d1, v5 ... </code></pre> <p>Is there a way with Pandas to convert these to a set of time series that I can plot <code>d1</code>, <code>d2</code> ...<code>dn</code> with timestamp on...
<python><pandas>
2023-10-06 17:22:05
1
1,680
avrono
77,246,025
15,341,457
Keras - adding an attention layer
<p>I am building an encoder-decoder architecture to do text summarization on restaurant reviews. I have been following this <a href="https://blog.paperspace.com/implement-seq2seq-for-text-summarization-keras/" rel="nofollow noreferrer">guide</a>. My model has 3 LSTM layers for the the encoder and one LSTM layer for dec...
<python><tensorflow><keras><deep-learning><lstm>
2023-10-06 16:18:59
1
332
Rodolfo
77,245,901
7,553,746
How to create a payload for requests using **kwargs?
<p>I'm trying to use **kwags to create a payload to send to an API but some parameters are optional. This code works fine for type as if it's not present it defaults to all but I also want to add <code>start_date</code> and <code>end_date</code> then realised this would not work as the parameters are optional and I ma...
<python><python-requests>
2023-10-06 16:00:10
1
3,326
Johnny John Boy
77,245,857
13,400,491
Use !reference or anchors with arguments in GitLab YAML
<p>In my GitLab YAML, I have several jobs that use the same basic command in their scripts but with different arguments. For example:</p> <pre class="lang-yaml prettyprint-override"><code>stages: - lint isort: stage: lint script: - pip install --trusted-host pypi.org --trusted-host files.pythonhosted.org --d...
<python><pip><gitlab><yaml><pipeline>
2023-10-06 15:53:55
0
367
user174358
77,245,851
3,177,186
Shutil copy2 says it copied the files, but I can't actually see them in Windows explorer
<pre class="lang-py prettyprint-override"><code>def do_it(): global files_to_move global copymove for file_dict in files_to_move.values(): if check_path(file_dict['new_path']) == False: return if (file_dict['disabled']): continue new_name = file_dic...
<python><windows><copy>
2023-10-06 15:53:02
1
2,198
not_a_generic_user
77,245,834
16,383,578
How to update multiple dictionary keys that reference to the same value simultaneously?
<p>I am working on a GUI program using PyQt6 and I am using QStyleSheet to stylize it, the stylesheet is hundreds of lines long and contains a lot of redundancies, so I want to write a class to manage the styling.</p> <p>The basic idea is simple, I have a few template strings in a dictionary, and an instance of the cla...
<python><dictionary>
2023-10-06 15:50:46
2
3,930
Ξένη Γήινος
77,245,726
19,675,781
How to use a row as legend in Seaborn barplot
<p>I have a dataframe like this:</p> <pre><code>index = ['Col-45', 'Col-68', 'Col-17', 'Col-69', 'Col-43', 'Col-49', 'Col-91', 'Col-13', 'Col-14', 'Col-18', 'Col-38', 'Col-37', 'Col-40', 'Col-44', 'Col-32', 'Col-82', 'Col-75', 'Col-19', 'Col-5', 'Col-6', 'Col-16', 'Col-4', 'Col-7', 'Col-41', 'Col-1...
<python><matplotlib><seaborn><bar-chart>
2023-10-06 15:32:35
1
357
Yash
77,245,654
10,973,108
Scrap data from "dinamic" XHR - this request does not appears in HTML
<p>I'm trying to scrape data from URL that get the data from an API. But, the problem of the XHR request it's that the URL generate is dinamic.</p> <p>I mean, whenever we do a request in the same URL, the XHR API URL changes.</p> <p>The same resource after reload request.</p> <p><a href="https://i.sstatic.net/B0xTH.png...
<python><web-scraping><python-requests><request><xmlhttprequest>
2023-10-06 15:21:53
0
348
Daniel Bailo
77,245,595
995,431
FastAPI TestClient overriding lifespan function
<p>In a more complicated setup using the <a href="https://python-dependency-injector.ets-labs.org/" rel="noreferrer">python dependency injector</a> framework I use the lifespan function for the FastAPI app object to correctly wire everything.</p> <p>When testing I'd like to replace some of the objects with different ve...
<python><python-3.x><dependency-injection><fastapi>
2023-10-06 15:14:33
4
325
ajn
77,245,262
7,009,806
How to automatically remove the namespace attached to a friend function defined within a C++ class, when using SWIG?
<p>I am trying to wrap a C++ class designed by a colleague of mine, using SWIG, for scripting programming in Python. These classes are defined as a bunch of source files which I have, but do not want to modify.</p> <p>All the classes are defined within a given namespace and include friend functions, for global treatmen...
<python><c++><swig>
2023-10-06 14:26:45
1
337
Olivier
77,245,234
512,480
AWS API Gateway, use unified Python file for Lambdas
<p>I am building my first REST API using API Gateway. I intend to use Python Lambda functions to do the work. I'm seeing that each Lambda function comes with its own space in which to insert Python code, but to me it would make a lot better sense to have one Python file containing all my handlers. I see that Lambda all...
<python><aws-lambda><aws-api-gateway>
2023-10-06 14:24:16
1
1,624
Joymaker
77,245,216
2,562,058
How to concatenate map objects without transforming them in iterables in python?
<p>Consider the following code:</p> <pre><code>def square(x): return x**2 def cube(x): return x**3 in1 = [0, 2, 3] in2 = [2, 1, 9] y1 = map(square, in1) y2 = map(cube, in2) </code></pre> <p>How to concatenate the two maps objects without explicitly converting the iterators <code>y1</code> and <code>y2</cod...
<python><python-3.x>
2023-10-06 14:19:51
1
1,866
Barzi2001
77,244,931
15,673,412
Scipy differential evolution - non-continuous bounds
<p>I am trying to setup a <code>differential_evolution</code> algorithm. I have approximately 15 variables, each with its own bounds (let's suppose they all share the same bounds <code>(150,250)</code>. I have successfully accomplished to do so.</p> <p>Now, I would like to add the possibility for any parameter to be se...
<python><scipy><genetic-algorithm><differential-evolution>
2023-10-06 13:38:09
1
480
Sala
77,244,743
13,146,029
Django AssertionError GraphQL
<p>I have an error on my GraphQL instance, I load the /graphql endpoint and it pops up with the below error.</p> <pre><code>AssertionError: You need to pass a valid Django Model in AuthorType.Meta, received &quot;None&quot;. </code></pre> <p>My schema for each is as follows:</p> <pre class="lang-py prettyprint-override...
<python><django>
2023-10-06 13:11:03
0
317
Graham Morby
77,244,582
4,530,214
Apply function element-wise
<p>In xarray, how can I apply a non-vectorize, non-universal function to a DataArrray, such that I can map each element in the values to a new one ? The custom function shall take a scalar value and return a scalar value:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np import xarray as xr def cu...
<python><pandas><python-xarray>
2023-10-06 12:49:48
2
546
mocquin
77,244,347
1,143,207
DynamoDB BatchGetItem Keys Array generation with multiple sort keys in python
<p>I might be missing something, but I struggle to generate multiple sort keys dict for use with Boto3 Batch get Item in python.</p> <p>For all other DB, which don't use sort key, I have something like this:</p> <p>I have a method that queries dynamo, but I use helper that populates the keys node:</p> <pre><code> ...
<python><amazon-dynamodb>
2023-10-06 12:13:35
1
1,520
Balkyto
77,244,324
12,133,068
snakemake get number of input of a rule
<p>I want to do something simple: get the number of input that has a <code>snakemake</code> rules, and use this value in my shell commands. I have a working solution with the trick below, but this is very ugly and I guess/hope there is something more pretty to get <code>N</code>?</p> <pre><code>rule x: input: ...
<python><snakemake>
2023-10-06 12:08:33
1
334
Quentin BLAMPEY
77,244,199
906,658
How do I freeze the requirements of a tox test environment?
<p>I usually install my requirements from an abstract file like so:</p> <pre><code># requirements.in pytest </code></pre> <p>I define test environments in a <code>tox.ini</code> like so:</p> <pre class="lang-ini prettyprint-override"><code>[testenv] deps = -rrequirements.in commands = pytest </code></pre> <p>How do I f...
<python><pip><subprocess><requirements.txt><tox>
2023-10-06 11:49:21
5
14,598
Bengt
77,244,092
1,044,117
Why monkey patching (via setattr) magic methods does not work?
<p><code>x</code> is an instance of some object:</p> <pre><code>&gt; x = type('someobject', (), {})() &gt; repr(x) &lt;someobject object at 0x10172d990&gt; </code></pre> <p>Why monkey patching a magic method (e.g. <code>__repr__</code>) does not work?</p> <pre><code>&gt; setattr(x, '__repr__', lambda self: f'&lt;someob...
<python>
2023-10-06 11:32:43
2
19,047
fferri
77,243,985
326,016
Multiple Choice user input and routing in Langchain Python
<p>I am building a chatbot for my website with Langchain and I want to lead the user through the conversation with different answer options that I want to predefine for each step.</p> <p>So my chatbot will greet the user with a message like this:</p> <blockquote> <p>Hi there, how can I help you? Do you want to know mor...
<python><langchain><py-langchain>
2023-10-06 11:11:51
1
1,158
Abenil
77,243,820
10,566,155
Import Python file in databricks notebook
<p>I am trying to import python files from databricks notebook. I am able to import the function but it keep giving me error - <em><strong>NameError: name 'col' is not defined</strong></em>.</p> <p>I have a file /Workspace/Shared/Common/common.py. The code in that file is:</p> <pre><code>def cast_datatypes(df_target, d...
<python><azure><pyspark><jupyter-notebook><azure-databricks>
2023-10-06 10:46:43
2
329
Harshit Mahajan
77,243,809
15,704,972
How do I select columns on the innermost level of a Pandas DataFrame with multiindexed columns without knowing the amount of levels?
<p>I have a function that needs to select certain columns in the innermost level of a dataframe with multiindexed columns by name, while also reporting all higher column levels. The names of the columns in the innermost level are consistent, but the amount of multiindex levels above them isn't fixed. I might for instan...
<python><pandas><multi-index>
2023-10-06 10:45:51
1
561
KeyboardCat
77,243,668
3,735,871
Airflow schedule job - how to run it before the end of interval
<p>I'm trying to schedule a yearly job in Airflow, that runs every year on Oct 1st. The problem is, for this year's job (today is Oct 6th 2023), the job won't run till next year (2024 Oct 1st ). I need to run past several years' jobs as well this year's.</p> <p>How should I schedule the job? I can't run command to trig...
<python><airflow>
2023-10-06 10:22:27
1
367
user3735871
77,243,599
1,739,884
How to type hint arguments of factory method, where the managed instances are from generic class with additional constructor args
<p>Consider the following case where we have a Manager which manages instances of certain classes. These classes must be a subclass of a given class but can be user-defined (i.e. are a generic).</p> <p>Since the Manager class has ownership of the instances, the question is how to correctly type-hint the situation as th...
<python><python-typing>
2023-10-06 10:11:39
1
6,230
Andreas H.
77,243,572
717,069
Python GIL and deadlock detection?
<p>When using Python a multi-threaded environment, it is quite easy to deadlock as we need to lock the Python GIL. While trying to lock the GIL, we may hold other locks and the Python thread holding the GIL may call us trying to get the same lock. Ideally, we'd have a <code>PyGILSTATE_TryEnsure()</code> such that on...
<python><multithreading><deadlock><gil>
2023-10-06 10:08:17
0
1,740
Jan Wielemaker
77,243,519
717,069
Threads, the Python GIL and save/restore thread state
<p>I'm working on making Python threads cooperate with SWI-Prolog threads, where SWI-Prolog supports fully independent native threads. We are talking about embedding Python. After initializing the embedded Python interpreter, the calling thread has a Python thread state. To allow other threads, I need to call <cod...
<python><multithreading><gil>
2023-10-06 09:59:48
0
1,740
Jan Wielemaker
77,243,328
7,179,299
Web scraping of a sports table in R
<p>I need to web scrape the table information from the following link, using R or Python: <a href="https://euroleaguefantasy.euroleaguebasketball.net/en/stats-fantasy-euroleague" rel="nofollow noreferrer">https://euroleaguefantasy.euroleaguebasketball.net/en/stats-fantasy-euroleague</a></p> <p>So far I have tried the <...
<python><r><web-scraping><rvest>
2023-10-06 09:30:29
2
3,168
LDT
77,243,323
1,374,987
Trying to install older version of python package from pypi but pip says version not available
<p>I'm trying to install an older version of the <code>opencv-python</code> package, specifically <a href="https://pypi.org/project/opencv-python/4.1.0.25/" rel="nofollow noreferrer">4.1.0.25</a> but when running <code>pip install opencv-python==4.1.0.25</code> it complains that <code>Could not find a version that sati...
<python><pip><pypi>
2023-10-06 09:30:26
0
4,696
PentaKon
77,243,224
2,562,058
map() returns an iterator that yelds numpy arrays. How to convert it in a numpy array?
<p>I am using a <code>map</code> function where each element pointed by the returned iterator is a <code>numpy</code> array, i.e.</p> <pre><code>result = list(map(func, values)) print(result[:2])) [array([0.981, 0.23]), array([1.231, -0.56])] </code></pre> <p>I wish the result to be a unique <code>numpy</code> array, ...
<python><python-3.x><numpy>
2023-10-06 09:15:03
3
1,866
Barzi2001
77,243,216
22,466,650
How to find the closest non null values to a target value?
<p>Sorry for the title but basically I'm dealing with a dataset that looks like a pacman game.</p> <p>So I need to find the coordinates of the closest ghosts to the pacman.</p> <pre><code>import pandas as pd pacman = [ list(&quot; G&quot;), list(&quot; P G &quot;), list(&quot; G &qu...
<python><pandas><numpy>
2023-10-06 09:13:55
1
1,085
VERBOSE
77,243,198
1,136,850
Python ModuleNotFoundError even after appending it
<p>I keep getting <code>ModuleNotFoundError: No module named 'pandas'</code>, while I already included its location:</p> <pre><code>import pandas as pd from flask import Flask, request, jsonify, send_file from io import BytesIO import re import json from Crypto.Cipher import AES from base64 import b64decode import os i...
<python><python-3.x><flask><python-module>
2023-10-06 09:11:18
4
3,227
CairoCoder
77,243,110
5,338,465
Python lambda type hint in pycharm
<p>I'm using Pycharm to develop python scripts.</p> <p>I have a list of class and want to sort this list by a class property.</p> <p>However, when I use:</p> <pre><code>results: list[HotelInfo] = get_result() results.sort(key=lambda x: x.price) </code></pre> <p>PyCharm's type hint shows that &quot;x&quot; is of type &q...
<python><python-3.x><pycharm>
2023-10-06 08:56:24
1
1,050
Vic
77,243,080
3,339,667
Combining Concatenate and wraps to get passthrough kwarg type hinting in python
<p>I've got a fun question I've been struggling with. Here's a toy bit of code:</p> <pre class="lang-py prettyprint-override"><code>from functools import wraps from pydantic import BaseModel class Config(BaseModel): vegetable: str = &quot;potato&quot; fruit: str = &quot;strawberry&quot; class SomeClass: ...
<python><python-typing><python-decorators>
2023-10-06 08:49:54
0
353
Samreay
77,242,993
14,365,042
How to reshape pandas dataframe into a symmetric matrix (corr-like square matrix)?
<p>I have a df like below:</p> <pre><code> name1 name2 value 0 A B 1300 1 A C 150 2 A D 300 3 B C 450 4 B D 200 5 C D 300 </code></pre> <p>I tried to <code>pivot</code> the table to plot a corr-like heatmap based on the <code>value</code> column:</p> <p...
<python><pandas><dataframe><pivot>
2023-10-06 08:34:52
1
305
Joe
77,242,992
11,328,614
Pytest asyncio, howto await in setup and teardown?
<p>I'm using <code>pytest-asyncio</code> to test my <code>asyncio</code> based library.</p> <p>I'm using the class-level approach, in which a <code>TestClass</code> has several <code>TestMethods</code> which are invoked by the test framework one after each other.</p> <p>The <code>setup</code> method initializes the <co...
<python><python-3.x><python-asyncio><teardown><pytest-asyncio>
2023-10-06 08:33:57
2
1,132
Wör Du Schnaffzig
77,242,892
6,562,240
Python List Comprehension: If Item Doesn't Exist, Insert a Value?
<p>I have two lists which i want to merge together as two separate arrays into one dataframe. The issue is, the data i am working with is patchy and has missing information</p> <p><strong>Data</strong></p> <p><a href="https://i.sstatic.net/JyQOq.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/JyQOq.png" ...
<python><list><list-comprehension>
2023-10-06 08:17:00
1
705
Curious Student
77,242,732
1,850,007
How to multiply array by each element of second array and concatenate them?
<p>My matrix:</p> <pre><code>a = np.array([[1, 2], [3, 4]]) b = np.array([[5, 6]]) </code></pre> <p>I want <code>c</code> as:</p> <pre><code>np.array([[5, 10, 6, 12], [15, 20, 18, 24]]) </code></pre> <p>Entry wise multiplication of <code>a</code> by <code>b</code>, then concatenate them. How to do this effectively with...
<python><numpy><kronecker-product>
2023-10-06 07:53:45
2
1,062
Lost1
77,242,703
2,385,132
Tensorflow dataset causes a memory leak
<p>I'm creating a dataset for my xception model training, I'm doing it like this:</p> <pre><code>def load_dataset(height: int, width: int, path: str, kind: str, batch_size=32) -&gt; tf.data.Dataset: directory = os.path.join(path, kind) return keras.utils.image_dataset_from_directory( directory=director...
<python><tensorflow><tensorflow-datasets>
2023-10-06 07:50:28
1
3,930
Marek M.
77,242,502
4,706,952
Color scatterplot by grouping in pandas
<p>Having a pandas <code>df</code> as follows:</p> <pre><code># Sample data data = { 'x': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 'y': [10, 9, 8, 7, 6, 5, 4, 3, 2, 1], 'z': ['A', 'B', 'C', 'A', 'B', 'C', 'A', 'B', 'C', 'A'] } # Creating a pandas DataFrame df = pd.DataFrame(data) </code></pre> <p>I try to make a s...
<python><pandas>
2023-10-06 07:17:33
1
7,517
symbolrush
77,242,474
3,161,120
pytest: how to terminate FastAPI TestClient after each test?
<p>I am testing FastAPI application that keeps open WebSocket connection forever. By design, only the client is supposed to close WebSocket. After test execution, pytest doesn't finish, it is hanging forever.</p> <ol> <li>What's the proper way of testing such an application?</li> <li>Is there any way to terminate the f...
<python><websocket><pytest><fastapi><ubuntu-22.04>
2023-10-06 07:12:01
1
1,830
gbajson
77,242,246
386,861
How to implement conditional colors on a time series plot in Altair
<p>I've got a dataset that I'm trying to work up around hospital admissions over time.</p> <p>Here's the python</p> <pre><code>import pandas as pd import altair as alt import numpy as np pd.options.display.max_columns = 10 pd.options.display.max_rows = 50 pd.set_option('display.max_colwidth', None) alt.data_transformer...
<python><pandas><altair>
2023-10-06 06:25:23
0
7,882
elksie5000
77,242,163
3,082,759
Azure Functions Postgres ID violation error on auto increment ID
<p>I have an Azure function that retrieve data from API and save it to Postgres DB. Now I have this returning error with duplicated ID</p> <blockquote> <p>Error occurred during database operation: duplicate key value violates unique constraint 'contacts_pkey' DETAIL: Key (id)=(12736022) already exists.</p> </blockquot...
<python><postgresql><azure-functions>
2023-10-06 06:07:07
1
387
PiotrK
77,242,012
3,211,801
Using bigquery client inside asyncio causes hanging issue in "OpenSSL/SSL.py", in recv_into
<p>We are doing some read operations using python bigquery library.</p> <pre><code>Python version: Python 3.8.10 Google bigquery package: https://pypi.org/project/google-cloud-bigquery/ (version: 2.30.1) </code></pre> <pre class="lang-py prettyprint-override"><code>from google.oauth2 import service_account from google....
<python><google-bigquery><openssl><python-asyncio>
2023-10-06 05:17:34
0
882
Nandha
77,241,984
14,963,549
How to take a screenshot by web scraping code (Selenium) in Databricks for Azure?
<p>I'm starting in the world of web scraping. my try is so simple. I'm download and installing firefox. Then, I start by going to a google, and just to confirm this code is working I'm trying to take a screenshot and save it into a temporary path in order to display at the end.</p> <p>Unfortunately, when I execute the ...
<python><selenium-webdriver><web-scraping><databricks><azure-databricks>
2023-10-06 05:07:48
0
419
Xkid
77,241,916
8,253,860
How to test the payload by mocking POST request in pytest?
<p>I have a function that sends some payload to an external API using <code>requests.post()</code> method. I want to test whether the payload satisfies certain conditions in the tests. Based on that, I need to mock requests post and capture the payload in the testing function. Ideally, I don't want to add another exter...
<python><unit-testing><python-requests><pytest>
2023-10-06 04:42:20
1
667
Ayush Chaurasia
77,241,833
264,136
variables to hold "none" if the list items don't exist
<pre><code>uut_image = image_file[0] hub_image = image_file[1] hub_sn_image = image_file[2] </code></pre> <p>I want the variables to hold &quot;none&quot; (string) if the list items don't exist.</p>
<python>
2023-10-06 04:14:35
1
5,538
Akshay J
77,241,797
12,892,937
Python QuasarDB connection refused
<p>I'm following QuasarDB guide here: <a href="https://doc.quasar.ai/master/primer.html" rel="nofollow noreferrer">https://doc.quasar.ai/master/primer.html</a></p> <pre><code>&gt; docker run -d --name qdb-server bureau14/qdb &gt; docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS ...
<python><docker>
2023-10-06 04:02:03
1
1,831
Huy Le
77,241,756
9,357,484
Error running code taking from Gymnasium tutorial
<p>I would like to run the following code using PyCharm IDE</p> <pre><code>import gymnasium as gym env = gym.make(&quot;LunarLander-v2&quot;, render_mode=&quot;human&quot;) observation, info = env.reset(seed=42) for _ in range(1000): action = env.action_space.sample() # this is where you would insert your policy ...
<python><openai-gym>
2023-10-06 03:48:57
2
3,446
Encipher