question_id
int64
59.5M
79.7M
creation_date
stringdate
2020-01-01 00:00:00
2025-07-15 00:00:00
link
stringlengths
60
163
question
stringlengths
53
28.9k
accepted_answer
stringlengths
26
29.3k
question_vote
int64
1
410
answer_vote
int64
-9
482
79,323,172
2025-1-2
https://stackoverflow.com/questions/79323172/django-request-get-adds-and-extra-quote-to-the-data
When I pass my parameters via Django request.GET I get an extra comma in the dictionary that I do not need. Encoded data that I redirect to the endpoint: /turnalerts/api/v2/statuses?statuses=%5B%7B%27conversation%27%3A+%7B%27expiration_timestamp%27%3A+%271735510680%27%2C+%27id%27%3A+%2757f7d7d4d255f4c7987ac3557bf536e3%...
The issue here is the double quote in the list. Nope. This is not part of the content of the string. This is because Python's repr(…) function [python-doc] tries to print the value as a Python literal expression, for example {'a': 'b'} prints single quotes around 'a' and 'b', but these are not part of the content of ...
2
1
79,322,543
2025-1-2
https://stackoverflow.com/questions/79322543/find-the-closest-converging-point-of-a-group-of-vectors
I am trying to find the point that is closest to a group of vectors. For context, the vectors are inverted rays emitted from center of aperture stop after exiting a lens, this convergence is meant to locate the entrance pupil. The backward projection of the exiting rays, while not converging at one single point due to ...
I'm assuming the answer to my question in the comment is that you have symmetry such that the "closest point" must lie on the z-axis. Furthermore, I'm assuming you are somewhat flexible about the notion of "closest". First, let's remove the zeroth point from position and direction, since that will pass through all poin...
1
1
79,322,091
2025-1-1
https://stackoverflow.com/questions/79322091/unable-to-acquire-impersonated-credentials
Im trying to generate signed urls, so i followed the official guide but im getting this error: google.auth.exceptions.TransportError: Error calling sign_bytes: {'error': {'code': 403, 'message': "Permission 'iam.serviceAccounts.signBlob' denied on resource (or it may not exist).", 'status': 'PERMISSION_DENIED', 'detail...
Per the documentation Service Account Token Creator (roles/iam.serviceAccountTokenCreator): this role is required for generating short-lived credentials for a service account when a private key file is not provided locally. This role should be granted to the principal that will create the signed URL. This means you h...
1
1
79,321,029
2025-1-1
https://stackoverflow.com/questions/79321029/python-unit-test-get-requests-assertion-error-not-picking-up-call
I'm testing basic GET requests under from the requests module. I'm using requests.Session to create a session instance which is later passed into the function. I'm mocking the the function calls. I've patched the session.get call within the function, however I get the following error: AssertionError: get('https://exam...
There are two issues in you code You use mock_session for the API call but test mock_get for it mock_get and mock_session are the session.get function, not Session instance Simplified test with two options @patch.object(Session, 'get') def test_fetch(self, mock_get): fetch_data_with_session(mock_get, "https://examp...
4
3
79,321,224
2025-1-1
https://stackoverflow.com/questions/79321224/cpython-pyatomic-gcc-h-is-not-a-file-or-a-directory
Im trying to use python in C++ but I get an error while trying to import Python : Error message : cmd /c chcp 65001>nul && C:\msys64\ucrt64\bin\g++.exe -fdiagnostics-color=always -g C:\Users\21211433\Desktop\Code\C++\First\src\python.c -o C:\Users\21211433\Desktop\Code\C++\First\src\python.exe In file included from C:/...
You seem to think that the compiler should know where to find an included header file based on the location of a previously included header file. That is not how it works. You need to specify to the compiler where to look for header files. In this case it seems you need to add 'C:/Users/21211433/AppData/Local/Programs/...
3
3
79,352,553
2025-1-13
https://stackoverflow.com/questions/79352553/beautifulsoup-prettify-changes-content-not-just-layout
BeautifulSoup prettify() modifies significant whitespace even if the attribute xml:space is set to "preserve". Example xml file with significant whitespace: <svg viewBox="0 0 160 50" xmlns="http://www.w3.org/2000/svg"> <text y="20" xml:space="default"> Default spacing</text> <text y="40" xml:space="preserve"> <tspan>re...
As MendelG expained in his answer BeautifulSoup prettify() does change the meaning of documents and prettify() is only meant as an aid for readability. I wanted a solution that would reformat the document without changing its meaning and with the least amount of changes. The following code prettifies xml without modify...
3
0
79,355,866
2025-1-14
https://stackoverflow.com/questions/79355866/optimizing-the-exact-prime-number-theorem
For example, given this sequence of the first 499 primes, can you predict the next prime? 2,3,5,7,...,3541,3547,3557,3559 The 500th prime is 3571. Prime Number Theorem The Prime Number Theorem (PNT) provides an approximation for the n-th prime: Computing p_500 ≈ 3107 takes microseconds! Exact Prime Number Theorem M...
TL;DR: the code can be optimized with gmpy2 and accelerated with multiple threads, but the main issue is that this formula is simply a very inefficient way of finding the next prime number. Implement a faster math precision library mpmath is indeed a bit slow. You can just use gmpy2 instead! It is a bit faster. gmpy2...
2
1
79,352,480
2025-1-13
https://stackoverflow.com/questions/79352480/force-direction-of-line-vector
I have a line vector where each segment has a randomly assigned direction. The image shows an example (which consists of two connected lines), How to set the direction of each line so that it is consistent? That is, connected lines have the same direction? The line vector does not have a direction attribute. This info...
You can use line_merge. For it to work you need each cluster of connected lines to be a multiline, which can be done using GeoPandas: from shapely.wkt import loads import geopandas as gpd data = [[1, 'LineString (543125 6941963, 544217 6941907)'], [2, 'LineString (544957 6941417, 544217 6941907)'], [3, 'LineString (544...
1
1
79,345,986
2025-1-10
https://stackoverflow.com/questions/79345986/fastest-exponentiation-of-numpy-3d-matrix
Q is a 3D matrix and could for example have the following shape: (4000, 25, 25) I want raise Q to the power n for {0, 1, ..., k} and sum it all. Basically, I want to calculate \sum_{i=0}^{k-1}Q^n I have the following function that works as expected: def sum_of_powers(Q: np.ndarray, k: int) -> np.ndarray: Qs = np.su...
We can perform this calculation in O(log k) matrix operations. Let M(k) represent the k'th power of the input, and S(k) represent the sum of those powers from 0 to k. Let I represent an appropriate identity matrix. Approach 1 If you expand the product, you'll find that (M(1) - I) * S(k) = M(k+1) - I. That means we can ...
3
4
79,356,690
2025-1-14
https://stackoverflow.com/questions/79356690/how-to-set-a-column-which-suffix-name-is-based-on-a-value-in-another-column
#Column X contains the suffix of one of V* columns. Need to put set column V{X} to 9 if X > 1. #But my code created a new column 'VX' instead of updating one of the V* columns import pandas as pd df = pd.DataFrame({'EMPLID': [12, 13, 14, 15, 16, 17, 18], 'V1': [2,3,4,50,6,7,8], 'V2': [3,3,3,3,3,3,3], 'V3': [7,15,8,9,10...
# your dataframe df = pd.DataFrame({'EMPLID': [12, 13, 14, 15, 16, 17, 18], 'V1': [2,3,4,50,6,7,8], 'V2': [3,3,3,3,3,3,3], 'V3': [7,15,8,9,10,11,12], 'X': [2,3,1,3,3,1,2] }) First, we get the columns names that we want to change and their indices on the original dataframe. # column name x = df['X'][(df['X'] > 1)] # co...
1
1
79,356,521
2025-1-14
https://stackoverflow.com/questions/79356521/is-it-possible-to-create-groups-layers-in-method-chaining-in-python
I am aware that I can use method chaining by simply having methods return self, e.g. object.routine1().routine2().routine3() But is it possible to organize methods into layers or groups when applying method chaining? e.g. object.Layer1.routine1().routine2().Layer2.routine3() The context is that I am trying to build a...
You can make each level-specific object a proxy object to the parent object so that it has access to both level-specific methods and parent-specific attributes, and as a bonus level-specific methods can then reference self.text instead of self.parent.text: class TextPreprocessorLevel: def __init__(self, parent): self._...
2
1
79,344,159
2025-1-9
https://stackoverflow.com/questions/79344159/disable-pyspark-to-print-info-when-running
I have started to use PySpark. Version of PySpark is 3.5.4 and it's installed via pip. This is my code: from pyspark.sql import SparkSession pyspark = SparkSession.builder.master("local[8]").appName("test").getOrCreate() df = pyspark.read.csv("test.csv", header=True) print(df.show()) Every time I run the program using...
Different lines are coming from different sources. Windows ("SUCCESS: ..."), spark launcher shell/batch scripts (":: loading settings ::...") core spark code logging using log4j2 core spark code printing using System.out.println() Different lines are written to different fds (std-out, std-error, log4j log file) Spa...
4
4
79,353,260
2025-1-13
https://stackoverflow.com/questions/79353260/tkinter-with-turtle
I was creating a tkinter/turtle program similar to MS paint and I have the barebones Turtle finished but I am unsure of how to add the turtle into tkinter as a sort of window (Having the tkinter as the main application window with a window of python inside the window acting as a widget almost how a label or checkbox or...
You can use the RawTurtle() function to define your turtle then from there you can use ScrolledCanvas() function and TurtleScreen to create the screen and then it goes into tkinter, then you can use screen instead of updating turtle itself. from turtle import RawTurtle, TurtleScreen, ScrolledCanvas import tkinter as tk...
2
0
79,355,428
2025-1-14
https://stackoverflow.com/questions/79355428/inheriting-str-and-enum-why-is-the-output-different
I have this python code. But why does it print "NEW" in the first case, and "Status.NEW" in the second case? import enum class Status(str, enum.Enum): """Status options.""" NEW = "NEW" EXCLUDED = "EXCLUDED" print("" + Status.NEW) print(Status.NEW)
This is a quirk of multiple inheritance (one of the reasons why a lot of people choose to shun it). print("" + Status.NEW) Here you're using the + operator on your Status.NEW object. Since Status inherits from str, it inherits the __add__ method from there. str.__add__ does string concatenation and uses its raw string...
13
19
79,344,960
2025-1-10
https://stackoverflow.com/questions/79344960/extracting-vendor-info-from-probe-request-using-scapy
Trying to extract the vendor information (Apple, Samsung, etc) from Probe Request coming from mobile, So far no luck. Not sure where the corrections to be made to get this info. Adding my code: import codecs from scapy.all import * from netaddr import * def handler(p): if not (p.haslayer(Dot11ProbeResp) or p.haslayer(D...
There are a few things that should be taken into consideration when dealing with your problem. First, the OUI used by the netaddr 1.3.0 package is outdated. I have an iPhone 16 with OUI 0C-85-E1. You can check directly in IEEE or here that it is a valid OUI, but it's not updated in the netaddr source. You can solve thi...
5
1
79,345,392
2025-1-10
https://stackoverflow.com/questions/79345392/running-functions-in-parallel-and-seeing-their-progress
I am using joblib to run four processes on four cores in parallel. I would like to see the progress of the four processes separately on different lines. However, what I see is the progress being written on top of each other to the same line until the first process finishes. from math import factorial from decimal impor...
My idea was to create all the task bars in the main process and to create a single multiprocessing queue that each pool process would have access to. Then when calc completed an iteration it would place on the queue an integer representing its corresponding task bar. The main process would continue to get these integer...
6
5
79,355,881
2025-1-14
https://stackoverflow.com/questions/79355881/how-to-extinguish-cycle-in-my-code-when-calculating-emwa
I'm calculating EWMA values for array of streamflow, and code is like below: import polars as pl import numpy as np streamflow_data = np.arange(0, 20, 1) adaptive_alphas = np.concatenate([np.repeat(0.3, 10), np.repeat(0.6, 10)]) streamflow_series = pl.Series(streamflow_data) ewma_data = np.zeros_like(streamflow_data) f...
If you have only few alpha values and/or have some condition on which alpha should be used for which row, you could use pl.coalesce(), pl.when() and pl.Expr.ewm_mean(): df = pl.DataFrame({ "adaptive_alpha": np.concatenate([np.repeat(0.3, 10), np.repeat(0.6, 10)]), "streamflow": np.arange(0, 20, 1) }) df.with_columns( p...
3
1
79,356,278
2025-1-14
https://stackoverflow.com/questions/79356278/merging-lists-of-dictionaries-based-on-nested-list-values
I'm struggling to create a new list based on two input lists. Here's an example: data_1 = [ { "title": "System", "priority": "medium", "subtitle": "mason", "files": [ {"name": "mason", "path": "/tmp/mason/mason.json"}, {"name": "mason", "path": "/tmp/mason/build.json"} ]}, { "title": "System", "priority": "medium", "su...
You can create a reverse mapping that maps paths in data_2 to names, and iteratively modify all names in data_1 with the paths mapped with the mapping: from itertools import chain from operator import itemgetter name_of = dict( map( itemgetter('path', 'name'), chain.from_iterable(map(itemgetter('files'), data_2)) ) ) f...
1
1
79,356,647
2025-1-14
https://stackoverflow.com/questions/79356647/python-accessing-eo-edmund-optics-camera
I have a camera (EO Edmund Optics Camera, Model UI-154xSE-M) connected to a Windows computer via USB. When I open IDS Camera Manager, The camera is "configured correctly and can be opened". I am trying to write a code in Python to have the camera capture an image every x minutes for a period of y total minutes using th...
So isOpened() says True, but the read() call returns False? It might be worth trying the read call several times, instead of failing at the first sign of trouble. Some cameras are weird like that. OpenCV also has this quirk where it tries to set 640 x 480 resolution. If a camera doesn't support that, the interaction wi...
2
4
79,355,047
2025-1-14
https://stackoverflow.com/questions/79355047/multiprocessing-with-tkinter-progress-bar-minimal-example
I'm looking for a way to track a multiprocessing task with Tkinter progress bar. This is something that can be done very straightforwardly with tqdm for display in the terminal. Instead of using tqdm I'd like to use ttk.Progressbar, but all attempts I have made at this, the tasks block on trying to update the progressb...
Calling pool.join() blocks the main thread until all the tasks are done, which causes Tkinter to hang. To get around this, you can call start_task in a thread. Running the thread with .start() (instead of .join()) will make it run in the background so it doesn't block the main thread. You can pass lists to the thread f...
2
2
79,356,143
2025-1-14
https://stackoverflow.com/questions/79356143/how-to-narrow-types-in-python-with-enum
In python, consider the following example from enum import StrEnum from typing import Literal, overload class A(StrEnum): X = "X" Y = "Y" class X: ... class Y: ... @overload def enum_to_cls(var: Literal[A.X]) -> type[X]: ... @overload def enum_to_cls(var: Literal[A.Y]) -> type[Y]: ... def enum_to_cls(var: A) -> type[X]...
The simple workaround is to include the implementation's signature as a third overload: (playgrounds: Pyright, Mypy) @overload def enum_to_cls(var: Literal[A.X]) -> type[X]: ... @overload def enum_to_cls(var: Literal[A.Y]) -> type[Y]: ... @overload def enum_to_cls(var: A) -> type[X] | type[Y]: ... def enum_to_cls(var: ...
4
4
79,355,830
2025-1-14
https://stackoverflow.com/questions/79355830/python-sqlalchemy-mapping-column-names-to-attributes-and-vice-versa
I have a problem where I need to access a MS SQL DB, so naturally it's naming convention is different: TableName(Id, ColumnName1, ColumnName2, ABBREVIATED,...) The way I got the model constructed in Python: class TableName(Base): __tablename__ = 'TableName' id = Column('Id', BigInteger, primary_key=True, autoincrement=...
Untested but something like this: from sqlalchemy import inspect old_to_new = {c.name: k for k, c in inspect(TableName).columns.items()} https://docs.sqlalchemy.org/en/20/orm/mapping_api.html#sqlalchemy.orm.Mapper.columns https://docs.sqlalchemy.org/en/20/orm/mapping_styles.html#inspection-of-mapper-objects
1
1
79,352,803
2025-1-13
https://stackoverflow.com/questions/79352803/how-to-detect-most-mortared-stones-with-opencv-findcontours
I need to correctly outline as many as possible of the mortared stones in a street zone. The code below correctly detects some of them in the stones image "in.jpg", but it is not obvious why many remain undetected or only partly outlined. I'd also like to fix cases like contour 56, 57 or 92 by exploiting the fact that ...
You can use cv2.moments(contour) for calculating the ratio between the contour length and the contour area. This will let you rule out non oval contours. Having said that, this is a relatively difficult problem for a classical CV approach. A neural network will do a better job (given enough training data) than findCont...
2
1
79,355,372
2025-1-14
https://stackoverflow.com/questions/79355372/how-to-get-the-day-month-name-of-a-column-in-polars
I have a polars dataframe df which has a datetime column date. I'm trying to get the name of the day and month of that column. Consider the following example. import polars as pl from datetime import datetime df = pl.DataFrame({ "date": [datetime(2024, 10, 1), datetime(2024, 11, 2)] }) I was hoping that I could pass p...
You can use pl.Expr.dt.strftime to convert a date / time / datetime column into a string column of a given format. The format can be specified using the chrono strftime format. In your specific example, the following specifiers might be of interest: %B for the full month name. %b for the abbreviated month name. Always...
5
7
79,354,633
2025-1-14
https://stackoverflow.com/questions/79354633/reshape-dictionary-to-make-violin-plot
I have some data that is saved in a dictionary of dataframes. The real data is much bigger with index up to 3000 and more columns. In the end I want to make a violinplot of two of the columns in the dataframes but for multiple dictionary entries. The dictionary has a tuple as a key and I want to gather all entries whic...
You could minimize the reshaping by using concat+melt and a higher level plotting library like seaborn: import seaborn as sns sns.catplot(data=pd.concat(data_dict, names=['section', None]) [['Data_1', 'Data_4']] .melt(ignore_index=False, var_name='dataset') .reset_index(), row='dataset', x='section', y='value', kind='v...
2
2
79,354,459
2025-1-14
https://stackoverflow.com/questions/79354459/apply-operation-to-all-elements-in-matrix-skipping-numpy-nan
I have an array filled with data only in lower triangle spaces, the rest is np.nan. I want to do some operations on this matrix, more precisely- with data elements, not nans, because I expect the behaviour when nans elements are skipped in vectorized operation to be much quicker. I have two test arrays: arr = np.array(...
I think this hypothesis is incorrect: I expect the behaviour when nans elements are skipped in vectorized operation to be much quicker In your array the data is contiguous, which is among others why vectorization is fast. If you used a masked array, this doesn't change this fact, there will be as much data and the ma...
1
2
79,353,825
2025-1-14
https://stackoverflow.com/questions/79353825/2d-how-to-make-bezier-curve-line-has-width-by-using-python
If I have a Bezier curve, how could I make it have width, and how to get vertices of its contour? My attempt: I have plot a Bezier curve by using one start point, two control points and one end points, their coordinates are: p0_ = [11, -0.45] p1_ = [13.5, -0.45] p2_ = [13.5, -4] p3_ = [16, -4] the figure is as shown b...
This follows the prescription in MBo's comment. For each point on the Bezier curve you compute the normal and then go width/2 along that normal to each side of the Bezier curve. To compute the normals you could take successive line segments along your discretised Bezier curve. However, I think you will get a smoother a...
2
2
79,354,062
2025-1-14
https://stackoverflow.com/questions/79354062/how-to-concantenate-elements-of-a-binary-column
I have a DataFrame with a binary column that represents the hexadecimal encoding of an initial string: random_id random_id_cesu8 123456789012 [31 32 33 34 35 36 37 38 39 30 31 32] The random_id_cesu8 column contains the binary representation of the random_id string encoded in UTF-8 and displayed as a list of ...
Here's a solution using PySpark to convert the binary column to its hexadecimal representation: from pyspark.sql import functions as F # Create DataFrame with the initial value df = spark.createDataFrame([("123456789012",)], ["value"]) # Convert the value to UTF-8 encoding and then to hex df = df.withColumn( "encoded_h...
1
1
79,354,405
2025-1-14
https://stackoverflow.com/questions/79354405/polars-schema-typeerror-dtypes-must-be-fully-specified-got-datetime
Hi I want to define a polars schema. It works fine without a datetime format. However it fails with pl.Datetime. import polars as pl testing_schema: pl.Schema = pl.Schema( { "date": pl.Datetime, "some_int": pl.Int64, "some_str": pl.Utf8, "some_cost": pl.Float64, }, ) The error: lib/python3.11/site-packages/polars/sche...
If you look at pl.Datetime, you'll find that it is initialized with parameters: class polars.datatypes.Datetime( time_unit: TimeUnit = 'us', time_zone: str | timezone | None = None ) Unlike, say, pl.Int64. Hence, you need to add the parentheses at the end, (), to use the defaults, or to pass arguments and override the...
3
4
79,354,192
2025-1-14
https://stackoverflow.com/questions/79354192/safe-eval-by-explitily-whitelisting-builtins-and-bailing-on-dunders
I know it's inadvisable to use eval() on untrusted input, but I want to see where this sanitiser fails. It uses a whitelist to only allow harmless builtins, and it immediately bails if there are any dunder properties called. (Note: the reason it string searches .__ and not just __ is because I want to allow things like...
Just put a space in: . __ and the standard bypasses work fine. Like this one: [x for x in (). __class__. __base__. __subclasses__() if x. __name__ == 'Quitter'][0]. __init__. __globals__['__builtins__']['__import__']( 'os').system('install ransomware or something') Seriously, don't use eval. These ad-hoc sanitizers ne...
1
2
79,350,300
2025-1-12
https://stackoverflow.com/questions/79350300/cant-change-recursion-limit-python
sys.setrecursionlimit is set to 20000, but I get error because of "996 more times", despite setting limit to a bigger number import sys from functools import * sys.setrecursionlimit(20000) @lru_cache(None) def f(n): if n <= 3: return n - 1 if n > 3: if n % 2 == 0: return f(n - 2) + (n / 2) - f(n - 4) else: return f(n -...
First, your code, as shown above, works fine on my system. Even when I reduce the recursion limit from 20000 down to 4000. However, if you rewrite your expressions to invoke f() on smaller numbers before larger numbers, then I'm able to run it with a recursion limit around 1250: import sys from functools import lru_cac...
1
1
79,353,015
2025-1-13
https://stackoverflow.com/questions/79353015/a-function-to-modify-other-already-defined-functions
Is there a way to write a function that takes some parameter, to modify multiple existing functions? For example, if I have: def add(a, b): return a + b def minus(a, b): return a - b def offset_b(func, n): (??) func(a, b - n) then I want to execute below: offset_b(add(1, 2), 0.5) offset_b(minus(1, 2), 0.5) I know one...
Define a function that accepts an existing function with known parameters, and returns a new function that wraps it: import functools # To borrow wrapped function's docs nicely def offset_b(func, n): @functools.wraps(func) def wrapped(a, b): return func(a, b-n) return wrapped You can then define new versions of add an...
1
4
79,352,669
2025-1-13
https://stackoverflow.com/questions/79352669/how-why-are-2-3-10-and-x-3-10-with-x-2-ordered-differently
Sets are unordered, or rather their order is an implementation detail. I'm interested in that detail. And I saw a case that surprised me: print({2, 3, 10}) x = 2 print({x, 3, 10}) Output (Attempt This Online!): {3, 10, 2} {10, 2, 3} Despite identical elements written in identical order, they get ordered differently. ...
It's a function of a couple things: Hash bucket collisions - For the smallest set size, 8 (implementation detail of CPython), 2 and 10 collide on their cutdown hash codes (which, again implementation detail, are 2 and 10; mod 8, they're both 2). Whichever one is inserted first "wins" and gets bucket index 2, the other...
20
28
79,352,276
2025-1-13
https://stackoverflow.com/questions/79352276/apply-function-for-lower-triangle-of-2-d-array
I have an array: U = np.array([3, 5, 7, 9, 11]) I want to get a result like: result = np.array([ [ np.nan, np.nan, np.nan, np.nan, np.nan], [U[0] - U[1], np.nan, np.nan, np.nan, np.nan], [U[0] - U[2], U[1] - U[2], np.nan, np.nan, np.nan], [U[0] - U[3], U[1] - U[3], U[2] - U[3], np.nan, np.nan], [U[0] - U[4], U[1] - U[...
A naive approach that does more work than necessary is to compute the entire difference and select the elements you need: np.where(np.arange(U.size)[:, None] > np.arange(U.size), U[:, None] - U, np.nan) This is one of the times where np.where is actually useful over a simple mask, although it can be done with a mask a...
2
2
79,350,683
2025-1-12
https://stackoverflow.com/questions/79350683/how-to-prevent-python-telebot-from-duplicating-messages
I've got a problem with Python Telebot, here is my code: import telebot token = 'token' bot = telebot.TeleBot(token) @bot.message_handler(func=lambda message: True) def start(message): bot.send_message(message.chat.id,"message") bot.register_next_step_handler(message, nextstep) def nextstep(message): bot.send_message(m...
Because your code does double-runs itself: at the end of the first turn finalstep calls start but then bot's message handler calls start again. And further: bot.register_next_step_handler() just adds a callable object to the bot's list of handlers, so that list grows after each message and bot runs all that handlers at...
2
1
79,350,990
2025-1-13
https://stackoverflow.com/questions/79350990/how-can-i-scrape-data-from-a-website-into-a-csv-file-using-python-playwright-or
I'm trying to scrape data from this website using Python and Playwright, but I'm encountering a few issues. The browser runs in non-headless mode, and the process is very slow. When I tried other approaches, like using requests and BeautifulSoup, I ran into access issues, including 403 Forbidden and 404 Not Found error...
Before even writing your scraping code, always take the time to understand the webpage. In this case, based on viewing the page source and looking through the network tab in dev tools, there's nothing dynamic at all here. My first instinct was to use simple HTTP requests with a user agent, but these get blocked by the ...
1
1
79,350,912
2025-1-12
https://stackoverflow.com/questions/79350912/nearest-neighbor-interpolation
Say that I have an array: arr = np.arange(4).reshape(2,2) The array arr contains the elements array([[0, 1], [2, 3]]) I want to increase the resolution of the array in such a way that the following is achieved: np.array([0,0,1,1], [0,0,1,1], [2,2,3,3], [2,2,3,3]]) what is this operation called? Nearest-neighbor inte...
You're looking for "nearest-neighbour upsampling", instead of "interpolation". A concise and efficient way to do this in numpy: import numpy as np arr = np.arange(6).reshape(2, 3) upsampled = np.repeat(np.repeat(arr, 2, axis=0), 2, axis=1) print("Original Array:") print(arr) print("Upsampled Array:") print(upsampled) ...
1
4
79,350,780
2025-1-12
https://stackoverflow.com/questions/79350780/cannot-connect-to-vpn-using-python-openvpn-client-api
I have a pyhton program from which I am using python-openvpn-client API to connect to a vpn server using an .ovpn configuration file. I have installed python 3.13.1 from the official website. Then I have created a virtual python environment to use in my python project. I have successfully installed the python-openvpn-c...
The python-openvpn-client 0.0.1 is for Unix-like systems like Linux, macOS or BSD. It's page says it was tested to work on macOS and Linux. The Windows systems do not support POSIX signals like SIGUSR1. You had this error message because SIGURS1 is not defined.The POSIX signals are supported on Unix-like systems.You co...
1
2
79,348,318
2025-1-11
https://stackoverflow.com/questions/79348318/how-do-i-resolve-installation-errors-for-installing-climada-using-mamba
I am trying to install Climada on my Mac. I have anaconda installed and python is as saved in /opt/anaconda3/bin/python (I believe it's python 3.11.8. The Climada documentation says to create a virtual environment using Mamba. mamba create -n climada_env -c conda-forge climada Then it says you can activate the environ...
You're trying to install an old package into a new interpreter. Set the controls of the way-back machine to an earlier era. Using the same interpreter that the Climada documentation author used should work smoothly. I believe it's python 3.11.8. That sounds like a good plan. However the "Pinned packages: - python=3.1...
3
1
79,350,430
2025-1-12
https://stackoverflow.com/questions/79350430/check-if-all-values-of-dataframe-are-true
How can I check if all values of a polars DataFrame, containing only boolean columns, are True? Example df: df = pl.DataFrame({"a": [True, True, None], "b": [True, True, True], }) The reason for my question is that sometimes I want to check if all values of a df fulfill a condition, like in the following: df = pl.Data...
As of the date of this answer, I found the following snippet most appropriate for polars: df.fill_null(False).min_horizontal().min() If no null values exist in df, one could omit .fill_null(False). Credit goes to roman, the logic of min_horizotnal().min() was first described by him in this answer on a similar issue on...
3
1
79,349,155
2025-1-12
https://stackoverflow.com/questions/79349155/how-do-i-multiply-the-values-of-an-array-contained-in-a-column-in-a-dataframe-b
I have tried to do this in order to create a new column, with each row being an array containing the values of column b multiplied by column a. data = {'a': [3, 2], 'b': [[4], [7, 2]]} df = pd.DataFrame(data) df['c'] = df.apply(lambda row: [row['a'] * x for x in row['b']]) The final result should look like this a b...
Your approach would have been correct with axis=1 (= row-wise, the default apply is column-wise): df['c'] = df.apply(lambda row: [row['a'] * x for x in row['b']], axis=1) Using apply is however quite slow since pandas creates an intermediate Series for each row. It will be more efficient to use pure python: a list com...
2
3
79,344,524
2025-1-10
https://stackoverflow.com/questions/79344524/errorit-looks-like-you-are-using-playwright-sync-api-inside-the-asyncio-loop
I have this setup File 1 from playwright.sync_api import sync_playwright class A: def __init__(self,login_dict): self.start = sync_playwright().start() self.browser = self.start.chromium.launch() self.context = self.browser.new_context() self.page = self.context.new_page() self.login_dict = login_dict File 2 import fi...
The files and classes in your code are obscuring the root cause. Nonetheless, it's good to see your intended use case, since you'd normally start Playwright with a with context manager, which isn't as obvious in the class setup. The minimal trigger is simply starting Playwright's sync API twice, which it wasn't designe...
3
1
79,339,486
2025-1-8
https://stackoverflow.com/questions/79339486/finding-loops-between-numbers-in-a-list-of-sets
Given a list of sets like: sets=[{1,2},{2,3},{1,3}] the product (1,2,3) will be generated twice in itertools.product(*sets), as the literals (1,2,3) and (2,3,1), because there is a loop. If there is no loop there will be no duplication, even though there might be lots of commonality between sets. A loop is formed to A...
To form a loop you must travel from one number ( A ) in a set to another number ( B ) in the set, then to the same number ( B ) in another set So, we cannot just connect pairs of sets that share one or more numbers. We must connect a pair of sets that share one or more numbers with one or more edges that are labelled w...
4
2
79,347,737
2025-1-11
https://stackoverflow.com/questions/79347737/django-view-is-rendering-404-page-instead-of-given-html-template
I'm working on a wiki project with django. I'm trying to render 'add.html' with the view add, but it sends me to 404 instead. All the other views are working fine. How should I fix add? views.py from django.shortcuts import render from django.http import HttpResponseRedirect, HttpResponse from django.urls import revers...
in your urls.py, <str:entry>/ path is defined before the add/ path. this causes django to interpret add/ as a dynamic entry parameter for the detail view instead of routing it to the add view. django document urlpatterns = [ path("", views.index, name="index"), path("add/", views.add, name="add"), # place "add/" before...
1
3
79,345,299
2025-1-10
https://stackoverflow.com/questions/79345299/best-default-location-for-shared-object-files
I have compiled C code to be called by a Python script. Of course I can include it with cdll.LoadLibrary("./whatever.so"), but I would prefer it to be accessible to all Python scripts in different folders. The idea is that I use default paths for shared objects and do not change environment variables or system files to...
If you do things right, then a shared library libfoo.so[.x.y.z] placed in /usr/local/lib (or in any of the directories listed in files /etc/ld.so.conf.d/*.conf) will be found in python3 by: cdll.LoadLibrary('libfoo.so.[x.y.z]'). For a shared library of your own making, /usr/local/lib is the appropriate place. For exam...
2
1
79,342,159
2025-1-9
https://stackoverflow.com/questions/79342159/finding-solutions-to-linear-system-of-equations-with-integer-constraint-in-scipy
I have a system of equations where each equation is a linear equation with boolean constraints. For example: x1 + x2 + x3 = 2 x1 + x4 = 1 x2 + x1 = 1 And each x_i is either 0 or 1. Sometimes there might be a small positive (<5) coefficient (for example x1 + 2 * x3 + x4 = 3. Basically a standard linear programming task...
You don't need to (fully) brute-force, and you don't need to find all of your solutions. You just need to find solutions for which each of your variables meets each of their extrema. The following is a fairly brain-off LP approach with 2n² columns and 2mn rows. It's sparse, and for your inputs does not need to be integ...
13
9
79,344,467
2025-1-10
https://stackoverflow.com/questions/79344467/is-my-time-complexity-analysis-for-finding-universal-words-om-k2-nk-corr
I’m given two string arrays, words1 and words2. A string b is a subset of string a if all characters in b appear in a with at least the same frequency. I need to find all strings in words1 that are universal, meaning every string in words2 is a subset of them. I need to return those universal strings from words1 in any...
Indeed, the call of count represents O(𝑘) time complexity, as it needs to scan all letters in the given word. So this makes the first loop's time complexity O(𝑚𝑘²). Similarly, the second loop has a complexity of O(26𝑛𝑘) = O(𝑛𝑘), if indeed your assumption about the range of the characters (a-z) is correct. You ca...
1
3
79,342,896
2025-1-9
https://stackoverflow.com/questions/79342896/how-can-i-override-settings-for-code-ran-in-urls-py-while-unit-testing-django
my django app has a env var DEMO which, among other thing, dictate what endpoints are declared in my urls.py file. I want to unit tests these endpoints, I've tried django.test.override_settings but I've found that urls.py is ran only once and not once per unit test. My code look like this: # settings.py DEMO = os.envir...
Vitaliy Desyatka's answer nearly works other than the fact that Django caches the URL resolver. This can be seen in Django's code, specifically the function django.urls.resolvers._get_cached_resolver is doing this. You can modify Vitaliy Desyatka's answer to add clearing of the cache to it as well like so: import impor...
1
1
79,342,183
2025-1-9
https://stackoverflow.com/questions/79342183/duckdbpyrelation-from-python-dict
In Polars / pandas / PyArrow, I can instantiate an object from a dict, e.g. In [12]: pl.DataFrame({'a': [1,2,3], 'b': [4,5,6]}) Out[12]: shape: (3, 2) ┌─────┬─────┐ │ a ┆ b │ │ --- ┆ --- │ │ i64 ┆ i64 │ ╞═════╪═════╡ │ 1 ┆ 4 │ │ 2 ┆ 5 │ │ 3 ┆ 6 │ └─────┴─────┘ Is there a way to do that in DuckDB, without going via pan...
duckdb features a function duckdb.read_json which should do this by simply streaming the dict as a json string, but no combination of its various parameters will make it read that dict the same way polars does unfortunately. You can rearrange the dict to match the structure expected for a "unstructured" json format in ...
1
2
79,343,703
2025-1-9
https://stackoverflow.com/questions/79343703/generalized-kronecker-product-with-different-type-of-product-in-numpy-or-scipy
Consider two boolean arrays import numpy as np A = np.asarray([[True, False], [False, False]]) B = np.asarray([[False, True], [True, True]]) I want to take the kronecker product of A and B under the xor operation. The result should be: C = np.asarray([[True, False, False, True], [False, False, True, True], [False, Tru...
You could use broadcasting and reshaping: m, n = A.shape p, q = B.shape C = (A[:, None, :, None] ^ B[None, :, None, :]).reshape(m*p, n*q) Simplified: C = (A[:, None, :, None] ^ B[None, :, None, :] ).reshape(A.shape[0]*B.shape[0], -1) Also equivalent to: C = (np.logical_xor.outer(A, B) .swapaxes(1, 2) .reshape(A.shape...
2
4
79,344,035
2025-1-9
https://stackoverflow.com/questions/79344035/how-to-add-requirements-txt-to-uv-environment
I am working with uv for the first time and have created a venv to manage my dependencies. Now, I'd like to install some dependencies from a requirements.txt file. How can this be achieved with uv? I already tried manually installing each requirement using uv pip install .... However, this gets tedious for a large list...
You can install the dependencies to the virtual environment managed by uv using: uv pip install -r requirements.txt When working with a project (application or library) managed by uv, the following command might be used instead: uv add -r requirements.txt This will also add the requirements to the project's pyproject...
3
4
79,343,784
2025-1-9
https://stackoverflow.com/questions/79343784/pyspark-issue-in-converting-hex-to-decimal
I am facing an issue while converting hex to decimal (learned from here) in pyspark. from pyspark.sql.functions import col, sha2, conv, substring # User data with ZIPs user_data = [ ("100052441000101", "21001"), ("100052441000102", "21002"), ("100052441000103", "21002"), ("user1", "21001"), ("user2", "21002") ] df_user...
Spark's LongType range is -9223372036854775808 to 9223372036854775807. However, your value 16524032462328413763 is outside of this range so it cannot store as LongType. If you remove .cast("bigint"), you can see that your values won't be null and have correct values.
1
3
79,343,521
2025-1-9
https://stackoverflow.com/questions/79343521/issues-generating-barcode-in-dataimage-pngbase64-format-with-custom-size-and-n
I’m working on a Python project where my goal is to generate barcodes in the data:image/png;base64 format, without any human-readable footer text. Additionally, I need to adjust the size (height and width) and DPI (dots per inch) of the barcode, but I'm encountering some difficulties. Specifically, I have two issues: I...
I think the docs are slightly off for the current latest version 0.15-1. I was able to change the size and remove the human readable barcode text from under the image with the following code: def generate_barcode_without_text(serial_no): barcode_instance = barcode.Code128(serial_no, writer=ImageWriter()) writer_options...
2
1
79,342,508
2025-1-9
https://stackoverflow.com/questions/79342508/inverse-fast-fourier-transform-ifft2-of-scipy-not-working-for-fourier-optics
I'm following a tutorial on youtube on Fourier Optics in python, to simulate diffraction of light through a slit. The video in question Source Code of video Now, I'm trying to implement the get_U(z, k) function and then display the corresponding plot below it, as shown in the video (I've got barebones knowledge abou...
Your units of lam are wrong - if you intend to use pint (but I suggest that you don't) then they should be in nm, not mm. When you have made that change I suggest that you remove all reference to pint and mixed units and work entirely in a single set of length units (here, m). This is because units appear to be strippe...
3
5
79,342,389
2025-1-9
https://stackoverflow.com/questions/79342389/numpy-grayscale-image-to-black-and-white
I use the MNIST dataset that contains 28x28 grayscale images represented as numpy arrays with 0-255 values. I'd like to convert images to black and white only (0 and 1) so that pixels with a value over 128 will get the value 1 and pixels with a value under 128 will get the value 0. Is there a simple method to do so?
Yes. Use (arr > 128) to get a boolean mask array of the same shape as your image, then .astype(int) to cast the bools to ints: >>> import numpy as np >>> arr = np.random.randint(0, 255, (5, 5)) >>> arr array([[153, 167, 141, 79, 58], [184, 107, 152, 215, 69], [221, 90, 172, 147, 125], [ 93, 35, 125, 186, 187], [ 19, 72...
1
4
79,340,547
2025-1-8
https://stackoverflow.com/questions/79340547/how-to-import-nested-modules-with-uv
I am managing a project with uv. My project includes - src - app.py - constants.py - notebooks - testing.ipynb - pyproject.toml where my pyproject.toml is [project] name = "benchmark-extractor" version = "0.1.0" description = "Add your description here" readme = "README.md" requires-python = ">=3.13" dependencies = [ ...
Add this section into pyproject.toml: [tool.uv] package = true Then run uv sync Now you should be able to import app in notebooks/testing https://docs.astral.sh/uv/concepts/projects/config/#project-packaging
1
3
79,341,984
2025-1-9
https://stackoverflow.com/questions/79341984/converting-a-column-to-date-in-pandas
I'm having difficulty with Pandas when trying to convert this column to a date. The table doesn't include a year, so I think that's making the conversion difficult. 28 JUL Unnamed: 0 Alura *Alura - 7/12 68,00 0 28 JUL NaN Passei Direto S/A. - 3/12 19,90 1 31 JUL NaN Drogarias Pacheco 25,99 2 31 JUL NaN Mundo Verde - R...
This looks like Brazilian Portuguese, you should install the pt_BR locale on your machine, then run: import locale locale.setlocale(locale.LC_ALL, 'pt_BR.UTF-8') df['Data_converted'] = pd.to_datetime(df['Data'], format='%d %b', errors='coerce') Output: Data Data_converted 0 28 JUL 1900-07-28 1 04 AGO 1900-08-04 And,...
1
4
79,340,487
2025-1-8
https://stackoverflow.com/questions/79340487/properly-re-expose-submodule-or-is-this-a-bug-in-pylance
I am working on a python package chemcoord with several subpackages, some of whom should be exposed to the root namespace. The repository is here, the relevant __init__.py file is here. For example there is a chemcoord.cartesian_coordinates.xyz_functions that should be accessible as chemcoord.xyz_functions Accessible, ...
nit: # -*- coding: utf-8 -*- hasn't been needed in python source files for a very very long time, given that it is default starting with interpreter 3.0. And 3.8 went EOL last year, so really you only need to worry about 3.9 and later. And these seem odd: ... import Cartesian as Cartesian, ... import Zmat as Zmat sys.m...
1
2
79,339,965
2025-1-8
https://stackoverflow.com/questions/79339965/why-does-pyrtools-imshow-print-a-value-range-thats-different-from-np-min-an
quick problem description: pyrtools imshow function giving me different and negative ranges details: im following the tutorial at https://pyrtools.readthedocs.io/en/latest/tutorials/01_tools.html since i dont have .pgm image, i'm using the below .jpg image. here is the modified python code import matplotlib.pyplot as ...
That is behavior of pyrtools, specifically decided by vrange='auto2'. 'auto2': all images have same vmin/vmax, which are the mean (across all images) minus/plus 2 std dev (across all images) (documentation in source) If you don't like that library's behavior, you can file a bug at https://github.com/LabForComputation...
2
2
79,340,441
2025-1-8
https://stackoverflow.com/questions/79340441/python-polars-expression-list-product
In Python-Polars, it is easy to calculate the Sum of all the lists in an array with polars.Expr.list.sum. See the example below for the sum: df = pl.DataFrame({"values": [[[1]], [[2, 3], [5,6]]]}) df.with_columns( sum=pl.concat_list(pl.col("values")).list.eval( pl.element().list.sum())) shape: (2, 2) ┌─────────────────...
pl.Expr.list.eval() to get into list context. pl.element() to get access to element within list context. pl.Expr.product() to calculate product. pl.Expr.list.first() to get the result as scalar. df.with_columns( product = pl.col.values.list.eval( pl.element().list.eval( pl.element().product() ).list.first() ) ) shap...
2
2
79,339,647
2025-1-8
https://stackoverflow.com/questions/79339647/why-does-scraping-followers-count-from-instagram-fails
I'm trying to scrape the number of followers of an array of username. I'm using BeautifulSoup. The code I'm using is the following import requests from bs4 import BeautifulSoup def instagram_followers(username): headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) ...
Code works fine in focus of your question, so issue is not reproducable, without any additional information. Check following: response.status_code as first indicator, may you scrape to aggressivly and the server will handle this by blocking your ip. also implement your headers, they are not used in your code import r...
2
0
79,338,219
2025-1-8
https://stackoverflow.com/questions/79338219/panda-iterate-rows-and-multiply-nth-row-values-to-nextn1-row-value
I am trying to iterate multiple column rows and multiply nth row to n+1 row after that add columns. I tried below code and it's working fine. Is there any other simply way to achieve the subtraction and multiplication part together? import pandas as pd df = pd.DataFrame({'C': ["Spark","PySpark","Python","pandas","Java"...
First remove iterating by iterrows, then is possible simplify a generalize solution by: cols = ['F','D'] for col in cols: s = df[f'{col}_x'].sub(df[f'{col}_y']) df[f'{col}_mul'] = s.mul(s.shift()) df['+'.join(cols)] = df.filter(like='mul').sum(axis=1, min_count=1) print (df) C F_x D_x F_y D_y F_mul D_mul F+D 0 Spark 2 ...
2
2
79,372,122
2025-1-20
https://stackoverflow.com/questions/79372122/how-to-check-if-a-cuboid-is-inside-camera-frustum
I want to check if an object (defined by four corners in 3D space) is inside the Field of View of a camera pose. I saw this solution and tried to implement it, but I missed something, can you please tell me how to fix it? the provided 4 points are 2 inside, 2 outside camera frustum. import numpy as np from typing imp...
EDIT: pending a response from the OP. There is a problem with your cam_pose matrix. The [0:3,0:3] components (first three rows and first three columns) should be a rotation matrix. However, it isn't: the first and third columns aren't orthogonal. Well, no matter how I try to do it, I think all those points lie outside ...
4
4
79,375,777
2025-1-21
https://stackoverflow.com/questions/79375777/fourier-series-implementation-cannot-approximate-batman-shape
I tried to implement a formula, from which a coefficients of Fourier Series could be calculated. (I used 3B1B's video about it: Video) and writing code for that, my first test subject was singular contour of batman logo, I first take a binary picture of batman logo and use marching squares algorithm to find contour of ...
In the definition of the Fourier series, you can see that n goes from negative infinity to positive infinity. The issue in your code is that you forgot to compute the coefficients associated with negative values of n. Here is a simple example that shows how to compute the coefficients (from -50 to 50) associated with a...
9
5
79,372,057
2025-1-20
https://stackoverflow.com/questions/79372057/aggregate-3d-array-using-zone-and-time-index-arrays
Using the small example below, I'm seeking to aggregate (sum) the values in the 3D dat_arr array using two other arrays to guide the grouping. The first index of dat_arr is related to time. The second and third indices are related to spatial (X, Y) locations. How can I sum values in dat_arr such that the temporal binni...
First, let's compute this with a loop to get a sense of the potential output: sums = {} # for each combination of coordinates for i in range(len(tim_idx)): for j in range(zon_arr.shape[0]): for k in range(zon_arr.shape[1]): # add the value to the (time, zone) key combination key = (tim_idx[i], zon_arr[j, k]) sums[key] ...
2
2
79,373,051
2025-1-21
https://stackoverflow.com/questions/79373051/how-to-handle-inconsistent-columns-ragged-rows-in-a-delimited-file-using-polar
I am working with a legacy system that generates delimited files (e.g., CSV), but the number of columns in these files is inconsistent across rows (ragged rows). I am reading the file from ADLS with Polars, but I'm encountering an issue depending on the structure of the second row in the file. pl.read_csv('sample.csv',...
Read it in as a single column by setting the separator to (hopefully) an unused utf8 character with no header and then use .str.split.list.to_struct followed by unnest to allow a dynamic number of columns. Then you have to rename the columns and slice out the first row. import polars as pl import io from warnings impor...
4
1
79,371,384
2025-1-20
https://stackoverflow.com/questions/79371384/cartopy-doesnt-render-left-and-right-longitude-labes
I'm using cartopy to draw a geomap. This is how I set up graticule rendering: if graticule: gl = ax.gridlines( draw_labels=True, linewidth=0.8, color='gray', alpha=0.5, linestyle='--', x_inline=False, y_inline=True ) gl.xlocator = mticker.FixedLocator(np.arange(-180, 181, 10)) gl.ylocator = mticker.FixedLocator(np.ara...
In draw_labels parameter, instead of setting it to True you can pass a dictionary with each 4 side and which coordinates you wish to see: gl = ax.gridlines( draw_labels={"bottom": "x", "left": "x", "right":"x"}, linewidth=0.8, color='gray', alpha=0.5, linestyle='--', x_inline=False, y_inline=True ) You will also need ...
1
2
79,375,373
2025-1-21
https://stackoverflow.com/questions/79375373/how-to-align-split-violin-plots-with-seaborn
I am trying to plot split violin plots with Seaborn, i.e. a pair of KDE plots stacked against each other, typically to see the difference between distributions. My use case is very similar to the docs except I would like to superimpose custom box plots on top (as in this tutorial) However, I am having a strange alignme...
The issue is due to the NaNs that you have after melting. This makes 4 groups and thus the violins are shifted to account for those. You could plot the groups independently: data_flat = data.melt('column').dropna(subset='value') violin_ax = plt.subplot() pal = sns.color_palette('Paired') for i, (name, g) in enumerate(d...
3
2
79,375,192
2025-1-21
https://stackoverflow.com/questions/79375192/how-to-define-the-search-space-for-a-simple-equation-optimization
I'm trying to learn skopt, but I'm struggling to get even a simple multivariate minimization to run. import skopt def black_box_function(some_x, some_y): return -some_x + 2 - (some_y - 1) ** 2 + 1 BOUNDS = [(0, 100.0), (0, 100.0)] result = skopt.dummy_minimize(func=black_box_function, dimensions=BOUNDS) When I run thi...
Quoting the documentation Function to minimize. Should take a single list of parameters and return the objective value. So black_box_function should not have two parameters some_x, some_y, but a single parameter some_xy, that is a list of those two def black_box_function(some_xy): some_x, some_y = some_xy return -som...
4
3
79,374,797
2025-1-21
https://stackoverflow.com/questions/79374797/how-to-calculate-horizontal-median
How to calculate horizontal median for numerical columns? df = pl.DataFrame({"ABC":["foo", "bar", "foo"], "A":[1,2,3], "B":[2,1,None], "C":[1,2,3]}) print(df) shape: (3, 4) ┌─────┬─────┬──────┬─────┐ │ ABC ┆ A ┆ B ┆ C │ │ --- ┆ --- ┆ --- ┆ --- │ │ str ┆ i64 ┆ i64 ┆ i64 │ ╞═════╪═════╪══════╪═════╡ │ foo ┆ 1 ┆ 2 ┆ 1 │ │...
There's no median_horizontal() at the moment, but you could use pl.concat_list() to create list column out of all pl.Int64 columns. pl.Expr.list.median() to calculate median. df.with_columns( pl.concat_list(pl.col(pl.Int64)).list.median().alias("Horizontal Median") ) shape: (3, 5) ┌─────┬─────┬──────┬─────┬─────────...
5
2
79,374,674
2025-1-21
https://stackoverflow.com/questions/79374674/pandas-dataframe-update-with-filter-func
I have two dataframes with identical shape and want to update df1 with df2 if some conditions are met import pandas as pd from typing import Any df1 = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]}) print(df1, "\n") df2 = pd.DataFrame({"A": [7, 8, 9], "B": [10, 3, 12]}) print(df2, "\n") # Define a condition function def...
Your function will receive a 1D numpy array (per column), it should be vectorized and return a boolean 1D array (callable(1d-array) -> bool 1d-array). Use numpy.isin to test membership: def condition(x): """condition function to update only cells matching the conditions""" return np.isin(x, [2, 7, 9]) df1.update(df2, f...
1
3
79,374,415
2025-1-21
https://stackoverflow.com/questions/79374415/matplotlib-multiple-axes-mixups
I have a problem with a multi axis matplotlib plot. The code is close to what I want but somehow axes are getting mixed up. The ticks are missing on ax4 aka the green y-axis but only show up on ax2 (the red one) and the labels are duplicated and appear on both axes, ax2 and ax4. import numpy as np import matplotlib.pyp...
You just need to replace: ax4.yaxis.set_tick_params(labelleft=True) by: ax4.yaxis.set_tick_params(which='major', left=True, right=False, labelleft=True, labelright=False) ax4.yaxis.set_tick_params(which='minor', left=True, right=False, labelleft=True, labelright=False) You put the yaxis major tick labels to the left ...
2
0
79,371,127
2025-1-20
https://stackoverflow.com/questions/79371127/module-does-not-explicitly-export-attribute-attr-defined
In bar.py foo is imported # bar.py from path import foo In my current file bar is imported and I use the get_id function of foo: from path import bar bar.foo.get_id() Mypy is complaining error: Module "bar" does not explicitly export attribute "foo" [attr-defined]
Is it your own module? Use one of these two options that are suggested in the mypy docs; the __all__ is generally preferred # This will re-export it as bar and allow other modules to import it from foo import bar as bar # This will also re-export bar from foo import bar __all__ = ['bar'] If its a 3rd party; but also v...
1
1
79,372,830
2025-1-20
https://stackoverflow.com/questions/79372830/add-business-days-including-weekends
I'm trying to adjust a date by adding a specified number of business days but I would like to adjust for weekends. The weekend days, however, could change depending on the record. So if my data set looks like this: ┌────────────┬────────┬──────────┬──────────┐ │ DT ┆ N_DAYS ┆ WKND1 ┆ WKND2 │ │ --- ┆ --- ┆ --- ┆ --- │ │...
week_mask supposed to be be Iterable, so it seems you can't pass expression there. You can iterate over different masks though: pl.DataFrame.partition_by() to split DataFrame into dict of dataframes. process dataframes, creating week_mask out of partition key. pl.concat() to concat result dataframes together. weekday...
4
2
79,373,355
2025-1-21
https://stackoverflow.com/questions/79373355/how-to-use-vectorized-calculations-in-pandas-to-find-out-where-a-value-or-catego
With a dataset with millions of records, I have items with various categories and measurements, and I'm trying to figure out how many of the records have changed, in particular when the category or measurement goes to NaN (or NULL from the database query) during the sequence. In SQL, I'd use some PARTITION style OLAP f...
You can use a combination of groupby.diff and fillna to achieve this. We compare the row difference with 0 to find any rows where measure changed: test_df['measure_change'] = test_df.groupby('item')['measure'].diff().fillna(0) != 0 Result: item measure measure_change 0 20 1 False 1 20 1 False 2 20 1 False 3 20 3 True...
2
3
79,371,872
2025-1-20
https://stackoverflow.com/questions/79371872/how-to-accelerate-the-cross-correlation-computation-of-two-2d-matrices-in-python
I am using Python to compute the cross-correlation of two 2D matrices, and I have implemented three different methods. Below is my experimental code along with their execution times: import numpy as np from scipy.signal import fftconvolve # Randomly generate 2D matrices a = np.random.randn(64, 4200) b = np.random.randn...
I do not think you can find a much faster implementation than that using a sequential code on CPU. This answer explains why. It also provide a slightly-faster experimental FFTW-based implementation which is up to 40% faster, and alternative possibly-faster solutions. Profiling and analysis The FFT library used by Scip...
3
5
79,371,928
2025-1-20
https://stackoverflow.com/questions/79371928/multiple-overlapping-seaborn-violin-plots-split-by-hue
I am trying to create overlapping and transparent violin plots split by one variable using seaborn in python. My dataset looks like this: The variable "names" are "one" to "nine", "distance" is from 0 to 1, condition is either "healthy" or "disease", and "sample_id" is 1 to 16. Each "condition" has 8 sample_ids. Pleas...
With density_norm="count", the width of the violin for the x-value with the highest count (for the given sample_id) is maximized. The width of the other violins is shrunk relative to their count. In the given dataset, it seems that each sample_id is either fully 'healthy' or fully 'disease'. When drawing one sample_id,...
1
2
79,365,212
2025-1-17
https://stackoverflow.com/questions/79365212/how-to-filter-a-lot-of-colors-out-of-an-image-the-numpy-way
I have an image, from which I would like to filter some colors: if a given pixel is in my set of colors, I would like to replace it by a white pixel. With an image called original of shape (height, width, 3) and a color like ar=np.array([117,30,41]), the following works fine: mask = (original == ar).all(axis=2) origina...
A simple way to solve this would be a look up table. A look up table with a boolean for every color would only cost 256 * 256 * 256 * 1 bytes = 16 MiB, and would enable you to determine if a color is in your list of disallowed colors in constant time. Here is an example. This code generates an image with multiple color...
2
2
79,370,632
2025-1-20
https://stackoverflow.com/questions/79370632/asyncio-future-running-future-objects
I have a code: import asyncio as aio async def coro(future: aio.Future): print('Coro start') await aio.sleep(3) print('Coro finish') future.set_result('coro result') async def main(): future = aio.Future() aio.create_task(coro(future)) await future coro_result = future.result() print(coro_result) aio.run(main()) In ma...
First, let's clear up some terminology. You said, "Then I 'run' the empty future with await future ..." A future is not "run". A future represents a value that will be set in the future. If you await the future, there has to be some other task that calls set_result on the future before your await is satisfied. Then you...
1
3
79,371,681
2025-1-20
https://stackoverflow.com/questions/79371681/matplotlib-colobar-with-wrong-range-in-3d-surface
I'm trying to plot a value around the unit sphere using surface plot and facecolors in matplotlib, but my colorbar shows the normalized values instead of the real values. How can I fix this so the colorbar has the right range? import numpy as np import matplotlib.pyplot as plt import matplotlib as mpl from matplotlib i...
The colorbar function itself doesn't have a norm argument according to the documentation for this function. For minimal alteration, you can pass a matplotlib.cm.ScalarMappable as the first argument of the colorbar call and it works as expected (presuming you also pass the appropriate ax argument). Here is a fully runna...
1
2
79,357,840
2025-1-15
https://stackoverflow.com/questions/79357840/extracting-credentials-from-1password-using-onepassword-python-library
I am using this python library ("OnePassword python client") in which to interact with my 1Password instance and extract API credentials from a vault named "Employee". Python Function: def authenticate(base_endpoint, api_key, api_secret): op = OnePassword() available_vaults = op.list_vaults() employee_vault = next((vau...
The Wandera/1password-client [GIT] [PyPI] library simply does not support Windows. From the Operating systems part of the README (as of Jan 2025): The library is split into two parts: installation and client in which we are slowly updating to cover as many operating systems as possible the following table should ensu...
5
8
79,371,481
2025-1-20
https://stackoverflow.com/questions/79371481/caching-of-parameterized-nested-fixtures-in-pytest
I am trying to understand how and when return values from pytest fixtures are cached. In my understanding, the goal of fixtures (in particular session-scoped fixtures) is that they are called only once and that return values are cached for future calls. This does not seem to be the case for nested parameterized fixture...
From the docs (Note box) Pytest only caches one instance of a fixture at a time, which means that when using a parametrized fixture, pytest may invoke a fixture more than once in the given scope. If you look closely at the console output you will see that you count the changes in the returned value from first test_le...
2
2
79,370,497
2025-1-20
https://stackoverflow.com/questions/79370497/type-annotate-inside-loop
The mypy error is Need type annotation for "args" [var-annotated] Need type annotation for "kwargs" [var-annotated] and here is the piece of code expected_args: Optional[Sequence[Tuple[Any, ...]]] expected_kwargs: Optional[Sequence[Dict[str, Any]]] ... expected_args_iter = iter(expected_args or ()) expected_kwargs_ite...
This appears to be a bug in mypy v1.14.0. For some reason, any iteration over itertools.zip_longest() with an empty sequence* in fillvalue will cause a similar issue. This is the simplest example I could construct: import itertools seq_a: list seq_b: list for a, b in itertools.zip_longest(seq_a, seq_b, fillvalue=[]): ....
2
2
79,369,085
2025-1-19
https://stackoverflow.com/questions/79369085/does-order-of-transforms-applied-for-data-augmentation-matter-in-torchvision-tra
I have the following Custom dataset class for an image segmentation task. class LoadDataset(Dataset): def __init__(self, img_dir, mask_dir, apply_transforms = None): self.img_dir = img_dir self.mask_dir = mask_dir self.transforms = apply_transforms self.img_paths, self.mask_paths = self.__get_all_paths() self.__pil_to_...
Yes, the order of transformations matters. In this case, the transform to tensors makes the difference. When v2.RandomHorizontalFlip is given two tensors, the flip will be applied independently. However, when two PIL images are given, the same transform will be applied to both images, thus keeping the image and mask al...
2
0
79,369,363
2025-1-19
https://stackoverflow.com/questions/79369363/scipy-minimise-to-find-inverse-function
I have a (non-invertible) function ak([u,v,w]) This takes a point on the surface of the unit octahedron (p: such that |u|+|v|+|w| = 1) and returns a point on the surface of the unit sphere. The function isn't perfect but the intention is to keep the distance between points authalic. I was thinking of using SciPy minimi...
One idea I found that helped significantly was to convert this from a minimization problem to a root-finding problem. The root-finders don't support constraints, so you need to change the objective function to force x to be L1 normalized before converting into Cartesian coordinates. def fn_root(op, tx): # octa_point, t...
3
3
79,366,429
2025-1-18
https://stackoverflow.com/questions/79366429/matplotlib-legend-not-respecting-content-size-with-lualatex
I need to generate my matplotlib plots using lualatex instead of pdflatex. Among other things, I am using fontspec to change the document fonts. Below I am using this as an example and set lmroman10-regular.otf as the font. This creates a few issues. One is that the handles in the legends are not fully centered and are...
It seems that when using custom font settings, you have to set the following rcParam: matplotlib.rcParams["pgf.rcfonts"] = False Otherwise, if I understand it correctly, the font settings are applied from the rcParams. This solves the spacing issue with your example: For more details, see also the documentation of th...
3
2
79,369,295
2025-1-19
https://stackoverflow.com/questions/79369295/convert-a-pdf-to-a-png-with-transparency
My goal is to obtain a PNG file with a transparent background from a PDF file. The convert tool can do the job: $ convert test.pdf test.png $ file test.png test.png: PNG image data, 595 x 842, 8-bit gray+alpha, non-interlaced But I would like to do it programmatically in python without relying on convert or any other ...
With PyMuPDF, you can do this: import pymupdf doc=pymupdf.open("test.pdf") for page in doc: pix = page.get_pixmap(alpha=True, dpi=150) pix.save(f"{doc.name}-{page.number}.png") Results in transparent PNG images named "test.pdf-0.png", etc. The images have a resolution of 150 DPI in above case. Note: I am a maintainer ...
1
3
79,368,759
2025-1-19
https://stackoverflow.com/questions/79368759/tensorflow-probability-mixturenormal-layer-example-not-working-as-in-example
Tensorflow version is 2.17.1 Tensoflow probability version is 0.24.0 Example from the documentation https://www.tensorflow.org/probability/api_docs/python/tfp/layers/MixtureNormal?hl=en is the following: import numpy as np import tensorflow as tf import tensorflow_probability as tfp tfd = tfp.distributions tfpl = tfp.l...
Taking a look at the release notes of TensorFlow Probability: "NOTE: In TensorFlow 2.16+, tf.keras (and tf.initializers, tf.losses, and tf.optimizers) refers to Keras 3. TensorFlow Probability is not compatible with Keras 3 -- instead TFP is continuing to use Keras 2, which is now packaged as tf-keras and tf-keras-nigh...
2
2
79,367,831
2025-1-18
https://stackoverflow.com/questions/79367831/python-3d-surface-interpolation-from-2d-simulation-data
I’m working with a 3D dataset in Python where some (x,y) points create frame-like structures, some of them with multiple z-values per (x,y) pair, which seems to lead to a problem with griddata. The provided code produces the interpolation between 2 data sets as a working example, and then tries to interpolate 2 data se...
Don't interpolate in a rectilinear parameter space. Instead, you need to Transform to a semipolar (cylindrical) coordinate space with y as linear, and xz radius and xz angle as the other axes. If I had to guess a safe x-z origin, it would be (0, 0). Interpolate on that. Prior to graphing, transform back to xyz. This ...
3
6
79,367,208
2025-1-18
https://stackoverflow.com/questions/79367208/why-does-my-finite-difference-weights-calculation-for-taylor-series-give-incorre
I'm trying to calculate the weights for a finite-difference approximation of the first derivative f′(x)f'(x)f′(x) using the Taylor series expansion. I'm solving for weights a,b,c,d,ea, b, c, d, ea,b,c,d,e such that: af(x+2Δx)+bf(x+Δx)+cf(x)+df(x−Δx)+ef(x−2Δx)a f(x+2\Delta x) + b f(x+\Delta x) + c f(x) + d f(x-\Delta x)...
You have a typo in the 4th line of the matrix A, the last element should be -8 instead of 8: A = np.array([ [1, 1, 1, 1, 1], # Coefficients of f(x) [2, 1, 0, -1, -2], # Coefficients of f'(x) [4, 1, 0, 1, 4], # Coefficients of f''(x) [8, 1, 0, -1, -8], # Coefficients of f'''(x) [16, 1, 0, 1, 16] # Coefficients of f''''(...
2
2
79,366,590
2025-1-18
https://stackoverflow.com/questions/79366590/how-to-correctly-implement-fermats-factorization-in-python
I am trying to implement efficient prime factorization algorithms in Python. This is not homework or work related, it is completely out of curiosity. I have learned that prime factorization is very hard: I want to implement efficient algorithms for this as a self-imposed challenge. I have set to implement Fermat's fact...
You're supposed to start with a ← ceiling(sqrt(N)), not a = int(n ** 0.5 + 0.5). At the very least use a = math.ceil(n ** 0.5) instead, then Fermat_Factor(17) already gives (1.0, 17.0) instead of (3.0, 5.0). But really better stay away from floats, use math.isqrt. And of course you don't need abs if you actually comput...
2
2
79,366,678
2025-1-18
https://stackoverflow.com/questions/79366678/attributeerror-figurecanvasinteragg-object-has-no-attribute-tostring-rgb-d
#AttributeError: 'FigureCanvasInterAgg' object has no attribute 'tostring_rgb'. Did you mean: 'tostring_argb'? #import matplotlib.pyplot as plt #======================== # This can be work # import matplotlib # matplotlib.use('TkAgg') # import matplotlib.pyplot as plt #========================= with open('notebook.txt'...
The following code runs successfully on my computer, and my maplotlib verson is 3.7.1 if you don't know your matplotlib verson,you can press "ctrl" and 'r',then input "cmd" to open the terminal,and input "pip list",then you can find your matlotlib version import matplotlib.pyplot as plt from matplotlib import rcParams ...
3
0
79,366,298
2025-1-17
https://stackoverflow.com/questions/79366298/how-to-check-for-specific-structure-in-nested-list-python
Suppose we have the list: mylist = [ [ "Hello", [ "Hi" ] ] ] How do I check that list containing "Hello" and "Hi" exists in mylist, in specifically this structure without flattening it? All the solutions are flattening the list, but I need to check for specific structure, like this Array |_ —-|_ “Hello” ———|_ “Hi” ——....
You can just ask whether it's in there: ["Hello", ["Hi"]] in mylist Attempt This Online!
1
1
79,365,680
2025-1-17
https://stackoverflow.com/questions/79365680/how-to-explain-pandas-higher-performances-compared-to-numpy-with-500k-rows
In some sources, I found that pandas works faster than numpy with 500k rows or more. Can someone explain this to me? Pandas have a better performance when the number of rows is 500K or more. — Difference between Pandas VS NumPy - GeeksforGeeks If the number of rows of the dataset is more than five hundred thousand (...
Adding to the discussion, here are those tests in the linked page reproduced with some minor changes to see if anything has changed since that original post was made almost 8 years ago and python and many of its libraries have upgraded quite a bit since then. According to python.org the newest version of python availab...
2
1
79,363,079
2025-1-16
https://stackoverflow.com/questions/79363079/what-is-causing-some-points-to-fail-sampling-an-enclosing-mesh-how-do-i-preve
I am using the PyVista package to resample a .vtk mesh of nonconforming rectangular prisms onto a grid of points. However, some of the points fail to sample the dataset, which results in a "0" value in the index of that point in pointset_sample.point_data['vtkValidPointMask'] and either 0 or some NaN color value when p...
I can reproduce your issue and I don't know why it happens, but frankly I've never quite understood the subtleties of sample/probe/interpolate and friends, despite multiple attempts of more knowledgeable people to explain these to me :) So I also don't know if any of the other similar filters could be applicable. It mi...
3
1
79,365,706
2025-1-17
https://stackoverflow.com/questions/79365706/why-factorization-of-products-of-close-primes-is-much-slower-than-products-of-di
This is a purely academic question without any practical consideration. This is not homework, I dropped out of high school long ago. I am just curious, and I can't sleep well without knowing why. I was messing around with Python. I decided to factorize big integers and measure the runtime of calls for each input. I use...
In don't recognize, that this question is related to programming. Your algorithm executes trial divisions (starting with the smallest numbers) and terminates at the square root of the input number, so the worst case is actually trying to factorize the square number of a prime (maximum factor possible). Encountering a l...
1
3
79,365,035
2025-1-17
https://stackoverflow.com/questions/79365035/using-sympy-replace-and-wild-symbols-to-match-and-substitute-arbitrary-functions
Is it possible with sympy Wild symbols and replace to match arbitrary function applications? What I would ideally like to do is the following: x = Symbol('x') expr1 = sin(x) expr2 = exp(x) F = Wild('F') #or maybe WildFunction('F')? result1 = expr1.replace(F(x), lambda F: F(tan(x))) #expected: sin(tan(x)) result2 = expr...
Yes, but you're looking for Wild's properties argument and can use the type() of the match to nest a function call >>> F = Wild("F", properties=[lambda F: F.is_Function]) >>> expr1.replace(F, lambda F: type(F)(tan(x))) sin(tan(x)) Or to be more picky about which functions are replaced >>> F = Wild("F", properties=[lam...
2
1
79,365,086
2025-1-17
https://stackoverflow.com/questions/79365086/can-i-have-different-virtual-environments-in-a-project-managed-by-uv
On a Windows machine, I'm developing a Python project that I manage using uv. I run the unit tests with uv run pytest, and uv automatically creates a virtual environment in .venv. So far, so good. But every now and then, I want to run the unit tests - or other commands - in Linux (from the same project source directory...
To support different virtual environments in a uv-managed project, the environment variable UV_PROJECT_ENVIRONMENT might be used. UV_PROJECT_ENVIRONMENT: Specifies the path to the directory to use for a project virtual environment. See the project documentation for more details. You could set it to .venv_windows or ....
2
1
79,358,200
2025-1-15
https://stackoverflow.com/questions/79358200/position-of-robotic-arm-base-in-gymnasium-robotics-fetch-environments-off-cente
I am trying to solve the Farama gymnasium-robotic fetch environments, specifically the "FetchReachDense-v3" problem. When running the simulation, the base of the robotic arm seems to be misplaced: This, firstly, looks weird, is not like that in the gymnasium-robotics documentation or other example solutions of this pr...
I found the problem. Apparently the gymnasium-robotics version (1.3.1) that is accessible through pip / pypi has versions v1 and v3 of the FetchReach environments (for me, it was not possible to run v2 even though it is mentioned in the documentation). When I went through the code on GitHub I saw that there also is a v...
2
3
79,365,194
2025-1-17
https://stackoverflow.com/questions/79365194/numerically-obtaining-response-of-a-damped-driven-oscillator-gives-peak-at-wrong
I am trying to plot the response of a periodically-driven damped oscillator whose dynamics is governed by, x''+ 2Gx' + f0^2 x = F cos(ft) where the constants denote the following. G: Damping coefficient f0: Natural frequency f: Driving frequently F: Strength of the drive To do so, I solved the above differential equati...
Your frequencies f0 and f1 are applied in the finite-difference model in rad/s. This may or may not have been your intention. However, your frequencies from the FFT are in cycles/s. Since you are using the symbol f, rather than omega, I would guess that you want them in cycles/s. In your finite-difference model then yo...
4
4