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,878,672
17,795,398
How can I get the seed of a numpy `Generator`?
<p>I am using <code>rng = np.random.default_rng(seed=None)</code> for testing purposes following <a href="https://numpy.org/doc/stable/reference/random/generator.html#numpy.random.default_rng" rel="nofollow noreferrer">documentation</a>.</p> <p>My program is a scientific code, so it is good to have some random values t...
<python><numpy><random>
2024-01-25 09:06:40
2
472
Abel Gutiérrez
77,877,808
2,998,077
Kivy to display current time on screen
<p>Below lines are used to create a popup window to display a running string (current time) from screen right to left. (system: Windows 10)</p> <p>It works as the screen pops, with no reported errors. But the screen display is blank (black).</p> <p>What went wrong here?</p> <pre><code>from kivy.app import App from kivy...
<python><kivy>
2024-01-25 06:04:22
1
9,496
Mark K
77,877,804
1,039,302
Dataframe - difference of rows by some style
<p>I want the difference of column 'position' by the column 'Seg' with 'x' adjacent.</p> <pre><code>import numpy as np import pandas as pd mydict = {'position':['0.0', '0.433', '2.013', '3.593', '5.173', '6.753', '6.9'],'Seg':['x', 'x', np.nan, np.nan, np.nan, np.nan, 'x']} df = pd.DataFrame.from_dict(mydict) df po...
<python><pandas><dataframe><difference>
2024-01-25 06:03:07
2
1,713
warem
77,877,686
6,824,915
Solving a LP Transportation Problem with Storage Constraints Using Pyomo Python
<p>It's been a few years since I have done any optimization and I am set about solving a transportation problem using LP via Pyomo.</p> <p>The minimization problem:</p> <p><a href="https://i.sstatic.net/cOA1n.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/cOA1n.png" alt="LP Minimization Problem" /></a><...
<python><linear-programming><pyomo>
2024-01-25 05:23:12
1
371
DudeWah
77,877,654
8,540,947
How to get the exact index ID numbers of Maya ramp points using Maya python commands and not API
<p>Is it possible to query the Index numbers of the points of a 2D graph texture in Maya using Maya commands and Python and not API code? The points do not necessarily start at 0 and are not always sequential. <a href="https://i.sstatic.net/ct07L.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/ct07L.jpg"...
<python><textures><maya>
2024-01-25 05:11:51
1
519
winteralfs
77,877,602
12,789,602
Odoo 16 MailThread._message_auto_subscribe_notify() missing 1 required positional argument: 'template'
<p>In Odoo 16, Mail Thread notify called in a custom module.</p> <pre class="lang-py prettyprint-override"><code>if approver.user_id: self._message_auto_subscribe_notify([approver.user_id.partner_id.id]) </code></pre> <p>But throwing an error,</p> <p><a href="https://i.sstatic.net/uM8Di.png" rel="nofollow noreferrer...
<python><python-3.x><xml><odoo><odoo-16>
2024-01-25 04:49:57
2
552
Bappi Saha
77,877,444
19,675,781
Seaborn heatmap legend disturb the plots order with subplots
<p>I have 2 dataframes like this:</p> <pre><code>df1 = pd.DataFrame(np.random.randint(0,50,size=(5,5)), columns=list('ABCDE')) df2 = pd.DataFrame(np.random.randint(0,50,size=(5,5)), columns=list('FGHIJ')) </code></pre> <p>I want to create 2 heatmaps side by side for these two dataframes. The dataranges of these datafra...
<python><matplotlib><seaborn><legend>
2024-01-25 03:51:38
1
357
Yash
77,877,343
10,693,596
List all properties defined on a Pydantic BaseModel
<p>Is there an elegant way to list all properties defined on a Pydantic BaseModel?</p> <p>It's possible to extract the list of fields via BaseModel.model_fields and the list of computed fields via BaseModel.model_computed_fields, but there does not appear to be a method for listing all the properties.</p> <pre class="l...
<python><pydantic><python-class><pydantic-v2>
2024-01-25 03:10:07
2
16,692
SultanOrazbayev
77,877,288
11,163,122
How to cache playwright-python contexts for testing?
<p>I am doing some web scraping using <a href="https://github.com/microsoft/playwright-python" rel="nofollow noreferrer"><code>playwright-python&gt;=1.41</code></a>, and have to launch the browser in a headed mode (e.g. <code>launch(headless=False)</code>.</p> <p>For CI testing, I would like to somehow cache the headed...
<python><caching><playwright><playwright-python>
2024-01-25 02:48:18
3
2,961
Intrastellar Explorer
77,877,225
3,727,079
How can I do this calculation without opening the same file twice?
<p>I've got a bunch of txt files: <code>A.txt</code>, <code>B.txt</code>, etc. With each file, I can calculate a variable <code>varA</code>, <code>varB</code>, etc. I then want to take the difference of these variables, select the 10 combinations whose differences are smallest, and use those txt files to perform even m...
<python><algorithm>
2024-01-25 02:21:14
1
399
Allure
77,876,971
10,391,013
Creating list of modified sub-words with indexes
<p>I have to make a code for a personal project. I got stuck in dealing with strings that have repeated characters. I need to get all correct indexes of each sub-word originated from a string (of course is a DNA string). I need all the correct indexes of each sub-words combinations (a list of small words build from the...
<python>
2024-01-25 00:35:04
2
504
Paulo Sergio Schlogl
77,876,917
6,111,957
PyTest produces warning DeprecationWarning: There is no current event loop
<p>I have added pytest-asyncio to my poetry test and dev groups with the following code:</p> <pre class="lang-py prettyprint-override"><code> async def blah(): return 1 @pytest.mark.asyncio async def test_me(mock_client, mock_config, event_loop): res = await blah() assert 1 ...
<python><pytest><pytest-asyncio>
2024-01-25 00:15:42
1
432
Yason
77,876,761
1,584,120
django rest framework serializer.data throws error about attribute in manytomany relationship
<p>I have the following models:</p> <pre><code>class MenuItem(models.Model): class Category(models.TextChoices): PIZZA = &quot;pizza&quot; SIDE = &quot;side&quot; OTHER = &quot;other&quot; name = models.CharField(max_length=40) description = models.TextField(max_length=150) ...
<python><django><django-models><django-rest-framework><manytomanyfield>
2024-01-24 23:23:27
1
1,261
user1584120
77,876,547
3,112,985
Why are Alembic environment tags Optional[str]
<p>I'm running Alembic within our application code, where we have already created the sqlalchemy engine. I can pass the engine to the env.py using the <code>tag</code> parameter. However, the definition of the Alembic command I'm calling in our application is (copied from the Alembic python package):</p> <pre><code>def...
<python><sqlalchemy><alembic>
2024-01-24 22:18:02
1
1,325
Jibbity jobby
77,876,520
1,591,921
Type-hint a Python function that *never* raises exception
<p>I have an async Python contextmanager that will (among other things) catch any exceptions thrown in the with-block.</p> <p>Is there a way to indicate to my users that doing a try-catch over it is a bad idea (as it will catch any exceptions).</p> <p>I think the answer is ”no, its impossible”, but couldnt find a defin...
<python><mypy><python-typing>
2024-01-24 22:12:39
0
11,630
Cyberwiz
77,876,489
16,547,860
Pyspark dataframe creadted using jdbc, but when tried to write it to a parquet file in hdfs, throws `year out of range` error
<p>I am trying to do data ingestion from Oracle to Hive DB(hdfs) using Pyspark.</p> <p>The source table has data row as given:</p> <pre><code>LOAD_TIMESTAMP| OPERATION| COMMIT_TIMESTAMP|KSTOKEY| LPOLNUM|LSYSTYP| XPOLVSN| LPOLVSN| XSTOTYP| DSTODAT| DSTOTIM| 2024-01-24 16:23:...|2.000...
<python><apache-spark><hadoop><pyspark><hdfs>
2024-01-24 22:05:53
0
312
Shiva
77,876,447
850,781
No module named 'distutils' despite setuptools installed
<p>I get:</p> <pre class="lang-none prettyprint-override"><code>$ pip install -e . ... ModuleNotFoundError: No module named 'distutils' </code></pre> <p>with Python 3.12, despite:</p> <pre class="lang-none prettyprint-override"><code>$ conda install setuptools ... All requested packages already installed. $ pip instal...
<python><conda><setuptools><distutils><python-3.12>
2024-01-24 21:55:48
2
60,468
sds
77,876,442
8,849,755
Why pandas.DataFrame.join is not doing what I expect?
<p>I have one data frame <code>inverters</code> which looks like this:</p> <pre><code> Voltage (ADCu) Time (ps) n_TDC signal 0 0 INV[0] 1404 INV[0] 1403 INV[0] 1403 INV[0] 1404 ...
<python><pandas>
2024-01-24 21:53:55
2
3,245
user171780
77,876,395
11,422,610
How do i break out of this while loop in Python?
<pre><code>def main(): dmn_options = [&quot;lenovo&quot;, &quot;rasbberrypi&quot;, &quot;Exit&quot;] while True: display_menu(dmn_options) user_choice = select_single_l(dmn_options);print(user_choice) def display_menu(options): print(&quot;Select an option:&quot;) for index, option in enumerate(...
<python><python-3.x><while-loop><break>
2024-01-24 21:44:31
2
937
John Smith
77,876,372
8,540,947
getting erroneous red points when controlling a Maya ramp texture using Python
<p>I am using a python script and the getAttr and setAttr Maya commands on 2d ramp textures in Maya 2022. The ramp attrs are saved out to a text file and read back in and applied to other ramps so the values can be shared. Sometimes, it works perfectly, but other times I am getting extra red points added to the ramp an...
<python><textures><maya>
2024-01-24 21:40:06
2
519
winteralfs
77,876,253
13,171,274
Sort imports alphabetically with ruff
<p>Trying ruff for the first time and I'm not being able to sort imports alphabetically, using default settings. According to docs ruff should be very similar to isort.</p> <p>Here is a short example with unsorted imports</p> <pre><code>import os import collections </code></pre> <p>Run ruff command</p> <pre><code>$ ruf...
<python><isort><ruff>
2024-01-24 21:12:26
2
358
alan
77,876,062
11,197,957
Safety of passing integers between Python and Rust
<h2>Is This Safe?</h2> <p>Suppose I wanted to call some <strong>Rust</strong> code from within <strong>Python</strong>. Suppose my <code>lib.rs</code> looks something like this:</p> <pre class="lang-rust prettyprint-override"><code>#[no_mangle] pub extern fn add(left: i32, right: i32) -&gt; i32 { return left+right;...
<python><rust><ctypes><integer-overflow>
2024-01-24 20:34:26
1
734
Tom Hosker
77,875,984
10,467,153
How to activate Python virtualenvironment not knowing the terminal
<p>I need to activate Python's virtual environment from inside Makefile.</p> <p>Python <code>venv</code> module creates virtual environment with activation files for 3 different terminals:</p> <ul> <li>activate</li> <li>activate.bat</li> <li>Activate.ps1</li> </ul> <p>is it possible to activate virtual environment from...
<python><makefile><terminal><virtualenv>
2024-01-24 20:19:30
1
352
tikej
77,875,969
10,935,321
Azure Machine Learning pin python version on notebook
<p>Looking for a way to use Python 3.10 on a compute resource associated to Azure ML Studio It appears 3.10 is available with ML Studio and we select 3.10 with SDK2 from the kernel selection dropdown but when running a &quot;python --version&quot; on the terminal, it says v 3.8.5. Is there a way to get Azure ML Studio ...
<python><azure><azure-machine-learning-service>
2024-01-24 20:16:09
1
385
mac
77,875,930
5,790,653
find the lowest number in json value and find the value of that key
<p>I have <code>file.json</code>:</p> <pre class="lang-json prettyprint-override"><code>[ { &quot;name&quot;: &quot;personA&quot;, &quot;valA&quot;: 2, &quot;valB&quot;: 0 }, { &quot;name&quot;: &quot;personB&quot;, &quot;valA&quot;: 3, &quot;valB&quot;: 2 ...
<python>
2024-01-24 20:07:42
2
4,175
Saeed
77,875,829
10,318,539
Connection of python 3.10.9 with Matrikon Server
<p>I am currently working on connecting Python with Matrikon Server Simulation. I am encountering several issues and am not aware of its default port. Nevertheless, I am facing errors in the process.</p> <p>Python Code:</p> <pre><code>import opcua c = opcua.Client(&quot;opc.tcp://localhost:53530/Matrikon.OPC.Simulation...
<python><opc>
2024-01-24 19:45:12
1
485
Engr. Khuram Shahzad
77,875,736
9,462,829
fetch GeoJSON from Flask backend and use it in Google Maps Javascript API
<p>I'm working on an app that'll draw some shapes on a Google Maps map, using Flask as the backend. As a test, I'm trying to draw <a href="https://storage.googleapis.com/mapsdevsite/json/google.json" rel="nofollow noreferrer">these shapes</a> into my map. I have this simple function:</p> <pre><code>@app.route('/test', ...
<javascript><python><flask>
2024-01-24 19:26:24
1
6,148
Juan C
77,875,632
20,793,070
How to create pandas dataframe without rounding long values
<p>I have the sample:</p> <pre><code>import pandas as pd data = [[1706121660, 1.152229705572702e-06, 1.074741466619169e-06, 1.074741466619169e-06, 1.074741466619169e-06, 0.28], [1706121600, 1.125333298543622e-06, 1.157527924446797e-06, 1.088866832550798e-06, 1.152229705572702e-06, 4.681397952]] df = pd.DataFrame(data)...
<python><pandas><dataframe>
2024-01-24 19:06:17
4
433
Jahspear
77,875,529
2,893,496
How to find a tag with an arbitrary attribute having an arbitrary value with Beautiful Soup?
<p>I am trying to find <code>&lt;a&gt;</code> tag with <code>itemprop</code> attribute being <code>url</code>. So far the only approach i found is to use a lambda:</p> <pre><code>soup.find(lambda a : a.name=='a' and a.has_attr('itemprop') and a['itemprop']=='url') </code></pre> <p>But somehow i cannot believe that this...
<python><beautifulsoup>
2024-01-24 18:45:32
1
5,886
v010dya
77,875,473
1,744,491
Pulumi error: key: massage(attr[key], seen) for key in attr if not key.startswith("_")
<p>I'm trying to build a simple bucket with intelligent tiering configuration, but I'm getting an error from pulumi code. The code message isn't intuitive and it seems to be a bug on the project or some config that I'm missing. Here follows my code:</p> <pre><code>import pulumi from pulumi_aws import s3 # logging buck...
<python><pulumi-python>
2024-01-24 18:34:57
1
670
Guilherme Noronha
77,875,331
7,748,291
Relative import of local package with VS code
<p>I typically have a folder open in VS code which contain my python project with a <code>.venv</code> folder.</p> <p>I placed my current project in such a way that I have to go back to the parent folder to find my other module.</p> <pre><code>workspace_folder -- module_to_import --- __init__.py --- submodule1 ---- __i...
<python><relative-import>
2024-01-24 18:06:25
0
363
mooder
77,875,253
4,240,413
Why does local inference differ from the API when computing Jina embeddings?
<p>I am computing <a href="https://jina.ai/news/jina-embeddings-2-the-best-solution-for-embedding-long-documents/" rel="nofollow noreferrer">Jina v2 embeddings</a> via the <code>transformers</code> Python libraries and via the API (see <a href="https://jina.ai/embeddings/" rel="nofollow noreferrer">https://jina.ai/embe...
<python><nlp><huggingface-transformers><sentence-transformers><jina>
2024-01-24 17:52:59
1
6,039
Davide Fiocco
77,875,128
2,386,113
How to aling the data along y-axis in Matlibplot
<p>I have created a MWE to explain my issue. As seen in the plot below, the curves are moving along the horizontal axis. I need to force the curves to move along the vertical axis, and set the corresponding ticks on the x-axis.</p> <p><a href="https://i.sstatic.net/TlPmE.png" rel="nofollow noreferrer"><img src="https:/...
<python><matplotlib>
2024-01-24 17:32:55
1
5,777
skm
77,875,111
8,919,749
How to get minutes between to dates?
<p>I have the following dates (<code>&quot;%Y-%m-%dT%H:%M:%S.%f&quot;</code> format) :</p> <pre><code>dateA = &quot;2024-01-24T03:09:28.000523&quot; dateB = &quot;2024-01-24T03:24:04.000719&quot; </code></pre> <p>How can we get the difference between these two dates for a result in minutes ?</p>
<python><date><datetime>
2024-01-24 17:30:49
1
380
Mamaf
77,875,055
3,358,927
How to force using a lower version python library in Databricks
<p>I am trying to use huggingface <code>transformers</code> in Databricks runtime 13.3. However current version of transformers can't be imported because it conflicts with the version of <code>urllib3</code> (2.1.0) that is preinstalled on the cluster. A lower version would work with <code>transformers</code>. However ...
<python><pip><databricks>
2024-01-24 17:22:39
1
5,049
ddd
77,875,049
1,254,515
Method association in python dataclass
<p>I have to maintain code which uses dataclasses. In these, methods from libraries are imported and associated and I find the way it's done confusing and not very readable. It's done like this (a very simplified example) :</p> <pre><code>from dataclasses import dataclass from code.custom.package import method_a, metho...
<python><python-dataclasses>
2024-01-24 17:22:05
2
323
Oliver Henriot
77,874,908
14,230,633
Polars `ValueError: could not convert value 'Unknown' as a Literal` when taking mean of function of variable
<pre><code>┌───────┬─────┐ │ group ┆ var │ │ --- ┆ --- │ │ i64 ┆ str │ ╞═══════╪═════╡ │ 1 ┆ x │ │ 1 ┆ x │ │ 2 ┆ x │ │ 2 ┆ y │ │ 3 ┆ y │ │ 3 ┆ y │ └───────┴─────┘ </code></pre> <p>Suppose the above dataframe is called <code>df</code> and I want to get the percentage of variables ...
<python><dataframe><python-polars>
2024-01-24 17:02:07
1
567
dfried
77,874,878
2,410,605
Selenium Python How Do I Read the child elements of the '//following' td tag?
<p><a href="https://i.sstatic.net/bD0ge.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/bD0ge.png" alt="enter image description here" /></a></p> <p>I have this list that I need to cycle through until I reach the munprod DB on the host server ending with &quot;01&quot;. I'm using the code below and appare...
<python><selenium-webdriver>
2024-01-24 16:57:30
2
657
JimmyG
77,874,837
6,766,408
On calling list values in robot framework returns an error "List '${element}' has no item in index 0"
<p>I am using Robot Framework, Selenium Library in Pycharm. I need to fetch product id from below table and then save it in the list</p> <p><a href="https://i.sstatic.net/oWbxV.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/oWbxV.png" alt="enter image description here" /></a></p> <p>below code to create...
<python><list><selenium-webdriver><pycharm><robotframework>
2024-01-24 16:53:05
2
312
ADS KUL
77,874,808
2,556,795
How to get all possible combinations at a column level
<p>I have following dataframe which is subset of my larger dataframe.</p> <pre class="lang-py prettyprint-override"><code>df = pd.DataFrame({'item':['a','a','a','b','b','a','b','a','a','b','a','b','a','a','b'], 'country':['in','in','in','in','in','in','us','us','us','us','us','uk','uk','uk','uk'], ...
<python><pandas>
2024-01-24 16:47:49
0
1,370
mockash
77,874,757
10,452,700
How can down-sampling periodic time-series data without loosing general pattern for characterization analysis?
<p>I'm experimenting with the characterization of data over time after downsampling. After studying this <a href="https://stackoverflow.com/q/18060619/10452700">post</a>, I generated some synthesized data with certain periodic patterns over time every 5mins (granularity of 5mins= data generated with the interval of 5 m...
<python><time-series><fft><resampling><periodic-processing>
2024-01-24 16:39:36
0
2,056
Mario
77,874,385
19,130,803
Simplifing big imports to short
<p>I am working on python application with following structure.</p> <pre><code>proj/ - __init__.py - pkg_one/ - __init__.py - module_a.py - module_b.py - pkg_two/ - __init__.py - module_c.py - sub_pkg_two/ - __init__.py - module_d.py - class D ...
<python>
2024-01-24 15:47:55
1
962
winter
77,874,240
1,488,821
Is there a way to block on applying tasks in Python ThreadPool if all the threads in the pool are busy?
<p>I'm consuming a queue and need to pass the data to a thread pool for processing, but I don't want to consume more items than the thread pool can handle. In other words, I want the thread pool to regulate the rate at which the queue is consumed.</p> <p>With Python's default <code>ThreadPool</code>, the <code>apply_as...
<python><python-multithreading>
2024-01-24 15:25:29
1
2,030
Ivan Voras
77,874,031
8,737,016
Efficient access of nested dictionaries from a list of keys
<p>I would like to be able to access a nested dictionary from a list of keys. For example, if</p> <pre class="lang-py prettyprint-override"><code>d = { 'a': { 'b': { 'c': 1 }, 'd': 2 } } </code></pre> <p>To access <code>c</code> I need the keys <code>'a'</code>, <code>'b'</co...
<python>
2024-01-24 14:57:32
0
2,245
Federico Taschin
77,873,841
2,182,636
Using Playwright to Find and Click on Button with Dynamic CSS (Scraping TikTok)
<p>I am working on an OSS scraper for various social media platforms. I have a small issue with TikTok. I can successfully scrape the profile and get metadata. However, I also want to pull back metadata about videos associated with the profile. The video information is contained in an XHR call.</p> <p>However, afte...
<python><playwright><playback><playwright-python><tiktok>
2024-01-24 14:31:18
1
586
cgivre
77,873,836
12,560,539
use typing.Dict or dict in the Python
<p>In the Python, dict and typing.Dict, I am seeing some information to say typing.Dict &quot;Deprecated since version 3.9&quot;</p> <p>I am confused what I should choose dict or typing.Dict since Python 3.9?</p>
<python>
2024-01-24 14:30:36
2
405
Joe
77,873,508
22,221,987
How to exclude logging.exception from logfile, but include it in stdout without defining custom logging level
<p>I have custom logger with default levels. I want to show <code>logging.exception</code> &quot;level&quot; in logfile, but exclude it from stdout (I want to leave short error messages in stdout). It's important that I don't want to declare custom level, because I want to leave some customisation space for user (switc...
<python><python-3.x><logging>
2024-01-24 13:40:23
1
309
Mika
77,873,455
14,586,843
model.fit throws me error "Expected tensor of type int64 but got type float" at random epoch
<p>I am trying to fit this model with tensorflow :</p> <pre class="lang-py prettyprint-override"><code>from tensorflow.keras.models import Sequential, load_model from tensorflow.keras.layers import Input, Dense, Dropout, BatchNormalization from tensorflow.keras.optimizers import Adam import tensorflow.keras.regularizer...
<python><python-3.x><tensorflow><keras>
2024-01-24 13:33:11
0
428
Louis Lecouturier
77,873,418
22,937,009
Efficient calculation of all permutations mapping a vector into another in Python?
<p>Given two vectors, I would like to calculate (in Python) all permutations (as vectors of coordinates) which map the first vector into the second. The vectors are given as <code>numpy</code> arrays of the same length, I call them <code>f_arr</code> (the source vector mapping from) and <code>t_arr</code> (the target v...
<python><numpy><permutation><combinatorics><enumeration>
2024-01-24 13:27:44
1
432
gabalz
77,873,084
3,975,218
Calling constructors of both parents in multiple inheritance in Python (general case)
<p>I'm trying to figure out the multiple inheritance in Python, but all articles I find are limited to simple cases. Let's consider the following example:</p> <pre><code>class Vehicle: def __init__(self, name: str) -&gt; None: self.name = name print(f'Creating a Vehicle: {name}') def __del__(se...
<python><inheritance><super><diamond-problem>
2024-01-24 12:32:00
2
740
Karol Borkowski
77,873,027
194,000
Django: Basic auth on only certain URL paths?
<p>I would like to password-protect only certain parts of my Django app with basic-auth. I'd like to protect all URLs except anything under <code>/api</code>.</p> <p>I'm trying to use the <a href="https://pypi.org/project/django-basicauth/" rel="nofollow noreferrer">django-basicauth package</a> to do this.</p> <p>I've ...
<python><django><basic-authentication>
2024-01-24 12:22:51
3
66,078
Richard
77,872,975
7,344,609
How to make use of Conditional expression of Pynamodb for graphQl?
<p>I am using PynamoDB for querying DynamoDB tables. Its a basic table with user_id as PK and name as SK. Also I have created a LSI with user_id as PK and unit as SK.</p> <p>To make a query based on user_id and name we can write the query in following way.</p> <pre><code>result = userModel.query(user_id, name) print(re...
<python><amazon-dynamodb><pynamodb>
2024-01-24 12:15:32
1
561
Darshan theerth
77,872,944
19,694,624
discord embed freezes on 2nd execution
<p>I have a problem with a slash command, with an embed actually.</p> <p>When I run the slash command, I get an embed with a button with a label &quot;xN&quot; (where N - any number from 1 to 99). This embed gets edited every 2 seconds, and the button's label and id increase by 1. If I click the button, callback functi...
<python><python-3.x><discord><discord.py><pycord>
2024-01-24 12:12:01
1
303
syrok
77,872,941
534,238
How can I use `DoOutputsTuple` as either the parameter or the return of a `PTransform` in Apache Beam
<p>I have some <code>DoFn</code>s that return multiple output <code>PCollection</code>s, where one represents the &quot;good&quot; data path and the other captures errors to redirect them. Something like the following:</p> <pre class="lang-py prettyprint-override"><code>output, error = ( pcol | &quot;Fi...
<python><apache-beam>
2024-01-24 12:11:15
1
3,558
Mike Williamson
77,872,848
5,733,813
Understanding interferences between python importing policy and pytest mocking
<p>I am having some troubles in understanding how to properly mock a function using <code>pytest-mock</code> module.</p> <p>I will report a minimal reproducible example:</p> <p>file: <code>src/mini_handler.py</code></p> <pre><code>import tempfile from src.mini_pdf_handler import mini_pdf_handler def mini_handler(): ...
<python><pytest><pytest-mock>
2024-01-24 11:56:30
1
521
Francesco Alongi
77,872,459
6,575,732
How to deal with nested protocols and generics for Python stubs
<p>I'm trying to define a <code>Protocol</code> for a <code>Stream</code> object. <code>Stream</code> should be generic over two parameters: inputs and outputs. <code>Stream</code> defines methods that return a new stream with the new inputs being the outputs from the original stream and the output something else. For ...
<python><generics><protocols><mypy><typing>
2024-01-24 10:59:46
0
351
DIN14970
77,872,293
12,892,937
Python how to vectorize this loop that perform assignment of a sub-rectangle inside an image
<p>I have 2 arrays: <code>bot</code> and <code>top</code>, and an <code>image</code>. I need to loop over the array, and for each pair of <code>(bot,top)</code>,I need to fill column <code>3 * i + 1</code> from rows <code>bot[i]</code> to <code>top[i]</code> with 255.</p> <p>I want to use vectorized code instead of a f...
<python><pandas><numpy><optimization><vectorization>
2024-01-24 10:37:04
1
1,831
Huy Le
77,872,291
11,937,086
Python tfcausalimpact: how can I access the p-value?
<p>I'm using tfcausalimpact (<a href="https://github.com/WillianFuks/tfcausalimpact" rel="nofollow noreferrer">https://github.com/WillianFuks/tfcausalimpact</a>).</p> <p>When I run the analysis, I know that I can access the p-value by instantiating the model</p> <p><code>ci = CausalImpact(data,pre_period,post_period)</...
<python><p-value><attribution>
2024-01-24 10:36:53
1
378
travelsandbooks
77,872,289
9,640,238
Disable caching or clear cache with QtWebEngine
<p>I have been using a slightly adapted version of the <code>OpenconnectSamlAuth</code> class that has been shared <a href="https://stackoverflow.com/a/65694690/9640238">here</a>, with PyQT5.</p> <p>Now, I'd like to either clear the cache or disable it entirely. I have to admit that the code is a bit opaque to me (I'm ...
<python><pyqt5>
2024-01-24 10:36:35
1
2,690
mrgou
77,872,274
1,631,190
Python Pandas Pivot Table Count Occurrences without dummy column
<p>Whats the most elegant way to pivot a dataframe and getting to counts from the following example:</p> <pre><code>id type 1 A 1 A 1 B 2 A 1 B </code></pre> <p>to get a wide format df looking like this</p> <pre><code>id A B 1 2 1 2 1 1 </code></pre> <p>At the moment I am going with creating...
<python><pandas><pivot>
2024-01-24 10:35:20
1
1,901
J-H
77,871,919
8,144,423
Ensure all dates are present in each group (eg retailer) in dataframe
<p>I am trying to make sure, that for every groups I will have all dates presents (as I would like to have sum of rolling window of 7 days). My initial data has &quot;blanks&quot; in days that retailer was not selling products, and I would like to fill them with 0.</p> <pre><code>Initial data: | Date | Retailer | Sales...
<python><dataframe>
2024-01-24 09:44:55
1
483
AAAA
77,871,888
6,535,324
source/activate python venv from shell script
<p>I have a shell script which I run on win10 usin git bash. It calls python under the hood. For this to work I need to run the following two lines before in git bash:</p> <pre><code>source /c/Mambaforge/etc/profile.d/conda.sh conda activate my_py_venv bash setup_stuff.sh bash shell_script_using_python.sh </code></pre>...
<python><bash><shell>
2024-01-24 09:39:29
0
2,544
safex
77,871,587
4,583,536
Environment variable interpolation does not work with @_here_
<p>I'm setting up hydra config for my python project and struggling a bit to get variable interpolation working in the following context.</p> <p>Directory structure</p> <pre><code>├── config/ │ ├── config.yaml │ ├── deployment.yaml │ │ ├── objects.yaml │ └── environment │ ├── dev.yaml │ └── prd.ya...
<python><fb-hydra><omegaconf>
2024-01-24 08:48:38
1
528
David Clarance
77,871,427
23,287,531
Script does not save output to correct path while using auto py to exe
<p>my program uses netsh to save wifi profile information on a txt file in a directory that is named as the system time of the moment of running the program</p> <p>so lets say you have signed into three wifi networks on your PC:</p> <p>Wifi1: password:123456 wifi2: password: abcdefg wifi3: password: 12456!</p> <p>and t...
<python><windows><visual-studio-code><netsh><auto-py-to-exe>
2024-01-24 08:13:47
1
433
Roee Zamir
77,871,393
3,098,783
Dockerfile build with setuptools - how to avoid full rebuild when files change
<p>If have to dockerize an existing project that uses setuptools for building from a <code>setup.py</code> file, instead of <code>requirements.txt</code>.</p> <p>This build includes large binary downloads (pytorch, fast-whisper) and after the build at runtime an initial download of the corresponding models. Alltogether...
<python><docker><caching><setuptools>
2024-01-24 08:06:50
2
8,471
Jankapunkt
77,871,364
6,882,746
Vectorize a Convex Hull and Interpolation loop on a specific axis of an ndarray
<p>I'm struggling to find an efficient way to implement this interpolated convex hull data treatment.</p> <p>I have a 2D ndarray, call it <code>arr</code>, with shape (2000000,19), containing floats. I have a 1D ndarray, call it <code>w</code>, with shape (19,), also containing floats.</p> <p>What I achieved (and works...
<python><numpy><vectorization><convex-hull>
2024-01-24 07:58:53
1
2,053
Laurent
77,871,144
12,705,907
TypeCheckError: argument "config_file" (None) did not match any element in the union: pathlib.Path: is not an instance of pathlib.Path
<p>I am getting an error when I tried to implement pandas profiling. Please find the code that I've tried, the error I got and the versions of the packages I used.</p> <p>Code:</p> <pre><code>import pandas as pd from pandas_profiling import ProfileReport df = pd.read_csv(&quot;data.csv&quot;) profile = ProfileReport(df...
<python><python-3.x><pandas><pip><pandas-profiling>
2024-01-24 07:16:30
1
714
Senthil Vikram Vodapalli
77,871,139
11,607,378
How do I debug a Python-C++ mixed project with gdb attach process and catch throw?
<p>I am having a mixed Python &amp; C++ project and using the following steps to debug:</p> <ul> <li>start Python process</li> <li>use <code>ps ax | grep python</code> to identify the process debugging process that will be attached to</li> <li>start the gdb attach process The &quot;gdb process&quot; in VSCode has follo...
<python><c++><gdb>
2024-01-24 07:15:26
0
673
Litchy
77,871,084
4,948,889
Unable to communication Socket Python from Local Windows system to WSL Ubuntu
<p>I have a simple socket communication program in python: This program is running from windows so that I can fetch the output:</p> <pre><code>#!/usr/bin/env python3 import socket HOST = &quot;172.19.112.1&quot;#&quot;127.0.0.1&quot; # The server's hostname or IP address PORT = 65432 # The port used by the server ...
<python><python-3.x><sockets><windows-subsystem-for-linux>
2024-01-24 07:01:13
0
7,303
Jaffer Wilson
77,870,975
10,964,685
Append new data to existing dataframe more efficiently - python
<p>Is there a more efficient way to append new data to an existing dataframe? As per the following example, I'm importing an existing df (<code>frame_orig</code>). Then some more code is performed, which produces some new values. I then append these back to the original df and export out.</p> <p>This works fine but if ...
<python><pandas>
2024-01-24 06:35:13
1
392
jonboy
77,870,893
896,112
"NumbaPerformanceWarning: '@' is faster on contiguous arrays" warning on `@jitclass` methods
<p>Consider the following program which creates a <code>Rotator</code> class that stores a rotation matrix <code>_R</code> and can <code>rotate</code> a vector <code>v</code>:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np import numpy.typing as npt import numba as nb from numba.experimental imp...
<python><numpy><numba>
2024-01-24 06:14:52
0
9,259
Carpetfizz
77,870,725
3,810,748
Python Plotly: X-Axis Glitches When Attempting to Draw Unified Spike Across Multiple Subplots
<h3>Background</h3> <p>I am currently attempting to draw a unified spike across multiple subplots when hovering. I want to do this to improve the visualization of the x-axis. I am currently following <a href="https://github.com/plotly/plotly.py/issues/1677#issuecomment-514661015" rel="nofollow noreferrer">advice from t...
<python><plotly>
2024-01-24 05:27:27
1
6,155
AlanSTACK
77,870,655
22,285,820
Replacing google slides images using slides api in shared google drives
<p>Following up with my <a href="https://stackoverflow.com/questions/77706103/replacing-google-slides-images-using-slides-api">previous</a> question, now, facing an error when I use <code>shared google drive</code> with the <code>service account</code> having <code>Manager</code> privilege on that shared drive, it is f...
<python><presentation><google-slides-api><google-slides><google-drive-shared-drive>
2024-01-24 05:01:53
0
596
nisakova
77,870,505
1,802,483
Python 3.12 Write Chinese in Excel CSV - UTF-8-SIG not work
<p>I am using Python 3.12.1 and upload it to AWS Lambda.</p> <p>What I am doing is to get data from a MySQL DB (with some Chinese text in it) and export to Excel CSV.</p> <p>Here is the code:</p> <pre class="lang-py prettyprint-override"><code># Copied from https://gist.github.com/tobywf/3773a7dc896f780c2216c8f8afbe62f...
<python><excel><csv><utf-8>
2024-01-24 03:56:17
1
705
Ellery Leung
77,870,483
9,184,839
How reboot remote machine via ssh avoiding timeout?
<p>I have this part of code where I am trying to reboot a remote machine over ssh :</p> <pre><code>def check_and_reboot(ssh, hostname): # if not ssh_connect(ssh, hostname): # print(&quot;SSH failed, restarting {}&quot;.format(hostname)) # Step 2: If connection fails, reboot the machine if not reboot...
<python><ubuntu><ssh><paramiko><reboot>
2024-01-24 03:49:22
1
505
Aravind S
77,870,417
574,563
no data from polygon.io websocket
<p>I'm running a python script locally in the console to connect to polygon.io's stocks websocket to get aggregate second data.</p> <p>when I run this code, I don't get any errors, but I also see no data streaming in the console. I am using AM.TSLA as a test. I verified with polygon support that my API key is capable o...
<python><websocket><polygon.io>
2024-01-24 03:28:03
1
487
Alexnl
77,870,183
10,518,698
Changing the name of the input layer of a pre-trained model in TensorFlow Transfer Learning
<p>I am trying to change the input layer's name of a Pre-trained TensorFlow model imported from Keras</p> <p>I am able to add the output layer name but I keep failing in adding input model name. Is it even possible to change the input layer name of a pre-trained model?</p> <p>I can't find any info about this in keras d...
<python><tensorflow><keras><tensorflow-lite><transfer-learning>
2024-01-24 01:56:24
1
513
JSVJ
77,869,957
896,112
Numba fails to compile `jitclass` with with constructor accepting Numpy array arguments
<p>The following implementations of <code>evaluate</code> compile correctly :</p> <pre class="lang-py prettyprint-override"><code>import numpy as np import numpy.typing as npt from numba import njit from numba.experimental import jitclass </code></pre> <p><strong>Standalone Function</strong></p> <pre class="lang-py pre...
<python><numpy><jit>
2024-01-24 00:24:40
1
9,259
Carpetfizz
77,869,940
9,213,600
How to delete the outer circle in an image and only keep the content inside it in OpenCV?
<p>I want to segment the bacteria types inside this microscopic image (original form is in gray), applying various thresholding operations to convert the image into binary format returns noisy results that effects the erosion/dilation/morphological operations that comes later. I want to remove the outer circle (contain...
<python><opencv><image-processing>
2024-01-24 00:18:54
0
1,104
Ali H. Kudeir
77,869,427
2,394,163
When developing Ansible plugins, how should you use module_utils imports?
<p>When developing custom Ansible modules in an Ansible collection, you often want to share code between multiple modules.</p> <p>If I have the following directory structure in my collection:</p> <pre><code>collection/ ... plugins/ modules/ module_one.py module_two.py module_utils/ utils.p...
<python><python-3.x><ansible><ansible-collections>
2024-01-23 21:42:26
1
2,054
Nick
77,869,389
7,087,604
Fast boolean interaction matrix with Numpy
<p>I have 2 integer vectors, one very long <code>document</code> (1E5 to 1E7 elements), and one rather short <code>query</code> (typically 5-8 elements). I want to create a 2D boolean matrix <code>(i, j)</code> that puts <code>1</code> where <code>document[i] == query[j]</code>, otherwise <code>0</code>. For example:</...
<python><numpy>
2024-01-23 21:33:43
1
713
Aurélien Pierre
77,869,307
152,873
Altair: How to format times in axis labels in a non-UTC non-local timezone?
<p>I'm trying to plot some time series data with Altair, and have the times (on the axis labels) show up in a fixed timezone that's not UTC and not the user's local timezone. As far as I can tell from the docs, those are the only options supported (local being the default, and <a href="https://altair-viz.github.io/user...
<python><altair><vega-lite>
2024-01-23 21:15:32
2
9,164
aviraldg
77,869,275
7,155,895
Converting a theme part from Tlc to Python
<p>I have a problem I'm having, which I don't know how to solve, due to my lack of knowledge. I'm trying to recreate the vertical scrollbar of the &quot;<a href="https://github.com/rdbende/Azure-ttk-theme/blob/main/theme/dark.tcl" rel="nofollow noreferrer">Azure-ttk-theme</a>&quot; theme (given that the program will no...
<python><tkinter><python-3.11><tlc>
2024-01-23 21:08:39
1
579
Rebagliati Loris
77,869,089
353,337
mypy doesn't realize a dataclass's member is really what it is via `__post_init__`
<p>I have a <code>dataclass</code> that contains a <code>list[tuple[str,str]]</code>, and I'd like to be able to initialize with a <code>dict[str,str]</code> too. Programmatically it's this:</p> <pre class="lang-py prettyprint-override"><code>from dataclasses import dataclass @dataclass class Foobar: list_of_tuple...
<python><mypy>
2024-01-23 20:28:48
1
59,565
Nico Schlömer
77,869,087
2,410,605
Selenium Python Trying to Better Understand WebDriverWait and Splash/Transition Screens
<p>I'm coding for a website that uses the transition screen below in between each data screen, including when you first connect to the site.</p> <p><a href="https://i.sstatic.net/PkXb9.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/PkXb9.png" alt="enter image description here" /></a></p> <p>So this scre...
<python><selenium-webdriver><webdriverwait>
2024-01-23 20:28:24
0
657
JimmyG
77,868,946
353,337
mypy doesn't understand that the function returns a string
<p>I have a function that returns a <code>str</code> or a specified fallback value (<code>str</code> or <code>None</code>). When giving a <code>str</code> fallback, the function is guaranteed to return a <code>str</code>. Running <a href="https://github.com/python/mypy" rel="nofollow noreferrer">mypy</a> on this howeve...
<python><mypy>
2024-01-23 20:00:47
3
59,565
Nico Schlömer
77,868,799
6,212,718
Polars dataframe: add columns conditional on other column yielding different lengths
<p>I have the following dataframe in <code>polars</code>.</p> <pre class="lang-py prettyprint-override"><code>df = pl.DataFrame({ &quot;Buy_Signal&quot;: [1, 0, 1, 0, 0], &quot;Returns&quot;: np.random.normal(0, 0.1, 5), }) </code></pre> <p>Ultimately, I want to do aggregations on column <code>Returns</code> c...
<python><python-polars>
2024-01-23 19:27:08
2
1,489
FredMaster
77,868,779
6,345,518
Python regex replace quotation marks
<p>Based on <a href="https://stackoverflow.com/a/77846735/6345518">my previous question</a>, I realized that many of my strings are in fact concatenated strings, which makes replacing quotation marks with C++ raw string literal delimiters even harder.</p> <p>F.i. I'd like to substitute the quotation marks in this text:...
<python><regex>
2024-01-23 19:22:35
2
5,832
JE_Muc
77,868,548
1,874,170
Standard way to convert errors into warnings?
<p>I've got this snippet of code, which converts certain <code>Exception</code>s into nonfatal <code>RuntimeWarning</code>s:</p> <pre class="lang-py prettyprint-override"><code> ... for f in filter(_tty_check, [sys.stderr, sys.stdout, sys.stdin]): cur_encoding = _tty_get_encoding(f) if f.encoding != ...
<python><exception><warnings>
2024-01-23 18:32:36
1
1,117
JamesTheAwesomeDude
77,868,494
10,101,636
Splitting a record into multiple records based on character length
<p>I have to split records in a dataframe into multiple records based on character lengths.<br /> <strong>UPDATE</strong>:</p> <p>The dataframe will have the key in a separate column. The <code>value</code> column should be split every 5 characters as above. The key should repeat with every new row generated. Also, a s...
<python><pyspark>
2024-01-23 18:21:17
2
403
Matthew
77,868,464
907,714
Can I further speed up query to find all objects within a range in python
<p>Lets say I have a list of a simple dataclass like:</p> <pre><code>@dataclass class Widget: category: str weight: int </code></pre> <p>I want to write a function that returns all widgets that equal a certain category and are within a certain weight like:</p> <pre><code>def query_widgets(category, lo_weight, h...
<python><algorithm><performance><optimization><data-structures>
2024-01-23 18:17:11
1
3,516
postelrich
77,868,386
1,041,958
Relative Import In Unittest
<p>I have reviewed several posts re: Relative vs Absolute imports, but none of the solutions proposed seemed to solve my problem.</p> <p>I have a directory structure like the following:</p> <pre><code>--src --dir1 --signal __init__.py parent_class.py --hf ...
<python><path><reference>
2024-01-23 18:04:22
1
955
StormsEdge
77,868,356
4,532,845
How to create a file-like wrapper that works just like a file but auto-delete on close/__del__?
<pre class="lang-py prettyprint-override"><code>def (): zip_fd = open(zip_path, mode=&quot;rb&quot;) file = _TemporaryFileWrapper(zip_fd) # Like the one inside tempfile.NamedTemporaryFile return FileResponse(file) # django </code></pre> <p>I would like my file deleted when eventually django is done respo...
<python><django>
2024-01-23 17:57:39
1
391
Edgard Lima
77,868,289
10,446,433
Python subprocess & Poetry cutted/shortened stdout
<p>Since the <em>requiremtns.txt</em> files from <a href="https://python-poetry.org" rel="nofollow noreferrer">Poetry</a> are hard to read, I try to write a simple script that creates the <em>requiremtns.txt</em> file but also at the same time creates a more human readable file next to it. A fitting Poetry command is:<...
<python><python-poetry>
2024-01-23 17:43:38
1
368
SimpleJack
77,868,077
12,320,336
How to prevent unintended blocks from being added?
<p>The top of my input file's third page: <a href="https://i.sstatic.net/5xu8y.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/5xu8y.png" alt="enter image description here" /></a></p> <p>The top of my output file's first page: <a href="https://i.sstatic.net/PfKhb.png" rel="nofollow noreferrer"><img src="...
<python><pdf><pdf-generation><pymupdf>
2024-01-23 17:08:11
0
319
SpectraXCD
77,867,894
13,518,907
Streaming local LLM with FastAPI, Llama.cpp and Langchain
<p>I have setup FastAPI with Llama.cpp and Langchain. Now I want to enable streaming in the FastAPI responses. Streaming works with Llama.cpp in my terminal, but I wasn't able to implement it with a FastAPI response.</p> <p>Most tutorials focused on enabling streaming with an OpenAI model, but I am using a local LLM (q...
<python><fastapi><langchain><llamacpp>
2024-01-23 16:36:43
1
565
Maxl Gemeinderat
77,867,650
6,457,405
You tried to access openai.File, but this is no longer supported in openai>=1.0.0
<p>I am doing fine tuning in chatgpt where I am looking to adjust the model so that it defines a set of subtopics (or related concepts) based on a specific topic (concept).</p> <p>This is my training dataset:</p> <pre><code>{&quot;prompt&quot;:&quot;Wellbeing of Child-&gt;&quot;,&quot;completion&quot;:&quot; Immunizati...
<python><python-3.x><openai-api><chatgpt-api>
2024-01-23 15:58:48
1
395
Daniel
77,867,618
3,336,423
How to convert elapsed days since January 1st year 0000 to Python elapsed seconds since January 1st year 1970
<p>I have a float that comes from Matlab, expressed as a number of days elapsed since January 1st of year 0000.</p> <p>Let's use <code>739183.392799916</code> as an example.</p> <p>In Matlab, <code>datestr(739183.392799916 ,'dd/mm/yyyy-HH:MM:SS.FFF')</code> gives <code>24/10/2023-09:25:37.913</code></p> <p>I'm working ...
<python><matlab><datetime>
2024-01-23 15:55:22
0
21,904
jpo38
77,867,589
127,251
How do you replace set_tight_layout with set_layout_engine?
<p>When I call <code>fig.set_tight_layout(True)</code> on a Matplotlib figure, I receive this deprecation warning:</p> <pre><code>The set_tight_layout function will be deprecated in a future version. Use set_layout_engine instead. </code></pre> <p>How do I call <code>set_layout_engine</code> so as to match the current ...
<python><matplotlib><deprecation-warning>
2024-01-23 15:50:25
1
5,593
Paul Chernoch
77,867,577
8,236,076
How to create table of contents using unstructured (the python package)
<h2>tl;dr</h2> <p>How can I extract a clean table of contents from a pdf document that has hierarchical section headers using the <a href="https://unstructured.io/" rel="nofollow noreferrer"><code>unstructured</code></a> package?</p> <h2>Some more details</h2> <p>I have a pdf document that is multiple pages long. The t...
<python><nlp>
2024-01-23 15:49:04
0
1,144
Willem