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,114,080
1,594,077
How to sort a 4D tensor based on the first value in the 4th dimension?
<p>I have a 4D tensor that I want to sort. The order of values in the 4th dimension is important to stay the same, but I want to sort arrays in the 3rd dimension based on the first value in the 4th dimension. I am using TensorFlow 2.11. I have tried with tf.argsort() and tf.gather_nd(), but I can't make it work.</p> <p...
<python><numpy><tensorflow>
2023-01-13 20:15:46
1
353
Soli Technology LLC
75,113,929
236,594
factory_boy: make a factory that returns the result of a function
<p>I have a function that generates a list of objects. The objects have complex relationships that are handled in the generator function.</p> <p>How do I make a factory (not a SubFactory!) that, when asked to generate a value, just calls this function?</p>
<python><factory-boy>
2023-01-13 19:56:54
1
2,098
breadjesus
75,113,746
16,978,074
read the edge list from a csv file and create a graph with networkx
<p>Hi everyone I want to read the edge list from a csv file and create a graph with networkx to calculate the betweenness centrality with python. My code is:</p> <pre><code>import pandas as pd import networkx as nx df = pd.read_csv('edges1.csv') Graphtype = nx.Graph() G = nx.from_pandas_edgelist(df, edge_attr='genre_id...
<python><csv><graph><networkx>
2023-01-13 19:33:40
1
337
Elly
75,113,742
4,796,942
Improving performance for a nested for loop iterating over dates
<p>I am looking to learn how to improve the performance of code over a large dataframe (10 million rows) and my solution loops over multiple dates <code>(2023-01-10, 2023-01-20, 2023-01-30)</code> for different combinations of <code>category_a</code> and <code>category_b</code>.</p> <p>The working approach is shown bel...
<python><sql><pandas><numpy><google-bigquery>
2023-01-13 19:32:44
1
1,587
user4933
75,113,685
7,800,760
Python: finding longest version of names
<p>I am using python to parse a news article and obtain a set of people names contained within it. Currently every <strong>Named Entity</strong> classified as a <strong>PER</strong>son (by <em>Stanford's Stanza</em> NLP library) gets added to a <strong>set</strong> as follows:</p> <pre><code>maxnames = set() # initial...
<python><string>
2023-01-13 19:25:21
1
1,231
Robert Alexander
75,113,505
4,822,772
Gravity form API with python
<p>The documentation of the API is <a href="https://docs.gravityforms.com/rest-api-v2/" rel="nofollow noreferrer">here</a>, and I try to implement this line in python</p> <pre><code>//retrieve entries created on a specific day (use the date_created field) //this example returns entries created on September 10, 2019 htt...
<python><wordpress-rest-api><gravity-forms-plugin>
2023-01-13 19:05:14
2
1,718
John Smith
75,113,503
2,738,155
run tests on a lambda container image?
<p>I'm using Lambda container images to package complicated libraries like opencv and pdf2image in Python.</p> <p>Is there a way to run unit tests against it so I can get a code coverage for tools like Sonar? With normal code, I could do the following: <code>python -m unittest -v</code></p> <p>But not sure how to do th...
<python><aws-lambda><bitbucket-pipelines>
2023-01-13 19:04:27
1
1,352
chomp
75,113,464
9,779,999
M1 trying to run SparkSession, but having RuntimeError: Java gateway process exited before sending its port number
<p>I am trying to run a simple command <code>spark = SparkSession.builder.appName(&quot;Basics&quot;).getOrCreate()</code> in my M1 Mac, Monterey 12.6.2, but it throws an error:</p> <pre><code>The operation couldn’t be completed. Unable to locate a Java Runtime. Please visit http://www.java.com for information on insta...
<python><macos><pyspark><zsh><java-home>
2023-01-13 19:01:48
1
1,669
yts61
75,113,403
2,146,381
scipy.integrate.quad with non plausible values
<p>He guys,</p> <p>I'm al little bit in trouble with math. So there is an <a href="https://stackoverflow.com/questions/74775404/">old question</a> and it's not really solved. I thought about editing the old one, but I think it's even good to start a new question.</p> <p>As you can see below there is an example of my ex...
<python><math><scipy>
2023-01-13 18:54:49
1
322
tux007
75,113,366
1,028,270
pip install --upgrade is installing my "local" version suffixed packages
<p>During development I build and push feature branch versions of my package that look like: <code>1.2.3+mybranch</code>.</p> <p>So I'll have packages named <code>1.2.3</code>, <code>1.2.3+mybranch</code> and <code>1.2.4+mybranch</code>, and <code>1.2.4</code>.</p> <p>The problem is it seems pip has no problem installi...
<python><pip>
2023-01-13 18:50:12
1
32,280
red888
75,113,344
8,401,374
Selenium can't find dynamially loaded input field element even after waiting for that specific element
<p>I'm trying to access an input field of username (of login page) with Selenium. The page is JavaScript based. <code>driver.get()</code> wait by default to load the complete page. In my case, it is unable to load that. I can inspect the element on browser (firefox) and I get this.</p> <pre><code>&lt;input type=&quot;t...
<python><selenium><xpath><css-selectors><webdriverwait>
2023-01-13 18:48:27
3
1,710
Shaida Muhammad
75,113,200
5,924,264
How to check the amount of memory a single/set of lines in python is using?
<p>I added several lines to a python codebase and now the memory is exceeding the limits. Is there a way to see how much memory a particular line or set of lines is using in Python?</p> <p>Here's the set of lines that I added</p> <pre><code> df[&quot;value_weighted_average&quot;] = ( df.reset_index().merge(df2...
<python><memory><memory-management>
2023-01-13 18:32:45
0
2,502
roulette01
75,113,164
1,275,973
Understanding Python dictionary "lookups" between dictionaries to replace keys
<p>I have two dictionaries and my objective was to replace the keys in first_dict, with the values in second_dict.</p> <p>I got the code working, but largely through trial and error, so would like some help understanding and translate exactly what is going on here in Python.</p> <pre><code>first_dict={&quot;FirstName&q...
<python><dictionary>
2023-01-13 18:28:40
1
326
alexei7
75,113,080
676,430
Finding files in a directory that have an underscore and no extension and adding an extension to it
<p>I have a directory with some files <strong>with an underscore and no extension</strong> that I would like to <strong>add an extension to it and get rid of the underscore</strong>.</p> <p><strong>Example: list of files in directory</strong></p> <pre><code>filename1_.jpg file_name_2_ file_name3 </code></pre> <p><stron...
<python><python-3.x>
2023-01-13 18:19:46
3
3,419
Rick T
75,112,863
11,462,274
Columns changing names when I try to filter rows from a DataFrame that aren't in another DataFrame according to specific columns
<p>Following this answer:</p> <p><a href="https://stackoverflow.com/a/47107164/11462274">https://stackoverflow.com/a/47107164/11462274</a></p> <p>I try to create a DataFrame that is only the lines not found in another DataFrame, however, not according to all columns, but according to only some specific columns, so I tr...
<python><pandas><dataframe>
2023-01-13 17:58:01
2
2,222
Digital Farmer
75,112,812
10,492,521
How do I make a Conan test package require the package that it is testing? Specifically if the package version is dynamic?
<p>let's say I have a package:</p> <pre><code>from conans import ConanFile class MainLibraryPackage(ConanFile): name = 'main' description = 'stub' def set_version(self): self.version = customFunctionToGetVersion() ... </code></pre> <p>And I have a test package for it:</p> <pre><code>import os ...
<python><c++><cmake><conan>
2023-01-13 17:52:36
1
515
Danny
75,112,776
4,083,786
vscode remote ssh integrated terminal not reading correct python
<p>I followed the instructions on how to set up a remote ssh development environment. I have a host: windows 10. I go to my terminal and ssh into a remote linux server for python development. When i remote in for the first time, its a fresh new environment. When i type</p> <pre><code>which python </code></pre> <p>I...
<python><visual-studio-code><ssh>
2023-01-13 17:49:52
1
1,182
turtle_in_mind
75,112,699
850,781
Compute correlations of several vectors
<p>I have several pairs of vectors (arranged as two matrices) and I want to compute the <em>vector</em> of their pairwise correlation coefficients (or, better yet, angles between them - but since correlation coefficient is its cosine, I am using <a href="https://numpy.org/doc/stable/reference/generated/numpy.corrcoef.h...
<python><numpy><linear-algebra><pearson-correlation>
2023-01-13 17:42:02
1
60,468
sds
75,112,530
4,556,675
Pytest monkeypatch mock leak
<p>I have a module that I am trying to unit test, and when running individual tests by themselves, each test will pass. When I try to run the full set of tests together in a single test session using <code>pytest test_some_module.py</code>, some tests will fail due to a monkeypatch mock that is leaking across tests.</p...
<python><redis><mocking><pytest><monkeypatching>
2023-01-13 17:26:47
0
5,868
CaptainDriftwood
75,112,453
2,706,344
Actual interpolation based on date
<p>This question here is a follow up question occurred in the comments of <a href="https://stackoverflow.com/q/75110993/2706344">Resampling on a multi index</a>.</p> <p>We start with following data:</p> <pre><code>data=pd.DataFrame({'dates':['2004','2008','2012'],'values':[k*(1+4*365) for k in range(3)]}) data['dates']...
<python><pandas><interpolation>
2023-01-13 17:19:09
3
4,346
principal-ideal-domain
75,112,399
4,040,743
How to round down a datetime to the nearest 5 Minutes?
<p>I need a Python3 function that rounds down a <code>datetime.datetime</code> object to the nearest 5 minutes. Yes, this has been discussed in previous SO posts <a href="https://stackoverflow.com/questions/32723150/rounding-up-to-nearest-30-minutes-in-python">here</a> and <a href="https://stackoverflow.com/questions/...
<python><python-3.x><datetime><rounding>
2023-01-13 17:13:47
3
1,599
Pete
75,112,340
6,932,839
Tkinter - After Second Button Click, Change Button Function to Close Window
<p>I am trying to figure out a way to change a button's text and functionality after I have clicked the <code>Submit</code> button a second time. In the below instance, I am trying to:</p> <p><strong>1)</strong> Change the button's text from <code>Submit</code> to <code>Close</code> after I have entered in the username...
<python><tkinter><label><tkinter-entry><tkinter-button>
2023-01-13 17:08:09
1
1,141
arnpry
75,112,280
978,434
Type support for dynamically added instance variable
<p>Because of working a lot with a 3rd party code (Django-ORM), I need to add some variables to the class that are not declared initially.</p> <p>The simplest Python example would be:</p> <pre class="lang-py prettyprint-override"><code>def enrich(obj): obj.c = 5 return obj </code></pre> <p>It works in Python, ...
<python><mypy><python-typing>
2023-01-13 17:02:46
0
3,179
Igor
75,112,254
10,967,961
Creating nodes for an undirected graph starting from pandas
<p>I have a dataframe that looks like this (I have 170000 observations in reality):</p> <pre><code>Firm pat cited_pat F_1 [p0,p1,p2] [p0,p1,p2] F_2 [] [] F_3 [p3,p6,p2] [p5,p0,p23,p29,p12,p8] F_4 [p0,p9,p25] [p0,p29,p31] ... </code></pre> <p>The idea is this:...
<python><pandas><networkx>
2023-01-13 17:00:12
1
653
Lusian
75,112,136
16,529,391
Python unable to install guesslang
<p>I'm trying to install <code>guesslang</code> with pip but it seems that the last version (which was released on August 2021) depends on an obsolete version of Tensorflow (<code>2.5.0</code>). The problem is that I can't find this version anywhere. So, how can I install it? Or is there any other python library that d...
<python><pip><language-detection>
2023-01-13 16:49:24
2
483
pasta64
75,112,083
4,439,524
Pandas eval returns error on date arithmetic using Timedelta
<p>When I try to use basic date arithmetic in Pandas' <code>eval()</code>, it gives the following error:</p> <p><code>Cannot convert input [1 days 00:00:00] of type &lt;class 'pandas._libs.tslibs.timedeltas.Timedelta'&gt; to Timestamp</code></p> <p>The same expression run against the data frame works fine, though. Is t...
<python><pandas><eval>
2023-01-13 16:44:39
0
1,456
gherka
75,111,895
10,134,422
Secure way to utilize AWS SSM parameter store to make API call
<p>I need to write a lambda function which makes an API call (to Airflow) using credentials stored in AWS SSM parameter store. I have been supplied with the key id for the credentials.</p> <p>How can I securely query the credentials and integrate them (again securely) into the API call?</p> <p>Is this on the right trac...
<python><aws-lambda><airflow><aws-ssm><airflow-api>
2023-01-13 16:26:05
1
460
Sanchez333
75,111,782
14,735,451
Efficient way to compare if items in a list exist in a list of lists
<p>I have 2 lists:</p> <pre><code>list_1 = ['Denver Broncos', 'Carolina Panthers', &quot;Levi's Stadium in the San Francisco Bay Area at Santa Clara, California&quot;, 'Carolina Panthers', 'gold'] list_2 = [['Denver Broncos', 'Denver Broncos', 'Denver Broncos'], ['Carolina Panthers', 'Carolina Panthers', 'Carolin...
<python><list>
2023-01-13 16:14:30
0
2,641
Penguin
75,111,707
10,798,503
How to reset Discord.OptionSelect in Python Pycord?
<p>I am trying to implement a &quot;Back&quot; button that will return to the previous dropdown. I am using Pycord.</p> <p>I have a dropdown with options to pick different food categories, after you pick a category, the dropdown menu changes to a new dropdown where see items in that category. In addition, you have a &q...
<python><discord.py><pycord>
2023-01-13 16:08:07
1
1,142
yarin Cohen
75,111,694
17,277,677
How to change dataframe from long to wide shape without losing duplicated values?
<p>I have given example dataframe:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd df = pd.DataFrame({ 'company_name': ['do holdings co', 'real estate b.v.', 'real estate b.v.','real coiffure', 'real coiffure', 'elendom', 'theatre media ltd'], 'sector_1': ['Industrials'...
<python><pandas><dataframe><formatting><dummy-variable>
2023-01-13 16:07:23
1
313
Kas
75,111,658
2,913,106
transform colors in colorbar, not the ticks
<p>When using a custom normalization, for instance <code>PowerNorm</code>, we can adjust the mapping between values and the colors. If we then show a corresponding colorbar, we can see the change when observing the ticks (compare left and right plot in the following picture).</p> <p>Is there a way to use the normalizat...
<python><matplotlib><transform><normalization><colorbar>
2023-01-13 16:04:17
1
11,728
flawr
75,111,569
13,142,245
Streamlit on AWS: serverless options?
<p>My goal is to deploy a Streamlit application to an AWS Serverless architecture. Streamlit does not appear to function properly without a Docker container, so the architecture would need to support containers.</p> <p>From various tutorials, EC2 is the most popular deployment option for Streamlit, which I have no inte...
<python><amazon-web-services><docker><serverless><streamlit>
2023-01-13 15:57:43
1
1,238
jbuddy_13
75,111,524
7,920,004
Python - handle empty list when iterating through dict
<p>I have a list of dicts and need to retreive <code>events</code> key which is a list. However that list is not always filled with data, depending on a case.</p> <p>How to iterate through them and not get <code>list index out of range</code> error? <code>[-1]</code> does work but when <code>events</code> is and empty ...
<python>
2023-01-13 15:54:46
2
1,509
marcin2x4
75,111,518
11,462,274
Analyze if the value of a column is less than another and this another is less than another and so on
<p>Currently I do it this way:</p> <pre class="lang-python prettyprint-override"><code>import pandas as pd dt = pd.DataFrame({ '1st':[1,0,1,0,1], '2nd':[2,1,2,1,2], '3rd':[3,0,3,2,3], '4th':[4,3,4,3,4], '5th':[5,0,5,4,5], 'minute_traded':[6,5,6,5,6] }) dt = dt[ (dt['1st'] &lt; dt['2nd']) &...
<python><pandas><dataframe>
2023-01-13 15:54:18
2
2,222
Digital Farmer
75,111,462
3,719,713
Annotate a mutating function default param
<p>Let's say I have this function:</p> <pre class="lang-py prettyprint-override"><code> def foo(inp = None): if inp is None: inp = [] inp.append(&quot;a&quot;) print(inp) </code></pre> <p>Note: <code>None</code> as default param must be used to avoid updating the same list.</p> <p>I want to annota...
<python><mypy>
2023-01-13 15:50:12
2
1,208
diegus
75,111,217
53,491
How do I run DBT models from a Python script or program?
<p>I have a DBT project, and a python script will be grabbing data from the postgresql to produce output.</p> <p>However, part of the python script will need to make the DBT run. I haven't found the library that will let me cause a DBT run from an external script, but I'm pretty sure it exists. How do I do this?</p> <p...
<python><dbt>
2023-01-13 15:28:30
1
12,317
Brian Postow
75,111,196
16,315,671
YOLOv8 : RuntimeError: An attempt has been made to start a new process before the current process has finished its bootstrapping phase
<p>An attempt has been made to start a new process before the current process has finished its bootstrapping phase.</p> <pre><code> This probably means that you are not using fork to start your child processes and you have forgotten to use the proper idiom in the main module: if __name__ == '__main_...
<python><yolo>
2023-01-13 15:26:30
3
461
Prince David Nyarko
75,111,097
10,003,538
How to convert byte array to hex string?
<p>Here is the sample code in JS :</p> <pre><code>function toHexString(bytes) { return bytes.map(function(byte) { return (&quot;00&quot; + (byte &amp; 0xFF).toString(16)).slice(-2); }).join(''); } input -&gt; Buffer.from(&quot;333138383223633D77DB&quot;, 'hex') output -&gt; 333138383223630770 </code></pre>...
<javascript><python>
2023-01-13 15:18:34
3
1,225
Chau Loi
75,111,080
2,173,320
Training wav2vec2 for multiple (classification) tasks
<p>I trained a wav2vec2 model using pytorch and huggingface transformer. Here is the code: <a href="https://github.com/padmalcom/wav2vec2-nonverbalvocalization" rel="nofollow noreferrer">https://github.com/padmalcom/wav2vec2-nonverbalvocalization</a></p> <p>I now want to train the model on a second tasks, e.g. age clas...
<python><pytorch><classification><huggingface>
2023-01-13 15:16:51
1
1,507
padmalcom
75,110,993
2,706,344
Resampling on a multi index
<p>I have a DataFrame of the following form: <a href="https://i.sstatic.net/o3Vhf.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/o3Vhf.png" alt="enter image description here" /></a></p> <p>You see that it has a multi index. For each <code>muni</code> index I want to do a resampling of the form <code>.re...
<python><pandas>
2023-01-13 15:10:54
1
4,346
principal-ideal-domain
75,110,767
7,437,143
Position of images as nodes in networkx plot?
<p>After using <a href="https://stackoverflow.com/a/53968787/7437143">this answer</a> to generate a plot with images as nodes, I am experiencing some difficulties in making the y-coordinate positions of the nodes line up with the y-coordinate positions of the images: <a href="https://i.sstatic.net/dWFLD.png" rel="nofol...
<python><image><matplotlib><networkx>
2023-01-13 14:50:17
1
2,887
a.t.
75,110,765
3,896,008
Truncating osmnx by bbox (or polygon): How to create dummy nodes at boundaries?
<p>I am trying to truncate an osmnx graph by bbox. It works as per the documentation. The reproducible self-explanatory code is given below:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np import osmnx as ox import geopandas as gpd import networkx as nx import matplotlib.pyplot as plt N, S, E, W...
<python><graph><truncate><osmnx>
2023-01-13 14:50:08
1
1,347
lifezbeautiful
75,110,739
14,607,802
Python Request, UnicodeEncodeError: 'charmap' codec can't encode character '\u0421' in position 1228799: character maps to <undefined>
<p>I am trying to request some information from Coincodex via Python:</p> <pre><code>url = &quot;https://coincodex.com/apps/coincodex/cache/all_coins.json&quot; response = requests.get(url) data = json.loads(response.text.encode('utf-8')) print(data) </code></pre> <p>However, I keep getting the following error:<code>Un...
<python>
2023-01-13 14:47:20
1
817
Charmalade
75,110,689
3,591,044
Generating text word by word for transformers
<p>I’m currently using GPT-J for generating text as shown below. This works well but it takes up to 5 seconds to generate the 100 tokens.</p> <p>Is it possible to do the generation word by word or sentence by sentence? Similar to what ChatGPT is doing (ChatGPT seems to produce the output word by word).</p> <pre><code>i...
<python><huggingface-transformers><huggingface>
2023-01-13 14:43:17
0
891
BlackHawk
75,110,664
5,810,060
How to find best string match out of multiple possibilities in a dataframe?
<p>I have a DF that looks like this:</p> <pre><code> Row Master Option1 Option2 1 00150042 plc WAGON PLC wegin llp 2 01 telecom, ltd. 01 TELECOM LTD telecom 1 3 0404 investments limited 0404 ...
<python><python-3.x><pandas><for-loop><similarity>
2023-01-13 14:41:12
1
906
Raul Gonzales
75,110,631
15,673,412
python plotly - produce plot upon two clicks
<p>Let's suppose I have a plotly <code>graph_objects.Figure</code> object containing a scatterplot:</p> <pre><code>y = np.random.rand(10) x = np.random.rand(10) names = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'L'] fig = go.FigureWidget() fig.add_trace(go.Scatter( x=x, y=y, ...
<python><onclick><plotly><plotly.graph-objects>
2023-01-13 14:37:45
0
480
Sala
75,110,547
815,653
Tensorflow's random.truncated_normal returns different results with the same seed
<p>The following lines are supposed to get the same result:</p> <pre class="lang-py prettyprint-override"><code>import tensorflow as tf print(tf.random.truncated_normal(shape=[2],seed=1234)) print(tf.random.truncated_normal(shape=[2],seed=1234)) </code></pre> <p>But I got:</p> <pre class="lang-py prettyprint-override">...
<python><tensorflow><machine-learning><tensor><random-seed>
2023-01-13 14:29:34
2
10,344
zell
75,110,411
11,622,712
Group datetime values by datetime ranges and calculate the min and max values per range
<p>I have the following DatetimeIndex values:</p> <pre><code>DatetimeIndex(['2021-01-18 01:32:00', '2021-01-18 01:33:00', '2021-01-18 01:34:00', '2021-01-18 01:35:00', '2021-01-18 01:36:00', '2021-01-18 01:37:00', '2021-12-16 12:07:00', '2021-12-16 12:08:00', ...
<python><datetime>
2023-01-13 14:19:05
2
2,998
Fluxy
75,110,264
7,698,116
How to perform a synchronous task in an asynchronous FastAPI REST endpoint without blocking the event loop?
<p>I have an application setup using FastAPI and Celery for some CPU intensive tasks (basically some synchronous functions defined). One of the REST endpoints is <code>request_data</code> defined as <code>async</code> that users can call to request data. It provides an optional parameter <code>force</code> that if <cod...
<python><asynchronous><concurrency><celery><fastapi>
2023-01-13 14:06:00
0
368
ATK
75,110,240
9,805,238
Comparing PDF files with varying degrees of strictness
<p>I have two folders, each including ca. 100 PDF files resulting from different runs of the same PDF generation program. After performing some changes to this program, the resulting PDF should always stay equal and nothing should break the layout, the fonts, any potential graphs and so on. This is why I would like to ...
<python><pdf><hash><pdfcompare>
2023-01-13 14:03:53
2
3,730
Hagbard
75,110,202
2,706,344
Why does the filtering by notnull() not work?
<p>I have a DataFrame <code>cMean</code>. Its origin is some resampling of some data. It contains many NaN values and I wanted to get rid of them so I tried <code>cMean[cMean.notnull()]</code>. However, they still show up: <a href="https://i.sstatic.net/xpXgy.png" rel="nofollow noreferrer"><img src="https://i.sstatic.n...
<python><pandas>
2023-01-13 13:59:49
1
4,346
principal-ideal-domain
75,110,151
8,170,368
How to make a module function use a locally named variable as a default parameter?
<p>I use the following function in several scripts in my project folder:</p> <pre><code>verbose_print = config[&quot;verbose&quot;].getboolean('print') def verbose(text, *args, **kwargs): if verbose_print: print(text, *args, **kwargs) return None </code></pre> <p><code>verbose_print</code> is a boolean value I...
<python><function>
2023-01-13 13:54:49
1
388
mariogarcc
75,110,046
353,337
Function in Python list comprehension, don't eval twice
<p>I'm composing a Python list from an input list run through a transforming function. I would like to include only those items in the output list for which the result isn't <code>None</code>. This works:</p> <pre class="lang-py prettyprint-override"><code>def transform(n): # expensive irl, so don't execute twice ...
<python><list-comprehension>
2023-01-13 13:45:44
2
59,565
Nico Schlömer
75,110,008
12,596,824
Assign column adding columns in pandas dynamically (method chaining in python)
<p>I want to create a new column named total which adds all the year columns (everything in these columns are integers). I want to do it dynamically because as each year passes there will be a new column (for example 2024).</p> <p>How can I do this in Python using method chaining and the assign operator?</p> <pre><code...
<python><pandas><method-chaining>
2023-01-13 13:41:59
3
1,937
Eisen
75,109,888
2,290,493
How to decorate iterables with an error handler?
<p>Suppose we have two kinds of methods: one returns a list, the other returns an iterator. So they are very comparable in the sense that both return values are iterable.</p> <p>I'd like to write a decorator that catches errors inside the iteration. The problem is that the iterator is returned without iteration and so ...
<python><error-handling><generator><decorator><iterable>
2023-01-13 13:30:07
1
846
Paul
75,109,865
12,011,020
Python: kedro viz SQLAlchemy DeprecationWarning
<p>I tried to work with kedro and started with the spaceflight tutorial. I installed the src/requirements.txt in a .venv. When running <code>kedro viz </code>(or <code>kedro run</code> or even <code>kedro --version</code>), I get lets of Deprecation Warnings. One of which is the following (relating to kedro viz)</p> <p...
<python><sqlalchemy><dependencies><kedro>
2023-01-13 13:28:23
1
491
SysRIP
75,109,854
3,105,485
How to get the precise position of an error within the line in Python
<p>How to get the precise position of an error within the line in Python? The Python interpreter gives the line of the error and the type of the Error, but if there are more points in the line that could cause that error then there is ambiguity, here is a toy example:</p> <p><code>example.py</code></p> <pre><code>xs = ...
<python><exception><runtime-error><error-messaging>
2023-01-13 13:27:40
1
6,751
Caridorc
75,109,379
12,018,177
Why Pytorch Dataset class does not returning list?
<p>I am trying to use torch.utils.Dataset on a custom dataset. In my dataset, in a single row I have a list of 10 images like as follow:</p> <pre><code>| word | images | gold_image | |:-----|:-------|:-----------| |'andromeda'|['image.1.jpg','image.2.jpg','image.3.jpg']|[0,0,1]| </code></pre> <p>I expect to return batc...
<python><pytorch><dataset><huggingface-datasets>
2023-01-13 12:42:55
1
383
Shantanu Nath
75,109,307
7,497,912
How to open a document from a Notes View with python noteslib?
<p>I have an established connection with a notes database and I am able to loop through all the records in a view. What I am curious about if it is possible to open a document and get the data from it using python. (Like double clicking on a record from an HCL Notes Client). Here is my code simplified:</p> <pre><code>i...
<python><lotus-notes><hcl-notes>
2023-01-13 12:37:30
1
417
Looz
75,108,992
7,558,835
Is it possible to have a Spark DataFrame partitioned by multiple columns, and at the same time partitioned by all the individual columns?
<p>To get more efficient joins in pyspark, I would like to repartition my dataframes on multiple columns at the same time.</p> <p>This is not what the <code>repartition</code> function already does. For example, if I am partitioning on columns 'c1' and 'c2', the <code>reparition</code> function only ensures that all ro...
<python><python-3.x><apache-spark><pyspark><apache-spark-sql>
2023-01-13 12:07:39
0
1,164
Diego Palacios
75,108,952
8,661,471
Converting Matplotlib axis to log only updates labels and not step spacing
<p>I am trying to scale the space on the vertical axis here so it is spaced logarithmically.</p> <p>After searching the internet the proposed solution was</p> <pre><code>ax.set_zscale('log') </code></pre> <p>After trying that you can see the result below that only the labels where changed and not the actual spacings.</...
<python><matplotlib><data-analysis>
2023-01-13 12:03:46
1
694
codeThinker123
75,108,872
17,124,619
Invalid identifier in sql create table query
<p>I understand from online articles that this issue is related to case-sensitivity with oracle sql. However, I cannot see the error in my query: For example:</p> <pre><code>ENGINE = create_engine('credentials', pool_pre_ping = True) connection = ENGINE.raw_connection() cursor = connection.cursor() cursor.execute(&q...
<python><sql><cx-oracle>
2023-01-13 11:55:51
0
309
Emil11
75,108,871
8,489,687
How to read the logs of the DagFile Processor Process in Airflow?
<p>I have a python file that generates logs dynamically, reading from a table in a database. I always edit this file blindly because I can't debug the execution of it.</p> <p>I know Airflow triggers a subprocess to process this file (the <code>DagFileProcessorProcess</code>), I just want to be able to read the logs of ...
<python><logging><airflow>
2023-01-13 11:55:50
1
355
Yago Dórea
75,108,809
1,668,622
How can a pre-built Python-installation be modified to work in another directory?
<p>For a project shipping with a pre-built customized Python distribution I need to be able to compile packages from source using <code>pip</code> (within the installed environment).</p> <p>This is what the file system structure for two installations of the final product might look like:</p> <pre><code>/opt ├── my-prog...
<python><pip><distutils>
2023-01-13 11:50:06
0
9,958
frans
75,108,790
4,451,521
How to convert a difference in timestamp to miliseconds?
<p>I have two dates in timestamp and their difference is</p> <pre><code>dt 0.006951093673706055 </code></pre> <p>dt is: <code>(1669983551.287477-1669983551.280526)</code></p> <p>I want to generate several dates (in datetime) with that difference</p> <p>Now normally I would do</p> <pre><code>date_list = [datetime.now() ...
<python><datetime><time><timedelta>
2023-01-13 11:47:59
1
10,576
KansaiRobot
75,108,709
6,029,488
Python Pandas: groupby.diff calculates difference between the last element of a group and the first element of the following group
<p>I have the following - already sorted - pandas dataframe:</p> <pre><code>instrumentExtId Date proxyMethod isForceXS xsValue curveValue .ID1 2008-03-28 00:00:00 CrossSectional FALSE 6.86046681 6.86046681 .ID1 2008-03-31 00:00:00 CrossSectional FALSE 6.9746...
<python><pandas><group-by><diff>
2023-01-13 11:40:08
1
479
Whitebeard13
75,108,586
9,510,800
How to sum up the value from previous row to subsequent rows pandas
<p>I have a dataframe with the below specs</p> <pre><code> | ID | Name| count | | -- |---- | ---- | | 1 | A | 75 | | 2 | B | 10 | | 3 | A | 15 | | 4 | A | 10 | | 5 | A | 5 | | 6 | A | 3 | </code></pre> <p>If I set the threshold for the count to be 1...
<python><pandas><numpy>
2023-01-13 11:29:20
1
874
python_interest
75,108,567
10,409,093
MongoDB: conditional updates considering arrays as unordered
<p>I need each document in a collection to be updated only if its content is different, regardless of the order of the elements in nested lists.</p> <p>Fundamentally, two versions should be the same if the elements are identical regardless of their order. MongoDB does not do that, by default.</p> <pre><code>def upsert(...
<python><mongodb><pymongo>
2023-01-13 11:26:41
2
2,177
Whole Brain
75,108,533
20,999,526
Why signInWithPopup() does not work with pywebview?
<p>I am trying google sign in with firebase and trying to load the page through pywebview.</p> <pre><code>from tkinter import * import webview as webview root = Tk() win_width = root.winfo_screenwidth() win_height = root.winfo_screenheight() root.geometry(&quot;%dx%d&quot; % (win_width, win_height)) webv...
<python><firebase><firebase-authentication><google-signin><pywebview>
2023-01-13 11:21:31
3
337
George
75,108,476
12,268,570
Unable to view in-memory table from SQLite database in PyCharm
<p>I am using PyCharm to capture some data from web and push it into in-memory database-table on SQLite. I have debugged the code, it works fine, in the debugger I can see data being fetched, it being pushed into db[table] location.</p> <p>Python code is as below -</p> <pre><code>import requests import dataset from bs4...
<python><sqlite><pycharm>
2023-01-13 11:15:47
0
646
Amogh Sarpotdar
75,108,450
1,186,904
How to override the default login for Django rest framework browsable API
<p>I have a Django Rest Framework (DRF) application and when we are using the browseable API page and click login it goes to the default Django login page. I want to override it to another page.</p> <p>Default api: <code>https://my-app/api-auth/login/ </code> But the new login page I want is this: <code>http://my-app/s...
<python><django><django-rest-framework><okta>
2023-01-13 11:12:41
1
823
najeeb
75,108,405
12,450,117
Access Scalene Profile Object via Python Code
<p>I want to access the profiler output in python code after scalene_profiler.stop() but I cant seem to find any function that can give me access to it? The reason i need it is because I want the time-consumed in seconds instead of the Percentages that are in the report generated, and I want to save this data in my own...
<python><profiling><scalene>
2023-01-13 11:08:54
0
480
Ramsha Siddiqui
75,108,358
12,103,188
How to display a 3D plot in Python?
<p>I have the following code segment, but when I run it I only get a blank white screen and the plot is not displayed. I'm using Python 3.10.9. Any ideas about the issue?:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt from matplotlib import cm from mpl_toolkits.mplot3d import Axes3D def np_bivariat...
<python><matplotlib>
2023-01-13 11:04:45
1
469
terett
75,108,339
20,999,380
Python cannot find a file that is definitely there
<p>I am trying to upload an MP3 file and play it using pydub:</p> <pre><code>import pydub from pydub import AudioSegment from pydub.playback import play blast_file = AudioSegment.from_mp3( &quot;C:/Users/am650/Downloads/radio_static.mp3&quot;) </code></pre> <p>From this, I get the fo...
<python><windows><pydub>
2023-01-13 11:03:23
1
345
grace.cutler
75,108,175
11,737,958
AttributeError: class object has no attribute
<p>I am new to python. I try to access the attribute <strong>acnt_amount</strong> from the class bank_Customer, but throws &quot;AttributeError&quot; error. How to access the attribute of the function <strong>getDetails</strong> to <strong>withdraw</strong> with in the class from one function to another function? What...
<python>
2023-01-13 10:48:07
3
362
Kishan
75,107,982
10,924,836
Choropleth map in Python
<p>Below you can see one example with the Choropleth map for Italy. Below you can see an example :</p> <pre><code>import pandas as pd import geopandas as gpd regions = ['Trentino Alto Adige', &quot;Valle d'Aosta&quot;, 'Veneto', 'Lombardia', 'Emilia-Romagna', 'Toscana', 'Friuli-Venezia Giulia', 'Liguria', 'Piemonte', ...
<python><geopandas><choropleth>
2023-01-13 10:32:29
1
2,538
silent_hunter
75,107,892
4,622,046
Write pandas dataframe (from CSV) to BigQuery in batch mode
<p>I have a list of csv files, I want to copy the rows and push them to BQ sequentially. At the moment, I am using pandas to read the csv files, and the <code>to_gbq</code> method to get the data in bigquery. However, since the files are big (few gigs each), I wanted to ingest the data in a batch mode to avoid any memo...
<python><pandas><google-bigquery>
2023-01-13 10:24:54
1
11,318
Zabir Al Nazi Nabil
75,107,845
1,717,026
Json field truncated in sqlalchemy
<p>I am getting my data from my postgres database but it is truncated. For VARCHAR, I know it's possible to set the max size but is it possible to do it too with JSON, or is there an other way?</p> <p>Here is my request:</p> <pre class="lang-py prettyprint-override"><code>robot_id_cast = cast(RobotData.data.op(&quot;-&...
<python><json><sqlalchemy>
2023-01-13 10:20:56
1
3,265
David Bensoussan
75,107,763
10,197,418
Why binary mode when reading/writing TOML in Python?
<p>When reading a <code>toml</code> file in normal read (<code>&quot;r&quot;</code>) mode, I get an error</p> <pre class="lang-py prettyprint-override"><code>import tomli with open(&quot;path_to_file/conf.toml&quot;, &quot;r&quot;) as f: # have to use &quot;rb&quot; ! toml_dict = tomli.load(f) </code></pre> <block...
<python><utf-8><toml>
2023-01-13 10:15:27
1
26,076
FObersteiner
75,107,749
1,889,762
Poetry self update hangs
<p>When running <code>poetry update</code>, as well as other related commands, I get the process stuck at</p> <pre><code>Resolving dependencies... </code></pre> <p>I'm using poetry version 1.2.2, so I wanted to upgrade it by running <code>poetry self update -vvv</code></p> <p>The process hangs indefinitely at this poin...
<python><python-poetry>
2023-01-13 10:14:31
2
3,760
HAL9000
75,107,569
16,332,690
Databricks not saving dataframes as Parquet properly in the blob storage
<p>I am using Databricks with a mounted blob storage. When I execute my Python notebook which creates large pandas DataFrame and tries to store them as .parquet files they show up having 0 bytes.</p> <p>The saving takes place in a submodule that I import and not in the main notebook itself. The strange this is that sav...
<python><azure><blob><databricks><parquet>
2023-01-13 09:59:34
1
308
brokkoo
75,107,534
10,924,836
Extracting years from data
<p>I want to extract data for years in the table below. Data are in the format <code>datetime64</code> and this data you can see below</p> <pre><code>import numpy as np import pandas as pd data = { 'Date': ['2021-01-01','2020-01-01','2019-01-01','2028-01-01'] } df = pd.DataFrame(data, columns = ['Dat...
<python><time>
2023-01-13 09:56:13
2
2,538
silent_hunter
75,107,525
4,291,923
Create pivot table from DataFrame with value columns on the "bottom"
<p>There is a dataframe:</p> <pre class="lang-py prettyprint-override"><code>df = pd.DataFrame.from_dict({ 'A': ['A1','A1','A1','A1','A2','A2','A2','A2'], 'B': ['B1','B1','B2','B2','B3','B3','B4','B4'], 'C': ['one','two','one','two','one','two','one','two'], 'D': [0, 0, np.nan, 1, 0, np.nan, 1, 1], ...
<python><pandas><dataframe><pivot-table>
2023-01-13 09:55:10
1
510
koshachok
75,107,407
6,682,498
Issue in using __repr__ function to return a non-string value from a method in a class
<p>I have a class that contains an <code>__init__</code> method, a method which changes the init value and a <code>__repr__</code> function that wants to print out the adjusted value</p> <p>The draft of the code is as follows</p> <pre><code>class Workflow: def __init__(self, a): self.a = a def b...
<python>
2023-01-13 09:45:57
3
389
Pak Hang Leung
75,107,329
9,850,681
How to return an object after insert with sqlalchemy?
<p>I would like to retrieve the object after inserting it into the database, by object I mean the Base class. Some examples:</p> <pre class="lang-py prettyprint-override"><code>class EdaToken(Base): __tablename__ = &quot;eda_token&quot; &quot;&quot;&quot;id, primary key&quot;&quot;&quot; id = Column( ...
<python><sqlalchemy><fastapi>
2023-01-13 09:38:24
1
460
Plaoo
75,107,327
6,195,489
Is it possible to use zoom from one graph in a Dash app to select input for second graph
<p>I have a dash app that plots a dataframe which has a date component, and an entry that is either true or false. There are two graphs in the dashboard, one with the data vs date, and one with a percentage of True/False like below:</p> <p><a href="https://i.sstatic.net/xGIPN.png" rel="nofollow noreferrer"><img src="ht...
<python><plotly-dash>
2023-01-13 09:38:12
1
849
abinitio
75,107,276
14,037,055
How many images are generated when Image augmentation is used (either for individual image or for all image)
<p>How can I determine how many images will be created after image augmentation via tensorflow ImageDataGenerator. What will be that number for an individual image and likewise all images.</p> <p>I have total 17 image (16 image for train and 1 image for test)</p> <pre class="lang-py prettyprint-override"><code> impo...
<python><tensorflow><data-augmentation><image-augmentation>
2023-01-13 09:33:55
0
469
Pranab
75,107,072
5,810,060
Iterating over 2 columns and comparing similarities in Python
<p>I have a DF that looks like this:</p> <pre><code>Row Account_Name_HGI company_name_Ignite 1 00150042 plc WAGON PLC 2 01 telecom, ltd. 01 TELECOM LTD 3 0404 investments limited 0404 Investments Ltd </code></pre> <p>what I am trying to do is to iterate thro...
<python><python-3.x><pandas><for-loop><similarity>
2023-01-13 09:15:27
2
906
Raul Gonzales
75,106,834
10,062,025
Scrape shopee using request is getting error type 2
<p>I am trying to scrape shopee sites using requests. With an example site <a href="https://shopee.co.id/Paha-Fillet-Ayam-Organik-Lacto-Farm-500gr-Paha-Fillet-Segar-Ayam-Probiotik-Organik-Paha-Boneless-Ayam-MPASI-Ayam-Sehat-Ayam-Anti-Alergi-Daging-Ayam-MPASI-i.382368918.8835294847" rel="nofollow noreferrer">https://sho...
<python><python-requests>
2023-01-13 08:50:38
1
333
Hal
75,106,725
3,088,891
How can I use .on(fig) without distorting the legend position in seaborn.objects?
<p>I am creating a plot in <strong>seaborn.objects</strong>. This plot has a legend, and I would also like to change its size.</p> <p>This can be done using the <code>.theme()</code> method, which affects the <strong>matplotlib</strong> <code>rcParams</code>:</p> <pre class="lang-py prettyprint-override"><code>import m...
<python><matplotlib><seaborn><seaborn-objects>
2023-01-13 08:40:40
1
1,253
NickCHK
75,106,677
572,616
Is it necessary to use abc.ABC for each base class in multiple inheritance?
<p>Consider the following code snippet:</p> <pre><code>import abc class Base(abc.ABC): @abc.abstractmethod def foo(self): pass class WithAbstract(Base, abc.ABC): @abc.abstractmethod def bar(self): pass class WithoutAbstract(Base): @abc.abstractmethod def bar(self): ...
<python><multiple-inheritance><abc>
2023-01-13 08:36:40
2
14,083
Woltan
75,106,657
3,062,183
Marshmallow schema from pydantic model
<p>Given <code>pydantic</code> models, what are the best/easiest ways to generate equivalent <code>marshmallow</code> schemas from them (if it's even possible)?</p> <p>I found <a href="https://gist.github.com/kmatarese/a5492f4a02449e13ea85ace8801b8dfb" rel="nofollow noreferrer">this snippet</a> and some other similar l...
<python><pydantic><marshmallow>
2023-01-13 08:34:50
0
1,142
Dean Gurvitz
75,106,643
5,901,318
django template rendering error when template have comparison 'equal'
<p>I got problem about template rendering in django. It's show up when there is kind of integer comparison with '=='.</p> <p>I have a view like ..</p> <pre><code> def mailtemplate_GetSchema(request, id=None): if id == None: svars = [] this_var = {} this_var['s_id']=str(uuid4()) this_var['varname'] = f...
<python><django><django-templates><jinja2>
2023-01-13 08:32:47
2
615
Bino Oetomo
75,106,604
2,201,789
RobotFramework to delete older folder or file
<p>I want to delete folders/files when its modified date is older than today date &lt;5 days.</p> <p>below is the sample test that I written in Robot Framework.</p> <p>The execution of test is passed and all content is deleted.</p> <p>This example, I have set the current year to 2022 so 2022 not equal to 2023 and delet...
<python><robotframework>
2023-01-13 08:28:40
1
1,201
user2201789
75,106,452
3,423,825
How to combine two or more QuerySets from different models and order objects chronologically?
<p>I have two querysets I need to combine and iterate through the objects chronologically, based on a <code>datetime</code> field which is common to both models. What is the best way to do that ?</p> <p>I'm able to combine querysets with <code>union</code> but objects are not sorted properly.</p> <pre><code>model_combi...
<python><django>
2023-01-13 08:14:47
1
1,948
Florent
75,106,356
1,436,800
Unable to apply migration on altered model in django
<p>I am new to django. I have changed some fields in my already created Django model. But It says this message when I try to apply migrations on it:</p> <pre><code>It is impossible to add a non-nullable field 'name' to table_name without specifying a default. This is because the database needs something to populate exi...
<python><django><django-models><django-rest-framework><django-migrations>
2023-01-13 08:03:50
1
315
Waleed Farrukh
75,106,282
6,753,182
How to reindex a datetime-based multiindex in pandas
<p>I have a dataframe that counts the number of times an event has occured per user per day. Users may have 0 events per day and (since the table is an aggregate from a raw event log) rows with 0 events are missing from the dataframe. I would like to add these missing rows and group the data by week so that each user h...
<python><pandas><multi-index><datetimeindex>
2023-01-13 07:56:52
1
3,290
FirefoxMetzger
75,106,167
3,247,006
How to hide the column assigned to "list_display" and "list_display_links" for "list_editable" in Django?
<p>I have <strong><code>Person</code> model</strong> below:</p> <pre class="lang-py prettyprint-override"><code># &quot;store/models.py&quot; from django.db import models class Person(models.Model): first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) </code></pre> <p>Then,...
<python><django><django-admin><hide><changelist>
2023-01-13 07:43:31
2
42,516
Super Kai - Kazuya Ito
75,106,098
11,795,964
How to apply itertools to a series
<p>I have a dataset of patient surgery. Many of the patients have had multiple operations and the value_counts aggregation of their multiple operation codes (there are 4 codes) is shown below.</p> <pre><code>['O011'] 2785 ['O012'] 1813 ['O011', 'O011...
<python><python-itertools>
2023-01-13 07:35:45
1
363
capnahab
75,106,068
4,835,496
GeoPandas: Apply function to row multiple time
<p>I have a GeoDataFrame with the following columns. The column <em>node_location</em> is a dictionary of OSM node IDs with the corresponding coordinates.</p> <pre><code>{ &quot;geometry&quot;: LineString(LINESTRING (8.6320625 49.3500941, 8.632062 49.3501782)), &quot;node_locations&quot;: {75539413: {&quot;lat&...
<python><geopandas>
2023-01-13 07:32:26
1
1,681
Kewitschka