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
74,815,268
11,946,045
How to find out the IP range for a certain country code in python?
<p>Is there a way to figure out the IP ranges for a certain country code without using <a href="https://pypi.org/project/maxminddb/" rel="nofollow noreferrer">MaxMind</a> or <a href="https://www.ip2location.com/development-libraries/ip2location/python" rel="nofollow noreferrer">IP2Location</a> where in both they provid...
<python><geolocation><maxmind><ip2location>
2022-12-15 17:15:53
1
814
Weed Cookie
74,815,173
19,069,334
FastAPI API Versioning - specifying deprecated version in Header
<p>I am using a <code>Header</code> named <code>Accept-Version</code> to handle API versioning in my FastAPI project at the function level. Following <a href="https://fastapi.tiangolo.com/tutorial/path-params/#predefined-values" rel="nofollow noreferrer">fastapi documentation</a>, a sub-class that inherits from <code>s...
<python><enums><fastapi><api-versioning>
2022-12-15 17:06:45
0
1,176
wavingtide
74,815,168
2,659,499
Method parameter type refering to the class it's defined in is causing AttributeError partially initialized module
<p>I have a dataclass in <code>extensions</code> &gt; <code>__init__.py</code> like:</p> <pre class="lang-py prettyprint-override"><code>@dataclass class Range: start: date end: date def overlap(self, other: Range) -&gt; bool: # method body removed </code></pre> <p>My IDE is complaining about the me...
<python><python-typing>
2022-12-15 17:06:30
1
1,975
Vahid
74,815,128
136,598
Separate or merged indices for index.yaml with GAE
<p>I do queries like this with Python GAE:</p> <pre><code>a1 = Activity.query().filter(Activity.first=='foo').order(-Activity.date) a2 = Activity.query().filter(Activity.second=='bar').order(-Activity.date) </code></pre> <p>Am I better off with two separate indices:</p> <pre><code>indexes: - kind: Activity propertie...
<python><google-app-engine><indexing><google-cloud-datastore>
2022-12-15 17:04:07
1
16,643
minou
74,815,119
2,050,067
Unique variable naming patterns in deep learning code
<p>Need help on understanding some naming patterns I see so far.</p> <p>Reading <a href="https://huggingface.co/blog/annotated-diffusion" rel="nofollow noreferrer">The Annotated Diffusion Model</a> source code, notice the camel case of some of the functions:</p> <pre><code> def Upsample(dim, dim_out=None): r...
<python><pytorch><naming-conventions>
2022-12-15 17:03:21
0
2,884
neurite
74,815,086
1,473,517
How to find the smallest threshold from one list to fit another list
<p>I have two lists of marks for the same set of students. For example:</p> <pre><code>A = [22, 2, 88, 3, 93, 84] B = [66, 0, 6, 33, 99, 45] </code></pre> <p>If I accept only students above a threshold according to list A then I can look up their marks in list B. For example, if I only accept students with at least a m...
<python><algorithm>
2022-12-15 17:00:38
2
21,513
Simd
74,814,895
7,171,984
Create new column based on condition from one column and the value from another column in pandas
<p>I have a DF with time given as hours, minutes or milliseconds. The time column has the type float and the time_unit column indicate if it is given as hour, minute or ms.</p> <p>I want to create a a new column that calculates the amount of seconds. Thus, I need a function that first checks what time_unit it is, then ...
<python><pandas>
2022-12-15 16:46:21
2
305
Energizer1
74,814,866
2,049,273
gzip decoding error when using Python requests but not curl
<p>I'm making a POST request of some JSON to an endpoint (Vertex AI Endpoint) and the request works when I make it via curl:</p> <pre class="lang-bash prettyprint-override"><code>curl \ -X POST \ -H &quot;Authorization: Bearer $TOKEN&quot; \ -H &quot;Content-Type: application/json&quot; \ $API_URL \ -d &quot;@input.jso...
<python><python-requests>
2022-12-15 16:44:10
0
1,271
swigganicks
74,814,799
3,087,409
Convert pandas dataframe to LaTeX without printing index
<p>I'm trying to print a dataframe as a LaTeX table, but I seem to have two bad options. (Note I'm using <code>io.formats.style.Styler.to_latex</code> rather than <code>dataframe.to_latex</code> since there's a deprecation warning on the former. But <code>dataframe.to_latex</code> doesn't solve my issue anyway, it just...
<python><pandas><latex>
2022-12-15 16:37:15
2
2,811
thosphor
74,814,697
2,897,989
LabelEncoding the target variable improves model massively vs. one-hot-encoding the same
<p>I'm using a Random Forest classifier on text data transformed into tf-idf (both the features and the target variable are text, the target variable being company names). Since using a LabelEncoder adds ordinality where there is none, I first tried to one-hot encode the companies (the full company name would be one co...
<python><machine-learning><random-forest>
2022-12-15 16:28:34
1
7,601
lte__
74,814,680
1,230,694
Merge data frame onto another but start from a certain row
<p>I have a large data frame which has reading data in it, and I want to merge another <code>dataframe</code> of the same structure but a subset of columns and far fewer rows.</p> <p>The idea is that the large <code>dataframe</code> represents almost all of what I want but I will have a set of readings that might start...
<python><pandas><dataframe>
2022-12-15 16:27:08
2
3,899
berimbolo
74,814,676
1,700,890
My python module does not see other modules
<p>I have a folder with 2 files.</p> <pre><code>import_test.py main.py. </code></pre> <p>Here is content of import_test.py:</p> <pre><code>def some_function(): df = pd.DataFrame({'col_1': [1,2,3], 'col_2': [1,2,3]}) return df </code></pre> <p>Here is content of main.py:</p> <pre>...
<python><import><module>
2022-12-15 16:26:42
2
7,802
user1700890
74,814,642
1,649,095
Predict with keras triggers OOM error message
<p>I fit a keras model without any problem. But when I try to predict a test sample, it triggers an OOM error message:</p> <blockquote> <p>InternalError: Failed copying input tensor from /job:localhost/replica:0/task:0/device:CPU:0 to /job:localhost/replica:0/task:0/device:GPU:0 in order to run _EagerConst: Dst tensor ...
<python><tensorflow><keras>
2022-12-15 16:24:23
0
2,703
Mark Morrisson
74,814,513
6,461,882
Copy python string characters to array.array (to be accessed later from C++)?
<p>How can one copy python string characters to <code>array.array</code>?</p> <pre class="lang-py prettyprint-override"><code>from array import array b = array('b', [0]*30) s = 'abc' # What should one do here to copy integer representation of 's' characters to 'b' ? </code></pre> <p>The integer representation of <code...
<python><c++><arrays><string><data-conversion>
2022-12-15 16:13:38
2
2,855
S.V
74,814,445
10,866,873
Tkinter <Enter> bind looping forever
<p>I am tring to make a selectable clock face for events. I have my Canvas object and created a bunch of circles with text inside them.</p> <p>I am wanting to invert the colour of the circle and text when the mouse is hovering over.</p> <p>The issues are:</p> <ul> <li>Leave detectected when entering text inside circle....
<python><tkinter><tkinter-canvas>
2022-12-15 16:08:50
1
426
Scott Paterson
74,814,437
13,142,245
JAX: Passing a dictionary rather than arg nums to identify variables for autodifferentiation
<p>I want to use JAX as a vehicle for gradient descent; however, I have a moderately large number of parameters and would prefer to pass them as a dictionary <code>f(func, dict)</code> rather than <code>f(func, x1, ...xn)</code>.</p> <p>So instead of</p> <pre class="lang-py prettyprint-override"><code># https://www.kag...
<python><gradient-descent><jax>
2022-12-15 16:07:59
1
1,238
jbuddy_13
74,814,420
7,585,973
How to cut/sampling by csv filesize on pyspark
<p>I am <code>df</code> is pyspark dataframe, I need to cut by size on production environment data, for example 100 MB</p> <p>Here's the script I usualy use (for not cutting scenario)</p> <p><code>df.coalesce(1).write.csv(output_path+&quot;/folder_name&quot;, header=True, mode='overwrite')</code></p> <p>How to cut some...
<python><dataframe><pyspark>
2022-12-15 16:06:21
0
7,445
Nabih Bawazir
74,814,386
9,182,743
How to combine rows in groupby with several conditions?
<p>I want to combine rows in pandas df with the following logic:</p> <ul> <li>dataframe is grouped by users</li> <li>rows are ordered by start_at_min</li> <li>rows are combiend when:</li> </ul> <p>Case A: if start_at_min&lt;=200:</p> <ul> <li>row1[stop_at_min] - row2[start_at_min] &lt; 5</li> <li>(eg: 101 -100 = 1 -&gt...
<python><pandas><dataframe>
2022-12-15 16:04:15
1
1,168
Leo
74,814,336
1,142,881
How to catch a Python exception from VBA?
<p>I’m using xlwings and calling python from VBA using the <code>RunPython</code> function. However exceptions such as <code>ValueError </code> are not caught by VBA in the standard way, for example:</p> <pre><code>Sub Test() On Error Goto PythonError RunPython(“…”) Exit Sub PythonEror: ‘Do something sensib...
<python><excel><vba><xlwings>
2022-12-15 15:59:24
0
14,469
SkyWalker
74,814,262
6,131,259
Pandas change values based on previous value in same column
<p>I have the following dataframe:</p> <p><a href="https://i.sstatic.net/gmAd2.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/gmAd2.png" alt="enter image description here" /></a></p> <pre><code>import pandas as pd import datetime df = pd.DataFrame({'ID': [1, 2, 1, 1], 'Date' : ...
<python><pandas><dataframe>
2022-12-15 15:54:22
1
331
FriendlyGuy
74,814,185
3,834,837
OSMnx: combine several multidirectional graphs
<p>I used OSMnx to retrieve the road networks in France. For execution time constraints, I retrieved the data department by department: While trying to retrieve the road network of all of France at once, my script ran for 4 days without results. Therefore, I retrieve the data department by department. I stored the data...
<python><osmnx>
2022-12-15 15:49:03
1
410
Mouaici_Med
74,814,057
7,454,177
How to override/ bypass a mock decorator in Python?
<p>Most of our external services are mocked for testing. Now I built test cases for the external services (Stripe in the example) and I would like to use the actual methods for only those tests. I could just decorate all the other tests, but those are a lot of tests and the likelihood of errors high. Also the mocks are...
<python><unit-testing><mocking>
2022-12-15 15:40:04
0
2,126
creyD
74,813,906
4,542,117
scipy.interpolate.griddata not working as expected
<p>I have a large dataset of temperatures throughout the US on a grid of 3km-3km:</p> <p><a href="https://i.sstatic.net/hp0lb.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/hp0lb.png" alt="Temps of the USA" /></a></p> <p>The temps (<code>temperature_data</code>), latitudes and longitudes of each grid po...
<python><scipy><grid><interpolation>
2022-12-15 15:28:58
0
374
Miss_Orchid
74,813,871
13,517,174
Passing a shape to numpy.reshape in a numba njit environment fails, how can I create a suitable iterable for the target shape?
<p>I have a function that takes in an array, performs an arbitrary calculation and returns a new shape in which it can be broadcasted. I would like to use this function in a <code>numba.njit</code> environment:</p> <pre><code>import numpy as np import numba as nb @nb.njit def generate_target_shape(my_array): ### s...
<python><numpy><numba>
2022-12-15 15:26:15
1
453
Yes
74,813,685
5,678,057
Pandas : 'to_datetime' function not consistent with dates
<p>When I read a date say <code>'01/12/2020'</code>, which is in the format <code>dd/mm/yyyy</code>, with <code>pd.to_datetime()</code>, it detects the month as <code>01</code>.</p> <pre><code>pd.to_datetime('01/12/2020').month &gt;&gt; 1 </code></pre> <p>But this behavior is not consistent.</p> <p>When we create a da...
<python><pandas><date>
2022-12-15 15:13:28
1
389
Salih
74,813,635
1,780,761
openCV - Generating disparity map from stereo images
<p>I calibrated my cameras and took a picture with each. Have rectified the images, and saved them. these are the images:</p> <p><a href="https://i.sstatic.net/eICjp.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/eICjp.jpg" alt="enter image description here" /></a> <a href="https://i.sstatic.net/Wu7xW.j...
<python><opencv><stereo-3d><disparity-mapping>
2022-12-15 15:09:52
0
4,211
sharkyenergy
74,813,316
7,713,770
how to render values from multiple methods in table format in template django
<p>I have a django app.</p> <p>And I have two methods:</p> <pre><code>def total_cost_fruit(self): return [3588.20, 5018.75, 3488.16] def total_cost_fruit2(self): return [3588.20, 5018.75, 3488.99] </code></pre> <p>And I try to render them as table.</p> <p>so this is the views.py:</p> <pre><code...
<python><html><django>
2022-12-15 14:46:16
1
3,991
mightycode Newton
74,813,301
219,976
Perform post request using Django rest framework
<p>I've got a Django rest framework APIView:</p> <pre><code>class MyAPIView(views.APIView): def post(self, request): field = request.POST.get(&quot;field&quot;) print(field) return Response({&quot;field&quot;: field}, status=200) </code></pre> <p>I want to call it from separate process using...
<python><django><post><django-rest-framework>
2022-12-15 14:44:53
1
6,657
StuffHappens
74,813,241
4,329,348
PyBullet get names of bodies in world
<p>I load an SDF file which contains multiple robots/objects and I want to get back the &quot;names&quot; of these robots/objects as defined in the SDF. PyBullet when using <code>loadSDF</code> will return a list of unique IDs for these bodies, I want to convert these IDs to names. Is that possible?</p>
<python><pybullet>
2022-12-15 14:39:55
1
1,219
Phrixus
74,813,119
4,893,016
401 Client Error: Unauthorized for url [mozilla-django-oidc - Keycloack]
<p>I'm trying to integrate Django and Keycloack using <code>mozilla-django-oidc</code>, but unfortunately I'm not having much success as I keep getting <code>401 Client Error: Unauthorized for url...</code></p> <p>I created a docker compose that runs Keycloack / KeycloackDB / Django app, like the following</p> <p><code...
<python><django><keycloak><openid-connect>
2022-12-15 14:30:30
1
649
NomadMonad
74,813,117
14,774,959
Split text in column into multiple rows each containing the same number of words
<p>Let's say I have the following dataframe:</p> <pre><code>import pandas as pd data = [ [&quot;a&quot;, &quot;Lorem ipsum dolor sit amet, consectetur adipiscing elit.&quot;], [&quot;b&quot;, &quot;Etiam imperdiet fringilla est, eu tristique risus varius vitae.&quot;] ] df = pd.DataFrame(data, c...
<python><pandas><dataframe>
2022-12-15 14:30:06
1
3,444
ClaudiaR
74,812,929
4,862,845
How to combine properties defined by different parent classes in python?
<p>Suppose we have two classes and each computes a property <code>stuff</code> in a different way. Is is possible to combine their outputs in a method/property of a child class?</p> <p>The following code shows the desired effect (though <code>get_stuff_from</code> needs to be replaced by a proper python construct, if s...
<python><properties><multiple-inheritance>
2022-12-15 14:15:29
4
317
LuizFelippe
74,812,798
19,339,998
PermissionError: [Errno 13] Permission denied: '/usr/local/lib/python3.8/dist-packages/grpc/__init__.py'
<p>I am using grpc in my app.py and I am going to run app.py inside SGX using Gramine, when I run command <code>gramine-sgx ./python app.py&quot;</code> I get error:</p> <pre><code>Traceback (most recent call last): File &quot;app.py&quot;, line 2, in &lt;module&gt; import grpc File &quot;&lt;frozen importlib._...
<python><grpc><sgx>
2022-12-15 14:03:48
1
341
sama
74,812,534
4,757,604
'psycopg2.errors.UndefinedTable: relation "table" does not exist' when makemigrations
<p>I have a django app (Django==4.1.2) and I am trying to migrate from sqlite3 to postgres.</p> <p>I have been following multiples guides on how to do this, and they all do more or less the same and those are the steps I followed:</p> <ol> <li>Get a dumpdata with <code>python manage.py dumpdata &gt; whole.json</code></...
<python><django><postgresql><sqlite><django-migrations>
2022-12-15 13:45:39
0
388
SaFteiNZz
74,812,145
16,424,940
selenium: stale element reference: element is not attached to the page document
<pre><code>from selenium.webdriver import Chrome from selenium.webdriver.common.by import By from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support import expected_conditions as EC import chromedriver_autoinstaller chromedriver_autoinstaller.install() TYPES = ['user', 'verified_aud...
<python><selenium><selenium-webdriver><selenium-chromedriver><staleelementreferenceexception>
2022-12-15 13:15:56
1
1,151
Lun
74,811,931
10,197,418
Interpolate time series data from one df to time axis of another df in Python polars
<p>I have time series data on different time axes in different dataframes. I need to interpolate data from one <code>df</code> to onto the time axis of another df, <code>df_ref</code>. Ex:</p> <pre class="lang-py prettyprint-override"><code>import polars as pl # DataFrame with the reference time axis: df_ref = pl.Data...
<python><dataframe><time-series><interpolation><python-polars>
2022-12-15 12:59:57
2
26,076
FObersteiner
74,811,878
18,749,472
passing django variables as parameters into href url
<p>On my home page i want to have 3 links that will redirect the user to a page <code>('127.0.0.1:8000/person/&lt;str:name&gt;')</code> which will display the name that they clicked. I would like to use a for loop to create links for these names as i plan to have much more than 3 names.</p> <p>I have tested with the tw...
<python><django><url><django-views><django-urls>
2022-12-15 12:54:54
1
639
logan_9997
74,811,660
6,057,371
pandas apply function on column only if condition on another column is met
<p>I have a dataframe:</p> <pre><code>df = A. Cond Val 1. True 0.8 5. False 0.8 2. False 0.6 4. False 0.5 </code></pre> <p>I want to update the value of the columns 'Val' by truncate it in 0.1, only when Cond is False and val is higher than 0.55. So new df will be:</p> <pre><code>df = A. Cond ...
<python><pandas><dataframe>
2022-12-15 12:38:52
3
2,050
Cranjis
74,811,658
2,802,576
Calling Python from C# using Pythonnet throws import error
<p>I have a use case where I want to be able to call a function which is written in Python from my C# code base. When I make a call to this function I want to be able to pass C# types(custom classes) to Python function and for that I was exploring <a href="https://github.com/pythonnet/pythonnet" rel="nofollow noreferre...
<python><c#><python.net>
2022-12-15 12:38:44
1
801
arpymastro
74,811,622
12,635,985
Django Haystack update index only for 1 model
<p>I am currently trying out Django haystack to update data from PostgreSQL to a solr collection.</p> <p>So, I have defined 2 models in <code>search_indexes.py</code>. So, when I run the command <code>python manage.py update_index</code> it indexes the data from both the models defined in <code>search_indexes.py</code>...
<python><django><solr><django-haystack>
2022-12-15 12:35:39
1
1,325
Mahesh
74,811,552
3,937,811
How to calculate the expectation value for a given probability distribution
<p>I am writing a program to determine the expectation value, expectation of the X^2 and E(X - X_avg)^2. I have written a program like so:</p> <pre><code># program : expectation value import csv import pandas as pd import numpy as np from scipy.stats import chi2_contingency import seaborn as sns import matplotlib.p...
<python><pandas><numpy>
2022-12-15 12:30:06
1
2,066
Evan Gertis
74,811,545
8,176,763
How to return multiple rows in sqlalchemy based on value of a column
<p>I have some <code>table</code> in a database that looks like that:</p> <pre><code>phase_type phase_start phase_end Obsolete 01/01/2021 02/02/2022 Obsolete 01/03/2021 02/07/2022 Obsolete 05/01/2021 09/02/2022 Available 05/07/2021 09/02/2027 Available 05/07/2023 09/02/2025 Available 05/07/2024 09/02/202...
<python><sqlalchemy>
2022-12-15 12:29:23
1
2,459
moth
74,811,521
275,002
429 Too many request error despite using proxies
<p>I am using StormProxies to access Etsy data but despite using proxies and implementing retries I am getting <code>429 Too Many Requests</code> error most of the time(~80%+). Here is my code to access data:</p> <pre><code>import requests def create_request(url, logging, headers={}, is_proxy=True): r = None t...
<python><python-requests>
2022-12-15 12:27:51
1
15,089
Volatil3
74,811,418
3,247,006
How to write a if statement with multiple conditions in multiple lines in Python?
<p>The <code>if</code> statement with <strong>multiple conditions</strong> in <strong>one line</strong> below works properly:</p> <pre class="lang-py prettyprint-override"><code>exam1 = 70 exam2 = 60 exam3 = 50 if (100 &gt;= exam1 and exam1 &gt;= 60) or (100 &gt;= exam2 and exam2 &gt;= 60) or (100 &gt;= exam3 and exam...
<python><python-3.x><if-statement><logical-operators><multiple-conditions>
2022-12-15 12:20:21
1
42,516
Super Kai - Kazuya Ito
74,811,167
10,569,922
Pandas Get Count of Each Row of DataFrame and assign to new column for long-format
<p>I get df:</p> <pre><code>task_id name tag 1 foo xyz 1 foo xyz 22 foo aaa 22 foo aaa 22 foo aaa 22 foo bbb 13 bar xyz 13 bar xyz 33 bar aaa 33 bar aaa </code></pre> <p>So I trying <code>df['tag'].value_count()</code> and <code>df_test.groupby('name')['tag'...
<python><pandas>
2022-12-15 11:59:20
2
521
TeoK
74,811,006
2,915,050
Python - Use Python variable for BigQuery Magic query structure (not query parameter)
<p>I want to use a Python variable to help build the structure of a BigQuery Magic SQL query, however I'm unable to identify a way to do so. It is <em><strong>not</strong></em> a parameter for a <code>WHERE</code> clause or anything similar - it's the structure of the query itself.</p> <p>This is the BigQuery Magic I w...
<python><google-bigquery>
2022-12-15 11:44:31
1
1,583
RoyalSwish
74,810,985
11,809,811
events on widgets that are drawn on a canvas?
<p>I have placed some widgets on a canvas (ultimately to enable scrolling). Here is the simplified code:</p> <pre><code>import tkinter as tk from tkinter import ttk root = tk.Tk() root.geometry('400x400') canvas = tk.Canvas(root, background = 'white') canvas.pack(expand = True, fill = 'both') canvas.create_window((10...
<python><tkinter>
2022-12-15 11:42:51
1
830
Another_coder
74,810,944
18,877,953
Joining logs from 2 Azure Log Analytics workspaces
<p>I'm using the Azure SDK for Python to query a log Analytics workspace.</p> <p>I have 2 workspaces I'd like to query, but I was wondering if there is a way to union the data inside the query instead of querying both workspaces and combining the result objects within my Python program.</p> <p>Something like this -</p>...
<python><azure><azure-log-analytics><azure-sdk><azure-sdk-python>
2022-12-15 11:39:47
2
780
LITzman
74,810,938
1,652,954
How to check if a list contains another list of different values
<p>i would like to know how to check if a list encompases another list regardless of similar values contains. given the example posted below, i want to have a condition checks for existence of a list inside a list. in other words, for the values of <code>l1</code> the check should return False and for <code>l2</code>...
<python>
2022-12-15 11:39:15
3
11,564
Amrmsmb
74,810,890
16,395,449
Add current date or time in the converted file using Pandas script
<p>I am trying to convert .csv to .xlsx using Pandas script. I want the filename to be appended or suffixed with current date(i.e. The converted xlsx file should display like this - sourcefile_12152022.xlsx)</p> <p>I tried this using - import time - but this is not working for me.</p> <pre><code>import time TodaysDate...
<python><python-3.x><pandas>
2022-12-15 11:35:00
1
369
Jenifer
74,810,861
7,547,932
How to mask row in Tensorflow without for loop
<p>I want to create a custom Layer for a Tensorflow model but the logic I have uses a for loop, which Tensorflow doesn't like. How can I modify my code to remove the for loop but still achieve the same result?</p> <pre><code>class CustomMask(tf.keras.layers.Layer): def call(self, inputs): mask = tf.where(in...
<python><tensorflow><keras>
2022-12-15 11:32:30
1
888
kynnemall
74,810,689
12,642,161
Custom sort without specifying all values
<p>Is there a way to sort values without having to specify all values in the list? I just want to, for example, sort by economics and then library. The remaining rows should be the same order as the original df.</p> <pre><code>order = [&quot;economics&quot;,&quot;library&quot;] df cat 0 library 1 economics 2 scie...
<python><pandas><sorting>
2022-12-15 11:18:08
2
398
arv
74,810,662
1,338,588
How to process the dataframe which was read from Kafka Topic using Spark Streaming
<p>I'm able to stream twitter data into my Kafka topic via a producer. When I try to consume through the default Kafka consumer I'm able to see the tweets as well.</p> <p><a href="https://i.sstatic.net/XXLuy.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/XXLuy.png" alt="enter image description here" /><...
<python><apache-spark><pyspark><spark-structured-streaming><spark-kafka-integration>
2022-12-15 11:15:19
1
9,532
Kulasangar
74,810,636
19,797,660
How to break line in python function description?
<p>I've tried to find the solution on how to break the line in a python function description, but there were none that worked for me. I have such a function:</p> <p><a href="https://i.sstatic.net/ZJHqE.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/ZJHqE.png" alt="enter image description here" /></a></p...
<python><pycharm>
2022-12-15 11:13:43
1
329
Jakub Szurlej
74,810,524
2,088,029
How to convert "Excel Xml"/"Xml Spreadsheet 2003", to .xlsx format without office/excel install
<p>The input files are single XML files, that can be generated from excel using &quot;Xml Spreadsheet 2003&quot;, often referred to as &quot;Excel XML&quot; format, and described in this namespace</p> <pre><code>xmlns=&quot;urn:schemas-microsoft-com:office:spreadsheet&quot; </code></pre> <p>(a simple file is at the end...
<python><java><c#><excel>
2022-12-15 11:04:44
1
2,907
MrD at KookerellaLtd
74,810,522
10,536,858
Is storing data in class attribute bad practice?
<p>I need to use some data multiple times in my project. I don't want to read it globally and then pass it to all functions. Is it good practice to store it in class attribute?</p> <p>Something like this:</p> <pre><code>class SomeData(): _data = None data_path = 'path.csv' @classmethod def get_data(cls...
<python>
2022-12-15 11:04:34
3
565
marcin
74,810,477
11,724,014
Python Graphviz - Import SVG file inside a node
<p>I need to import a SVG image using the python librairy of graphviz.</p> <p>Here is the SVG file (created with the software draw.io):</p> <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; standalone=&quot;no&quot;?&gt; &lt;!-- Do not edit this file with editors other than diagrams.net --&gt; &lt;...
<python><svg><graphviz><pygraphviz>
2022-12-15 11:00:51
1
1,314
Vincent Bénet
74,810,332
9,182,743
Type hint for output of plotly express?
<p>If I have a function that returns a plotly express figure, what is the correct way of type hinting?</p> <p>The figure is of type: <code>&lt;class 'plotly.graph_objs._figure.Figure'&gt;.</code></p> <p>Should I type hint by separately importing plotly, and writing: <code>-&gt; plotly.graph_objs._figure.Figure </code>?...
<python><plotly><python-typing><plotly-express>
2022-12-15 10:49:10
1
1,168
Leo
74,810,192
221,270
pyrtlsdr installation Windows 10
<p>I am trying to install pyrtlsdr, I first installed SDRUno and checked whether my SDRPlay is connected and working fine. That's ok. Then I try to install pyrtlsdr with pip on Windows 10 with Python 3.11.0 [MSC v.1929 64 bit (AMD64)] on win32.</p> <p>This sample rise the following error:</p> <pre><code>from rtlsdr imp...
<python><rtl-sdr><pyrtlsdr>
2022-12-15 10:36:31
1
2,520
honeymoon
74,810,124
508,907
How to run an IPython CELL magic from a script (%% magic)
<p>Jupyter magic commands (starting with a single <code>%</code>, e.g. <code>%timeit</code>) can be run in a script using the answer from <a href="https://stackoverflow.com/questions/10361206/how-to-run-an-ipython-magic-from-a-script-or-timing-a-python-script">How to run an IPython magic from a script (or timing a Pyth...
<python><jupyter><ipython><ipython-magic>
2022-12-15 10:30:31
1
14,360
ntg
74,810,051
4,882,200
Insert a bold hyphen in a matplotlib title, rather than minus sign?
<p>I'd like to insert a bold title with a hyphen. I've tried:</p> <pre><code>import matplotlib.pyplot as plt import numpy as np # Data for plotting t = np.arange(0.0, 2.0, 0.01) s = 1 + np.sin(2 * np.pi * t) fig, ax = plt.subplots() ax.plot(t, s) ax.set_title(r&quot;$\bf{hyphenated-example}$&quot;) </code></pre> <p>T...
<python><matplotlib><latex>
2022-12-15 10:24:39
1
305
Femkemilene
74,809,944
19,580,067
Split a single column to 2 different column
<p>Need to split the single column into 2 different columns.</p> <p>I have tried few steps using regex but not able to achieve the result.</p> <p>Any suggestions, please?</p> <p>In the given data, we have the values of both 'A' and 'B' merged together as a single column. We need to split that.</p> <pre><code>Data 1 ...
<python><dataframe><extract>
2022-12-15 10:15:12
1
359
Pravin
74,809,826
2,560,292
SQLAlchemy + mysql / mariadb: bulk upsert with composite keys
<p>Using SQLAlchemy and a MariaDB backend, I need to bulk upsert data. Using <a href="https://stackoverflow.com/a/69968892/2560292">this answer</a> I was able to make it work for model with a single primary key. However, I can't make it work with composite keys.</p> <p>The key part of the code is this one:</p> <pre cla...
<python><mysql><sqlalchemy><mariadb>
2022-12-15 10:05:32
1
1,196
Shan-x
74,809,798
14,649,310
How to validate JSON and Array types in SQLAlchemy?
<p>I have an <code>SQLAlchemy</code> model and two of the properties do not seem to be validated by <code>SQLAlchemy</code> nor do I get an error form the db which is counter intuitive and not what I would expect.</p> <p>Specifically the <code>JSON</code> type and the <code>ARRAY(Text)</code> types do not fail when wro...
<python><validation><sqlalchemy>
2022-12-15 10:03:55
1
4,999
KZiovas
74,809,598
10,121,996
How to parse and iterate to save information in dyanomodb with lamda in python
<p>In order to save data from lamda to dynamodb,</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>import json import boto3 from botocore.exceptions import ClientError dyna...
<python><amazon-web-services><aws-lambda><amazon-dynamodb><boto3>
2022-12-15 09:48:04
1
733
Sobhit Sharma
74,809,457
10,966,677
Catch any of the errors in psycopg2 without listing them explicitly
<p>I have a <code>try</code> and <code>except</code> block where I would like to catch <strong>only</strong> the errors in the <code>psycopg2.errors</code> and not any other error.</p> <p>The explicit way would be:</p> <pre><code>try: # execute a query cur = connection.cursor() cur.execute(sql_query) except...
<python><postgresql><psycopg2>
2022-12-15 09:34:47
2
459
Domenico Spidy Tamburro
74,809,136
972,647
Parsing and flattening complex JSON with Pydantic
<p>I need to consume JSON from a 3rd party API, i.e. I have to deal with whatever this API returns and can't change that.</p> <p>For this specific task the API returns what it calls an &quot;entity&quot;. Yeah, not very meaningful. The issue is the structure is deeply nested and in my parsing I want to be able to flatt...
<python><json><parsing><pydantic>
2022-12-15 09:09:16
1
7,652
beginner_
74,809,061
14,799,981
Click on button and fill elements inside a Table using Selenium Python
<p>I have <code>html table</code> that both include <code>button</code> and <code>fill form</code> as follows</p> <pre><code>&lt;table class=&quot;configTbl&quot; cellspacing=&quot;0&quot;&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td&gt;&lt;span id=&quot;_0&quot; class=&quot;login_input_text&quot;&gt;Use...
<python><selenium><selenium-webdriver><automated-tests>
2022-12-15 09:02:18
0
2,263
RF1991
74,808,898
606,025
How uninstall pip3
<p>I am having some problems with pip when trying to install a python application. It says its not able to find pip3, but its installed</p> <p>Digging deeper I think I have locations where pip3 is installed.</p> <p>While trying to uninstall, even that is not working since it referring to the other pip3</p> <p>How to I ...
<python><pip><erpnext>
2022-12-15 08:46:48
2
1,453
frewper
74,808,691
7,373,353
Hide optional content group in PDF with borb for python
<p>I am following this tutorial to add an OCR-layer to scanned PDFs: <a href="https://github.com/jorisschellekens/borb-examples#72-performing-ocr-on-a-pdf" rel="nofollow noreferrer">https://github.com/jorisschellekens/borb-examples#72-performing-ocr-on-a-pdf</a></p> <p>However, unlike the pictures in the tutorial, the ...
<python><ocr><tesseract><python-tesseract><borb>
2022-12-15 08:26:50
0
395
leabum
74,808,652
12,108,866
Can't get the changed global variable
<p>t.py</p> <pre><code>value = 0 def change_value(): global value value = 10 </code></pre> <p>s.py</p> <pre><code>import t from t import value t.change_value() print(f'test1: {t.value}') print (f'test2: {value}') </code></pre> <p>Output</p> <blockquote> <p>test1: 10</p> <p>test2: 0</p> </blockquote> <p>Why i...
<python>
2022-12-15 08:22:51
5
343
ABHIJITH EA
74,808,528
8,785,163
How to avoid overlapping logs with ThreadPoolExecutor?
<p>I would like to log some information by thread. But the multi-threading code I wrote is leading to overlapping logs and this makes the logs not readable and easy-to-use.</p> <pre class="lang-py prettyprint-override"><code>from concurrent.futures import ThreadPoolExecutor from io import StringIO import logging from ...
<python><multithreading>
2022-12-15 08:10:43
1
443
Mistapopo
74,808,517
17,782,348
Remove rows where at least one zero value
<p>Here is my data frame</p> <pre><code> Param1 Param2 datetime ts 1669246574000 6.06 -1.80 22-24-11 01:36:14 UTC 1669242973000 6.50 -1.7...
<python><pandas><dataframe>
2022-12-15 08:09:44
1
559
devaskim
74,808,427
3,352,254
Deploy python worker to heroku without running immediatly
<p>I have a simply python script that I deploy on Heroku as worker:</p> <p>Procfile:</p> <pre><code>worker: python main.py </code></pre> <p>The script is scheduled to run every day at a specific time with the <code>Heroku Scheduler</code>. I don't want it to run to other times.</p> <p>Every time I push new changes to h...
<python><heroku><scheduled-tasks><worker>
2022-12-15 07:59:50
1
825
smaica
74,808,375
12,097,553
django-dash: callback generated div id tag not found by other callback
<p>I have been working with plotly dash and especially django-dash for a while, and I am now facing an issue that I am not able to resolve. I am confusedbecause I have successfully used the same structure in the past. Hopefully a pair of fresh eyes could help me see what I am messing up.</p> <p>Here is what I have: =&g...
<python><django><plotly-dash>
2022-12-15 07:54:27
1
1,005
Murcielago
74,808,286
20,731,770
I am trying to open an img in a tkinter window, but the pillow library is giving my an error
<p>I am trying to insert a photo in tkinter window python. I am using the library PIL (pillow) but it gives my an error</p> <p>code:</p> <pre class="lang-py prettyprint-override"><code>from PIL import ImageTk, Image my_img = ImageTk.PhotoImage(Image.open(link)) my_label = Label(window, image=my_img) my_label.place(x=x...
<python><python-imaging-library>
2022-12-15 07:45:56
1
590
Adam Basha
74,807,987
16,971,617
How to use color science and OpenCV in Python
<p>Here is my code using <a href="https://github.com/colour-science/colour" rel="nofollow noreferrer">Colour</a> to do color calibration. It uses numpy float64 type but how can I convert back to the format that is compatible in openCV, ideally uint8 because Canny only works with uint8?</p> <pre class="lang-py prettypri...
<python><numpy><opencv><colors>
2022-12-15 07:18:01
2
539
user16971617
74,807,729
13,583,510
isalpha giving True for some Sinhala words
<p>I'm trying to check if a sentence only has Sinhala words (they can be nonsense words as long as they are written in Sinhala). Sometimes there can be English words in a sentence mixed with sinhala words. The thing is sometimes Sinhala words give <code>True</code> when checked with <code>isalpha()</code> giving incorr...
<python><unicode><utf-8><isalpha>
2022-12-15 06:48:17
3
10,345
cmgchess
74,807,667
386,861
UnboundLocalError: local variable var referenced before assignment - how to debug
<p>I'm working through a tutorial based on this and have hit this error.</p> <p>I am trying to work up my skill in Python and am not sure how to debug this because the error confuses me.</p> <pre><code>import random MAX_LINES = 3 MAX_BET = 100 MIN_BET = 1 ROWS = 3 COLS = 3 symbol_count = { &quot;A&quot;: 2, ...
<python>
2022-12-15 06:40:31
1
7,882
elksie5000
74,807,602
317,460
How to "diagram as code" zoomable block diagram in Python, or with another tool Python can interact with?
<p>Is there a package in Python (or JavaSs) that can generate GUI like in the image below? Allowing to:</p> <ol> <li>Generate block diagrams as code</li> <li>Zoom into\out-of blocks interactively.</li> </ol> <p>There are packages that support &quot;Diagrams as code&quot; in Python (<a href="https://github.com/mingramme...
<python><diagram>
2022-12-15 06:32:39
0
3,627
RaamEE
74,807,493
10,976,654
How to use pytest mark parametrize with functions with multiple arguments
<p>How can I use the values from an imported CSV in pytest? The functions take multiple arguments (mix of keyword and positional). I looked at @pytest.mark.parametrize but I didn't understand how to use multiple arguments.</p> <p>I am importing using np.genfromtxt, but here is an MRE with the column names:</p> <pre><co...
<python><pytest>
2022-12-15 06:15:45
1
3,476
a11
74,807,372
3,247,006
How to run "SELECT FOR UPDATE" instead of "SELECT" when changing and deleting data in Django Admin?
<p>I have the code below:</p> <pre class="lang-py prettyprint-override"><code># &quot;store/models.py&quot; from django.db import models class Person(models.Model): name = models.CharField(max_length=30) </code></pre> <pre class="lang-py prettyprint-override"><code># &quot;store/admin.py&quot; from django.contri...
<python><python-3.x><django><django-admin><select-for-update>
2022-12-15 05:59:49
2
42,516
Super Kai - Kazuya Ito
74,807,332
6,628,988
Not able to import module from other directory using python?
<p>Please find my project structure attached as image below</p> <p><a href="https://i.sstatic.net/n2xQS.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/n2xQS.png" alt="enter image description here" /></a></p> <p>I'm running jobs/my_job.py from project root directory i.e from sample_project, when I'm runn...
<python><python-3.x>
2022-12-15 05:54:46
1
430
Saranraj K
74,807,014
2,463,341
ImportError: pycurl: libcurl link-time version (7.79.1) is older than compile-time version (7.84.0)
<p>I know this question has been asked before, but none of the solutions seem to be working for me. I am running this on Mac OS Monterey (12.6.1). Installed Python 3.7.12 (using pyenv) and using Poetry as a dependency manager.</p> <p>I did the following steps after activating &amp; deactivating the virtual environment ...
<python><macos><pip><openssl><python-poetry>
2022-12-15 05:03:25
2
499
Vinnie
74,806,983
219,976
Custom Authentication in Django Rest Framework
<p>I have a django rest framework application with custom authentication scheme implemented. Now I want to allow external app call some methods of my application. There's an endpoint for external app to login /external-app-login which implemented like this:</p> <pre><code>class ExternalAppLoginView(views.APIView): ...
<python><django><authentication><django-rest-framework>
2022-12-15 04:57:45
1
6,657
StuffHappens
74,806,952
3,121,975
Why is multiplication faster than bitshift
<p>I recently posted an answer where I suggested using bitshift instead of multiplication as a performance boost. It was pointed out to me that this isn't the case with the following example:</p> <pre><code>from timeit import repeat for e in ['x*2 ', 'x&lt;&lt;1'] * 3: print(e, min(repeat(e, 'x=5'))) x*2 0.015567...
<python>
2022-12-15 04:52:21
0
8,192
Woody1193
74,806,886
7,690,767
Use standard library or 3rd party to conviently uncurry Python functions
<p>I am experimenting with Functional Programming in Python and I usually end up needing a way to uncurry functions.</p> <p>I solve this issue by using:</p> <pre class="lang-py prettyprint-override"><code>from typing import Callable, TypeVar T = TypeVar(&quot;T&quot;) R = TypeVar(&quot;R&quot;) def uncurry(function: ...
<python><functional-programming><currying><toolz>
2022-12-15 04:39:49
0
503
Ezequiel Castaño
74,806,815
13,560,598
subclassing the builtin enumerate in python
<p>Consider the code below. I am trying to subclass the builtin <code>enumerate</code> so that it prints a line for every turn of the for loop. The code seems to be working, which is surprising, because I have never called <code>super().__init__(x)</code>. So, what is happening here? Who is initializing the base class ...
<python><built-in><enumerate>
2022-12-15 04:25:41
1
593
NNN
74,806,803
1,686,236
Pandas-generated .tar.gz can't be extracted
<p>I have saved a pandas DataFrame to disk as a compressed .tar.gz file, using <code>data.to_csv(path+'file.csv.tar.gz', compression='infer')</code>, which seems to work fine. However, when I later try to extract the file using (on Ubuntu) <code>tar -xzvf file.csv.tar.gz</code>, I get the messages <code>tar: This does ...
<python><pandas><tar>
2022-12-15 04:23:27
0
2,631
Dr. Andrew
74,806,767
12,149,817
How to use a list as an argument of a function in python?
<p>I have a function that finds similarity between columns of two dataframes:</p> <pre><code>def jac_sim_df(df1, df2, thresh): L = [] for col in df1.columns: js_list = [] genes1 = df1.loc[df1[col] &gt;= 2,:].index #get DEGs for each column in df1 for column in df2.columns: ...
<python>
2022-12-15 04:16:09
2
720
Yulia Kentieva
74,806,697
15,299,206
How to update list of dictionary in dynamodb using boto3 with Conditional check
<p>I have dynamodb</p> <ul> <li><code>groupId</code> is partition key</li> <li><code>empdetails</code> is list</li> <li><code>dataDetails</code> is the attribute name which i need to update</li> <li>if list is not there it has to create, but if its there then I need update the dictionary</li> </ul> <p>I need to update ...
<python><amazon-dynamodb><boto3>
2022-12-15 04:00:14
1
488
sim
74,806,619
4,451,521
Plotting list of tuples (both plot and scatter)
<p>I would like to plot as lines and also as points a list of tuples so I have</p> <pre><code>import matplotlib.pyplot as plt import numpy as np x = np.arange(0, 3 * np.pi, 0.1) y = np.sin(x) lista=[(0,1,3),(1,4,5),(2,0,2),(3,5,10),(4,3,7)] #lista=[(0,1),(1,4),(2,0),(3,5),(4,3)] plt.scatter(*zip(*lista)) #plt.plot(*...
<python><matplotlib>
2022-12-15 03:45:23
1
10,576
KansaiRobot
74,806,560
1,447,953
Assign coordinate to dimension in xarray
<p>Suppose I have the following DataSet:</p> <pre><code>&gt;&gt;&gt; coords = {&quot;coords&quot;: (&quot;x&quot;, [10, 20, 30, 40])} &gt;&gt;&gt; dset = xr.Dataset(coords=coords) &gt;&gt;&gt; dset &lt;xarray.Dataset&gt; Dimensions: (x: 4) Coordinates: coords (x) int64 10 20 30 40 Dimensions without coordinates:...
<python><python-xarray>
2022-12-15 03:34:00
1
2,974
Ben Farmer
74,806,078
5,562,092
add/remove security group rules to existing SG in pulumi python
<pre><code>db_sg = ec2.get_security_group(id=&quot;sg-number&quot;) ec2.SecurityGroupRule( &quot;db-ingress&quot;, type=&quot;ingress&quot;, description= &quot;allow tcp to db&quot;, protocol=&quot;tcp&quot;, to_port= 5432, from_port= 5432, security_group_id = db_sg.id, ) ec2.SecurityGroupR...
<python><pulumi>
2022-12-15 01:58:18
1
875
A H Bensiali
74,806,043
5,067,401
Issues with getting cuda to work on torch, importing torch and cuda modules into Python
<p>I'm having some basic issues running the torch and cuda modules in my Python script.</p> <p>I think that this has something to do with the different versions of Python that I have installed. I have two versions of Python installed:</p> <p><a href="https://i.sstatic.net/5DLNL.png" rel="nofollow noreferrer"><img src="...
<python><pip><pytorch><cuda>
2022-12-15 01:50:37
1
473
ejn
74,806,038
10,976,654
Column stacking nested numpy structure array, help getting dims right
<p>I'm trying to create a nested record array, but I am having trouble with the dimensions. I tried following the example at <a href="https://stackoverflow.com/questions/19201868/how-to-set-dtype-for-nested-numpy-ndarray">how to set dtype for nested numpy ndarray?</a>, but I am misunderstanding something. Below is an M...
<python><numpy><structured-array>
2022-12-15 01:49:19
1
3,476
a11
74,805,849
19,161,399
Package Publishing (Python) failing through Poetry
<p>I am new to this, trying to publish a package to pypi.org using Poetry package. on my local the build is working, I am able to import the package test run it, it's all good.</p> <p>but when I try to publish it to pypi.org, I get below error - as per the article I was following <a href="https://www.brainsorting.dev/p...
<python><pypi><python-poetry>
2022-12-15 01:07:38
3
404
Ankiz
74,805,824
14,311,397
"eb create" deploys .venv directory, even although it's included in .ebignore file
<p>I'm deploying a Flask API to Amazon Elastic Beanstalk through the eb CLI, following the <a href="https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-flask.html" rel="nofollow noreferrer">instructions here</a> and even although my <code>.ebignore</code> file is set to ignore the <code>.venv</c...
<python><amazon-elastic-beanstalk>
2022-12-15 01:02:14
1
441
LeperAffinity666
74,805,790
11,117,255
How do I convert bytes to utf-8 without turning regular strings into NaNs?
<p>I have a process that runs on multiple pandas dataframes. Sometimes the data comes in the form of bytes, such as:</p> <pre><code>&gt;&gt;&gt; pd.DataFrame[['x']] ['x'] b'123' b'111' b'110' </code></pre> <p>And other times it comes in the form of regular integers</p> <pre><code>&gt;&gt;&gt; pd.DataFrame[['x']] ['x'] ...
<python><pandas><unicode><byte>
2022-12-15 00:56:25
2
2,759
Cauder
74,805,688
11,939,660
Most pythonic way to reuse a generator?
<p>I have two generators with the following signature:</p> <ul> <li><code>gen1(inputs) -&gt; Iterator[A]</code></li> <li><code>gen2(Iterator[A]) -&gt; Iterator[B]</code></li> </ul> <p>My goal is to write another generator (let's called it <code>final_gen</code>) that gives me both <code>A</code> and <code>B</code>.</p>...
<python><generator>
2022-12-15 00:35:39
1
421
Hongtao Yang