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
βŒ€
79,272,285
5,028,466
UserWarning: DataFrame constructor is internal. Do not directly use it. in Foundry
<p>I'm running a Code Workbook in palantir foundry, where one of the steps is below code that takes data from a dataset:</p> <pre><code>import pyspark.sql.functions as F def df_kyc (JOHNNY): JOHNNY = JOHNNY.select(*[ F.col(c).cast(&quot;string&quot;).alias(c) if t == &quot;timestamp&quot; else F.col(c) for c, t in JOHN...
<python><pyspark><palantir-foundry><foundry-code-workbooks>
2024-12-11 15:32:17
1
537
Turpan
79,272,268
447,426
How replace WriteOnlyCollection in DB object - "because the WriteOnlyCollection does not support implicit iteration or direct assignment"
<p>I have an DB object &quot;Part&quot; with a field:</p> <pre><code>health_indicators: WriteOnlyMapped[&quot;HealthIndicators&quot;] = relationship(&quot;HealthIndicators&quot;, uselist=True, back_populates=&quot;part&quot;) </code></pre> <p>So per ...
<python><sqlalchemy>
2024-12-11 15:28:06
1
13,125
dermoritz
79,272,147
1,014,299
ModuleNotFoundError when referencing folder in Python
<p>I have a Python3 project arranged as follows:</p> <p>C:\automation\framework\constants.py</p> <p>C:\automation\tests\unit-tests\test_myunittest.py</p> <p>In my unit test, I'm trying to call methods in framework folder, which has the required <strong>init</strong>.py file At the start of my unit test, I have the foll...
<python><python-3.8><python-module><python-packaging>
2024-12-11 14:49:35
1
1,091
bearaman
79,272,105
5,775,358
VSCode ruff ignores ruff.toml
<p>For a project I have created a <code>ruff.toml</code> file. In this file is among other things a different line-length defined. When ruff is used from the cli <code>ruff format</code> it works as expected. But when I use <code>Ruff: format document</code> from the extension it goes back to the line length defined in...
<python><visual-studio-code><ruff>
2024-12-11 14:39:18
2
2,406
3dSpatialUser
79,272,102
11,159,734
Azure Document Intelligence (formrecognizer) - 'InvalidContent' when passing pdf
<p>I upload a pdf file to my streamlit application like this:</p> <pre><code>import streamlit as st uploaded_file = st.file_uploader(&quot;Upload pdf file&quot;, type=&quot;pdf&quot;) result = analyze_general_document(uploaded_file) </code></pre> <p>I want to analzye this pdf using the <code>Azure Document Intelligenc...
<python><azure><streamlit><azure-form-recognizer>
2024-12-11 14:37:50
3
1,025
Daniel
79,272,101
453,851
How to type hint a decorator to dictate some parameters but not all?
<p>I'm looking of a way (the way) to type hint a decorator indicating the parameters that must exist only. The decorator does not change the signature of the function it wraps.</p> <pre class="lang-py prettyprint-override"><code>from functools import wraps def my_decorator(func): @wraps(func) def wrapper(a: in...
<python><python-typing><mypy>
2024-12-11 14:37:35
1
15,219
Philip Couling
79,272,091
561,243
Use of subclasses of Generic in other classes
<p>I am again fighting against the use of bound type variable in python.</p> <p>Have a look at this example:</p> <pre class="lang-py prettyprint-override"><code> from typing import Generic, TypeVar, Any ParameterType = TypeVar('ParameterType') class Parameter(Generic[ParameterType]): def __init__(self, name: str...
<python><python-typing><mypy>
2024-12-11 14:33:13
0
367
toto
79,271,961
10,306,224
Pydantic/Django Ninja use only existing keys (even with None)
<p>having an app in Django Ninja with schemas:</p> <pre><code>class NumericalFilterSchema(Schema): gt: Optional[int] = None lt: Optional[int] = None gte: Optional[int] = None lte: Optional[int] = None exact: Optional[int] = None class Config(Schema.Config): extra = &quot;forbid&quot; ...
<python><django><validation><pydantic><django-ninja>
2024-12-11 13:50:15
1
905
Leemosh
79,271,959
6,571,328
UPOS Mappings - Tensorflow Datasets TDFS
<p>I am using the tensorflow tdfs dataset <a href="https://www.tensorflow.org/datasets/catalog/xtreme_pos" rel="nofollow noreferrer">extreme/pos</a> which I retrieve using the code below. It is annotated with universal part of speech <a href="https://universaldependencies.org/u/pos/" rel="nofollow noreferrer">POS</a> ...
<python><tensorflow>
2024-12-11 13:50:06
2
393
RodP
79,271,953
4,451,315
cumulative sum per group in PyArrow
<p>In pandas I can do:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd df = pd.DataFrame({'a': [1,2,3,4,5,6], 'b': ['x']*3+['y']*3}) df.groupby('b')['a'].cumsum() </code></pre> <pre><code>0 1 1 3 2 6 3 4 4 9 5 15 Name: a, dtype: int64 </code></pre> <p>How can I get the s...
<python><pyarrow>
2024-12-11 13:48:15
2
11,062
ignoring_gravity
79,271,832
3,084,842
Calculating negative values with numpy.log
<p>I'm trying to do a calculation that contains negative values inside a log (base-e) function. Python's numpy package has the <a href="https://numpy.org/doc/stable/reference/generated/numpy.log.html" rel="noreferrer"><code>log</code></a> function, MWE below:</p> <pre><code>from numpy import exp, log z = 1j*log(-1.1) ...
<python><numpy>
2024-12-11 13:07:34
5
3,997
Medulla Oblongata
79,271,828
2,805,692
No module named 'awsgluedq'
<p>I am trying to run aws glue script in local docker environment</p> <pre><code>import sys from awsglue.transforms import * from awsglue.utils import getResolvedOptions from pyspark.context import SparkContext from awsglue.context import GlueContext from awsglue.job import Job from awsgluedq.transforms import Evaluate...
<python><aws-glue>
2024-12-11 13:06:48
1
317
sdk
79,271,808
5,767,535
Python not finding files from module when not using `from`
<p>I have the following folder structure:</p> <pre><code>C: └── dev └── my_scripts β”œβ”€β”€ __init__.py └── my_utils.py </code></pre> <p>The file <code>my_utils.py</code> includes some function <code>f</code>.</p> <p>The following code works:</p> <pre><code>import sys sys.path.append('C:\dev') from my_sc...
<python><import>
2024-12-11 13:00:52
1
2,343
Daneel Olivaw
79,271,750
16,804,841
Access container class from contained class with python dataclasses
<p>I have a parent class, that contains a child class. Both are implemented with python dataclasses. The classes look like this:</p> <pre class="lang-py prettyprint-override"><code>from __future__ import annotations from dataclasses import dataclass @dataclass class Parent: name: str child: Child @dataclass...
<python><python-typing><mypy><python-dataclasses>
2024-12-11 12:39:54
1
313
Hazel
79,271,743
14,691,751
Why can't my Python interpreter or Arlpy see the Acoustics Toolbox models?
<p>I am trying to use the <a href="http://oalib.hlsresearch.com/AcousticsToolbox/" rel="nofollow noreferrer">Acoustics Toolbox</a> in Python, using the <code>arlpy</code> module. I am able to import <code>arlpy</code> but it cannot see any of the models:</p> <pre><code>&gt;&gt;&gt; import arlpy.uwapm as pm &gt;&gt;&gt;...
<python><windows><path>
2024-12-11 12:38:09
0
388
Dan Pollard
79,271,631
12,016,688
Why reference count of None object is fixed?
<p>I was experimenting with refcount of objects, and I noticed the reference count of <code>None</code> object does not change when I bind identifiers to <code>None</code>. I observed this behavior in python version <code>3.13</code>.</p> <pre class="lang-py prettyprint-override"><code>Python 3.13.0 (main, Oct 7 2024,...
<python><python-3.10><reference-counting><python-3.13>
2024-12-11 11:59:52
1
2,470
Amir reza Riahi
79,271,442
8,831,742
Imported igraph graph does not correctly recognize nodes
<p>I'm switching from <code>networkx</code> to <code>igraph</code> for my graph analysis project and the graph i'm loading from a file is incorrectly classified as completely disconnected.</p> <p>Here is the code i'm using:</p> <pre><code>from sys import argv,getsizeof from igraph import Graph # read network file asse...
<python><graph-theory><igraph>
2024-12-11 11:00:50
0
353
none none
79,271,319
8,868,419
Seleniumbase not logging
<p>I am trying to capture responses using Selenium and undetected, this is working normally using those two:</p> <pre><code>import undetected_chromedriver as uc capabilities = DesiredCapabilities.CHROME capabilities[&quot;goog:loggingPrefs&quot;] = {&quot;performance&quot;: &quot;ALL&quot;} driver = uc.Chrome(headles...
<python><selenium-webdriver><seleniumbase>
2024-12-11 10:22:15
2
2,722
Matteo
79,271,266
3,906,713
Scipy.optimize.minimize returns `Desired error not necessarily achieved due to precision loss.` for a toy problem
<pre><code>import numpy as np from scipy.optimize import minimize np.random.seed(42) nDim = 24 xBase = np.random.normal(0, 1, nDim) x0 = np.zeros(nDim) loss = lambda x: np.linalg.norm(x - xBase) # loss = lambda x: (x - xBase).dot(x - xBase) res = minimize(loss, x0, method = 'BFGS', options={'gtol': 1.0E-3, 'maxiter...
<python><scipy><minimization>
2024-12-11 10:06:38
1
908
Aleksejs Fomins
79,271,090
9,884,998
Generalizing a gaussian mix to take any number of arguments with numpy.vectorize causes performance issues
<p>I am optimizing a gaussian mix using maximum likelyhood estimation. Originally I used the following model:</p> <pre><code>def normal(x, mu, sigma): &quot;&quot;&quot; Gaussian (normal) probability density function. Args: x (np.ndarray): Data points. mu (float): Mean of the distributi...
<python><numpy><performance><gaussian-mixture-model>
2024-12-11 09:05:11
1
529
David K.
79,271,050
14,351,788
logging.getLogger cannot get the logging config info
<p>I have two .py files: main.py and utils.py. The main.py will import funciton from utils.py My plan is that the log info in both .py files can be recorded in the same log file</p> <p>Here is my code:</p> <p>in the main.py:</p> <pre><code>from utils import run import logging # log setting log_path = './logs' if not o...
<python><logging>
2024-12-11 08:50:23
0
437
Carlos
79,270,968
414,830
what is the correct way to pass context to a playwright function when using python django as the basis for a webapp?
<p>I've got a web app that I built first with Flask, then totally rebuilt with Django, to get advantage of the admin interface. It builds a flyer for a kids football match, using the context to overlay on a background image via css absolute position. Once the coach is happy with the image, a button calls a Generate fun...
<python><django><playwright><playwright-python>
2024-12-11 08:19:34
1
1,043
bytejunkie
79,270,956
1,769,197
Python: weird characters in extract_message
<p>I use <code>extract_message</code> from <a href="https://pypi.org/project/extract-msg%20package" rel="nofollow noreferrer">pypi.org/project/extract-msg</a> package to extract outlook messages. It works well until this outlook file causes the error message. I found out that the problem is that the email content conta...
<python><encoding>
2024-12-11 08:14:50
0
2,253
user1769197
79,270,937
7,962,284
Issue with Python Flask App Deployment to Azure App Service During Zip Deployment
<p>I'm facing an issue with deploying my Python Flask app to <strong>Azure App Service(Python 3.9)</strong> using zip deployment. Below are the details:</p> <p><strong>Directory structure:</strong></p> <pre><code>. |---app.py |---requirements.txt </code></pre> <p><strong>Working Code:</strong></p> <p><em>app.py:</e...
<python><azure><flask><gunicorn><zipdeploy>
2024-12-11 08:08:16
1
1,007
chiru
79,270,796
22,146,392
Script is being ran twice when rendering jinja2 template?
<p>I have a python script that renders a jinja2 template. Something like this:</p> <p><code>basic.py</code></p> <pre class="lang-py prettyprint-override"><code>#!/usr/bin/env python3 from jinja2 import Environment, PackageLoader, select_autoescape env = Environment( loader=PackageLoader('basic'), autoescape=se...
<python><jinja2>
2024-12-11 07:20:32
2
1,116
jeremywat
79,270,612
4,248,409
Suppress stdout of a coroutine without affecting other coroutines in python
<pre class="lang-py prettyprint-override"><code>import asyncio import contextlib import os async def my_coroutine(): with open(os.devnull, 'w') as f, contextlib.redirect_stdout(f): print(&quot;This will not be printed&quot;) await asyncio.sleep(1) print(&quot;This will be printed&quot;) async ...
<python><python-asyncio>
2024-12-11 06:05:39
1
530
BAdhi
79,270,538
852,854
The osmnx call graph_from_bbox() reports that it takes 1 positional argument, however, help(ox.graph.graph_from_bbox) appears to expect 4
<p>I am writing a simple test driver to generate an html file, displaying two possible, real-world routes for a very limited area. When I run the python script, I get what I thought would be an easy error to resolve: &quot;line 12, in &lt;module&gt; graph = ox.graph.graph_from_bbox(*bbox, network_type=&quot;drive&quot;...
<python><geospatial><osmnx>
2024-12-11 05:18:50
1
703
plditallo
79,270,262
4,755,229
How do I use cygdb in Conda environment?
<p>I'm trying to run <code>cygdb</code> according to <a href="https://cython.readthedocs.io/en/latest/src/userguide/debugging.html" rel="nofollow noreferrer">this</a> document. However, the <code>cygdb</code> always seem to find the system python instead of the python of current conda environment, as:</p> <pre><code>It...
<python><gdb><cython>
2024-12-11 01:46:13
0
498
Hojin Cho
79,270,237
6,041,629
Modify simple interpolation function to work on a vector?
<p>I am doing many thousands of repetitive interpolations within an optimization algorithm in Python. I have written a function to interpolate a single value fairly efficiently. I would like to extend this to allow for 1D array inputs, as this may help speed up the computations avoiding for loops in my optimizer.</p> <...
<python><interpolation>
2024-12-11 01:31:50
1
526
Kingle
79,270,224
8,176,763
optimizing pull and push to db with python csv and psycopg using airflow
<p>I have a task in airflow that invokes a helper function, the helper function reads data from oracle db and writes that data into an io buffer in batches. Then once the buffer is ready I read from that buffer and write the data. I think the reading step should be fine in terms of memory footprint if i reduce the the ...
<python><io><airflow><psycopg3>
2024-12-11 01:21:59
0
2,459
moth
79,270,171
1,378,252
Unable to import module 'index': No module named 'pydantic_core._pydantic_core
<p>I'm using amplify to push my lambda. When I run it locally via <code>amplify mock function {functionName}</code> it runs and behaves as expected. When I deploy using <code>amplify push</code> it successfully deploys. However when I attempt to run the lambda from the AWS lambda ui I get the following error message.</...
<python><aws-lambda><runtime><aws-amplify><apple-m3>
2024-12-11 00:37:42
1
4,462
toddmetheny
79,270,111
21,935,028
Extract function arguments in PLSQL calls with Antlr4/Python4
<p>I am trying to extract the arguments in function/procedures calls in Oracle PLSQL using Antlr4 and Python3.</p> <p>I trap the enterFunction_argument event (is the right term?) and I <strong>think</strong> the context could have the arguments under <code>arguments</code>, <code>argument</code>, <code>function_argumen...
<python><antlr4>
2024-12-10 23:45:27
1
419
Pro West
79,269,991
4,288,043
Python dateutil is being inconsistent with American vs British date formats
<p>I am using the dateutil library with its 'fuzzy' ability to parse dates out of strings. It seemed to be actually quite good at it but on careful inspection it was jumping back and forth between British and American date formats in reading in, namely whether the middle number is a month (British) or a day (American)<...
<python><python-dateutil>
2024-12-10 22:30:19
1
7,511
cardamom
79,269,976
1,473,517
Is it possible to store bytes in raw format with no space overhead?
<p>I am using heapq and would like the values to be raw bytes to be compared alphabetically. I want to use as little space as possible. Strings, even byte strings, unfortunately come with a space overhead. For example, take this MWE with fake data:</p> <pre><code>from heapq import heappush from pympler.asizeof import a...
<python>
2024-12-10 22:22:56
2
21,513
Simd
79,269,946
986,618
How to create a custom, dynamic permalink/path for pages in Wagtail?
<p>I am trying to define custom permalinks for my Wagtail pages.</p> <p>I use the following code in my model:</p> <pre><code>def get_url_parts(self, request): site_id, root_url, _ = super().get_url_parts(request) return ( site_id, root_url, f&quot;/{self.date.year}/{self.date.month}/{sel...
<python><wagtail>
2024-12-10 22:07:56
0
7,340
MMM
79,269,724
480,118
Importing module error: module does not provide an export named default/{module name}
<p>I have a script named <code>/src/web/static/js/my_vue_widget.js</code>. It looks like this:</p> <pre class="lang-js prettyprint-override"><code>const MyVueWidget = { name: 'MyVueWidget', ... }; export default MyVueWidget; </code></pre> <p>I have an HTML <code>/src/web/static/templates/index.html</code> whic...
<javascript><python><vue.js><fastapi>
2024-12-10 20:33:15
0
6,184
mike01010
79,269,686
13,132,728
Alternate background colors in styled pandas df that also apply to MultiIndex in python pandas
<h1>SETUP</h1> <p>I have the following <code>df</code>:</p> <pre><code>import pandas as pd import numpy as np arrays = [ np.array([&quot;fruit&quot;, &quot;fruit&quot;, &quot;fruit&quot;,&quot;vegetable&quot;, &quot;vegetable&quot;, &quot;vegetable&quot;]), np.array([&quot;one&quot;, &quot;two&quot;, &quot;tot...
<python><pandas><dataframe><pandas-styles>
2024-12-10 20:19:41
1
1,645
bismo
79,269,677
13,328,553
KMS with encryption SDK - how to do envelope encryption?
<p>I am currently using the aws encryption sdk to encrypt and decrypt some of my data (encrypted at rest).</p> <p>However, when trying to decrypt a lot of the data at once, it is very slow. On inspection, it seems that the SDK is making a HTTP call for each piece of data!</p> <p>I found a good post on this sub that sug...
<python><amazon-web-services><encryption><amazon-kms>
2024-12-10 20:16:34
1
464
SoftwareThings
79,269,600
13,634,560
unable to access vaex dataframe
<p>I am using Vaex for the first time. With <code>vaex.example()</code>, I can save the dataframelocal as <code>df</code>. However, with real world data, this doesn't seem possible. See screenshot below.</p> <p><a href="https://i.sstatic.net/ENPyrpZP.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/ENPyrp...
<python><vaex>
2024-12-10 19:50:49
0
341
plotmaster473
79,269,542
3,765,883
Python/VScode 'continue' causes rest of loop code to be grayed out
<p>I have the following Python code (in VScode IDE):</p> <pre><code>def parse_seeyou_waypoints(lines, bounds=None): waypoint_list = WaypointList() cherrypy.log('in parse_seeyou_waypoints function:') #gfp 241210: modified to wait for header line before processing #gfp 241210: added 'ISO-8859-2' decoding...
<python><visual-studio-code>
2024-12-10 19:34:46
1
327
user3765883
79,269,489
13,163,640
Celery infinite retry pattern issue
<p>I am using celery with AWS SQS for async tasks.</p> <pre><code>@app.task( autoretry_for=(Exception,), max_retries=5, retry_backoff=True, retry_jitter=False, acks_late=True, ) @onfailure_reject(non_traced_exceptions=NON_TRACED_EXCEPTIONS) def send_order_update_event_task(order_id, data): ........
<python><django><celery><amazon-sqs>
2024-12-10 19:15:07
1
567
Dev
79,269,336
6,089,311
How to use one field expression for multiple columns in polars
<p>I have some data:</p> <pre class="lang-py prettyprint-override"><code>import polars as pl import pandas as pd df = pl.DataFrame({ &quot;dt&quot;:pd.date_range(&quot;2024-12-01&quot;, periods=4, freq=&quot;D&quot;), &quot;A&quot;: {&quot;value&quot;:[10, 10, 20, 30], &quot;multiple&quot;:[1,2,0,0]}, &quo...
<python><dataframe><python-polars>
2024-12-10 18:14:35
0
586
Jan
79,269,275
1,938,552
Sub-attribute annotation syntax
<p>It is possible to type the following code in Python3.12:</p> <pre><code>class B: pass b = B() class A: a: &quot;x&quot; b.c: &quot;y&quot; </code></pre> <p>Without <code>b</code> declaration, this code throws NameError. After that, <code>A.__annotations__</code> shows: <code>{'a': 'x'}</code>. Annotati...
<python><python-typing>
2024-12-10 17:57:58
1
1,059
haael
79,269,259
11,091,148
Azure OpenTelemetry Exporter duplicates logs
<p>I have a simple python script to export logs into an app insights trace table by following this <a href="https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/monitor/azure-monitor-opentelemetry/samples/logging/basic.py" rel="nofollow noreferrer">example</a>, however, the log entries get duplicated. What could...
<python><azure><logging><open-telemetry>
2024-12-10 17:54:56
1
526
Bennimi
79,269,139
435,563
python SyncManager used by remote processes: how to identify shared objects
<p>Using a <a href="https://docs.python.org/3/library/multiprocessing.html#multiprocessing.managers.SyncManager" rel="nofollow noreferrer">SyncManager</a>, if a group of processes need to share more than one <code>dict()</code> (say), the typical recipe is for the starting process to create them, and pass proxies to su...
<python><synchronization><python-multiprocessing>
2024-12-10 17:19:00
1
5,661
shaunc
79,269,129
11,581,214
<textarea> tag is not rendered properly using CSS with IronPDF
<p>I am attempting to convert an HTML form to a fillable PDF with IronPDF (IronPdf 2024.8.1.3) in Python (3.12.6). The HTML renders appropriately in Chrome. Tags other than the &lt;textarea&gt; tag render appropriately in the PDF (verifying use of the CSS). IronPDF is not using the defined textarea style to override th...
<python><html><forms><pdf><ironpdf>
2024-12-10 17:15:34
1
524
BalooRM
79,269,114
25,413,271
decorate function and method with same decorator
<p>I have a function, a class implementing the similar method and a decorator. The current decorator signature does allow it to be used for the function but doesn't work with the method as expected.</p> <pre><code>from functools import wraps def nice(f): @wraps(f) def decorator(a, b): result = f(a, b) ...
<python><function><class><decorator>
2024-12-10 17:11:34
2
439
IzaeDA
79,269,012
13,132,728
How to style all cells in a row of a specific MultiIndex value in pandas
<h1>SETUP</h1> <p>I have the following <code>df</code>:</p> <pre><code>import pandas as pd import numpy as np arrays = [ np.array([&quot;fruit&quot;, &quot;fruit&quot;, &quot;fruit&quot;,&quot;vegetable&quot;, &quot;vegetable&quot;, &quot;vegetable&quot;]), np.array([&quot;one&quot;, &quot;two&quot;, &quot;tot...
<python><pandas><dataframe><pandas-styles>
2024-12-10 16:38:02
1
1,645
bismo
79,268,684
16,712,729
Folium's "FloatImage" not displayed in Vscode notebook
<p>I try to use FloatImage from folium.plugin to display an image on a Folium map.</p> <p>When I print the map on a jupyter notebook in VScode, the image is replaced by an alt text.</p> <p><img src="https://i.sstatic.net/wiaGCs4Y.png" alt="map" /></p> <p>However, when I save the map as an html, the image is visible.</p...
<python><visual-studio-code><folium>
2024-12-10 14:52:21
0
499
NicolasPeruchot
79,268,560
6,946,110
Middleware for fetching the user from database for each request
<p>I have a (SQLAlchemy) User model as follows:</p> <pre><code>class User(BaseModel): id: uuid: Mapped[UUID] = mapped_column(UUID, ...) </code></pre> <p>I need to check if the user exists in DB for every request. I know I should define a dependency for it, but I have more than 100 tiny and big endpoints. So, it's n...
<python><pytest><fastapi><pytest-fixtures><fastapi-middleware>
2024-12-10 14:10:56
1
1,553
msln
79,268,478
561,243
Understanding unbound type error with mypy
<p>I am new to static type checking in python and honestly I believed it was much easier that what it actually is.</p> <p>Here is an ultra simplified version of my code:</p> <pre class="lang-py prettyprint-override"><code> from typing import Collection, TypeVar, Generic ItemType = TypeVar('ItemType') class WorkerMeta...
<python><python-typing><mypy>
2024-12-10 13:47:32
1
367
toto
79,268,326
1,473,517
What's wrong with my code to convert a matrix to and from a byte string?
<p>I have this function to convert a binary 2d array to a byte array:</p> <pre><code>def flatten_and_pad_to_multiple_of_8(binary_matrix): # Step 1: Calculate the size of the original flattened array rows, cols = binary_matrix.shape current_length = rows * cols # Step 2: Calculate the required lengt...
<python><numpy><numba>
2024-12-10 12:53:21
2
21,513
Simd
79,268,316
253,954
How do I add a computed column to an SQLModel table?
<p>I am using SQLModel together with FastAPI and I have the models <code>Package</code> and <code>Download</code>s, where a <code>Package</code> has multiple <code>Download</code>s which in turn have a <code>count</code> field. My goal is to add up the <code>Download.count</code>s associated to each package in a query ...
<python><fastapi><sqlmodel>
2024-12-10 12:50:32
0
8,019
fqxp
79,268,272
6,195,489
Making predictions using numpyro and MCMC
<p>I am following the numpyro example in celerite2 <a href="https://celerite2.readthedocs.io/en/latest/tutorials/first/" rel="nofollow noreferrer">here</a>, which has a numpyro interface.</p> <p>Further up using emceee they make predictions <a href="https://celerite2.readthedocs.io/en/latest/tutorials/first/" rel="nofo...
<python><numpyro>
2024-12-10 12:38:44
0
849
abinitio
79,268,222
13,840,270
Pyspark: Subset Array based on other column value
<p>I use Pyspark in Azure Databricks to transform data before sending it to a sink. In this sink any array must at most have a length of 100. In my data I have an <code>array</code> that is always length 300 an a field specifying how many values of these are relevant (<code>n_relevant</code>).</p> <p><code>n_relevant</...
<python><arrays><pyspark><azure-databricks>
2024-12-10 12:23:40
2
3,215
DuesserBaest
79,268,152
28,063,240
Why does BeautifulSoup output self-closing tags in HTML?
<p>I've tried with 3 different parsers: <code>lxml</code>, <code>html5lib</code>, <code>html.parser</code></p> <p>All of them output invalid HTML:</p> <pre><code>&gt;&gt;&gt; BeautifulSoup('&lt;br&gt;', 'html.parser') &lt;br/&gt; &gt;&gt;&gt; BeautifulSoup('&lt;br&gt;', 'lxml') &lt;html&gt;&lt;body&gt;&lt;br/&gt;&lt;/b...
<python><beautifulsoup>
2024-12-10 11:59:11
2
404
Nils
79,268,122
10,153,071
Any faster and memory-efficient alternative of torch.autograd.functional.jacobian(model.decoder, latent_l)?
<p>I have a decoder <code>model.decoder</code>, which is comprised of a series of Convolutional Batchnorm and ReLU layers. I have a latent vector <code>latent_l</code>, which is a 8 dimensional latent vector, say, has the dimension (1, 8, 1, 1), where 1 is the batch size. I am doing <code>torch.autograd.functional.jaco...
<python><pytorch><automatic-differentiation>
2024-12-10 11:45:49
1
536
Jimut123
79,268,106
2,443,525
Can not install latest version of PIP package
<p>I'm trying to install the latest version of pyworkforce in my virtual environment, but for some reasons it installs an old version:</p> <pre><code>% python3 -m venv venv % source venv/bin/activate % pip install --upgrade --no-cache-dir pyworkforce Collecting pyworkforce Downloading pyworkforce-0.5.1-py3-none-any.w...
<python><pip>
2024-12-10 11:42:11
1
426
Lodewijck
79,267,891
11,561,121
Run GlueJobOperator with parameters based on dag run parameter
<p>My Airflow dags has multiple variables as run params. I would like to launch a Glue job with specific parameters based on one of the run params:</p> <p>when run_type=0 I would like to launch the job with 2 workers standard type. Otherwise I would like to launch the job with 10 workers G.2X type.</p> <p>This is what...
<python><airflow>
2024-12-10 10:33:11
0
1,019
Haha
79,267,768
2,546,099
Change installation of pytorch from CUDA-based torch to CPU-based torch in docker-build
<p>I have a poetry-based project I'd like to pack into a docker image. For that, I use the following docker script:</p> <pre><code>FROM python:3.12 AS builder ARG CUR_GIT_COMMIT ENV CUR_GIT_COMMIT=$CUR_GIT_COMMIT RUN pip install poetry==1.8.4 RUN apt-get update &amp;&amp; apt-get install ffmpeg libsm6 libxext6 libegl...
<python><docker><python-poetry>
2024-12-10 09:53:15
0
4,156
arc_lupus
79,267,542
1,867,328
How to get information of a function and its arguments in Python
<p>I ran below to get information about the list of arguments and default values of a function/method.</p> <pre><code>import pandas as pd import inspect inspect.getfullargspec(pd.drop_duplicates) </code></pre> <p>Results:</p> <pre><code>Traceback (most recent call last): File &quot;&lt;stdin&gt;&quot;, line 1, in &lt...
<python><pandas><signature>
2024-12-10 08:45:56
1
3,832
Bogaso
79,267,492
1,317,099
How to Redact Sensitive Data in Debug Logs from Python Libraries (httpx, httpcore, hpack)
<p>I am working on an application that uses the Supabase Python client, and I’ve run into an issue with sensitive data like tokens appearing in debug logs. These logs include REST API calls that expose sensitive query parameters and headers, which I'd like to redact.</p> <p>For example, here are some log snippets:</p> ...
<python><supabase>
2024-12-10 08:26:07
0
1,345
Ganesh Rathinavel
79,267,490
1,334,657
How to add extra attributes to PyTorch labels?
<p>I want to train NNs for classification with PyTorch and let's say that I have data similar to here. <a href="https://i.sstatic.net/MBHxXyOp.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/MBHxXyOp.png" alt="enter image description here" /></a></p> <p>HW1, HW2 midterms, final, merits are features for t...
<python><pandas><pytorch>
2024-12-10 08:25:39
0
3,038
bensw
79,267,176
219,153
How to enable automatic color cycling for Arc patches in matplotlib?
<p>In this Python 3.12 script:</p> <pre><code>import matplotlib.pyplot as plt from matplotlib.patches import Arc fig, ax = plt.subplots() for a1 in range(0, 360, 20): ax.add_patch(Arc((0, 0), 10, 10, theta1=a1, theta2=a1+20)) ax.set_aspect('equal') ax.autoscale_view() plt.show() </code></pre> <p>I would like...
<python><matplotlib><colors>
2024-12-10 06:09:27
2
8,585
Paul Jurczak
79,267,083
4,794
Summarize higher dimensions in numpy
<p>I have a numpy array that holds board game states for all possible moves, and I want to summarize some of those moves. I'm struggling to vectorize that code and avoid a for loop when I choose which moves I want to summarize.</p> <p>Here's a simplified example of what I'm trying to do. I create a 3x3x3x3 array that r...
<python><numpy><vectorization>
2024-12-10 05:18:33
1
56,676
Don Kirkby
79,267,077
1,040,688
Python matrices in GF(2)
<p>I want to manipulate matrices of elements of the finite field GF(2), where every element is a 1 or a 0, in Python. I see that numpy can use dtype=bool, but it uses saturating addition, not wrapping, so it doesn't implement GF(2) where <code>1 + 1 = 0</code>. Is there a way to do this in numpy, or another package? I ...
<python><numpy><linear-algebra>
2024-12-10 05:15:15
2
1,321
Gavin Wahl
79,267,051
8,800,836
Efficient solution of A @ X = B with B a triangular matrix in scipy or numpy
<p>Consider three square matrices <code>A</code>, <code>X</code>, and <code>B</code> that form the linear system:</p> <pre class="lang-py prettyprint-override"><code>A @ X = B </code></pre> <p>to be solved for a particular solution <code>X</code> (which might not be unique).</p> <p>I know that the matrix <code>B</code>...
<python><numpy><scipy><linear-algebra>
2024-12-10 05:00:31
0
539
Ben
79,267,004
698,182
How do you enable runtime-repack in llama cpp python?
<p>After updating llama-cpp-python I am getting an error when trying to run an ARM optimized GGUF model <code>TYPE_Q4_0_4_4 REMOVED, use Q4_0 with runtime repacking</code>. After looking into it, the error comes from <a href="https://github.com/ggerganov/llama.cpp/pull/9921/files" rel="nofollow noreferrer">this</a> cha...
<python><python-3.x><pip><llama-cpp-python><llamacpp>
2024-12-10 04:19:30
0
1,931
ekcrisp
79,266,819
13,135,901
Faster glossary generation
<p>I am trying to make a table of contents for my <code>queryset</code> in Django like this:</p> <pre class="lang-py prettyprint-override"><code>def get_toc(self): toc = {} qs = self.get_queryset() idx = set() for q in qs: idx.add(q.title[0]) idx = list(idx) idx.sort() for i in idx: ...
<python><django>
2024-12-10 01:31:59
3
491
Viktor
79,266,812
28,063,240
How to split an HTML string around tags?
<p>How can I use Python to split an html string by a specified unpaired tag? For example</p> <pre><code>split('hello&lt;br &gt;there', 'br') </code></pre> <p>should return <code>['hello', 'there']</code>,</p> <pre><code>split('&lt;div id=&quot;d71&quot;&gt;text1&lt;br data-i=&quot;1&quot;&gt;text2&lt;br&gt;text3&lt;...
<python><beautifulsoup><lxml>
2024-12-10 01:23:11
3
404
Nils
79,266,809
11,505,680
Scipy minimize with conditioning
<p>I have a function of 3 variables that I want to optimize. Unfortunately, the variables have different orders of magnitude, meaning that the problem is very ill-conditioned. I'm handling this by multiplying the optimization variable by a conditioning matrix. (In the example below, my conditioning matrix is diagonal, ...
<python><optimization><scipy>
2024-12-10 01:16:37
1
645
Ilya
79,266,778
3,765,883
Python: lines =file.readlines() puts extra 'b' character in front of each line?
<p>I'm trying to debug a web app built by somebody else. The app is supposed to parse a text file containing lines that represent geographical waypoints in a comma-separated format. When viewed in a windows app like notepad++ or the web-based text viewer <a href="https://filehelper.com" rel="nofollow noreferrer">http...
<python><readlines>
2024-12-10 00:49:10
1
327
user3765883
79,266,767
9,850,548
How to handle heterogenous GNN?
<p>I have created this data:</p> <pre><code>HeteroData( user={ x=[100, 16] }, keyword={ x=[321, 16] }, tweet={ x=[1000, 16] }, (user, follow, user)={ edge_index=[2, 291] }, (user, tweetedby, tweet)={ edge_index=[2, 1000] }, (keyword, haskeyword, tweet)={ edge_index=[2, 3752] } ) </code></pre> <p>And these t...
<python><pytorch><pytorch-geometric><gnn>
2024-12-10 00:42:57
1
317
aliiiiiiiiiiiiiiiiiiiii
79,266,709
28,063,240
How to access container's python packages from the host?
<p>I would like to have local read access to the Python packages that my docker container process installs.</p> <p>I thought the easiest way to do this would be to &quot;symlink&quot; a local file to a directory on the container's directory, which I thought I could do with volumes/mounts.</p> <p>I have tried many diffe...
<python><django><docker><docker-compose>
2024-12-09 23:40:30
0
404
Nils
79,266,572
1,940,534
Python Selenium selecting an option in a list
<p>I have a SELECT list</p> <pre><code>&lt;select size=&quot;4&quot; name=&quot;ctl00$ContentPlaceHolder1$lstAvailableClients&quot; id=&quot;ctl00_ContentPlaceHolder1_lstAvailableClients&quot; style=&quot;height:150px;width:250px;&quot;&gt; &lt;option value=&quot;2780&quot;&gt;2780 - R W M (self)&lt;/option&gt; ...
<python><selenium-webdriver>
2024-12-09 22:07:15
2
1,217
robm
79,266,557
2,815,937
python: heatmap with categorical color and continuous transparency
<p>I want to make a heatmap in python (seaborn, matplotlib, etc) with two dimensions of information. I have a categorical value I want to assign to color, and a continuous variable (i.e. between 0-100 or 0-1) I want to assign to transparency, so each box has its own color and transparency (or intensity).</p> <p>for exa...
<python><matplotlib><seaborn>
2024-12-09 21:58:12
2
735
andbeonetraveler
79,266,516
12,358,733
Python http.client using HTTP Proxy server going to non-HTTPS site
<p>I'm working to retrieve API data in an environment where an outbound HTTP/HTTPS proxy server is required. When connecting to the site using HTTPS via the proxy using <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/CONNECT" rel="nofollow noreferrer">Tunneling</a>, it works fine. Here's example co...
<python><proxy><http-proxy><http.client>
2024-12-09 21:32:48
0
931
John Heyer
79,266,479
2,587,904
Python insert image into cell
<p>How can I use python code to insert an image (local file) into an excel cell.</p> <p>In the Excel UI <a href="https://support.microsoft.com/en-us/office/insert-picture-in-cell-in-excel-e9317aee-4294-49a3-875c-9dd95845bab0" rel="nofollow noreferrer">https://support.microsoft.com/en-us/office/insert-picture-in-cell-in...
<python><excel><pandas><image><airtable>
2024-12-09 21:16:08
0
17,894
Georg Heiler
79,266,470
5,289,570
How to use virtual environments in Jupyter Notebook in VS Code
<p>I use Jupyter extension (v2024.10.0), Python (v2024.20.0), and Pylance (v2024.12.1) with default interpreter path, VS Code 1.95.3 on MacOS Sonoma 14.6. I want to debug Python code interactively in jupyter notebooks using the same virtual environment I use when running modules via Terminal.</p> <p>e.g. I have a proje...
<python><visual-studio-code><jupyter-notebook><virtualenv>
2024-12-09 21:10:25
2
1,416
Wassadamo
79,266,454
5,344,240
Spark cache inside a function
<p>I have this toy example function returning a cached spark DataFrame (DF):</p> <pre><code>def foo(df): try: base = complicated_query(df) base.cache() # lazy cache base.count() # trigger cache - wrong design??? nu...
<python><azure><apache-spark><pyspark><azure-databricks>
2024-12-09 21:03:42
1
455
Andras Vanyolos
79,266,438
5,970,782
Jupyterlab alternative for pdb/ipdb
<p>How can I set a breakpoint in a Python script running in a Jupyter notebook such that:</p> <ul> <li>When the breakpoint is hit, the variables from the script are available in the Jupyter kernel.</li> <li>I can interact with and modify those variables in the Jupyter notebook during the pause.</li> <li>After resuming ...
<python><debugging><jupyter><ipdb><jupyter-kernel>
2024-12-09 20:57:28
0
791
Pavel Prochazka
79,266,275
14,700,182
Python: FastAPI not accepting SQLModel as a return type on routes
<p>I'm making an API based on the <code>FastAPI</code> docs (<a href="https://fastapi.tiangolo.com/tutorial/sql-databases/#install-sqlmodel" rel="nofollow noreferrer">https://fastapi.tiangolo.com/tutorial/sql-databases/#install-sqlmodel</a>). I have noticed this docs are kind of deprecated due to <code>@app.on_event(&q...
<python><fastapi><uvicorn>
2024-12-09 19:43:34
0
334
Benevos
79,266,143
141,650
How to transitively "import" a conftest.py file?
<p>I have a directory structure with 1 base class, 1 test file, and 2 <code>conftest.py</code> files, like so:</p> <pre><code>/tests/base/BUILD py_library( name=&quot;some_base&quot;, srcs=[&quot;some_base.py&quot;] ) /tests/base/conftest.py import pytest @pytest.hookimpl(tryfirst=True, hookwrapper=T...
<python><pytest>
2024-12-09 18:49:58
0
5,734
Stephen Gross
79,266,000
5,489,736
slow vtk rendering on ec2 machine
<p>I am running the following code to render a 3D mesh using vtk.</p> <p>On my MacBook Pro M2 (32GB RAM), the code runs significantly faster compared to AWS EC2 instances, including both CPU (c7i.8xlarge) and GPU (g5.2xlarge).</p> <p>Specifically, the call to window_to_image_filter.Update() is about 100x slower on the ...
<python><vtk><xvfb><osmesa>
2024-12-09 17:59:07
0
398
Cowabunga
79,265,951
7,658,051
configuring karrigell logging to log uncaught exceptions
<p>I am managing a third-part app made with python's framework <a href="https://karrigell.sourceforge.net/en/index.html" rel="nofollow noreferrer">Karrigell</a>.</p> <p>I have added a new logger, <code>my_logger</code>, which is declared and instantiated in a file called <code>my_logging.py</code></p> <p>I see that the...
<python><exception><stderr><traceback><uncaught-exception>
2024-12-09 17:40:59
0
4,389
Tms91
79,265,874
3,486,684
Generating a dataframe of *combinations* (not permutations)?
<p>Suppose I have a bag of items <code>{a, b}</code>. Then I can choose pairs out of it in a variety of ways. One way might be to pick all possible permutations: <code>[a, a], [a, b], [b, a], [b, b]</code>. But I might disallow repetition, in which case the possible permutations are: <code>[a, b], [b, a]</code>. I migh...
<python><python-polars>
2024-12-09 17:16:11
1
4,654
bzm3r
79,265,786
1,802,693
Using DataSource in bokeh library for color, alpha and other properties
<p>So far in python's bokeh library I've used a patch method to draw some objects, but the current solution runs in a for loop which is not optimal for this library:</p> <pre class="lang-py prettyprint-override"><code>for data_point in data_points: tf_sec = pd.Timedelta(data_point['tf']) / 2.0 dt = tf...
<python><pandas><bokeh>
2024-12-09 16:46:40
0
1,729
elaspog
79,265,466
9,112,151
Redis: Cannot release a lock that's no longer owned
<p>I'm trying to lock certain key.</p> <p>I have <code>httpx.Auth</code> subclass:</p> <p>from redis.asyncio import Redis from httpx import AsyncClient, Auth</p> <p>def get_redis_client(): return Redis(host=settings.redis_host, port=settings.redis_port)</p> <p>class BearerAuth(Auth): esm_url_get_token: str = urljoin(se...
<python><redis>
2024-12-09 15:04:36
0
1,019
ΠΠ»ΡŒΠ±Π΅Ρ€Ρ‚ АлСксандров
79,265,302
25,413,271
Sum up column values by special logic
<p>Say we have an array like:</p> <pre><code>a = np.array([ [k11, k12, k13, k14, k15, k16, k17, k18], [k21, k22, k23, k24, k25, k26, k27, k28], [k31, k32, k33, k34, k35, k36, k37, k38], [k41, k42, k43, k44, k45, k46, k47, k48] ]) const = C </code></pre> <p>I need to create a vector from this array like...
<python><numpy>
2024-12-09 14:20:56
3
439
IzaeDA
79,265,067
12,890,458
Why does the output change after putting code in a function in a simpy process?
<p>In a simpy process I handle a simpy interrupt. I do this in two places and so I want to put the handling code in a function. Before putting it in a function all functions well, after putting it in a function it yields different results.</p> <p>Below the written out code</p> <pre><code>def offer(env, simpy_car, simpy...
<python><simpy>
2024-12-09 13:01:59
1
460
Frank Tap
79,264,799
1,276,622
Classes uses the same properties
<p>I have a simple piece of code. In it I make 2 animals a cat and a spider. They have a difference number of legs and eyes. I just want to print these data.</p> <pre><code>class Legs: def __init__(self, amount): self.amount = amount def legsInfo(self): return f&quot;{self.amount} legs&quot; ...
<python><class>
2024-12-09 11:27:55
4
4,410
Vincent
79,264,683
7,344,164
Error loading Pytorch model checkpoint: _pickle.UnpicklingError: invalid load key, '\x1f'
<p>I'm trying to load the weights of a Pytorch model but getting this error: <code>_pickle.UnpicklingError: invalid load key, '\x1f'.</code></p> <p>Here is the weights loading code:</p> <pre><code>import os import torch import numpy as np # from data_loader import VideoDataset import timm device = torch.device('cuda' ...
<python><deep-learning><pytorch><pickle><torch>
2024-12-09 10:47:29
1
14,299
DevLoverUmar
79,264,675
3,400,076
Often Misused: File Upload - Fortify
<pre><code>&lt;input id=&quot;field&quot; name=&quot;upload&quot; type=&quot;file&quot; /&gt; </code></pre> <p>Fortify flagged the above line of code and indicated as Medium Priority, with the title, Often Misused: File Upload.</p> <p>The recommendation indicated that</p> <blockquote> <p>Do not allow file uploads if th...
<python><jinja2><fortify>
2024-12-09 10:45:57
0
519
xxestter
79,264,662
7,600,014
Showing package specifiers
<p>In my project, which I manage with <code>uv</code>, some transitive dependency is restricting numpy to <code>numpy==2.0</code>; even though the newest version is <code>numpy=2.2</code>.</p> <p>Is there any convenient way to make <code>uv</code> tell me what the cause of this restriction in my dependency tree is?</p>...
<python><uv>
2024-12-09 10:42:35
1
487
mzoll
79,264,514
6,239,971
Data retrieving and SQL database update
<p>I'm trying to retrieve some data from an API and save them to a local database I created. All data come from Google Ads campaigns, and I need to make two separate calls because of their docs, but that's good. I take the data, mix them in a dataframe, and then call a second function to check if that specific row is a...
<python><pandas><dataframe><sqlite3-python>
2024-12-09 09:51:44
0
454
Davide
79,264,444
4,211,520
How to automate ffmpeg to split and merge parts of video, and keep the audio in sync?
<p>I have a Python script that automates trimming a large video (2 hours) into smaller segments and then concatenating them without re-encoding, to keep the process fast. The script runs these ffmpeg commands:</p> <pre><code>import subprocess # Extract chunks segments = [(0, 300), (300, 600), (600, 900)] # example se...
<python><video><ffmpeg>
2024-12-09 09:29:22
1
31,711
Tree
79,264,326
597,742
Use `structlog` in a library while respecting `stdlib` log configuration
<p>I'm looking to use <code>structlog</code> in a Python library, but would also like to transparently support the logging configuration set up by a containing application. In particular:</p> <ul> <li>if a log level is set (e.g. via <code>logging.basicConfig</code>), respect that</li> <li>support the standard <code>pyt...
<python><structlog>
2024-12-09 08:46:27
1
41,806
ncoghlan
79,264,247
12,813,584
similarity from word to sentence after doing words Embedding
<p>I have dataframe with 1000 text rows.</p> <p>I did word2vec .</p> <p>Now I want to create a new field which give me the distance from each sentence to the word that i want, lets say the word &quot;king&quot;.</p> <p>I thought about taking in each sentence the 4 closet words to the word king and make average of them...
<python><nlp><text-mining><word2vec><similarity>
2024-12-09 08:14:04
1
469
rafine
79,264,125
6,301,394
Casting expression result
<p>Would it be possible to cast an expression into a specific datatype without casting the source columns?</p> <p>Consider the following frame:</p> <pre><code>df = pl.DataFrame({&quot;A&quot;: [1, 2, 3], &quot;B&quot;: [4, 5, 6]}, schema={'A': pl.UInt8, 'B': pl.UInt8}) β”Œβ”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β” β”‚ A ┆ B β”‚ β”‚ --- ┆ --- β”‚ β”‚ u8 ┆...
<python><python-polars>
2024-12-09 07:14:32
1
2,613
misantroop
79,263,708
14,205,874
Spotipy (python) functions run forever with OAuth
<pre><code> import requests import json import spotipy from credentials import CLIENT_ID, CLIENT_SECRET, REDIRECT_URI from spotipy.oauth2 import SpotifyOAuth # auth print('starting auth') sp = spotipy.Spotify(auth_manager=SpotifyOAuth(client_id=CLIENT_ID, redirect_uri=REDIRECT_URI, clie...
<python><spotipy>
2024-12-09 02:29:14
0
407
Tony