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
77,566,724
2023-11-28
https://stackoverflow.com/questions/77566724/handle-circular-import-of-subclasses-types-in-abstract-class
I am facing a circular import error when I define type aliases for the subclasses of an abstract class. This is an example of what I'm trying to achieve: #abstract_file_builder.py from abc import ABC, abstractmethod from typing import Generic, MutableSequence, TypeVar from mymodule.type_a_file_builder import TypeARow f...
By placing the following line in your abstract class you kind of add information of your concrete subclasses to your abstract class: GenericRow = TypeVar("GenericRow", TypeARow, TypeBRow) That doesn't look right to me. I think you should rather remove this dependency, because in consequence it would mean, that you pot...
2
2
77,566,151
2023-11-28
https://stackoverflow.com/questions/77566151/pymunk-body-object-being-problematic
I am using this video tutorial: Video I am making a ball (with 0 mass at the moment) in pymunk and trying to show it on pygame but it is not working I tried doing this to make a ball in pymunk and pygame and I was expecting a ball with no movement(I will make it move later on): import pymunk import pygame pygame.init()...
When creating the body, you must specify a mass and a moment not equal to 0 (see pymunk.Body): body = pymunk.Body() body = pymunk.Body(1, 1) In addition, pygame.disaply.flip() is missing after drawing the objects in the scene and if the body should fall, you must also specify the gravity (e.g. space.gravity = (0, 100)...
2
2
77,559,175
2023-11-27
https://stackoverflow.com/questions/77559175/how-can-i-change-the-size-of-a-checkbox-in-pysimplegui
I made some checkboxes with PySimpleGUI like so: import PySimpleGUI as sg WINDOW_SIZE = (1280, 710) CHECKBOX_SIZE = (1000, 40) sg.theme('Dark Blue 3') indicator_column = [ [sg.Checkbox("First", size=CHECKBOX_SIZE)], [sg.Checkbox("Second")], # in the actual code there are more checkboxes ] layout = [ [sg.Column(indicato...
You'll find one solution posted on Trinket where you can execute it. It's based on a PySimpleGUI Demo Program, also posted in the PSG Repo and in the psgdemos PyPI release. Like the normal Checkbox Element, you can click the box or the text next to it. This bit of code also flips the text, something not normally done s...
2
1
77,557,429
2023-11-27
https://stackoverflow.com/questions/77557429/validate-a-function-call-without-calling-a-function
I'd like to know if I can use pydantic to check whether arguments would be fit for calling a type hinted function, but without calling the function. For example, given kwargs = {'x': 1, 'y': 'hi'} def foo(x: int, y: str, z: Optional[list] = None): pass I want to check whether foo(**kwargs) would be fine according to t...
You can extract the annotations attribute from the function and use it to build a pydantic model using the type constructor: def form_validator_model(func: collections.abc.Callable) -> type[pydantic.BaseModel]: ann = func.__annotations__.copy() ann.pop('return', None) # Remove the return value annotation if it exists. ...
4
4
77,564,964
2023-11-28
https://stackoverflow.com/questions/77564964/checking-if-a-tensors-values-are-contained-in-another-tensor
I have a torch tensor like so: a=[1, 234, 54, 6543, 55, 776] and other tensors like so: b=[234, 54] c=[55, 776] I want to create a new mask tensor where the values of a will be true if there is another tensor (b or c) are equal to it. For example, in the tensors we have above I would like to create the following mask...
Based on the answers to on the PyTorch forum here, you could explicitly use a for loop, e.g., import torch a = torch.tensor([1, 234, 54, 6543, 55, 776]) b = torch.tensor([234, 54]) c = torch.tensor([55, 776]) a_masked = sum(a == i for i in b).bool() + sum(a == i for i in c).bool() print(a_masked) tensor([False, True, T...
2
2
77,541,498
2023-11-24
https://stackoverflow.com/questions/77541498/applying-python-udf-function-per-row-in-a-polars-dataframe-throws-unexpected-exc
I have the following polars DF in Python df = pl.DataFrame({ "user_movies": [[7064, 7153, 78009], [6, 7, 1042], [99, 110, 3927], [2, 11, 152081], [260, 318, 195627]], "user_ratings": [[5.0, 5.0, 5.0], [4.0, 2.0, 4.0], [4.0, 4.0, 3.0], [3.5, 3.0, 4.0], [1.0, 4.5, 0.5]], "common_movies": [[7064, 7153], [7], [110, 3927], ...
What went wrong with your approach Ignoring performance penalties for python UDFs, there are two things that went wrong in your approach. apply which is now map_rows in the context that you're trying to use it is expecting the output to be a tuple where each element of the tuple is an output column. Your function does...
4
5
77,564,682
2023-11-28
https://stackoverflow.com/questions/77564682/pandas-groupby-transform-with-custom-condition
Suppose I have the following table: import pandas as pd data = pd.DataFrame({ 'Group':['A','A','A','A','B','B'] , 'Month':[1,2,3,4,1,2] , 'Value':[100,300,700,750, 200,400] }) I would like to use groupby and transform functions in pandas to create a new column that is equal to the value of each group in month 2. Here...
Use Series.map with filtered rows in boolean indexing: s = data[data['Month'].eq(2)].set_index('Group')['Value'] data['Desired_Result'] = data['Group'].map(s) print (data) Group Month Value Desired_Result 0 A 1 100 300 1 A 2 300 300 2 A 3 700 300 3 A 4 750 300 4 B 1 200 400 5 B 2 400 400 With GroupBy.transform is poss...
3
6
77,547,060
2023-11-25
https://stackoverflow.com/questions/77547060/fail-to-start-flask-connexion-swagger
Problem I initiated a Flask app (+ Connexion and Swagger UI) and tried to open http://127.0.0.1:5000/api/ui. The browser showed starlette.exceptions.HTTPException: 404: The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again. Setup % pip install "connexion...
TL:DR: You need an ASGI server to run your application. A similar problem on the connexion github issue tracker. This will only lead you to the documentation on running your application which can be found here. Bearing the above in mind, I managed to create my own solution: __init__.py: from connexion import FlaskApp d...
3
2
77,561,415
2023-11-28
https://stackoverflow.com/questions/77561415/how-to-include-a-text-summary-within-a-printed-table
Say I have two dataframes: data1 = { 'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 30, 35], 'Height': [165, 182, 177] } df1 = pd.DataFrame(data1) data2 = { 'Summary': ["Alice is the youngest", "Bob is the tallest"] } df2 = pd.DataFrame(data2) Is there a way I could vertically concatenate the two dfs in such a way: ...
You can use tabulate and post-process the outputs: import tabulate as t t.PRESERVE_WHITESPACE = True width1 = 10 width2 = width1 * df1.shape[1] + df1.shape[1]*2 str1 = t.tabulate(df1.applymap(f'{{:^{width1}}}'.format), list(df1), tablefmt='outline', stralign='center', numalign='center') str2 = t.tabulate(df2.applymap(f...
3
1
77,534,017
2023-11-23
https://stackoverflow.com/questions/77534017/pythons-built-in-sum-function-taking-forever-to-compute-sums-of-very-large-rang
This works well and returns 249999500000: sum([x for x in range(1_000_000) if x%2==0]) This is slower but still returns 24999995000000: sum([x for x in range(10_000_000) if x%2==0]) However, larger range of values such as 1_000_000_000 takes a very long time to compute. In fact, this returns an error: sum([x for x in...
After I posted the below code based on the Gauss Sum, Kelly Bundy pointed out a simplification of the math and a practical simplification making use of properties of a range object. He suggested I add this here. An arbitrary range can be visualized as a trapezoid. That there is the sum for the area of a trapezoid. It a...
2
2
77,562,118
2023-11-28
https://stackoverflow.com/questions/77562118/how-to-calculate-time-between-rows-for-each-id-in-a-pandas-dataframe-using-polar
I am working on a task where I have a Pandas DataFrame using Polars library in Python, containing columns for 'ID' and 'Timestamp'. Each row represents the end of a session identified by the 'Timestamp'. I am trying to create a new column called 'time_since_last_session', which should contain the time duration between ...
You can group by ID and then apply the rolling diff to each group: df.group_by("ID").map_groups( lambda g: g.with_columns( pl.col("Timestamp").diff().dt.total_seconds().fill_null(0).alias("Diff") ) )
3
-2
77,561,341
2023-11-28
https://stackoverflow.com/questions/77561341/getting-gps-boundaries-for-each-hexbin-in-a-python-plotly-hexbin-mapbox-heat-m
I have created a hexbin "heat map" in Python using plotly by mapping a number of locations (using GPS latitude / longitude), along with the value of each location. See code below for sample df and hexbin figure plot. Data Desired When I mouse-over each hexbin, I can see the average value contained within that hexbin. B...
You can extract the coordinates of the six corners of each hexbin as well as the values from fig.data[0]. However, I am not sure where the centroids information is stored in the figure object, but we can create a geopandas dataframe from this data, and get the directly get the centroids attribute of the geometry column...
2
2
77,550,969
2023-11-26
https://stackoverflow.com/questions/77550969/weighted-sum-of-pytrees-in-jax
I have a pytree represented by a list of lists holding parameter tuples. The sub-lists all have the same structure (see example). Now I would like to create a weighted sum so that the resulting pytree has the same structure as one of the sub-lists. The weights for each sub-list are stored in a separate array / list. So...
I think this will do what you have in mind: def wsum(*args, weights=weights): return jnp.asarray(weights) @ jnp.asarray(args) reduced = jax.tree_util.tree_map(wsum, *pytree) For the edited question, where tree elements have more general shapes, you can define wsum like this instead: def wsum(*args, weights=weights): r...
2
2
77,559,112
2023-11-27
https://stackoverflow.com/questions/77559112/django-duplicate-action-when-i-press-follow-or-unfollow-button
I am doing CS50w project4 problem, so I have to build a Social Media app. This problem has a part where in the profile of the user a follow and unfollow button has to be available. My problem is when I press the follow or unfollow button, this increase or decrease the followers and the people that the user follow. view...
The main problem is that you wrote symmetrical='false' as a string literal, and the truthiness of that string is, well, True. You should use the False constant, so symmetrical=False. But you are overcomplicating things. Django is perfectly capable to handle a ManyToManyField [Django-doc] in the two directions. Indeed, ...
2
2
77,558,127
2023-11-27
https://stackoverflow.com/questions/77558127/pyspark-foreachpartition-with-additional-parameters
I'm trying to execute my function using spark_df.foreachPartition(), and I want to pass additional parameter but apparently the function supports only one parameter (the partition). I tried to play with it and do something like this : def my_function(row, index_name) : return True def partition_func(row): return my_fun...
There might be other ways, but one simple approach could be to create a broadcast variable (or a container that holds any variables you may need), and then pass it to be used in your foreachPartition function. Something like this: def partition_func_with_var(partition, broadcast_var): for row in partition: print(str(br...
2
2
77,558,347
2023-11-27
https://stackoverflow.com/questions/77558347/use-python-to-calculate-timing-between-bus-stops
The following is an example of the .csv file of thousands of lines I have for the different bus lines. Table: trip_id arrival_time departure_time stop_id stop_sequence stop_headsign 107_1_D_1 6:40:00 6:40:00 AREI2 1 107_1_D_1 6:40:32 6:40:32 JD4 2 107_1_D_1 6:41:27 6:41:27 PNG4 3 Raw Data: trip_id,ar...
I think in such cases you can use shift. Here is an example: df = pd.read_csv('...') result = pd.DataFrame() for _, trip_df in df.groupby('trip_id', sort=False): # type: str, pd.DataFrame trip_df = trip_df.sort_values('stop_sequence') trip_df['arrival_time'] = pd.to_timedelta(trip_df['arrival_time']) trip_df['departure...
2
2
77,558,059
2023-11-27
https://stackoverflow.com/questions/77558059/how-to-check-if-a-path-is-a-relative-symlink-in-python
os package has os.path.islink(path) to check if path is a symlink. How do I determine if a file located at path is a relative symlink? Note that path can be an absolute path (i.e. path == os.path.abspath(path)), e.g. /home/user/symlink that is a relative symlink to ../ which is relative. As opposed to a link to /home/u...
I think you just have to read the actual target pathname and check it. def isrellink(path): return os.path.islink(path) and not os.path.isabs(os.readlink(path))
2
2
77,549,662
2023-11-25
https://stackoverflow.com/questions/77549662/python-grpc-set-timeout-per-one-attempt
I wrote something like this: settings = { 'methodConfig': [ { 'name': [{}], 'timeout': '0.5s', 'retryPolicy': { 'maxAttempts': 5, 'initialBackoff': '0.1s', 'maxBackoff': '2s', 'backoffMultiplier': 2, 'retryableStatusCodes': [ 'UNAVAILABLE', 'INTERNAL', 'DEADLINE_EXCEEDED', ], }, }, ], } settings_as_json_string = json.d...
There is no per-attempt timeout in the design of the retry functionality in gRPC. The general theory is that any attempt could succeed, and artificially cutting an attempt off early only reduces the chances of achieving any success at all.
2
3
77,556,822
2023-11-27
https://stackoverflow.com/questions/77556822/how-to-ascribe-the-value-count-of-a-list-item-to-a-new-column-pandas
Imagine that I have a dataset df with one column containing a dictionary with two list types (list_A and list_B) as value: data = [{"list_A": [2.93, 4.18, 4.18, None, 1.57, 1.57, 3.92, 6.27, 2.09, 3.14, 0.42, 2.09], "list_B": [820, 3552, 7936, None, 2514, 4035, 6441, 15379, 2167, 6147, 3322, 1177]}, {"list_A": [2.51, 3...
Use list comprehension for get first values of list_A, test non missing values by notna and count Trues by sum: df['count_first_item'] = [pd.notna([y['list_A'][0] for y in x]).sum() for x in df['column_dic']] print (df) column_dic count_first_item 0 [{'list_A': [2.93, 4.18, 4.18, None, 1.57, 1.5... 2 Or use Series.exp...
2
2
77,554,214
2023-11-27
https://stackoverflow.com/questions/77554214/transpose-df-columns-based-on-the-column-names-in-pandas
I have a pandas dataframe as below and I would like to transpose the df based on the column Names I want transpose all the coumns that has _1,_2,_3 & _4. I have 100+ Values in my df, Below is the example data. import pandas as pd data = { # One Id Column 'id':[1], #Other columns 'c1':['1c'], 'c2':['2c'], 'c3':['3c'], ...
You can first reshape with wide_to_long, then melt: standard_cols = ['id','c1','c2','c3'] value_cols = ['V1','S1'] result_cols = ['OC','GC','PF'] result_cols = [c.lower() for c in result_cols] out = (pd .wide_to_long( df, i=standard_cols, stubnames=result_cols+value_cols, j='j', sep='_') .reset_index() .melt(standard_c...
2
5
77,539,458
2023-11-23
https://stackoverflow.com/questions/77539458/using-pytest-and-hypothesis-how-can-i-make-a-test-immediately-return-after-disc
I'm developing a library, and I'm using hypothesis to test it. I usually sketch out a (buggy) implementation of a function, implement tests, then iterate by fixing errors and running tests. Usually these errors are very simple (e.g., a typo), and I don't need simplified test cases to figure out the issue. For example: ...
Building on my comment from earlier - did you look at this? https://hypothesis.readthedocs.io/en/latest/settings.html#hypothesis.settings.phases Looks like there's some support for having different "Setting Profiles". I bet you could have one where you eliminate the Shrinking phase. Maybe that's the way to do. Yeah! Th...
2
3
77,548,545
2023-11-25
https://stackoverflow.com/questions/77548545/adding-subttiles-to-plotly-dash-video-player-in-python
I am trying to add subtitles to my Plotly Dash video player, i.e. VTT captions overlay, in Python. I cannot find any examples or instruction on this. from dash import Dash, dcc, html, Input, Output, State import dash_player And in a html Div somewhere: dash_player.DashPlayer( id='vid1', controls = True, url = "http://...
My strategy in the end was to create a div ('subtitle-container') as a sibling to the DashPlayer in the layout: dash_player.DashPlayer( id='vid', controls = True, url = None, style={'margin-top':'20px','margin-bottom':'20px', 'margin-left':'10px'}, playing= False, muted= False ), html.Div( id='subtitle-container', chil...
3
2
77,539,758
2023-11-23
https://stackoverflow.com/questions/77539758/asyncio-bufferedprotocol-doesnt-do-what-it-says-in-the-documentation-doesnt-a
According to the documentation: "BufferedProtocol implementations allow explicit manual allocation and control of the receive buffer. Event loops can then use the buffer provided by the protocol to avoid unnecessary data copies. This can result in noticeable performance improvement for protocols that receive big amount...
After spending a lot of time reading through the asyncio code and related issues I think I can at least partially answer the question myself, although I would still appreciate anyone smarter than me chiming in and elaborating or correcting me if I'm wrong: The issue: There is an issued with the WSARecv() Windows functi...
3
1
77,552,595
2023-11-26
https://stackoverflow.com/questions/77552595/regex-find-words-that-have-a-o-in-second-position-and-end-in-ions
The other day, I was trying to teach the principles of Regex to a student - I am far from an expert but wanted to show the principles of it. I have a text file containing all the words of the English language, and I wanted to define a series of rules in regex so that the only word that would come out would be "CONGRATU...
Short answer is: ^([A-Z]O[A-Z]*)?IONS$ Explanation: Using Venn diagram. Rule 1: words with O as second letter ^.O or `^.O.*$ Rule 2: words that ends with IONS IONS$ or `^.*IONS$ In the intersection of Rule 1 & 2 (there are 3 2 disjoint cases): case 1 the shortest word is the word IONS, None for 5 letters, second ...
2
2
77,548,225
2023-11-25
https://stackoverflow.com/questions/77548225/reduce-list-of-lists-in-jax
I have a list holding many lists of the same structure (Usually, there are much more than two sub-lists inside the list, the example shows two lists for the sake of simplicity). I would like to create the sum or product over all sub-lists so that the resulting list has the same structure as one of the sub-lists. So far...
You can do this with tree_map of a sum over the splatted list: reduced = jax.tree_util.tree_map(lambda *args: sum(args), *list_of_lists) print(reduced) [[Array([8], dtype=int32), Array([10, 12], dtype=int32)], [Array([14], dtype=int32), Array([16, 18], dtype=int32)]]
2
2
77,544,934
2023-11-24
https://stackoverflow.com/questions/77544934/why-do-i-need-the-chromedriver-in-selenium
I have following code: from selenium import webdriver driver = webdriver.Chrome() driver.get("https://google.com") This code works well except that it is really slow. I don´t use the ChromeDriver. Just the normal Chrome Browser on my Mac. Why do I have to download the ChromeDriver? It doesn´t speed up the code executi...
Your code is perfectly fine. selenium version > 4.12.0 There is no need to download the chromedriver manually, Selenium's new in-built tool Selenium Manager will automatically download and manage the drivers for you. https://www.selenium.dev/documentation/selenium_manager/ https://www.selenium.dev/blog/2023/status_of_s...
3
4
77,544,480
2023-11-24
https://stackoverflow.com/questions/77544480/understanding-memory-leak-with-c-extension-for-python
I have been struggling to understand what I am doing wrong with the memory management of this this C++ function for a python module, but I don't have much experience in this regard. Every time I run this function, the memory consumption of the python interpreter increases. The function is supposed to take in two numpy ...
Py_XINCREF(x_obj) is not needed because Py_BuildValue("O", x_obj) will increment the reference count for you. In other words, you're accidentally increasing the reference count too much by 1
2
2
77,543,244
2023-11-24
https://stackoverflow.com/questions/77543244/logarithm-of-a-positive-number-result-in-minus-infinity-python
I have this image: HI00008918.png I want to apply a logarithmic function (f(x) = (1/a)*log(x + 1), where a = 0.01) on the image... So this is the code: import numpy as np import matplotlib.pyplot as plt import skimage.io as io car = io.imread('HI00008918.png') # plt.imshow(car, cmap='gray', vmin=0, vmax=255) a = 0.01 f...
It looks like np.log(x + 1) gives -Inf only where x is 255 in an array. Because the array x is uint8, adding 1 to 255 causes overflow, which wraps the result yielding 0. The log of 0 is -Inf. You might want to cast the image to a floating-point type before applying the function: carLog = fnLog(car.astype(np.float32)) ...
2
3
77,537,125
2023-11-23
https://stackoverflow.com/questions/77537125/asan-memory-leaks-in-embedded-python-interpreter-in-c
Address Sanitizer is reporting a memory leak (multiple actually) originating from an embedded python interpreter when testing some python code exposed to c++ using pybind11. I have distilled the code down to nothing other than calling PyInitialize_Ex and then PyFinalizeEx #include <Python.h> int main() { Py_InitializeE...
Py_Initialize has a long lasting known issue, whose origin is in C source codes. For C++ programmers I recommend boost.python as a replacement that uses C++ features to simplify interoperability between the 2 languages.
4
1
77,542,762
2023-11-24
https://stackoverflow.com/questions/77542762/in-python-typing-is-there-a-way-to-specify-combinations-of-allowed-generic-types
I have a pretty small but versatile (maybe too much) class in Python that effectively has two generic types that are constrained together. My code (yet poorly typed) code should show my intent: class ApplyTo: def __init__( self, *transforms: Callable[..., Any], to: Any | Sequence[Any], dispatch: Literal['separate', 'jo...
You can replace the union of MutableMapping and MutableSequence with a Protocol: import typing DispatchType = typing.Literal['separate', 'joint'] # `P` must be declared with `contravariant=True`, otherwise it errors with # 'Invariant type variable "P" used in protocol where contravariant one is expected' K = typing.Typ...
3
2
77,541,867
2023-11-24
https://stackoverflow.com/questions/77541867/class-type-of-class-that-was-created-with-metaclass
class Meta(type): def __new__(cls, name, bases, dct): new_class = type(name, bases, dct) new_class.attr = 100 # add some to class return new_class class WithAttr(metaclass=Meta): pass print(type(WithAttr)) # <class 'type'> Why does it print <class 'type'>, but not <class '__main__.Meta'> Am I right that class WithAttr...
This is because you're making an explicit call to type(name, bases, dct), which in turn calls type.__new__(type, name, bases, dct), with the type class passed as the first argument to the type.__new__ method, effectively constructing an instance of type rather than Meta. You can instead call type.__new__(cls, name, bas...
3
5
77,542,112
2023-11-24
https://stackoverflow.com/questions/77542112/vectorized-lookup-in-dataframe-using-numpy-array
Given a numpy array such as the one below, is it possible to use vectorization to return the associated value in column HHt without using a for loop? ex_arr = [2643, 2644, 2647] for i in ex_arr: h_p = df.at[i, "HHt"] Example df: HHt 2643 1 2644 2 2645 3 2646 4 2647 5 2648 6 2649 7 2650 8 Exp...
Use DataFrame.loc, if need list or array add Series.to_list or Series.to_numpy: print (df.loc[ex_arr,'HHt'].to_list()) [1, 2, 5] print (df.loc[ex_arr,'HHt'].to_numpy()) [1 2 5]
2
3
77,539,424
2023-11-23
https://stackoverflow.com/questions/77539424/breadth-first-search-bfs-in-python-for-path-traversed-and-shortest-path-taken
I tried implementing a bread-first search algorithm a lot, but I just don't get it right. The start node is S and the goal node is J. I'm just not getting J at all. This is the code that I'm using for printing the path being traversed, but I also need to find the shortest path: graph = { 'S' : ['A','B', 'C'], 'A' : ['...
You'd need to tell your BFS function what your target node is, so that the BFS traversal can stop as soon as that target node is encountered. Some other comments: Your dict literal has a duplicate key 'J' — you should remove it. visited and queue only serve a single BFS call, and should start from scratch each time a...
3
3
77,541,316
2023-11-24
https://stackoverflow.com/questions/77541316/duckdb-how-to-iterate-over-the-result-returned-from-duckdb-sql-command
Using DuckDB Python client, I want to iterate over the results returned from query like import duckdb employees = duckdb.sql("select * from 'employees.csv' ") Using type(employees) returns 'duckdb.duckdb.DuckDBPyRelation'. I'm able to get the number of rows with len(employees), however for-loop iteration seems to not ...
Apparently, from DuckDB API, something like the following should work. I unfortunately cannot test it because DuckDB's package won't install for whatever reason. I hope this helps you get in the right path to finding your answer. import duckdb employees = duckdb.sql("select * from 'employees.csv'") rows = employees.fe...
2
3
77,528,356
2023-11-22
https://stackoverflow.com/questions/77528356/gpiod-is-not-a-package
I'm trying to use libgpiod in python on my orangepi model 4B. I installed it with: sudo apt install libgpiod-dev python3-libgpiod Now I try to use it: from gpiod.line import Direction, Value But I get an error: ModuleNotFoundError: No module named 'gpiod.line'; 'gpiod' is not a package If I open python in terminal a...
libgpiod-dev includes the the libgpiod C lib and its header files, while python3-libgpiod includes the Python bindings to that lib. So with the command: sudo apt istall libgpiod-dev python3-libgpiod You're installing the libgpiod lib, C headers and python bindings. This lib is an abstraction layer to use gpio char dev...
2
3
77,537,779
2023-11-23
https://stackoverflow.com/questions/77537779/how-do-i-use-pip-pipx-and-virtualenv-of-the-current-python-version-after-upgrad
This is the first time I am upgrading python (from 3.11.3 to 3.12.0) and some questions came up along the way. I think I have somehow understood how Path works on windows, but am not getting the complete picture right now. At the moment I have the issue, that python and pip still by default use the old python installat...
Through a lot of trial and error I figured it out, maybe it helps some people: How do I use the correct version of pip? In my case, I needed to remove python 3.9 and 3.11 (especially the Scripts folder, that is where pip.exe is located) from the system path. I also removed 3.11/Scripts from user path. For my terminal t...
2
3
77,536,610
2023-11-23
https://stackoverflow.com/questions/77536610/filling-nulls-after-merge-but-only-to-the-newly-merged-columns
I have two dataframes that I am merging: import pandas as pd df = pd.DataFrame({'ID': [1,2,3,4], 'Column A': [2, 3, 2, 3], 'Column B': [None, None, 3, None]}) df2 = pd.DataFrame({'ID': [1,2,4], 'Column C': [2, 3, 22]}) df = df.merge(df2, on='ID', how='left') df The output is: ID Column A Column B Column C 0 1 2 NaN 2...
You can use the IDs to generate a mask for boolean indexing: out = df.merge(df2, on='ID', how='left') m = ~df['ID'].isin(df2['ID']) out[m] = out[m].fillna(0) Alternatively, reindex and concat: out = pd.concat([df.set_index('ID'), df2.set_index('ID') .reindex(df['ID'], fill_value=0)], axis=1) Another (not as nice) opt...
3
3
77,532,558
2023-11-22
https://stackoverflow.com/questions/77532558/size-of-image-stream-in-opencv-for-python
In Python 3.7 I read an png image with opencv and convert it to an jpg image stream. How can I determine the number of bytes of the stream? image=cv2.imread('test.png',0) image_stream = io.BytesIO(cv2.imencode(".jpg",image)[1].tobytes())
(success, data) = cv2.imencode(".jpg", image) assert success print(data.nbytes) This number of bytes is identical to the size of the bytes object returned by the .tobytes() call. Creating a BytesIO() also does not affect this size.
3
4
77,531,213
2023-11-22
https://stackoverflow.com/questions/77531213/convert-pandas-column-names-from-snake-case-to-camel-case
I have a pandas dataframe where the column names are capital and snake case. I want to convert them into camel case with first world starting letter to be lower case. The following code is not working for me. Please let me know how to fix this. import pandas as pd # Sample DataFrame with column names data = {'RID': [1,...
You could use a regex to replace _x by _X: df.columns = (df.columns.str.lower() .str.replace('_(.)', lambda x: x.group(1).upper(), regex=True) ) Or with a custom function: def to_camel(s): l = s.lower().split('_') l[1:] = [x.capitalize() for x in l[1:]] return ''.join(l) df = df.rename(columns=to_camel) Output: rid ...
3
3
77,528,415
2023-11-22
https://stackoverflow.com/questions/77528415/how-to-join-two-dataframes-for-which-column-values-are-within-a-certain-range-an
I have been reading this other post, since I am dealing with a similar situation. However, I have a problem. In my version of df_1, I have timestamps which are outside of the values of the time ranges presented in df_2. Let's say I have an extra row print df_1 timestamp A B 0 2016-05-14 10:54:33 0.020228 0.026572 1 201...
I would use janitor's conditional_join that enables a left join easily and much more efficiently than using apply: import janitor out = df_1.conditional_join(df_2, ('timestamp', 'start', '>='), ('timestamp', 'end', '<='), right_columns=['event'], how='left') Or, if your intervals are non-overlapping and you expect a s...
3
2
77,527,951
2023-11-22
https://stackoverflow.com/questions/77527951/how-to-cancel-tasks-in-anyio-taskgroup-context
I write a script to find out the fastest one in a list of cdn hosts: #!/usr/bin/env python3.11 import time from contextlib import contextmanager from enum import StrEnum import anyio import httpx @contextmanager def timeit(msg: str): start = time.time() yield cost = time.time() - start print(msg, f"{cost = }") class Cd...
You can call the cancel method of the cancel_scope attribute of the task group to cancel all of its tasks: async with anyio.create_task_group() as tg: ... tg.cancel_scope.cancel()
2
2
77,527,874
2023-11-22
https://stackoverflow.com/questions/77527874/how-can-i-add-the-x-or-y-value-from-a-line-above-without-reading-lines-not-c
So i a .csv that has a simplified machine programm that looks like this: X51.972,Y1433.401 LASER_ON X41.972 Y1438.401 X51.97 LASER_OFF X51.972,Y1382.401 LASER_ON X41.972 Y1377.401 X51.97 When there is only an X value, I want to write the Y value from the line above next to the X value and when there is only a Y value ...
The key is that you have to track the last values of X and Y. If there's a LASER line, you leave those two values alone but save the record. Also, you can't really use the CSV module to write the data if the lines are variable in length. output_csv_file = 'x.csv' lines = [] X = 'X0' Y = 'Y0' with open(output_csv_file) ...
2
2
77,507,520
2023-11-18
https://stackoverflow.com/questions/77507520/cannot-import-name-langchainembedding-from-llama-index
I'm trying to build a simple RAG, and I'm stuck at this code: from langchain.embeddings.huggingface import HuggingFaceEmbeddings from llama_index import LangchainEmbedding, ServiceContext embed_model = LangchainEmbedding( HuggingFaceEmbeddings(model_name="thenlper/gte-large") ) service_context = ServiceContext.from_def...
INFO 2024: This answer worked in 2023 when question was asked but it seems they moved all code and now you have to use other answers. Not from llama_index import LangchainEmbedding but from llama_index.embeddings import LangchainEmbedding (See source code for llama_index/embeddings/__ init__.py)
3
10
77,519,206
2023-11-20
https://stackoverflow.com/questions/77519206/polars-equivalent-to-pandas-min-count-on-groupby
I'm trying to find the equivalent of a min_count param on polars groupby, such as in pandas.groupby(key).sum(min_count=N). Let's suppose the dataframe df = pl.from_repr(""" ┌───────┬───────┐ │ fruit ┆ price │ │ --- ┆ --- │ │ str ┆ i64 │ ╞═══════╪═══════╡ │ a ┆ 1 │ │ a ┆ 3 │ │ a ┆ 5 │ │ b ┆ 10 │ │ b ┆ 10 │ │ b ┆ 10 │ │ ...
I don't think there's a built-in min_count for this, but you can just filter: ( df.group_by("fruit") .agg(pl.col("price").sum(), pl.len()) .filter(pl.col("len") >= 4) .drop("len") ) shape: (1, 2) ┌───────┬───────┐ │ fruit ┆ price │ │ --- ┆ --- │ │ str ┆ i64 │ ╞═══════╪═══════╡ │ b ┆ 50 │ └───────┴───────┘
4
5
77,494,964
2023-11-16
https://stackoverflow.com/questions/77494964/why-list-comprehensions-create-a-function-internally
This is disassembly of a list comprehension in python-3.10: Python 3.10.12 (main, Jun 11 2023, 05:26:28) [GCC 11.4.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import dis >>> >>> dis.dis("[True for _ in ()]") 1 0 LOAD_CONST 0 (<code object <listcomp> at 0x7fea68e0dc60, file "<d...
The main logic of creating a function is to isolate the comprehension’s iteration variablepeps.python.org. By creating a function, Comprehension iteration variables remain isolated and don’t overwrite a variable of the same name in the outer scope, nor are they visible after the comprehension However, this is ineffic...
49
69
77,522,753
2023-11-21
https://stackoverflow.com/questions/77522753/how-to-use-to-dict-and-orient-records-in-polars-that-is-being-used-in-pandas
Using polars, I am not getting the same output as pandas when calling to_dict. Pandas. df = pd.DataFrame({ 'column_1': [1, 2, 1, 4, 5], 'column_2': ['Alice', 'Bob', 'Alice', 'Tom', 'Tom'], 'column_3': ['Alice1', 'Bob', 'Alice2', 'Tom', 'Tom'] }) df.to_dict(orient='records') produces [{'column_1': 1, 'column_2': 'Alice...
To replicate the behaviour of pandas' to_dict with orient="records", you can use pl.DataFrame.to_dicts (notice the extra s). df.to_dicts() Output. [{'column_1': 1, 'column_2': 'Alice', 'column_3': 'Alice1'}, {'column_1': 2, 'column_2': 'Bob', 'column_3': 'Bob'}, {'column_1': 1, 'column_2': 'Alice', 'column_3': 'Alice2...
7
10
77,507,580
2023-11-18
https://stackoverflow.com/questions/77507580/userwarning-figurecanvasagg-is-non-interactive-and-thus-cannot-be-shown-plt-sh
I am using Windows 10 PyCharm 2021.3.3 Professional Edition python 3.11.5 matplotlib 3.8.1 How can I permanently resolve this issue in my development environment? import numpy as np import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt # Read data from file, skipping the first row (header) data = np...
I have the same issue. In my case, I installed the PyQt5==5.15.10. After that, I run my code successfully. pip install PyQt5==5.15.10 or pip install PyQt5 with python==3.11 But from 2024, you guys should install version PyQt6 or the last version with python==3.12 or later.
49
73
77,517,922
2023-11-20
https://stackoverflow.com/questions/77517922/subclassing-polygon-in-shapely
I'm working with Shapely in Python and trying to subclass the Polygon class. However, I'm encountering an error when trying to add a custom attribute during object creation. Could you please provide guidance on how to subclass the Polygon class in Shapely and add custom attributes without running into this error? This ...
You need to downgrade shapely to version 1.7 unfortunately. They intentionally got rid of any subclassing capability in 1.8 and they explicitly say they aren't going to support it anymore. See the issue here: https://github.com/shapely/shapely/issues/1698
3
1
77,502,027
2023-11-17
https://stackoverflow.com/questions/77502027/infer-return-type-annotation-from-other-functions-annotation
I have a function with a complex return type annotation: from typing import (Union, List) # The -> Union[…] is actually longer than this example: def parse(what: str) -> Union[None, int, bool, float, complex, List[int]]: # do stuff and return the object as needed def parse_from_something(which: SomeType) -> ????: retur...
What you describe is not possible by design. From PEP 484: It is recommended but not required that checked functions have annotations for all arguments and the return type. For a checked function, the default annotation for arguments and for the return type is Any. An exception is the first argument of instance and cl...
2
1
77,520,963
2023-11-21
https://stackoverflow.com/questions/77520963/using-locally-deployed-llm-with-langchains-openai-llm-wrapper
I have deployed llm model locally which follows openai api schema. As it's endpoint follows openai schema, I don't want to write separate inference client. Is there any way we can utilize existing openai wrapper by langchain to do inference for my localhost model. I checked there is a openai adapter by langchain, but i...
It turns out you can utilize existing ChatOpenAI wrapper from langchain and update openai_api_base with the url where your llm is running which follows openai schema, add any dummy value to openai_api_key can be any random string but is necessary as they have validation for this and finally set model_name to whatever m...
2
2
77,494,543
2023-11-16
https://stackoverflow.com/questions/77494543/seleniumbase-undetected-chrome-driver-how-to-set-request-header
I am using seleniumbase with Driver(uc=True), which works well for my specific scraping use case (and appears to be the only driver that consistently remains undetected for me). It is fine for everything that doesn't need specific header settings. For one particular type of scrape I need to set the Request Header (Acce...
My code fragments from second effective solution derived from now deleted bountied answer (the .v2 was the piece I had not seen previously and which I think is what made it work): ... from seleniumwire import webdriver from selenium.webdriver.chrome.options import Options from seleniumwire.undetected_chromedriver.v2 im...
7
2
77,505,030
2023-11-17
https://stackoverflow.com/questions/77505030/openai-api-error-you-tried-to-access-openai-chatcompletion-but-this-is-no-lon
I am currently working on a chatbot, and as I am using Windows 11 it does not let me migrate to newer OpenAI library or downgrade it. Could I replace the ChatCompletion function with something else to work on my version? This is the code: import openai openai.api_key = "private" def chat_gpt(prompt): response = openai....
Try updating to the latest and using: from openai import OpenAI client = OpenAI( # defaults to os.environ.get("OPENAI_API_KEY") api_key="private", ) def chat_gpt(prompt): response = client.chat.completions.create( model="gpt-3.5-turbo", messages=[{"role": "user", "content": prompt}] ) return response.choices[0].message...
20
34
77,510,558
2023-11-19
https://stackoverflow.com/questions/77510558/why-do-different-devices-use-the-same-session-in-django
I use the session to count the number of failed logins. But when I use Wi-Fi internet, because the IP of two devices (mobile and PC) is the same, Django uses the same session. If I have two failed logins on PC and two failed logins on mobile, it will add these two together. But the interesting thing is that when I log ...
All devices using the same Wi-Fi have the same external IP, what you mentioned as a problem is actually an advantage that prevents malicious attacks on the site.
2
2
77,484,926
2023-11-15
https://stackoverflow.com/questions/77484926/how-to-scroll-in-a-nav-element-using-seleniumbase-in-python
<nav class="flex h-full w-full flex-col p-2 gizmo:px-3 gizmo:pb-3.5 gizmo:pt-0" aria-label="Menu"> This is the nav although, its a-lot longer its full of divs I just want to know how to scroll till the end of the menu. Edit: loading element that has to be accounted for <svg stroke="currentColor" fill="none" stroke-wid...
There are lots of specialized scroll methods in SeleniumBase: self.scroll_to(selector) self.slow_scroll_to(selector) self.scroll_into_view(selector) self.scroll_to_top() self.scroll_to_bottom() But you might not even need to scroll to the element. There's a self.js_click(selector) method, which lets you click on hidde...
4
1
77,519,280
2023-11-20
https://stackoverflow.com/questions/77519280/pyspark-cumsum-with-salting-over-window-w-skew
How can I use salting to perform a cumulative sum window operation? While a tiny sample, my id column is heavily skewed, and I need to perform effectively this operation on it: window_unsalted = Window.partitionBy("id").orderBy("timestamp") # exected value df = df.withColumn("Expected", F.sum('value').over(window_unsal...
From what I see, the main issue here is that the timestamps must remain ordered for partial cumulative sums to be correct, e.g., if the sequence is 1,2,3 then 2 cannot go into different partition than 1 and 3. My suggestion is to use salt value based on timestamp that preserves the ordering. This will not completely re...
2
2
77,490,435
2023-11-15
https://stackoverflow.com/questions/77490435/attributeerror-cython-sources
I am using: python: 3.12 OS: Windows 11 Home I tried to install catboost==1.2.2 I am getting this error: C:\Windows\System32>py -3 -m pip install catboost==1.2.2 Collecting catboost==1.2.2 Downloading catboost-1.2.2.tar.gz (60.1 MB) ---------------------------------------- 60.1/60.1 MB 5.1 MB/s eta 0:00:00 Installing ...
Edit: Adding the work arounds which worked for people. Two workarounds exist: 1.Preinstall cython<3, then install pyyaml without build isolation, then install the rest of your dependencies "AttributeError: cython_sources" with Cython 3.0.0a10 #601 (comment) $ pip install "cython<3.0.0" wheel $ pip install "pyyaml==5.4....
31
88
77,485,901
2023-11-15
https://stackoverflow.com/questions/77485901/pytest-how-to-find-the-test-result-after-a-test
After a test has been executed I need to collect the result of that test. But I don't find the result in the FixtureRequest object. I can find the test name and some additional data but nowhere I see something that shows if a test has been passed or failed. Nor if there were some exceptions example code: class TestSome...
The way to achieve this is by using hooks. The hook will add the test result as an attribute of the test item, which afterwards you will be able to check and perform necessary actions. # example conftest.py import pytest # set up a hook to be able to check if a test has failed @pytest.hookimpl(tryfirst=True, hookwrappe...
3
2
77,522,941
2023-11-21
https://stackoverflow.com/questions/77522941/using-sample-weights-through-metadata-routing-in-scikit-learn-in-nested-cross-va
I am using the sklearn version "1.4.dev0" to weight samples in the fitting and scoring process as described in this post and in this documentation. https://scikit-learn.org/dev/metadata_routing.html sklearn GridSearchCV not using sample_weight in score function I am trying to use this in a nested cross validation schem...
cross_validate trains and scores the estimator, which means if the hyperparameters of the estimators are the same, then the trained versions inside cross_validate would also be the same, which is the case here since both est_weighted and est_unweighted use alpha=0.1. There are a few issues here though, first, you're no...
2
3
77,526,562
2023-11-21
https://stackoverflow.com/questions/77526562/is-there-a-function-i-can-use-to-replace-my-if-statements-and-variables
I'm trying to figure out how to make my code more readable and have less lines in my code. It contains a lot of if elif statements that seem like can be combined into a few. fl = input("file:").lower().strip() a = fl.endswith(".jpeg") b = fl.endswith(".jpg") c = fl.endswith(".txt") d = fl.endswith(".png") e = fl.endswi...
Use a dictionary to map extensions to content-types. import os extension_content_types = { ".jpeg": "image/jpeg", ".jpg": "image/jpeg", ".txt": "text/plain", ".png": "image/png", ".pdf": "application/pdf", ".zip": "application/zip", ".gif": "image/gif", } fl = input("file:").lower().strip() filename, ext = os.path.spli...
3
5
77,522,301
2023-11-21
https://stackoverflow.com/questions/77522301/how-to-change-sympy-plot-properties-in-jupyter-with-matplotlib-methods
The following code in a script works as expected, from sympy import * x = symbols('x') p = plot(x, x*(1-x), (x, 0, 1)) ax = p._backend.ax[0] ax.set_yticks((0, .05, .25)) p._backend.fig.savefig('Figure_1.png') but when I copy the code above in a notebook cell, this is what I get If it is possible to manipulate the (h...
As per this answer of Display two Sympy plots as two Matplotlib subplots, with inline mode in Jupyter, p.backend(p) must be used. The problem is that sympy.plotting.plot.plot(*args, show=True, **kwargs) creates its own figure and axes and plots.show() displays the plot immediately. Because of the way inline mode work...
2
4
77,522,801
2023-11-21
https://stackoverflow.com/questions/77522801/how-to-create-a-rotating-animation-of-a-scatter3d-plot-with-plotly-and-save-it-a
With plotly in jupyter I am creating a Scatter3D plot as follows: # Configure the trace. trace = go.Scatter3d( x=x, y=y, z=z, mode='markers', marker=dict(color=colors, size=1) ) # Configure the layout. layout = go.Layout( margin={'l': 0, 'r': 0, 'b': 0, 't': 0}, height = 1000, width = 1000 ) data = [trace] plot_figure ...
Note pio.write_image() expects a Figure object or dict representing a figure as the 1st argument (we can't just pass an update object or a frame). The idea is precisely to apply the changes from each animation frame to the figure and export it at each point sequentially : frames=[] for k, t in enumerate(np.arange(0, 6....
3
2
77,518,816
2023-11-20
https://stackoverflow.com/questions/77518816/can-i-install-a-python-package-in-a-conda-environment-while-a-script-is-currentl
I used a SLURM manager to submit a bunch of scripts that all run in one Conda environment. I would like to install a new Python package to this environment. Do I need to wait until all of my scripts are done running? Or can I install the package now without messing anything up?
Can you? Sure. Should you? No. It could lead to changing existing packages, which could potentially lead to problems (e.g., missing references, API changes) - really depends on how the scripts are written and the dynamics of library loading throughout the scripts. However, there is a larger issue of working reproducibl...
2
5
77,522,071
2023-11-21
https://stackoverflow.com/questions/77522071/error-numpy-core-multiarray-failed-to-import-pyhdf
I'm trying to open HDF files using a python code provided in this website (https://hdfeos.org/software/pyhdf.php). However, I get an error while importing the pyhdf package import os from pyhdf.SD import SD, SDC import numpy as np import rasterio The error : ------------------------------------------------------------...
As commented by @Cow, I am posting this as an answer: The following packages are required to build and install pyhdf: Python: Python 2.6 or newer for Python 2, or Python 3.2 or newer for Python 3. NumPy HDF4 libraries (to use their HDF4 binaries, you will also need szip, available from the same page) Compiler suite e.g...
3
2
77,522,673
2023-11-21
https://stackoverflow.com/questions/77522673/google-calendar-api-understanding-of-token-json
I am working with the Google calendar API, the python quickstart in particular, but the language does not matter. The example from https://developers.google.com/calendar/api/quickstart/python has: if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow =...
Question 1: My question is about token.json, is that file shared between all users, or should a separator file be created for each person? Token Json is single user. In fact as your code is written it is single user. The first thing that sample does is check if the file exists if os.path.exists("token.json"): If it ...
2
3
77,521,658
2023-11-21
https://stackoverflow.com/questions/77521658/vscode-python-pylance-does-not-gray-out-unaccessed-variable
In below screenshot when hovering over the grayed out variables Pylance (correctly!) says they are not accessed, e.g.; "_baz" is not accessed Pylance. My question is about waz, which is clearly not accessed in either tabs, still not grayed out. Why isn't it grayed out? I thought maybe it was related to waz not being a...
Global variables without an underscore are considered public, so it might be used when imported from somewhere else.
2
2
77,521,686
2023-11-21
https://stackoverflow.com/questions/77521686/how-to-make-overlapping-windows-of-weeks-based-on-the-nearest-available-dates-in
Sorry guys for the title but it is really what I'm trying to do. Here is a table to explain that more. The bold lines makes the years and the the thin ones makes the weeks. For the expected output. It really doesn't matter its format. All I need is that if I ask for the dates of a pair YEAR/WEEK, I get the correspondi...
Looks like you could use a simple mask for the YEAR/WEEK and expand it one row above/below (assuming sorted dates): df = df.sort_values(by=['YEAR', 'WEEK']) def some_window_function(year, week): mask = df['YEAR'].eq(year) & df['WEEK'].eq(week) return df[mask|mask.shift()|mask.shift(-1)] some_window_function(2022, 5) O...
2
1
77,522,054
2023-11-21
https://stackoverflow.com/questions/77522054/count-unique-value-with-prioritize-value-in-pandas
I have a simple data frame as below: import pandas as pd import numpy as np df = pd.DataFrame({'CUS_NO': ['900636229', '900636229', '900636080', '900636080', '900636052', '900636052', '900636053', '900636054', '900636055', '900636056'], 'indicator': ['both', 'left_only', 'both', 'left_only', 'both', 'left_only', 'both'...
You can sort_values to have "both" on top (if more categories, use a Categorical to define a custom order), then drop_duplicates: tmp = (df .sort_values(by='indicator') .drop_duplicates(subset=['CUS_NO', 'Nationality'], keep='first') ) df2 = pd.pivot_table(tmp, values='CUS_NO', index='Nationality', columns='indicator',...
3
2
77,500,505
2023-11-17
https://stackoverflow.com/questions/77500505/how-to-draw-the-radius-of-a-circle-within-a-cartopy-projection
I am trying to draw the radius of a circle on a Cartopy projection through one point. And I couldn't find anything related to this. Here is what I have so far: fig = plt.figure(figsize=(10, 6)) ax = fig.add_subplot(1, 1, 1, projection=ccrs.Mercator()) ax.set_extent([18, 28, 59.5, 64.1], crs=ccrs.PlateCarree()) ax.coast...
This code should give the required radius line that passes the X mark. The code: from shapely.geometry import Polygon from cartopy.geodesic import Geodesic # from geographiclib import matplotlib.pyplot as plt import cartopy.crs as ccrs import cartopy import cartopy.feature as cfeature fig = plt.figure(figsize=(10, 6)) ...
2
3
77,521,378
2023-11-21
https://stackoverflow.com/questions/77521378/confusing-output-with-pandas-rolling-window-with-datetime64us-dtype
I get confusing results from pandas.rolling() when the dtype is datetime64[us]. Pandas version is 2.1.1. Let df be the dataframe day x 0 2021-01-01 3 1 2021-01-02 2 2 2021-01-03 1 3 2021-01-05 4 4 2021-01-08 2 5 2021-01-14 5 6 2021-01-15 6 7 2021-01-16 1 8 2021-01-19 5 9 2021-01-20 2 Its dtypes are: day datetime64[ns...
I can't reproduce it on pandas 2.1.2, make sure to use a recent version: print(pd.__version__) 2.1.2 df["day"] = df["day"].astype("datetime64[us]") print(df.dtypes) day datetime64[us] x int64 dtype: object df.rolling("3d", on="day", center=True)["x"].sum() 0 5.0 1 6.0 2 3.0 3 4.0 4 2.0 5 11.0 6 12.0 7 7.0 8 7.0 9 7.0 N...
3
2
77,516,280
2023-11-20
https://stackoverflow.com/questions/77516280/install-youtokentome-in-poetry-requires-cython-unable-to-configre-correctly
I'm trying to convert whipser-diarization to poetry. It goes well until I add nemo_toolkit[asr]==1.20.0, which depends on youtokentome (that name is well thought of, btw) File "/tmp/tmpexmdke23/.venv/lib/python3.10/site-packages/setuptools/build_meta.py", line 507, in run_setup super(_BuildMetaLegacyBackend, self).run...
Building this package is done in an isolated environment, so it doesn't matter if Cython is installed in your current environment. youtokentome has to define its build requirements according to PEP 518. There seems to be a Pull Request for it for a long time: https://github.com/VKCOM/YouTokenToMe/pull/108
3
2
77,503,260
2023-11-17
https://stackoverflow.com/questions/77503260/can-we-stop-the-dash-post-dash-dash-update-component-http-1-1-log-messages
Has anyone figured out how to stop the following Dash log messages? They clutter up my logs, and on a busy website, make it almost impossible to see actual, useful log messages when errors occur. [17/Nov/2023:16:28:10 +0000] "POST /dash/_dash-update-component HTTP/1.1" 204 0 "https://example.com/" "Mozilla/5.0 (iPhone;...
I finally solved the problem, I think. As @EricLavault suggested, it was a Gunicorn problem, not a Dash/Flask logging problem. What I was seeing were the "access logs", which looked like this: [17/Nov/2023:16:28:10 +0000] "POST /dash/_dash-update-component HTTP/1.1" 204 0 "https://example.com/" "Mozilla/5.0 (iPhone; CP...
3
2
77,514,237
2023-11-20
https://stackoverflow.com/questions/77514237/getting-numbers-from-an-array-using-mask-and-regex
Having this array with code and collection, where X is a mask that can be "any number": input_array = [{"code": "XXXX10", "collection": "one"}, {"code": "XXX610", "collection": "two"}, {"code": "XXXX20", "collection": "three"}] I want a function that given any 6 digit code, for example 000710 returns the value that ma...
You could iterate the entire collection, saving the length of the "X" part of any match, and then return the shortest: input_array = [{"code": "XXXX10", "collection": "one"}, {"code": "XXX610", "collection": "two"}, {"code": "XXXX20", "collection": "three"}] def get_collection_from_code(analysis_code): results = {} for...
2
1
77,515,427
2023-11-20
https://stackoverflow.com/questions/77515427/new-pandas-dataframe-column-with-totals-from-a-different-dataframe-by-conditions
I have two tables: one ('sales') with sales data (types of goods, dates of sale, and quantity) and another ('ref') with types of goods and a reference date. I want to add a column to the second table that would show the total quantity of the corresponding item sold within seven days (give or take) from the reference da...
You can use conditional_join from pyjanitor: ref['start'] = ref['Date'] - pd.to_timedelta(7, unit='d') ref['end'] = ref['Date'] + pd.to_timedelta(7, unit='d') out = (sales .conditional_join( ref, ('Date', 'end', '<='), ('Date', 'start', '>='), ('Fruit', 'Fruit', '=='), how='right', df_columns='Quantity') .groupby(['Fru...
2
3
77,517,147
2023-11-20
https://stackoverflow.com/questions/77517147/in-python-if-i-make-a-list-of-optional-values-and-then-filter-out-none-how-do
In Python, when collecting a sequence of Optional values into an Iterable or List while filtering out None values, how do you express to the typechecker that the element type of the resulting Iterable is no longer Optional and the list does not contain Nones? Take the following example: def a(i: InputType) -> Optional[...
Following the suggestion of @MateenUlhaq in the comments the problem you are facing is probably due to the use of filter(partial(is_not, None)) that makes it hard for the language server to infer the type of ots return value. You can make it easier for it by filtering out the Nones at the beginning. The following is an...
3
2
77,514,680
2023-11-20
https://stackoverflow.com/questions/77514680/use-textwrap-shorten-with-a-list
this code creates me a table in an excel file and a pie plot, the label fields, taken from a list of values, are way too long. plt.pie(df.Confronto.value_counts(), labels=textwrap.shorten(df.Confronto.value_counts().index.tolist(), width=10, placeholder="...")) plt.title("Confronto {} - {}".format(Mese,Mese2,)) plt.sh...
I am not sure as to what you are trying to achieve with this code, so I'll just explain why the exception is raised. That happens because pandas.Index.tolist returns a list, and textwrap.shorten is used on strings. So, cannot strip a string if it's a list. I assume df.Confronto.value_counts().index.tolist() returns a l...
3
3
77,508,717
2023-11-18
https://stackoverflow.com/questions/77508717/where-to-find-the-code-for-esrk1-and-rswm1-in-the-julia-library-source-code
I'm trying to implement the SDE solver called ESRK1 and the adaptive stepsize algorithm called RSwM1 from Rackauckas & Nie (2017). I'm writing a python implementation, mainly to confirm to myself that I've understood the algorithm correctly. However, I'm running into a problem already at the implementation of ESRK1: Wh...
So, I guess I found the first half of the answer to my question: The code for the ESRK1 method appears to be found in two places in StochasticDiffEq.jl: The coefficients from the paper (although they are now called SRIW1 instead of ESRK1) here: https://github.com/SciML/StochasticDiffEq.jl/blob/9d8eb5503f1d78cdb0de76691...
3
1
77,511,828
2023-11-19
https://stackoverflow.com/questions/77511828/qgraphicsview-dragmode-with-middle-mouse-button
I encountered the problem indicated in the title. The only solutions I found were quite old and perhaps something has changed since then and now it is possible to make the DragMode.ScrollHandDrag action for the middle mouse key? class InfiniteCanvas(QGraphicsView): def __init__(self, parent=None): super(InfiniteCanvas,...
You are trying to call the default mousePressEvent with the synthesized left click event, but since you overrode that function without ever calling the base implementation, nothing will happen. When you do the following: def mousePressEvent(self, event): if event.button() == Qt.MidButton: self.viewport().setCursor(Qt....
2
4
77,502,026
2023-11-17
https://stackoverflow.com/questions/77502026/maximum-subarray-sum-with-at-most-k-elements
Maximum subarray sum with at most K elements : Given an array of integers and a positive integer k, find the maximum sum of a subarray of size less than or equal to k. A subarray is a contiguous part of the array. For example, if the array is [5, -3, 5, 5, -3, 5] and k is 3, then the maximum subarray sum with at most k...
There is an O(n) solution at https://cs.stackexchange.com/a/151327/10147 We can have O(n log n) with divide and conquer. Consider left and right halves of the array: the solution is either in (1) the left half exclusively, (2) the right half exclusively, or (3) a suffix of the left combined with a prefix of the right. ...
3
1
77,509,605
2023-11-19
https://stackoverflow.com/questions/77509605/mt19937-generator-in-c-and-numpy-generate-different-numbers
I am trying to reproduce some C++ code in Python that involves random number generations. The C++ code uses the MT19937 generator as follows: #include <random> #include <iostream> int main() { std::mt19937 generator(1234); std::uniform_real_distribution<double> distribution(0.0, 1.0); for (int i = 0; i < 10; ++i) { std...
The Mersenne Twister generator has a defined sequence for any seed that you give it. There are also test values that you can use to verify that the generator you use is conforming. The distributions are on the other hand not standardized and may produce different values in different implementations. Remove the distribu...
3
4
77,505,772
2023-11-18
https://stackoverflow.com/questions/77505772/finding-the-largest-groups-with-conditions-after-using-groupby
This is my dataframe: import pandas as pd df = pd.DataFrame( { 'a': ['a', 'a', 'a', 'c', 'b', 'a', 'a', 'b', 'c'], 'b': [20, 20, 20,-70, 70, -10, -10, -1, -1], } ) And this is the output that I want. I want to create a dataframe with two rows: direction length sum 0 long 3 60 1 short 2 -20 I want to get the largest ...
You need to use several groupby operations, one to find the streaks, one to aggregate the length and sum, and one to filter the output with idxmax on the largest length: group = df['b'].ne(df['b'].shift()).cumsum() out = (df .assign(direction=np.sign(df['b'])) .replace({'direction': {1: 'long', -1: 'short'}}) .groupby(...
2
4
77,503,300
2023-11-17
https://stackoverflow.com/questions/77503300/cause-of-this-error-no-list-matches-the-given-query
The user can add that product to the watch list by clicking on the add button, and then the add button will change to Rimo. And this time by clicking this button, the product will be removed from the list. There should be a link on the main page that by clicking on it, all the products in the watch list will be display...
The reason for your initial error is that <form method= "get" action = "{% url 'add' %}"> is creating a url with the parameter productid, which your path, path('add/', views.add, name='add'), does not handle. You could change it to path('add/<int:productid>', views.add, name='add') and change the view to def add(reques...
2
2
77,503,593
2023-11-17
https://stackoverflow.com/questions/77503593/python-tabulate-tablefmt-rounded-outline-prints-3-spaces-instead-of-1-space-betw
How can i avoid extra spaces in the tabulate grid? rows = [ ["A1", "B2"], ["C3", "D4"], ["E5", "E6"], ] print(tabulate(rows, headers="firstrow", tablefmt='rounded_outline')) gives me 2 extra spaces in every cell ╭──────┬──────╮ │ A1 │ B2 │ ├──────┼──────┤ │ C3 │ D4 │ │ E5 │ E6 │ ╰──────┴──────╯ how can i solve it to ...
You can leverage the MIN_PADDING constant. import tabulate rows = [ ["A1", "B2"], ["C3", "D4"], ["E5", "E6"], ] tabulate.MIN_PADDING = 0 print(tabulate.tabulate(rows, headers="firstrow", tablefmt="rounded_outline")) Outputs: ╭────┬────╮ │ A1 │ B2 │ ├────┼────┤ │ C3 │ D4 │ │ E5 │ E6 │ ╰────┴────╯
3
0
77,503,109
2023-11-17
https://stackoverflow.com/questions/77503109/how-to-fix-invalidmanifesterror-for-pre-commit-with-black
Running python pre-commit with black latest version 23.11.0 leads to a wired InvalidManifestError. snippet from .pre-commit-config.yaml repos: - repo: https://github.com/psf/black rev: 23.11.0 hooks: - id: black types: [] files: ^.*.pyi?$ # format .py and .pyi files` output message: │ │ stdout = 'An error has occurred...
you're using an outdated version of pre-commit. you need to be using at least version 3.2.0 which introduced the renamed stages disclaimer: I wrote pre-commit
6
8
77,502,500
2023-11-17
https://stackoverflow.com/questions/77502500/is-it-possible-with-pathlib-to-set-file-modification-time
I need to rewrite a lot of files, but I need them to keep their modification time as I need them indexed by time. I am aware that I could use os, but as I like pathlib's object oriented way, I would prefer to use pathlib if that is an option. Pathlib-docs mention getting the st_mtime, but not setting it. I only found t...
No, it's not. pathlib is for manipulating paths, not files. It's useful to think of it as a convenience wrapper around path string. Path.stat() is just a convenience method, doing nothing but calling os.stat() on path. So yes, you have to use os.utime().
3
2
77,502,055
2023-11-17
https://stackoverflow.com/questions/77502055/calling-simple-hello-world-function-from-a-compiled-c-dll-from-python-results
The C code: // my_module.c #include <stdio.h> __declspec(dllexport) void hello() { printf("Hello World!\n"); } __declspec(dllexport) int add_numbers(int a, int b) { return a + b; } // entry point int main() { return 0; } The build script: # build.py from setuptools._distutils.ccompiler import new_compiler compiler = n...
it seems distutils is linking the msvc CRT incorrectly. you shouldn't import anything with an underscore such as _distutils, as it is not a part of the public API and you shouldn't use it. since this is a simple windows dll you could call cl.exe directly and compile it. (make sure you open x64 Native Tools Command Prom...
2
3
77,500,616
2023-11-17
https://stackoverflow.com/questions/77500616/product-between-multiindex-and-a-list
I have a MultiIndex object with 2 levels: import pandas as pd mux = pd.MultiIndex.from_tuples([(1,1), (2,3)]) >>> MultiIndex([(1, 1), (2, 3)], ) I want to multiply it by a list l=[4,5], I tried pd.MultiIndex.from_product([mux.values, [4,5]]) >>> MultiIndex([((1, 1), 4), ((1, 1), 5), ((2, 3), 4), ((2, 3), 5)], ) I man...
I think your approach is quite reasonable. Another option using a cross-merge with an intermediate DataFrame format: pd.MultiIndex.from_frame(mux.to_frame().merge(pd.Series([4, 5], name=2), how='cross')) Output: MultiIndex([(1, 1, 4), (1, 1, 5), (2, 3, 4), (2, 3, 5)], names=[0, 1, 2])
3
3
77,493,160
2023-11-16
https://stackoverflow.com/questions/77493160/why-we-cannot-use-alone-starred-target-while-assignment-in-python
I was going through the python docs on simple assignment. I found below from the docs. Assignment of an object to a target list, optionally enclosed in parentheses or square brackets, is recursively defined as follows. If the target list is a single target with no trailing comma, optionally in parentheses, the object ...
You can instead add a comma to make the unpacking assignment to an explicit tuple: *a, = 1, 2, 3 as pointed out in PEP-3132: It is also an error to use the starred expression as a lone assignment target, as in *a = range(5) This, however, is valid syntax: *a, = range(5) It is also pointed out in the same documenta...
3
4
77,492,044
2023-11-16
https://stackoverflow.com/questions/77492044/how-to-create-a-stripplot-with-multiple-subplots
This is my example data data = {'pro1': [1, 1, 1, 0], 'pro2': [0, 1, 1, 1], 'pro3': [0, 1, 0, 1], 'pro4': [0.2, 0.5, 0.3, 0.1]} df = pd.DataFrame(data) I want to make striplot in seaborn like this (but actually wrong when running): sns.stripplot(x=['pro1', 'pro2', 'pro3'], y='pro4', data=df) This is my alternative co...
In my opinion, the easiest is to melt and catplot: import seaborn as sns sns.catplot(df.melt('pro4'), x='variable', y='pro4', hue='variable', col='value', kind='strip') Output:
2
3
77,498,106
2023-11-16
https://stackoverflow.com/questions/77498106/how-to-perform-a-left-join-on-two-pandas-dataframes-for-a-specific-use-case
Example Data: Here is a simplified representation of my dataframes: My first dataframe(df1) is like: col1 col2 col3 col4 col5 1 2 a 3 4 11 22 aa 33 44 111 222 aaa And my second dataframe(df2) is something like: col3 col4 col5 a 3 4 aa 332 442 aaa 333 444 And i want my merged dataframe ...
A proposition with merge/lreshape : mg = pd.merge(df1, df2, on="col3", how="left") grps = {c: [f"{c}_{s}" for s in ["x", "y"]] for c in df1.columns.intersection(df2.columns).drop("col3")} out = pd.lreshape(mg, grps).drop_duplicates().convert_dtypes() NB: The loop is really optional here and can be replaced with a hard...
2
5
77,497,397
2023-11-16
https://stackoverflow.com/questions/77497397/how-to-autogenerate-pydantic-field-value-and-not-allow-the-field-to-be-set-in-in
I want to autogenerate an ID field for my Pydantic model and I don't want to allow callers to provide their own ID value. I've tried a variety of approaches using the Field function, but the ID field is still optional in the initializer. class MyModel(BaseModel): item_id: str = Field(default_factory=id_generator, init_...
Use a combination of a PrivateAttr field and a computed_field property: from uuid import uuid4 from pydantic import BaseModel, PrivateAttr, computed_field class MyModel(BaseModel): _id: str = PrivateAttr(default_factory=lambda: str(uuid4())) @computed_field @property def item_id(self) -> str: return self._id print(MyMo...
3
5
77,490,803
2023-11-15
https://stackoverflow.com/questions/77490803/draw-rectangles-in-a-circular-pattern-in-turtle-graphics
To make use of the turtle methods and functionalities, we need to import turtle. “turtle” comes packed with the standard Python package and need not be installed externally. The roadmap for executing a turtle program follows 3 steps: a- Import the turtle module. b- Create a turtle to control. c- Draw around using the t...
Your rectangles look pretty good, although you don't need to draw the fill and outline separately. All that's missing is moving forward and backward from the start point to the corner of each square: from turtle import Screen, Turtle def draw_rectangle_with_border(t, width, height): t.pendown() t.begin_fill() for _ in ...
2
2
77,495,593
2023-11-16
https://stackoverflow.com/questions/77495593/polars-how-to-bin-a-datetime-type-column
I am trying to bin a date column. I was able to do that fairly easy using Pandas library. But I am getting the following error with Polars: Traceback (most recent call last): File "\workspace\polars.py", line 4, in <module> pl.col("ts").cut( File "\venvs\polars\Lib\site-packages\polars\utils\deprecation.py", line 192, ...
This looks like a bug - do you want to report it to https://github.com/pola-rs/polars/issues ? For now, as a workaround, you could cast to int: breaks = pl.date_range(start_year, end_year, interval="3mo", eager=True) df.with_columns( pl.col("ts").cast(pl.Int64).cut( breaks.cast(pl.Int64), ).alias("period_bins") )
3
2
77,488,499
2023-11-15
https://stackoverflow.com/questions/77488499/how-to-re-infer-datatypes-on-existing-polars-dataframe
I have the following problem: I have a csv-file with faulty values (strings instead of integers) in some rows. To remedy that, I read it into polars and filter the dataframe. To be able to read it, I have to set infer_schema_length = 0, since otherwise the read would fail. This reads every column as a string, though. H...
I don't think Polars has this funtionality yet, but I think I found a valid way to solve your problem: from io import BytesIO import polars as pl dataset_path = "./test_data.csv" ids_df = pl.read_csv(dataset_path, infer_schema_length=0) print("ids_df",ids_df) filtered_df = ids_df.filter(~(pl.col("Label") == "Label")) p...
2
4
77,492,161
2023-11-16
https://stackoverflow.com/questions/77492161/is-there-a-way-to-handle-overlapping-keyword-bracketing-in-python
Suppose I have a list of keywords and an input string labelled section, I want my code to find those keywords within section and put them inside [] square brackets. However, my keywords sometimes overlap with each other. keywords = ["alpha", "alpha beta", "alpha beta charlie", "alpha beta charlie delta"] To fix that I ...
You can join the sorted keywords into an alternation pattern instead of substituting the string with different keywords 4 times, each time potentially substituting the replacement string from the previous iteration: import re keywords = ["alpha", "alpha beta", "alpha beta charlie", "alpha beta charlie delta"] keywords....
3
4
77,489,704
2023-11-15
https://stackoverflow.com/questions/77489704/groupby-giving-same-aggregate-value-for-all-groups
I am trying to take mean of each group and trying to assign those to a new column in another dataframe but the first group's mean value is populating across all groups. Below is my dataframe df1 level value CF 5 CF 4 CF 6 EL 2 EL 3 EL 1 EF 4 EF 3 EF 6 I am taking the mean of each group and saving it to a new column in...
You should not use groupby.transform, this is mostly useful when you want to assign to the same dataframe. Here you need to map: df2['value'] = df2['level'].map(df1.groupby(['level'])['value'].mean())
2
2
77,487,996
2023-11-15
https://stackoverflow.com/questions/77487996/using-glob-to-recursively-get-terminal-subdirectories
I have a series of subdirectories with files in them: /cars/ford/escape/sedan/ /cars/ford/escape/coupe/ /cars/ford/edge/sedan/ /cars/ferrari/testarossa/ /cars/kia/soul/coupe/ etcetera. I'd like to get all of these terminal subdirectory paths from the root, /cars/, using glob (within Python), but not include any of the...
glob is the wrong tool for this job: traditional POSIX-y glob expressions don't support any kind of negative assertion (extglobs do, but it's still a restrictive kind of support -- making assertions about an individual name, not what does or doesn't exist on the same filesystem -- that doesn't apply to your use case, a...
2
3
77,444,332
2023-11-8
https://stackoverflow.com/questions/77444332/openai-python-package-error-chatcompletion-object-is-not-subscriptable
After updating my OpenAI package to version 1.1.1, I got this error when trying to read the ChatGPT API response: 'ChatCompletion' object is not subscriptable Here is my code: messages = [ {"role": "system", "content": '''You answer question about some service''' }, {"role": "user", "content": 'The user question is ....
In the latest OpenAI package the response.choices object type is changed and in this way you must read the response: print(response.choices[0].message.content) The complete working code: from openai import OpenAI client = OpenAI(api_key='YourKey') GPT_MODEL = "gpt-4-1106-preview" #"gpt-3.5-turbo-1106" messages = [ {"r...
51
98
77,469,097
2023-11-12
https://stackoverflow.com/questions/77469097/how-can-i-process-a-pdf-using-openais-apis-gpts
The web interface for ChatGPT has an easy pdf upload. Is there an API from openAI that can receive pdfs? I know there are 3rd party libraries that can read pdf but given there are images and other important information in a pdf, it might be better if a model like GPT 4 Turbo was fed the actual pdf directly. I'll state ...
As of today (openai.__version__==1.42.0) using OpenAI Assistants + GPT-4o allows to extract content of (or answer questions on) an input pdf file foobar.pdf stored locally, with a solution along the lines of from openai import OpenAI from openai.types.beta.threads.message_create_params import ( Attachment, AttachmentTo...
30
17
77,482,135
2023-11-14
https://stackoverflow.com/questions/77482135/cant-import-name-cygrpc-from-grpc-cython
I'm trying to locally test a function i've written, but keep getting the error "cannot import name 'cygrpc' from 'grpc._cython" which causes attempts to run the function to fail I've made sure i'm running python 3.9 for compatibility, and the most recent version of azure functions core tools, as specified on the micros...
What worked for me was running func init in the project (I'd cloned the project to a new machine and not run this step). After this it worked fine.
3
0
77,455,386
2023-11-9
https://stackoverflow.com/questions/77455386/how-to-format-polars-duration
This: df = (polars .DataFrame(dict( j=['2023-01-02 03:04:05.111', '2023-01-08 05:04:03.789'], k=['2023-01-02 03:04:05.222', '2023-01-02 03:04:05.456'], )) .select( polars.col('j').str.to_datetime(), polars.col('k').str.to_datetime(), ) .with_columns( l=polars.col('k') - polars.col('j'), ) ) print(df) produces: j (dat...
It looks like you need to use pl.format and cobble together what you want with dt.total_seconds, dt.total_milliseconds, etc. These aren't intended to be used together so if you do it'll be (roughly) doubling (for 2 elements) the total time so, imo, best to use the most granular unit and do the math yourself since you'v...
2
3