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,874,658
2,098,831
How to display inlay type hints in Pylance that use (python) aliases?
<p>I'm using pylance/pyright in VSCode and have activated the following option:</p> <pre><code>&quot;python.analysis.inlayHints.variableTypes&quot;: true </code></pre> <p>This cause the IDE to suggest type hints in the code. However, the suggested hints do not take in account that I have imported libraries with aliases...
<python><python-typing><pylance>
2023-03-29 08:08:09
1
5,135
Carmellose
75,874,626
11,913,986
merge two dfs based on lookup of a common column keeping duplicates
<p>I have df1 as:</p> <pre><code>import pandas as pd index = [0, 1, 2, 3] columns = ['col0', 'col1'] data = [['A', 'D'], ['A', 'D'], ['C', 'F'], ['A', 'D'] ] df1 = pd.DataFrame(data, index, columns) col0 col1 0 A D 1 B E 2 C F 3 A D </code></pre> <p>I have df2 as:</p> ...
<python><pandas><database><dataframe><pyspark>
2023-03-29 08:04:21
2
739
Strayhorn
75,874,549
19,106,705
Remove for loop in pytorch
<p>I want to remove <code>for loop</code> in pytorch.</p> <p>I wrote the code as below, but it's not cool. And it doesn't use the GPU well either.</p> <pre class="lang-py prettyprint-override"><code>for i in range(idx.shape[0]): for j in range(idx.shape[2]): for k in range(idx.shape[3]): for x in range(idx....
<python><pytorch>
2023-03-29 07:55:34
1
870
core_not_dumped
75,874,491
9,798,210
How to add the text to the side of the line using matplotlib?
<p>I have a code which generates the line using matplotlib. Below is the code</p> <pre><code>import matplotlib.pyplot as plt plt.figure(1100) plt.plot(np.array([1,1]),np.array([0,3]),'k','LineWidth',5) x = np.array([1,1]) y = np.array([0,3]) plt.text(x[-1], y[-1]+0.5, '(t)', ha='center') plt.show() </code></pre> <p>Bel...
<python><python-3.x><matplotlib>
2023-03-29 07:48:22
1
1,835
merkle
75,874,453
2,666,289
Typing unpacking of a class
<p>When using a tuple in Python and unpacking, types can be automatically deduced by type checkers (mypy/pyright):</p> <pre class="lang-py prettyprint-override"><code>t = (33, &quot;hello&quot;) a, b = t # a, b correctly deduced by both mypy and pyright </code></pre> <p>How can I achieve the same with a custom class (...
<python><python-typing>
2023-03-29 07:43:03
1
38,048
Holt
75,874,357
2,971,574
Pyspark: Count number of True values per row
<p>Working in databricks, I've got a dataframe which looks like this:</p> <pre><code>columns = [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;] data = [(True, True, True), (True, True, True), (True, False, True)] df = spark.createDataFrame(data).toDF(*columns) df.display() </code></pre> <p><a href="https://i.sstatic.net/o...
<python><pyspark><databricks><azure-databricks>
2023-03-29 07:31:29
2
555
the_economist
75,874,348
6,214,197
Python: Creating fast api request with valid custom headers
<p>Was struggling in finding how to create a fast.Request object with custom headers for testing. Spent around 3 hours searching for it. Adding it here so that you can save some time.</p>
<python><http><testing><request><fastapi>
2023-03-29 07:30:31
1
957
Shubham Arora
75,874,050
2,971,574
Check whether boolean column contains only True values
<p>Working in Databricks, I've got a dataframe which looks like this:</p> <pre><code>columns = [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;] data = [(True, True, True), (True, True, True), (True, False, True)] df = spark.createDataFrame(data).toDF(*columns) df.display() </code></pre> <p><a href="https://i.sstatic.net/O...
<python><apache-spark><pyspark><databricks><azure-databricks>
2023-03-29 06:57:59
3
555
the_economist
75,874,043
11,479,825
Convert specific list of strings cells into multiple rows and keep the other columns
<p>I have pandas dataframe that looks like this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>label</th> <th>pred</th> <th>gt</th> </tr> </thead> <tbody> <tr> <td>label1</td> <td>val1</td> <td>val11</td> </tr> <tr> <td>label2</td> <td>['str1', str2']</td> <td>['str1', 'str3', 'str4']</td...
<python><pandas><pandas-explode>
2023-03-29 06:57:14
1
985
Yana
75,873,947
8,477,952
Python KeyError in format() using strings
<p>I tried to use the <code>format()</code> function in python and it gives me the <code>KeyError</code>. Don't get why. I looked up some websites using the <code>format()</code> function in combination with strings and I was convinced that I was doing it right, obviously I am not.</p> <pre><code>servoid = &quot;te...
<python><format>
2023-03-29 06:44:49
1
407
bask185
75,873,838
9,042,093
Change the error stream in logger in python
<p>I dont want any logger prints in my terminal. I have separate log file where I will dump all the logger messages.</p> <p>So now if I do</p> <pre><code>logger.exception('error') </code></pre> <p>The message will be shown in terminal which I dont want.</p> <p>I assume I need to change something here in my code.</p> <p...
<python><python-3.x><python-logging>
2023-03-29 06:29:40
0
349
bad_coder9042093
75,873,522
9,501,624
More efficient cookie cutter for boolean array to simulate detector response?
<p>I am applying a predefined pattern to a chain of events to simulate a dead time of a detector.</p> <p>I tried to think of a vectorized method to apply that pattern (e.g. <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.convolve.html#scipy.signal.convolve" rel="nofollow noreferrer">convoluti...
<python><numpy><filter><vectorization>
2023-03-29 05:43:22
1
3,844
Christian Karcher
75,873,428
7,975,962
How to install diff version of a package (transformers) without internet in kaggle notebook w/o killing the kernel while keeping variables in memory?
<p>I have prepared an inference pipeline for a Kaggle competition and it has to be executed without internet connection.</p> <p>I'm trying to use different versions of transformers but I had some issues regarding the installation part.</p> <p>Kaggle's default transformers version is <code>4.26.1</code>. I start with in...
<python><jupyter-notebook><pip><huggingface-transformers><python-importlib>
2023-03-29 05:26:20
2
974
gunesevitan
75,873,335
8,510,149
Linear Regression over Window in PySpark
<p>I want to perform a Linear Regression over a Window in PySpark. I have a timeseries and I want the slope of that timeseries for each person (identified by an ID) in a dataset looking 12 months back.</p> <p>My idea was to do like this:</p> <pre><code>sliding_window = Window.partitionBy('ID').orderBy('date').rowsBetwe...
<python><pyspark><linear-regression>
2023-03-29 05:07:53
1
1,255
Henri
75,873,239
1,718,152
Efficiently persist many slices referencing the same dataframe
<p>I have a list of DataFrames which are slices to another DataFrame. I'm looking for a way to efficiently persist the DataFrames.</p> <pre><code>import pandas as pd import numpy as np timestamps = pd.date_range(&quot;2018-01-01&quot;, &quot;2023-03-29&quot;, freq=&quot;H&quot;) values = np.random.rand(len(timestamps)...
<python><pandas><pickle>
2023-03-29 04:50:46
0
448
Semi
75,873,232
10,748,412
How to get individual columns values into a list using Python
<p>I have an image which is the extracted row of a table and it looks like this: <a href="https://i.sstatic.net/Y69bI.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/Y69bI.png" alt="enter image description here" /></a></p> <p>I want to extract each column which is separated by vertical lines into a list....
<python><opencv><machine-learning><deep-learning><paddleocr>
2023-03-29 04:48:37
1
365
ReaL_HyDRA
75,873,117
3,891,431
python call a function before every "continue"
<p>I am writing many files each with many samples into a database.</p> <p>My code is in this format:</p> <pre><code>files = find_my_files() for file in files: try: check_file(file) except: logging.warning(f'{file} did not pass the check, skipping this file') continue try: pr...
<python><python-3.x>
2023-03-29 04:23:06
1
4,334
Rash
75,873,099
13,957,283
Django rest framework slow response time
<p>I am working on a project. I am using <strong>Django rest framework</strong>.</p> <p>I have a category model. And there is only 2 rows. And the api response time is 180 ms avarage.</p> <p>it is <strong>too slow</strong> for only 2 rows. And api is <strong>very simple</strong>. Why it is too slow for such a simple ap...
<python><django><django-rest-framework>
2023-03-29 04:18:20
0
1,216
Noa
75,873,043
15,155,978
How to upload a table from a CSV file to GCP BigQuery using a Python script?
<p>I’m new to GCP BigQuery. I would like to upload <a href="https://drive.google.com/file/d/1zd4hcopyarm7PvRvBDfga2_1OHRdjTzW/view?usp=share_link" rel="nofollow noreferrer">this dataset</a> to BigQuery using a Python script as follow: (I’m using this <a href="https://medium.com/pipeline-a-data-engineering-resource/auto...
<python><google-cloud-platform><google-bigquery>
2023-03-29 04:05:47
0
922
0x55b1E06FF
75,872,456
1,925,518
Python least means squares adaptive filter implementation
<p>I'm trying to write a least means squares adaptive filter in python similar to that of <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.least_squares.html" rel="nofollow noreferrer">least_squares</a> in scipy. I'm trying to follow the <a href="https://en.wikipedia.org/wiki/Least_mean_squa...
<python>
2023-03-29 01:54:50
1
735
EarthIsHome
75,872,372
11,141,816
Numerical instability of system of equations of large order polynomials
<p>I have a set of non linear polynomials</p> <pre><code>V_n(Input[N])=0 </code></pre> <p>where <code>n</code> runs from <code>1</code> to <code>N</code>, with <code>N</code> of <code>Input[N]</code> unknowns. The <code>V_n()</code> contained the polynomial tern of <code>x**N</code>. I used the newton's methods to find...
<python><matrix><numerical-methods><newtons-method>
2023-03-29 01:38:38
0
593
ShoutOutAndCalculate
75,872,342
2,977,256
JAX performance problems
<p>I am obviously not following best practices, but maybe that's because I don't know what they are. Anyway, my goal is to generate a tubular neighborhood about a curve in three dimensions. A curve is give by an array of length three <code>f(t) = jnp.array([x(t), y(t), z(t)])</code>.</p> <p>Now, first we compute the un...
<python><jax>
2023-03-29 01:30:22
1
4,872
Igor Rivin
75,872,319
1,942,626
tensorflow predict is too slow
<p>I built up a model with 500 captcha images with tensorflow. It works fine on my macbook M1 at a good speed. But when I deployed it to cloud Ubuntu server with 4 cores. it became very slow. Esp. it takes long time when it starts up.</p> <p>I am using tb-nightly==2.13.0a20230328 version.</p> <p>Can I run the process a...
<python><tensorflow><captcha>
2023-03-29 01:24:59
0
845
user1942626
75,872,170
17,274,113
writing an array to a raster file with spatial attributes using array2raster. ` AttributeError: NoneType`
<p>I have two scripts. One uses hydrology tools and finds the depths of sinks in a dem and outputs a binary sink/no-sink array. The other script labels pixel groups. After this I have a function <code>array2raster</code> from <a href="https://gist.github.com/jkatagi/a1207eee32463efd06fb57676dcf86c8?permalink_comment_id...
<python><arrays><geospatial><raster>
2023-03-29 00:47:27
1
429
Max Duso
75,872,125
5,342,009
Speechmatics submit a job without audio argument
<p>I have implemented a SpeechMatics speech to text application with their API as given in this document <a href="https://docs.speechmatics.com/introduction/batch-guide" rel="nofollow noreferrer">with the code</a> below :</p> <pre><code>from speechmatics.models import ConnectionSettings from speechmatics.batch_client ...
<python><django>
2023-03-29 00:35:35
1
1,312
london_utku
75,872,072
9,872,200
Python assign covariance row wise calculation
<p>I am trying to assign the covariance value to a column based on the dataframe I have. The df is ~400k records x 30+ columns. The two data series that act as inputs for COV() are all aligned as a single record (with ~400k records). I would like to assign the column names as a list and then do operations as arrays....
<python><arrays><pandas><statistics><covariance>
2023-03-29 00:18:45
1
513
John
75,871,807
10,474,998
Rename subfolder in multiple folders by replacing a part of the string
<p>Assuming I have multiple subfolders inside many different folders (**). All the folders are in a main folder called Project1. I want to replace the string name of the folders using <code>substring</code> function.</p> <pre><code>import glob import os import pandas as pd paths = glob.glob(&quot;CC:/Users/xxx/Colleg...
<python><python-3.x><pandas>
2023-03-28 23:13:33
2
1,079
JodeCharger100
75,871,610
217,332
Spawning a new process with an asyncio loop from within the asyncio loop running in the current process
<p>I'm a little confused about the interaction between multiprocessing and asyncio. My goal is to be able to spawn async processes from other async processes. Here is a small example:</p> <pre><code>import asyncio from multiprocessing import Process async def sleep_n(n): await asyncio.sleep(n) def async_sleep(n...
<python><linux><python-asyncio><python-multiprocessing>
2023-03-28 22:33:10
2
83,780
danben
75,871,584
4,538,768
Serialize several models in Django
<p>I am looking to optimize the serialization of multiple models. Currently, I am able to serialize the models through the use of <code>SerializerMethodField</code> and providing the needed fields. I would like to use directly the serializer <code>SiteSchoolSerializer</code> to fetch in advance the results using <code>...
<python><django><django-models><django-rest-framework><django-views>
2023-03-28 22:27:32
2
1,787
JarochoEngineer
75,871,529
310,370
cv2 rembg remove function changes the color tone of the input image. How to fix it?
<p>in this demo color is not changed : <a href="https://huggingface.co/spaces/KenjieDec/RemBG" rel="nofollow noreferrer">https://huggingface.co/spaces/KenjieDec/RemBG</a></p> <p>So here my method</p> <pre><code>def remove_background(image_path): # Read the input image input_image = cv2.imread(image_path, cv2.IM...
<python><image-processing><rembg>
2023-03-28 22:18:08
1
23,982
Furkan Gözükara
75,871,388
5,342,009
Speechmatics Python Code fails to use Google Cloud Storage signed url with fetch_data
<p>I am experimenting with Speechmatics Transcription API using a file in Google Cloud Storage with a signed url.</p> <p>The <a href="https://docs.speechmatics.com/features-other/fetch-url" rel="nofollow noreferrer">SpeechMatics Document</a> says that I have to use fetch_data parameter in order to provide a URL to the ...
<python><google-cloud-platform><google-cloud-storage>
2023-03-28 21:53:50
1
1,312
london_utku
75,871,250
9,481,731
using fstring or format causing 404 return in server response
<p>Team, on linux, Using f-string or format or concatenate in python gets 404 response from server and works when I use values statically. a more strange part is when i run this locally on MAC with fstring it works.</p> <p>Code I tried is commented</p> <pre><code>GERRIT_CN = os.environ.get('GERRIT_CHANGE_NUMBER') GERRI...
<python><python-3.x><sonarqube>
2023-03-28 21:32:33
0
1,832
AhmFM
75,871,154
6,462,301
Plotly: Share x-axis for subset of subplots
<p>The following python code will share the x-axis for all three subplots:</p> <pre><code>from plotly.subplots import make_subplots import plotly.graph_objects as go fig = make_subplots(rows=3, cols=1, shared_xaxes=True, vertical_spacing=0.02) fig.add_trace(go.Scatter(x=[0, 1, ...
<python><plotly><subplot>
2023-03-28 21:18:24
3
1,162
rhz
75,871,139
967,621
Read a file line by line in Pyodide
<p>The code below reads the user-selected input file entirely. This requires a lot of memory for very large (&gt; 10 GB) files. I need to read a file line by line.</p> <p><strong>How can I read a file in Pyodide one line at a time?</strong></p> <hr /> <pre><code>&lt;!doctype html&gt; &lt;html&gt; &lt;head&gt; &...
<javascript><python><webassembly><pyodide>
2023-03-28 21:15:45
2
12,712
Timur Shtatland
75,871,053
4,977,957
Standard Approach to Adding Services to Python FastAPI App?
<p>I define a service as a class that provides DRY methods that can be called from anywhere in the code.</p> <p>My FastAPI controller has an endpoint:</p> <pre><code>@router.get(&quot;/health&quot;) async def health_check(): return {&quot;status&quot;: &quot;pass&quot;} </code></pre> <p>I would like to update it to <...
<python><dependency-injection><service><fastapi>
2023-03-28 21:03:37
2
12,814
VSO
75,871,001
15,452,898
Advanced filtering in PySpark
<p>Currently I'm performing some calculations on a large database that contains various information on how loans are paid by various borrowers. From technical point of view, I'm using PySpark and have just faced with an issue of how to use advanced filtering operations.</p> <p>For example my dataframe looks like this:<...
<python><pyspark><filtering>
2023-03-28 20:56:44
2
333
lenpyspanacb
75,870,967
10,620,003
Split the dataframe with a minimal way in pandas
<p>I have 10 different dataframe with shape 1000*1000. I have to use a part of this data frames for the training and validation. Now I am using the following lines of code to separate this dfs:</p> <pre><code> df1_train = df1.loc[:, Start:end] df2_train = df2.loc[:,Start:end] df3_train = df3.loc[:,Start:end] ... </...
<python><pandas>
2023-03-28 20:51:50
2
730
Sadcow
75,870,852
15,067,623
Placing brackets in logical formula where possible in Python
<p>How can I place brackets where possible in a first order logical formula in Python? This formula only exists out of logical not ¬, and ∧ or ∨, implies → and bi implies ↔. For example &quot;¬(A ∧ B) ∨ C&quot; yields ((¬(A ∧ B)) ∨ C). You can see my attempt below. I want a function that wraps each operator in bracke...
<python><string><parsing><logic>
2023-03-28 20:37:38
1
1,386
Jip Helsen
75,870,708
15,433,308
Python equivalent of JTS ConcaveHullOfPolygons
<p>The latest version of JTS <a href="https://locationtech.github.io/jts/javadoc/org/locationtech/jts/algorithm/hull/ConcaveHullOfPolygons.html" rel="nofollow noreferrer">implements an algorithm</a> that computes a concave hull of the input polygons, which guarantees the input polygons are contained in the result hull....
<python><geometry><computational-geometry><jts><concave-hull>
2023-03-28 20:18:59
1
492
krezno
75,870,695
781,938
How do I get a pandas MultiIndex level as a series, keeping the original MultiIndex?
<p>Suppose I have a MultiIndex like:</p> <pre class="lang-py prettyprint-override"><code>multiindex = pd.MultiIndex.from_product([['a', 'b'], range(3)], names=['first', 'second']) </code></pre> <pre><code>MultiIndex([('a', 0), ('a', 1), ('a', 2), ('b', 0), ('b', 1), ...
<python><pandas><dataframe>
2023-03-28 20:16:46
1
6,130
william_grisaitis
75,870,461
877,329
Workaround for "Unknown template argument type 604" when usinig clang python bindings
<p>I am playing around with python-clang, version 15. I fed it with a concept, and got error</p> <pre><code>ValueError: Unknown template argument kind 604 </code></pre> <p>This is the code:</p> <pre class="lang-py prettyprint-override"><code>import clang.cindex def visit_nodes(node, src_file, depth): if node.locat...
<python><clang><c++20>
2023-03-28 19:44:44
1
6,288
user877329
75,870,293
5,089,311
Tkinter: share single Frame accross multiple tabs (or dynamically reparent)
<p>I have <code>tkinter.Notebook</code> that contains multiple tabs. I have <code>tkinter.Frame</code> &quot;run box&quot; with set of controls, that I want share across several tabs. Specifically <code>Test info</code> and <code>Test list</code> should have it.</p> <p><a href="https://i.sstatic.net/MUwyj.png" rel="nof...
<python><tkinter>
2023-03-28 19:23:39
1
408
Noob
75,870,152
781,938
Pandas: raise an error if indexes don't match when concat'ing or merging?
<p>I want to concatenate (index-wise) or merge two pandas DataFrames. However, I want this to fail if the two DataFrames don't share the same index (potentially MultiIndex).</p> <p>Does pandas offer a way to assert this when combining such datasets?</p> <p>For example:</p> <pre class="lang-py prettyprint-override"><cod...
<python><pandas><dataframe>
2023-03-28 19:06:10
1
6,130
william_grisaitis
75,870,150
3,507,127
Convert Pandas DataFrame to nested dictionary where key value pairs are columns
<p>I have a pandas dataframe with 3 columns. Say it looks like this:</p> <pre><code>test_df = pd.DataFrame({ 'key1': [1, 1, 1, 1, 2, 2, 2], 'key2': ['a', 'b', 'c', 'd', 'e', 'f', 'g'], 'value': ['a-mapped', 'b-mapped', 'c-mapped', 'd-mapped', 'e-mapped', 'f-mapped', 'g-mapped'] }) </code></pre> <pre><code>&...
<python><pandas>
2023-03-28 19:05:42
4
9,006
Vincent
75,869,943
3,529,833
How to run a local AWS Lambda container as part of a docker compose?
<p>I'm having a huge headache figuring this out, I just want to emulate a local AWS Lambda service to easily test integration without writing custom clients and such</p> <p>I have this monorepo:</p> <pre><code> | lambda-service-emulator/ ---| app.py ---| Dockerfile | lambda-function/ ---| Dockerfile | docker-compo...
<python><amazon-web-services><docker><aws-lambda>
2023-03-28 18:42:28
0
3,221
Mojimi
75,869,900
967,526
pants with isort thinks my python modules are third party
<p>I have a pants project that I've modified from the <a href="https://github.com/pantsbuild/example-python" rel="nofollow noreferrer">example repo</a> so that the source code resides under <code>project1/src</code>:</p> <pre><code>├── BUILD ├── LICENSE ├── README.md ├── mypy.ini ├── pants.ci.toml ├── pants.toml ├── pr...
<python><isort><pants>
2023-03-28 18:38:38
1
3,498
chadrik
75,869,700
9,461,736
VS code has the wrong ipython directory
<p>My ipython version on mac terminal and on VS code terminal are different. I have different packages installed in both. And this is confirmed when I do which python, I get:</p> <p>❯ which ipython</p> <pre><code>/usr/local/bin/ipython </code></pre> <p>and</p> <p>❯ which ipython</p> <pre><code>/Users/myname/opt/anacon...
<python><visual-studio-code>
2023-03-28 18:13:57
1
519
stracc
75,869,605
2,445,273
Python requests result doesn't match the website because of JavaScript
<p>I'm trying to scrape links of products from a webpage (url below). The page uses JavaScript. I tried different libraries, but the links don't show up in the results (the links have the format <code>*/product/*</code>, as you can see by hovering over product links when you open the below url).</p> <pre class="lang-py...
<javascript><python><web-scraping><python-requests><python-requests-html>
2023-03-28 18:02:57
1
1,720
LoMaPh
75,869,542
11,001,493
Can't get file size because it apparently doesn't exist
<p>I'm creating a code to get the size of all files inside folders from a directory.</p> <pre><code> import os rootdir = &quot;Z:&quot; # Identifying all files and sizes, and putting them inside lists files = [] sizes = [] for dirpath, dirnames, filenames in os.walk(rootdir): for f in f...
<python><path><size>
2023-03-28 17:55:19
0
702
user026
75,869,481
350,143
remove stripes / vertical streaks in remote sensing images
<p>I have a remote sensing photo that has bright non continuous vertical streaks or stripes as in the pic below, my question is there a way to remove them using python and opencv or any other ip library? <a href="https://i.sstatic.net/iamHP.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/iamHP.jpg" alt="...
<python><opencv><image-processing><image-enhancement>
2023-03-28 17:48:16
6
931
Atheer
75,869,474
211,983
How to determine if a datetime object overlaps with an ical string?
<p>Suppose I have an ical string:</p> <pre><code>cal_str = &quot;&quot;&quot; BEGIN:VEVENT DTSTART;TZID=America/New_York:20211019T000000 DTEND;TZID=America/New_York:20211019T235959 RRULE:FREQ=WEEKLY;BYDAY=SU,MO,TU,WE,TH,FR,SA X-STATE:convenience END:VEVENT &quot;&quot;&quot; </code></pre> <p>And a <code>datetime</code>...
<python><icalendar>
2023-03-28 17:47:31
2
9,624
tipu
75,869,291
1,258,059
Cache errors using Spotify API in Python program
<p>I am running into a problem with my Python script. The code executes, but after it displays a caching error:</p> <pre class="lang-none prettyprint-override"><code>Couldn't read cache at: .cache Couldn't write token to cache at: .cache Couldn't read cache at: .cache Couldn't write token to cache at: .cache Couldn't r...
<python>
2023-03-28 17:25:20
2
595
joshmrodg
75,869,145
10,311,694
Unit testing - how to split cases into multiple files that all share the same setUp/tearDown?
<p>I have one test suite in a single file that is getting very long. It doesn't make sense to split the test cases into different classes because they all test different steps of the same user flow. This is also why they share the same <code>setUp</code>/<code>tearDown</code> methods and share class variables. Certain ...
<python><unit-testing><python-unittest>
2023-03-28 17:09:28
0
451
Kevin2566
75,869,041
1,803,648
how to sleep in twisted LoopingCall
<p>I have a <code>work()</code> method that calls functions that may invoke <code>time.sleep</code>. This clearly goes against recommended twisted usage.</p> <p>Suppose one could replace LoopingCall with <code>threads.deferToThread()</code> and loop manually in our worker, but are there alternative ways to accomplish t...
<python><twisted><twisted.internet>
2023-03-28 16:57:59
1
598
laur
75,868,981
16,739,739
Pythonic way to setup fixture for test
<p>I have a fixture with <code>scope=&quot;session&quot;</code>, as it is webserver which should be started and finished only once for all tests. But I want to clear cache before running a new test, so I made fixture that gets webserver and cleans cache:</p> <pre><code>import pytest class Webserver: def __init__(...
<python><pytest><fixtures>
2023-03-28 16:52:57
1
693
mouse_00
75,868,847
21,420,742
How to modify rows with conditions? In Python
<p>I have a dataset of employee history containing information on job, manager, and etc. What I am trying to see is if a manager has taken over for another in their absence. If that happens have the current manager filing in add a <strong>(Sub)</strong> next to their name.</p> <p>This is the output I have:</p> <pre><co...
<python><python-3.x><pandas><dataframe><numpy>
2023-03-28 16:36:11
2
473
Coding_Nubie
75,868,823
17,101,330
Why pyqtgraph legend text cannot contain special characters like: '>', '<'
<p>I am plotting data with pyqtgraph inside a PySide6 Application. Anyways, the problem is that the text gets cut off if a name contains a special character like '&lt;' or '&gt;'.</p> <p>Here is a minimal example:</p> <pre><code>from PySide6 import QtCore, QtWidgets import pyqtgraph as pg plt = pg.plot() plt.addLegend...
<python><pyqtgraph><pyside6>
2023-03-28 16:34:15
2
530
jamesB
75,868,813
2,074,794
SQLite generate series is missing when calling with python
<p>The following statement works fine when used directly in sqlite:</p> <p><code>SELECT * FROM generate_series(1, 10);</code></p> <p>But when I try to use it via python sqlite3, it fails:</p> <pre><code>import sqlite3 c = sqlite3.connect(&quot;:memory:&quot;) c.execute(&quot;SELECT * FROM generate_series(1, 10)&quot;)...
<python><sqlite>
2023-03-28 16:32:48
0
2,156
kaveh
75,868,744
1,128,648
Python script is reporting Google sheet api Quota exceed error
<p>I have below function to update my google sheet every 3 seconds.</p> <pre><code>def update_gsheet(): global ce_trade_status, pe_trade_status while ce_trade_status != 'completed' or pe_trade_status != 'completed': try: batch_update_values = [ {&quot;range&quot;: &quot;A2&qu...
<python><google-cloud-platform><google-api><google-sheets-api>
2023-03-28 16:24:44
1
1,746
acr
75,868,739
453,673
What is the Python colon followed by a greater than sign meant for? :>
<p>I came across this code in PyTorch's example code:</p> <pre><code>if batch % 100 == 0: loss, current = loss.item(), (batch + 1) * len(X) print(f&quot;loss: {loss:&gt;7f} [{current:&gt;5d}/{size:&gt;5d}]&quot;) </code></pre> <p>and</p> <pre><code>print(f&quot;Test Error: \n Accuracy: {(100*correct):&gt;0.1...
<python><syntax>
2023-03-28 16:24:07
0
20,826
Nav
75,868,668
13,896,667
Pymssql - insert large string - DBPROCESS is dead or not enabled
<p>I'm trying to insert a single row to a table that has a <code>nvarchar(max)</code> column (say response) using python's <code>pymssql</code> library.</p> <p>The other columns are straightforward - one nvarchar(10) column, two nvarchar(30) columns, two date columns and one bigint column</p> <p>I don't really have con...
<python><sql-server><limit><pymssql>
2023-03-28 16:17:43
0
342
wkgrcdsam
75,868,632
15,724,084
python selenium timeout exception does not pass compiling
<p>I have some Selenium WebDRiver code that searches for the &quot;Next&quot; button and if it exists, it clicks it. If not, the script should catch <code>TimeoutException</code> and continue.</p> <p>Code:</p> <pre><code>from selenium.common.exceptions import TimeoutException def clicking_next_page(): btn_next_to_...
<python><selenium-webdriver><timeoutexception>
2023-03-28 16:13:45
1
741
xlmaster
75,868,523
361,530
Unwanted tkinter trace event
<p>I just discovered a nasty behavior in tkinter trace events. When the user selects a character or characters to change, on the first keystroke two events occur: the first is the deleting of the selected characters and the second is the insertion of the first character typed by the user. The problem arises on an En...
<python><tkinter><trace>
2023-03-28 16:01:54
1
389
RadlyEel
75,868,509
12,711,133
Data format being changed when saving .xls file with Python
<p>TLDR I have dates that show in this format '44992', which I can't recognise - is there a way to turn that into another format in JS?</p> <p>I have a Python script that pulls a spreadsheet from a website. In that original spreadsheet, there's a column with dates in this format: <code>07/03/2023 00:00:00</code></p> <p...
<javascript><python>
2023-03-28 16:00:09
1
412
Gordon Maloney
75,868,334
835,523
How to compare 2 files in python, ignoring whitespace
<p>How can I compare two files to check if they have the same contents, ignoring whitespace, in Python?</p> <p>This is something I need to do programmatically. I have a pytest test and while it passes locally on my windows computer it fails in our linux build environment and I believe whitespace is to blame.</p> <p>I t...
<python>
2023-03-28 15:41:30
1
4,741
Steve
75,868,233
10,462,461
Tuple unpacking and np.max() giving unexpected values
<p>I have a dataset that I am trying to filter and apply an adjustment value using tuples.</p> <pre><code>df = pd.DataFrame({ 'loannum': ['1', '2', '3', '4'], 'or_dep': [250000, 650000, 1000000, 300000] }) loan2adj = [('1', 50000), ('3', 250000), ('2', 100000)] </code></pre> <p>My expected output looks like th...
<python><pandas><numpy><tuples>
2023-03-28 15:30:16
1
340
gernworm
75,868,186
6,346,482
Pandas: Alter a column by condition using other columns
<p>I have this dataframe here (sorry for the bad example)</p> <pre><code>import pandas as pd import random df = pd.DataFrame({ &quot;Alpha&quot;: [&quot;A&quot;, &quot;A&quot;, &quot;A&quot;, &quot;A&quot;, &quot;B&quot;, &quot;B&quot;, &quot;B&quot;, &quot;B&quot;], &quot;Beta&quot;: [&quot;C&quot;, &quot;D&qu...
<python><pandas>
2023-03-28 15:25:41
2
804
Hemmelig
75,868,166
10,266,106
Speed Up Numpy Process Across Multiple Arrays in Parallel
<p>I have constructed a script to find the 8 nearest indices at the current index in a loop; in essence a moving window algorithm. The parallel component entails doing this across multiple 2-D arrays, which may vary in total amount but will always have the same dimensions (say 2800i x 1200j). I've tested this script be...
<python><numpy><multiprocessing><numpy-ndarray>
2023-03-28 15:23:36
1
431
TornadoEric
75,868,129
12,760,550
Create a column ranking order of records by date
<p>Imagine I have the following dataframe with employees, their contract type (values could be Employee, Contractor and Agency). Also, one person can have more than 1 contract as you could see in the dataframe example below:</p> <pre><code>ID Name Contract Date 10000 John Employee 2021-01-01 10000 ...
<python><pandas><group-by><lines-of-code>
2023-03-28 15:20:14
1
619
Paulo Cortez
75,867,923
3,073,612
MongoDB $indexOfArray not working for a nested object inside an array
<p>I have a document with the following data</p> <pre><code>{ &quot;_id&quot;: &quot;640311ab0469a9c4eaf3d2bd&quot;, &quot;id&quot;: 4051, &quot;email&quot;: &quot;manoj123@gmail.com&quot;, &quot;password&quot;: &quot;SomeNew SecurePassword&quot;, &quot;about&quot;: null, &quot;token&quot;: &quo...
<python><mongodb><pymongo>
2023-03-28 15:02:10
1
2,756
Sibidharan
75,867,922
13,158,157
pandas pivot table: dropna does not create new column
<p>I have a data frame with two columns: df._merge and df.A. df.A is an object column with a few values and NA.</p> <p>When trying to output pairs and their count with <code>pivot_table</code> I am missing the na values, and using <code>dropna=False</code> in <code>pivot_table</code> does not return them.</p> <pre><cod...
<python><pandas><pivot-table>
2023-03-28 15:02:02
1
525
euh
75,867,791
11,922,765
Python Download A list of URL linked ZIP files
<p>I have a list of URLs to download data. I am doing this on Kaggle. I want to know how to download this data, save to kaggle or local machine. The goal is, download this data onto Python and combine them into a single CSV file and download this big file. Presently each URL corresponds to one year data.</p> <p>Ref: <a...
<python><url><python-requests><io><zip>
2023-03-28 14:49:48
1
4,702
Mainland
75,867,783
15,915,737
How trigger dbt cloud job on free version
<p>I wan't to trigger dbt cloud job with API request from a python script, however the API is not accessible for unpaid version as the error suggest : <code>{&quot;status&quot;: {&quot;code&quot;: 401, &quot;is_success&quot;: false, &quot;user_message&quot;: &quot;The API is not accessible to unpaid accounts.&quot;, &q...
<python><triggers><jobs><dbt-cloud>
2023-03-28 14:48:51
1
418
user15915737
75,867,644
112,976
How to return Pydantic object with a specific http response code in FastAPI?
<p>I have an endpoint which returns a Pydantic object. However, I would like a response code other than 200 in some cases (for example if my service in not healthy). How can I achieve that with FastAPI?</p> <pre><code>class ServiceHealth(BaseModel): http_ok: bool = True database_ok: bool = False def is_eve...
<python><http><fastapi><pydantic>
2023-03-28 14:34:59
2
22,768
poiuytrez
75,867,636
11,452,928
How to get value of jaxlib.xla_extension.ArrayImpl
<p>Using <code>type(z1[0])</code> I get <code>jaxlib.xla_extension.ArrayImpl</code>. Printing <code>z1[0]</code> I get <code>Array(0.71530414, dtype=float32)</code>. How can I get the actual number <code>0.71530414</code>?</p> <p>I tried <code>z1[0][0]</code> because <code>z1[0]</code> is a kind of array with a single ...
<python><arrays><jax>
2023-03-28 14:34:18
2
753
fabianod
75,867,580
4,810,328
package data in setup.py
<p>I have some data and config file in the project root folder(same as setup.py) and I want to add them to the wheel build as package data. So my setup.py looks like below:</p> <pre><code>from setuptools import find_packages, setup setup( name=&quot;dbx_test&quot;, packages=find_packages(exclude=[&quot;tests&q...
<python><python-packaging><python-wheel>
2023-03-28 14:30:22
0
711
Tarique
75,867,551
241,552
Bazel: add executable to PATH
<p>I am having trouble with installing python in my Bazel build. I tried following different approaches, starting with the official bazel_rules documentation, but I get the error <code>/usr/bin/env: ‘python3’: No such file or directory</code>. I have tried several approaches with downloading the python installation as ...
<python><bazel>
2023-03-28 14:27:08
1
9,790
Ibolit
75,867,416
3,152,686
Extract substrings from a list of patterns in Python
<p>I have a list of patterns that contains the Page ID of my webpage</p> <pre><code>patterns = [ https://www.my-website.com/articles/$1/show, https://www.my-website.com/groups/$1/articles/$2, https://www.my-website.com/blogs/$1/show, https://www.my-website.com/groups/$1/docum...
<python><string><extract>
2023-03-28 14:13:41
2
564
Vishnukk
75,867,330
5,432,214
Mypy, ignore types for remaining elements
<p>I have a function like this</p> <pre class="lang-py prettyprint-override"><code>def _parse(input_dict: dict) -&gt; Tuple[int, str, ???]: entity = 3 _id = &quot;test&quot; return ( entity, _id, *super()._parse(input_dict), ) </code></pre> <p>I know the types of the first two r...
<python><type-hinting><mypy>
2023-03-28 14:04:40
0
1,310
HitLuca
75,867,274
10,437,110
Value of a column at time t is subracted by running mean of the past 1000 values
<p>I have a dataframe called <code>df</code>.</p> <p>It has a column name <code>x</code>.</p> <p>I want to update the <code>df['x']</code> such that value at index i is changed to value at index i - mean of previous 1000 values.</p> <p>How to achieve that in Python?</p>
<python><python-3.x><pandas><dataframe>
2023-03-28 13:59:25
1
397
Ash
75,867,199
15,756,325
Why is mypy not inferring Django CharField choices as type with django-stubs?
<p>I have a Django model with a field that is a <code>models.CharField</code> with choices:</p> <pre class="lang-py prettyprint-override"><code>from django.db import models class MyChoice(models.TextChoices): FOO = &quot;foo&quot;, _(&quot;foo&quot;) BAR = &quot;bar&quot;, _(&quot;bar&quot;) BAZ = &quot;ba...
<python><django><django-models><mypy><django-stubs>
2023-03-28 13:53:16
0
409
tinom9
75,867,074
119,253
testing.postgres failing with "Command not found: initdb"
<p>I'm trying to run some unit tests on a python function that updates a database. I'm attempting to use testing.postgres to create a local database upon which to carry out the tests. I have the following code for my unit test:</p> <pre><code>from unittest import TestCase import testing.postgresql import psycopg2 impor...
<python><postgresql><python-unittest>
2023-03-28 13:42:25
0
2,936
Columbo
75,867,049
14,230,633
LGBM's best_iteration_ is None when using early early_stopping callback even though early stopping occurs
<p>If I fit a model with</p> <pre><code>gbm = lgb.LGBMRegressor(learning_rate=0.01, n_estimators=250) gbm.fit( X_train, y_train, eval_set=[(X_test, y_test)], eval_metric='l2', callbacks=[lgb.early_stopping(3)], verbose=-1 ) </code></pre> <p>the output is</p> <pre><code>Early stopping, best itera...
<python><machine-learning><lightgbm>
2023-03-28 13:40:10
1
567
dfried
75,866,753
2,171,348
how to get variable starting with double-underscore displayed in eclipse/pydev debug view
<p>In the eclipse/pydev debug view, if a dict object has a key starting with double-underscore, like { &quot;__my_key&quot;: , ...}, that key won't show up in the variables view in debug mode; the other keys all show up as expected. Is there a setting to change to get the double-underscore key displayed in debug mode?<...
<python><eclipse><debugging><pydev>
2023-03-28 13:14:41
1
481
H.Sheng
75,866,706
3,241,257
Is there an easier way to allow all http methods in Sanic framework?
<p>I'm developing a proxy server by using Sanic. (The reason why I chose this framework is that it is so fast and it uses asynchronous event loop.)</p> <p>So I want to catch all requests to my Sanic server and do some post-processings.</p> <pre><code>@app.route(&quot;/&lt;path:path&gt;&quot;, methods = []) # Here is th...
<python><http><sanic>
2023-03-28 13:11:01
2
908
jeongmin.cha
75,866,487
626,664
How to find similarity between two vectors?
<p>I have two embedding vectors A1 and B1, of size 32 (it could be 64, and so on).</p> <pre><code>A = torch.rand(32) A1 = torch.unsqueeze(A, dim = 1) A1 B = torch.rand(32) B1 = torch.unsqueeze(B, dim = 1) B1 </code></pre> <p>Now, I want to be able to find how similar are they, based on every say 4, 8, 16 elements. So ...
<python><vector><pytorch><similarity>
2023-03-28 12:50:39
2
1,559
Droid-Bird
75,865,962
2,772,805
color meanings when shapely polygons are displayed
<p>Is there a signification for colors (red, green) when you display a shapely polygon object ?</p> <p><a href="https://i.sstatic.net/zUjB5.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/zUjB5.png" alt="enter image description here" /></a></p>
<python><shapely>
2023-03-28 11:57:15
1
429
PBrockmann
75,865,819
9,758,352
How to install python cryptography 38.0.4 without pip on Ubuntu
<p>My pip has corrupted after trying to install Apache Airflow. Every time I am trying to use it I am getting the following message</p> <pre><code>Traceback (most recent call last): File &quot;/usr/bin/pip&quot;, line 11, in &lt;module&gt; load_entry_point('pip==20.0.2', 'console_scripts', 'pip')() File &quot;/...
<python><python-3.x><ubuntu><pip><pypi>
2023-03-28 11:43:38
1
457
BillTheKid
75,865,732
10,291,291
Python Subprocess cannot find module
<p>Been stuck on this for a while and can't quite work it out.</p> <h1>Setup</h1> <h2>Folder Structure</h2> <pre><code>- Home - folder1 + script1.py + script2.py - folder2 + script3.py </code></pre> <h2>Scripts</h2> <h3>Script1</h3> <pre><code>import logging logger=........ import os cwd = os.getcwd() ...
<python><subprocess><python-import><python-venv><python-packaging>
2023-03-28 11:34:17
1
2,924
Quixotic22
75,865,619
5,024,631
Convert any binary combination to boolean
<p>I have a function that returns numpy arrays which consist of a numbers. These numbers are always two different numbers, e.g.:</p> <pre><code>np.array([0,3,3,0,0,0,3]) np.array([1,4,1,1,1,4,4]) np.array([0,3,3,0,0,0,3]) </code></pre> <p>How could I convert these binary combinations of numbers to boolean, i.e. <code>n...
<python><numpy><boolean>
2023-03-28 11:23:11
4
2,783
pd441
75,865,524
4,428,377
Error "Check whether your GraphDef-interpreting binary is up to date with your GraphDef-generating binary." when running TFLite model in Android
<p>I built a <strong>keras-ocr tflite</strong> model using <a href="https://github.com/tulasiram58827/ocr_tflite" rel="nofollow noreferrer">ocr_tflite</a>.</p> <p>Following are the tensorflow library versions used on mac osx m1 -</p> <pre><code>tensorflow-datasets 4.8.3 tensorflow-deps 2.10.0 tensorflow...
<python><android><firebase><tensorflow><tflite>
2023-03-28 11:12:44
1
1,668
aquaman
75,865,420
11,546,773
Polars apply return only null after second row
<p>I'm trying to apply a custom function to each row of the dataframe. The function itself returns a dataframe with more columns and rows. To obtain one big dataframe I use <code>explode()</code> in the end.</p> <p>The first <code>apply()</code> is performed succesfully. But after that it only returns <code>null</code>...
<python><dataframe><python-polars>
2023-03-28 11:02:36
2
388
Sam
75,864,929
7,123,933
Can't open lib 'ODBC Driver 18 for SQL Server in Docker image
<p>I created image in Docker with Dockerfile:</p> <pre><code># Write your dockerfile code here # Use an official Python runtime as a base image FROM python:3.8-slim-buster USER root # Upgrade version of pip to avoid warning message RUN pip install --upgrade pip RUN apt-get update &amp;&amp; apt-get install unixodbc-de...
<python><docker>
2023-03-28 10:12:15
0
359
Lukasz
75,864,903
17,639,970
filtering out node_id based on their tags?
<p>I'd like to work with a portion of nodes od an *.osm file. It's looks like this:</p> <pre><code> &lt;node id=&quot;614006085&quot; visible=&quot;true&quot; version=&quot;5&quot; changeset=&quot;87511557&quot; timestamp=&quot;2020-07-03T16:17:13Z&quot; user=&quot;clay_c&quot; uid=&quot;119881&quot; lat=&quot;40.71273...
<python><julia><openstreetmap>
2023-03-28 10:09:33
0
301
Rainbow
75,864,866
5,197,329
OmegaConf - how to delete a single parameter
<p>I have a code that looks something like this:</p> <pre><code>def generate_constraints(c): if c.name == 'multibodypendulum': con_fnc = MultiBodyPendulum(**c) </code></pre> <p>where c is an OmegaConf object containing a bunch of parameters. Now I would like to pass all the parameters in c except the name t...
<python><fb-hydra><omegaconf>
2023-03-28 10:05:59
2
546
Tue
75,864,807
1,175,081
Mypy complaining about [no-any-return] rule being violated for obvious boolean expression
<p>The following code throws a mypy error:</p> <pre><code>from typing import Dict, Any def asd(x: Dict[str, Any]) -&gt; bool: return x['a'] == 1 asd({&quot;x&quot;: 2}) </code></pre> <p>IMO it doesn't matter what is passed as a dict. <code>x['a'] == 1</code> should always be a boolean. But mypy complains with:</p...
<python><mypy><python-typing>
2023-03-28 10:00:04
2
14,967
David Schumann
75,864,772
973,936
Failed to install Feast in Python 3.7
<p>I am trying to install feature store library named feast inside Python 3.7.</p> <pre><code>~$ pip install feast==0.25.2 </code></pre> <p>Running this command gives us the following error</p> <pre><code>Collecting feast==0.25.2 Using cached feast-0.25.2.tar.gz (3.5 MB) Installing build dependencies ... done Get...
<python><feast>
2023-03-28 09:56:36
1
1,152
habibalsaki
75,864,755
9,510,800
How to append all possible pairings as a column in pandas
<p>I have a dataframe like below:</p> <pre><code>Class Value1 Value2 A 2 1 B 3 3 C 4 5 </code></pre> <p>I wanted to generate all possible pairings and my output dataframe looks like below</p> <pre><code>Class Value1 Value2 A_Value1 A_Value2 B_Value1 B_Value2 C_Value1...
<python><pandas><numpy>
2023-03-28 09:55:00
2
874
python_interest
75,864,690
10,134,422
Building airflow in docker compose with pycurl in requirements gets Permission denied: 'curl-config'
<p><strong>The problem</strong></p> <p>When building a docker image for apache airflow, build fails at <em>RUN pip install -r requirements.txt</em> (when installing pycurl package) with:</p> <pre><code>Permission denied: 'curl-config' </code></pre> <p><strong>What I think the problem is</strong></p> <p>I think this pro...
<python><docker><docker-compose><airflow><pycurl>
2023-03-28 09:48:39
1
460
Sanchez333
75,864,676
1,367,705
How to print list of objects grouped by itertools' groupby?
<p>I have a class with some fields. I created a list of objects of this class and now I want to group the list by one of the fields inside the objects. It <em>almost</em> works, but unfortunately it shows me only one Dog, but the result for this data should be different.</p> <p>The code:</p> <pre><code>from collections...
<python><group-by><itertools-groupby>
2023-03-28 09:47:10
1
2,620
mazix