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
78,446,008
2024-5-8
https://stackoverflow.com/questions/78446008/altair-boxplot-border-to-be-set-black-and-median-line-red
I want to set a black border color to the boxplot of a altair graph, i try to add stroke parameter to black on the encoding chanel but this overrided my red median line to black. This is the code I am trying: def plot_hourly_boxplot_altair(data, column, session_state=None): # Convert 'fecha' column to datetime format d...
You can set the properties of the box components inside mark_boxplot as mentioned here in the docs, rather than via the encoding: import altair as alt from vega_datasets import data source = data.cars() alt.Chart(source).mark_boxplot( color='lightblue', box={'stroke': 'black'}, # Could have used MarkConfig instead medi...
3
3
78,448,761
2024-5-8
https://stackoverflow.com/questions/78448761/how-can-i-observe-the-intermediate-process-of-cv2-erode
I've been observing the results when I apply cv2.erode() with different kernel values. In the code below, it is (3, 3), but it is changed to various ways such as (1, 3) or (5, 1). The reason for this observation is to understand kernel. I understand it in theory. And through practice, I can see what kind of results I g...
When you call cv2.erode from Python it eventually gets down to one C++ API call of cv::erode. As you can see in the documentation, this API does not support inspecting intermediate result from the process. This means it is also not available from the Python wrapper. The only way you can achieve what you want is to down...
3
3
78,447,053
2024-5-8
https://stackoverflow.com/questions/78447053/create-multiple-columns-from-a-single-column-and-group-by-pandas
work = pd.DataFrame({"JOB" : ['JOB01', 'JOB01', 'JOB02', 'JOB02', 'JOB03', 'JOB03'], "STATUS" : ['ON_ORDER', 'ACTIVE','TO_BE_ALLOCATED', 'ON_ORDER', 'ACTIVE','TO_BE_ALLOCATED'], "PART" : ['PART01', 'PART02','PART03','PART04','PART05','PART06']}) How can I use Pandas to groupby the JOB, split Status into columns based ...
Try: x = df.groupby("JOB")["PART"].agg(", ".join).rename("PART_CON") y = pd.crosstab(df["JOB"], df["STATUS"]).astype(bool) print(pd.concat([y, x], axis=1).reset_index()) Prints: JOB ACTIVE ON_ORDER TO_BE_ALLOCATED PART_CON 0 JOB01 True True False PART01, PART02 1 JOB02 False True True PART03, PART04 2 JOB03 True Fals...
5
5
78,445,577
2024-5-8
https://stackoverflow.com/questions/78445577/polars-select-multiple-element-wise-products
Suppose I have the following dataframe: the_df = pl.DataFrame({'x1': [1,1,1], 'x2': [2,2,2], 'y1': [1,1,1], 'y2': [2,2,2]}) ┌─────┬─────┬─────┬─────┐ │ x1 ┆ x2 ┆ y1 ┆ y2 │ │ --- ┆ --- ┆ --- ┆ --- │ │ i64 ┆ i64 ┆ i64 ┆ i64 │ ╞═════╪═════╪═════╪═════╡ │ 1 ┆ 2 ┆ 1 ┆ 2 │ │ 1 ┆ 2 ┆ 1 ┆ 2 │ │ 1 ┆ 2 ┆ 1 ┆ 2 │ └─────┴─────┴───...
you can do something like this: zs = ['z1','z2'] df.with_columns( (pl.col(xc) * pl.col(yc)).alias(zc) for xc, yc, zc in zip(xs, ys, zs) ) ┌─────┬─────┬─────┬─────┬─────┬─────┐ │ x1 ┆ x2 ┆ y1 ┆ y2 ┆ z1 ┆ z2 │ │ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │ │ i64 ┆ i64 ┆ i64 ┆ i64 ┆ i64 ┆ i64 │ ╞═════╪═════╪═════╪═════╪═════╪═════...
4
4
78,446,065
2024-5-8
https://stackoverflow.com/questions/78446065/socket-gaierror-errno-2-name-or-service-not-known-firebase-x-raspberry-pi
I am using a Python program to click a picture on my Raspberry Pi 3B+ when motion is detected and send this image to firebase storage. import RPi.GPIO as GPIO import gpiozero import datetime import picamera import time import os import pyrebase firebase_config = { "apiKey": "...", "authDomain": "x.firebaseapp.com", "da...
Since you have been able to successfully transfer data using your local computer, this is purely a Pi and/or network issue. The error "socket. gaierror: [Errno -2] Name or service not known" typically points to a DNS resolution issue. This error indicates that the hostname used in your application cannot be resolved to...
2
2
78,445,852
2024-5-8
https://stackoverflow.com/questions/78445852/django-annotation-convert-time-difference-to-whole-number-or-decimal
I am trying to sum the hours user spent per day. I wanted to convert this into whole number or decimal to represent HOURS(e.g. 2, 6.5), to easily plot this to my chart. But the result of below code is in this format HH:mm:ss. Any one can help me with this? day = Clocking.objects.filter(clockout__isnull=False, user=nid)...
Based on Func using the sql functions TIMEDIFF and then TIME_TO_SEC, will return the seconds: day = Clocking.objects.filter(clockout__isnull=False, user=nid).annotate(date=TruncDate('clockin')) .values('date').annotate( total=Sum( Func( Func( F('clockout'),F('clockin'), function='TIMEDIFF'), function='TIME_TO_SEC') ))....
3
2
78,436,539
2024-5-6
https://stackoverflow.com/questions/78436539/superimpose-plot-with-background-image-chart
I am trying to use an existing graph as a background for new data that I want to plot on top of the graph. I have been able to do so when using a graph with all information contained within the axes and using the extent parameter of plt.imshow because then I just have to scale the image. I would like to scale and shift...
We can follow this answer to a related question and adapt it to your needs (see code comments for explanations): import matplotlib.pyplot as plt bg_img = plt.imread('stackoverflow/bg.png') # TODO: Adjust as necessary bg_width, bg_xlim, bg_ylim = 6, (0, 20), (0, 15) # Create a figure with the same aspect ratio and scale...
2
3
78,423,306
2024-5-3
https://stackoverflow.com/questions/78423306/how-to-asynchronously-run-matplolib-server-side-with-a-timeout-the-process-hang
I'm trying to reproduce the ChatGPT code interpreter feature where a LLM create figures on demand by executing to code. Unfortunately Matplotlib hangs 20% of time, I have not managed to understand why. I would like the implementation: to be non-blocking for the rest of the server to have a timeout in case the code is ...
I finally found the source of the bug, and it was NOT in the code interpretor (I should have expected it since I could not reproduce the bug in a simplified settings). It turns GPT does not always respect the signature of the tools. For instance instance instead of returning a dict {"code": "..."} it will sometimes dir...
4
0
78,436,536
2024-5-6
https://stackoverflow.com/questions/78436536/how-do-i-prevent-virtual-environments-having-access-to-system-packages
noob here. I have a dockerised jupyter lab instance where I have a bunch of packages installed for the root user, and now I want to add an additional kernel that has no packages at all (yet). Here's how I've tried to do that: # SYSTEM SETUP FROM python:3.11.5-bookworm ADD requirements/pip /requirements/pip RUN pip inst...
Check Kernel Configuration: Make sure that when you install the ipykernel in your blank-env, you are activating the virtual environment before installing it. FROM python:3.11.5-bookworm ADD requirements/pip /requirements/pip RUN pip install -r /requirements/pip RUN python -m venv /venv/blank RUN /venv/blank/bin/pip in...
3
0
78,439,730
2024-5-7
https://stackoverflow.com/questions/78439730/openssl-3-0s-legacy-provider-failed-to-load
When I started Anaconda Prompt (Anaconda3),the following error message floats and I could not figure out hhow to resolve it. "Error while loading conda entry point: conda-content-trust (OpenSSL 3.0's legacy provider failed to load. This is a fatal error by default, but cryptography supports running without legacy algor...
conda install cryptography If you are using linux / Mac then add this command to .bashrc or .zshrc file export CRYPTOGRAPHY_OPENSSL_NO_LEGACY=1 and then run source ./bashrc or ./zshrc If you are using Window Under "System variables", click "New..." and add CRYPTOGRAPHY_OPENSSL_NO_LEGACY as the variable name and 1 ...
3
3
78,430,267
2024-5-4
https://stackoverflow.com/questions/78430267/why-is-pandas-str-functions-slower-than-apply
I'm processing a large dataset, particularly these two columns: Genotype Iteration 10010110011011101101011000010011111011111000000111001001101111111101101111001011 0 00011100001011010000000110010010100101101011001010101110110111000101000110000000 0 001001001001001010001001011001101001011100001001110000000110...
The answer is that the str operations are not vectorize as @mozway and @roganjosh mentioned.
3
1
78,444,253
2024-5-7
https://stackoverflow.com/questions/78444253/autoencoders-and-polar-coordinates
Can an autoencoder learn the transformation into polar coordinates? If a set of 2D data lies approximately on a circle, there is a lower-dimensional manifold, parameterized by the angle, that describes the data 'best'. I tried various versions without success. import matplotlib.pyplot as plt import numpy as np import p...
Can an autoencoder learn the transformation into polar coordinates? If a set of 2D data lies approximately on a circle, there is a lower-dimensional manifold, parameterized by the angle, that describes the data 'best'. Neural nets can be trained to learn arbitrary transformations, including analytical ones like mappi...
3
2
78,418,808
2024-5-2
https://stackoverflow.com/questions/78418808/how-to-write-a-test-if-the-argument-defines-a-type
This is not a pydantic question, but to explain why am I asking: pydantic.TypeAdapter() accepts (among many others) all the following type definitions as its argument and can create a working validator for them: int int|str list list[str|int] typing.Union[int,str] typing.Literal[10,20,30] Example: >>> validator = pyda...
I think you can use typing.get_origin combined with isinstance(x, type) like you already mentioned: import typing def defines_type(x): return isinstance(x, type) or typing.get_origin(x) is not None Testing it out we see our defines_type function returns True for all these: int int|str list list[str|int] typing.Union[i...
4
2
78,421,110
2024-5-2
https://stackoverflow.com/questions/78421110/how-to-draw-a-polygon-spanning-the-pole-with-cartopy
I am trying to draw polygons on a map at arbitrary locations, including places that span the pole and the dateline. Conceptually, consider drawing instrument footprints for orbital measurements, where the corners of the footprints are known in lat/long (or cartesian). I have been able to get mid-latitude polygons to dr...
I think that the following is a general solution that is sufficient for my purposes: from matplotlib.patches import Polygon import matplotlib.pyplot as plt import cartopy.crs as ccrs # Test patches are boxes with regular angular width qSz = 40/2 poly = [ ( -qSz, qSz ), ( qSz, qSz ), ( qSz, -qSz ), ( -qSz, -qSz ) ] fig ...
2
1
78,438,668
2024-5-6
https://stackoverflow.com/questions/78438668/generating-random-passphrases-from-sets-of-strings-with-secrets-random-is-not-ve
I have a requirement for a basic passphrase generator that uses set lists of words, one for each position in the passphrase. def generate(self) -> str: passphrase = "%s-%s-%s-%s-%s%s%s" % ( self.choose_word(self.verbs), self.choose_word(self.determiners), self.choose_word(self.adjectives), self.choose_word(self.nouns)...
Nature of the Problem Let's start by asserting that there is a 1-to-1 mapping between k-dimensional list indices for lists of length ℓ1,...,ℓk and integers in the range [0,...,Π(ℓ1,...,ℓk)-1], where Π denotes the product of the set of values. The following python class shows an implementation of the math which does tha...
2
2
78,424,396
2024-5-3
https://stackoverflow.com/questions/78424396/plotting-a-combined-heatmap-and-clustermap-problems-with-adding-two-colorbars
I have two omics datasets which I woud like to compare. For this I plot one as a clustermap, and extract the order from it and plot the exact same genes as a heatmap, so that I can make a direct comparison between the two datasets. However, I would like to show the colorbars for both, and I cannot seem to get it to wor...
Below you find some example code to adapt the layout and add the colorbars. Some remarks: sns.clustermap has a parameter cbar_pos to directly set the position of the colobar sns.clustermap also has a parameter dendrogram_ratio which define the space for the row and column dendrograms (the column dendrograms aren't use...
2
1
78,443,779
2024-5-7
https://stackoverflow.com/questions/78443779/how-to-check-if-a-lazyframe-is-empty
Polars dataframes have an is_empty attribute: import polars as pl df = pl.DataFrame() df.is_empty() # True df = pl.DataFrame({"a": [], "b": [], "c": []}) df.is_empty() # True This is not the case for Polars lazyframes, so I devised the following helper function: def is_empty(data: pl.LazyFrame) -> bool: return ( data....
As explained in the comments, "A LazyFrame doesn't have length. It is a promise on future computations. If we would do those computations implicitly, we would trigger a lot of work silently. IMO when the length is needed, you should materialize into a DataFrame and cache that DataFrame so that that work isn't done twic...
5
6
78,445,033
2024-5-7
https://stackoverflow.com/questions/78445033/implement-frequency-encoding-in-polars
I want to replace the categories with their occurrence frequency. My dataframe is lazy and currently I cannot do it without 2 passes over the entire data and then one pass over a column to get the length of the dataframe. Here is how I am doing it: Input: df = pl.DataFrame({"a": [1, 8, 3], "b": [4, 5, None], "c": ["foo...
pl.len() will evaluate to the "column length". You can also use it in a group context (agg/over) as a way to count the values. df.with_columns(pl.len().over("c") / pl.len()).collect() shape: (3, 3) ┌─────┬──────┬──────────┐ │ a ┆ b ┆ c │ │ --- ┆ --- ┆ --- │ │ i64 ┆ i64 ┆ f64 │ ╞═════╪══════╪══════════╡ │ 1 ┆ 4 ┆ 0.333...
2
2
78,444,101
2024-5-7
https://stackoverflow.com/questions/78444101/footnotes-causing-errant-match-using-regex-in-python
I'm parsing text in Python using regex that typically looks like some version of this: JT Meta Platforms, Inc. - Class A Common Stock (META) [ST]S (partial) 02/08/2024 03/05/2024 $1,001 - $15,000 F S: New S O: Morgan Stanley - Select UMA Account # 1 JT Microsoft Corporation - Common Stock (MSFT) [ST]S (partial) 02/08/2...
Since you expect only single matches per line, you can use ^(?![A-Z] [A-Z]:).*\(([A-Z]+\.?[A-Z]*)\) See the regex demo. Details: ^ - start of string (?![A-Z] [A-Z]:) - exclude the string that starts with an uppercase letter + space + uppercase letter + : .* - any zero or more chars other than line break chars as many...
2
1
78,440,198
2024-5-7
https://stackoverflow.com/questions/78440198/restarting-the-python-interpreter-using-python-c-api
I have a C++/Qt application where I am running a Python interpreter session within the process of the main application. I have built a 'python console' as a QPlainTextEdit widget, which handles the input and output for the interpreter using the Python C API. The point of all this is that Python will have direct access ...
From Py_FinalizeEx documentation: Bugs and caveats: The destruction of modules and objects in modules is done in random order; this may cause destructors (del() methods) to fail when they depend on other objects (even functions) or modules. Dynamically loaded extension modules loaded by Python are not unloaded. Small ...
3
1
78,425,424
2024-5-3
https://stackoverflow.com/questions/78425424/how-can-you-specify-python-runtime-version-in-vercel
I am trying to deploy a simple FastAPI app to vercel for the first time. Vercel.json is exactly below. { "devCommand": "uvicorn main:app --host 0.0.0.0 --port 3000", "builds": [ { "src": "api/index.py", "use": "@vercel/python", "config": { "maxLambdaSize": "15mb", "runtime": "python3.9" } } ], "routes": [ { "src": "/(....
I've scrolled through vercel docs but wasn't been able find any references that python version could be specified in builds or functions section of Vercel.json. in 'builds' you specify npm package @vercel/python. I guess this is more like interface for node.js to run python3 scripts. in 'functions' you kind off specif...
3
2
78,442,162
2024-5-7
https://stackoverflow.com/questions/78442162/how-to-construct-a-networkx-graph-from-a-dictionary-with-format-node-neighbor
I have the following dictionary that contains node-neighbor-weight pairs: graph = { "A": {"B": 3, "C": 3}, "B": {"A": 3, "D": 3.5, "E": 2.8}, "C": {"A": 3, "E": 2.8, "F": 3.5}, "D": {"B": 3.5, "E": 3.1, "G": 10}, "E": {"B": 2.8, "C": 2.8, "D": 3.1, "G": 7}, "F": {"G": 2.5, "C": 3.5}, "G": {"F": 2.5, "E": 7, "D": 10}, }...
You need to add the dictionary as edges to the graph import networkx as nx from matplotlib import pyplot as plt graph = { "A": {"B": 3, "C": 3}, "B": {"A": 3, "D": 3.5, "E": 2.8}, "C": {"A": 3, "E": 2.8, "F": 3.5}, "D": {"B": 3.5, "E": 3.1, "G": 10}, "E": {"B": 2.8, "C": 2.8, "D": 3.1, "G": 7}, "F": {"G": 2.5, "C": 3.5...
2
1
78,426,073
2024-5-3
https://stackoverflow.com/questions/78426073/best-way-to-avoid-a-loop
I have 2 dataframes of number x and y of same length and an input number a. I would like to find the fastest way to calculate a third list z such as : z[0] = a z[i] = z[i-1]*(1+x[i]) + y[i] without using a loop like that : a = 213 x = pd.DataFrame({'RandomNumber': np.random.rand(200)}) y = pd.DataFrame({'RandomNumber...
You can't really vectorize this function, the development of the operation becomes too complex. For instance, z[i+1] expressed in function of z[i-1] is equal to: z[i-1]*(1+x[i])+y[i] + z[i]*(x[i+1]+x[i]*x[i+1]) + y[i]*x[i] + y[i+1] And this get worse for each step As suggested in comment, if speed is a concern, you co...
3
1
78,438,776
2024-5-6
https://stackoverflow.com/questions/78438776/linear-regression-on-groupby-pandas-dataframe
Currently I have my code set up like this: def lregression(data, X, y): X = df['sales'].values.reshape(-1, 1) y = df['target'] model = LinearRegression() result = model.fit(X, y) return model.score(X, y) Then, I'm trying to apply this model per brand: df.groupby('brand').apply(lregression, X, y) But the result just g...
DATAFRAME A minimal reproducible example is always nice to have, I'll provide it here: np.random.seed(42) data = { 'brand': np.random.choice(['Brand A', 'Brand B', 'Brand C'], size=300), 'sales': np.random.randint(100, 1000, size=300), 'target': np.random.randint(100, 1000, size=300) } df = pd.DataFrame(data) FUNCTION...
2
1
78,440,430
2024-5-7
https://stackoverflow.com/questions/78440430/sorting-a-polars-liststruct-by-struct-value
How do I use polars.Expr.list.sort to sort a list of structs by one of the struct values, i.e. df = pl.DataFrame([{"id": 1, "data": [{"key": "A", "value": 2}, {"key": "B", "value": 1}]}]) I want to sort data by the value field, i.e. the result should be df = pl.DataFrame([{"id": 1, "data": [{"key": "B", "value": 1}, {...
Indeed, pl.Expr.list.sort does not take any arguments on the comparison function used for the sorting. This seems like a reasonable feature request for polars' Github page. Until this is implemented, I can think of 2 possible approaches. Polars seems to sort the list primarily based on the first struct field. Hence, r...
3
5
78,440,228
2024-5-7
https://stackoverflow.com/questions/78440228/understanding-the-role-of-shuffle-in-np-random-generator-choice
From the documentation for numpy's random.Generator.choice function, one of the arguments is shuffle, which defaults to True. The documentation states: shuffle bool, optional Whether the sample is shuffled when sampling without replacement. Default is True, False provides a speedup. There isn't enough information for...
You are still getting a random choice regardless of your selection for shuffle. If you select shuffle=False, however, the ordering of the output is not independent of the ordering of the input. This is easiest to see when the number of items chosen equals the total number of items: import numpy as np rng = np.random.de...
3
2
78,426,546
2024-5-3
https://stackoverflow.com/questions/78426546/where-did-sys-modules-go
>>> import sys >>> del sys.modules['sys'] >>> import sys >>> sys.modules Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: module 'sys' has no attribute 'modules' Why does re-imported sys module not have some attributes anymore? I am using Python 3.12.3 and it happens in macOS, Lin...
This is pretty obviously something you shouldn't do, naturally liable to break things. It happens to break things this particular way on the Python implementation you tried, but Python doesn't promise what will happen. Most of what I am about to say is implementation details. The sys module cannot be initialized like ...
8
9
78,434,935
2024-5-6
https://stackoverflow.com/questions/78434935/in-python-how-can-should-decorators-be-used-to-implement-function-polymorphism
Supposing we have a class as follows: class PersonalChef(): def cook(): print("cooking something...") And we want what it cooks to be a function of the time of day, we could do something like this: class PersonalChef(): def cook(time_of_day): ## a few ways to do this, but this is quite concise: meal = {'morning':'brea...
A simpler approach would be to create a decorator factory that stores the decorated function in a dict that maps the function name and time of day to the function object, and returns a wrapper function that calls the stored function in the first class in the MRO that has it defined for the given time of day: def at_tim...
3
1
78,439,363
2024-5-6
https://stackoverflow.com/questions/78439363/how-does-the-javascript-pendant-of-a-python-class-implementation-look-like
Am studying the difference between those two languages and i was wondering why i can't access the variables in javascript classes without initiating an instance but i can do that in python here is an example of what am talking about: PYTHON CLASS class Car: all =[] def __init__(self, name): self.name = name Car.all.ap...
You need to declare it static, otherwise it's an instance property: class Car { static all = []; constructor(name, miles) { this.name = name; this.miles = miles; Car.all.push(this); } } let ford = new Car("ford", 324); let tesla = new Car("tesla", 3433); console.log(Car.all); In Python variables declared outside m...
2
3
78,428,358
2024-5-4
https://stackoverflow.com/questions/78428358/create-multipolygon-objects-from-struct-type-and-listlistlistf64-columns-u
I have downloaded the NYC Taxi Zones dataset (downloaded from SODA Api and saved as json file - Not GeoJson or Shapefile). The dataset is rather small, thus I am using the whole information included. For the convenience of the post I am presenting the first 2 rows of the dataset: original (with struct type value of th...
I have eventually found a solution for this problem. As already described I am flattening the list of coordinates (a.k.a Points). A point in geospatial data is a (x,y) coordinate. Thus, a MultiPolygon is a combination of multiple Points. def flatten_list_of_lists(data) -> list: return [subitem2 for subitem1 in data for...
3
0
78,438,578
2024-5-6
https://stackoverflow.com/questions/78438578/replace-dots-commas-in-string-so-that-it-can-be-cast-to-float
I'm trying to convert a str column from str to float (it's intended to be a float). However, the string have commas and dots and I'm not being able to correctly replace the values: import polars as pl df = pl.DataFrame({"numbers": ["1.004,00", "2.005,00", "3.006,00"]}) df = df.with_column( df["numbers"].str.replace("."...
str.replace uses regular expressions, so the dot matches the first character. Just escape it: import polars as pl df = pl.DataFrame({ "numbers": ["1.004,00", "2.005,00", "3.006,00"] }) df = ( df .with_columns( pl.col('numbers').str.replace("\.", "").str.replace(",", ".").cast(pl.Float64) ) ) print(df) Output: shape: (...
3
3
78,434,965
2024-5-6
https://stackoverflow.com/questions/78434965/numpy-index-argsorted-with-integer-array-while-retaining-sorting-order
I have an array x and the result of argsorting it i. I need to sort x (and y, irrelevant here) according to i hundreds of times. It is therefore not doable to sort the data twice, everything needs to be achieved via the initial sorting i. If I take x[i] it returns the sorted x as expected. However, I now only want to u...
In [263]: x = np.array([14, 15, 9, 6, 19, 18, 4, 11, 10, 0]) ...: i = np.argsort(x) ...: n = np.array([2, 5, 7, 8]) i and n do different, and unrelated indexing operations. Both make copies (not views), which don't retain any information on the original x: In [264]: x[i] Out[264]: array([ 0, 4, 6, 9, 10, 11, 14, 15, 1...
2
1
78,437,755
2024-5-6
https://stackoverflow.com/questions/78437755/plotly-how-to-change-the-tick-text-of-the-colorbar-in-a-heatmap
I am using Plotly package for my visualizations. This MWE creates a 10x10 matrix and plots it in a Heatmap. import numpy as np import pandas as pd import plotly.graph_objects as go vals = np.random.rand(10,10)*5 vals = np.around(vals) tick_text = ['A','B','C','D','E'] df = pd.DataFrame(vals) fig = go.Figure(go.Heatmap(...
You also need to specify the coloraxis the trace should refer to when building the heatmap. coloraxis - Sets a reference to a shared color axis. References to these shared color axes are "coloraxis", "coloraxis2", "coloraxis3", etc. Settings for these shared color axes are set in the layout, under layout.coloraxis, la...
2
1
78,420,645
2024-5-2
https://stackoverflow.com/questions/78420645/worker-failed-to-index-functions-with-azure-functions-fastapi-local-using-asgi
Running into an error that has started after a reboot. I am testing using Azure Functions in conjunction with FastAPI based on: https://dev.to/manukanne/azure-functions-and-fastapi-14b6 Code was operating and test API call worked as expected. After a reboot of the machine and restarting VSCode I am now running into an ...
Based on comments by JarroVGIT, I refactored the function_app.py code to: import azure.functions as func from fastapi import FastAPI, Request, Response import logging fast_app = FastAPI() @fast_app.exception_handler(Exception) async def handle_exception(request: Request, exc: Exception): return Response( status_code=40...
2
2
78,437,508
2024-5-6
https://stackoverflow.com/questions/78437508/verifying-constructor-calling-another-constructor
I want to verify Foo() calls Bar() without actually calling Bar(). And then I want to verify that obj is assigned with whatever Bar() returns. I tried the following: class Bar: def __init__(self, a): print(a) class Foo: def __init__(self): self.obj = Bar(1) ### import pytest from unittest.mock import Mock, patch from m...
This line: assert result.obj == mock_bar Should be: assert result.obj == mock_bar.return_value It is the result of calling Bar which gets assigned in self.obj = Bar(1), not Bar itself.
2
2
78,434,960
2024-5-6
https://stackoverflow.com/questions/78434960/how-to-mock-property-with-side-effects-based-on-self-using-pytest
I've tried the code bellow, using new_callable=PropertyMock to mock a property call, and autospec=True to be able to access self in the side effect function: from unittest.mock import PropertyMock def some_property_mock(self): if self.__some_member == "some_value" return "some_different_value" else: return "some_other_...
Since the property some_property is patched with MagicMock, which is then patched with MyMock, and you want to set the return value of the property callable when it's called, you should do so on the mock object returned from patching MagicMock with MyMock instead: with mock.patch.object(mock, 'MagicMock', MyMock) as pr...
4
2
78,436,247
2024-5-6
https://stackoverflow.com/questions/78436247/tkinter-control-the-location-of-colorchooser
I have a program where I want to use the colorchooser dialog from tkinter. My problem is that the color chooser dialog is always opening on the top left of the root window. For example with the following code I get it as shown in the picture. import tkinter as tk from tkinter import ttk from tkinter.colorchooser import...
It seems it must be at this position relative to parent. So a working trick with a fake hidden parent : import tkinter as tk from tkinter import ttk from tkinter.colorchooser import askcolor class App: def __init__(self, master): self.master = master self.master.geometry('400x200') self.button = ttk.Button(self.master,...
5
6
78,436,275
2024-5-6
https://stackoverflow.com/questions/78436275/convert-raw-bytes-image-data-received-from-python-into-c-qt-qicon-to-be-displa
I am creating small GUI system and I would like to get an image in the form of raw bytes from Python code and then create QImage/QIcon using those raw bytes. For C++/Python interaction I am using Boost Python. On Python code side I printed the raw bytes: b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00@\x00\x00\x00@\x...
Assuming on the Python side you have data.rawBytes = thumbnail._raw_bytes without the str wrapper, and a C++ variable obj referring to data, you can use the Python Buffer protocol like so: Py_Buffer view = {0}; int ret = PyObject_GetBuffer(obj.attr("rawBytes").ptr(), &view, PyBUF_SIMPLE); if (ret == -1) { // handle er...
2
2
78,436,093
2024-5-6
https://stackoverflow.com/questions/78436093/inspect-asm-gives-no-output
I have this simple MWE: from numba import njit @njit def add(a, b): return a + b # Now let's inspect the assembly code for the 'add()' function. for k, v in add.inspect_asm().items(): print(k) when I run it I get no output. What is the right way to inspect the assembly?
You need to first compile the function to populate .inspect_asm(), either by calling it or by specifying the signature. E.g.: from numba import njit @njit def add(a, b): return a + b # first call add() to compile it add(1, 2) print(add.inspect_asm()) Prints: {(int64, int64): '\t.text\n\t.file\t"<string>"\n\t.globl\t_Z...
2
2
78,435,402
2024-5-6
https://stackoverflow.com/questions/78435402/compute-number-of-hours-the-user-spent-per-day
I have Clocking table in database. I wanted to count the users' time spent per day. For example 2024-03-21, user 1 spend 6.8 hours, the next day he spends n number of hours and so on (['6.8', 'n', ... 'n']) user date timein timeout 1 2024-03-21 10:42 AM 12:00 PM 1 2024-03-21 01:10 PM 06:00 PM 1 2024-03-22 01...
Please don't use a CharField to keep track. Imagine that a person enters now, then how will that work? It means you make the number of possible values a lot larger, and also increases disk space usage, altough that last one is probably not that much of an issue. There are essentially two options: working with TimeField...
2
3
78,434,296
2024-5-6
https://stackoverflow.com/questions/78434296/polars-dataframe-how-do-i-drop-alternate-rows-by-group
I have a sorted dataframe with a column that represents a group. How do I filter it to remove all the alternate rows by the group. The dataframe length is guaranteed to be an even number if it matters. Sample Input: ┌───────────┬───────────┐ │ group_col ┆ value_col │ │ --- ┆ --- │ │ i64 ┆ i64 │ ╞═══════════╪═══════════...
.gather_every() exists. In order to use it with .over() - you can change the default mapping_strategy= to explode df.select( pl.all().gather_every(2).over("group_col", mapping_strategy="explode") ) shape: (4, 2) ┌───────────┬───────────┐ │ group_col ┆ value_col │ │ --- ┆ --- │ │ i64 ┆ i64 │ ╞═══════════╪═══════════╡ │...
4
2
78,434,979
2024-5-6
https://stackoverflow.com/questions/78434979/how-to-fit-axis-and-radius-of-3d-cylinder
Once I get some 3-D point coordinates, what algorithm do I use to fit an optimal cylindrical and get the direction vector and radius of the central axis? My previous idea was to divide a cylinder into layers, and as the number of layers increased, the figure formed by the dots got closer to the cylinder, but in this c...
Here is a MCVE to regress axis defined by p0 and p1 (vectors) and radius R (scalar). First we create some dummy dataset: import numpy as np import matplotlib.pyplot as plt from scipy import optimize from scipy.spatial.transform import Rotation def cylinder(n=60, m=20, r=2, h=5): t = np.linspace(0, m * 2 * np.pi, m * n)...
3
2
78,435,356
2024-5-6
https://stackoverflow.com/questions/78435356/python-hexbin-plot-with-2d-function
I'm trying to display a two dimensional function on a hexagonal grid with pyplot.hexbin but it only produces a line and ignores the rest of the function. How do I solve this? def func(x,y): return x*2+y*2 x = np.linspace((-0.5)/4*5, (0.5)/4*5, int(2e3)) y = np.linspace(-0.5, 0.5, int(2e3)) plt.hexbin(x, y, func(x,y), g...
The func(x,y) function returns a scalar value for each (x, y) pair, but hexbin expects x and y to be arrays of the same length representing coordinates. Input another array Z with the scalar values which will be the colours of each hex. Try: import numpy as np import matplotlib.pyplot as plt def func(x,y): return x*2+y...
2
1
78,435,157
2024-5-6
https://stackoverflow.com/questions/78435157/confusing-conversion-of-types-in-pandas-dataframe
Suppose I have a list of list of numbers that happen to be encoded as strings. import pandas as pd pylist = [['1', '43'], ['2', '42'], ['3', '41'], ['4', '40'], ['5', '39']] Now I want a dataframe where these numbers are integers. I can see from pandas documentation that I can force a data type via dtype, but when I r...
I would consider it a bug. During instantiation, the input goes though several checks (_homogenize / sanitize_array / _try_cast). I believe an intermediate float dtype is created which triggers the error (on pandas 2.2): ValueError: Trying to coerce float values to integers A workaround would be to use: pd.DataFrame(p...
3
3
78,434,699
2024-5-6
https://stackoverflow.com/questions/78434699/why-does-filtering-based-on-a-condition-results-in-an-empty-dataframe-in-pandas
I'm working with a DataFrame in Python using pandas, and I'm trying to apply multiple conditions to filter rows based on temperature values from multiple columns. However, after applying my conditions and using dropna(), I end up with zero rows even though I expect some data to meet these conditions. The goal is compar...
Use DataFrame.where: condition = (df1[temp_cols].lt(df1[ambient_col] + 40, axis=0)) df1[temp_cols] = df1[temp_cols].where(condition) If need new DataFrame add DataFrame.reindex: temp_cols = ['Temp1', 'Temp2', 'Temp3', 'Temp4', 'Temp5', 'Temp6'] ambient_col = 'AmbientTemp' condition = (df1[temp_cols].lt(df1[ambient_col...
2
3
78,433,658
2024-5-5
https://stackoverflow.com/questions/78433658/what-is-this-einsum-operation-doing-e-np-einsumij-kl-il-a-b
given A = np.array([[1,2],[3,4],[5,6],[7,8]]) B = np.array([[9,10,11],[12,13,14]]) matrix multiplication would be if I did C = np.einsum('ij,jk->ik', A, B) but if I don't multiply j in the input instead using k ... E = np.einsum('ij,kl->il', A, B) what am I effectively summing across? Is there a way to think about t...
This sums A over axis=1, B over axis=0 and computes the outer product: np.einsum('ij,kl->il', A, B) np.outer(A.sum(1), B.sum(0)) array([[ 63, 69, 75], [147, 161, 175], [231, 253, 275], [315, 345, 375]]) You could check the individual einsum results: # sum over 1 np.einsum('ij->i', A) # array([ 3, 7, 11, 15]) # sum ove...
3
2
78,430,312
2024-5-4
https://stackoverflow.com/questions/78430312/how-to-get-pyparsing-to-match-1-day-or-2-days-but-fail-1-days-and-2-day
I'm trying to match a sentence fragment of the form "after 3 days" or "after 1 month". I want to be particular with the single and plural forms, so "1 day" is valid but "1 days" is not. I have the following code which is nearly there but the first two entries in the failure tests don't fail. Any suggestions please that...
Only the case after 1 days passes when it should fail, the other three cases fail as expected. The issue is that the check multi = Word(nums) + units uses nums which includes 1, so even if your singular variant does not work, this one will. I looked up how nums is defined, apparently it is nums = '0123456789' (see here...
2
1
78,433,277
2024-5-5
https://stackoverflow.com/questions/78433277/how-to-deal-with-a-python-project-dependency-that-must-exist-in-the-env-but-ca
I don't have a lot of experience with python project organization, but I've been trying to follow modern best practices using a pyproject.toml and structure as in this video (minus the ci bits). This is ultimately a geoprocessing tool for ArcGIS Pro, though I've tried to abstract the logic of the tool from the 'backend...
How do you deal with this situation? What are best practices? So you should list arcpy in your pyproject.toml or requirements. It simply "exists" in the conda environment provided by the install of ArcGIS Pro Great. So if you list the dependency, users will know that you require the ArcGIS Pro to work. I've tried ...
3
1
78,428,161
2024-5-4
https://stackoverflow.com/questions/78428161/how-to-create-two-frames-top-and-bottom-that-have-the-same-height-using-tkint
In Tkinter Python, I want to create two frames and place one on top of the other, and then insert a matplotlib plot inside each of these two frames. That, I managed to do. The problem is that, when created, these two frames always seem to have different heights (the bottom one is always smaller than the top one). My go...
Different idea: create one FigureCanvasTkAgg but two axis fig, (ax1, ax2) = plt.subplots(2) and matplotlib will control size. import tkinter as tk from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg import matplotlib.pyplot as plt import numpy as np root = tk.Tk() #root.state('zoomed') plt.rcParams["axes.p...
2
1
78,430,938
2024-5-5
https://stackoverflow.com/questions/78430938/polars-how-to-partition-a-big-dataframe-and-save-each-one-in-parallel
I have a big Polars dataframe with a lot of groups. Now, I want to partition the dataframe by group and save all sub-dataframes. I can easily do this as follows: for d in df.partition_by(["group1", "group2"]): d.write_csv(f"~/{d[0, 'group1']}_{d[0, 'group2']}.csv") However, the approach above is sequential and slow wh...
As far as I am aware, Polars does not currently offer a way to parallelize .write_*() / .sink_*() calls. For Parquet files, this would be similar to writing a "Hive Partitioned Dataset": https://github.com/pola-rs/polars/issues/11500 https://github.com/pola-rs/polars/issues/15441 # CSV Hive partitioning Multiprocessi...
2
2
78,431,472
2024-5-5
https://stackoverflow.com/questions/78431472/how-to-extract-text-from-an-element-using-bs4
I am scraping Airbnb (Link to the following page), and one of the things I want to get is since when is the host hosting, as shown in the picture below (marked with red pen): image example The code I am currently using to solve this is: account_active_since = soup.find('li', class_='l7n4lsf atm_9s_1o8liyq_keqd55 dir di...
Here is one way of getting that information (no BeautifulSoup needed): from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC...
2
1
78,429,932
2024-5-4
https://stackoverflow.com/questions/78429932/langchain-ollama-and-llama-3-prompt-and-response
Currently, I am getting back multiple responses, or the model doesn't know when to end a response, and it seems to repeat the system prompt in the response(?). I simply want to get a single response back. My setup is very simple, so I imagine I am missing implementation details, but what can I do to only return the sin...
Using a PromptTemplate from Langchain, and setting a stop token for the model, I was able to get a single correct response. from langchain_community.llms import Ollama from langchain import PromptTemplate # Added llm = Ollama(model="llama3", stop=["<|eot_id|>"]) # Added stop token def get_model_response(user_prompt, sy...
2
8
78,429,220
2024-5-4
https://stackoverflow.com/questions/78429220/how-can-i-fit-my-position-vs-light-intensity-data-into-a-diffraction-pattern-cur
I am trying to fit my position vs. light intensity data into a function of the form: Intensity pattern of single slit diffraction The data is from a single slit diffraction experiment, the slit with was 0.08 mm = 0.00008 m, wavelength was 650 nm = 0.00000065 m. The distance between the slit and the light sensor was 70 ...
Physically a diffraction pattern is similar to a Lorentzian curve. You can fit it as follows, by changing your p0. import numpy as np import matplotlib.pyplot as plt from scipy.optimize import curve_fit def intensityFunction(x, a, b): numerator = np.sin(np.pi * (x - b) * 0.00008 / (np.sqrt(0.49 + x ** 2 - 2 * b * x + b...
2
1
78,427,306
2024-5-3
https://stackoverflow.com/questions/78427306/field-validator-not-getting-called-in-model-serializer
I am quite new to Django. I am working on a django app which needs to store films, and when I try to load film instances with the following program: import os import json import requests # Assuming the JSON content is stored in a variable named 'films_json' json_file_path: str = os.path.join(os.getcwd(), "films.json") ...
Because ModelSerializer will map release field to a DateField. This way the validation is made against the default input date formats set by the framework. In order to override that, you need to set your own valid inputs list (I will do it at settings.py, but of course can be anywhere). DATE_INPUT_FORMATS = [ "%Y", "%Y...
2
1
78,428,016
2024-5-4
https://stackoverflow.com/questions/78428016/using-matplotlib-pcolormesh-how-can-i-stop-the-drawn-tiles-from-one-row-to-be-c
I have individual x arrays for each intensity (Z) array. Which means that the intensity rows will not be stacked on top of each other. I do not want the tiles to "tilt" so they are connected to the row above and below, I just want them to be straight in the y direction and connected in the x direction. Thank you very m...
If you use flat shading, where x and y represent the corners of each quadrilateral, then you can plot one row at a time. Note I explicitly set the vmin and vmax parameter in the pcolormesh call so that the colour range will be the same for each row even if their actual max and min differ. import numpy as np import matp...
3
2
78,428,311
2024-5-4
https://stackoverflow.com/questions/78428311/custom-hadamard-style-product-of-two-matrices-in-python
I have two numpy matrices A and B (of size m x n, m<>n, m=number of rows, n=number of columns). Both are digital matrices, consisting solely of entries 0 or 1. I want to calculate a matrix product C from these two matrices that obeys the following rules in terms of A(row, column): If A(i,j) = 1 and B(i,j)=1, C(i,j)=1. ...
IIUC you can do: Suppose you have two matrices 5x2: # A [[0 1 0 1 1] [1 1 1 1 0]] # B [[0 0 1 1 1] [0 0 1 1 0]] Then: m, n = A.shape # 5, 2 p = B.sum(axis=1) # [3 2] q = p / (n - p) # [1.5 0.66666667] m1 = A & B m2 = (A & ~B) * -q[:, None] print(m1 + m2) Prints: [[ 0. -1.5 0. 1. 1. ] [-0.66666667 -0.66666667 1. 1. 0....
4
1
78,427,983
2024-5-4
https://stackoverflow.com/questions/78427983/why-does-dictid-1-id-2-sometimes-raise-keyerror-id-instead-of-a
Normally, if you try to pass multiple values for the same keyword argument, you get a TypeError: In [1]: dict(id=1, **{'id': 2}) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) Input In [1], in <cell line: 1>() ----> 1 dict(id=1, **{'id': 2}) TypeE...
This looks like a Python bug. The code that's supposed to raise the TypeError works by detecting and replacing an initial KeyError, but this code doesn't work right. When the exception occurs in the middle of another exception handler, the code that should raise the TypeError fails to recognize the KeyError. It ends up...
49
48
78,427,086
2024-5-3
https://stackoverflow.com/questions/78427086/parse-string-with-specific-characters-if-they-exist-using-regex
I have text containing assorted transactions that I'm trying to parse using regex. Text looks like this: JT Meta Platforms, Inc. - Class A Common Stock (META) [ST]S (partial) 02/08/2024 03/05/2024 $1,001 - $15,000 F S: New S O: Morgan Stanley - Select UMA Account # 1 JT Microsoft Corporation - Common Stock (MSFT) [ST]S...
Make the "rest" after the transaction part (up to and including D:... line) optional trans = re.findall( r'\([A-Z] [^$]* \$[^$]*\$[,\d]+ (?: [^$]* D:.+ )?', text, re.X) for t in trans: print(t,'\n---') This prints (META) [ST]S (partial) 02/08/2024 03/05/2024 $1,001 - $15,000 --- (MSFT) [ST]S (partial) 02/08/2024 03/05...
2
1
78,426,876
2024-5-3
https://stackoverflow.com/questions/78426876/accessing-values-in-a-dictionary-with-jmespath-in-python-when-the-value-is-an-in
Using the dictionary: d = {'1': 'a'} How can I extract the value a using the JMESPath library in Python? The following attempts did not work: import jmespath value = jmespath.search("1", d) # throws jmespath.exceptions.ParseError: invalid token value = jmespath.search("'1'", d) # returns the key '1' instead of the val...
You can directly address an identifier if it is an unquoted-string, so A-Za-z0-9_ and if the string starts with A-Za-z_. From the grammar rule listed above identifiers can be one or more characters, and must start with A-Za-z_. An identifier can also be quoted. This is necessary when an identifier has characters not s...
2
2
78,426,163
2024-5-3
https://stackoverflow.com/questions/78426163/how-do-python-main-process-and-forked-process-share-gc-information
From the post https://stackoverflow.com/a/53504673/9191338 : spawn objects are cloned and each is finalised in each process fork/forkserver objects are shared and finalised in the main process This seems to be the case: import os from multiprocessing import Process import multiprocessing multiprocessing.set_start_met...
on linux using fork start_method when creating child processes, python uses os._exit() (note the underscore) to terminate the child process once the function ends .... this is somewhat equivalent to the process crashing, therefore no destructors have any chance of being called, the process just terminates, and the OS j...
2
2
78,425,500
2024-5-3
https://stackoverflow.com/questions/78425500/how-to-parallelize-a-simple-loop-over-a-matrix
I have a large matrix and I want to output all the indices where the elements in the matrix are less than 0. I have this MWE in numba: import numba as nb import numpy as np A = np.random.random(size = (1000, 1000)) - 0.1 @nb.njit(cache=True) def numba_only(arr): rows = np.empty(arr.shape[0]*arr.shape[1]) cols = np.emp...
The provided algorithm is inherently sequential due to the long dependency chain of instruction which is also data dependent. However, this is possible to do an equivalent operation in parallel using a scan. Implementing such a parallel algorithm based on a scan is much more complex (especially an efficient cache-frien...
2
2
78,423,942
2024-5-3
https://stackoverflow.com/questions/78423942/computing-line-that-follows-objects-orientation-in-contours
I am using cv2 to compute the line withing the object present in the mask image attached. The orientation/shape of the object might vary (horizontal, vertical) from the other mask images in my dataset. But the problem is, the method I have used to compute the line is not reliable. It works for the few images but failed...
When I was doing particle scan analysis, I eventually went with a PCA-like approach: %matplotlib notebook import matplotlib.pyplot as plt import numpy as np import cv2 im = cv2.imread("mask.png", 0) # read as gray y, x = np.where(im) # get non-zero elements centroid = np.mean(x), np.mean(y) # get the centroid of the pa...
2
3
78,423,810
2024-5-3
https://stackoverflow.com/questions/78423810/sympy-piecewise-with-numpy-array
I'd like to implement sympy.Piecewise on numpy arrays. Consider: import numpy as np from sympy import Piecewise x = np.array([0.1,1,2]) y = np.array([10,10,10]) Piecewise((x * y, x > 0.9),(0, True)) However, when I tried running it I got the following error: TypeError: Argument must be a Basic object, not ndarray Is t...
The simpy.Piecewise is not directly compatible with numpy arrays. Use np.where to achieve similar functionality: import numpy as np x = np.array([0.1,1,2]) y = np.array([10,10,10]) result = np.where(x > 0.9, x * y, 0)
2
1
78,423,647
2024-5-3
https://stackoverflow.com/questions/78423647/lambda-comparing-a-timestamp-to-all-timestamps-from-another-column-within-a-grou
I'm having trouble with specifying a lambda function. I would like to have something like the lambda below, but not quite. The code should compare a rejected_time with any paid_out_time within the group and return True, if a rejected_time occurs within 5 minutes after any paid_out_time. f = lambda x: ((x['rejected_time...
EDIT: For improve performance is used merge_asof with tolerance parameter: cols = ['paid_out_time', 'rejected_time'] df[cols] = df[cols].apply(pd.to_datetime, errors='coerce') df1 = df[['personal_id','application_id','rejected_time']].reset_index() df2 = df[['personal_id','application_id','paid_out_time']] df3 = pd.mer...
2
1
78,422,647
2024-5-3
https://stackoverflow.com/questions/78422647/sort-a-list-of-points-in-row-major-snake-scan-order
I have a list of points that represent circles that have been detected in an image. [(1600.0, 26.0), (1552.0, 30.0), (1504.0, 32.0), (1458.0, 34.0), (1408.0, 38.0), (1360.0, 40.0), (1038.0, 54.0), (1084.0, 52.0), (1128.0, 54.0), (1174.0, 50.0), (1216.0, 52.0), (1266.0, 46.0), (1310.0, 46.0), (1600.0, 74.0), (1552.0, 76...
I would first sort the data by a diagonal sweep, i.e. by increasing sum-of-coordinates. At each point (in that order) determine what would be a good left-neighbor among the points that were already processed. A good neighbor will be in the ">" shaped cone at its left, and the rightmost candidate. Once attached, the att...
4
4
78,421,170
2024-5-2
https://stackoverflow.com/questions/78421170/pydantic-how-do-i-represent-a-list-of-objects-as-dict-serialize-list-as-dict
In Pydantic I want to represent a list of items as a dictionary. In that dictionary I want the key to be the id of the Item to be the key of the dictionary. I read the documentation on Serialization, on Mapping types and on Sequences. However, I didn't find a way to create such a representation. I want these in my api ...
You can use PlainSerializer(docs) to change the serialization of a field, e.g., to change the desired output format of datetime: from pydantic import Field, BaseModel, PlainSerializer from uuid import UUID, uuid4 from datetime import datetime from typing import Annotated CustomUUID = Annotated[ UUID, PlainSerializer(la...
3
1
78,421,550
2024-5-2
https://stackoverflow.com/questions/78421550/how-to-retrieve-file-position-during-json-parsing-with-ijson-in-python
I'm using the ijson library in Python to parse a large JSON file and I need to find the position in the file where specific data is located. I want to use file.tell() to get the current position of the file reader during the parsing process. But it's only giving me the length of the file. from ijson import parse with o...
ijson.parse is using buffered reads of the source file: >>> help(ijson.parse) Help on function parse in module ijson.common: parse(source, buf_size=65536, **config) If your file is smaller than 64K it will look like f.tell() is returning the file size. If you use parse(f, buf_size=1) the f.tell() should be accurate, b...
2
2
78,417,252
2024-5-2
https://stackoverflow.com/questions/78417252/overload-function-with-supportsint-and-not-supportsint
I want to overload the function below so if passed a value that supports int() Python type hints int otherwise Python type hints the value passed. Python typing module provides a SupportsInt type we can use to check if our value supports int. from typing import Any, SupportsInt, overload @overload def to_int(value: Sup...
Types make positive promises - they specify things an object can do. Not things an object can't do. If you have an object of static type float, you know this object supports __int__, so you know it's a member of type SupportsInt. If you have an object of static type object, object does not have an __int__ method, but t...
2
3
78,416,773
2024-5-2
https://stackoverflow.com/questions/78416773/how-do-i-use-python-logging-with-uvicorn-fastapi
Here is a small application that reproduces my problem: import fastapi import logging import loguru instance = fastapi.FastAPI() @instance.on_event("startup") async def startup_event(): logger = logging.getLogger("mylogger") logger.info("I expect this to log") loguru.logger.info("but only this logs") When I launch thi...
It's because the --log-level=debug only applies to uvicorn's logger, not your mylogger logger - whose level remains set at WARNING. If you add a line to the end of your script such as logging.basicConfig(level=logging.DEBUG, format="%(asctime)s | %(levelname)-8s | " "%(module)s:%(funcName)s:%(lineno)d - %(message)s") ...
2
3
78,418,960
2024-5-2
https://stackoverflow.com/questions/78418960/how-do-i-know-if-flag-was-passed-by-the-user-or-has-default-value
Sample code: import click @click.command @click.option('-f/-F', 'var', default=True) def main(var): click.echo(var) main() Inside main() function, how can I check if var parameter got True value by default, or it was passed by the user? What I want to achieve: I will have few flags. When the user does not pass any of ...
As I haven't really used click - maybe there's some functionality to handle this but as a workaround, I'd set the default value to None and check against if the value if its None when command is called. Something like this: import click @click.command @click.option('-f/-F', 'var', default=None) def main(var): if var is...
2
2
78,419,347
2024-5-2
https://stackoverflow.com/questions/78419347/iterate-over-the-next-12-months-from-today-using-python
I am trying to write python code that takes the first of the next month and creates a dataframe of the next 12 months. I have tried two ways to which did not work. I created a FOR LOOP but I am stuck on the fact that it does not store the range in the list. I got a Value Error: Month must be in 1..12 so I'm stuck as w...
If working with pandas.DataFrame, you mostly don't need for loops. Just do : import pandas as pd import datetime as dt from dateutil.relativedelta import relativedelta today = dt.date.today() first_day_next_month = (today.replace(day=1) + relativedelta(months=1)) first_day_next_12_months = [first_day_next_month + relat...
2
3
78,413,671
2024-5-1
https://stackoverflow.com/questions/78413671/duckdb-insert-the-hive-partitions-into-parquet-file
I have jsonl files partitioned by user_id, and report_date. I am converting these jsonl files into parquet files and save them in the same folder using the following commands in DuckDB jsonl_file_path ='/users/user_id=123/report_date=2024-04-30/data.jsonl' out_path = '/users/user_id=123/report_date=2024-04-30/data.parq...
If I understand correctly, you want to do a partitioned write and need to use PARTITION_BY. When doing a partitioned write, you should not include the hive partition as part of your output path. The partitioned write will build those paths and file names for the case where there are many files per partition. You can te...
2
2
78,419,061
2024-5-2
https://stackoverflow.com/questions/78419061/stable-icon-recognition-by-opencv-python
I have the following issue: I need to detect icons in an image reliably. The image also contains text, and the icons come in various sizes. Currently, I'm using Python with the cv2 library for this task. However, unfortunately, the current contour detection algorithm using cv2.findContours isn't very reliable. Here's h...
I think edge detection can work quite well here, I did a small example which worked for now: im = cv2.imread("logos.jpg") imGray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY) edges = cv2.Canny(imGray,5, 20) This gave the following result: After this, detecting contours and filtering by area will work quite nicely, as the sq...
2
2
78,417,247
2024-5-2
https://stackoverflow.com/questions/78417247/how-to-reverse-a-numpy-array-using-stride-tricks-as-strided
Is it possible to reverse an array using as_strided in NumPy? I tried the following and got garbage results Note : I am aware of indexing tricks like ::-1, but what to know if this can be achieved thru ax_strided. import numpy as np from numpy.lib.stride_tricks import as_strided elems = 16 inp_arr = np.arange(elems).as...
Indeed you can reverse an array using as_strided() (notwithstanding the question of whether you should); however, one has to get both the strides and the array offset correct: In the 1-dimensional case, one has to start from the last element and negate the stride (which, for an 8-bit/1-byte data type, is the same as ...
2
2
78,417,828
2024-5-2
https://stackoverflow.com/questions/78417828/are-there-good-reason-to-accept-float-but-not-int-in-a-function-in-python
In a big library, I had a 'bug' because a function which accept only float but not int def foo(penalty: float): if not isinstance(penalty, float): raise ValueError(f"`penalty` has to be a float, but is {penalty}") # some instruction I would like to open a PR with the following : def foo(penalty: int | float): if not i...
A few reasons might exist: Floats have methods that integers don't. For example the fromhex or hex methods exist on float objects, but not int objects. If the function makes use of such methods, accepting an int will cause it to fail. Sometimes, floats are specifically needed when dealing with foreign functions, for ...
2
4
78,416,528
2024-5-2
https://stackoverflow.com/questions/78416528/only-do-this-action-once-in-a-for-loop
I need to do this action once under certain conditions in a for loop to stop duplicates appearing in the checkboxes. Theoretically, this should work I believe but when the conditions are met for this if statement (cycles == 1 & len(tasks) > 1) it skips over the statement anyway which really confuses me. I have been try...
The issue lies in the way you're using the '&' operator. In Python '&' is a bitwise AND operator, not a logical AND operator. For logical AND, you should use 'and' So, instead of: if cycles == 1 & len(tasks) > 1: You should use: if cycles == 1 and len(tasks) > 1:
2
3
78,416,147
2024-5-1
https://stackoverflow.com/questions/78416147/changing-the-exception-type-in-a-context-manager
I currently have code that looks like this scattered throughout my codebase: try: something() except Exception as exc: raise SomethingError from exc I would like to write a context manager that would remove some of this boiler-plate: with ExceptionWrapper(SomethingError): something() It looks like it is possible to s...
This sort of simple context manager is easiest to implement using contextlib.contextmanager, which creates a context manager out of a generator. Simply wrap the first yield statement in the generator with a try block and raise the desired exception in the except block: import contextlib from typing import Iterator clas...
3
4
78,402,347
2024-4-29
https://stackoverflow.com/questions/78402347/pandera-errors-backendnotfounderror-with-pandas-dataframe
pandera: 0.18.3 pandas: 2.2.2 python: 3.9/3.11 Hi, I am unable to setup the pandera for pandas dataframe as it complains: File "/anaconda/envs/data_quality_env/lib/python3.9/site-packages/pandera/api/base/schema.py", line 96, in get_backend raise BackendNotFoundError( pandera.errors.BackendNotFoundError: Backend not f...
This can be solved by including a get_backend method in CaseSchema: import pandas as pd import pandera as pa from pandera.backends.pandas.container import DataFrameSchemaBackend class CaseSchema(pa.DataFrameSchema): case_id = pa.Column(pa.Int) @classmethod def get_backend(cls, check_obj=None, check_type=None): if check...
5
0
78,400,266
2024-4-29
https://stackoverflow.com/questions/78400266/python-rolling-indexing-in-polars-library
I'd like to ask around if anyone knows how to do rolling indexing in polars? I have personally tried a few solutions which did not work for me (I'll show them below): What I'd like to do: Indexing the number of occurrences within the past X days by Name Example: Let's say I'd like to index occurrences within the past 2...
You could start with the approach giving the maximum count for each group (using pl.len() within the aggregation) and post-process the Counter column to make it's values increase within each group. ( df .rolling(index_column="Date", period="2d", group_by="Name") .agg( pl.len().alias("Counter") ) .with_columns( (pl.col(...
4
3
78,382,516
2024-4-25
https://stackoverflow.com/questions/78382516/pyenv-switching-between-python-and-pyspark-versions-without-hardcoding-environ
I have trouble getting different versions of PySpark to work correctly on my windows machine in combination with different versions of Python installed via PyEnv. The setup: I installed pyenv and let it set the environment variables (PYENV, PYENV_HOME, PYENV_ROOT and the entry in PATH) I installed Amazon Coretto Java ...
I "solved" the issue by completely removing the Python path from the PATH environment variable and doing everything exclusively via pyenv. I suppose my original task is not possible. I can still start a Python process by running pyenv exec python in the terminal. But disappointingly I cannot launch a Spark process from...
3
0
78,396,068
2024-4-27
https://stackoverflow.com/questions/78396068/how-to-plot-shap-summary-plots-for-all-classes-in-multiclass-classification
I am using XGBoost with SHAP to analyze feature importance in a multiclass classification problem and need help plotting the SHAP summary plots for all classes at once. Currently, I can only generate plots one class at a time. SHAP version: 0.45.0 Python version: 3.10.12 Here is my code: import xgboost as xgb import s...
The issue is that explainer.shap_values(X_test) will return a 3D DataFrame of shape (rows, features, classes) and to show a bar plot summary_plot(shap_values) requires shap_values to be a list of (rows, features) where the list is: length = number of classes. For my own purposes, I used the following function which con...
3
5
78,379,820
2024-4-24
https://stackoverflow.com/questions/78379820/llm-studio-fail-to-download-model-with-error-unable-to-get-local-issuer-certif
In LLM studio, when I try to download any model, I am facing following error: Download Failed: unable to get local issuer certificate
I've experienced the same in a corporate network. To get around I have been manually downloading through my browser (the url is to the left of the error message in your screenshot) and manually loading the models into the appropriate dir: ~/.cache/lm-studio/models in the appropriate subpath. ie ~/.cache/lm-studio/model...
2
4
78,389,654
2024-4-26
https://stackoverflow.com/questions/78389654/exporting-pointset-unstructuredgrid-data-as-stl-file-from-pyvista
I am using pyvista to mesh 3D scan data of terrain and save them to stl files to save in blender. Some of the .xyz files contain data for a single continuous area while others include a number of smaller areas, with no data inbetwean. I have managed to get this to work for the continuous regions: import numpy as np imp...
Based on the input from Andras I used extract_surface() to extract the surface and save to stl file. import numpy as np import pyvista as pv xyz_path = r"Path_to_file.xyz" stl_path = r"Path_to_file.stlr" data = np.loadtxt(xyz_path) cloud = pv.PolyData(data) surf = cloud.delaunay_2d() cell_sizes = surf.compute_cell_size...
2
1
78,407,858
2024-4-30
https://stackoverflow.com/questions/78407858/how-do-i-create-a-constructor-that-would-receive-different-types-of-parameters
I have this Point class. I want it to be able to recieve double and SomeType parameters. Point.pxd: from libcpp.memory cimport shared_ptr, weak_ptr, make_shared from SomeType cimport _SomeType, SomeType cdef extern from "Point.h": cdef cppclass _Point: _Point(shared_ptr[double] x, shared_ptr[double] y) _Point(shared_pt...
In Cython, you cannot directly overload constructors (or any methods) as you might in C++ or other languages that support method overloading. However, you can achieve similar functionality by using factory methods or by using Python's flexibility with arguments. Given your scenario where the Point class needs to accept...
4
-1
78,382,641
2024-4-25
https://stackoverflow.com/questions/78382641/can-three-given-coordinates-be-points-of-a-rectangle
I am currently learning how to code in Python and I came across this task and I am trying to solve it. But I think I got a mistake somewhere and I was wondering can maybe someone help me with it. The task is to write a code that will: Import four 2D coordinates (A, B, C and X) from a text file Check can A, B, C be poin...
Let's look at the logic for your is_rectangle function. def is_rectangle(point1, point2, point3): distances = [ distance(point1, point2), distance(point2, point3), distance(point3, point1) ] distances.sort() if distances[0] == distances[1] and distances[1] != distances[2]: return True else: return False You are testin...
2
2
78,405,706
2024-4-30
https://stackoverflow.com/questions/78405706/auto-rescale-y-axis-for-range-slider-in-plotly-bar-graph-python
Is there a way to force the rangeslider in plotly to auto-rescale the y-axis? Manually selecting a date range with the DatePicker works fine as the y-axis automatically updates. However, when updating through the rangeslider, the y-axis doesn't auto-rescale. Without re-scaling, the figure is hard to interpret. It's alm...
You can achieve this using a clientside callback. The idea is the same as for Autorescaling y axis range when range slider used : we register a JS handler for the relayout event that will update the yaxis range according to the y data that are within the xaxis range. Add this to your current code : app.clientside_callb...
3
2
78,406,108
2024-4-30
https://stackoverflow.com/questions/78406108/update-dmc-slider-text-style-plotly-dash
How can the ticks be manipulated using dash mantine components? I've got a slider below, that alters the opacity of a bar graph. I know you can change the size and radius of the slider bar. But I want to change the fontsize, color of the xticks corresponding to the bar. You could use the following css with dcc.sliders ...
According to the Styles API, you can use the static selector .mantine-Slider-markLabel to customize the tick labels, but it seems there is no selector for the active tick specifically, so you would have to use a clientside callback to apply a custom class, say mantine-Slider-markLabel-active, to the active element when...
3
1
78,379,995
2024-4-24
https://stackoverflow.com/questions/78379995/creating-a-custom-colorbar-in-matplotlib
How can I create a colorbar in matplotlib that looks like this: Here is what I tried: import matplotlib.pyplot as plt from matplotlib.colors import LinearSegmentedColormap from matplotlib.cm import ScalarMappable from matplotlib.colors import Normalize # Define the custom colormap colors = ['red', 'cyan', 'darkgreen']...
One solution is to draw wide white edges around the color segments (using cb.solids.set below), hide the spines (cb.outline.set_visible) and draw vertical lines as dividers (cb.ax.axvline). To match the desired colorbar, make sure to pass a ymin that is greater than 0. import matplotlib.pyplot as plt from matplotlib.co...
2
3
78,411,087
2024-4-30
https://stackoverflow.com/questions/78411087/split-pandas-column-and-create-new-columns-that-has-the-count-of-those-split-val
I have an excel file in which one of the columns has multiple values seperated by a comma (please see the attached image) For the StuType column, the numbers go all the way from 1 to 13 including some blank rows (as can be seen in ResponseID = 8538 and 8562). I am reading the file into pandas. The goal is to have 13 d...
Edit: all credits to @mozway for the refactored solution (see this comment). Here's an approach with Series.str.get_dummies: df = ( df.join( df.pop('StuType') .str.get_dummies(sep=',') .rename(columns=int) .reindex(range(1, 14), axis=1, fill_value=0) ) ) Output Response 1 2 3 4 5 6 7 8 9 10 11 12 13 0 8524 0 0 0 0 1...
2
4
78,408,880
2024-4-30
https://stackoverflow.com/questions/78408880/how-to-perform-matthews-corrcoef-in-sklearn-simultaneously-for-every-column-usin
I want to perform Matthews correlation coefficient (MCC) in sklearn to find the correlation between different features (boolean vectors) in a 2D numpyarray. What I have done so far is to loop through each column and find correlation value between features one by one. Here is my code: from sklearn.metrics import matthew...
You can use numba to speed up the computing, e.g: import numba import numpy as np @numba.njit def _fill_cm(m, c1, c2): m[:] = 0 for a, b in zip(c1, c2): m[a, b] += 1 @numba.njit def mcc(confusion_matrix): # https://stackoverflow.com/a/56875660/992687 tp = confusion_matrix[0, 0] tn = confusion_matrix[1, 1] fp = confusio...
2
1
78,410,548
2024-4-30
https://stackoverflow.com/questions/78410548/polars-use-column-values-to-reference-other-column-in-when-then-expression
I have a Polars dataframe where I'd like to derive a new column using a when/then expression. The values of the new column should be taken from a different column in the same dataframe. However, the column from which to take the values differs from row to row. Here's a simple example: df = pl.DataFrame( { "frequency": ...
You could build the when/then in a loop: freq_refs = df.get_column("frequency_ref") expr = pl.when(False).then(None) # dummy starter value for c in freq_refs: expr = expr.when(pl.col("frequency_ref") == c).then(pl.col(c)) expr = expr.otherwise(0) # Apply the conditions to calculate res df = df.with_columns( pl.when(fix...
5
4
78,406,682
2024-4-30
https://stackoverflow.com/questions/78406682/dae-equation-system-solved-with-gekko-suddenly-not-working-anymore-error-messag
I have previously successfully solved a mechanical system using the gekko package. However, without having changed anything in my code, I now get the following error message: --------------------------------------------------------------------------- Exception Traceback (most recent call last) Cell In[3], line 15 13 m....
The public server is under significant load with ~315,000 downloads of the gekko package each month. I recommend switching to remote=False for a faster and more reliable response by solving locally instead of through the public server. m = GEKKO(remote=False) This may change the behavior because there are more solver ...
3
0
78,409,623
2024-4-30
https://stackoverflow.com/questions/78409623/pandas-divide-by-each-value-occurrence-in-one-column
I have a dataframe which contains a column labeled Pool. I want to create a new column labeled "Volume" which is 310 divided by the occurrence of each value of Pool. For example there are three occurrences of Pool 1 so 310/3 = 103.3. There are 4 occurrences of Pool 2 so 310/4 = 77.5 and so forth. Any ideas on how to do...
Use Series.map with Series.value_counts for counts per groups: df["Volume"] = 310 / df['Pool'].map(df['Pool'].value_counts()) #alternative with division from right side - rdiv #df["Volume"] = df['Pool'].map(df['Pool'].value_counts()).rdiv(310) Or GroupBy.transform: df["Volume"] = 310 / df.groupby('Pool')['Pool'].trans...
2
2
78,405,417
2024-4-29
https://stackoverflow.com/questions/78405417/changing-the-color-scheme-in-a-matplotlib-animated-gif
I'm trying to create an animated gif that takes a python graph in something like the plt.style.use('dark_background') (i.e black background with white text) and fades it to something like the default style (ie. white background with black text). The above is the result of running the below. You'll see that it doesn't ...
I couldn't figure out how to make the figure facecolor transition, but a workaround is to use a single subfigure, and adjust the facecolor of that. I also set the color properties directly on the artists rather than using rcParams as I think there is sometimes inconsistency about exactly when rcParams get applied (e.g....
2
2
78,407,270
2024-4-30
https://stackoverflow.com/questions/78407270/rendering-depth-from-mesh-and-camera-parameters
I want to render depth from mesh file, and camera parameters, to do so I tried RaycastingScene from open3d with this mesh file as follows: #!/usr/bin/env python3 import numpy as np import open3d as o3d import matplotlib.pyplot as plt def render_depth( intrins:o3d.core.Tensor, width:int, height:int, extrins:o3d.core.Ten...
The raycasting scene is working correctly. However, your extrinsic matrix is setting the camera inside the mesh and thus you are seeing how mesh looks from inside. I roughly measured the mesh bbq_sauce in meshlab and it is of width ~53 units. You can either move the camera away from the mesh, using either: extrens_[2, ...
2
1
78,407,769
2024-4-30
https://stackoverflow.com/questions/78407769/counting-values-of-columns-in-all-previous-rows-excluding-current-row
I'm currently learning Pandas and stuck with a problem. I have the following data: labels = [ 'date', 'name', 'opponent', 'gf', 'ga'] data = [ [ '2023-08-5', 'Liverpool', 'Man Utd', 5, 0 ], [ '2023-08-10', 'Liverpool', 'Everton', 0, 0 ], [ '2023-08-14', 'Liverpool', 'Tottenham', 3, 2 ], [ '2023-08-18', 'Liverpool', 'Ar...
You can shift with fill_value=0, then cumsum: df['total_gf'] = df['gf'].shift(fill_value=0).cumsum() df['total_ga'] = df['ga'].shift(fill_value=0).cumsum() Alternatively, processing all columns at once: df[['total_gf', 'total_ga']] = df[['gf', 'ga']].shift(fill_value=0).cumsum() Or, create a new DataFrame: out = df.j...
4
2
78,407,883
2024-4-30
https://stackoverflow.com/questions/78407883/add-column-with-a-count-of-other-columns-that-have-any-value-in
My data frame is similar to below: Name Col1 Col2 Col3 Col4 Col5 Col6 A Y Y Y B Y Y Y Y C Y Y Y D Y I want to add a column that counts the other columns containing a value similar to: Name Col1 Col2 Col3 Col4 Col5 Col6 Score A Y Y Y 3 B Y Y Y Y 4 C Y Y Y 3 D Y 1 I have tried the following but with no success: df['Sco...
If there are missing values use DataFrame.count with subset of columns: df['Score'] = df[['Col1','Col2','Col3','Col4','Col5','Col6']].count(axis=1) print (df) Name Col1 Col2 Col3 Col4 Col5 Col6 Score 0 A Y Y NaN Y NaN NaN 3 1 B Y NaN Y Y NaN Y 4 2 C NaN Y Y NaN Y NaN 3 3 D Y NaN NaN NaN NaN NaN 1
2
4
78,406,587
2024-4-30
https://stackoverflow.com/questions/78406587/geodataframe-conversion-to-polars-with-from-pandas-fails-with-arrowtypeerror-di
I try to convert a GeoDataFrame to a polars DataFrame with from_pandas. I receive an ArrowTypeError: Did not pass numpy.dtype object exception. So I can continue working against the polars API. Expected outcome would be a polars DataFrame with the geometry column being typed as pl.Object. I'm aware of https://github.co...
You could drop the geometry before making the polars dataframe from_pandas, then assign it later as a new column : out = ( pl.from_pandas(gdf.drop(columns=["geometry"])) .with_columns(pl.Series("geometry", gdf["geometry"].tolist())) ) Output : ┌──────────┬───────────────┬───────────────┬────────────┬──────────────────...
2
1
78,406,864
2024-4-30
https://stackoverflow.com/questions/78406864/how-to-do-groupby-on-multi-index-dataframe-based-on-condition
I have a multi index dataframe, and I want to combine rows based on certain conditions and I want to combine rows per index. import pandas as pd # data data = { 'date': ['01/01/17', '02/01/17', '03/01/17', '01/01/17', '02/01/17', '03/01/17'], 'language': ['python', 'python', 'python', 'r', 'r', 'r'], 'ex_complete': [6,...
IIUC use DataFrame.rename with aggregate, e.g. sum: out = (df_from_json.rename({pd.Timestamp('01/01/17'):'1_2', pd.Timestamp('02/01/17'):'1_2'}, level=0) .groupby(level=[0,1]).sum()) print (out) ex_complete date language 2017-03-01 00:00:00 python 10 r 8 1_2 python 11 r 16 out = (df_from_json.rename({'python':'Python...
2
1
78,405,685
2024-4-30
https://stackoverflow.com/questions/78405685/find-the-next-value-the-actual-value-plus-50-using-polars
I have the following dataframe: df = pl.DataFrame({ "Column A": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], "Column B": [2, 3, 1, 4, 1, 7, 3, 2, 12, 0] }) I want to create a new column C that holds the distance, in rows, between the B value of the current row and the next value in column B that is greater than or equal to B + 5...
Ok, so first I should say - this one looks like it requires join on inequality on multiple columns and from what I've found pure polars is not great with it. It's probably possible to do it with join_asof but I couldn't make it pretty. I'd probably use duckdb integration with polars to achieve the results: import duckd...
5
2