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
βŒ€
77,362,961
2,763,030
How to tell if a python package installation includes precompiled binaries?
<p>Is there a reliable way to determine if when installing a Python package with pip/conda if the installer includes precompiled binaries? I would like to exclude or at least know when this happens. Sometimes this can be determined from looking at the setup/project in the source distribution or by the name of the whl f...
<python><pip><conda>
2023-10-25 21:20:19
1
1,731
John D.
77,362,957
12,242,085
How to drop duplicated values in one column for each id in Data Frame in Python Pandas?
<p>I have Data Frame in Python Pandas like below:</p> <pre><code>data = {'id': [1, 1, 1, 1, 2, 2, 3, 3], 'nps': [8, 8, 8, 8, 7, 7, 9, 9], 'target': [True, True, True, True, False, False, True, True], 'score': [0.56, 0.78, 0.56, 0.78, 0.6785, 0.42, 0.9, 0.63], 'day': ['2023-02-15', '2023...
<python><pandas><dataframe><duplicates><drop-duplicates>
2023-10-25 21:19:08
1
2,350
dingaro
77,362,703
1,422,096
How to plot an histogram correctly with numpy, and match it with the density function?
<p>TL;DR: <strong>How to plot the result of <code>np.histogram(..., density=True)</code> correctly with Numpy?</strong></p> <p>Using <code>density=True</code> should help to match the histogram of the sample, and the density function of the underlying random variable, but it doesn't:</p> <pre class="lang-py prettyprint...
<python><numpy><matplotlib><statistics><probability-density>
2023-10-25 20:29:36
3
47,388
Basj
77,362,389
10,318,539
How to Run a Dynamic Qiskit Circuit Using the Sampler Primitive?
<p>I aim to execute my Qiskit dynamic circuit using a sampler. The rationale behind this choice is that a sampler allows me to run multiple circuits concurrently, whereas using a backend restricts me to executing one circuit at a time. However, while I have developed the code, I am uncertain about where to specify the ...
<python><qiskit>
2023-10-25 19:26:28
1
485
Engr. Khuram Shahzad
77,362,308
8,903,959
What's the difference between 'pip3 install -e .' and 'python3 setup.py develop'
<p>When installing a Python package locally in editable mode, both 'pip3 install -e .', and 'python3 setup.py develop', will both install the package locally in editable mode. I know that 'pip3 install -e .' is recommended over 'python3 setup.py develop', but I am unclear as to why and what the differences are between ...
<python><pip><setuptools><setup.py><python-packaging>
2023-10-25 19:11:52
1
1,097
Justin Furuness
77,362,216
3,419,103
Add startup/shutdown handlers to FastAPI app with lifespan API
<p>Consider a FastAPI using the <code>lifespan</code> parameter like this:</p> <pre class="lang-py prettyprint-override"><code>def lifespan(app): print('lifespan start') yield print('lifespan end') app = FastAPI(lifespan=lifespan) </code></pre> <p>Now I want to register a sub app with its own lifecycle fu...
<python><fastapi><lifecycle><starlette>
2023-10-25 18:56:54
2
18,137
Falko
77,362,087
4,031,815
Keep getting conflicts when installing python, flask and google cloud bigquery
<p>I have this env.yml</p> <pre><code>name: env-app channels: - conda-forge - defaults dependencies: - google-cloud-bigquery=3.12.0 - flask=3.0.* - python=3.12.* </code></pre> <p>If I run <code>micromamba env create --file environment.yml</code> I get this output:</p> <pre><code>conda-forge/osx-arm64 ...
<python><flask><conda>
2023-10-25 18:31:22
0
25,646
CommonSenseCode
77,361,959
1,656,122
Python webbrowser module keep browser open
<p>I am trying to open a website with Python's webbrowser module, however, I want the browser to continue to stay open after the script is finished and not close out.</p> <pre><code>import webbrowser # Logic/code that programmatically gets a URL print(webbrowser.open(url)) # while True: # continue print(&quot;sc...
<python><browser><module>
2023-10-25 18:06:15
1
415
Dylan Holmes
77,361,799
13,086,128
AttributeError: 'DataFrame' object has no attribute 'group_by'
<p>I am trying to group by a polars dataframe following the document:</p> <p><a href="https://pola-rs.github.io/polars/py-polars/html/reference/dataframe/api/polars.DataFrame.group_by.html#polars.DataFrame.group_by" rel="noreferrer">https://pola-rs.github.io/polars/py-polars/html/reference/dataframe/api/polars.DataFram...
<python><python-3.x><dataframe><python-polars>
2023-10-25 17:43:34
1
30,560
Talha Tayyab
77,361,638
4,726,246
Anaconda Nested Virtual environment bug
<p>Whenever I open terminal using VS code, it shows nested conda environment. Currently there are two environments, base and myenv. When I start terminal, I am greeted by this :</p> <pre><code>(myenv) (base) username:directory$ </code></pre> <p>Any tips on how to debug this or how to find out what's going on?</p>
<python><bash><terminal><anaconda>
2023-10-25 17:15:30
1
598
infiNity9819
77,361,637
5,684,326
Containerizing a flask application that uses PYODBC
<p>I am trying to create a container and it's telling me that the ODBC Driver 17 for SQL server can't be opened. here is the container but I have tried many different containers. This is the code that throws the error.</p> <pre><code>class Database: @staticmethod def _get_connection_string_from_secrets(file_pat...
<python><sql-server><docker><flask><odbc>
2023-10-25 17:15:19
0
484
jdmneon
77,361,569
19,838,568
KafkaConsumer with sasl_mechanism "OAUTHBEARER" not calling token() function
<p>I am trying to get a minimal <strong>kafka</strong> consumer working, using kafka-python. Authentication is via OAuth.</p> <p>I created a TokenProvider class, which is working fine. Any time, token() is called, it will check whether there is a current token and if not, fetch one from the OAuth URL.</p> <pre><code>&g...
<python><apache-kafka><oauth><kafka-consumer-api>
2023-10-25 17:04:32
1
2,406
treuss
77,361,546
4,442,337
Get a package directory path using importlig.resources with >=py37 compatibility?
<p>I'm trying to make a <code>constants.py</code> file which can be accessed to get global available paths through the whole package. I'm using <code>importlib.resources</code> which should be in standard lib since <code>python3.7</code> according to <a href="https://docs.python.org/3/library/importlib.resources.html" ...
<python><python-3.x>
2023-10-25 17:00:51
1
2,191
browser-bug
77,361,437
1,431,728
How can I test a list of method calls in Python?
<p>Using this code I can print a list of the methods called in my test method:</p> <pre class="lang-py prettyprint-override"><code>import unittest from unittest.mock import patch, Mock, call class MyTest(unittest.TestCase): @patch(mymodule.DepObj) def mytest(self, mock_obj): mock_obj_ret = mock_obj.ret...
<python><python-unittest>
2023-10-25 16:45:03
1
7,417
JohnK
77,361,396
3,091,161
Why id() of a method changes after I call the hex() function?
<p>The <code>id()</code> function gives different values for the same method, and I don't know why.</p> <p>Here's a minimal reproducible example:</p> <pre><code>&gt;&gt;&gt; class Test(): ... def test(self): ... pass ... &gt;&gt;&gt; a = Test() &gt;&gt;&gt; id(a.test), id(a.test), id(a.test), hex(1), id(a.t...
<python>
2023-10-25 16:38:55
0
1,693
enkryptor
77,361,341
101,647
python pint : Create a "pace" metric from velocity metrics
<p>Using the <code>pint</code> library in python - It has support for unit conversions, which work great.</p> <p>For example:</p> <pre><code>units.Quantity(2, &quot;mph&quot;).to(&quot;kph&quot;) </code></pre> <p>I would like to understand how I could define a unit <code>pacem</code> - which would be &quot;minutes per ...
<python><pint>
2023-10-25 16:29:35
1
2,197
time4tea
77,361,304
3,787,836
Fast direct pixel access in python, go or julia
<p>I wrote a small program that creates random noise and displays it full screen (5K resolution). I used pygame for it. However the refresh rate is horribly slow. Both the surfarray.blit_array and random generation take a lot of time. Any way to speed this up? I am also flexible to use julia or golang instead. or also...
<python><numpy><pygame-surface><psychopy><psychtoolbox>
2023-10-25 16:24:56
1
359
Loreno Heer
77,361,097
12,492,675
How to merge two data frames to show unique count of rows?
<p>I have 2 Dataframes in my project as shown below.</p> <pre><code>Table 1 Order_id Prod_id Price A AA 5 B BB 10 C CC 15 D AA 5 E CC 20 Table 2 Prod_id Price AA 5 BB 10 CC 15 CC 20 </code></pre> <p>My t...
<python><dataframe><merge><duplicates>
2023-10-25 15:54:43
2
1,326
Simran Aswani
77,360,937
859,141
Passing Parent PK to ModelForm in Class Based Create and Update View
<p>I'm updating function based views to class based views and having issues re-establishing the link between campaign and books. My Book Model has a foreign key link to Campaigns.</p> <pre><code>campaign = models.ForeignKey(Campaign, on_delete=models.DO_NOTHING) </code></pre> <p>I have a ModelForm where I set the camp...
<python><django><modelform>
2023-10-25 15:33:07
1
1,184
Byte Insight
77,360,933
345,660
Efficient way to convert 4 billion hex integers to decimal integer in R or python
<p>I have a csv file with about 4.4 billion rows. It has 25 categorical columns, all of which are hexadecimal encoded integers, such as <code>EE6B2800</code> and <code>10642AC00</code>.</p> <p>I have a machine with 3TB of RAM and used <code>data.table::fread</code> to load the dataset. R reads these values as strings (...
<python><r><data.table><large-data><categorical-data>
2023-10-25 15:32:45
1
30,431
Zach
77,360,874
9,185,312
SQLAlchemy Python backend, after a few hours of no use will give a 500 error on any request, then it will work fine
<p>Everytime I start my backend up and I wait for a few hours, then come back to it, on the first request I will have an error like this:</p> <pre><code>sqlalchemy.exc.OperationalError: (pymysql.err.OperationalError) (2006, &quot;MySQL server has gone away (ConnectionResetError(10054, 'An existing connection was forcib...
<python><mysql><sqlalchemy>
2023-10-25 15:25:40
1
1,180
Alex Stroescu
77,360,860
13,146,029
ImportError: cannot import name 'db' from partially initialized module 'application'
<p>Im trying to set up a Flask factory, first time I have tried. I keep getting the following error:</p> <pre><code>Traceback (most recent call last): File &quot;/Users/grahammorby/Documents/GitHub/tagr-api/venv/lib/python3.12/site-packages/flask/cli.py&quot;, line 219, in locate_app __import__(module_name) Fil...
<python><flask>
2023-10-25 15:24:14
1
317
Graham Morby
77,360,698
1,914,781
print dataframe contains "\n" chars
<p>I have a dataframe which contains &quot;\n&quot; to format text, how can I get output as below:</p> <pre><code> key val 0 A x y z 1 B apple orange 2 C good bad best...
<python><pandas>
2023-10-25 15:02:21
2
9,011
lucky1928
77,360,636
2,114,608
Python JustPy QTable custom row color
<p>I am creating QTable:</p> <pre><code>some_table = jp.QTable( hide_bottom=True, title=f'Some Table Title', data=[], columns=some_table_columns, a=some_table_div, dense=True, style=&quot;margin-bottom:25px&quot; ) </code></pre> <p>next, I have</p> <pre><code>for some_item in some_item_str_l...
<python><quasar><justpy>
2023-10-25 14:54:36
0
2,027
PrzemysΕ‚aw Kalita
77,360,610
274,460
Can Flask and Quart avoid the redirect when a default path parameter is used?
<p>Consider this web service:</p> <pre><code>from flask import Flask, jsonify, Blueprint app = Flask(__name__) @app.route(&quot;/&lt;int:d&gt;&quot;) @app.route(&quot;/&quot;, defaults={&quot;d&quot;: 1}) def a(d): return jsonify({&quot;d&quot;: d}) </code></pre> <p>If I use call it with a parameter other than th...
<python><flask>
2023-10-25 14:52:08
1
8,161
Tom
77,360,592
22,538,132
How to create an OrientedBoundingBox from Depth image and bounding box
<p>I want to crop a poincloud using the segmented mask (rectangle) and depth image, (I can consider that there is no rotation for now).</p> <pre class="lang-py prettyprint-override"><code>import open3d as o3d ## dummy pointcloud demo_icp_pcds = o3d.data.DemoICPPointClouds() pcd = o3d.io.read_point_cloud(demo_icp_pcds....
<python><geometry><crop><point-clouds><open3d>
2023-10-25 14:50:02
1
304
bhomaidan90
77,360,456
6,626,531
Import order in python for specific packages
<p>I ran pylint on my codebase and it complained that <code>from config import ConfigParser</code> was defined before <code>from pathlib import Path</code> Why is this the case?</p> <p>When I ran isort of the file, it agreed with pylint. From what I understand it groups imports by type</p> <ul> <li>Native to python</li...
<python><python-3.x><pylint><isort>
2023-10-25 14:34:00
2
1,975
Micah Pearce
77,360,380
559,827
How to read a single CLI keypress from Python 3 on Unix without requiring ENTER or root privileges?
<p>The problem described in the title is, apparently, incredibly hard. Every solution I have found for it (and there are <em><strong>dozens</strong></em> of them in SO alone) is inadequate for at least one of the following reasons:</p> <ul> <li>Python 2-specific;</li> <li>unnecessarily portable/cross-platform (hence h...
<python><python-3.x><unix><keyboard><keyboard-events>
2023-10-25 14:25:55
1
35,691
kjo
77,360,322
5,013,084
Set shape of only some points in altair scatter plot
<p>I am trying to set the shape for one variable in this altair scatterplot (since I am dealing with live data, I do not know every possible domain value), therefore I am trying to set the value for only two of those values.</p> <pre><code>import altair as alt from vega_datasets import data source = data.cars() alt....
<python><altair>
2023-10-25 14:18:34
1
2,402
Revan
77,360,224
293,420
Bokeh standalone embed serve folder for content (v 3.3.0 2023)
<p>I'm trying to run a server on a remote location to render a plot with circles so that the tooltip includes an image of the item hovered on.</p> <p>I'm using Bokeh 3.3.0 and tornado. This is my code:</p> <pre><code>from bokeh.layouts import column from bokeh.models import ColumnDataSource,HoverTool from bokeh.plottin...
<python><server><tooltip><bokeh><tornado>
2023-10-25 14:05:52
1
3,654
lesolorzanov
77,360,174
2,727,655
Map BERT token indices to Spacy token indices
<p>I’m trying to make Bert’s (<code>bert-base-uncased</code>) tokenization token indices (not ids, token indices) map to Spacy’s tokenization token indices. In the following example, my approach doesn’t work becos Spacy’s tokenization behaves a bit more complex than I anticipated. Thoughts on solving this?</p> <pre><co...
<python><mapping><spacy><tokenize><bert-language-model>
2023-10-25 13:58:12
1
554
lrthistlethwaite
77,360,126
1,107,595
Same frame multiple times when using select and vframes
<p>I'm using ffmpeg in python using the ffmpeg-python wrapper</p> <p>I run the following:</p> <pre><code>filename = &quot;something.mp4&quot; frame_number = 5 # It works fine if I ask to start at 0 out, err = ( ffmpeg.input(filename) .filter_('fps', fps=10) .filter_('select', 'gte(n,{})'.format(frame_numbe...
<python><ffmpeg>
2023-10-25 13:52:34
1
2,538
BlueMagma
77,360,066
4,704,065
Print elements when the difference is greater/lesser than a condition in numpy array
<p>in a numpy array , I have to print out elements when the difference between elements is &gt; or &lt; 1 Basically it should print the element when the difference is &gt; or &lt; 1</p> <pre><code>Input : arr=np.array([1, 3, 3,4,7,4,1,6,7,8,9,5,13]) Output: 3,7,4,1,6,5,13 </code></pre> <p>This is what I tried , but the...
<python><numpy><numpy-ndarray>
2023-10-25 13:45:49
3
321
Kapil
77,360,061
7,055,769
RecursionError: maximum recursion depth exceeded while calling a Python object when updating choice field
<p>model:</p> <pre><code>StatusChoices = ( (&quot;TODO&quot;, &quot;todo&quot;), (&quot;DOING&quot;, &quot;doing&quot;), (&quot;DONE&quot;, &quot;done&quot;), ) class Task(models.Model): status = models.CharField( choices=StatusChoices, default=StatusChoices[0], max_length=5, ...
<python><django><django-rest-framework>
2023-10-25 13:44:50
3
5,089
Alex Ironside
77,359,687
5,507,389
Get unique values from sets in Pandas DataFrame columns
<p>I'm working with a Pandas DataFrame which has the following structure:</p> <pre><code>import pandas as pd data = {&quot;col1&quot;: [{1}, {5}, {}, {1, 2}], &quot;col2&quot;: [{1, 2}, {}, {}, {3, 4}]} df = pd.DataFrame(data) print(df) col1 col2 0 {1} {1, 2} 1 {5} {} 2 {} {} 3 {1, 2...
<python><python-3.x><pandas><dataframe>
2023-10-25 12:58:08
1
679
glpsx
77,359,672
12,242,085
How to stay for each id in Data Frame only rows for one random month from column with dates in Python Pandas?
<p>I have Data Frame in Python Pandas like below:</p> <pre><code>df = pd.DataFrame({'id': [1, 1, 1, 2, 2, 2], 'day': ['2023-03-01', '2023-03-10', '2023-04-05', '2023-03-15', '2023-04-20', '2023-04-25'], 'col1' : [123, 66, 7, 890, 456, 100]}) </code></pre> <p><a href="https://i.ssta...
<python><pandas><dataframe><date>
2023-10-25 12:55:47
3
2,350
dingaro
77,359,597
1,134,856
SSLCertVerificationError EE certificate key too weak
<p>I'm trying to call a rest service using python like so:</p> <pre><code>import requests import certifi ... requests.get(endpoint_url, data=query, auth=my_auth, verify=certifi.where(), timout=1000) ... </code></pre> <p>This results in a <code>SSLCertVerificationError</code> with the message <code>EE certificate key to...
<python><python-requests><request>
2023-10-25 12:45:03
0
2,600
treeno
77,359,543
583,464
Strip strings and date, time from mixed string with numbers
<p>I have this kind of dataset:</p> <pre><code>import pandas as pd import numpy as np x = np.array([ '355395.7037', '355369.6383', '355367.881', '355381.419', '357394.9D7a82te7o6fm4o9n4t3h7 print: 06/10/202', '357405.7897626596']) y = np.array...
<python><arrays><pandas><data-cleaning>
2023-10-25 12:37:33
2
5,751
George
77,359,323
18,771,355
Simclr/Resnet18 cross entropy loss : 0D or 1D target tensor expected, multi-target not supported
<p>I am trying to implement a SimCLR/Resnet18 model with a custom dataset.</p> <p>My training dataset used for pretext tasks is composed of 7000 with various unlabeled types of pictures, all aggregated in <code>train_X_v1.bin</code>, of shape <code>(7000, 3, 224, 224)</code>. For the fine tuning I have two files <code>...
<python><python-3.x><deep-learning><pytorch><resnet>
2023-10-25 12:06:52
1
316
Willy Lutz
77,359,161
13,518,907
BFloat16 is not supported on MPS (macOS)
<p>I accessed a Llama-based model on Huggingface named: &quot;LeoLM/leo-hessianai-7b-chat&quot;. I downloaded the model on my Mac with the device set as 'MPS'. The download worked, however when I want to test the model I get following error:</p> <pre><code>TypeError: BFloat16 is not supported on MPS </code></pre> <p>Ab...
<python><macos><large-language-model><llama><bfloat16>
2023-10-25 11:45:24
2
565
Maxl Gemeinderat
77,359,094
10,133,797
`stmt` vs `functools.partial` for `timeit.Timer`
<p>I've read that <code>functools.partial(fn, *args, **kw)</code> saves overhead compared to <code>lambda: fn(*args, **kw)</code>. But is it also advantageous over <code>stmt</code> + <code>globals</code>?</p> <pre class="lang-py prettyprint-override"><code>timeit.Timer(partial(fn, *args, **kw)).repeat(200, 5) </code>...
<python><performance><time><timeit>
2023-10-25 11:36:10
0
19,954
OverLordGoldDragon
77,358,942
4,517,263
Python how to add words from text file that contains letters from another word
<p>I have a text file that contains words between 2-7 letters. Now I want to to do the following:</p> <ol> <li>Make a new sub-list with all words with 7 letters.</li> <li>For each 7 letter word <strong>W</strong>, list all the words from the original list that are anagrams of any subset of letters of <strong>W</strong>...
<python>
2023-10-25 11:12:43
1
607
Mat Koffman
77,358,840
2,074,697
pandas to_sql gives conversion errors even after specifiying dtype
<p>I'm trying to make a program which imports data from an Excel to SQL tables. I need to do this for <em>several hundred</em> files, so I need to have a general approach.</p> <p>I'm using SQLAlchemy to import my data frame to SQL Server, but the column ProductCode causes an issue. The first 1000 or so rows are integer...
<python><pandas><sqlalchemy>
2023-10-25 10:54:10
0
1,242
Cenderze
77,358,836
2,534,342
How to make ruff to use f-string instead str.format?
<p>I'm trying <code>ruff</code> but when I do <code>ruff check .</code> on my example:</p> <pre class="lang-py prettyprint-override"><code>print(&quot;%s&quot; % &quot;hello&quot;) </code></pre> <p>it shows:</p> <pre><code>UP031 Use format specifiers instead of percent format </code></pre> <p>and if I do <code>ruff che...
<python><ruff>
2023-10-25 10:53:51
3
612
alanwilter
77,358,702
937,019
Coloring line segments in altair
<p>How do I change the color of line segments in an altair plot? In my example, I want to color all line segments that are above 1 to red and below 1 to green. My current attempts look like this:</p> <pre class="lang-py prettyprint-override"><code>df = pd.DataFrame({ 'x': [1, 2, 3, 4, 5], 'y': [0.8, 0.9, 1.1, 1...
<python><altair>
2023-10-25 10:30:24
0
626
magum
77,358,655
736,662
Running two tasks in one Locust test and weigh the calls relative
<p>I have a non-working Locust test like this:</p> <pre><code>from locust import HttpUser, between, task from locust.contrib.fasthttp import FastHttpUser import random import json import csv from datetime import datetime, timedelta server_name = &quot;https://rknwvb.com:7072&quot; save_from_date = &quot;2023-07-05T08...
<python><locust>
2023-10-25 10:21:55
1
1,003
Magnus Jensen
77,358,638
7,243,493
dynamic numpy conditions based on values from array
<p>I am trying to find out how I can use <code>np.where</code> in a dynamic way, where I select some predefined values, pass them to a function and let them create the condition. Ideally I want to create long conditions with several logical operators.</p> <p>In the code below I am stupidly trying to use a string:</p> <...
<python><pandas><numpy>
2023-10-25 10:19:37
2
568
Soma Juice
77,358,599
2,745,609
Python Covert Duration String to Number Format in Hours
<p>I have a Pandas dataframe with a Duration column with contains durations as text with the following format. Some strings have &quot;Days&quot; added at the beginning where some of them just have the hour minute and second information:</p> <pre class="lang-py prettyprint-override"><code>df = Duration 0 16h:48m...
<python><pandas><datetime><timedelta>
2023-10-25 10:15:27
2
474
Solijoli
77,358,512
2,650,325
Google Sheets API: socket.timeout: The read operation timed out
<p>I am trying to upload about 40k rows (39345 rows x 60 columns) with Google Sheets API and I am getting the following error:</p> <pre><code>Error, sleep for 101 seconds Traceback (most recent call last): File &quot;C:\***lib\site-packages\pysuite\gsheets.py&quot;, line 38, in execute return func.execute() Fil...
<python><google-cloud-platform><google-sheets-api>
2023-10-25 10:03:55
1
2,417
Manuel Perez Heredia
77,358,341
4,490,376
Why are environment variables not being overridden in pytest?
<p>I'm writing some unit tests for a basic flask app. Currently I'm testing the config.py file (mainly to learn, but also to test an environment dependent database configuration).</p> <p>The file looks like:</p> <p>config.py</p> <pre><code>from os import environ as env from dotenv import load_dotenv load_dotenv() c...
<python><pytest><.env>
2023-10-25 09:40:21
1
551
741852963
77,358,007
21,404,794
Instantiating various crabnet models in same code
<p>I stumbled upon <a href="https://crabnet.readthedocs.io/en/latest/" rel="nofollow noreferrer">crabnet</a> recently, and I'm using it in a catalysis project. It's been a good addition to the project, but I've found a problem.</p> <p>I wanted to train crabnet in different subsets of my dataset (filtering on reaction c...
<python><neural-network><artificial-intelligence>
2023-10-25 08:55:16
1
530
David Siret MarquΓ©s
77,357,935
13,518,907
Add custom prompts to Llama 2 for RAG
<p>I have downloaded Llama 2 locally and it works. Now I want to adjust my prompts/change the default prompt to force Llama 2 to anwser in a different language like German. Here is my code:</p> <pre><code>from langchain.llms import LlamaCpp from langchain.chains import LLMChain from langchain.callbacks.manager import C...
<python><nlp><prompt><langchain><large-language-model>
2023-10-25 08:44:32
1
565
Maxl Gemeinderat
77,357,723
3,685,918
How can I create xticks with varying intervals?
<p>I am drawing a line chart using matplotlib as shown below.</p> <pre><code>import matplotlib.pyplot as plt import pandas as pd import io temp = u&quot;&quot;&quot; tenor,yield 1M,5.381 3M,5.451 6M,5.505 1Y,5.393 5Y,4.255 10Y,4.109 &quot;&quot;&quot; data = pd.read_csv(io.StringIO(temp), sep=&quot;,&quot;) plt.plot(...
<python><pandas><matplotlib><xticks>
2023-10-25 08:17:17
1
427
user3685918
77,357,714
13,942,929
Git & Python : How to removed a cache/pycache of a deleted folder?
<p>Let's say my project structure looks like the below</p> <pre><code>Main Folder - SubCode Folder - SubTest Folder </code></pre> <p>I want to delete everything cache from that subtest folder including the folder itself. How can I do that?</p>
<python><git><caching>
2023-10-25 08:15:43
0
3,779
Punreach Rany
77,357,678
4,944,986
SciPy optimization doesn't return optimal solution
<p>I'm attempting to maximize a sectional area function related to my master thesis. I've come up with a function <code>double_T_Ixx</code>, and I wish to optimize it using SciPy's <code>minimize</code> function. While I understand the analytical solution, the optimization output is not aligning with my expectations.</...
<python><optimization><scipy>
2023-10-25 08:11:44
1
945
Finn Eggers
77,357,606
812,912
Pylint recursive bug when directory is prefix of another directory
<p>I am observing weird behavior for pylint when I have a directory name being a prefix of another directory. Here is minimal setup to reproduce:</p> <pre><code>mkdir pylint_test cd pylint_test mkdir dataset touch dataset/__init__.py mkdir dataset_123 echo &quot;from collections import Counter&quot; &gt; dataset_123/a....
<python><pylint>
2023-10-25 07:59:59
1
71,364
Ivaylo Strandjev
77,357,375
4,047,444
Perform Calculation on One DataFrame Based on the Common Columns of a Second DataFrame
<p>Assume the two <code>DataFrames</code> have equal columns but different rows even though the examples are equal in length. I was able to find the commonalities of the two DataFrames. I want to use that similarity to perform calculations on one of the DataFrames and put the result in another DataFrames. In summary...
<python><pandas><dataframe>
2023-10-25 07:25:07
2
861
dreamzboy
77,357,094
22,466,650
How to index a df with a 2D array and lookup for values from another one?
<p>My inputs are <code>df</code> and two arrays :</p> <pre class="lang-py prettyprint-override"><code>df = pd.DataFrame({'id': ['id1', 'id2', 'id3', 'id4', 'id5']}) indexes = np.array( [[1, 2], [4, 0], [0, 1], [2, 0], [1, 0]]) values = np.array( [[0.012, 0.019], [0.009, 0.012], [0.019,...
<python><pandas>
2023-10-25 06:37:22
1
1,085
VERBOSE
77,357,034
7,495,742
Frame Loader over a sleeping function in python
<p>i wrote this snippet of code but i cannot get the expected behaviour, i guess i must use <em><strong>threading</strong></em> but i didn't figure out how to use it correctly :(</p> <p>What i would like is the second Frame to continue to show the <em><strong>loading</strong></em> while the main frame runs a <em><stron...
<python><multithreading><wxpython><sleep><loader>
2023-10-25 06:24:46
1
357
Garbez FranΓ§ois
77,357,003
17,519,895
Docker image giving Timeout after 300 seconds
<p>I am testing a AWS lambda docker image on Local computer and if the process is under 5min/300 sec, it runs smoothly, and if the time limit approaches 300 sec, it gives timeout error. I haven't set any time limit anywhere. Here's my docker script:</p> <pre><code>FROM public.ecr.aws/lambda/python:3.9 ENV GOOGLE_APPLIC...
<python><amazon-web-services><docker><aws-lambda>
2023-10-25 06:19:16
1
421
Aleef
77,356,809
1,903,629
In dagster sensors is there a way to re run a RunRequest for a run key
<p>I have a sensor, whenever there is a new file in my file system it will create a run request with file path as run_key. And a asset job will be invoked. That job will fetch the file and do some operations and write it to an external database.</p> <p>But it is possible that the external database write could fail so I...
<python><dagster>
2023-10-25 05:26:15
0
4,193
ted
77,356,779
13,443,954
How to use chained page object locators?
<p>I have a function, contains the page objects</p> <pre><code>class TemplateListPage: def __init__(self, page): self.list_first_row = self.page.locator(&quot;.grid-row&quot;).first self.use_btn = self.page.locator(&quot;.useTemplate&quot;) </code></pre> <p>And I would like to chain the button with the f...
<python><playwright><playwright-python>
2023-10-25 05:17:31
1
333
M AndrΓ‘s
77,356,692
1,718,989
Python Operator Precedence with Shortcut Operator?
<p>I understand that Python follows an operator precedence with the acronym PEMDAS or P-E-MD-AS</p> <p>Now Python happens to use shortcut operators so for example if I were to write</p> <pre><code>x=5 x=x+1 </code></pre> <p>This could be re-written as</p> <pre><code>x+=1 </code></pre> <p>Now I noticed something a bit o...
<python><shortcut><operator-precedence>
2023-10-25 04:52:51
2
311
chilly8063
77,356,663
1,854,821
tox-conda: multiple Python interpreters for tests
<p>All afternoon I've been reading and rereading documentation for <a href="https://tox.wiki/en/latest/config.html" rel="nofollow noreferrer">tox</a> and <a href="https://github.com/tox-dev/tox-conda" rel="nofollow noreferrer">tox-conda</a>, <a href="https://cloudcity.io/blog/2018/03/12/multiversion-testing-with-tox/" ...
<python><conda><tox>
2023-10-25 04:42:04
1
473
Timothy W. Hilton
77,356,497
342,553
MySQL is it possible to group by duration intersection?
<p>I have a set of phone call data which has <code>start</code> and <code>end</code> timestamps, I need to work out the most concurrent calls within a month, so the call &quot;duration&quot;s need to overlap, unfortunately I don't think I can use &quot;sliding window&quot; as it only works with single field.</p> <p>eg....
<python><mysql>
2023-10-25 03:46:43
1
26,828
James Lin
77,356,419
6,739,732
Why is Python's BZ2 Decompressor shrinking the block?
<p>The BZ2 file I'm using is a partial dump of Wikipedia [<a href="https://dumps.wikimedia.org/enwiki/20231020/enwiki-20231020-pages-articles-multistream1.xml-p1p41242.bz2" rel="nofollow noreferrer">here</a>]</p> <p>Here's a Python code I wrote to test the length of a 10000-byte block before and after decompression:</p...
<python><bz2>
2023-10-25 03:13:45
1
313
Rapid Readers
77,356,352
10,844,937
Python check if a string is a standard US dollar or not?
<p>I have some strings which only contains [<code>0-9</code>][<code>,</code>][<code>.</code>]. I need to check if they are in standard US dollar format. The number of the decimal of the string may be <code>0</code>, <code>1</code> or <code>2</code>. Here are some examples whether they are standard or not.</p> <pre><cod...
<python><python-3.x>
2023-10-25 02:47:38
1
783
haojie
77,356,332
10,853,071
Dask client causing memory expection?
<p>IΒ΄ve been migrating some of my codes from pandas do dask. Many of them are already working. Studing a little bit more about dask, IΒ΄ve faced it &quot;Client()&quot; feature for monitoring usage. Nice function! But it does break my code!</p> <p>Dask without client</p> <pre><code>import dask.dataframe as dd from dask....
<python><dask><dask-distributed><dask-dataframe>
2023-10-25 02:39:25
0
457
FΓ‘bioRB
77,356,258
12,810,409
`np.gradient` has high variance for non-uniform spacing
<p>I encountered high variance in <code>np.gradient</code> for relatively smooth data.</p> <p>Suppose we want to calculate <code>dx/dt</code>:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt x = np.array([13.11149679, 13.2141427 , 13.37743691, 13.3934357 , 13.56163066, 13.60207566, 13.69304133]...
<python><numpy><numerical-methods>
2023-10-25 02:09:23
2
378
Toon Tran
77,356,229
14,109,040
Splitting Pandas dataframe by columns and concatenate to create single dataframe
<p>I have an excel file in the following format:</p> <p><a href="https://i.sstatic.net/gIr5J.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/gIr5J.png" alt="enter image description here" /></a></p> <p>I want to read it using Python and concatenate the tables(the number of tables could change) into a sing...
<python><pandas>
2023-10-25 01:58:45
2
712
z star
77,356,173
433,570
Is there a way to add path to sys.path automatically when activating an python environment?
<p>I'm trying to add project_root to sys.path when activating the project environment</p> <p>(currently conda, but it can be pyenv, poetry..)</p> <p>The project_root might be different for people depending on where they created the project_root in their local file system.</p> <p>So is there a way for me to setup so tha...
<python><virtualenv>
2023-10-25 01:37:24
1
42,105
eugene
77,356,097
5,560,837
`sorted(my_list, key = lambda x, y: ... )` possible?
<p>If I want to sort a list of non-empty strings by this criteria -</p> <p><code>&quot;x + y &gt; y + x&quot;</code> (for any <code>x = lst[i]</code>, <code>y = lst[j]</code> that <code>0 &lt;= i &lt; j &lt; len(lst)</code>)</p> <p>I know one way is to define a <code>my_key</code> class and put the logic in this class,...
<python><string><sorting><lambda><key>
2023-10-25 00:55:15
1
417
Egret
77,356,073
159,072
data frame is not stacked vertically when saved
<p>data1.dat</p> <pre><code> 1 ASN C 7.042 9.118 0.000 1 1 1 1 1 0 2 LEU H 5.781 5.488 7.470 0 0 0 0 1 0 3 THR H 5.399 5.166 6.452 0 0 0 0 0 0 4 GLU H 5.373 4.852 6.069 0 0 0 0 1 0 5 LEU H 5.423 5.164 6.197 0 0 0 0 2 0 6 LYS H 5.247 4.943 6.434 0 0 0 0 1 0 7 ASN C...
<python><pandas><csv>
2023-10-25 00:48:05
1
17,446
user366312
77,356,035
361,100
PyCharm wrongly recognizes pydevd.py path when debugging on Windows
<p>When I click Debug button on PyCharm, it wrongly recognizes where <code>pydevd.py</code> file resides.</p> <p>The console message is as below;</p> <pre><code>C:\Users\young\AppData\Local\Microsoft\WindowsApps\python3.10.exe &quot;C:/Users/young/AppData/Local/Programs/PyCharm Professional/plugins/python/helpers/pydev...
<python><debugging><pycharm><console>
2023-10-25 00:32:47
1
25,138
Youngjae
77,356,026
12,242,085
How to expand Data Frame to artificially create dates up to the 31st day in each month no matter how many days that month has in Python Pandas?
<p>I have Data Frame in Python Pandas like below:</p> <pre><code>data = { 'id': [1, 1, 2, 2, 3], 'nps': [8, 8, 7, 7, 5], 'target': [True, True, False, False, True], 'nps_score': [0.56, 0.56, 0.6785, 0.6785, 0.44], 'event_day': ['2023-02-15', '2023-02-22', '2023-06-10', '2023-06-20', '2022-02-11'] } ...
<python><pandas><dataframe><date>
2023-10-25 00:31:43
2
2,350
dingaro
77,356,025
20,258,214
CTkToplevel is brought to the front and then goes back
<p>I am encountering a really weird problem in <code>customtkinter</code>.</p> <p>I created a <code>CTkToplevel</code> window and brought it to the front using <code>lift()</code> method. It got to the front, and immediately after was sent behind my root window.</p> <h3>Simplified Code Using <code>customtkinter</code>:...
<python><tkinter><customtkinter>
2023-10-25 00:30:48
0
1,598
nokla
77,355,767
3,143,269
In Python is it possible to have a Stream based socket and a PIpe used asynchronously?
<p>I have been searching high and low for 10 days now trying to find an example where there is an asynchronous streams socket (I need to use receiveuntil()) and a multiprocessing Pipe in use in the same script?</p> <p>I like asyncio as I can await data arrival for the socket and the pipe. At least it seems like I shoul...
<python><python-3.x>
2023-10-24 22:46:00
1
1,124
AeroClassics
77,355,743
7,318,120
in python 3.12 i see type ListOrSet[T] = list[T] | set[T], but how do i use this?
<p>In the new python 3.12 docs i see this:</p> <pre class="lang-py prettyprint-override"><code>type ListOrSet[T] = list[T] | set[T] </code></pre> <p>But I dont know how or where this is used. Is this for type hinting and where can this be used?</p> <p>The docs are here: <a href="https://peps.python.org/pep-0695/" rel="...
<python><types>
2023-10-24 22:39:24
1
6,075
darren
77,355,707
1,722,361
Python3 import module without relative path
<p>I have a folder test with the following py files</p> <pre><code>mytest/ - test.py - utility.py - pb2.py - pb2_grpc.py </code></pre> <p>pb2 and pb2_grpc are generated by python grpc tool.</p> <p>in test.py, there are</p> <pre><code>import utility import pb2 import pb2_grpc </code></pre> <p>in pb2_grpc.py, there is</p...
<python><python-3.x><python-module>
2023-10-24 22:26:19
2
427
user1722361
77,355,420
9,343,043
How to merge dictionary of dataframes on shared column
<p>I have a dictionary of 7 dataframes of t-statistic values (for a different clinical site), where each dataframe has two columns of about 100 Brain ROIs and the t statistic value for that ROI. My goal is to create a dataframe of each ROI with each t-statistic values.</p> <p>For this post though, for the sake of brevi...
<python><pandas><dictionary><merge><concatenation>
2023-10-24 21:14:12
1
871
florence-y
77,355,368
11,618,586
Calculating duration from a timestamp column by groups
<p>I have a pandas dataframe like so:</p> <pre><code> dttm runid 9/7/2023 00:10 1694020173 9/7/2023 00:10 1694020173 9/7/2023 00:10 1694020173 9/7/2023 00:10 1694020173 9/7/2023 00:10 1694020173 9/29/2023 20:31 1695908276 9/29/2023 20:31 1695908276 9/29/2023 20:31 1695908276 9/29/2023 20:31 1695908276 ...
<python><pandas>
2023-10-24 21:00:28
2
1,264
thentangler
77,355,318
10,990,958
I have some buttons in customtkinter and they are not moving when I change position how would I achive my end result?
<p>So I've been working on this random selector. I am trying to move the buttons to the positions I want them, but for some reason they are not moving. This is the code:</p> <pre><code>import random import customtkinter import PIL from PIL import Image customtkinter.set_appearance_mode(&quot;light&quot;) # Create a ...
<python><button><customtkinter>
2023-10-24 20:49:56
1
349
Pandas INC
77,355,232
901,449
Django model relations - "Owning" a related model enforced at the model level
<p>I'm not really sure how to title this question, so forgive my title's ambiguity.</p> <p>I have two models, <code>Customer</code> and <code>Address</code>. Each has typical fields you would infer from their model names. <code>Address</code> is also set as an inline to <code>Customer</code> in admin.py:</p> <pre><code...
<python><django><django-models>
2023-10-24 20:30:02
2
2,780
pspahn
77,355,192
19,299,757
How do I refer IAM user name in lambda event?
<p>I've an AWS Lambda function which just prints the event</p> <pre><code>import json import logging logger = logging.getLogger() logger.setLevel(logging.INFO) def respond(err, res=None): return { 'statusCode': '400' if err else '200', 'body': err.message if err else json.dumps(res), 'heade...
<python><amazon-web-services><aws-lambda><aws-api-gateway>
2023-10-24 20:20:32
0
433
Ram
77,354,976
3,543,200
debian:12-slim breaking apt update for mysql
<p>In switching from <code>python:3.8.16-slim</code> (which is based on <code>debian:11-slim</code>) to <code>python:3.8.18-slim</code> (which is based on <code>debian:12-slim</code>), the following Dockerfile now fails to build with the following error. The change in python version is the only difference.</p> <pre><co...
<python><docker><dockerfile><debian><debian-bookworm>
2023-10-24 19:38:53
1
997
gmoss
77,354,731
5,960,363
Define common Pydantic fields, use subsets of them in models
<h2>Setup</h2> <p>I have a long list of variables to be used in email templates.</p> <h5>Example</h5> <pre class="lang-py prettyprint-override"><code>cust_name: str bill_address: str ship_address: str ref_num: int # ...list continues </code></pre> <p>Overlapping combinations of these appear in the templates, whic...
<python><design-patterns><types><fastapi><pydantic>
2023-10-24 18:57:45
2
852
FlightPlan
77,354,502
19,980,284
AttributeError: module 'transformers' has no attribute 'BertTokenizerFast'
<p>I have installed spacy onto a Jupyter Notebook in Jupyter Lab that I access through the Anaconda Navigator, all on a remote desktop.</p> <p>I was able to install spacy using</p> <pre><code>!pip install spacy </code></pre> <p>But when I tried to run</p> <pre><code>import spacy nlp = spacy.load('en_core_web_sm') </cod...
<python><pip><spacy>
2023-10-24 18:14:42
1
671
hulio_entredas
77,354,401
9,983,652
what is the final model to use when using stratified kfold cv?
<p>When using statified kfold cv, we fit the model for each of 5 folds for example so we got 5 models for each fold respectively, Then my question is what is the final model to use for prediction? For example, in below code, the code get accuracy result of each of 10 fold, then which kfold model to use after traning an...
<python><scikit-learn>
2023-10-24 17:59:36
1
4,338
roudan
77,354,334
17,274,113
Openpyxl: loading excel "Table" as variable. `ValueError: Table with name Membership already exists`
<p>I have been working with excel documents lately, and having difficulty grasping &quot;tables&quot;. I think some of the confusion stems from the fact that some online resources refer to an array of values in a worksheet as a table, whereas I am interested in dealing with a table object (&quot;insert table&quot; in ...
<python><excel><openpyxl><xlsx>
2023-10-24 17:48:21
1
429
Max Duso
77,354,288
755,934
No module named 'pydantic_core._pydantic_core' server for python serverless on AWS lambda
<p>I read these StackOverflow questions: <a href="https://stackoverflow.com/questions/77305721/aws-lambda-error-on-fast-api-no-module-named-pydantic-core-pydantic-core">1</a> <a href="https://stackoverflow.com/questions/76650856/no-module-named-pydantic-core-pydantic-core-in-aws-lambda-though-library-is-i">2</a> that c...
<python><aws-lambda><serverless-framework><pydantic>
2023-10-24 17:40:42
1
5,624
Daniel Kats
77,354,262
616,460
Python package not being found after install
<p>I have a project directory structure like this:</p> <pre><code> root\ .git\ server\ setup.py company\ __init__.py zed\ __init__.py server\ __init__.py server.py util.py ...
<python><setuptools><python-packaging>
2023-10-24 17:37:29
1
40,602
Jason C
77,354,233
235,671
MyPy complains about isinstance(obj, Callable) being incompatible with _ClassInfo
<p>I've got a couple of <code>if</code>s that all use <code>isinstance</code>. One of them is checking the <code>obj</code> against <code>Collable</code> with <code>isinstance(obj, Callable)</code> as suggested in <a href="https://stackoverflow.com/a/65505019/235671">this</a> answer. But when I run <code>mypy</code> on...
<python><python-3.x><mypy><python-typing>
2023-10-24 17:32:13
0
19,283
t3chb0t
77,354,114
13,217,286
Generate combinations of items in a Polars List using expressions?
<p>Is there a way to generate combinations of items within a list inside a Polars column without resorting to <code>.map_elements()</code> + <strong>itertools</strong> for each row?</p> <p>This is my current solution:</p> <pre class="lang-py prettyprint-override"><code>import polars as pl import itertools pl.Config(fm...
<python><dataframe><list><python-itertools><python-polars>
2023-10-24 17:14:15
2
320
Thomas
77,354,058
4,031,815
Micromamba and Dockerfile error: /bin/bash: activate: No such file or directory
<p>Used to have a Dockerfile with <code>conda</code> and <code>flask</code> that worked locally but after installing <code>pytorch</code> had to switch to <code>micromamba</code>, the old <code>CMD</code> no longer works after switching to image <code>mambaorg/micromamba:1-focal-cuda-11.7.1</code>, this is how my Docke...
<python><docker><flask><dockerfile><conda>
2023-10-24 17:03:58
1
25,646
CommonSenseCode
77,353,746
7,188,690
subtraction from nested dictioanaries in a pandas dataframe
<p>I have a dataframe where I want to find the difference in the unique_users and total_sessions for the latest day(2023-09-06) and previous day(2023-09-07) for a specific hour 2 and 13 separately for each key 'jio' and 'other' and for a specific Exception. I need to consider the Exception and Hour and Date to calculat...
<python><pandas>
2023-10-24 16:09:18
1
494
sam
77,353,402
1,182,794
aiohttp posting list of jsons
<p>I saw in somebody's code that they are posting a list of requests in one aiohttp post call, and expecting to receive list of responses back. I have tried that myself and it worked (if you are curious what I'm requesting, those are blocks of Ethereum, I'm talking to a live node):</p> <pre><code>def aiohttp_test(): ...
<python><aiohttp>
2023-10-24 15:25:33
2
622
DimaA6_ABC
77,353,375
20,770,190
Why I get No module named 'requests' within the github actions runner?
<p>I have a <code>gihub-actions</code> file with a part to run <code>pytest</code> via <code>poetry</code>:</p> <pre><code> build: runs-on: ubuntu-latest strategy: matrix: python-version: ['3.10',] steps: - uses: actions/checkout@v2 - name: Set up Python ${{ matrix.python-version ...
<python><continuous-integration><pytest><github-actions><python-poetry>
2023-10-24 15:22:26
3
301
Benjamin Geoffrey
77,353,344
6,494,707
Conjugate symmetric: 3D Fourier transform dimension
<p>I have a real-valued input 3D array with the shape of <code>(H,W,D)=[8,8,20]</code>, where H, W, and D represent height, width and depth(z dimension), respectively. When computing the DFT, what will be the dimension of the DFT complex array (3D Fourier Transform)?</p> <p>I read in one article that 2D DFT becomes lik...
<python><signal-processing><fft><dft>
2023-10-24 15:19:04
1
2,236
S.EB
77,353,338
633,439
Applying binary map gives NaN in some columns of the dataset
<p>I have a dataset named Housing having some string values in some columns as shown below:</p> <p><a href="https://i.sstatic.net/0mdxu.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/0mdxu.png" alt="enter image description here" /></a></p> <p>I need to convert those 'yes' or 'no' values to 0 or 1. To do...
<python><pandas><list><dataset>
2023-10-24 15:18:22
1
1,107
kzs
77,353,210
8,261,345
How to dampen a series of values in Pandas, with more dampening if further from the average?
<p>I have a series of values that oscillate about the average, 1.0, with a minimum of 0 and no maximum, e.g.</p> <pre><code>s = pd.Series([1.0, 1.03, 1.05, 1.2, 0.8, 0.97, 0.99]) </code></pre> <p>I wish to 'damp' this series about the average of 1, i.e. values close to 1, such as 1.01 and 0.99 should be changed very li...
<python><pandas><math>
2023-10-24 14:59:55
1
694
Student