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,959,903
13,132,728
How to efficiently round data in a streamlit dataframe
<p>Pandas' <code>.style.set_precision(2)</code> is completely stalling my streamlit app. Is there a more efficient way to round data that is displayed in a streamlit app using <code>st.dataframe</code>, <code>st.write</code>, or <code>st.table</code>?</p> <p>I am simply trying to round my dataframe to two decimals. My ...
<python><pandas><streamlit>
2023-04-07 15:38:06
2
1,645
bismo
75,959,757
3,503,228
Module installed using pip, but not found in python
<p>Installed calplot:</p> <pre class="lang-bash prettyprint-override"><code>$ pip install calplot Requirement already satisfied: calplot in /home/lamy/.local/lib/python3.10/site-packages (0.1.7.5) Requirement already satisfied: matplotlib in /home/lamy/.local/lib/python3.10/site-packages (from calplot) (3.7.1) Requirem...
<python><pandas><module>
2023-04-07 15:21:22
1
6,635
Porcupine
75,959,755
1,780,761
flask - send_file with lazy loading
<p>i have a huge table (80k rows) with an image in each row. i want to lazy load the images while scrolling. The images are stored in a directory outside flask, so i have to use send_file. this is my python code:</p> <pre><code>@app.route('/getLogImage/') def getLogImage(): fileName = request.args.get('fn', None) ...
<python><flask><lazy-loading>
2023-04-07 15:21:06
1
4,211
sharkyenergy
75,959,702
2,628,868
the docker build stuck at transferring context forever
<p>when I using this command to build docker <code>Docker version 20.10.14, build a224086</code> image in macOS 13.2 with M1 chip, the build process blocked in transferring context forever, this is the build log output:</p> <pre><code>โžœ docker build -f ./Dockerfile -t=reddwarf-pro/cha-server:v1.0.0 . [+] Building 318.6...
<python><docker>
2023-04-07 15:14:37
0
40,701
Dolphin
75,959,463
472,599
How to insert multiple records in a table with psycopg2.extras.execute_values() when one of the columns is a sequence?
<p>I am trying to insert multiple records in a single database call with the psycopg2.extras.execute_values(cursor, statement, argument_list) function. It works when I have a list with only strings or integers as field values. But I want the id field to be assigned from a postgres sequence. I tried using nextval('name_...
<python><postgresql><psycopg2>
2023-04-07 14:44:03
1
1,359
Bjinse
75,959,341
10,313,194
Selenium login Instragram why it has to login again when open new url
<p>I login Instragram and open some instragram page like this code.</p> <pre><code>url=['https://www.instagram.com'] user_names = [] user_comments = [] driver = driver = webdriver.Chrome('C:/Users/User/chromedriver_win32/chromedriver') driver.get(url[0]) time.sleep(3) username = WebDriverWait(driver, 10).until(EC.eleme...
<python><selenium-webdriver>
2023-04-07 14:29:49
1
639
user58519
75,959,314
3,810,748
Huggingface model training loop has same performance on CPU & GPU? Confused as to why?
<h2>Question</h2> <p>I created two Python notebooks to fine-tune BERT on a Yelp review dataset for sentiment analysis. The only difference between the two notebooks is that <a href="https://nbviewer.org/gist/AlanCPSC/f263426dce9b7b9580cd48dbc45910b0" rel="nofollow noreferrer">one runs on a CPU</a> <code>.to(&quot;cpu&q...
<python><pytorch><huggingface-transformers><huggingface>
2023-04-07 14:26:17
1
6,155
AlanSTACK
75,959,247
2,100,039
Assign Week Number Column to Dataframe with Defined Dict in Python
<p>I have been trying to get this to work and cannot find a solution. I have data that looks like this in dataframe (df):</p> <pre><code>index plant_name business_name power_kwh mos_time day month year 0 PROVIDENCE HEIGHTS UNITED STATES 7805.7 2023-02-25 08:00:00 56 2 2023 1 P...
<python><dictionary><week-number>
2023-04-07 14:18:07
1
1,366
user2100039
75,959,228
128,618
added a c column total to get total by column name
<pre><code>from pprint import pprint import pandas as pd input = [ {&quot;item&quot;: &quot;i1&quot;, &quot;balance&quot;: 11, &quot;warehouse&quot;: &quot;W1&quot;}, {&quot;item&quot;: &quot;i1&quot;, &quot;balance&quot;: 12, &quot;warehouse&quot;: &quot;W4&quot;}, {&quot;item&quot;: &quot;i1&quot;, &quo...
<python><pandas>
2023-04-07 14:16:02
2
21,977
tree em
75,959,070
18,157,326
TypeError: 'SnapResponse' object is not callable
<p>I have define a custom exception handler in python 3.10 fastapi <code>fastapi==0.95.0</code> app like this:</p> <pre><code>async def too_much_face_exception_handler(request, exc): resp = SnapResponse(result=&quot;&quot;,resultCode=&quot;TOO_MUCH_FACE&quot;) return resp </code></pre> <p>when the code run into...
<python><fastapi>
2023-04-07 13:56:36
1
1,173
spark
75,959,005
610,569
Deduplicating a list while keeping its order, and OrderedSet?
<p>Given a list as follows, deduplicating the list without concern for order, we can do this:</p> <pre><code>from collections import OrderedDict x = [1,2,3,9,8,3,2,5,3,2,7,3,6,7] list(set(x)) # Outputs: [1, 2, 3, 5, 6, 7, 8, 9] </code></pre> <p>If we want to keep the order, we can do something like:</p> <pre><code>li...
<python><list><duplicates><ordereddict>
2023-04-07 13:47:45
0
123,325
alvas
75,958,983
273,657
SQLAlchemy behaves differently on Windows and Linux when connecting to Oracle
<p>I have a simple python script that connects to an Oracle database. The connection is setup as follows (summarized):</p> <pre><code>engine = sqlalchemy.create_engine(&quot;oracle+cx_oracle://username:password@localhost:1521/?service_name=mydb&quot;, arraysize=1000) conn = engine.connect() df = pd.read_sql(&quot;se...
<python><pandas><sqlalchemy>
2023-04-07 13:45:15
0
15,926
ziggy
75,958,940
7,012,917
Compute rolling z-score over Pandas Series with Scipy gives error
<p>I have generic DataFrame with float numbers and no NaN's or Inf's. I want to compute the rolling Z-Score over the column <code>Values</code> and took help of <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.zscore.html" rel="nofollow noreferrer">Scipy's z-score</a>.</p> <p>This works, but it...
<python><pandas><scipy>
2023-04-07 13:39:21
1
1,080
Nermin
75,958,912
8,971,383
Couldnt install pymongo==4.3.3
<p>My Ubuntu server had python 2.7.17 as default. When i try to install <strong>pymongo==4.3.3</strong>,prompt an error to upgrade python version to 3. Then i install python3 and set as default version. All commands i executed as root.Then i check python version using <code>python --version</code> and as root i can see...
<python><python-3.x><python-2.7>
2023-04-07 13:34:34
1
627
kavindu
75,958,907
610,569
Deduplicating nested values that are also key in outer dictionary - Python
<p>Given an input dictionary,</p> <pre><code>x = {'A fantastic gift for art lovers': ['Designed for adults, this stunning piece ' 'of 3D art can be proudly displayed on a ' 'wall following a rewarding build ' ...
<python><dictionary><duplicates><key-value>
2023-04-07 13:33:52
1
123,325
alvas
75,958,899
8,231,100
Keras & Pytorch Conv2D give different results with same weights
<p>My code:</p> <pre><code>import tensorflow as tf from tensorflow.keras.layers import Conv2D import torch, torchvision import torch.nn as nn import numpy as np # Define the PyTorch layer pt_layer = torch.nn.Conv2d(3, 12, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1), bias=False) # Get the weight tensor from the ...
<python><tensorflow><keras><pytorch><conv-neural-network>
2023-04-07 13:33:25
2
365
Adrien Nivaggioli
75,958,770
2,131,200
Python: how to print argparse in alphabetical order
<p>I am looking for a canonical way to print the returned arguments of <code>argparse</code> in alphabetical order:</p> <pre class="lang-py prettyprint-override"><code>import argparse parser = argparse.ArgumentParser('Some program', add_help=False) parser.add_argument('--bb', type=str) parser.add_argument('--aa', type=...
<python><argparse>
2023-04-07 13:15:45
1
1,606
f10w
75,958,759
11,608,962
Is there a way to keep request body structure unchanged in FastAPI (pydantic)?
<p>During a <code>POST</code> request, I would like to keep the request body unchanged as per the definition of the <code>BaseModel</code> irrespective of what the user has passed.</p> <p>Consider the below <code>BaseModel</code>:</p> <pre class="lang-py prettyprint-override"><code>from pydantic import BaseModel class...
<python><fastapi><pydantic>
2023-04-07 13:14:17
2
1,427
Amit Pathak
75,958,707
18,157,326
is it possible to get the project root dir in python fastapi app
<p>My python3 fastapi project root dir is <code>'/Users/john/source/reddwarf/backend/chat-server/'</code> . I am tried to get the python project root dir like this:</p> <pre><code>root_path = os.path.abspath(os.path.dirname(__file__)) </code></pre> <p>but the dir is <code>'/Users/john/source/reddwarf/backend/chat-serv...
<python>
2023-04-07 13:06:29
1
1,173
spark
75,958,405
4,754,082
How to create a subscriptable custom type for Python type annotations?
<p>I'm trying to write a converter for <em>attrib</em> that converts a <em>IterableA</em> of <em>Type1</em> to an <em>IterableB</em> or <em>Type2</em>.</p> <p>For example:</p> <pre class="lang-py prettyprint-override"><code>converter = make_iter_converter(tuple, int) converter([&quot;1&quot;, &quot;2&quot;]) &gt;&gt;&g...
<python><python-typing>
2023-04-07 12:25:30
2
870
Kamoo
75,958,365
20,920,790
Why I got KeyError in loop "for" with regular expressions?
<p>I got pandas.Series with few values.</p> <pre><code>money = pd.Series(df_t['ะกะพะบั€ะฐั‰ะตะฝะฝะพะต ะฝะฐะธะผะตะฝะพะฒะฐะฝะธะต '].unique()) 0 USDCNY_TOM 1 USDRCNY_TOD dtype: object </code></pre> <p>My regular expression:</p> <pre><code>m_trim = re.compile(r'_TOM$|_TOD$') </code></pre> <p>When I run this code, it's works.</p> <pre><cod...
<python><pandas><regex>
2023-04-07 12:20:20
1
402
John Doe
75,958,310
5,351,558
Is pulp.lpDot(a,n) not equivalent to pulp.lpSum([a[i] * n[i] for i in range(N)])?
<p>I have a decision variable vector <code>n</code>, and <code>a</code> is a constant vector. What confuses me is why <code>lpDot(a,n)</code> is not equivalent to <code>lpSum([a[i] * n[i] for i in range(N)])</code> in a constraint?</p> <p>Here is the code:</p> <pre><code>import pulp import numpy as np # params N = 2 a...
<python><optimization><pulp><integer-programming>
2023-04-07 12:13:52
1
418
Yfiua
75,958,215
13,294,769
Can't create table with boolean column using SQLAlchemy on Redshift
<p>After a succesfull connection to Redshift, I'm trying to ensure my tables exist in the cluster. This is the code I'm running:</p> <pre class="lang-py prettyprint-override"><code>from sqlalchemy.engine import URL, create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Boolean, SM...
<python><python-3.x><sqlalchemy><amazon-redshift>
2023-04-07 12:03:06
1
1,063
doublethink13
75,958,201
4,315,597
Where does virtualenvwrapper's activate script live on Ubuntu?
<p>I installed python2 and virtualenvwrapper on my ubuntu machine in order to run a very old set of scripts I've saved for an obscure task.</p> <p>I run the following:</p> <pre><code>sudo apt-get install python2 cd ~/path/to/my/project pip install virtualenvwrapper source ~/.virtualenvs/ccs/bin/activate </code></pre> <...
<python><ubuntu><pip><virtualenv><virtualenvwrapper>
2023-04-07 12:01:49
1
1,213
Mayor of the Plattenbaus
75,958,181
2,628,868
how to specify the custom python path when using visual studio code to debug
<p>I am using visual studio code(1.77.1) to debbugging a python application, how to specify the python path in <code>launch.json</code>? I have tried like this:</p> <pre><code>&quot;python.pythonPath&quot;: &quot;/path&quot;, </code></pre> <p>but did not work. I also read the docs <a href="https://code.visualstudio.com...
<python><visual-studio-code>
2023-04-07 11:56:48
1
40,701
Dolphin
75,958,121
12,201,164
AWS EC2 user data: run python script at startup as non-root user
<p>When my EC2 VM (Ubuntu) starts, I'd like it to execute a python script <code>myscript.py</code> as <code>ec2-user</code> instead of the default <code>root</code> user. This includes using the <code>ec2-user</code>'s python executable, installed packages and binaries (e.g. chromedriver)</p> <p>How can I do this?</p> ...
<python><amazon-web-services><amazon-ec2><su><ec2-userdata>
2023-04-07 11:47:10
1
398
Dr-Nuke
75,958,003
4,120,479
Unity Barracuda cannot import .onnx file correctly
<p>I'm trying to implement inferencing YoloV5 models on Unity C#.</p> <p>I trained my own dataset, confirmed it works on python envs.</p> <p>Also, using given export.py, I converted .pt file to .onnx file and checked it works on python envs for inference.</p> <p>However, .onnx files cannot imported on Unity.</p> <p>Unf...
<python><unity-game-engine><onnx>
2023-04-07 11:29:35
1
521
Wooni
75,957,945
378,214
What is Spark's default cluster manager
<p>When using PySaprk and getting the Spark Session using following statement:</p> <pre><code> spark = SparkSession.builder .appName(&quot;sample-app&quot;) .getOrCreate() </code></pre> <p>app works fine but I am unsure which cluster manager is being with this spark session. Is it local or standalone....
<python><apache-spark><pyspark>
2023-04-07 11:20:24
1
2,263
Bagira
75,957,922
17,724,172
Python, Matplotlib horizontal bar chart
<p>How would I start the horizontal bars at different places on the x axis? Just a blank space for x number of days at the beginning of bars would be okay. I may need to revise this using ax.broken_barh, but that seems like a lot of work and about twice as much data just to have the projects start on different days. ...
<python><matplotlib><bar-chart>
2023-04-07 11:17:29
2
418
gerald
75,957,763
14,594,208
How to change the value of a Series element if preceded by N or more consecutive values to the value preceding it?
<p>Consider the following Series <code>s</code>:</p> <pre class="lang-py prettyprint-override"><code>0 0 1 0 2 0 3 1 4 1 5 1 6 0 </code></pre> <p>For <code>N = 3</code>, we can see that the items at indices <code>3</code> and <code>6</code> are both preceded by <code>&gt;= N</code> same value occur...
<python><pandas>
2023-04-07 10:49:22
1
1,066
theodosis
75,957,488
10,571,370
Python Pandas - drop duplicates from dataframe and merge the columns value
<p>I am trying to remove duplicates from my Dataframe and save their data into the columns where they are NA/Empty.</p> <p>Example: I've the following DATAFRAME and I would like to remove all the duplicates in column A but merge the values from the rest of the tables</p> <div class="s-table-container"> <table class="s-...
<python><pandas><dataframe><merge><duplicates>
2023-04-07 10:13:15
2
303
Darmon
75,957,447
12,130,817
YOLOv5: does best.pt control for overfitting?
<p>After each YOLOv5 training, two model files are saved: <code>last.pt</code> and <code>best.pt</code>. I'm aware that:</p> <ul> <li><code>last.pt</code> is the latest saved checkpoint of the model. This will be updated after each epoch.</li> <li><code>best.pt</code> is the checkpoint that has the best validation loss...
<python><machine-learning><artificial-intelligence><yolov5><fitness>
2023-04-07 10:07:41
1
373
Peter
75,957,365
1,608,276
How to type annotate a decorator to make it Override-friendly?
<p>I find that adding type annotation for a decorator will cause typing error in overriding case in <strong>VSCode Pylance strict mode</strong>. following is a minimal-complete-example (in Python3.8 <em>or later?</em>):</p> <pre><code>from datetime import datetime from functools import wraps from typing import Any _pe...
<python><overriding><python-decorators><python-typing><pyright>
2023-04-07 09:55:52
1
3,895
luochen1990
75,957,315
5,561,649
How to detect that an operation on a folder won't be able to complete before starting said operation, from Python on Windows?
<p>If we want to move or delete a folder, but some of its contained files are currently being used, the operation will likely fail after it has already started, and the folder could be left in a half-way, &quot;corrupt&quot; state.</p> <p>Is there a fast way to detect in advance that this will happen to avoid starting ...
<python><windows>
2023-04-07 09:47:34
1
550
LoneCodeRanger
75,957,048
1,581,090
How to use "fcntl.lockf" in Python?
<p>I found <a href="https://stackoverflow.com/questions/1320812/detect-and-delete-locked-file-in-python">this question</a> but I do not know how to use the suggestion. I have tried</p> <pre><code>with open(fullname) as filein: fcntl.lockf(filein, fcntl.LOCK_EX | fcntl.LOCK_NB) </code></pre> <p>and</p> <pre><code>wi...
<python><fcntl>
2023-04-07 09:08:13
1
45,023
Alex
75,956,862
18,661,363
Why are gitlab jobs not sharing docker image?
<p>We have a Python project which required postgres docker image. The application runs fine on local system after starting docker container. We have added two gitlab jobs, one is to start the docker container and another is to run the python script, but it seems that the second job is not executing successfully which ...
<python><docker><gitlab-ci>
2023-04-07 08:46:00
2
329
Prashant kamble
75,956,779
19,574,336
Windows bazel says python is not an executable when building tflite
<p>I'm trying to build c++ tflite for windows using bazel by following the <a href="https://www.tensorflow.org/install/source_windows" rel="nofollow noreferrer">official documentation</a>. So far I've installed everything it want's me to and added them to <code>PATH</code>. Then I cloned the github repo and checked out...
<python><c++><windows><tensorflow><bazel>
2023-04-07 08:32:37
1
859
Turgut
75,956,534
4,367,019
Select camera programatically
<p>My program should select three cameras and take pictures with each of it.</p> <p>I have the following code at the moment:</p> <pre><code>def getCamera(camera): graph = FilterGraph() print(&quot;Camera List: &quot;) print(graph.get_input_devices()) #tbd get right Camera try: device = gra...
<python><python-3.x><camera>
2023-04-07 07:57:13
2
5,638
Felix
75,956,472
8,071,608
Using a python 2.6 package in python 3.10
<h1>Background</h1> <p>I want to learn python through creating an isometric RPG computer game. To make it a little more fun at the start, I thought I would instead of starting from scratch, alter another very basic isometric RPG and bit by bit make it my own*. I thought <a href="https://www.pygame.org/project/294" rel=...
<python><python-2.6>
2023-04-07 07:44:15
2
2,341
Tom
75,956,424
3,964,056
Retry func if it takes longer than 5 seconds or if it fails
<p>I m in a situation where I have a func that calls the 3rd party API using the native lib of that company. Usually, the response time is excellent, like 1-2 secs but sometimes, the func would take 30-50 seconds to get the response. I want to make the func work in way that if it takes longer than the 5 seconds, then I...
<python><python-3.x><concurrent.futures><python-tenacity>
2023-04-07 07:37:15
0
984
PanDe
75,956,209
13,595,011
Error "'DataFrame' object has no attribute 'append'"
<p>I am trying to append a dictionary to a DataFrame object, but I get the following error:</p> <blockquote> <p>AttributeError: 'DataFrame' object has no attribute 'append'</p> </blockquote> <p>As far as I know, DataFrame does have the method &quot;append&quot;.</p> <p>Code snippet:</p> <pre class="lang-py prettyprint-...
<python><pandas><dataframe><concatenation><attributeerror>
2023-04-07 07:05:59
4
3,471
Maksimjeet Chowdhary
75,956,116
3,783,002
Subprocess with visual studio debugger attached to process causes a problem in python project
<p>I'm facing a very annoying issue with Visual Studio 2022. Here's how to replicate it.</p> <p>Folder contents:</p> <pre><code>test-debugpy-issue | test-debugpy-issue.sln | \---test-debugpy-issue cli.py test-debugpy-issue.pyproj test_debugpy_issue_simplified.py </code></pre> <p>Contents of...
<python><visual-studio-2022><visual-studio-debugging><debugpy>
2023-04-07 06:50:30
1
6,067
user32882
75,956,066
6,333,825
How do I use an operand contained in a PySpark dataframe within a calculation?
<p>I have a PySpark dataframe that contains operands (specifically greater than, less than, etc). I want to use those operands to calculate a result using other values in the dataframe and create a new column with this new data. For instance:</p> <pre><code>from pyspark.sql import Row from pyspark.sql.functions impor...
<python><dataframe><pyspark>
2023-04-07 06:40:56
1
586
Concrete_Buddha
75,955,739
2,272,824
How to select the column from a Polars Dataframe that has the largest sum?
<p>I have Polars dataframe with a bunch of columns I need to find the column with, for example, the largest sum.</p> <p>The below snippet sums all of the columns:</p> <pre class="lang-py prettyprint-override"><code>df = pl.DataFrame( { &quot;a&quot;: [0, 1, 3, 4], &quot;b&quot;: [0, 0, 0, 0], ...
<python><python-polars>
2023-04-07 05:45:37
3
391
scotsman60
75,955,658
1,220,955
Getting slow response form google OR tools
<p>I am using the OR tool Python library to resolve the cutting stock problem. But it has been taking too long for the last few days to respond. It is taking time more than 1 minute to respond.</p> <p>I am using Python code as an API and passing the below data.</p> <p>API Data :</p> <pre><code>{ &quot;child_rolls&q...
<python><python-3.x><response><or-tools>
2023-04-07 05:23:54
1
4,547
Hkachhia
75,955,596
9,371,736
Azure Cognitive Search: got an unexpected keyword argument 'query_language' in python vscode
<p>I'm trying to use semantic search enabled azure cognitive search in my flask app (in python virtual env). When I do pip install azure.search.documents, 11.3.0 version gets installed and I get following error:</p> <pre><code>TypeError: Session.request() got an unexpected keyword argument 'query_language' </code></pre...
<python><azure><visual-studio-code><azure-cognitive-search><semantic-search>
2023-04-07 05:07:10
2
307
Swasti
75,955,541
5,302,323
How to use Macbook terminal caffeinate to stop macbook from going to sleep while running Jupyter code on Chrome?
<p>I'd like to keep my battery saving options but ensure my macbook is awake and running my code before it goes to sleep.</p> <p>From what I understand, there is a command called caffeinate that does just this.</p> <p>My Chrome has several windows / tabs. How do I tell the Terminal to focus specifically on the tab whic...
<python><google-chrome><jupyter>
2023-04-07 04:52:32
1
365
Cla Rosie
75,955,538
2,368,205
Is PIL (pillow) corrupting my image files?
<p>Here's the basic code:</p> <pre><code> file = &quot;C:\DLS\sampleImage.jpg&quot; image = Image.open(file) image.close() print(str(image.width) + &quot;x&quot; + str(image.height)) </code></pre> <p>Given a regular .jpg image file, I can open it fine. After I run this script, the file size goes to 1KB (or likely less...
<python><image><python-imaging-library>
2023-04-07 04:51:27
0
658
Will Belden
75,955,289
4,883,787
Cannot use pip to download scipy for wheel
<p>I need to install some Python packages in another computer that cannot connect to the Internet. I tried to use the <code>pip</code> command to access the packages I listed in <code>packages.txt</code> and put the wheel files in <code>./packs</code>. The full command is as follows,</p> <pre><code>pip3 download -d ./p...
<python><pip><scipy><python-wheel>
2023-04-07 03:38:18
1
723
Ding Li
75,955,196
10,263,660
How to alias a type used in a class before it is declared?
<p>I have code similar to this example</p> <pre class="lang-py prettyprint-override"><code>import typing class C(): def __init__(self, callback: typing.Callable[[C], int]): self._callback = callback def getCallback() -&gt; typing.Callable[[C], int]: return self._callback class C2(): def _...
<python><python-typing>
2023-04-07 03:06:45
1
2,487
FalcoGer
75,955,154
8,075,540
exit not raising SystemExit in Jupyter Notebook
<p>I was writing a Python tutorial in Jupyter Notebook and was trying to demonstrate why one should never use a bare <code>except</code>. My example was</p> <pre class="lang-py prettyprint-override"><code>try: exit(0) except: print('Did not exit') </code></pre> <p>The idea was that <code>exit</code> would rais...
<python><exception><jupyter-notebook>
2023-04-07 02:56:07
0
6,906
Daniel Walker
75,955,105
2,657,491
Python how to determine duplicates or no duplicate for all columns
<p>I want to output at once to see if column has duplicates or no duplicates on its own. For example:</p> <pre><code> Student Date flag 0 Joe December 2017 4 1 James January 2018 5 2 Bob April 2018 6 3 Joe December 2017 8 4 Jack February 2018 9 5 Jack March 20...
<python><duplicates>
2023-04-07 02:39:39
1
841
lydias
75,955,059
4,420,797
torch.cuda.is_available() return True inside PyCharm project, return False outside project in Terminal
<p>I have installed the latest pytorch with cuda support using <code>conda install pytorch torchvision torchaudio pytorch-cuda=11.7 -c pytorch -c nvidia</code> command.</p> <p>When I run my project on Terminal anc activate conda environment, it returns <code>torch.cuda.is_available()</code> returns False and causes an ...
<python><pytorch><conda><torch>
2023-04-07 02:24:48
1
2,984
Khawar Islam
75,955,026
13,776,631
why accuracy remains about 0.5 in simple binary classification?
<p>I made a binary classifier. The classifier comprises of 3 linear layers, 2 relu layers and the last sigmoid layer. Then, I trained my classifier.</p> <p>However, My binary classifier's train accuracy doesn't decrease :( it should classify (x1,x2)-&gt;1 if x1&lt;x2 else (x1,x2)-&gt;0</p> <p>My code is:</p> <pre class...
<python><deep-learning><pytorch><classification>
2023-04-07 02:14:20
1
301
beginner
75,954,989
994,658
Best approach to generate a bunch of graphs from BigQuery?
<p>I have a ~10GB table in BigQuery which holds about ~2000 series that I want to plot individually using Matplotlib. The table has three columns, <code>series_id</code>, <code>date</code>, and <code>value</code>. I want to generate a time series for each value, 2000 times.</p> <p>I could do 2000 queries, one for each ...
<python><google-bigquery>
2023-04-07 02:04:51
0
3,674
Justin
75,954,765
5,942,100
Difficult field name conversion to specific values while performing row by row de-aggregation (Pandas) updated
<p>I have a dataset where I would like to convert specific field names to values while performing a de aggregation the values into their own unique rows as well as perform a long pivot.</p> <p><strong>Data</strong></p> <pre><code># create DataFrame data = { &quot;Start&quot;: ['8/1/2013', '8/1/2013'], &quot;Dat...
<python><pandas><numpy>
2023-04-07 00:59:42
1
4,428
Lynn
75,954,676
6,440,589
How to rerun docker-compose after modifying containerized python script
<p>Docker newbie question here.</p> <p>I am working on containerizing my own Python script, following <a href="https://www.docker.com/blog/how-to-dockerize-your-python-applications/" rel="nofollow noreferrer">this tutorial</a> and <a href="https://dev.to/davidsabine/docker-compose-hello-world-1p14" rel="nofollow norefe...
<python><docker><docker-compose>
2023-04-07 00:31:33
2
4,770
Sheldon
75,954,655
14,278,409
Sequential chaining of itertools operators
<p>I'm looking for a nice way to sequentially combine two itertools operators. As an example, suppose we want to select numbers from a generator sequence greater than a threshold, after having gotten past that threshold. For a threshold of 12000, these would correspond to <code>it.takewhile(lambda x: x&lt;12000)</code>...
<python><generator><python-itertools>
2023-04-07 00:26:43
2
730
njp
75,954,637
2,817,520
Is it possible not to use Flask decorators?
<p>I don't know why, but I don't like decorators. Can I use</p> <pre><code>def load_user(): if &quot;user_id&quot; in session: g.user = db.session.get(session[&quot;user_id&quot;]) app.before_request(load_user) </code></pre> <p>instead of</p> <pre><code>@app.before_request def load_user(): if &quot;use...
<python><flask>
2023-04-07 00:22:07
1
860
Dante
75,954,612
3,232,771
How can I tell which ax is selected on an interactive shiny for python plot?
<p>I'd like to generate a figure with <strong>multiple subplots</strong> that has basic interactivity; clicking, hovering etc...</p> <p>Here is an example of a figure with a single subplot from the official docs: <a href="https://shinylive.io/py/examples/#basic-plot-interaction" rel="nofollow noreferrer">https://shinyl...
<python><py-shiny>
2023-04-07 00:13:50
1
396
davipatti
75,954,596
9,682,236
Why Does Copied Object Avoid Modification in Python?
<p>I have the following data and following function that works to sort the products to the front of the list that match the specified category.</p> <pre><code>products =[{'t1': 'bbq', 'category': 2}, {'name': 't5', 'category': 3}, {'name': 't6', 'category': 3}, {'name': 't2', 'category': 2}, {'name': 't3', 'cate...
<python>
2023-04-07 00:10:25
0
1,125
Mark McGown
75,954,474
2,707,864
Sympy solve looking for complex solutions, even if real=True?
<p>I mean to solve a symbolic equation via <code>sympy.solve</code>. It was taking surprisingly long, so I tried a few variations, until I found a posible cause. It looks for complex solutions, while I am only interested in real solutions.</p> <p>Code below...</p> <pre><code>import sympy as sp import numpy as np x, y, ...
<python><sympy><solver><complex-numbers>
2023-04-06 23:36:41
3
15,820
sancho.s ReinstateMonicaCellio
75,954,444
8,667,016
Ranking using multiple columns within groups allowing for tied ranks in Pandas
<h3>Intro and problem</h3> <p>How can I rank observations within groups where the ranking is based on more than just one column and where the ranking allows for tied ranks?</p> <p>I know how to calculate aggregated group-level statistics using the <code>groupby()</code> method and I also know how to rank using multiple...
<python><pandas><group-by><grouping><ranking>
2023-04-06 23:28:07
1
1,291
Felipe D.
75,954,402
18,125,194
Seasonal decompose 'You must specify a period or x must be a pandas object with a PeriodIndex or a DatetimeIndex with a freq not set to None'
<p>I am trying to use statsmodels.tsa's seasonal decompose, but I keep getting this error</p> <p>'ValueError: You must specify a period or x must be a pandas object with a PeriodIndex or a DatetimeIndex with a freq not set to None'</p> <p>I have tryed to use a DatetimeIndex with a monthly period like this <code>time.in...
<python><statsmodels>
2023-04-06 23:12:30
1
395
Rebecca James
75,954,342
15,178,267
Django: 'QuerySet' object has no attribute 'product_obj' when running for loop
<p>I am trying to loop through a queryset, get the product object and remove the qty of items ordered from the product's stock amount.</p> <p>This is how my model Looks</p> <pre><code>class CartOrderItem(models.Model): order = models.ForeignKey(CartOrder, on_delete=models.CASCADE) product_obj = models.ForeignKe...
<python><django><django-models><django-views>
2023-04-06 22:56:07
2
851
Destiny Franks
75,954,280
2,778,224
How to change the position of a single column in Python Polars library?
<p>I am working with the Python Polars library for data manipulation on a DataFrame, and I am trying to change the position of a single column. I would like to move a specific column to a different index while keeping the other columns in their respective positions.</p> <p>One way of doing that is using <code>select</c...
<python><dataframe><python-polars>
2023-04-06 22:39:29
4
479
Maturin
75,954,211
5,617,608
ValueError: source code string cannot contain null bytes
<p>I'm originally an Ubuntu user, but I have to use a Windows Virtual Machine for some reason.</p> <p>I was trying to pip-install a package using the CMD, however, I'm getting the following error:</p> <pre><code>from pip._vendor.packaging.utils import canonicalize_name ValueError: source code string cannot contain n...
<python><python-3.x><windows><virtual-machine>
2023-04-06 22:24:00
2
1,759
Esraa Abdelmaksoud
75,954,193
7,752,049
Filtering data does not work properly on docker
<p>I have dockerized my Flask project, It gets <code>added_at</code> as a datetime and filters my products:</p> <pre><code>def post(self): args = request.get_json() products = Product.query args = {k: v for k, v in args.items() if v} added_at = args['added_at'] if 'added_at' in args else datetime.now() - t...
<python><docker><docker-compose>
2023-04-06 22:20:03
0
2,479
parastoo
75,954,148
5,942,100
Tricky conversion of field names to values while performing row by row de-aggregation (using Pandas)
<p>I have a dataset where I would like to convert specific field names to values while performing a de aggregation the values into their own unique rows as well as perform a long pivot.</p> <p><strong>Data</strong></p> <pre><code>Start Date End Area Final Type Middle Stat Low Stat Hi...
<python><pandas><numpy>
2023-04-06 22:10:56
3
4,428
Lynn
75,953,893
7,587,176
Connecting to snowflake in Jupyter Notebook
<p>I have a very base script that works to connect to snowflake python connect but once I drop it in a jupyter notebook , I get the error below and really have no idea why?</p> <pre><code>import snowflake.connector conn = snowflake.connector.connect(account='account', user='user'...
<python><snowflake-cloud-data-platform>
2023-04-06 21:22:58
1
1,260
0004
75,953,757
6,392,779
Selenium Select Div By Class, no such element
<p>I am trying to use selenium to open a webpage and click an element (maximize screen button that's not really a button) to maximize the video. I've tried a few variations of finding element by xpath, but none have worked.. Here is my code below, the webpage is accessible.. I really just need the xpath/to know how th...
<python><selenium-webdriver>
2023-04-06 21:02:31
2
901
nick
75,953,653
6,878,762
Pyspark: optimize getting proportion of df at each level of each categorical column
<p>TLDR: I'm new to pyspark and I think I'm not being &quot;sparky&quot; while trying to do a bunch of aggregations.</p> <p>I have a set of data for which I need to know the proportion of data at each level of each categorical column. For example if I start with the following:</p> <pre><code>|box|potato|country| |1 |r...
<python><dictionary><optimization><pyspark><aggregate>
2023-04-06 20:48:34
1
347
HJT
75,953,556
1,574,054
VS Code cannot find python libpython3.10.so
<p>I am trying to select a vritual environment as the default interpreter for python in vs code, but this fails. In the terminal I can, without issues run</p> <pre><code>$ &lt;venv_path&gt;/python Python 3.10.8 (main, Mar 14 2023, 20:30:44) [GCC 12.2.0] on linux Type &quot;help&quot;, &quot;copyright&quot;, &quot;credi...
<python><visual-studio-code><environment-variables><shared-libraries>
2023-04-06 20:35:17
1
4,589
HerpDerpington
75,953,432
4,154,548
Reticulate sees some (but not all) python packages using Rstudio on Ubuntu
<p>Setting a conda environment (in this case named <code>r420v1</code> where python is in &quot;/home/tjm/anaconda3/envs/r420v1/bin/python3&quot; ) in reticulate &quot;works&quot; in that it sets the appropriate version of python, libpython, and python home. However, it identifies only numpy (correct version 1.24.2 al...
<python><r><rstudio><conda><reticulate>
2023-04-06 20:15:50
0
2,906
Thomas Matthew
75,953,418
5,091,720
Selenium Other ways to find_element for onclick
<p>I am looking at a table that has this <code>&lt;tr onclick=&quot;setValue('115751')&quot; role=&quot;row&quot; class=&quot;odd&quot;&gt;</code> like shown below. I am trying use Selenium to find_element and click on distinct rows based on the setValue. Since I normally use xpath I tried to use that but xpath does no...
<python><selenium-webdriver>
2023-04-06 20:13:25
1
2,363
Shane S
75,953,279
4,212,158
ModuleNotFoundError: No module named 'pandas.core.indexes.numeric' using Metaflow
<p>I used Metaflow to load a Dataframe. It was successfully unpickled from the artifact store, but when I try to view its index using <code>df.index</code>, I get an error that says <code>ModuleNotFoundError: No module named 'pandas.core.indexes.numeric'</code>. Why?</p> <p>I've looked at other answers with similar err...
<python><pandas><pickle><netflix-metaflow>
2023-04-06 19:52:50
5
20,332
Ricardo Decal
75,953,229
1,578,210
Referencing a class variable
<p>I have a class with several variables inside</p> <pre class="lang-py prettyprint-override"><code>class myClass(): def __init__(self): self.first = &quot;&quot; self.second = &quot;&quot; self.third = &quot;&quot; </code></pre> <p>Ok, so if I then initialize a variable to that class, I understand...
<python><python-3.x>
2023-04-06 19:43:55
1
437
milnuts
75,953,212
89,480
How can I render a text to multiple filled polygons?
<p>I'm need to extrude text to a 3D triangle mesh using trimesh, open3d, or something similar.</p> <p>Since these libraries don't contain any font related functions, I want to obtain polygons that correspond to glyph outlines as polygons and extrude those.</p> <p>I've tried using fontTools and ended at using its <code>...
<python><fonts><geometry><polygon>
2023-04-06 19:42:17
1
3,958
cube
75,952,937
869,809
how to load data into mysql database when a flask app is running and "protecting" the data?
<p>I have several flask (python=3.10) applications running on my server (Ubuntu 20.04.6 LTS). They are, as of now, working great and being served via Apache and mod_wsgi. My requirements.txt is below.</p> <p>For example, this is from the conf file in the sites-enabled directory:</p> <pre><code> WSGIDaemonProcess op...
<python><mysql><flask><flask-sqlalchemy>
2023-04-06 19:05:47
0
3,616
Ray Kiddy
75,952,667
6,794,223
How to use return value (str) of one activity as input a second activity in temporal python sdk?
<p>I'm using the python sdk for <a href="https://temporal.io/" rel="nofollow noreferrer">https://temporal.io/</a>. I have a workflow that i'd like to execute two sequential activities.</p> <ol> <li>Do X and return a filepath.</li> <li>Do Y with data at that filepath.</li> </ol> <pre><code>@workflow.defn class ScraperWo...
<python><temporal-workflow>
2023-04-06 18:28:20
2
312
user6794223
75,952,446
4,918,765
Get table description from Python sqlalchemy connection object and table name as a string
<p>Starting from a <code>sqlalchemy</code> connection object in Python and a table name as a string how do I get table properties, eg column names and datatypes.</p> <p>For example, connect to a database in <code>sqlalchemy</code></p> <pre><code>from sqlalchemy import create_engine conn = create_engine('mssql+pyodbc://...
<python><pandas><sqlalchemy>
2023-04-06 17:58:34
1
2,723
Russell Burdt
75,952,237
4,329,348
Is there a convinient tool like Makefile for Python that will append a path to PYTHONPATH?
<p>I have an issue where I want to add a path to PYTHONPATH. Of course, I don't want to modify my <code>.bashrc</code> to get just this project running.</p> <p>PyCharm for example will add to PYTHONPATH the root contents when you create a configuration and as a result when you run the program from within PyCharm it wil...
<python>
2023-04-06 17:26:58
1
1,219
Phrixus
75,952,055
4,329,348
Can't understand why Python won't import the file
<p>I have the following project structure:</p> <pre><code>โ”œโ”€โ”€ my_app โ”œโ”€โ”€ __init__.py โ”œโ”€โ”€ my_pkg โ”‚ย ย  โ”œโ”€โ”€ __init__.py โ”‚ย ย  โ”œโ”€โ”€ utils.py โ”‚ย ย  โ”œโ”€โ”€ app.py โ”œโ”€โ”€ other_pkg... โ”‚ย ย  โ”œโ”€โ”€ __init__.py โ”‚ย ย  โ”œโ”€โ”€ ... โ”œโ”€โ”€ ... </code></pre> <p>I want in the <code>my_app/my_pkg/app.py</code> to import <cod...
<python>
2023-04-06 17:06:19
1
1,219
Phrixus
75,952,042
13,812,982
ExcelWriter using openpyxl engine ignoring date_format parameter
<p>I have read quite a few answers on this, but when I run my code I don't get the same result.</p> <p>I am using pandas 2.0.0 and openpyxl 3.1.2 on Python 3.9</p> <p>This is a reduced example of my issue, which is that <em>I can't get the ExcelWriter to respect my choice of date format</em>. I am trying to append a ne...
<python><excel><pandas>
2023-04-06 17:04:35
1
4,331
DS_London
75,951,990
4,730,598
problem with if statement? not equal rule doesnt work?
<p>I have 1000 dataframes that have same structure, but some of them may contain strings as values. With all those frames I need to do the same calculations, just exclude rows in those dataframes where subsrings occur. The example of the structure of the dataset with string is as follows:</p> <pre><code>time x ...
<python><pandas><numpy>
2023-04-06 16:57:27
2
403
Ison
75,951,948
15,545,814
Pip installs packages in the wrong directory
<p>So I want to install the opencv-python package. I typed in pip install opencv-python and got this:</p> <pre><code>Collecting opencv-python Downloading opencv_python-4.7.0.72-cp37-abi3-win_amd64.whl (38.2 MB) โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ” 38.2/38.2 MB 3.1 MB/s eta 0:00:00 Requirement already satisfi...
<python><pip><python-module><python-packaging><pythonpath>
2023-04-06 16:51:59
2
512
LWB
75,951,840
6,458,245
Fast way to create dict of dicts and insert element in python?
<p>Is there a way to condense this code?</p> <pre><code> key2 = 1 self.mydict = {1:{}} if key1 in self.mydict.keys(): self.mydict[key1][key2] = None else: self.mydict[key1] = {} self.mydict[key1][key2] = None </code></pre> <p>As you can see if the key doesn't exist I need to first...
<python><dictionary>
2023-04-06 16:39:14
1
2,356
JobHunter69
75,951,825
7,059,087
How to make PyTest use the `conftest.py` of a parent directory
<p>I am working on a suite of tests for a project that were not written by me. The way they were set up is as follows</p> <pre><code>root/ conftest.py testType1/ a.py testType2/ etc. </code></pre> <p>The file <code>a.py</code> is as follows</p> <pre><code>class TestClass: value_thats_important = N...
<python><python-3.x><testing><pytest>
2023-04-06 16:37:16
1
532
wjmccann
75,951,773
11,922,765
Plot temperature barplot with sorted axis categories
<p>I want to show number of samples in specific range of the temperature. The problem is, x-axis of the plot is not arranged in the proper order: lowest range first (negative temperatures ) and bigger range next. In the below plot, -5750 is lowest temperature. But it appears in the middle. It is to be first one on x-ax...
<python><pandas><matplotlib><seaborn><histogram>
2023-04-06 16:31:33
1
4,702
Mainland
75,951,765
2,103,050
tf_agents changing underlying suite_gym reward function
<p>I'm trying to modify the MountainCarContinuous-v0 environment from <code>suite_gym()</code> because training is getting stuck in a local minima. The default reward function penalizes large actions which are preferred for optimal solving. So I would like to try other reward functions to see if I can get it to train p...
<python><reinforcement-learning><openai-gym><tensorflow-agents>
2023-04-06 16:30:44
0
377
brian_ds
75,951,753
1,827,854
Why does the __mul__ magic method behave differently than the human-readable version?
<p>I've been explaining Python magic functions to someone and I naturally showed these examples:</p> <pre><code>In [1]: str(&quot;v&quot;).__mul__(5) Out[1]: 'vvvvv' In [2]: &quot;v&quot; * 5 Out[2]: 'vvvvv' </code></pre> <p>But then I moved on to how transitivity is implemented and tried also this example that failed...
<python>
2023-04-06 16:29:21
2
625
mapto
75,951,678
1,028,133
A short expression to pick from two values based on bool?
<p>If one has two values in a list:</p> <pre><code>choices = [1,2] </code></pre> <p>and one wants to assign these values to two variables based on a <code>bool</code> parameter (let's call it <code>ascending</code>) like this:</p> <pre><code>if ascending: a,b = choices[1], choices[0] else: a,b = choices[0], choices...
<python>
2023-04-06 16:21:31
2
744
the.real.gruycho
75,951,672
10,859,585
Pandas DataFrame with row list and column list
<p>I must be missing something, but I cannot find any guides on how to construct a pandas dataframe using both list of rows and columns. The purpose is that the <code>row_list</code> and <code>col_list</code> are updated in a loop and can hold more or less strings, but will always equal each other in length.</p> <p>Usi...
<python><pandas><dataframe><list>
2023-04-06 16:20:29
1
414
Binx
75,951,653
6,039,697
Make a function return the same type of a overriden base class method
<p>I have an abstract base class <code>MyClass</code> which contains an abstract method <code>get_type</code> which returns a class type.</p> <p>I also have a funtion <code>fn</code> which expects an instance of <code>MyClass</code> and I want to typing the return of <code>fn</code> as an instance of the same type retu...
<python><python-typing>
2023-04-06 16:17:54
0
1,184
Michael Pacheco
75,951,558
92,441
Beautiful Soup - ignore `<span>` while providing `string` to `find()` method
<p>I am parsing some text in Python, using BeautifulSoup4.</p> <p>The address block starts with a cell like this:</p> <pre><code>&lt;td&gt;&lt;strong&gt;Address&lt;/strong&gt;&lt;/td&gt; </code></pre> <p>I find the above cell using <code>soup.find(&quot;td&quot;, &quot;Address&quot;)</code></p> <p>But, now some address...
<python><html><beautifulsoup>
2023-04-06 16:04:00
2
2,442
ianmayo
75,951,472
11,512,576
how to set the name of returned index from df.columns in pandas
<p>I have a dataframe <code>df</code> in pandas. When I run <code>df.columns</code>, <code>Index(['Col1', 'Col2', 'Col3'], dtype='object', name='NAME')</code> is returned. What's the <code>name</code> here, how can I update it. And it doesn't appear in other dataframes, how can I add it. Thanks.</p>
<python><pandas><dataframe>
2023-04-06 15:54:18
2
491
Harry
75,951,469
15,178,267
How to check if a date is still less than 5 days in django query?
<p>I am trying to check if the date an order was created is still less than 5 days, then i want to display a <code>New Order</code> Text.</p> <p>This is how i have tried doing this</p> <pre><code>def vendor_orders(request): five_days = datetime.now() + timedelta(days=5) new_orders = CartOrder.objects.filter(pay...
<python><django><django-models><django-rest-framework><django-views>
2023-04-06 15:53:43
1
851
Destiny Franks
75,951,304
3,231,250
faster way to search column pairs in another dataframe
<p>I have a big dataframe called <code>df</code> around 45 million row like below. <a href="https://drive.google.com/drive/folders/1ydrVDE5mU9KHT8k9XybTjGInqdFg07R4?usp=sharing" rel="nofollow noreferrer">download</a></p> <pre><code> gene1 gene2 score 0 PIGA ATF7IP1 -0.047236 1 PIGB ATF7IP2 -0...
<python><pandas><dataframe><vectorization>
2023-04-06 15:35:58
2
1,120
Yasir
75,951,299
4,298,200
Wrong encoding when redirecting printed unicode characters on Windows PowerShell
<p>Using python 3, running the following code</p> <pre><code>print(&quot;some box drawing:&quot;) print(&quot;โ”Œโ”€โ”ฌโ”ผโ”ดโ”&quot;) </code></pre> <p>via</p> <pre class="lang-console prettyprint-override"><code>py my_app.py </code></pre> <p>prints</p> <pre class="lang-console prettyprint-override"><code>some box drawing: โ”Œโ”€โ”ฌโ”ผโ”ดโ”...
<python><windows><unicode><encoding><redirectstandardoutput>
2023-04-06 15:35:35
2
6,008
Georg Plaz
75,951,190
2,543,622
sentence transformer use of evaluator
<p>I came across <a href="https://github.com/UKPLab/sentence-transformers/blob/master/examples/training/sts/training_stsbenchmark_continue_training.py" rel="nofollow noreferrer">this script</a> which is second link on <a href="https://www.sbert.net/examples/training/sts/README.html" rel="nofollow noreferrer">this page<...
<python><nlp><sentence-transformers>
2023-04-06 15:22:42
1
6,946
user2543622