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,857,047
2024-8-10
https://stackoverflow.com/questions/78857047/working-with-known-indexes-on-a-numpy-array
I'm working on a Python project that generates random tile maps using NumPy. While my code is functional, it's currently too slow, and I'm struggling to vectorize it effectively to improve performance. I start with a small grid (e.g., 4x4) and place a few land tiles. The map is then upscaled by subdividing each tile in...
Note: I kept the explanation to a minimum, but this answer is still long. If you're only looking for the code, just scroll to the end. In my opinion, the key to vectorization is to extract the parts that can be vectorized. But before that, there is one part that needs to be corrected. The following code is doing someth...
2
3
78,856,452
2024-8-10
https://stackoverflow.com/questions/78856452/is-a-bab-equivalent-to-minb-a
I came upon a bit of third party Python code that read: count = [remaining, readlen][remaining > readlen] After staring at it for a bit, I have to ask: are there any cases where this construct is NOT equivalent to: count = min(readlen, remaining) i.e. are there there any functional differences between the two?
Let's assume a == b. In this case, [a,b][a>b] returns a, since a>b evaluates to False, which is then cast to 0. But min(b, a) returns b (first argument). This is not relevant for numbers, but it may matter if a and b are mutable objects, like lists: >>> a = [1, 2] >>> b = [1, 2] >>> c = [a, b][a>b] >>> c is a True >>> ...
2
6
78,856,047
2024-8-10
https://stackoverflow.com/questions/78856047/how-to-do-group-by-and-then-subtract-group-mean-from-each-entry-in-the-group-in
In pandas I can calculate the centered grouped columns as follows for a dataframe with columns ['a','b','c']: df[['b','c']] = df[['b','c']].sub(df.groupby('a')['b','c'].transform(mean)) What is the equivalent code in Polars? I tried implementing it with sub in polars but it expects expression and not dataframe. I need...
TLDR. In polars, this is achieved with the window function pl.Expr.over. Concretely, your pandas code would look as follows. df.with_columns( pl.col("b", "c") - pl.col("b", "c").mean().over("a") ) Applied to some sample data, this could look as follows. import polars as pl df = pl.DataFrame({ "a": [0, 0, 0, 1, 1, 1],...
2
3
78,856,001
2024-8-10
https://stackoverflow.com/questions/78856001/how-to-combine-two-columns-into-keyvalue-pairs-in-polars
I'm working with a Polars DataFrame, and I want to combine two columns into a dictionary format, where the values from one column become the keys and the values from the other column become the corresponding values. Here's an example DataFrame: import polars as pl df = pl.DataFrame({ "name": ["Chuck", "John", "Alice"],...
You can try this code snippet, This seems to be the closest you can get has pl does not have a naive dict. See reference : data_types_polaris import polars as pl df = pl.DataFrame( {"name": ["Chuck", "John", "Alice"], "surname": ["Dalliston", "Doe", "Smith"]} ) df = df.select( [ "name", "surname", ( pl.struct(["name", ...
2
2
78,854,166
2024-8-9
https://stackoverflow.com/questions/78854166/convert-dataframe-to-nested-json-records
I have a spark dataframe as follows: ---------------------------------------------------------------------------------------------- | type | lctNbr | itmNbr | lastUpdatedDate | lctSeqId| T7797_PRD_LCT_TYP_CD| FXT_AIL_ID| pmyVbuNbr | upcId | vndModId| ____________________________________________________________________...
You can groupby the desired fields, then aggregate F.collect_list(F.create_map(...)) to get the inner fields for locations and itemDetails. Sample data: pandasDF = pd.DataFrame({ "type": ["prd_lct","prd_lct","test"], "lctNbr": [145, 145, 148], "itmNbr": [147, 147, 150], "lastUpdatedDate": ["2024-07-22T05:24:14", "2024-...
4
0
78,854,478
2024-8-9
https://stackoverflow.com/questions/78854478/how-can-i-replace-null-values-in-polars-with-a-prefix-with-ascending-numbers
I am trying to replace null values in my dataframe column by a prefix and ascending numbers(to make each unique).ie df = pl.from_repr(""" ┌──────────────┬──────────────┐ │ name ┆ asset_number │ │ --- ┆ --- │ │ str ┆ str │ ╞══════════════╪══════════════╡ │ Office Chair ┆ null │ │ Office Chair ┆ null │ │ Office Chair ┆ n...
df = df.with_columns( pl.col("asset_number").fill_null( "PREFIX - " + pl.int_range(pl.len()).cast(pl.String) ) )
3
3
78,854,275
2024-8-9
https://stackoverflow.com/questions/78854275/how-to-differentiate-and-split-os-environ-into-defaults-and-addons
Is it possible to split os.environ into default environment variables and custom addon variables? For example, using syntax of sets representing the key/ENV_VAR_NAME: custom_addon_env_var_keys = set(os.environ.keys()) - set(os.environ.default.keys()) # is there this `os.environ.default` kinda thing? Is there some kind...
Python modules are only ever imported once within the same program instance. It doesn't matter how many different files you have importing something, that first time it's imported is the only time it's run, and everything else reuses it. There are two ways to take advantage of this. First, the more clean way, which is ...
3
1
78,852,566
2024-8-9
https://stackoverflow.com/questions/78852566/colormap-of-imshow-not-linked-to-surface-plot
I have created a figure with two subplots. On the left is a 3D surface plot and on the right side is 2D projection of the 3D plot with imshow. I want the colormap of the imshow plot to be linked to the 3D plot. But the scale does not fit. import numpy as np import matplotlib.pyplot as plt id = np.arange(-600,750,150) i...
There are two things here: The default origin for imshow (on your 2D plot) is "upper", meaning the vertical axis points downwards by default. Since you have the lower numbers at the bottom of your axis, you want to set origin="lower". You can use the mappable object that is created by imshow to create the colorbar, w...
2
1
78,852,837
2024-8-9
https://stackoverflow.com/questions/78852837/file-path-good-for-windows-and-android
I have a python script that uses images from a folder. The script might work on Windows and Android as well. The problem is I should indicate different file path for the same images (included in the folder where the script is). Is there a format I can use valid for both? For Android I am using "./image.png", but this d...
If you want some dynamic path, you can use os: import os path = os.path.join('folder1', 'folder2', '...', 'image.png') You can use as many as you need, or just image.png.
2
3
78,852,009
2024-8-9
https://stackoverflow.com/questions/78852009/pandas-re-arranging-columns-with-date-year-as-header
Wish to re-arrange date columns (with Month Year as header) in descending order from left to right. All non-date cols are shifted to extreme left before the date columns begin. If possible as the Column headers are mix-case, so need to process as case-insensitive. demo = { 'Name': ['Alice', 'Bob', 'Charlie', 'David'], ...
You can convert to_datetime with errors='coerce' as key to sort_index. In addition pass ascending=False, na_position='first' as parameters to get the dates in descending order and the non-dates first: df = pd.DataFrame(demo) result = df.sort_index( axis=1, key=lambda x: pd.to_datetime(x, errors='coerce', format='mixed'...
2
1
78,850,636
2024-8-8
https://stackoverflow.com/questions/78850636/what-is-password-based-authentication-in-the-usercreationform-in-django-and-how
I made a form that inherits from the UserCreationForm and use class based view that inherits CreateView and when I use runserver and display the form, there is a section at the bottom Password-based authentication that I don't notice forms.py from django.contrib.auth import get_user_model from django.contrib.auth.forms...
From Django version 5.1 onwards the UserCreationForm has a usable_password field by default. This relates to the feature Django has for setting unusable passwords for users. This is useful in case you're using some kind of external authentication like Single Sign-On or LDAP. Since your form seems to be a user facing on...
4
7
78,851,490
2024-8-9
https://stackoverflow.com/questions/78851490/is-it-possible-to-not-get-nan-for-the-first-value-of-pct-change
My DataFrame is: import pandas as pd df = pd.DataFrame( { 'a': [20, 30, 2, 5, 10] } ) Expected output is pct_change() of a: a pct_change 0 20 -50.000000 1 30 50.000000 2 2 -93.333333 3 5 150.000000 4 10 100.000000 I want to compare df.a.iloc[0] with 40 for the first value of pct_change. If I use df['pct_change'] = d...
You can use the fill_value keyword argument in pct_change. The pct_change documentation says: Additional keyword arguments are passed into DataFrame.shift or Series.shift. and Series.shift accepts a fill_value argument to fill missing rows. import pandas as pd df = pd.DataFrame({"a": [20, 30, 2, 5, 10]}) df["pct_chan...
5
5
78,850,424
2024-8-8
https://stackoverflow.com/questions/78850424/how-to-set-visual-studio-code-python-interpreter-to-a-python-virtual-environment
I have a python virtual environment in /Documents and a project in /Documents/Code/Python/example. I want to use this venv in my project but I can't get the vs code python interpreter to recognize that the venv in /Documents is a venv. I tried to use set the interpreter path by using the "Find..." button to manually se...
it could be that vscode didn't find the correct interpreter path. Are you creating a virtual environment using the command python -m venv myvenv? Or try restarting vscode after clearing the cache and then opening it up to create a new virtual environment. If you still can't recognize it, you can set the path to the vir...
2
1
78,850,502
2024-8-8
https://stackoverflow.com/questions/78850502/does-shelve-write-to-disk-on-every-change
I wish to use shelve in an asyncio program and I fear that every change will cause the main event loop to stall. While I don't mind the occasional slowdown of the pickling operation, the disk writes may be substantial. Every how often does shelve sync to disk? Is it a blocking operation? Do I have to call .sync()? If I...
shelve, by default, is backed by the dbm module, in turn backed by some dbm implementation available on the system. Neither the shelve module, nor the dbm module, make any effort to minimize writes; an assignment of a value to a key causes a write every time. Even when writeback=True, that just means that new assignmen...
5
5
78,850,381
2024-8-8
https://stackoverflow.com/questions/78850381/how-to-export-dask-html-high-level-graph-to-disk
There is a way to generate a HTML high level graph in a jupyter notebook as shown in dasks' documentation: https://docs.dask.org/en/stable/graphviz.html#high-level-graph-html-representation Taking the example from the docs, you put the following code in a jupyter cell import dask.array as da x = da.ones((15, 15), chunk...
By default, the Notebook interface will display the _repr_html_() method's output for whatever it's trying to display. In the case of a Dask Array, the dask attribute is an instance of a HighLevelGraph, whose implementation is here: https://github.com/dask/dask/blob/ed5f68897b3a097f7c5ec1a9ec13ce49c112a544/dask/highlev...
3
2
78,847,944
2024-8-8
https://stackoverflow.com/questions/78847944/using-xlsxwriter-in-python-how-insert-27-digit-number-in-cell-and-display-it-as
I'm writing an Excel using XLSXWRITER package in Python. Formats are applied to cells and this all works, except for one cell when the value assigned is a 27 digit text string (extracted from some source). I've read How to apply format as 'Text' and 'Accounting' using xlsxwriter. It suggests to set the number format to...
This may be a case where it is better to use write_string() instead of the more generic write().
1
4
78,849,429
2024-8-8
https://stackoverflow.com/questions/78849429/convert-the-same-local-time-to-utc-on-different-dates-respecting-the-local-dst
I have several local time points: import datetime from zoneinfo import ZoneInfo as zi wmr = datetime.time(hour=12, tzinfo=zi("GMT")) ecb = datetime.time(hour=14, minute=15, tzinfo=zi("CET")) jpx = datetime.time(hour=14, tzinfo=zi("Japan")) which I want to convert to UTC times given a date. E.g., local2utc(datetime.dat...
Python uses the IANA time zone database. The list of time zone names can be found here. According to this table, "GMT" is a time zone that has a 0 UTC offset and does not observe daylight saving. Perhaps "Europe/London" would give you the results you are looking for.
2
2
78,844,584
2024-8-7
https://stackoverflow.com/questions/78844584/have-regex-skip-a-match-if-it-occurs-within-1024-characters
I have the following regex.replace: self.reply = raw_reply.replace(b"<" + rcid + b":", b"") where rcid is a command reference. raw_reply is a huge mass of data in bytes e.g. <35:\x07\x98c\x45\x09 etc. I want it to remove all instances of, for example <35: but only if one has not been replaced less than 1024 character...
Use a regular expression that matches up to 1024 characters after the pattern you're replacing. Capture the excess 1024 characters in a capture group so you can copy them to the replacement. The next match will have to be after this, since overlapping matches are not processed. self.reply = re.sub(b"<" + rcid + b":(.{,...
3
3
78,847,998
2024-8-8
https://stackoverflow.com/questions/78847998/list-to-dataframe-with-row-and-column-headers
I need to convert a list (including headers) to a Dataframe. If I do it directly using pl.DataFrame(list), the headers are created and everything is kept as a string. Moreover, the table is transposed, such that the first element in the list becomes the first column in the dataframe. Input list. [ ['Earnings estimate',...
You can explicitly define the orient= to prevent transposition: pl.DataFrame(data[1:], orient="row", schema=data[0]) shape: (5, 5) ┌───────────────────┬─────────────────────────┬──────────────────────┬─────────────────────┬──────────────────┐ │ Earnings estimate ┆ Current qtr. (Jun 2024) ┆ Next qtr. (Sep 2024) ┆ Curre...
4
2
78,845,357
2024-8-7
https://stackoverflow.com/questions/78845357/python-polars-how-can-i-convert-the-values-of-a-column-with-type-enum-into
The polars user guide suggests that enums have a physical, integer representation. Is it possible to access the integers associated with an enum value? For example, is there a nicer way to get the integer representation in the following example? import numpy as np import polars as pl np.random.seed(556) enum_vals = [ "...
For this, pl.Expr.to_physical exists. The documentation also lists the dtype of the underlying physical representation, which is pl.UInt32 for pl.Categorical / pl.Enum. df.with_columns( pl.col("enum_vals").to_physical() ) shape: (5, 1) ┌───────────┐ │ enum_vals │ │ --- │ │ u32 │ ╞═══════════╡ │ 8 │ │ 5 │ │ 3 │ │ 2 │ │...
3
5
78,845,297
2024-8-7
https://stackoverflow.com/questions/78845297/how-do-define-custom-auto-imports-for-pylance-visual-studio-code
When I type out something like np. I think this triggers Visual Studio Code + Pylance's (not sure) auto-import completion by suggesting that import numpy as np might be relevant. I would like to create similar custom auto-import/complete associations. For example: between pl and polars, so that if I type something like...
This is tracked by an open enhancement request: Allow auto-import abbreviations to be configured #2589. I suggest that you give that discussion an upvote to show support for it. You can also subscribe to it to get notified about discussion and progress. Please avoid making noisy comments there like ones that just consi...
3
1
78,845,657
2024-8-7
https://stackoverflow.com/questions/78845657/python-playwright-locator-not-returning-expected-value
I'm not getting the expected value returned from the below code. from playwright.sync_api import sync_playwright import time import random def main(): with sync_playwright() as p: browser = p.firefox.launch(headless=False) page = browser.new_page() url = "https://www.useragentlist.net/" page.goto(url) time.sleep(random...
Your second locator XPath has no @class=, so it's different than the first one that works. Store the string in a variable so you don't have to type it twice or encounter copy-paste or stale data errors. In any case, your approach seems overcomplicated. Each user agent is in a <code> tag--just scrape that: from playwrig...
2
1
78,845,737
2024-8-7
https://stackoverflow.com/questions/78845737/convert-xml-file-into-dictionary-with-elementtree
I have an XML configuration file used by legacy software, which I cannot change or format. The goal is to use Python 3.9 and transform the XML file into a dictionary, using only xml.etree.ElementTree library. I was originally looking at this reply, which produces almost the expected results. Scenario.xml file contents:...
To get Scenario into the result, use tree.tag as the key in the outermost dictionary when calling the function. To handle nodes with no text, add the #text key to the dictionary in a separate statement, so it can be conditional. def format_xml_to_dictionary(element: ElementTree.Element): ''' Format xml to dictionary :p...
2
3
78,844,160
2024-8-7
https://stackoverflow.com/questions/78844160/getting-a-flat-view-of-a-nested-list
In Python, is it possible to get a flat view of a list of lists that dynamically adapts to changes to the original, nested list? To be clear, I am not looking for a static snapshot, but for a view that reflects changes. Further, the sub-lists should not be restricted to a primitive type, but be able to contain arbitrar...
You would need to create a class that holds a reference to the original lists. You don't want a copy of the lists, you just need a reference. This class knows how to access and update the values at each of the lists it holds. You can access any item in the list in O(log n) search complexity (binary search) without usin...
3
3
78,842,466
2024-8-7
https://stackoverflow.com/questions/78842466/split-a-polars-dataframe-into-multiple-chunks-with-groupby
Consider the following pl.DataFrames: import datetime import polars as pl df_orig = pl.DataFrame( { "symbol": [*["A"] * 10, *["B"] * 8], "date": [ *pl.datetime_range( start=datetime.date(2024, 1, 1), end=datetime.date(2024, 1, 10), eager=True, ), *pl.datetime_range( start=datetime.date(2024, 1, 1), end=datetime.date(20...
Here is a solution that fully stays within the polars expression API. The primary idea is to preprocess the helper dataframe into a dataframe of symbol, split_idx, and row_idx. Here, row_idx is the index of a row within a group defined by symbol and split index. It can serve as a "skeleton" and we can (after adding suc...
2
2
78,843,191
2024-8-7
https://stackoverflow.com/questions/78843191/numpy-on-small-arrays-elementary-arithmetic-operations-performances
I am not 100% positive that this question has a solution besides "that's the overhead, live with it", but you never know. I have a very simple set of elementary mathematical operations done on rather small 1D NumPy arrays (6 to 10 elements). The arrays' dtype is np.float32, while other inputs are standard Python floats...
I am not 100% positive that this question has a solution besides "that's the overhead, live with it", but you never know. Generally, Numpy is not optimized for computing small arrays (also for computing arrays where the last target axis is small too). For example, creating arrays, collecting them, analysing types, et...
3
2
78,843,497
2024-8-7
https://stackoverflow.com/questions/78843497/how-to-collect-process-local-state-after-multiprocessing-pool-imap-unordered-com
After using a Pool from Python's multiprocessing to parallelize some computationally intensive work, I wish to retrieve statistics that were kept local to each spawned process. Specifically, I have no real-time interest in these statistics, so I do not want to bear the overhead that would be involved with using a synch...
IDK if this is the best solution (could you just log to a file as you go, then parse the files from each child afterwards?), but you mentioned ensuring a task is evenly distributed to all workers. This would commonly be achieved with a Barrier. It is somewhat difficult to pass certain things to child processes like loc...
2
1
78,843,479
2024-8-7
https://stackoverflow.com/questions/78843479/use-pandas-operations-to-transpose-and-reindex
I have the following dataframe: Sample ID 'Deinococcus soli' Cha et al. 2014 16SrX (Apple proliferation group) 16SrXII (Stolbur group) 0 C1day1_barcode01 21 1 0 1 C1day21_barcode19 22 0 0 2 C3day1_barcode03 13 0 0 3 C3day14_barcode15 14 2 2 4 T1day21_barcode22 19 1 1 This is my desired output: Sample ID C1day1_barco...
set_index on the "Sample ID" column to set it aside, transpose to reshape, rename_axis to exchange the axis names, and reset_index to move back the IDs as column: out = (df.set_index('Sample ID').T .rename_axis(index='Sample ID', columns=None) .reset_index() ) Alternative: col = 'Sample ID' out = (df.set_index(col).T ...
2
2
78,843,358
2024-8-7
https://stackoverflow.com/questions/78843358/efficient-excel-sumif-equivalent-in-python
I am trying to figure out how to create the equivalent of SUMIF in Python. The solution I have currently works, but it is way too inefficient and it takes 20 minutes to run. What would be the most efficient way to reach the result that i want? Here is the what I am doing currently boiled down to a very simple form. In ...
For a more general approach, you can melt the sales_data to get a relationship between 'Product Dimensions' and 'sum_of_sales', then groupby on 'Product Dimensions', aggregate with sum, and merge it on conditions_data: sales_data = ( pd.melt( sales_data, id_vars=["sum_of_sales"], value_vars=sales_data.filter(like="Prod...
3
2
78,820,308
2024-8-1
https://stackoverflow.com/questions/78820308/how-can-i-call-a-java-class-method-from-python
I am making an Android app in Python using briefcase from BeeWare that must start a service. And I have this code... This is the relevant code from file MainActivity.java: package org.beeware.android; import com.chaquo.python.Kwarg; import com.chaquo.python.PyException; import com.chaquo.python.PyObject; import com.cha...
I found it! It goes like this... from org.beeware.android import MainActivity class Application(toga.App): # ...UI code here def start_tcp_service(self, widget): msg = 'START pressed!' print(msg); self.LogMessage(msg) self.CallJavaMethod('startMyService') def CallJavaMethod(self, method_name): MainActInst = MainActivit...
2
4
78,836,105
2024-8-5
https://stackoverflow.com/questions/78836105/why-isnt-the-pytest-addoption-hook-run-with-the-configured-testpaths-usag
Summary: I'm trying to set up a custom pytest option with the pytest_addoption feature. But when trying to configure my project with a project.toml file while using the said custom option, I'm getting the following error: $ pytest --foo foo ERROR: usage: pytest [options] [file_or_dir] [file_or_dir] [...] pytest: error:...
It looks like it indeed was an usage error (and also facepalm-worthy material): pytest --foo=bar rather than pytest --foo bar. $ pytest --foo bar ERROR: usage: pytest [options] [file_or_dir] [file_or_dir] [...] pytest: error: unrecognized arguments: --foo inifile: /home/vmonteco/code/MREs/pytest__addoption__pyproject_t...
2
2
78,839,084
2024-8-6
https://stackoverflow.com/questions/78839084/how-can-i-remove-nulls-in-the-process-of-unpivoting-a-polars-dataframe
I have a large polars dataframe that I need to unpivot. This dataframe contains lots of null values (at least half). I want to drop the nulls while unpivoting the dataframe. I already tried to unpivot the dataframe first and then filter it with drop_nulls() or similar approaches. However, this is too memory-intensive (...
Very likely you can make the operation more efficient in runtime and memory consumption by using pl.LazyFrames and polars' streaming engine. By using pl.LazyFrames, the melt / unpivot and filter / drop_nulls won't be operations eagerly, but first aggregated into a query plan. When collecting the lazy DataFrame (i.e. ma...
3
2
78,829,500
2024-8-3
https://stackoverflow.com/questions/78829500/querying-data-from-simbad-using-astroquery
I'm making a script in Python to get information for all objects from the NGC and IC catalogs. Actually, I already have this information from OpenNGC, however, coordinates don't have the same precision, so I need to combine both dataframes. What I want is: the name, RA in J2000, Dec in J2000 and the type. What I also w...
You're almost there. You can change a bit the ADQL by joining the table ident that contains all identifiers (and not only the main one), so that you don't miss any sources. The fluxes are in the table flux. I remove the duplicates with DISTINCT. SELECT DISTINCT TOP 100 main_id, otype, ra, dec, flux, flux_err, filter, f...
2
1
78,839,103
2024-8-6
https://stackoverflow.com/questions/78839103/how-to-return-plain-text-or-json-depending-on-condition
Is there a way to do something like this using FastAPI: @app.post("/instance/new", tags=["instance"]) async def MyFunction(condition): if condition: response = {"key": "value"} return response else: return some_big_plain_text The way it is coded now, the JSON is returned fine, but some_big_plain_text is not human frie...
It is just needed to add a FastAPI Response: from fastapi import FastAPI, Response @app.post("/instance/new", tags=["instance"]) async def MyFunction(condition): if condition: response = {"key": "value"} return response else: return Response(content=some_big_plain_text, media_type="text/plain")
3
0
78,814,860
2024-7-31
https://stackoverflow.com/questions/78814860/adding-status-text-to-a-textual-footer
I'm trying to create an enditor where the Footer contains the usual bindings on the left and some status information on the right, for example the line number. The Footer in textual is very simple so I thought to extend it, but I'm unable to see both my label and the binding of the base Footer. This is my code: class M...
I'd recommend solving this by laying out multiple widgets, instead of overriding the Footer class. The Footer widget uses dock: bottom; layout: grid; grid-columns: auto, which makes this a little tricky. But you can wrap the Footer in a fixed-sized container, and lay out your label next to that. from textual.app import...
3
4
78,839,287
2024-8-6
https://stackoverflow.com/questions/78839287/f2py-in-numpy-2-0-1-does-not-expose-variables-the-way-numpy-1-26-did-how-can-i
I used to run a collection of Fortran 95 subroutines from Python by compiling it via f2py. In the Fortran source I have a module with my global variables: MODULE GEOPLOT_GLOBALS IMPLICIT NONE INTEGER, PARAMETER :: N_MAX = 16 INTEGER, PARAMETER :: I_MAX = 18 INTEGER, PARAMETER :: J_MAX = 72 ... END MODULE GEOPLOT_GLOBA...
This must be a bug in f2py. See here: https://github.com/numpy/numpy/issues/27167 What got me unstuck is an ugly workaround: I simply added some useless dummy code to the module, like that: MODULE GEOPLOT_GLOBALS USE MOD_TYPES IMPLICIT NONE INTEGER, PARAMETER :: N_MAX = 16 INTEGER, PARAMETER :: I_MAX = 18 INTEGER, PARA...
4
3
78,836,505
2024-8-5
https://stackoverflow.com/questions/78836505/how-to-evaluate-nested-boolean-logical-expressions-in-python
I'm working on a complex rule parser that has the following properties: A space character separates rules A "+" character indicates an "AND" operator A "," character indicates an "OR" operator A "-" indicates an optional element Tokens in parenthesis should be evaluated together I'm able to do simple rules but having...
A great tool for this job would be a proper parser for expression grammars. I'm using parsimonious for this answer, which allows you to define a BNF or eBNF like syntax for your grammar, to assist with decoding your DSL. edit I updated the grammar to check the or "," operator before checking for the rule break operato...
5
3
78,838,421
2024-8-6
https://stackoverflow.com/questions/78838421/ollama-with-rag-for-local-utilization-to-chat-with-pdf
I am trying to build ollama usage by using RAG for chatting with pdf on my local machine. I followed this GitHub repo: https://github.com/tonykipkemboi/ollama_pdf_rag/tree/main The issue is when I am running code, there is no error, but the code will stop at embedding and will stop after that. I have attached all possi...
ChromaDB does not support large tokens of more than 768 I suggest we change the vector base to FAISS because the chroma has issues with dimensionality which is not comparable with the embedding model, to be precise the database chromadb allows 768 while embedding model offers 1028. Here is the reviewed code import logg...
4
3
78,828,009
2024-8-3
https://stackoverflow.com/questions/78828009/how-can-i-get-the-group-that-has-the-largest-streak-of-negative-numbers-in-a-col
This is an extension to this accepted answer. My DataFrame: import pandas as pd df = pd.DataFrame( { 'a': [-3, -1, -2, -5, 10, -3, -13, -3, -2, 1, 2, -100], 'b': [1, 2, 3, 4, 5, 10, 80, 90, 100, 99, 1, 12] } ) Expected output: a b 5 -3 10 6 -13 80 7 -3 90 8 -2 100 Logic: a) Selecting the longest streak of negatives ...
You can keep the same logic, just add one extra filtering step (e.g. with query) to get all max sizes, before getting the idxmax of sum of "b": # negative numbers m = df['a'].lt(0) # form groups g = m.ne(m.shift()).cumsum() out = df[g.eq(df[m] .groupby(g)['b'].agg(['size', 'sum']) .query('size == size.max()') ['sum'].i...
3
1
78,814,702
2024-7-31
https://stackoverflow.com/questions/78814702/toggle-geometry-layer-within-plotly-dash-mapbox
I've used the following post to plot maki symbols over a plotly mapbox. Plotly Mapbox Markers not rendering (other than circle) import dash from dash import Dash, dcc, html, Input, Output import dash_bootstrap_components as dbc import plotly.express as px import plotly.graph_objs as go import numpy as np import request...
The issue is the trailing commas: star = marker( dfi, "star", size=.1, color="red", lon=[-70, -80, -90], lat=[30, 40, 45] ), airport = marker( dfi, "airport", size=.1, color="green", lon=[-70, -80, -90], lat=[30, 40, 45] ), This causes both star and airport to be a tuple instead of a dict, and breaks the creation of t...
3
3
78,829,984
2024-8-3
https://stackoverflow.com/questions/78829984/configuring-pytest-to-find-tests-across-multiple-project-directories
I'm looking to unit test all my AWS Lambda code in my project using pytest. Due to how I have to configure the directory structure to work with infrastructure as code tooling, each Lambda sits within it's own CloudFormation stack, I've got a pretty non-standard directory structure. I'm unable to get pytest to run all t...
Managed to solve this after painstakingly going through different approachs. The solution is a combination of using the new(ish) importlib import mode and having some custom sys.path manipulation in conftest.py. Configure pytest.ini as this: [pytest] addopts = --import-mode=importlib Add the following code into confte...
4
1
78,841,209
2024-8-6
https://stackoverflow.com/questions/78841209/syntax-improvement-with-working-sympy-statement-novice-level-question
My question may be about how to avoid putting an array into another unneeded array in SymPy. There may be still more to the question I'm not aware of, though. But within my limitations, that is the question I have at hand. To make this question explicit and concrete, see the following... I want to compute the magnitude...
This is how I would approach it: from sympy import * init_printing() var("s") omega = symbols("omega", real=True, positive=True) # Butterworth(4) b4 = [ s**2 + s*(sqrt(2)*sqrt(2 - sqrt(2)) + sqrt(2)*sqrt(sqrt(2) + 2) + 2*sqrt(sqrt(2) + 2))/4 + 1, s**2 - s*(-sqrt(2)*sqrt(sqrt(2) + 2) - 2*sqrt(2 - sqrt(2)) + sqrt(2)*sqrt...
2
3
78,841,211
2024-8-6
https://stackoverflow.com/questions/78841211/how-to-get-the-dimensions-of-a-toga-canvas-in-python
In a Python BeeWare project, I want to use toga.Canvas to draw some horizontal rectangles, but I don't know from where to get the Canvas width. I can't find any documentation for the toga.Canvas() dimensions on the internet... def redraw_canvas(self): x = 4; y = 4; for i in range(7): with self.canvas.context.Fill(colo...
There doesn't appear to be any way to get this information from the public API, but there are some non-public properties used in the Toga Canvas example: canvas.layout.content_width canvas.layout.content_height These should work for any Toga widget, not just Canvas.
2
0
78,841,010
2024-8-6
https://stackoverflow.com/questions/78841010/format-datetime-in-polars
I have a polars dataframe that contains a datetime column. I want to convert this column to strings in the format %Y%m. For example, all dates in January 2024 should be converted to "202401". from datetime import datetime import polars as pl data = { "ID" : [1,2,3], "dates" : [datetime(2024,1,2),datetime(2024,1,3),date...
Note that pl.Expr.dt.strftime is available under the pl.Expr.dt namespace. Hence, it is called on the dt attribute of an expression and not the expression directly. df.with_columns( pl.col("dates").dt.strftime("%Y%m") ) shape: (3, 2) ┌─────┬────────┐ │ ID ┆ dates │ │ --- ┆ --- │ │ i64 ┆ str │ ╞═════╪════════╡ │ 1 ┆ 20...
7
5
78,839,874
2024-8-6
https://stackoverflow.com/questions/78839874/why-if-cant-be-used-in-scipy-optimize-inequality-constraint
Consider a simple question using Scipy.optimize: Maximize(xy) s.t x^2+y^2=200. The right code is this : import numpy as np from scipy.optimize import minimize def objective(var_tmp): x, y = var_tmp return -x * y def constraint(var_tmp): x, y = var_tmp return 200 - (x ** 2 + y ** 2) initial_guess = [1, 1] constraints = ...
By default, SciPy uses SLSQP to minimize a problem which has constraints. (Several other minimizers have support for constraints; see the "Constrained Minimization" section of the minimize() documentation.) SLSQP requires that its constraints be differentiable. Here is a passage from the SLSQP paper showing this. In th...
2
4
78,834,627
2024-8-5
https://stackoverflow.com/questions/78834627/replace-an-empty-value-with-nan-in-dataframe
I have a dataframe with empty values in some rows like this: ID Date Price Curr A Jan 21 (10,0) USD B Aug 8 (10,0) USD C Sep 29 (10,0) USD settle Aug 24 ( ,) where the last row has 2 empty values in Price and Curr columns. How can I either replace the empty values with nan so I can dropna() or drop the rows that conta...
To drop the rows that are empty, you can try something like this: import pandas as pd data = { "ID": ["A", "B", "C", "settle"], "Date": ["Jan 21", "Aug 8", "Sep 29", "Aug 24"], "Price": [(10, 0), (10, 0), (10, 0), ()], "Curr": ["USD", "USD", "USD", ""] } df = pd.DataFrame(data) # Filter out rows where Price is an empty...
2
1
78,832,340
2024-8-4
https://stackoverflow.com/questions/78832340/get-an-item-of-the-output-after-applying-str-split-to-a-polars-dataframe-column
how can i select last item of list in paths column after applying the str.split("/") function? dataNpaths = pl.scan_csv("test_data/file*.csv", has_header=True, include_file_paths = "paths").collect() dataNpaths.with_columns(pl.col("paths").str.split("/").alias("paths")) >>> dataNpaths.with_columns(pl.col("paths").str....
You should the List accessor .list which is similar to .str: dataNpaths.with_columns(pl.col("paths").str.split("/").list[-1]) .alias('paths') is superfluous as you are using the old column name not creating a new column. Alternatively as the last element of the List is needed, the same result can be obtained using a ....
3
3
78,829,950
2024-8-3
https://stackoverflow.com/questions/78829950/in-python-what-is-the-space-complexity-of-list1-list2
This code (a solution to this LeetCode challenge) first iterates through a list nums, updating counts of integers 0, 1, 2, also called red, white, and blue respectively. nums is guaranteed to only have the integers 0, 1, and/or 2. After finding the counts, the code uses [::], a trick to modify a list in-place, to sort ...
Your assessment that the code you've shown takes O(n) extra space to temporarily build a new list with the sorted values is correct. It's possible to do a counting sort like this in O(1) space, but the code to implement it in Python is just a little more complicated: def sortColors(nums: List[int]) -> None: red = white...
2
4
78,823,898
2024-8-2
https://stackoverflow.com/questions/78823898/measure-balanceness-of-a-weighted-numpy-array
I have player A and B who both played against different opponents. player opponent days ago A C 1 A C 2 A D 10 A F 100 A F 101 A F 102 A G 1 B C 1 B C 2 B D 10 B F 100 B F 101 B F 102 B G 1 B G 2 B G 3 B G 4 B G 5 B G 6 B G 7 B G 8 First, I want to find the opponent tha...
First, I think "balanceness" needs to consider how many days ago the matches were played. For example, suppose A and B played 1 match against C, both 100 days ago. Again, let A and B both play 1 match against E, 1 day and 199 days ago respectively. Although the number of matches is the same, their recency is different,...
6
3
78,836,766
2024-8-5
https://stackoverflow.com/questions/78836766/is-there-a-way-to-enforce-the-number-of-members-an-enum-is-allowed-to-have
Making an enum with exactly n many members is trivial if I've defined it myself: class Compass(enum.Enum): NORTH = enum.auto() EAST = enum.auto() SOUTH = enum.auto() WEST = enum.auto() ## or ## Coin = enum.Enum('Coin', 'HEADS TAILS') But what if this enum will be released into the wild to be subclassed by other users?...
An easier approach would be to check the number of Enum members of a subclass in an __init_subclass__ method: class Threenum(enum.Enum): def __init_subclass__(cls): if len(cls) != 3: raise TypeError('Subclass of Threenum must have exactly 3 members.') Demo here You can also create such a class with a factory function:...
5
4
78,835,754
2024-8-5
https://stackoverflow.com/questions/78835754/is-pythons-list-clear-thread-safe
In Python, suppose one thread is appending/popping items to/from a list/collections.deque/similar built-in container, while another thread occasionally empties the container via its clear() method. Is this interaction thread-safe? Or is it possible for the clear() to interfere with a concurrent append()/pop() operation...
update Methods like list.clear are not atomic in the sense that other threads can add elements to the list (or other container) before the method returns to the current code. They are "thread safe" in the sense that they won't ever be in an inconsistent state that will cause an exception - but not "atomic" . In other w...
2
5
78,836,369
2024-8-5
https://stackoverflow.com/questions/78836369/what-is-the-fastest-solution-to-remove-lines-from-a-text-file
In my project, I need to develop a program in Python to insert a UUID in a device. There will be 1.000 devices produced per day, the UUIDs need to be inserted into each device, and only once. I have a large input file (100.000 lines) containing all the available UUIDs, as follows: str[32] str[32] ... str[32] str[32] E...
Here: Here's how to remove used UUID to solve your issue: import os def next_uuid(in_file, used_file): used = set() if os.path.exists(used_file): with open(used_file) as f: used = set(l.strip() for l in f) with open(in_file) as f: for l in f: u = l.strip() if u not in used: with open(used_file, 'a') as uf: uf.write(f"{...
2
0
78,835,461
2024-8-5
https://stackoverflow.com/questions/78835461/i-am-trying-to-add-alt-text-to-images-inside-a-pdf-programatically
I have the ALT text generated just need to add it somehow to the images under the figure tag. A little background - I want to my my pdf accessible to the WCAG 2.1 AA standards and i am using adobe autotag feature to tag the pdf. It tags the images as /figure. I can totally extract the figures and generate alt text but ...
The MCID for Alt text is either allocated at time of PDF generation (so for this WEB.HTML page by the browsers PDF generator), or can be easily be manually assigned in a GUI, when checking for the other human verified content. Thus Acrobat pre-flight is the simplest and easiest point to index Alt Text in the mandatory ...
2
1
78,833,796
2024-8-5
https://stackoverflow.com/questions/78833796/reload-module-that-is-imported-into-init-py
What works: I have a package version_info in which I define a string version_info. When I increment version_info.version_info, the main code prints out the incremented value after the reload. What doesn't work: When I increment the value in version_info_sub.py, it is not updated upon reload. I suspect that the importli...
I think I got your problem. I made a reload_package function for you. import inspect def reload_package(package_): modules_names_paths = inspect.getmembers(package_, inspect.ismodule) modules_names = [x[0] for x in modules_names_paths] for module_name in modules_names: module_ = getattr(package_, module_name) reload(mo...
2
1
78,831,434
2024-8-4
https://stackoverflow.com/questions/78831434/new-column-in-pandas-dataframe-using-least-squares-from-scipy-optimize
I have a Pandas dataframe that looks like the following: Race_ID Date Student_ID feature1 1 1/1/2023 3 0.02167131 1 1/1/2023 4 0.17349148 1 1/1/2023 6 0.08438952 1 1/1/2023 8 0.04143787 1 1/1/2023 9 0.02589056 1 1/1/2023 1 0.03866752 1 1/1/2023 10 0.0461553 1 1/1/2023 45 0.09212758 1 1/1/2023 23 0.10879326 1 1/1/2023 1...
Here is how to parametrize and automatize your regression for each group. First we load your dataset: import io import numpy as np import pandas as pd from scipy import integrate, stats, optimize data = pd.read_fwf(io.StringIO("""Race_ID Date Student_ID feature1 1 1/1/2023 3 0.02167131 1 1/1/2023 4 0.17349148 1 1/1/202...
2
2
78,830,224
2024-8-4
https://stackoverflow.com/questions/78830224/how-can-i-get-around-an-unresolved-hostname-or-unrecognized-name-error-using-htt
I a trying to access a website's information programmatically, but on both Java and Python it is unable to resolve a hostname. If I specify the IP address, it changes the error to TLSV1_UNRECOGNIZED_NAME. This website is able to resolve without any additional work through any browser though. I have looked through a lot...
How can I get around an unresolved hostname or unrecognized name error using HTTP(S) in java or python? This is most likely not a problem in the Java or Python code1. A failure to resolve a DNS name is most likely caused by: not talking to the correct DNS server(s), or a failure in the authoritative server, or a cha...
2
3
78,831,215
2024-8-4
https://stackoverflow.com/questions/78831215/how-to-plot-a-histogram-as-a-scatter-plot
How to plot a similar graph in python? import matplotlib.pylab as plt import numpy as np from scipy.stats import binom y = binom.rvs(n = 10, p = 0.5, size = 100) counts, bins = np.histogram(y, bins=50) plt.scatter(bins[:len(counts)], counts) plt.grid() plt.show()
First off, when the data is discrete, the bin edges should go in between the values. Simply setting bins=50 chops the distance between the lowest and the highest value into 50 equally-sized regions. Some of these regions might get no values if their start and end both lie between the same integers. To show the values i...
4
2
78,832,050
2024-8-4
https://stackoverflow.com/questions/78832050/405-method-not-allowed-error-for-post-request-by-flask-app
I have a simple web app to message (using Twilio API) selected respondents with the following code: app.py client = Client(account_sid, auth_token) @app.route('/') def index(): return render_template('index.html') @app.route('/send_sms',methods=['POST']) def send_sms(): message = request.form['message'] selected_groups...
I think I understand the problem. I think the procedures you're following are: You have your index.html open in VS Code. You clicked "Go Live" in order to start Live Server. When using your form, it returns a 405 in browser, like this: I see the exact same header information that you describe when I follow these pro...
2
2
78,830,658
2024-8-4
https://stackoverflow.com/questions/78830658/how-to-achieve-the-same-rolling-result-in-polars-as-in-pandas-with-duplicate-tim
I am working with both pandas and polars for rolling operations, but I am encountering different results when dealing with duplicate timestamps. I want to replicate the pandas behavior in polars. Here’s an example illustrating the issue with rolling_sum: Pandas Code: import pandas as pd import polars as pl data = { "ti...
AFAIK there are currently no parameters of pl.DataFrame.rolling or pl.Expr.rolling_sum_by allowing to control the handling of duplicate values in the by column. This would probably make a good feature request. Until then, you could explicitly aggregate all values in the window into a list column. For duplicate values i...
3
2
78,829,918
2024-8-3
https://stackoverflow.com/questions/78829918/is-there-any-way-to-know-when-im-passed-the-last-item-while-iterating-through-a
I'm trying to create a text representation of a JSONField that has some data structured as an array of dictionaries like this: [ { "key1":"value1", "key2":"value2" }, { "key3":"value3", "key4":"value4", "key5":"value5" } ] My goal is to represent this data in the Django template like this: ( key1=value1 & key2=value2...
Just found it! Silly me, Seems like Django already provides a pretty neat built-in forloop object for templates that works like a charm! Will drop it here for anyone who might have the same problem {% for k,v in dict %} k=v {% if forloop.last != True %} &amp; {% endif %} {% endfor %}
2
1
78,829,678
2024-8-3
https://stackoverflow.com/questions/78829678/is-there-a-way-to-do-this-with-a-list-comprehension
I have a list that looks something like this: data = ['1', '12', '123'] I want to produce a new list, that looks like this: result = ['$1', '1', '$2', '12', '$3', '123'] where the number after the $ sign is the length of the next element. The straightforward way to do this is with a for loop: result = [] for element ...
You can do it with two loops: result = [item for s in data for item in (f"${len(s)}", s)] ['$1', '1', '$2', '12', '$3', '123']
3
7
78,817,543
2024-7-31
https://stackoverflow.com/questions/78817543/griddb-tql-invalid-column
I'm currently working with GridDB for a project involving IoT data, and I'm facing an issue with executing SQL-like queries using GridDB's TQL (Time Series SQL-like Query Language). Here is a brief description of what I am trying to achieve: I have a container in GridDB which stores IoT sensor data. I am trying to quer...
By default, SQL column names are case insensitive in some languages like MYSQL. TQL is case sensitive though. change value to Value: query = ts.query("SELECT * FROM sensorData WHERE Value > 26")
2
2
78,828,192
2024-8-3
https://stackoverflow.com/questions/78828192/what-caused-python-3-13-0b3-compiled-with-gil-disabled-be-slower-than-3-12-0
I did a simple performance test on python 3.12.0 against python 3.13.0b3 compiled with a --disable-gil flag. The program executes calculations of a Fibonacci sequence using ThreadPoolExecutor or ProcessPoolExecutor. The docs on the PEP introducing disabled GIL says that there is a bit of overhead mostly due to biased r...
From the latest question edits, it seems the version of Python-3.13 used for testing was built with debug mode enabled and without optimisations enabled. The former flag in particular can have a large impact on performance testing, whilst the latter will have a much smaller, but still significant, impact. In general, i...
5
4
78,828,636
2024-8-3
https://stackoverflow.com/questions/78828636/valueerror-while-saving-a-dataframe
I am facing hurdle while saving a pandas data frame to parquet file Code I am using - import pandas as pd import yfinance as yf start_date = "2022-08-06" end_date = "2024-08-05" ticker = 'RELIANCE.NS' data = yf.download(tickers=ticker, start=start_date, end=end_date, interval="1h") data.reset_index(inplace=True) data['...
Your code worked for me without any issues. I assume this issue is arising from the parquet engine that you are using to save the file as parquet( io.parquet.engine, pyarrow or fastparquet). Here are the versions of the libraries I have used: Pandas version: 2.2.2 PyArrow version: 16.1.0 To make sure you are using pya...
3
0
78,828,151
2024-8-3
https://stackoverflow.com/questions/78828151/is-there-a-way-to-prevent-setup-from-launching-a-browser-for-each-test-method
I'm practicing writing test cases for web automation and I have written functions to test login, find my username in the user home page and test logout functionality of GitHub. However, I've learned through both experience and reading that setUp() is initiated before each test method, and my problem is that before ever...
In python unittest you have 3 levels of setup / teardown. Method level: setUp / tearDown: called before / after each test method. Class level: setUpClass / tearDownClass: called before / after tests in an individual class. Module level: setUpModule / tearDownModule: called before / after tests in an individual module....
2
1
78,825,612
2024-8-2
https://stackoverflow.com/questions/78825612/trouble-resizing-widgets-in-custom-tkinter-when-going-into-another-page
I was trying to use the set_widget_scale function to resize my widgets based on the resolution of the window, when I resize the widgets on the main page it works fine when the resolution is chosen, when I go to the other page it raises this error: ("_tkinter.TclError: invalid command name ".!ctkoptionmenu.!dropdownmenu...
This method avoids using destroy constantly. Instead, it uses frames to separate pages. You can destroy the frames when not used, as demonstrated by the added destroy button. import customtkinter as ct class App(ct.CTk): def __init__(self): super().__init__() self.title("Test") self.geometry("640x480") self.end_button ...
2
1
78,827,639
2024-8-3
https://stackoverflow.com/questions/78827639/playwright-issue-with-the-footer-template-parsing
Playwright (Python) save a page as PDF function works fine when there's no customisation in the header or footer. However, when I try to introduce a custom footer, the values don't seem to get injected appropriately. Example code: from playwright.sync_api import sync_playwright def generate_pdf_with_page_numbers(): wit...
From the Playwright docs, header_template (which has the same format as footer_template) provides a number of magic class names you can use to inject certain pieces of data into the page: from playwright.sync_api import sync_playwright # 1.44.0 def generate_pdf_with_page_numbers(): with sync_playwright() as p: browser ...
2
2
78,827,479
2024-8-2
https://stackoverflow.com/questions/78827479/any-efficient-way-to-create-a-heatmap-matrix
Given a set of coordination and values like coors=np.array([[0,0],[1,1],[2,2]]) heat_values=[3,2,1] I would like to generate a matrix like mtx=[[3,0,0], [0,2,0], [0,0,1]] Any functions can do the jobs?
I would use numpy.zeros and indexing: mtx = np.zeros(coors.max(0)+1, dtype=int) mtx[tuple(coors.T)] = heat_values Output: array([[3, 0, 0], [0, 2, 0], [0, 0, 1]]) NB. if heat_values is an array, better use dtype=heat_values.dtype. This should generalize to any dimension of coors: coors=np.array([[1,0,0],[0,1,1],[0,2,...
2
3
78,817,794
2024-7-31
https://stackoverflow.com/questions/78817794/how-to-preserve-input-and-output-values-when-adding-new-tabs
I'm encountering a peculiar issue when developing my Python shiny app. My app currently has the functionality to dynamically generate new tabs with the press of a navset tab called "+". However, after pressing "+", the state (including input and output values) of the previous tabs reset back to empty. Is there a way to...
The reason for the reset is that the navset_tab is re-rendered each time a new nav_panel gets appended. So an approach would be better where we have the navset_tab outside of the server and then append a nav_panel on click without re-rendering everything. The difficulty is on the one hand that ui.insert_ui does not see...
2
1
78,826,115
2024-8-2
https://stackoverflow.com/questions/78826115/how-to-make-a-barplot-with-a-double-grouped-axis-using-pandas
I am working on a plot where I want to show two groups on one axis and a third group as fill-value. The problem is, that when I plot it, the y-axis shows values in tuples: data_dict = {'major_group': list(np.array([['A']*10, ['B']*10]).flat), 'minor_group': ['q ','r ','s ','t ']*5, 'legend_group':np.repeat(['d','e','f'...
This code will create horizontal stacked bars, grouped hierarchically in the y-axis label: import matplotlib.pyplot as plt import pandas as pd import numpy as np from pandas import DataFrame def create_data() -> DataFrame: data_dict = { 'major_group': list(np.array([['A'] * 10, ['B'] * 10]).flat), 'minor_group': ['q', ...
2
1
78,824,983
2024-8-2
https://stackoverflow.com/questions/78824983/python-str-subclass-with-lazy-evaluation-of-its-value-for-argparse
I am building a command-line program that uses argparse. In the (assumed-to-be) rare case of a wrong call, argparse will show a description string supplied when creating the ArgumentParser. I want this description to show the version number of my program. I want to extract this from the pyproject.toml file via tomllib....
In a roundabout way: don't set description, and only set it just before ArgumentParser would format the help. import argparse import time class MyArgParser(argparse.ArgumentParser): def format_help(self): if not self.description: print("Now thinking hard...") time.sleep(3) self.description = "An application!" return su...
2
1
78,824,984
2024-8-2
https://stackoverflow.com/questions/78824984/cannot-use-selector-in-polars-dataframe-unpivot
I cannot use the pl.exclude() selector as index in pl.DataFrame.unpivot despite the documentation of this method type hinting the index parameter as follows. index: 'ColumnNameOrSelector | Sequence[ColumnNameOrSelector] | None' = None The follow code can be used to reproduce the error. import polars as pl df = pl.Data...
pl.exclude is a "regular" polars expression (of type pl.Expr). Selectors are special objects (also expressions, but of a specific subtype cs._selector_proxy_) that can be found in pl.selectors. import polars.selectors as cs column_list = ['baz', 'qux'] df.unpivot(column_list, index=cs.exclude(column_list)) shape: (6, ...
4
5
78,824,444
2024-8-2
https://stackoverflow.com/questions/78824444/django-url-reset-after-authentication-fail
if user is not None: login(request, user) return redirect('home') else: error_message = "Invalid username or password." return render(request, 'login.html', {'error_message': error_message}) Using the above code, if user enters wrong credentials, login.html shows up successfully with error message. But now the URL is...
The issue with the action mentioned in the html page in form tag. you must have something like <form method="post" action="authentication_view/"> To solve the issue, best way is to remove the action from form tag. by default html form submit to same page. do something like this. <form method="post"> If you are loading...
2
1
78,824,119
2024-8-2
https://stackoverflow.com/questions/78824119/pytest-doesnt-found-my-settings-directory
I tried to start pytest but the settings file cannot be found by pytest I'm in virtualenv with Python 3.11.9 and pytest 8.3.2 ImportError: No module named 'drf.settings' pytest-django could not find a Django project (no manage.py file could be found). You must explicitly add your Django project to the Python path to ha...
You need to add pythonpath within the pytest.ini as follows: [pytest] pythonpath = drf DJANGO_SETTINGS_MODULE = drf.settings python_files = test_*.py Or you can change the layout of the tests and move the pytest.ini from the project's root to the tests folder like this SO post. Note: use drf.settings instead of drf.s...
2
1
78,824,644
2024-8-2
https://stackoverflow.com/questions/78824644/what-is-the-best-way-to-return-the-group-that-has-the-largest-streak-of-negative
My DataFrame is: import pandas as pd df = pd.DataFrame( { 'a': [-3, -1, -2, -5, 10, -3, -13, -3, -2, 1, 2, -100], } ) Expected output: a 0 -3 1 -1 2 -2 3 -5 Logic: I want to return the largest streak of negative numbers. And if there are more than one streak that are the largest, I want to return the first streak. I...
Your code is fine, you could simplify it a bit, avoiding the intermediate columns: # get sign s = np.sign(df['a']) # form groups of successive identical sign g = s.ne(s.shift()).cumsum() # keep only negative, get size per group and first group with max size out = df[g.eq(df[s.eq(-1)].groupby(g).size().idxmax())] Or, s...
3
1
78,823,597
2024-8-2
https://stackoverflow.com/questions/78823597/space-complexity-of-dijkstra
I was working on some Leetcode questions for Dijkstra's algorithm and I do not quite understand the space complexity of it. I looked online but I found various answers and some were rather complicated so I wanted to know if I understood it correctly. # initialize maxheap maxHeap = [(-1, start_node)] heapq.heapify(maxHe...
Since I use a visit set and a priority queue to keep track of the nodes would the space complexity just simply be O(V) where V is the number of vertices in the graph? For what concerns the set: yes. In the worst case, the target is the last node that could be visited, and then set will in the end have an entry for ev...
3
0
78,822,168
2024-8-1
https://stackoverflow.com/questions/78822168/use-polars-when-then-otherwise-on-multiple-output-columns-at-once
Assume I have this dataframe import polars as pl df = pl.DataFrame({ 'item': ['CASH', 'CHECK', 'DEBT', 'CHECK', 'CREDIT', 'CASH'], 'quantity': [100, -20, 0, 10, 0, 0], 'value': [99, 47, None, 90, None, 120], 'value_other': [97, 57, None, 91, None, 110], 'value_other2': [94, 37, None, 93, None, 115], }) ┌────────┬─────...
You can pass list of column names into pl.col() and when\then\otherwise accepts Expr which can contain multiple columns. cols = ['value', 'value_other', 'value_other2'] df.with_columns( pl .when((pl.col.quantity != 0) | pl.col.value.is_not_null()) .then(pl.col(cols)) .otherwise(0) ) # or df.with_columns( pl .when(pl.co...
9
6
78,823,052
2024-8-1
https://stackoverflow.com/questions/78823052/what-does-python3-t-do
$ python3 -t -c 'print("hello world")' hello world What does -t do? It's not mentioned in python3 --help. Usually unknown options cause a non-zero exit code, like $ python3 -r Unknown option: -r usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ... Try `python -h' for more information.
The -t option in python3 was a feature from Python 2.x that warned about inconsistent use of tabs and spaces in the source code. However, this option was removed in Python 3.x. Therefore, when you run python3 -t -c 'print("hello world")', Python 3 just ignores the -t option and executes the code as usual.
5
3
78,821,557
2024-8-1
https://stackoverflow.com/questions/78821557/assigning-an-attribute-to-a-staticmethod-in-python
I have a scenario where I have objects with static methods. They are all built using an outside def build_hello() as class variables. def build_hello(name: str): @staticmethod def hello_fn(): return "hello my name is " # Assign an attribute to the staticmethod so it can be used across all classes hello_fn.first_name = ...
Method retrieving from a class, in Python, be it regular instance methods, class methods or static methods, use an underlying mechanism to actually build the method object at the time it is requested (usually with the . operator, but also with a getattr(...) call): The objects that are bound to class namespaces have a ...
5
4
78,820,057
2024-8-1
https://stackoverflow.com/questions/78820057/how-can-i-find-the-maximum-value-of-a-dynamic-window-and-the-minimum-value-below
This is my DataFrame: import pandas as pd df = pd.DataFrame( { 'a': [3, 1, 2, 5, 10, 3, 13, 3, 2], } ) Expected output is creating a a_max and a_min: a a_max a_min 0 3 NaN NaN 1 1 3 1 2 2 3 1 3 5 3 1 4 10 3 1 5 3 10 3 6 13 10 3 7 3 13 3 8 2 13 2 Logic: I explain the logic row by row. There is a dynamic window for th...
This is a tricky one, I would use a cummax+shift, then mask+ffill to compute a_max. Then a_min is the groupby.cummin per group of identical a_max: # compute the shifted cummax cm = df['a'].cummax().shift() # a_max is the cummax except if the current row is larger df['a_max'] = cm.mask(df['a'].gt(cm)).ffill() # a_min is...
2
2
78,816,181
2024-7-31
https://stackoverflow.com/questions/78816181/how-can-i-link-the-records-in-the-training-dataset-to-the-corresponding-model-pr
Using scikit-learn, I've set up a regression model to predict customers' maximum spend per transaction. The dataset I'm using looks a bit like this; the target column is maximum spend per transaction during the previous year: customer_number | metric_1 | metric_2 | target ----------------|----------|----------|------- ...
The error you are computing is the absolute error. When averaged it gives the Mean Absolute Error which is commonly used to evaluate regression models. You can read about the choice of an error metric here. This error vector is the length of your test dataset and its elements are in the same order as your records. Many...
3
2
78,818,244
2024-7-31
https://stackoverflow.com/questions/78818244/get-a-single-row-in-a-tuple-indexed-dataframe
I have a pandas DataFrame: >>> f = pd.DataFrame.from_dict({"r0":{"c0":1,"c1":2},("r",1):{"c0":3,"c1":4}},orient="index") c0 c1 r0 1 2 (r, 1) 3 4 I can get the 1st row: >>> list(f.loc["r0"].items()) [('c0', 1), ('c1', 2)] but not the second row because f.loc[("r",1)] raises KeyError. I suppose I can do >>> list(f.loc[...
Try using cross-section to get values from multiple indices. list(f.xs(("r", 1)).items())
2
5
78,816,780
2024-7-31
https://stackoverflow.com/questions/78816780/how-do-i-combine-mimetypefilters-and-namefilters-for-a-qfiledialog-using-pyqt6-o
Using PyQt6, I am investigating using QFileDialog directly without the use of one of the static functions (i.e. don't use QFileDialog.getOpenFileName). The issue that I am running into is creating a filter list that uses a combination of MIME types and named types. For example, say you want to set a filter for *.css an...
Combining mime-filters and name-filters is quite easy to achieve using QMimeDatabase. Doing things this way will allow you to merge glob patterns (e.g. *.qss with the css defaults), as well as getting full control over the final ordering of the filters. This won't normally be possible when using the QFileDialog methods...
2
3
78,817,557
2024-7-31
https://stackoverflow.com/questions/78817557/is-it-possible-to-solve-leetcode-1653-using-recursion
I am trying to solve LeetCode problem 1653. Minimum Deletions to Make String Balanced: You are given a string s consisting only of characters 'a' and 'b'​​​​. You can delete any number of characters in s to make s balanced. s is balanced if there is no pair of indices (i,j) such that i < j and s[i] = 'b' and s[j]= 'a'...
It is the memory needed for your memo data structure that is the major contribution to the error you get. You could avoid keying by tuple, and pre-allocate your memo as two lists, like so: memo = { "a": [None] * len(s), "b": [None] * len(s) } ...and adapt your code to align with this structure. So: if memo[last_char...
2
1
78,817,297
2024-7-31
https://stackoverflow.com/questions/78817297/how-to-control-recursion-depth-in-pydantic-s-model-dump-serialization
I have the following classes: class Info: data: str class Data: info: Info When I call model_dump in Data class, pydantic will serialize the classe recursively as described here This is the primary way of converting a model to a dictionary. Sub-models will be recursively converted to dictionaries. Is there any way t...
Converting to a dictionary solves this: >>> data = Data(info=Info(data='test')) >>> dict(data) {'info': Info(data='test')}
3
3
78,816,988
2024-7-31
https://stackoverflow.com/questions/78816988/how-to-delete-row-with-max-min-values
I have dataframe: one N th 0 A 5 1 1 Z 17 0 2 A 16 0 3 B 9 1 4 B 17 0 5 B 117 1 6 XC 35 1 7 C 85 0 8 Ce 965 1 I'm looking the way to keep alternating 0101 in column three without doubling 0 or 1. So, i want to delete row with min of values in case if i have two repeating 0 in column th and max values if i have repeat...
using a custom groupby.idxmax You can swap the sign if "th" is 1 (to get the max instead of min), then set up a custom grouper (with diff or shift + cumsum) and perform a groupby.idxmax to select the rows to keep: out = df.loc[df['N'].mul(df['th'].map({0: 1, 1: -1})) .groupby(df['th'].ne(df['th'].shift()).cumsum()) .id...
3
3
78,815,902
2024-7-31
https://stackoverflow.com/questions/78815902/reading-writing-polars-data-frame-with-list-column-from-to-database
Writing a df with a list column like so df = pl.DataFrame({'a': [1,2,3], 'b':[['A','B'], ['C', 'D'], ['E', 'F']]}) df.write_database( "test", "sqlite:///test.db", if_table_exists = "replace", ) works fine, but then running pl.read_database_uri(query="SELECT * FROM test", uri="sqlite://test.db") gives the error Runtim...
I believe that that in your case you'll need to save list of strings as BLOB in MySQL lite and later somehow decode bytes back to list. However there is two problems: polars standard protocol connectorx can't read BLOB columns, thus you need to swith to adbc Even after switching to adbc it is not clear how to convert ...
3
2
78,816,652
2024-7-31
https://stackoverflow.com/questions/78816652/multiply-polars-columns-of-number-type-with-object-type-which-supports-mul
I have the following code. import polars as pl class Summary: def __init__(self, value: float, origin: str): self.value = value self.origin = origin def __repr__(self) -> str: return f'Summary({self.value},{self.origin})' def __mul__(self, x: float | int) -> 'Summary': return Summary(self.value * x, self.origin) def __...
Remember that Polars is designed so that computations run in Rust, not Python, where it's like 1000x faster. If you have Python operations you want to run, you lose a lot of the benefit of using Polars in the first place. But, thankfully, Polars does have a very nice feature that is relevant here, which is “native” pro...
3
5
78,817,193
2024-7-31
https://stackoverflow.com/questions/78817193/how-is-type-not-a-keyword-in-python
In Python 3.12 we have type aliases like this: Python 3.12.4+ (heads/3.12:99bc8589f0, Jul 27 2024, 11:20:07) [GCC 12.2.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> type S = str >>> S S By this syntax I assumed that, from now, the type word is considered a keyword, but it's not...
The PEG parser introduced in Python 3.9 is a lot more flexible than the old parser, so it's just capable of handling this kind of thing. Trying to make type a keyword would have broken too much existing code, so they just... didn't. match/case is a similar story - making those keywords would have broken way too much co...
4
7
78,815,235
2024-7-31
https://stackoverflow.com/questions/78815235/problem-with-seaborn-kdeplot-when-plotting-two-figures-side-by-side
I am trying two plot two 2d distributions together with their marginal distributions on the top and side of the figure like so: Now I wantto combine the above figure with the following figure, such that they appear side by side: However, when doing so, the marginal distributions arent plotted.. Can anyone help? The ...
You can't do this directly as the marginal distributions require a jointplot, which is a figure-level plot and cannot directly add extra axes. It's however fairly easy to modify the JointGrid code to add more axes. The key is to change: # add more space to accommodate an extra plot # gs = plt.GridSpec(ratio + 1, ratio ...
2
2
78,814,853
2024-7-31
https://stackoverflow.com/questions/78814853/create-a-widget-factory-in-qt
Hello~ I'm creating a set of custom widgets that extend the native widgets in Qt. My custom widgets are supposed to be constructed from a data source, and they all provide a custom function Foobar. For example: class CheckBox: public QCheckBox, public Control { Q_OBJECT public: CheckBox(QWidget* parent = 0); CheckBox(D...
So you want to have QWidget*s with additional interface Foobar. I am afraid it might not be possible, not in a straightforward C++ way, without wrapper classes, e.g. similar to setupUi(parentPtr); pattern used by Qt User Interface Compiler . Qt doesn't allow multiple inheritance from QObject, so you cannot design your ...
3
4
78,814,153
2024-7-31
https://stackoverflow.com/questions/78814153/i-cant-install-pyinstaller-from-command-line-in-debian-linux
I wanted Pyinstaller on my Debian machine, so I ran the following command: sudo pip3 install pyinstaller This returned the following error: error: externally-managed-environment × This environment is externally managed ╰─> To install Python packages system-wide, try apt install python3-xyz, where xyz is the package you...
As the error message states, you would need to install through apt to install globally, if that's not available for whaterver reason, the next best thing is to install that package into a virtual environment of some sort (e.g. with virtualenv env and then source env/bin/activate to activate the virtual environment). In...
2
1
78,802,547
2024-7-27
https://stackoverflow.com/questions/78802547/compute-minimum-area-convex-k-gon-in-2d
I am trying to solve the following problem: given a set of points P and a value k, find the area of the smallest convex k-gon defined by a subset of points S of P with |P| = n and |S| = k. I found this paper describing an algorithm solving the problem in O(kn^3) (which is exactly what I need, considering in my case k c...
I changed the function get_slope_clockwise(pj, P). The original function can not ensure the correct order using the absolute value of the slope. Absolute values can lead to points on opposite sides of the line (with positive and negative slopes) being treated as equivalent, which can disrupt the desired clockwise order...
3
1
78,809,996
2024-7-30
https://stackoverflow.com/questions/78809996/how-to-load-templates-in-django-for-specific-application
So I am learning Django at in advanced level. I already know how to include templates from BASE_DIR where manage.py is located. However I wanted to know how to locate templates in the specific app in Django. For example, I have a project named mysite and an app called polls. I then specify the templates directory in se...
If you have the app specific templates located at polls/templates/polls/, then you need to add that path to TEMPLATES in settings.py as shown below: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'polls/templates')], # here the app template path is set 'APP...
2
3
78,794,422
2024-7-25
https://stackoverflow.com/questions/78794422/matplotlib-plot-not-responding-in-vscode-debug-mode
I'm encountering an issue when trying to plot a simple graph using Matplotlib in Python while in debug mode in VSCode. The plot works perfectly in normal execution mode, but when I set a breakpoint and run the code in debug mode, the plot window becomes unresponsive. Example Code: import matplotlib.pyplot as plt # Samp...
I also had this issue. I got it working again by running Python 3.11.9 instead of 3.12.*, and I also had to switch to matplotlib 3.8.3 instead of 3.9.*. Has been driving me crazy for a couple weeks. So, try setting up a virtual environment in VSCode with matplotlib 3.8.3 and switching your interpreter to 3.11.9 in that...
2
9
78,796,828
2024-7-26
https://stackoverflow.com/questions/78796828/i-got-this-error-oserror-winerror-193-1-is-not-a-valid-win32-application
I trying to run an Python file today and got this error below! Anyone know what's issue and the solution to fix it? Traceback (most recent call last): File "C:\Users\Al PC\PycharmProjects\Fe\report_auto-final-v2.7.py", line 60, in <module> driver = webdriver.Chrome(service=chrome_service, options=options) # ChromeDrive...
If you construct the service like this: service = ChromeService(ChromeDriverManager().install()) I noticed ChromeDriverManager().install() returns <path stuff>\chromedriver-win32\THIRD_PARTY_NOTICES.chromedriver instead of the chromedrive.exe. This works for me: chrome_install = ChromeDriverManager().install() folder ...
9
26
78,802,585
2024-7-27
https://stackoverflow.com/questions/78802585/abbreviating-dataclass-decorator-without-losing-intellisense
Scenario Suppose I want to create an alias for a dataclasses.dataclass decorator with specific arguments. For example: # Instead of repeating this decorator all the time: @dataclasses.dataclass(frozen=True, kw_only=True) class Entity: ... # I just write something like this: @struct class Entity: ... The static analyze...
Decorate struct() with dataclass_transform(frozen_default = True, kw_only_default = True): (playgrounds: Mypy, Pyright) # 3.11+ from typing import dataclass_transform # 3.10- from typing_extensions import dataclass_transform @dataclass_transform(frozen_default = True, kw_only_default = True) def struct[T](cls: type[T])...
4
3
78,806,812
2024-7-29
https://stackoverflow.com/questions/78806812/third-party-notices-chromedriver-exec-format-error-undetected-chromedriver
undetected_chromedriver with webdriver_manager was working well few days ago for scraping websites but out of nowhere it started throwing the error: OSError: [Errno 8] Exec format error: '/Users/pd/.wdm/drivers/chromedriver/mac64/127.0.6533.72/chromedriver-mac-x64/THIRD_PARTY_NOTICES.chromedriver' I am guessing it is ...
The command ChromeDriverManager().install(): creates a new folder without the executable and it retrieves the wrong file. First, you need to remove the .wdm folder and then reinstall webdriver-manager: Windows Location: r"C:\Users\{user}\.wdm" Linux Location: /home/{user}/.wdm Mac Location: /Users/{user}/.wdm rm -rf...
18
31
78,808,819
2024-7-29
https://stackoverflow.com/questions/78808819/issue-with-polars-and-polars-talib
I'm fairly new to programming as a whole and I'm trying to learn using Polars with the polars_talib library. However when I import polars_talib I get the following error: ModuleNotFoundError Traceback (most recent call last) Cell In[19], line 8 6 import mintalib as mt 7 import pandas_ta as pta ----> 8 from polars.utils...
This issue has been fixed in the latest version of the library. Please update to version 0.1.3, which now supports Polars v1, to resolve the problem.
2
0
78,788,533
2024-7-24
https://stackoverflow.com/questions/78788533/preventing-the-gibbs-phenomenon-on-a-reverse-fft
i am currently filtering some data and ran into trouble, when filtering smaller frequencies from a large trend.The Reverse FFTs seem to have large spikes at the beginning and the ending. Here is the Data before and after filtering smaller frequencies. I have looked into the mathematic phenomenon and it is called the Gi...
Following the suggestion of Martin Brown's comment, the following code subtracts a ramp before FFT and adds it back after IFFT (I needed to make up my own values for Sensor_4, Values_per_second, and time, as the corresponding variables were missing in the question, so you might need to tune the parameters to match your...
4
2