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,936,981
6,702,598
Python venv: automatically install requirements.txt when entering venv
<p>How do I setup my virtual environment (<code>venv</code>) to automatically install all <code>requirement</code>s (<code>.txt</code>) upon activation?</p> <h5>Unsatisfying workaround:</h5> <p>I created a file <code>activate_venv.sh</code></p> <pre><code>source venv/bin/activate pip install -r requirements.txt </code>...
<python><python-venv><requirements.txt>
2022-12-28 06:34:39
1
3,673
DarkTrick
74,936,903
1,927,609
Why do some os functions ignore trailing spaces on Windows?
<p>I've tried the example program below on both Windows and Linux with Python 3.11.0.</p> <pre class="lang-py prettyprint-override"><code>import os if __name__ == &quot;__main__&quot;: directory_name = &quot;foo &quot; file_name = &quot;bar.txt&quot; os.mkdir(directory_name) print(os.path.exists(direct...
<python><windows><directory><whitespace>
2022-12-28 06:22:06
1
1,483
Andrew Tapia
74,936,843
19,458,490
How can I select the entire import statements using regular expressions?
<p>I'm writing a static code analysis tool in Python.</p> <p>Here's a sample of a code that needs to be analyzed:</p> <pre><code>import { component$, useClientEffect$, } from '@builder.io/qwik' import Swiper from 'swiper' import { Navigation, Pagination } from 'swiper' import { Image } from 'Base' impo...
<python><regex><code-analysis><static-code-analysis>
2022-12-28 06:12:51
1
624
Mohammad Miras
74,936,697
10,934,636
How to open multiple persistent chrome profiles using playwright
<p>I have some Chrome profiles in which I have my different accounts logged in. I'm writing a multi-threaded script that will run each profile using <code>launch_persistent_context</code> so that I'm already logged in and script starts working from thereon.</p> <p>I'm using Playwright, on Windows 10.</p> <p>Here's my c...
<python><playwright-python>
2022-12-28 05:50:56
1
712
stuckoverflow
74,936,605
14,627,505
Merge 2 dfs, with the row if it is the only row that contains the word
<p>I have 2 pandas data frames:</p> <pre class="lang-py prettyprint-override"><code>df1 = pd.DataFrame({'keyword': ['Sox','Sox','Jays','D', 'Jays'], 'val':[1,2,3,4,5]}) df2 = pd.DataFrame({'name': ['a b c', 'Sox Red', 'Blue Jays White Sox'], 'city':[f'city-{i}' for i in [1,2,3]], ...
<python><pandas><regex><dataframe><merge>
2022-12-28 05:37:47
2
3,903
Vladimir Fokow
74,936,282
10,305,444
tf.strings.operations raises TypeError: Value passed to parameter 'input' has DataType string not in list of allowed
<p>I'm trying to create a superficial layer to pre-process data inside models. Here is an my Layer:</p> <pre><code>class StringLayer(tf.keras.layers.Layer): def __init__(self): super(StringLayer, self).__init__() def call(self, inputs): return tf.strings.join([some_python_function(word) for word in tf.stri...
<python><tensorflow><keras>
2022-12-28 04:34:48
0
4,689
Maifee Ul Asad
74,936,103
3,277,133
How to pivot and stack dataframe in pandas without group by while having duplicate values in the pivot?
<p>I have df that looks like this:</p> <pre><code>ref text id a zz 12eia a yy radf02 b aa a8adf b bb 2022a </code></pre> <p>I am trying to rotate this dataframe to look like below with values in column <code>ref</code> becoming column names and values in <code>tex...
<python><pandas>
2022-12-28 03:56:24
1
3,707
RustyShackleford
74,936,051
8,901,144
PySpark drop Duplicates and Keep Rows with highest value in a column
<p>I have the following Spark dataset:</p> <pre><code>id col1 col2 col3 col4 1 1 5 2 3 1 1 0 2 3 2 3 1 7 7 3 6 1 3 3 3 6 5 3 3 </code></pre> <p>I would like to drop the duplicates in the column...
<python><pyspark><duplicates>
2022-12-28 03:44:05
2
1,255
Marco
74,935,787
4,503,546
How do I convert rows into a calendar performance table using Python/Pandas or Excel?
<p>I have 2 columns which hold dates and performance returns by month back several years. The data is in a csv and looks like this:</p> <pre><code>Date: Return 12/2022: -1% 11/2022: +2% 10/2022: +1% ... 1/2002: -1% </code></pre> <p>I want to convert this into a more traditional performance table/matrix which has a...
<python><excel><pandas><dataframe>
2022-12-28 02:41:32
2
407
GC123
74,935,545
15,542,245
Order of dictionary key/values changes output of script
<p>The problem occurs in a script processing lines of text like the following:</p> <pre><code>import re combo_dict = { 'Mngr': 'Manager', 'Shp': 'Shop' } rexCapDoubleWord = '(?s)\s([A-z]+\s[A-z]+)$' fileLines = ['001 AALTONEN Alan Roy 2 Berkeley_Road,_Welltown Shp Mngr'] for fileLine in fileLines: ...
<python><dictionary>
2022-12-28 01:49:33
2
903
Dave
74,935,303
6,346,514
Python, Looping through subdirectories for zip files, OS Error Invalid Argument \\
<p>I am trying to look into my directory for zip files and perform a function on them. It does seem to loop through some of the files correctly but gets stuck with <code>OS Error \\</code></p> <p>Directory structure is like:</p> <pre><code> //Stack/Over/Flow/2022 - 10/Original.zip //Stack/Over/Flow/2022 - 09/Next fi...
<python><pandas>
2022-12-28 00:45:42
0
577
Jonnyboi
74,935,217
3,696,490
QTableWidget truncate beginning of long cell instead of end
<p>I am creating a GUI in pyqt and I use QTableWidget to show some list of files.</p> <p>When the string in a cell is too long, the end is truncated and replaced by &quot;...&quot;. Like in this photo <a href="https://i.sstatic.net/eyYE9.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/eyYE9.png" alt="en...
<python><qt><pyqt><pyqt5>
2022-12-28 00:25:33
0
550
user206904
74,935,202
8,439,343
InvalidArgumentError: Graph execution error:
<p>when running this script, I get an error when calling the model.fit(dataset, epochs=5) method when I want to train the model and I get the error InvalidArgumentError: Graph executes error:</p> <p>`</p> <pre><code>import nltk nltk.download('punkt') nltk.download('wordnet') nltk.download('stopwords') nltk.download('om...
<python><tensorflow><machine-learning><chatbot>
2022-12-28 00:23:08
1
311
Lucas Torres
74,934,919
2,359,865
construct a python rich tree from list of descendants
<p>I am trying to construct a python <code>rich.Tree</code> from a list of descendants, <code>d</code>.</p> <pre><code>d = {0: [1, 2], 2: [3, 4, 5], 4: [6, 7]} </code></pre> <p>I expect to get something like this:</p> <pre><code># manually constructed string expected = \ &quot;&quot;&quot; 0 ├── 1 └── 2 └── 3 └...
<python><tree><descendant><rich>
2022-12-27 23:21:45
2
462
acortis
74,934,918
2,265,682
Run an async function from a sync function... without knowing whether there is already a running event loop?
<p>So it is a common question for someone first coming to python's async to ask, &quot;how do I run an async function from a sync function?&quot; Hopefully if you're here you already know that the answer to that question is <code>asyncio.run()</code>.</p> <p>But this is <em>not</em> really the answer. Because suppose I...
<python><python-asyncio>
2022-12-27 23:21:44
0
421
FishFace
74,934,917
4,164,680
Neural Network on the Iris dataset convergaes very quickly
<p>I'm tasked with writing a ANN using only NumPy (no TensorFlow, PyTorch , etc.) on the iris dataset. I'm running 2000 epochs and it seems by the time of epoch 40 the accuracy of the network stays at 0.66. Also the parameters while debugging are either extremely high or extremely low (for example, for <code>self.layer...
<python><numpy><neural-network><iris-dataset>
2022-12-27 23:21:24
1
351
Amit Toren
74,934,901
17,553,278
How can I print a day and a time using Python strftime?
<p><strong>Context:</strong> I'm trying to format a day and time using Python's strftime function, but I'm encountering a &quot;ValueError.&quot; I want the output to be in the format &quot;1 day, 2:45:00&quot; to represent a valid datetime object. However, my current code is throwing the following error: &quot;ValueEr...
<python><python-datetime><valueerror><strptime><strftime>
2022-12-27 23:18:43
1
325
Baboucarr Badjie
74,934,871
11,633,074
python class function append on all instance of an object
<p>I wanted to make a script in order to manage my friends and I, walkie talkies. so I created 4 classes: a Range is a modification that can upgrade the walkie talkie a Walkie Talkie describe the radio and its possible mods(Range) a Person describe me or my friends and their radios a TalkieRangeData is a class to handl...
<python>
2022-12-27 23:10:44
0
436
lolozen
74,934,853
297,780
Fatal Python Error with SQLAlchemy connect_engine
<p>I'm trying to use Pandas to pull data from a remote DB2 database on an M1 Mac. My script works on a Windows 10 system, but I get a fatal error when I run from my Mac. I've never experienced fatal errors before so I'm not sure how to proceed with troubleshooting. Here's my code:</p> <pre><code>import pandas as pd fro...
<python><sqlalchemy><db2>
2022-12-27 23:06:00
0
1,414
Lenwood
74,934,746
2,266,881
Multiple responses/checkpoints in a flask env function from python
<p>I have a regular python script that runs some code and returns a response with some data in a flask environment. Now, i'm looking for a way to &quot;return&quot; or to somehow 'pass back' some kind of message to the request sender, without interrupting the process, to report the state of progress in the code (everyt...
<python><flask>
2022-12-27 22:47:37
0
1,594
Ghost
74,934,711
11,003,343
Couchbase / Python Access to sample project throws error UnAmbiguousTimeoutException error code 14
<p>I am trying to wrap my head arround couchbase DB. For that I am starting a couchbase cluster via docker-compose.</p> <pre class="lang-yaml prettyprint-override"><code>version: &quot;3.7&quot; services: couchbase1: # Starts a first node with the name couchbase1. image: couchbase:enterpri...
<python><docker-compose><couchbase>
2022-12-27 22:41:56
1
664
NameVergessen
74,934,678
20,652,094
How to combine columns into a new table - Python or R
<p>Scenario:</p> <p>If I have this table, let's call it <code>df</code>:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>survey_answer_1___1</th> <th>survey_answer_1___2</th> <th>survey_answer_1___3</th> <th>survey_answer_2___1</th> <th>survey_answer_2___2</th> </tr> </thead> <tbody> <tr> <...
<python><r><python-3.x>
2022-12-27 22:36:35
5
307
user123
74,934,618
3,311,276
Getting ModuleNotFoundError: No module named 'MySQLdb'
<p>I created a virtualenv with following installed:</p> <pre><code>$ pip freeze aniso8601==9.0.1 attrs==22.2.0 click==8.1.3 configparser==5.3.0 Flask==2.2.2 flask-restplus==0.13.0 Flask-SQLAlchemy==3.0.2 greenlet==2.0.1 itsdangerous==2.1.2 Jinja2==3.1.2 jsonschema==4.17.3 MarkupSafe==2.1.1 mysql-connector-python==8.0....
<python><mysql><sqlalchemy><mysql-python>
2022-12-27 22:26:20
2
8,357
Ciasto piekarz
74,934,456
2,601,293
Create an ISO9660 compliant filename using pycdlib
<p>I'm trying to implement the pycdlib <a href="https://clalancette.github.io/pycdlib/example-creating-new-basic-iso.html" rel="nofollow noreferrer">example-creating-new-basic-iso</a> example shown below. About half way down there is a line that reads, <code>iso.add_fp(BytesIO(foostr), len(foostr), '/FOO.;1')</code>. ...
<python><iso9660>
2022-12-27 22:00:30
2
3,876
J'e
74,934,405
7,397,195
Scrapy Xpath or CSS Selector for next chevron
<p>consider this url: <a href="https://www.yachtworld.com/boats-for-sale/type-power/class-power-sport-fishing/?length=40-970" rel="nofollow noreferrer">boat listing</a></p> <p>I'm trying various selector methods to select the following tag for following the results to subsequent pages.</p> <p><div class="snippet" data...
<python><css><xpath><scrapy>
2022-12-27 21:51:54
1
454
leeprevost
74,934,118
10,181,236
compute timeseries with values from a column of a pandas dataframe
<p>I have two dataframes df_t with columns: id, user_id, timestamp score and df_u with column user_id. A user_id in df_t may be repeated while it is unique in df_u. I want to compute a timeseries for each user_id of length 365, one step for each day of the year 2019. Each timestep needs to have the score of the user_id...
<python><pandas>
2022-12-27 21:05:49
0
512
JayJona
74,933,925
3,572,505
regex python catch selective content inside curly braces, including curly sublevels and \n chars
<p>regex python catch <strong>selective</strong> content inside curly braces, including curly sublevels</p> <p>The best explanation is a minimum representative example (as you can see is for .bib for those who know latex..). Here is the representative input raw text:</p> <pre><code>text = &quot;&quot;&quot; @book{book1...
<python><regex><curly-braces>
2022-12-27 20:37:05
3
903
José Crespo Barrios
74,933,907
1,822,494
Question about copies on assignment in numpy
<p>Consider the following piece of code:</p> <pre><code>import numpy as np a = np.zeros(10) b = a b = b + 1 </code></pre> <p>If I print <code>a</code> and <code>b</code>, I get</p> <pre><code>&gt;&gt;&gt; a array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]) </code></pre> <p>and</p> <pre><code>&gt;&gt;&gt; b array([1., 1.,...
<python><numpy>
2022-12-27 20:34:25
1
818
TheProofIsTrivium
74,933,774
2,743,931
SWIG python MacOS issue
<p>I'm using MacOS on M1 Pro Macbook and I want to build a minimalistic-example SWIG binding to python.</p> <p>I have a C++ file:</p> <pre><code>// mymodule.cpp int square(int x){ return x*x; } </code></pre> <p>interface file</p> <pre><code>//mymodule.i %module mymodule %{ extern int square(int x); %} extern int s...
<python><c++><swig>
2022-12-27 20:16:15
0
312
user2743931
74,933,710
3,209,087
How to extract NULL and empty strings from MySQL into csv using Python with "" for empty string and nothing (not even quotes) for NULL
<p>I am trying to select specific columns from a MySQL table into csv. This table has integers, varchar, NULL and empty strings. I want to differentiate between NULL and empty strings in specific way.</p> <p>For DB row content: <code>ABC, 123,,NULL,2022-12-22</code></p> <p>The csv should have: <code>&quot;ABC&quot;|&qu...
<python><mysql><pandas><dataframe>
2022-12-27 20:08:09
0
1,041
300
74,933,691
19,797,660
Custom function Weighted Moving Average using Pandas.DataFrame, for some reason the value drops to 0.0 after 26 iterations
<p>I am testing my functions that calculates price indicators and I have a strange BUG that I don't know how to resolve.</p> <p>EDIT: Columns in the csv I've shared are all lower case, in case of testing the function with this csv you'd like to use this code:</p> <pre><code>data = pd.read_csv(csv_path) data = data....
<python><pandas>
2022-12-27 20:05:51
2
329
Jakub Szurlej
74,933,658
558,619
Python: Async function that works in script (__main__) and IPython
<p>I am struggling to wrap my head around how to get a simple class to work in both IPython (I use spyder interactive interpreter, Jupyter notebook etc a lot), as well as a traditional script launched from command line.</p> <p>At the top of my script, I have:</p> <pre><code>import asyncio import nest_asyncio nest_async...
<python>
2022-12-27 20:01:31
0
3,541
keynesiancross
74,933,476
19,939,086
Finding a "good date" which has two or fewer different digits with an additional requirement
<p>I have a coding problem with determining a &quot;good date&quot; (more description below).</p> <p>I solved the original problem but got stuck on the follow-up problem. I attached my questions and solution to the original problem below. Thank you for your help in advance.</p> <h4>Original Problem:</h4> <blockquote> <...
<python><algorithm><date><datetime>
2022-12-27 19:36:24
3
938
KORIN
74,933,414
3,612,823
Cross Join, Compare Values, and Select Closest Match - More Efficient Way?
<p>I asked a similar question in sql format here: <a href="https://stackoverflow.com/questions/74909237/cross-join-compare-values-and-select-closest-match-more-efficient-way">Cross Join, Compare Values, and Select Closest Match - More Efficient Way?</a></p> <p>I have two tables with 3 columns each. I cross join and sub...
<python><pandas><numpy>
2022-12-27 19:28:19
1
1,053
Adam12344
74,933,280
157,971
How can I transform or query JSON data in my Github Workflow?
<p>I am using the <code>octokit/request-action</code> action in my Github Workflow to <a href="https://docs.github.com/en/rest/releases/releases?apiVersion=2022-11-28#get-a-release-by-tag-name" rel="nofollow noreferrer">obtain information about a certain Github Release via its tag name</a>:</p> <pre class="lang-yaml pr...
<python><json><github-actions><github-api>
2022-12-27 19:09:42
0
26,702
void.pointer
74,933,255
9,977,758
Tk button is not clickable and image is not loading
<p>I have created a GUI that shows data about videos from YouTube and allows me to select which video I want to download.</p> <p>The code works well, but for some reason some of the images don't load and I can't select the video.</p> <p>This is the result I get:</p> <p><a href="https://i.sstatic.net/LBg2Z.png" rel="nof...
<python><tkinter><tkinter-button><tkinter-photoimage>
2022-12-27 19:07:27
1
1,050
SagiZiv
74,933,254
3,928,553
Trichromy photography based on PIL
<p>I'm trying to imitate in a simple way (=&gt; without any I.A.) <a href="https://en.wikipedia.org/wiki/Trichromy" rel="nofollow noreferrer">the old trichromy process to colorize B&amp;W photographs</a>.</p> <p><a href="https://i.sstatic.net/dpFlP.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/dpFlP.jp...
<python><python-imaging-library><photography>
2022-12-27 19:07:06
1
617
Raphadasilva
74,933,141
3,405,980
python regex split function equivalent in golang
<p>I've below python code to match regex::</p> <pre><code>import re digits_re = re.compile(&quot;([0-9eE.+]*)&quot;) p = digits_re.split(&quot;Hello, where are you 1.1?&quot;) print(p) </code></pre> <p>It gives this output::   <code>['', '', 'H', 'e', '', '', 'l', '', 'l', '', 'o', '', ',', '', ' ', '', 'w', '', 'h',...
<python><regex><go><regex-group>
2022-12-27 18:53:48
2
3,962
harshavmb
74,933,076
14,676,485
How to extract array element from array column?
<p>I'm working with a dataset available here: <a href="https://www.kaggle.com/datasets/lehaknarnauli/spotify-datasets?select=artists.csv" rel="nofollow noreferrer">https://www.kaggle.com/datasets/lehaknarnauli/spotify-datasets?select=artists.csv</a>. What I want to do is to extract first element of each array in column...
<python><pandas>
2022-12-27 18:46:48
2
911
mustafa00
74,933,024
1,441,592
How to create new pandas dataframe column from file that contains json?
<p>I have a dataset with metadata about voice calls</p> <p>It looks like</p> <pre><code>Data columns (total 4 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 phone 100 non-null string 1 group_id 100 non-null int64 2 question_id 100 non-null in...
<python><pandas>
2022-12-27 18:40:01
1
3,341
Paul Serikov
74,932,923
1,230,479
Beautiful soup not loading new page after Selenium click
<p>The first page is loaded and parsed as expected but after the clicking on Next page, the BS4 does not get the new page from driver.page_source</p> <pre><code>from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.supp...
<python><selenium><selenium-webdriver>
2022-12-27 18:29:04
1
2,119
futurenext110
74,932,855
12,596,824
getting directories and subdirectories using python OS and outputting csv file
<p>I want to write Python code to create a CSV file based on getting information from a directory and subdirectories only if the subdirectory contains moo.</p> <pre><code>. ├── a.txt ├── b.txt ├── foo │ └── w.txt │ └── a.txt └── moo └── cool.csv └── bad.csv └── more └── wow.csv </code></pre> <p>...
<python><operating-system>
2022-12-27 18:21:36
1
1,937
Eisen
74,932,787
18,366,396
How to make python request (oauth2)
<p>i need to get the token for making the finale api rest requests. The specs of the api are:</p> <ol> <li><p><code>basicAuthentication</code> Use: the <code>client_id</code> and <code>client_secret</code> (both URL-encoded, RFC6749) separated by a semicolon &quot;{{client_id}}:{{client_secret}}&quot; <code>base64 e...
<python>
2022-12-27 18:12:42
1
841
saro
74,932,511
13,086,128
-1 < 2 == 1 False?
<p>I am comparing an equation in python:</p> <pre><code>-1 &lt; 2 == 1 </code></pre> <p>it gives <code>False</code> as output</p> <p>The Left Hand side of the <code>==</code>:</p> <p><code>-1 &lt; 2</code> which evaluates to <code>True</code></p> <p>Right Hand side of the <code>==</code> is:</p> <p><code>1</code></p> <...
<python><python-3.x><math>
2022-12-27 17:42:36
1
30,560
Talha Tayyab
74,932,426
11,135,962
Faster/better way to extract string with a substring present in a list?
<p>I have a couple of lists <code>generator = [&quot;one#zade&quot;, &quot;one#zaat&quot;, &quot;one#osde&quot;, &quot;one#za&quot;]</code> &amp; <code>accepted_channels = [&quot;zade&quot;, &quot;zaat&quot;]</code>.</p> <p>I am trying to extract elements from the <code>generator</code> list which have as a substring a...
<python><performance><for-loop>
2022-12-27 17:32:30
1
3,620
some_programmer
74,932,417
15,637,435
How to efficiently build ngrams based on categories in a dataframe
<h2>Problem</h2> <p>I have a dataframe that consists of text which belongs to a category. I now want to get the most commonly used n-grams (bigrams in the example) per category. I managed to do this, but the code for this is way too long in my opinion.</p> <h2>Sample Code</h2> <pre><code>import pandas as pd import nltk...
<python><pandas><nlp><nltk><n-gram>
2022-12-27 17:32:04
1
396
Elodin
74,932,372
11,642,909
Matplotlib animation update legend using ArtistAnimation
<p>I want to update the legends in using the ArtistAnimation from Matplotlib.</p> <p>I try to adapt this solution : <a href="https://stackoverflow.com/questions/49158604/matplotlib-animation-update-title-using-artistanimation">Matplotlib animation update title using ArtistAnimation</a> to the legend but it didn't worke...
<python><matplotlib>
2022-12-27 17:26:01
1
391
Pierre Marsaa
74,932,285
1,230,479
Python Selenium: Clicking on the next page not working
<p>I am using the following code to click on the next page, by clicking the next element.</p> <p>However this code is not working. Any thoughts on what I might be doing wrong.</p> <p>Final goal:</p> <p>Use BeautifulSoup on each of the pages.</p> <pre><code>from selenium import webdriver from selenium.webdriver.common....
<python><selenium><selenium-webdriver>
2022-12-27 17:17:01
1
2,119
futurenext110
74,932,013
9,874,393
Is this proper use of a ternary operator
<p>I want a short form the remove an element from a list and use the following:</p> <pre><code>&gt;&gt;&gt; a = [1, 2, 3, 4] &gt;&gt;&gt; val = 3 &gt;&gt;&gt; a.remove(val) if val in a else None &gt;&gt;&gt; a &gt;&gt;&gt; [1, 2, 4] &gt;&gt;&gt; val = 10 &gt;&gt;&gt; a.remove(val) if val in a else None &gt;&gt;&gt; a &...
<python>
2022-12-27 16:50:42
1
3,555
Bruno Vermeulen
74,932,007
6,734,243
is it possible to iterate a Tuple traitlets?
<p>I transformed some of my lib variable into <code>traitlets</code> and I'm facing an error when iterating on a <code>Tuple</code> even though this is possible with built-in <code>tuple</code>.</p> <pre class="lang-py prettyprint-override"><code>from traitlets import Tuple a = Tuple((1,2,4)).tag(sync=True) for i in a...
<python><python-traitlets>
2022-12-27 16:49:59
1
2,670
Pierrick Rambaud
74,931,838
8,207,701
Can't pickle local object 'EvaluationLoop.advance.<locals>.batch_to_device' PyTorch
<p>I'm trying to train a model using PyTorch Lightning.</p> <pre><code>trainer = pl.Trainer( logger = logger, max_epochs = N_EPOCHS, ) trainer.fit(model,data_module) </code></pre> <p>But while doing that, I'm getting the following error after a sanity check progress bar.</p> <pre><code>AttributeError: Can...
<python><pytorch><pytorch-lightning>
2022-12-27 16:34:25
2
1,216
Bucky
74,931,611
13,564,858
Function to find a continuous sub-array which adds up to a given number in python
<p>I want to know what's wrong in the below code. Will it consume more time to in some certain scenarios? Expected time complexity: O(n)</p> <pre><code>def subArraySum(self,arr, n, s): if sum(arr[0:n]) == s: return [1, n] if sum(arr[0:n]) &lt; s: return [-1] start = 0 i =1 sum_elements = 0 ...
<python><data-structures>
2022-12-27 16:11:44
1
429
Lucky Ratnawat
74,931,530
1,211,082
How to efficiently use PyMongo cursor
<p>Please propose ways to access data returned from <code>collections.find()</code> in an efficient manner.</p> <p>Is a <code>for</code> iteration the recommended way? How do I keep the character of a cursor being an <code>Iterable</code>?</p> <p>Thx</p>
<python><performance><pymongo><database-cursor>
2022-12-27 16:03:32
1
6,069
Martin Senne
74,931,513
5,431,283
Pandas loop over each line of a column and append the corresponding value in a new column
<p>I have the following CSV with EC2 instances in them:</p> <pre><code>instanceID,region i-0020cad819e7393c0,DUB i-00006ea9f2460375f,DUB </code></pre> <p>I want to create a column based on the tags of those instances, for example, the name of those instances.</p> <pre class="lang-py prettyprint-override"><code>import b...
<python><pandas>
2022-12-27 16:01:37
1
673
Daniel
74,931,485
5,281,811
Custom pattern matching with regular expressions and three lists
<p>i'm a newbie and i'm trying to build a custom pattern matcher with three dynamically generated lists with the same length. It's for a tool that stores three personal sensible informations, its not that important. I thought putting them into three lists would be good to do some custom pattern matching.<br> One list f...
<python><regex><list>
2022-12-27 15:59:06
2
373
Laz22434
74,931,418
8,665,843
Split large JSON file into smaller files
<p>I have a need to split very large json file (20GB) into multiple smaller json files (Say threshold is 100 MB).</p> <p>The Example file layout looks like this.</p> <p>file.json</p> <pre><code>[{&quot;name&quot;:&quot;Joe&quot;, &quot;Place&quot;:&quot;Denver&quot;, &quot;phone_number&quot;:[&quot;980283&quot;, &quot...
<python><json><linux><shell>
2022-12-27 15:52:45
2
1,405
kites
74,931,396
18,308,393
Logits and labels must have same shape for Keras model
<p>I am new to Keras and have been practicing with resources from the web. Unfortunately, I cannot build a model without it throwing the following error:</p> <blockquote> <p>ValueError: <code>logits</code> and <code>labels</code> must have the same shape, received ((None, 10) vs (None, 1)).</p> </blockquote> <p>I have ...
<python><tensorflow><keras>
2022-12-27 15:50:55
3
367
Dollar Tune-bill
74,931,393
12,242,085
How to replace values in column in one DataFrame by values from second DataFrame both have major key in Python Pandas?
<p>I have 2 DataFrames in Python Pandas like below:</p> <p>DF1</p> <pre><code>COL1 | ... | COLn -----|------|------- A | ... | ... B | ... | ... A | ... | ... .... | ... | ... </code></pre> <p>DF2</p> <pre><code>G1 | G2 ----|----- A | 1 B | 2 C | 3 D | 4 </code></pre> <p>And I need to replace val...
<python><pandas><dataframe><replace>
2022-12-27 15:50:41
2
2,350
dingaro
74,931,285
4,040,743
Python 2 Script to Python 3 in a Docker Container :: "No module named 'Queue'"
<p>I have a Python 2 script that I'm trying to run within the latest <a href="https://hub.docker.com/_/python" rel="nofollow noreferrer">Python docker container</a>. That container supports Python 3, and I thought could manually adapt the script. My manual adaptations worked just fine... except for this:</p> <p>The o...
<python><docker><module><version>
2022-12-27 15:39:51
1
1,599
Pete
74,931,219
16,389,095
How to load .mat file properly
<p>I'm trying to load a .mat file with this the code:</p> <pre><code>from scipy.io import loadmat matFile = loadmat('myFile.mat') print(matFile) </code></pre> <p><a href="https://i.sstatic.net/AMIsX.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/AMIsX.png" alt="enter image description here" /></a></p> ...
<python><matlab><scipy>
2022-12-27 15:33:23
0
421
eljamba
74,931,215
2,561,452
Imported module can not find input file that exists in same directory as the Python script?
<p>I have a Python program that uses the OpenAI Whisper module to transcribe audio to text. Unfortunately, despite passing a fully resolved path to that module, it crashes with an error saying it can't find the file. I know the file exists in the directory because as you can see from my code and output below, the scr...
<python><path><subprocess><createprocess>
2022-12-27 15:32:54
1
14,395
Robert Oschler
74,931,209
12,349,101
Getting Nth permutation of a sequence and getting back original using its index and modified sequence
<p>I know the most popular permutation algorithms (thanks to wonderful question/answer on SO, and other related sites, such as Wikipedia, etc), but I recently wanted to see if I could get the Nth permutation without exhausting the whole permutation space.</p> <p>Factorial comes to mind, so I ended up looking at posts s...
<python><algorithm><permutation>
2022-12-27 15:32:23
1
553
secemp9
74,931,165
5,982,721
RTSP connection issue on IP Camera
<p>I have flir blackfly s bfs-pge-04s2c-cs model ip camera. I have poe injector that is connected to router and to camera. I can find the camera ip. My problem is I cannot connect with rtsp.</p> <p>with EasyPySpin I can get a frame with the code below.</p> <pre><code>import cv2 import EasyPySpin cap = EasyPySpin.Video...
<python><connection><rtsp><ip-camera>
2022-12-27 15:27:44
2
487
nogabemist
74,931,079
7,333,766
Can I safely remove from __future__ import absolute_import in python 3 files?
<p>I am working on a project that used to use python 2, but does not anymore.</p> <p>I see many lines of code like these :</p> <pre><code>from __future__ import absolute_import </code></pre> <p><strong>Can I safely remove them all ?</strong></p> <p>From what I read, it seems it was only used in python 2 to mimic Python...
<python><python-3.x>
2022-12-27 15:18:42
1
2,215
Eli O.
74,931,053
7,058,363
How to make Plotly Pie charts the same size always
<p>I'm generating different Pie charts that have legends of different lengths. The problem is that when the legend is long, the Pie chart is smaller, I'd like to make the Pie chart always the same size.</p> <p>This is my code:</p> <pre class="lang-py prettyprint-override"><code>pie_chart = go.Pie(labels=labels, values=...
<python><charts><plotly>
2022-12-27 15:15:50
2
3,493
Genarito
74,930,978
7,805,917
Pyspark add columns to existing dataframe
<p>I have the following code to do the implementation of having multiple condition columns in a single dataframe.</p> <pre class="lang-py prettyprint-override"><code>small_list = [&quot;INFY&quot;,&quot;TCS&quot;, &quot;SBIN&quot;, &quot;ICICIBANK&quot;] frame = spark_frame.where(col(&quot;symbol&quot;) == small_list[0...
<python><pyspark><apache-spark-sql>
2022-12-27 15:07:41
2
3,836
Inder
74,930,970
39,939
In python flask with mysql, can I use the same connection throught the app life cycle?
<p>Here is my python flask code:</p> <pre><code>from flask import * import mysql.connector app = Flask(__name__) conn = mysql.connector.connect( host=&quot;&lt;my db host&gt;&quot;, user=&quot;&lt;my db user&gt;&quot;, password = &quot;&lt;my db password&gt;&quot;, database = '&lt;my db&gt;' ) @app.route('/po...
<python><flask><mysql-python><mysql-connector>
2022-12-27 15:07:00
1
4,915
yigal
74,930,955
11,956,484
Piviot dataframe with duplicate indexes without applying aggfunction
<p>I have data that is in long form. It looks like this</p> <pre><code>Analysis Mode SID Run ID Accession ID Analyte Concentration QC - 111522 QC L Be 0.01 QC - 111522 QC M Be 0.04 SAMPLE EM123 111522 E2214172001 Be ...
<python><pandas>
2022-12-27 15:05:50
1
716
Gingerhaze
74,930,934
11,795,918
Frappe save objects in another doctype based on the base doctype?
<p>I am tring to trigger an event to save doctype data based on another doctype.</p> <p>This is how my doctype are:</p> <ol> <li>Employee has a Job Role.</li> <li>Job Role has tow doctypes as Table 'Job Role Course Item' and 'Job Role Skill Item'.</li> <li>'Job Role Course Item' is a Table type linked with 'Course Temp...
<python><postgresql><query-builder><frappe>
2022-12-27 15:04:06
1
1,567
Dhia Shalabi
74,930,922
9,957,710
How to load a custom Julia package in Python using Python's juliacall
<p>I already know <a href="https://stackoverflow.com/questions/73070845/how-to-import-julia-packages-into-python">How to import Julia packages into Python</a>.</p> <p>However, now I have created my own simple Julia package with the following command: <code>using Pkg;Pkg.generate(&quot;MyPack&quot;);Pkg.activate(&quot;M...
<python><julia>
2022-12-27 15:03:17
1
42,537
Przemyslaw Szufel
74,930,795
5,172,570
Is it possible to iteratively build up legend entries through multiple plot function calls?
<p>Based on the question and answer here (<a href="https://stackoverflow.com/questions/40736920/line-plus-shaded-region-for-error-band-in-matplotlibs-legend;">Line plus shaded region for error band in matplotlib&#39;s legend</a> and similar to <a href="https://stackoverflow.com/questions/26217687/combined-legend-entry-...
<python><matplotlib><legend>
2022-12-27 14:52:38
3
381
Ben Vincent
74,930,743
14,676,485
How to extract array's element from column of arrays?
<p>I have a dataframe where one of the columns consist of arrays. I need to extract first element from each array in this column. So, for the first row it would be 'classical harp', for 2nd - 'classic persian pop' etc. Here is an example:</p> <p><a href="https://i.sstatic.net/qf5qz.png" rel="nofollow noreferrer"><img s...
<python><pandas>
2022-12-27 14:47:19
1
911
mustafa00
74,930,597
597,858
how do I breakdown a string in multiple components
<p>I have a string 'ABCAPITAL23JAN140CE'. This is the symbol for an option traded on stock exchange. ABCAPITAL part of the string is the company name. 23 is year 2023. JAN is for month. 140 is the strike price and CE is the type of the option.</p> <p>All these components can vary for different options.</p> <p>I need a ...
<python><string>
2022-12-27 14:33:25
4
10,020
KawaiKx
74,930,552
13,038,144
Matplotlib groupby scatter colormap Warning: " No data for colormapping provided via 'c' "
<p>I'm having issues with colormapping of simple scatter plots when created using pandas <code>groupby</code>.</p> <h3>Example</h3> <pre class="lang-py prettyprint-override"><code>import pandas as pd df = pd.DataFrame(data= {'class': ['A']*5 + ['B']*5, 'index': [i for i in range(10)], ...
<python><pandas><matplotlib><plot><scatter-plot>
2022-12-27 14:28:54
1
458
gioarma
74,930,492
1,492,613
is there a way to determine udisks default mount path?
<p>It can be <code>/media/</code> or <code>/media/$USER</code> or <code>/run/media/$USER</code> depends on distro or customization. Is there a unified way to get its value programmatically regardless distros?</p>
<python><bash><udisks>
2022-12-27 14:24:12
1
8,402
Wang
74,930,487
16,690,173
Difference in cv2.imshow window size with and without waitkey commented out
<p>I'm trying to use <code>cv2.imshow</code> to display a specific section of my screen.</p> <p>However, while running, I noticed the displayed window is smaller than expected. I've stepped through the code with the debugger and noticed that when <code>cv2.waitKey(1)</code> triggers the <code>cv2.imshow</code> window r...
<python><opencv>
2022-12-27 14:23:50
0
303
mak47
74,930,366
4,796,942
Conditionally format cells in a google sheet using pygsheets
<p>I am trying to learn how to conditionally format cells in a worksheet using pygsheets. The reason for this is to only allow the end user interacting with a google sheet to only be able to input values that are in the correct format.</p> <p>For example, how can we format the sheet so that:</p> <ul> <li>cells A2 to A5...
<python><google-sheets><formatting><gspread><pygsheets>
2022-12-27 14:12:12
1
1,587
user4933
74,930,335
2,301,970
Adjust matplotlib RadioButtons font size
<p>I wonder if anyone has an advice on how to adjust the font size on the <code>RadiouButtons</code> side text. Taking the <a href="https://matplotlib.org/stable/gallery/widgets/radio_buttons.html" rel="nofollow noreferrer">widget example</a> from matplotlib</p> <pre><code>import numpy as np import matplotlib.pyplot as...
<python><matplotlib><widget>
2022-12-27 14:09:48
1
693
Delosari
74,930,327
893,254
Python Pandas and Matplotlib - How can I control the relative size of the figure to text labels?
<p>Here is a figured produced by Python Pandas + Matplotlib</p> <p><a href="https://i.sstatic.net/Sqcc1.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/Sqcc1.png" alt="pandas and matplotlib bar graph" /></a></p> <p>The problem is obvious: The x-axis labels are too large relative to the overall figure siz...
<python><pandas><matplotlib><pdf>
2022-12-27 14:09:14
1
18,579
user2138149
74,930,294
2,409,793
Unable to use google.cloud (storage) from within a python script
<p>I am trying to run the following simple script</p> <pre><code>#!/usr/local/bin/python3.9 from google.cloud import storage client = storage.Client() for blob in client.list_blobs('my-bucket', prefix='some/path'): print(str(blob)) </code></pre> <p>This fails as follows:</p> <pre><code>▶ ./test.py Traceback (most...
<python><python-3.x><google-cloud-platform><gcloud>
2022-12-27 14:06:20
1
19,856
pkaramol
74,930,282
2,007,927
How to install cryptography library on Docker container?
<p>I develop our company website with Odoo 14. I installed Odoo on my local machine (<code>macOS Monterey (12.5.1)</code>) via Docker. I use Docker Desktop and I have created <code>docker-compose.yaml</code> taking <a href="https://hub.docker.com/_/odoo" rel="nofollow noreferrer">official Odoo docker image page</a> as ...
<python><docker><odoo><odoo-14>
2022-12-27 14:05:20
2
586
george
74,929,989
12,057,138
How can I get a value only if it exist else return an empty dict in one line?
<p>How to I check if a value exist and then return it and if it doesnt, return an empty dict {} (or any other operation) in one line?</p> <p>I currently do the following which is will crash on none existing value + I also feel it could be written in a much more <em>python</em> way:</p> <pre><code>if (test[0].value): ...
<python>
2022-12-27 13:39:34
3
688
PloniStacker
74,929,947
4,295,805
Twisted application ignoring a certain UNIX signal - is it possible?
<p>Let's say we have the following situation:</p> <p><code>kill &lt;pid&gt;</code> sends <code>SIGTERM</code></p> <p><code>kill -&lt;SIGNAL&gt; &lt;pid&gt;</code> sends <code>&lt;SIGNAL&gt;</code></p> <p>Sometimes, during development, I need to kill my application and restart it, at the moment - using the first type of...
<python><unix><signals><posix><twisted>
2022-12-27 13:35:38
2
1,345
Leontyev Georgiy
74,929,803
139,271
How to Retain Expicit Zero Values in a Python Scipy Sparse COO (Coordinate Format) Matrix?
<p>I create a COO matrix, with zero values in the data array. When I query the new COO matrix data array, I can see those zero values in the array. However, I cannot get the indices for those zero values. I use the nonzero() method to retrieve the indices and indices for those zero values are missing. Does anyone know ...
<python><scipy><sparse-matrix>
2022-12-27 13:21:13
1
484
JStrahl
74,929,673
1,807,163
How to get original payload body in except block after raise_for_status is called()
<p>I have a python web server endpoint that calls an external API</p> <pre><code> try: resp = requests.post( url, json={...}, ) resp.raise_for_status() resp_result = resp.json() except requests.exceptions.HTTPError as e: ...
<python><python-requests>
2022-12-27 13:07:54
1
5,201
rasen58
74,929,665
7,657,152
Download files using Python-Telegram-bot
<p>I was trying to download the file send by the user via telegram app using python script, I am using the Python-telegram-bot library, I was not able to download the file, below is my code.</p> <pre><code>from telegram.ext import ApplicationBuilder, MessageHandler, filters BOT_TOKEN = '...' # Enable logging logging....
<python><telegram><python-telegram-bot>
2022-12-27 13:07:09
2
564
Bhuvan Kumar
74,929,454
9,078,185
Pandas perform identical transformation on multiple dataframes where inline is not an option
<p>I have a situation where I want to <code>shift</code> multiple dataframes by one line. A <code>for</code> loop is the first thing that comes to mind, but that does not actually store the dataframe. Other SO posts suggest using the <code>inline=True</code> option, which works for certain transformations but not <code...
<python><pandas>
2022-12-27 12:47:54
2
1,063
Tom
74,929,204
11,998,258
Using processing.py in Anaconda
<p>On page below I read that processing.py is in fact &quot;add-on called Python Mode&quot;:</p> <p><a href="https://py.processing.org/tutorials/gettingstarted/" rel="nofollow noreferrer">https://py.processing.org/tutorials/gettingstarted/</a></p> <p>Does it mean that I cannot by any means use processing inside my pyth...
<python><anaconda><processing>
2022-12-27 12:22:06
1
302
RunTheGauntlet
74,929,195
15,775,069
Why is rust-mongodb library slow compared to c++ version?
<p>I've loaded this <a href="http://data.insideairbnb.com/spain/catalonia/barcelona/2022-09-10/data/calendar.csv.gz" rel="nofollow noreferrer">airbnb dataset</a> into a local mongodb(version 4.4.17) database called <code>sample_db</code> and collection called <code>barcelona_cal</code>. There are <code>6175334</code> ...
<python><c++><mongodb><rust>
2022-12-27 12:20:54
0
361
yuser099881232
74,928,639
11,092,636
When opening word file "/" doesn't work but "\\" does (package os in python)
<p>Create a <code>main.py</code> file and a <code>test.docx</code> file in the parent directory.</p> <p>This works:</p> <pre class="lang-py prettyprint-override"><code>import os os.startfile(&quot;..\\test.docx&quot;) </code></pre> <p>This does not</p> <pre class="lang-py prettyprint-override"><code>import os os.star...
<python><operating-system>
2022-12-27 11:21:20
1
720
FluidMechanics Potential Flows
74,928,552
707,145
Converting or printing all sections of rendered quarto document into html in one go
<p>I want to convert <a href="https://shiny.rstudio.com/py/docs/get-started.html" rel="nofollow noreferrer">Shiny for Python</a> document into pdf. Jumping to each section and then printing into pdf is possible. However, wondering if there is a more compact way to print all sections in a one go.</p>
<python><html><quarto><py-shiny>
2022-12-27 11:10:50
1
24,136
MYaseen208
74,928,500
5,680,504
Python module install error when I tried to pip numpy
<p>When I install <code>numpy</code> lib using <code>python -m pip install numpy==1.18.1</code> command, I got the following errors.</p> <pre><code>ramirami-pc:anomalydetector sclee01$ python -m pip install numpy==1.18.1 DEPRECATION: Configuring installation scheme with distutils config files is deprecated and will no ...
<python>
2022-12-27 11:03:47
3
1,329
sclee1
74,928,439
14,661,648
How to specify the years on an axis when using plot() on DateTime objects
<p>The plotting goes like this:</p> <p><code>plt.plot(df['Date'], df['Price'])</code></p> <p><code>df['Date']</code> consists of DateTime objects with several years and <code>df['Price']</code> are integers. However on the actual line graph, it automatically selects about 4 years spaced apart in the graph with large in...
<python><matplotlib>
2022-12-27 10:57:39
1
1,067
Jiehfeng
74,928,438
5,994,555
Using python 3.8 but importing pytest from 2.8 instead of 3.8
<p>I'm using python 3.8 but pytest keeps getting imported from 2.7 These are my commands:</p> <pre><code>python3.8 -m venv venv . ./venv/bin/activate pip3.8 install --upgrade pip pip3.8 install -U pytest pip3.8 install -r requirements.txt </code></pre> <p>Then I check:</p> <pre><code>(venv) xxx@xxx:~/Documents/my-dashb...
<python><pytest><version>
2022-12-27 10:57:32
1
497
Sabina Orazem
74,928,324
11,867,978
How to remove the Scientific notation E getting stored in CSV using Python without pandas?
<p>I am trying to get details from DB and store in CSV, but when i open the csv I see the rows for Id reflecting as below: Id 4.98518E+11</p> <p>How to remove the E+ from csv wihtout using Pandas.</p>
<python><amazon-web-services><dynamodb-queries>
2022-12-27 10:43:59
1
448
Mia
74,928,180
10,924,836
Probit regression in Python
<p>I am trying to implement Probit regression. Dependent values are credit which has integer values 0 and 1. The other three features are salaries, sales, and stores. Before I put in the model I scaled these three features with a Robust Scaler. Below you can see the result of the regression</p> <pre><code>import statsm...
<python><regression>
2022-12-27 10:27:05
0
2,538
silent_hunter
74,928,054
15,852,600
How do I create a new dataframe from another existing one by applying a changing formula?
<p>I have the following dataframe :</p> <pre><code>df_1 = pd.DataFrame({ 'col1' : [20, 60, 55, 80, 32, 33], 'col2' : [10, 16, 18, 12, 19, 20], 'col3' : [5, 2, 7, 9, 1, 2] }) </code></pre> <p>It has the following display:</p> <pre><code> col1 col2 col3 0 20 10 5 1 60 16 2 2 55 18 7 3 80 12 ...
<python><pandas><dataframe>
2022-12-27 10:14:37
1
921
Khaled DELLAL
74,928,052
12,181,414
SQLModel with Pydantic validator
<p>I want to use <code>SQLModel</code> which combines pydantic and SQLAlchemy.</p> <p>I have a <code>UserCreate</code> class, which should use a custom validator.</p> <p>This is my Code:</p> <pre><code>class UserBase(SQLModel): firstname: str lastname: str username: str email: str password: str ...
<python><sqlalchemy><pydantic><sqlmodel>
2022-12-27 10:14:29
1
2,155
Data Mastery
74,928,049
17,148,496
How to multiply all columns with each other
<p>I have a pandas dataframe and I want to add to it new features, like this:</p> <p>Say I have features <code>X_1,X_2,X_3 and X_4</code>, then I want to add <code>X_1 * X_2, X_1 * X_3, X_1 * X_4</code>, and similarly <code>X_2 * X_3, X_2 * X_4</code> and <code>X_3 * X_4</code>. I want to add them, not replace the orig...
<python><pandas>
2022-12-27 10:14:06
2
375
Kev
74,927,703
2,983,359
django: Page not found (404)
<p><a href="https://i.sstatic.net/15jEu.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/15jEu.png" alt="Project view" /></a></p> <p>project/urls.py</p> <pre><code>from django.contrib import admin from django.urls import path, include from django.http import HttpResponse urlpatterns = [ path(&quot;ad...
<python><django>
2022-12-27 09:36:01
3
1,035
bizimunda