question_id int64 59.5M 79.7M | creation_date stringdate 2020-01-01 00:00:00 2025-07-15 00:00:00 | link stringlengths 60 163 | question stringlengths 53 28.9k | accepted_answer stringlengths 26 29.3k | question_vote int64 1 410 | answer_vote int64 -9 482 |
|---|---|---|---|---|---|---|
79,068,019 | 2024-10-8 | https://stackoverflow.com/questions/79068019/is-there-a-more-efficient-way-to-get-x-z-slices-from-a-stack-of-x-y-images | I have a CT scan of an object: images with pixels in an x-y grid, one image per z value. I want to make x-z images, to view the object from a different angle. The most obvious way to do this: load all the images into a 3D array like bigImageArray[x,y,z] and save the slices bigImageArray[:,y,:] for each value of y. The ... | let's say you can fit n x-y or n x-z images into memory. Load up n x-y images and use them to write out n width x n x n "blocks". Repeat until you've covered z. Then, load up all the blocks that have y=0, and use them to write out n x-z images. Repeat until you've covered y. | 2 | 1 |
79,065,880 | 2024-10-8 | https://stackoverflow.com/questions/79065880/pytest-overriding-production-database-with-test-database | I have started writing tests for my FastAPI/SQLAlchemy app and I would like to use a separate empty database for tests. I added an override in my conftest.py file but the function override_get_db() never gets called. As a result, tests are run on the production database and cannot get them to run on the testing databas... | There is a problem with the way you're trying to override get_db: app.dependency_overrides[get_db] = override_get_db override_get_db is a fixture. You can't use fixtures for dependencies. There are many possible solutions. From what I see, currently you only need the database for your client, so you could add all logi... | 3 | 3 |
79,067,196 | 2024-10-8 | https://stackoverflow.com/questions/79067196/multiprocess-with-joblib-and-skimage-picklingerror-could-not-pickle-the-task-t | I'm trying to parallelize the task of finding minimum cost paths through a raster cost surface, but I keep bumping into the same PicklingError: Could not pickle the task to send it to the workers. This is a code example of what's going on: import numpy as np from skimage.graph import MCP_Geometric import timeit from jo... | This is because MCP_Geometric is unpickable. You need to move initialization of this class into task function: import numpy as np from skimage.graph import MCP_Geometric import timeit from joblib import Parallel, delayed np.random.seed(123) cost_surface = np.random.rand(1000, 1000) pois = [(np.random.randint(0, 1000),... | 2 | 1 |
79,067,236 | 2024-10-8 | https://stackoverflow.com/questions/79067236/collatzs-hypothesis-want-to-reuse-code-instead-of-repeating | I am trying to learn python and came across this Collatz's hypothesis where I need to take any non-negative and non-zero integer number as input and if it's even, evaluate a condition otherwise, if it's odd, evaluate another condition if number ≠ 1, go back to even condition. I am checking same condition multiple times... | Because you loop through it and regularly check for c0 being 1 and c0 not being 0, why not just use that as the while condition? Using it would make the break check unnecessary. Additionally, you don't need to use a while loop to check for even or odd numbers. Instead, you can use one while loop and conditionals inside... | 1 | 2 |
79,066,478 | 2024-10-8 | https://stackoverflow.com/questions/79066478/django-reusable-many-to-one-definition-in-reverse | I'm struggling to make a Many-to-one relationship reusable. Simplified, let's say I have: class Car(models.Model): ... class Wheel(models.Model): car = models.ForeignKey(Car) ... Pretty straight forward. What, however, if I'd like to use my Wheel model also on another model, Bike? Can I define the relationship in reve... | If I understand correctly, you will need to "subclass" from a parent model. For instance, Vehicle: class Vehicle(models.Model): pass class Bike(Vehicle): pass class Wheel(models.Model): vehicle = models.ForeignKey( Vehicle, on_delete=models.CASCADE, related_name='wheels', ) Now to access the Wheel instances from a Bik... | 1 | 1 |
79,066,076 | 2024-10-8 | https://stackoverflow.com/questions/79066076/distinguish-native-type-from-user-type | I want to be able to distinguish some native class like _functools.partial (code, code) from some user-class like: class MyClass: pass I want to test this from within Python (so not using the CPython API or so). But it's ok if this only works with CPython. It should work for CPython >=3.6. How? More specifically, I wa... | While playing around, I noticed that all entries in Py_tp_members will always become corresponding member descriptors in the type. And you can check for those, via inspect.ismemberdescriptor (which just checks isinstance(object, types.MemberDescriptorType)). I think this type of descriptor would not be used otherwise. ... | 2 | 1 |
79,059,046 | 2024-10-6 | https://stackoverflow.com/questions/79059046/how-to-get-images-in-beautifulsoup-from-javascript | At my shcool we have a interactive white boards and we can export them to a website with a provided link. Only problem is that the links expire (which is stupid), so I want to make a simple python script that gets the images and downloads them. Here is the link to the website: https://air.ifpshare.com/documentPreview.h... | Note: this answer contains different methods to reach your goal. I saw your target web app fetching image download URLs from an API endpoint and it is easy to fetch those images using the requests library with a little bit of code (no need to use bs4 if you want). here is the API endpoint https://air.ifpshare.com/api/p... | 1 | 2 |
79,066,206 | 2024-10-8 | https://stackoverflow.com/questions/79066206/python-pandas-groupby-two-columns-without-merging-them | My dataframe looks like this: | col1 | col2 | col3 | | ---- | ---- | ---- | | 1 | abc | txt1 | | 1 | abc | txt2 | | 2 | abc | txt3 | | 1 | xyz | txt4 | | 2 | xyz | txt5 | I want to merge the text in col3 between rows only if the rows have the same value in col1 AND the rows have same value in col2. Expected result: | ... | A possible solution, which: Performs a group-by operation using two columns, col1 and col2, as the grouping keys. It then aggregates the values in col3 for each group by applying a lambda function that concatenates the values into a single string, with each value separated by a comma. (df.groupby(['col1', 'col2'], ... | 1 | 1 |
79,063,686 | 2024-10-7 | https://stackoverflow.com/questions/79063686/how-to-catch-throw-and-other-exceptions-in-coroutine-with-1-yield | I have var DICTIONARY, which is a dictionary where the keys are English letters and the values are words that start with the corresponding letter. The initial filling of DICTIONARY looks like this: DICTIONARY = { 'a': 'apple', 'b': 'banana', 'c': 'cat', 'd': 'dog', } My code has 2 while loops, since higher try-except ... | I believe that there is two errors. First - is that you are using while True: block twice. I would simplify the code into smth like this: def alphabet(): while True: try: letter = yield #waiting for first input from send try: word = DICTIONARY[letter] except KeyError: word = 'default' # return 'default', if key is not ... | 1 | 2 |
79,063,091 | 2024-10-7 | https://stackoverflow.com/questions/79063091/fastapi-stateful-dependencies | I've been reviewing the Depends docs, official example from typing import Annotated from fastapi import Depends, FastAPI app = FastAPI() async def common_parameters(q: str | None = None, skip: int = 0, limit: int = 100): return {"q": q, "skip": skip, "limit": limit} @app.get("/items/") async def read_items(commons: Ann... | Is there an appropriate way to pass a stateful instance of a class object across methods? Yes, you could use lifespan for this: import asyncio from contextlib import asynccontextmanager from fastapi import FastAPI, Depends, Request from typing import AsyncIterator, TypedDict import joblib import boto3 import os class... | 2 | 2 |
79,063,987 | 2024-10-8 | https://stackoverflow.com/questions/79063987/mypy-reporting-problem-namedtuple-type-as-an-attribute-is-not-supported | I have the following class, and MyPy is reporting the problem NamedTuple type as an attribute is not supported for the self.Data attribute. from collections import namedtuple from collections.abc import MutableSequence class Record(MutableSequence): def __init__(self, recordname: str, fields: list, records=None): if re... | This makes a lot of sense if you consider how namedtuple works. It's a code-generator, and it creates a new type. Therefore, if you use it during the class init like this, you will be generating a new type per-instance, and different instances of Record will have different types for self.Data, even if they have the sam... | 2 | 2 |
79,063,140 | 2024-10-7 | https://stackoverflow.com/questions/79063140/modulenotfounderror-no-module-named-distutils-msvccompiler-when-trying-to-ins | I'm working inside a conda environment and I'm trying to downgrade numpy to version 1.16, but when running pip install numpy==1.16 I keep getting the following error: $ pip install numpy==1.16 Collecting numpy==1.16 Downloading numpy-1.16.0.zip (5.1 MB) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 5.1/5.1 MB 10.8 MB/s eta ... | What seemed to solve this issue was installing a specific version of setuptools (<65) into the conda environment: conda install "setuptools <65" | 2 | 6 |
79,052,036 | 2024-10-3 | https://stackoverflow.com/questions/79052036/bloomberg-python-query-returning-unknown-valueerror | I am trying to query specific Bloomberg tickers and write them into an excel. The code itself is pretty straightforward and I have gotten it to work for all tickers except "Move Index". When querying for the this particular ticker, I am getting the exception: raise ValueError(data) ValueError: []. I blocked out the par... | Short answer: change the ticker to MOVE Index or move Index. Long answer: The Bloomberg API does not seem to accept mixed case tickers (but does accept mixed case fields). Using the low-level blpapi: import blpapi sessionOptions = blpapi.SessionOptions() sessionOptions.setServerHost('localhost') sessionOptions.setServe... | 2 | 1 |
79,062,434 | 2024-10-7 | https://stackoverflow.com/questions/79062434/conda-downgrading-numpy-during-package-update | I have a virtual Conda environment named dev that was created using the following YAML file: # *** dev.yml *** name: dev channels: - defaults # Check this channel first - conda-forge # Fallback to conda-forge if packages are not available in defaults dependencies: - python==3.12 - numpy>=2.0.1 # ...more libraries witho... | It is likely that an update to one of the packages might have pinned the newest version to use numpy less that v2. To override this behavior, you can pin a version during the update: conda update --all numpy=2.* Or you can pin the package by adding the package spec to the file at <environment>/conda-meta/pinned before... | 2 | 1 |
79,062,305 | 2024-10-7 | https://stackoverflow.com/questions/79062305/check-for-duplicates-in-a-column-while-excluding-a-sub-string | I am looking for an optimized way of checking for any duplicates in a Panda dataframe column, but excluding a given position in every element of that column. In the example there is a duplication in 'id1_ver1_ready' if we exclude the version number ('id1_ver1_ready' <-> 'id1_ver3_ready'). Same for ( 'id5_ver1_unknown' ... | Another possible solution, which filters df by removing duplicate entries based on the first and third parts of the ID column: The str.split('_', expand=True) method splits the ID strings at the underscores into separate columns, resulting in a dataframe where each part of the ID is in its own column. The duplicated(... | 2 | 1 |
79,061,156 | 2024-10-7 | https://stackoverflow.com/questions/79061156/sympy-tr8-trigonometric-linearization-not-working-as-expected | I'm using SymPy version 1.13.3 to integrate an expression involving trigonometric functions. My goal is to linearize trigonometric products using the TR8 function from sympy.simplify.fu. However, the results with and without linearization should be identical, but they are not. Here's a simplified version of my code: im... | The problem is that you are using float numbers with symbolic integration, which sometimes leads to wrong results. When doing symbolic integration, always use exact numbers. Use sympy's nsimplify to convert floats to rational. integrand_2 = integrand.nsimplify() integrand_3 = linearize_trigo_expr(integrand_2) r2 = inte... | 1 | 2 |
79,046,408 | 2024-10-2 | https://stackoverflow.com/questions/79046408/remove-special-character-and-units-form-pandas-column-name-with-python | I'm working on a script to convert a data file from one format to another. I need to remove the special characters from the column headers. I am using Pandas to read a CSV file with the below structure. I'm looking for a tidy way to remove the [units] form the column name. Data File: Date ,Time ,app1_sum [Ml] ,app1_q [... | You can use the following code to replace all brackets and their content in the columns names: df.rename(columns=lambda x: re.sub(r'\[[^\]]+\]', '', x), inplace=True) \[ will match the opening bracket [ [^\]]+ will match an abtritrary number of every character except ] \] will match the closing bracket The \ are neede... | 2 | 2 |
79,061,819 | 2024-10-7 | https://stackoverflow.com/questions/79061819/check-if-any-value-in-a-polars-dataframe-is-true | This is quite a simple ask but I can't seem to find any clear simplistic solution to this, feels like I'm missing something. Let's say I have a DataFrame of type df = pl.from_repr(""" ┌───────┬───────┬───────┐ │ a ┆ b ┆ c │ │ --- ┆ --- ┆ --- │ │ bool ┆ bool ┆ bool │ ╞═══════╪═══════╪═══════╡ │ false ┆ true ┆ false │ │ ... | These two options are a bit shorter and stay in pure Polars. # Unpivot all the booleans into a single "value" column # Pull the "value column out as a Series any do the any df.unpivot()["value"].any() # pl.all().any() checks for any True values per column # pl.any_horizontal() checks horizontally per row, reducing to a... | 3 | 2 |
79,057,984 | 2024-10-5 | https://stackoverflow.com/questions/79057984/multiple-versions-of-single-jupyter-notebook-for-different-audiences-e-g-tutor | I'm working on creating assignments for students using Jupyter Notebooks. My goal is to generate different versions of the same Notebook to distribute to tutors and students. I need certain cells, such as those containing exercise solutions, to be included only in the tutor's version, while other cells should be exclus... | This is all built in to nbconvert. You can just do: # ensure all output has been produced jupyter nbconvert tutor-source-only.ipynb --to notebook \ --execute --output tutor-with-output.ipynb # remove cells that you want the students to figure out on their own and # optionally remove the output of some/all cells, so the... | 1 | 1 |
79,059,427 | 2024-10-6 | https://stackoverflow.com/questions/79059427/is-np-zeros-is-the-fastest-way-to-initiate-a-1d-numpy-boolean-array-of-trues | Trying to find the fastest method to initiate a 1D numpy array of True values. %timeit -n 100000 -r 30 np.ones(10000, dtype=bool) returns 750 ns ± 35.7 ns whereas %timeit -n 100000 -r 30 ~np.zeros(10000, dtype=bool) returns 682 ns ± 7.47 ns Behaviour probably depends on the array size but is there a general rule of thu... | np.frombuffer(bytearray().ljust(10000, b"\x01"), dtype=bool) is faster than empty or full. Benchmark results for NumPy 1.22.4: $ python3 -m timeit -s 'import numpy as np' 'np.ones(10000, dtype=bool)' 100000 loops, best of 5: 2.12 usec per loop $ python3 -m timeit -s 'import numpy as np' '~np.zeros(10000, dtype=bool)' 2... | 3 | 5 |
79,059,021 | 2024-10-6 | https://stackoverflow.com/questions/79059021/incrementing-to-the-last-decimal-in-python | I want to write function in python when given float or string for example 0.003214 to return me 0.003215, but if I give it 0.00321 to return 0.003211, it will apply on other floats also like 0.0000324 -> 0.00003241. What is wrong with my solution and how do I fix it? def add_one_at_last_digit(v): after_comma = Decimal(... | Here is a working solution from decimal import Decimal def add_one_at_last_digit(v: float | str) -> float: d = Decimal(str(v)) decimal_places = abs(d.as_tuple().exponent) add = Decimal(f"1e-{decimal_places}") result = (d + add).quantize(Decimal(f"1e-{decimal_places}")) return float(result) The key ideas are: d = Deci... | 4 | 11 |
79,057,153 | 2024-10-5 | https://stackoverflow.com/questions/79057153/python-multiprocessing-with-multiple-locks-slower-than-single-lock | I am making experiments with multiprocessing in Python. I wrote some code that requires concurrent modification of 3 different variables (a dict, a float and an int), shared across the different process. My understanding of the works behind locking tells me that if I have 3 different shared variables, it will be more e... | This has nothing to do with the locking, you are just sending 3 locks per call instead of 1, which is 3 times the transmission overhead. to verify this you can test keep sending the 3 locks but only use 1 of them, you will get the same time as using the 3 locks change 2 of the locks to be simple Manager.Value objects,... | 2 | 1 |
79,058,482 | 2024-10-6 | https://stackoverflow.com/questions/79058482/is-there-a-way-to-prevent-repetition-of-similar-blocks-of-code-in-these-hashing | I created this program to calculate the sha256 or sha512 hash of a given file and digest calculations to hex. It consists of 5 files, 4 are custom modules and 1 is the main. I have two functions in different modules but the only difference in these functions is one variable. See below: From sha256.py def get_hash_sha25... | You could union these 2 functions into a single one: import hashlib def get_hash(hash_type): if hash_type == 'sha256': hash_obj= hashlib.sha256() elif hash_type == 'sha512': hash_obj = hashlib.sha512() else: print("Invalid hash type.Please choose 'sha256'or'sha512'") return filename = input("Enter the fileename: ") try... | 5 | 5 |
79,056,942 | 2024-10-5 | https://stackoverflow.com/questions/79056942/can-i-improve-my-numpy-solution-to-an-exercise | I have been asked to use the following set of column indices: y = np.array([3, 0, 4, 1]) to turn into 1 all the elements in the following matrix: x = np.zeros(shape = (4, 5)) that have y as starting column and rows given by the position of y. Just to be clear. The final result has to be the following: [[0. 0. 0. 1. 1... | Lots of ways of doing this. For example, since x is basically a boolean mask, you can compute a mask and turn it into whatever type you want: x = (np.arange(5) < y[:, None]).astype(float) You might also use np.where to avoid the conversion: x = np.where(np.arange(5) < y[:, None], 1.0, 0.0) | 4 | 3 |
79,057,529 | 2024-10-5 | https://stackoverflow.com/questions/79057529/indexerror-index-7-is-out-of-bounds-for-axis-0-with-size-7 | I am trying to assess whether the lips of a person are moving too much while the mouth is closed (to conclude it is chewing). The mouth closed part is done without any issue, but when I try to assess the lip movement through landmarks (dlib) there seems to be a problem with the last landmark of the mouth. Inspired by t... | lip = shape[61:68] The slices exclude the end element. So you got 7 elements: 61,62,63,64, 65,66,67. And len(lip) == 7 confirms that. If there truly are 8 points for the lip shape, and they include element 68, the slice should be: lip = shape[61:69] assert(len(range(61, 69) == 8) assert(len(lip) == 8) Note that if sh... | 3 | 3 |
79,056,727 | 2024-10-5 | https://stackoverflow.com/questions/79056727/lalr-grammar-for-transforming-text-to-csv | I have a processor trace output that has the following format: Time Cycle PC Instr Decoded instruction Register and memory contents 905ns 86 00000e36 00a005b3 c.add x11, x0, x10 x11=00000e5c x10:00000e5c 915ns 87 00000e38 00000693 c.addi x13, x0, 0 x13=00000000 925ns 88 00000e3a 00000613 c.addi x12, x0, 0 x12=00000000 ... | For $ to mean end-of-line, you need to add the m, i.e. MULTILINE flag DECODED_INSTRUCTION: / ... /xim | 2 | 1 |
79,056,585 | 2024-10-5 | https://stackoverflow.com/questions/79056585/beautifulsoup-in-python-find-works-as-unexpected-way-with-tuples | I am practicing crawling web, and yesterday I had an unexpected correct result which I dont think it should be work. I used soup.find(id=i) to find the attribute key i, I though i must be string, but when I passed a tuple - which is first element of tuple is string that is key, and I was surprise when it still ran corr... | I searched the BeautifulSoup source code And found 3 occurrences where it checks if something is a tuple. I haven't went to the whole chain of calls, but it seems to me that whenever you pass tuples or lists as arguments, BeautifulSoup will turn it into a space-separated string, and will further checks for every values... | 2 | 1 |
79,055,467 | 2024-10-4 | https://stackoverflow.com/questions/79055467/whats-a-fast-way-to-identify-all-overlapping-sets | I need to identify and consolidate all intersecting sets so that I ultimately have completely discrete sets that share no values between them. The sets currently exist as values in a dictionary, and the dictionary keys are sorted by priority that needs to be preserved. For example, starting with the following sets in d... | This is a graph problem, you can use networkx.connected_components: # pip install networkx import networkx as nx # make graph G = nx.from_dict_of_lists(d) # identify connected components sets = {n: c for c in nx.connected_components(G) for n in c} # keep original order out = {n: sets[n] for n in d} Output: {'b': {'a',... | 2 | 2 |
79,054,792 | 2024-10-4 | https://stackoverflow.com/questions/79054792/apply-pandas-dictionary-with-gt-lt-conditions-as-keys | I have created the following pandas dataframe: ds = {'col1':[1,2,2,3,4,5,5,6,7,8]} df = pd.DataFrame(data=ds) The dataframe looks like this: print(df) col1 0 1 1 2 2 2 3 3 4 4 5 5 6 5 7 6 8 7 9 8 I have then created a new field, called newCol, which has been defined as follows: def criteria(row): if((row['col1'] > 0)... | Yes, you could do this with IntervalIndex: dic = {(0, 2): 'A', (2, 3): 'B', } other = 'C' bins = pd.IntervalIndex.from_tuples(dic) labels = list(dic.values()) df['newCol'] = (pd.Series(labels, index=bins) .reindex(df['col1']).fillna(other) .tolist() ) But given your example, it seems more straightforward to go with cu... | 2 | 1 |
79,053,694 | 2024-10-4 | https://stackoverflow.com/questions/79053694/pyotp-couldnt-pass-the-same-secret-key-to-multiple-methods | I am implementing a forgot password feature on my application. In order to generate the otp code I have used the pyotp library. The code generates the otp code but when I try to reset the password using the generated password, it shows the error that "the verification code has beeen expired" but the otp code here has t... | You generate new secret key at your Method to reset password , that's why this happens. Instead, you should use secret key from created VerificationCode. Here is simple example: First of all, you need to save this secret key: secret = pyotp.random_base32() totp = pyotp.TOTP(secret,interval=settings.verification_code_... | 1 | 2 |
79,052,892 | 2024-10-4 | https://stackoverflow.com/questions/79052892/in-a-class-body-is-it-safe-to-use-vars-to-dynamically-set-an-attribute | In Python, I can use vars() to dynamically set class attributes class A: vars()['x'] = 1 print(A.x) # Prints 1 However, the documentation for vars() states Without an argument, vars() acts like locals(). Note, the locals dictionary is only useful for reads since updates to the locals dictionary are ignored. This ind... | In the very early versions of Python, all namespaces, whether in functions, classes or modules, were all implemented as a dictionary. But for performance reasons, since Python 1.0, the implementation of function namespaces was changed to use the STORE_FAST and LOAD_FAST bytecodes to access local variables as indices in... | 1 | 2 |
79,052,587 | 2024-10-4 | https://stackoverflow.com/questions/79052587/vs-code-1-94-run-selection-line-in-python-terminal-very-slow | I've just started using VSCode (moving over from Spyder) and I regularly run lines/selections from my code in the terminal. When I have a terminal open, shift + enter runs my selection in a new terminal and is incredibly slow. The below takes about 5 seconds to send print(1) If i copy and paste it in the new terminal... | As for the delay, according to this post on GitHub, the issue seems to be with the latest version (v2024.16.0) of the Python extension for VS Code. Downgrading it (and restarting the app) seems to do the trick for the time being. | 2 | 2 |
79,052,139 | 2024-10-3 | https://stackoverflow.com/questions/79052139/numpy-random-uniform-valid-bounds-for-double | numpy.random.uniform returns a double between the specified low and high bounds. I can use np.finfo(np.double) to get the min and max representable number, but if I use those values in numpy.random.uniform I get an error. import numpy as np info = np.finfo(np.double) np.random.uniform(low=info.min, high=info.max) Ove... | uniform actually performs low + (high-low) * np.random.random(). However high - low is not possible: info.max-info.min # RuntimeWarning: overflow encountered in scalar subtract info.max-info.min You found the limits of uniform. The difference between low and high should not exceed abs(info.max). np.random.uniform(low=... | 1 | 2 |
79,051,048 | 2024-10-3 | https://stackoverflow.com/questions/79051048/folium-map-refuses-to-fill-the-height-of-its-container | I am trying to display a folium map in a card in a shiny for Python app using the code below (Reproducible example): from shiny import App, ui, render, reactive import folium app_ui = ui.page_fluid( ui.tags.style( """ /* apply css to control height of some UI widgets */ .map-container { height: 700px !important; width:... | This is an issue with folium, where m._repr_html_() causes the map to be embedded within a div which has padding-bottom: 60%; by default. This has to be overwritten if you want to use the whole space. Below is an example where this is done by just replacing the css with more suitable one, in particular, I remove the pa... | 1 | 2 |
79,050,277 | 2024-10-3 | https://stackoverflow.com/questions/79050277/create-hybrid-table-with-snowflake-sqlalchemy | I want to add Snowflake hybrid tables to my database schema using SQLAlchemy. Per this issue, support for hybrid tables is not implemented in the Snowflake SQLAlchemy official dialect. Is there a way for me to customize the CREATE TABLE ... statement generated by SQLAlchemy so that it actually generates CREATE HYBRID T... | You can pass prefixes to a table. from sqlalchemy import create_engine from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column class Base(DeclarativeBase): ... class SomeTable(Base): __tablename__ = "some_table" __table_args__ = {"prefixes": ["HYBRID"]} id: Mapped[int] = mapped_column(primary_key=True) engine... | 1 | 2 |
79,048,601 | 2024-10-2 | https://stackoverflow.com/questions/79048601/filtering-a-list-based-on-the-values-of-another-list-in-polars | Let's say I have the following DataFrame: df = pl.DataFrame({ 'values': [[0, 1], [9, 8]], 'qc_flags': [["", "X"], ["T", ""]] }) I only want to keep my values if the corresponding qc_flag equals "". Does anyone know the correct way to go about this? I've tried something like this: filtered = df.with_columns( pl.col("va... | pl.Expr.list.eval to evaluate expression within list. pl.arg_where() to find indexes where value is "". pl.Expr.list.gather() to take sublist by indexes. df.with_columns( filtered = pl.col.values.list.gather( pl.col.qc_flags.list.eval(pl.arg_where(pl.element() == "")) ) ) shape: (2, 3) ┌───────────┬───────────┬─────... | 6 | 2 |
79,046,568 | 2024-10-2 | https://stackoverflow.com/questions/79046568/netgraph-animation-how-to-display-frame-numbers | I'm trying to add a frame number to a simulation visualization modified from here. Is there any simple way to add a frame number to this animation so that it displays as a part of the plot title? import numpy as np import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation from netgraph import Graph... | When animating while using blit (blit=True), figure level titles cannot be changed, as blit caches everything outside of the axis being animated. The simplest change is to set blit to false, and then update the figure title within the animation update function. import numpy as np import matplotlib.pyplot as plt from ma... | 2 | 1 |
79,045,172 | 2024-10-2 | https://stackoverflow.com/questions/79045172/why-is-the-snake-increasing-its-speed-when-it-grows | I am working on the famous snake game in Python and I've stumbled upon a glitch where the snake starts doing when it eats food. The snake should keep constant speed throughout the game and the segments should be of equal distance from each other. But what happens is every time the snake eats food it increases its speed... | The move method looks incorrect: def move(self): for seg_num in range(len(self.segments) - 1, 0, -1): self.head.forward(MOVE_DISTANCE) # Moving distance of head new_x = self.segments[seg_num - 1].xcor() new_y = self.segments[seg_num - 1].ycor() self.segments[seg_num].goto(new_x, new_y) I don't think you want to move t... | 2 | 5 |
79,048,582 | 2024-10-2 | https://stackoverflow.com/questions/79048582/error-when-trying-to-apply-a-conditional-statement-to-sympy | I'm trying to set a conditional statmeent in sympy so that when the iterable is not equal to a certain number (30) in this case, it returns 0. My code is: def formula(address): address0 = 30 logic = 3 * x # Define the symbol and the summation range x = symbols('x') expr = Piecewise( (x + logic, logic == address0), # Wh... | The == operator will instantly evaluate to True or False based on structure of the objects. Since 3*x is not 30 the equality evaluates to False and that term of the Piecewise is ignored. Use the following instead: ... from sympy import Eq expr = Piecewise( (x + logic, Eq(logic,address0)), (0, True)) # (x+logic)-(x-logi... | 1 | 2 |
79,048,534 | 2024-10-2 | https://stackoverflow.com/questions/79048534/conditional-marker-for-scatterplot-matplotlib | I am trying to plot x1 and x2 against each other, and if class == 1, then marker should be +, if class == 0, then the marker should just be a dot. The file.csv is structured like this, the class column which is the conditional will only be either 1 or 0: x1 x2 mark 1 2 0 9 4 1 0 5 1 2 6 0 Here's the cod... | I would plot it this way for all the data, if you're going to select a subset, consider using a new dataframe to select the subset: import matplotlib.pyplot as plt # the rows where class is 1 and plot them with '+' marker plt.scatter(df[df['class']==1]['x1'], df[df['class']==1]['x2'], marker='+') # the rows where class... | 1 | 1 |
79,046,761 | 2024-10-2 | https://stackoverflow.com/questions/79046761/im-trying-to-make-the-petals-rotate-from-the-color-orange-yellow-to-orange-as | I'm doing an assignment on using turtles to make sunflower petals using pentagons. Everything is as it should be, except for the color of the petals. It strictly says that the colors of said pentagons have to be in a rotation of "orange, yellow, orange, yellow" with it repeating from there on. To do so we have to use f... | You just need to think about the order in which you do things - it's sequential unless told otherwise. Make sure that you set a colour BEFORE using it to draw a petal. Make sure that you update c every time the colour changes, or you will simply output "black". def draw_sunflower(tur, speed, n_sided, radius, num_petal)... | 4 | 2 |
79,046,060 | 2024-10-2 | https://stackoverflow.com/questions/79046060/what-is-the-type-hint-for-the-pytest-fixture-capsys | When writing pytest tests for a function that is supposed to print something to the console, to verify the output string I am using the capsys fixture and capsys.readouterr(). This is the code I am currently using: @pytest.mark.parametrize( "values,expected", [ ([], "guessed so far: \n"), (["single one"], "guessed so f... | Per the documentation for capsys, it: Returns an instance of CaptureFixture[str]. This class indeed has a readouterr method (returning a CaptureResult, which has an out attribute). So your test should look like: @pytest.mark.parametrize( # ... ) def test_print_guesses(capsys: pytest.CaptureFixture[str], values: list,... | 2 | 2 |
79,045,268 | 2024-10-2 | https://stackoverflow.com/questions/79045268/generate-all-possible-boolean-cases-from-n-boolean-values | If two fields exist, the corresponding fields are Boolean values. x_field(bool value) y_field(bool value) I want to generate all cases that can be represented as a combination of multiple Boolean values. For example, there are a total of 4 combinations that can be expressed by two Boolean fields as above. x_field(tr... | I'm surprised no one has proposed this simple one-liner yet... from itertools import product fields = ['x', 'y', 'z'] [dict(zip(fields, values)) for values in product([True,False], repeat=len(fields))] Output: [{'x': True, 'y': True, 'z': True}, {'x': True, 'y': True, 'z': False}, {'x': True, 'y': False, 'z': True}, {... | 1 | 4 |
79,045,061 | 2024-10-2 | https://stackoverflow.com/questions/79045061/how-to-avoid-memory-error-for-large-dataarray | In Python I have a large xarray dataarray (da) of the shape In [1]: da.shape Out[1]: (744, 24, 30, 131, 215) I need to perform the operation da = 10**da however, I'm running into a memory error MemoryError: Unable to allocate 56.2 GiB for an array with shape (744, 24, 30, 131, 215) and data type float32 Is there a w... | Chunking the dataarray did the trick. da = da.chunk({'dim0':50,'dim1': 24, 'dim2': 30, 'dim3': 131, 'dim4': 215}) da = 10**da | 2 | 0 |
79,044,320 | 2024-10-1 | https://stackoverflow.com/questions/79044320/passing-in-arguments-to-dependency-function-makes-it-recognized-as-a-query-param | Take a look at the following Route Handler @some_router.post("/some-route") async def handleRoute(something = Depends(lambda request : do_something(request, "some-argument"))): return JSONResponse(content = {"msg": "Route"}, status_code = 200) So the dependency function do_something takes in a request and a string val... | My current solution to this is the following: def get_do_something(value: str): async def fixed_do_something(request: Request): return await do_something(request, roles) return fixed_do_something Notice how instead of directly passing the request with your additional parameters, you are now using a wrapper function. T... | 2 | 2 |
79,042,147 | 2024-10-1 | https://stackoverflow.com/questions/79042147/handling-on-off-behavior-in-milp-optimization-problems-in-gekko | I'm trying to understand how to implement ON/OFF behavior in optimization problems to be solved in GEKKO effectively. Consider the following scenario: 2 power generators, with upper and lower bounds one generator has a power loss of 30% the total generated power must meet an external power demand the goal is to minimi... | As you correctly noted, when gen1 can only operate above the lower bound (gen1_lb) or at 0, use a binary variable gen1_onoff to switch the operation mode: m.options.SOLVER = 1 # APOPT solver for Mixed Integer solutions gen1_onoff = m.Var(value=1, integer=True, lb=0, ub=1) # Binary variable Egen1 = m.Var(value = 30, lb ... | 2 | 1 |
79,027,616 | 2024-9-26 | https://stackoverflow.com/questions/79027616/pandas-groupby-transform-mean-with-date-before-current-row-for-huge-huge-datafra | I have a Pandas dataframe that looks like df = pd.DataFrame([['John', '1/1/2017','10'], ['John', '2/2/2017','15'], ['John', '2/2/2017','20'], ['John', '3/3/2017','30'], ['Sue', '1/1/2017','10'], ['Sue', '2/2/2017','15'], ['Sue', '3/2/2017','20'], ['Sue', '3/3/2017','7'], ['Sue', '4/4/2017','20']], columns=['Customer', ... | You could use a custom groupby.apply with expanding.mean and a mask on the duplicated date to ffill the output: df['Deposit_Date'] = pd.to_datetime(df['Deposit_Date']) df['PreviousMean'] = (df.groupby('Customer') .apply(lambda s: s['DPD'].expanding().mean().shift() .mask(s['Deposit_Date'].duplicated()) .ffill(), includ... | 2 | 2 |
79,026,966 | 2024-9-26 | https://stackoverflow.com/questions/79026966/tcp-connections-not-being-cleaned-up-in-windows-python | I'm running a Windows server on AWS that is serving some data to IOT devices, but after a while the server stops responding to requests because it hangs on the s.accept() call, I've managed to determine that this happens because the server has too many TCP connections open so the OS wont allocate any more which makes s... | I've managed to fix the issue, the fix seems to have been to use socket.setdefaulttimeout(10), I'm not sure why this works but not s.settimeout(10), but now the server has been running for 6 days without issues (it used to run for about 8-12 ish hours before halting), there are now 0 connections stuck in the closed wai... | 2 | 0 |
79,029,557 | 2024-9-27 | https://stackoverflow.com/questions/79029557/polars-dataframe-how-to-efficiently-aggregate-over-many-non-disjoint-groups | I have a dataframe with columns x, y, c_1, c2, ..., c_K, where K is somewhat large (K ≈ 1000 or 2000). Each of the columns c_i is boolean column, and I'd like to compute an aggregation f(x, y) over rows where where c_i is True. (For example, f(x,y) = x.sum() * y.sum().) One way to do this is: ds.select([ f(pl.col("x").... | In general, I would not think that multiple filters are inefficient in polars. To verify this, I benchmarked three different approaches: 1. Generator of expressions with 2 filters This approach was proposed in the question. df.select( ( pl.col("x").filter(f"c_{i+1}").sum() * pl.col("y").filter(f"c_{i+1}").sum() ).alias... | 3 | 2 |
79,043,704 | 2024-10-1 | https://stackoverflow.com/questions/79043704/efficiently-simulating-many-frequency-severity-distributions-over-thousands-of-i | I've got a problem at work that goes as follows: We have, say, 1 million possible events which define frequency-severity distributions. For each event we have an annual rate which defines a Poisson distribution, and alpha and beta parameters for a Beta distributions. The goal is to simulate in the order of >100,000 "ye... | I profiled @WarrenWeckesser's answer, and I found that it spends 93% of its time generating poisson-distributed numbers using the rate array. Here's a line profile of what I'm talking about: Timer unit: 1e-09 s Total time: 3.57874 s File: /tmp/ipykernel_2774/1125349843.py Function: simulate_warren_answer at line 1 Line... | 1 | 2 |
79,034,526 | 2024-9-28 | https://stackoverflow.com/questions/79034526/performance-optimal-way-to-serialise-python-objects-containing-large-pandas-data | I am dealing with Python objects containing Pandas DataFrame and Numpy Series objects. These can be large, several millions of rows. E.g. @dataclass class MyWorld: # A lot of DataFrames with millions of rows samples: pd.DataFrame addresses: pd.DataFrame # etc. I need to cache these objects, and I am hoping to find an... | What about storing huge structures in parquet format while pickling it, this can be automated easily: import io from dataclasses import dataclass import pickle import numpy as np import pandas as pd @dataclass class MyWorld: array: np.ndarray series: pd.Series frame: pd.DataFrame @dataclass class MyWorldParquet: array:... | 4 | 6 |
79,042,253 | 2024-10-1 | https://stackoverflow.com/questions/79042253/how-do-i-speed-up-querying-my-600mio-rows | My database has about 600Mio entries that I want to query (Pandas is too slow). This local dbSNP only contains rsIDs and genomic positions. I used: import sqlite3 import gzip import csv rsid_db = sqlite3.connect('rsid.db') rsid_cursor = rsid_db.cursor() rsid_cursor.execute( """ CREATE TABLE rsids ( rsid TEXT, chrom TEX... | Others have suggested defining your rsid column as the primary key, or alternatively creating a unique index on it. That's a good idea. Another thing: rsid IN ('dirty','great','list','of',items') may use a so-called skip-scan to get its results. If your rsid_list is very large, or if it pulls in values that are lexical... | 3 | 2 |
79,044,789 | 2024-10-1 | https://stackoverflow.com/questions/79044789/why-is-python-calculation-with-float-numbers-faster-than-calculation-with-intege | This example shows that python calcuation with float numbers is faster than with integer numbers. I am wondering why calculation with integer is not faster than with float import time # Number of operations N = 10**7 # Integer addition start_time = time.time() int_result = 0 for i in range(N): int_result += 1 int_time ... | Python uses integers with no fixed size. Under the hood it's an array of digits (not base-10 digits, but fixed size integers that fit into 1 array element, to which we refer as "digit" in this case) that can be extended if needed. That's why you can have absurdly large integers in Python. CPUs have instructions to perf... | 2 | 5 |
79,042,519 | 2024-10-1 | https://stackoverflow.com/questions/79042519/default-class-representation-in-repl-python | Where can I find the implementation of the default class representation in Python/REPL? Example: >>> class Foo: ... pass >>> Foo <class '__main__.Foo'> Where is that whole string <class '__main__.Foo'> coming from? Is it defined in any PEP? I've tried greping the source of https://github.com/python/cpython for <class ... | The string <class '__main__.Foo'> comes from the type.__repr__ method, which is implemented with the type_repr function in Objects/typeobject.c of CPython: PyObject *result; if (mod != NULL && !_PyUnicode_Equal(mod, &_Py_ID(builtins))) { result = PyUnicode_FromFormat("<class '%U.%U'>", mod, name); } | 2 | 4 |
79,044,503 | 2024-10-1 | https://stackoverflow.com/questions/79044503/can-pyright-mypy-deduce-the-type-of-an-entry-of-an-ndarray | How can I annotate an ndarray so that Pyright/Mypy Intellisense can deduce the type of an entry? What can I fill in for ??? in x: ??? = np.array([1, 2, 3], dtype=int) so that y = x[0] is identified as an integer as rather than Any? | This is not currently possible. As defined in the type stubs, ndarray.__getitem__ has 5 @overloads. When the type checker evaluates x[0], it uses the second one, which returns Any: @overload def __getitem__(self, key: SupportsIndex | tuple[SupportsIndex, ...]) -> Any: ... The other four all return ndarray/NDArray: @ov... | 1 | 2 |
79,044,369 | 2024-10-1 | https://stackoverflow.com/questions/79044369/mathematical-expression-possible-instead-of-using-a-while-loop | It seems possible to execute this without using a loop, in python: check = -arr[i] while check >= mi: check -= k arr[i] and mi are constants at this point. I want to minimise the value of check such that it obeys the following: check = (x * k) - arr[i] for some x AND: check >= mi Everything here is an integer. Obviou... | The problem is the ">=". That gives your code an off-by-one. Plus, you have addition and subtraction swapped. We need to REDUCE -arr[i] by the x*k value. x = math.ceil((-arr[i]-mi+1)/k) check = -arr[i] - x * k Consider an example, where arr[i] = -14, mi = 5, k = 3. If we do this by hand, we go 14, 11, 8, 5, 2. So, 4 s... | 2 | 0 |
79,044,322 | 2024-10-1 | https://stackoverflow.com/questions/79044322/conditionally-slice-a-pandas-multiindex-on-specific-level | For my given multi-indexed DataFrame: df = pd.DataFrame( np.random.randn(12), index=[ [1,1,2,3,4,4,5,5,6,6,7,8], [1,2,1,1,1,2,1,2,1,2,2,2], ] ) 0 1 1 1.667692 2 0.274428 2 1 0.216911 3 1 -0.513463 4 1 -0.642277 2 -2.563876 5 1 2.301943 2 1.455494 6 1 -1.539390 2 -1.344079 7 2 0.300735 8 2 0.089269 I would like to sl... | Another possible solution, which is based on the following: df.groupby(level=0) groups the dataframe by the first level of the index. filter(lambda x: set(x.index.get_level_values(1)) == {1, 2}) checks if the second level of the index for each group contains both 1 and 2, and retains only the groups that meet this co... | 4 | 4 |
79,043,009 | 2024-10-1 | https://stackoverflow.com/questions/79043009/how-do-i-update-a-package-on-conda-forge | How do I update a package on conda-forge? I'm trying to install the newest version of neuralprophet, but it is outdated on the conda-forge channel. There are pull requests on the feedstock github page, but how do I merge these? Can I merge these, or are special permissions needed? As a side note, I've also tried to get... | You cannot merge the PRs unless you are a maintainer of the github repo. For situations where the package you need is not available or outdated on the anaconda repo, you can install all of the dependencies that are required using conda, and then install the package via PIP. This puts the package as the only part that i... | 2 | 3 |
79,042,426 | 2024-10-1 | https://stackoverflow.com/questions/79042426/pure-polars-version-of-safe-ast-literal-eval | I have data like this, df = pl.DataFrame({'a': ["['b', 'c', 'd']"]}) I want to convert the string to a list I use, df = df.with_columns(a=pl.col('a').str.json_decode()) it gives me, ComputeError: error inferring JSON: InternalError(TapeError) at character 1 (''') then I use this function, import ast def safe_literal... | A general ast eval is not yet available. The problem with json_decode is that the list representation uses single quotes (instead of double quotes as used in JSON). In your example, this issue can be circumvented by replacing the single quotes using pl.Expr.str.replace_all as follows. df.with_columns( pl.col("a").str.r... | 1 | 2 |
79,041,290 | 2024-9-30 | https://stackoverflow.com/questions/79041290/sort-all-matrix | I'm trying to sort a matrix if I have [[5 7 1 2] [4 8 1 4] [4 0 1 9] [2 7 5 0]] I want this result [[9 8 7 7] [5 5 4 4] [4 2 2 1] [1 1 0 0]] this is my code, I'm using random numbers import numpy as np MatriX = np.random.randint(10, size=(4,4)) print(MatriX) for i in range(10): for j in range(10): a=np.sort(-MatriX,a... | It's as simple as this: import numpy as np data = np.random.randint(10, size=(4,4)) print(data) result = np.sort(data.flatten())[::-1].reshape(data.shape) print(result) Output: [[4 7 7 6] [1 9 5 0] [5 8 1 2] [2 5 7 3]] [[9 8 7 7] [7 6 5 5] [5 4 3 2] [2 1 1 0]] An explanation of the parts of np.sort(data.flatten())[::... | 2 | 5 |
79,040,124 | 2024-9-30 | https://stackoverflow.com/questions/79040124/p-values-for-all-pairs-between-two-matrices-to-achieve-matlabs-corr-function | I have been trying to implement in Python (with numpy and scipy) this variant of Matlab's corr function, but it seems I cannot solve it by myself. What I need is to implement the alternative Matlab corr implementation: [rho,pval] = corr(X,Y) I would appreciate any help on this!!! What I tried: I tried to modify the sol... | I think the easiest way is to do it in pandas, using scipy.stats pearsonr, which returns the pairwise rho and pval. I tested with some sample below, and I believe the results match the matlab results. import numpy as np from scipy.stats import pearsonr import pandas as pd X = np.array([ [0.5377, 0.3188, 3.5784, 0.7254]... | 2 | 0 |
79,039,949 | 2024-9-30 | https://stackoverflow.com/questions/79039949/pandas-pct-change-but-loop-back-to-start | I'm looking at how to use the pandas pct_change() function, but I need the values 'wrap around', so the last and first values create a percent change value in position 0 rather than NaN. For example: df = pd.DataFrame({'Month':[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], 'Value':[1, 0.9, 0.8, 0.75, 0.75, 0.8, 0.7, 0.65, 0.... | Just use numpy.roll that is designed for this specific purpose: import numpy as np df['percent change'] = df['Value'].div(np.roll(df['Value'], 1)) Output: Month Value percent change 0 1 1.00 1.111111 1 2 0.90 0.900000 2 3 0.80 0.888889 3 4 0.75 0.937500 4 5 0.75 1.000000 5 6 0.80 1.066667 6 7 0.70 0.875000 7 8 0.65 0... | 2 | 1 |
79,039,864 | 2024-9-30 | https://stackoverflow.com/questions/79039864/why-x-yi-faster-than-xi-yi | I'm new to CuPy and CUDA/GPU computing. Can someone explain why (x / y)[i] faster than x[i] / y[i]? When taking advantage of GPU accelerated computations, are there any guidelines that would allow me to quickly determine which operation is faster? Which to avoid benchmarking every operation. # In VSCode Jupyter Noteboo... | The ratio of arithmetic capability to bytes retrieval capability on a GPU (at least, maybe also CPU) is generally lopsided in favor of arithmetic capability. Therefore algorithm performance can often be predicted by the the number of memory operations required. The first step in the x[i]/y[i] realization is to create x... | 3 | 7 |
79,039,069 | 2024-9-30 | https://stackoverflow.com/questions/79039069/cancelling-all-tasks-on-failure-with-concurrent-futures-in-python | I am using Python's concurrent.futures library with ThreadPoolExecutor and ProcessPoolExecutor. I want to implement a mechanism to cancel all running or unexecuted tasks if any one of the tasks fails. Specifically, I want to: Cancel all futures (both running and unexecuted) when a task fails. Raise the error that caus... | Is this the correct way to handle task cancellation in ThreadPoolExecutor and ProcessPoolExecutor? Your approach is almost correct, but there are some important things to note: executor.shutdown(wait=False) only prevents new tasks from being submitted. It doesn't actually cancel the running tasks. The tasks that have ... | 1 | 3 |
79,038,956 | 2024-9-30 | https://stackoverflow.com/questions/79038956/pandas-series-str-split-not-accepting-3-keyword-arguments | I'm doing a project using the MIMIC-IV dataset as a source. I found a preprocessing pipeline which is widely used in many projects. When I try to run through said pipeline all is well until I try to generate the time series data representation module (I haven't modified the data nor the pipeline code in any way myself)... | In recent pandas versions, many functions switched to keyword only, you can actually see this in str.split documentation. # positional # keyword-only Series.str.split(pat=None, *, n=-1, expand=False, regex=None) The * means that onlt pat can be used as a positional parameter, n/expand/regex must be provided as keywor... | 1 | 2 |
79,032,773 | 2024-9-27 | https://stackoverflow.com/questions/79032773/stuck-on-scraping-with-beautifulsoup-while-learning-need-some-pointers | I started learning screen scraping using BeautifulSoup. To get started I took a wikipedia article in the following format <table class="wikitable sortable jquery-tablesorter"> <caption></caption> <thead> <tr> <th colspan="2" style="width: 6%;" class="headerSort" tabindex="0" role="columnheader button" title="Sort ascen... | You can do most of the work using DataFrame from io import StringIO import pandas as pd df = pd.read_html(StringIO(html_page))[0] df.columns = ['month', 'day', 'movie', 'director', 'cast', 'producer', 'reference'] df['month'] = df['month'].str.split(' ').apply(''.join) df['cast'] = df['cast'].str.split(r'\s{2,}', regex... | 3 | 2 |
79,037,716 | 2024-9-30 | https://stackoverflow.com/questions/79037716/typing-error-with-inherited-classes-having-overloaded-constructor-with-different | With the code below: import abc class ABCParent(metaclass=abc.ABCMeta): def __init__(self, a: str, sibling_type: type[ABCParent]) -> None: self.a = a self._sibling_type = sibling_type def new_sibling(self, a: str) -> ABCParent: return self._sibling_type(a) class ChildA(ABCParent): def __init__(self, a: str) -> None: su... | So, I think one approach that could work depending on the specifics of your actual use-case is making ._sibling_type a generic callable and making the classes generic as well, parametrized with the same type variable. import abc import typing P = typing.TypeVar("P", bound="ABCParent") class ABCParent(typing.Generic[P],... | 3 | 4 |
79,032,868 | 2024-9-27 | https://stackoverflow.com/questions/79032868/differences-between-columns-containing-lists | I have a data frame where the columns values are list and want to find the differences between two columns. data={'NAME':['JOHN','MARY','CHARLIE'], 'A':[[1,2,3],[2,3,4],[3,4,5]], 'B':[[2,3,4],[3,4,5],[4,5,6]]} df=pd.DataFrame(data) Why doesn't it work? df = df.assign(X1 = lambda x: [y for y in x['A'] if y not in x['B'... | So, this is where lambdas get interesting. These two lambdas will have the same result: df = df.assign(X1 = lambda x: [y for y in x['A']]) #unvectorized, x is the entire DataFrame df = df.assign(X1 = lambda x: x['A']) #vectorized, x is a single row One (lengthy) way to do what you are asking is to iterate through each... | 1 | 2 |
79,025,526 | 2024-9-26 | https://stackoverflow.com/questions/79025526/escaping-quotes-in-python-subprocesses-for-windows | I'm trying to terminate a Python program that uses many threads on its own. If I'm not mistaken, just sys.exit() works fine. However, to guard against my many mistakes, including losing references to threads, I tried the following: subprocess.Popen(['start', 'cmd.exe', '/c', f'timeout 5&taskkill /f /fi "PID eq {os.getp... | From subprocess.Popen: args should be a sequence of program arguments or else a single string or path-like object. Run notepad.exe and be sure to not type in its window so "Untitled - Notepad" is the title. I'm using WINDOWTITLE eq Untitled* so I don't have to look up the PID. Use a single string for the command. Thi... | 3 | 1 |
79,037,379 | 2024-9-29 | https://stackoverflow.com/questions/79037379/why-does-my-planetary-orbit-simulation-produce-a-straight-line-instead-of-an-ell | I'm trying to simulate the orbit of a planet using the compute_orbit method, but when I plot the resulting positions, I get a straight line instead of an expected elliptical orbit. Below are the relevant parts of my code. Code Snippet def get_initial_conditions(self, planet_name): planet_id = self.PLANETS[planet_name] ... | This problem has mismatched units. In the following code: obj = Horizons(id=planet_id, location='@sun', epochs=2000.0) eph = obj.vectors() position = np.array([eph['x'][0], eph['y'][0], eph['z'][0]]) velocity = np.array([eph['vx'][0], eph['vy'][0], eph['vz'][0]]) The obj.vectors() query does not return output in mete... | 1 | 3 |
79,034,510 | 2024-9-28 | https://stackoverflow.com/questions/79034510/qt-pyside6-what-is-the-best-way-to-implement-an-infinite-data-fetching-loop-wit | I am implementing a small multi-threaded GUI application with PySide6 to fetch data from a (USB-connected) sensor and to visualize the data with Qt. I.e., the use can start and stop the data fetching: When clicking the play button a worker object is created and moved to the QThread and the QThread is started. The inte... | Qt really has no say in this, It depends on the communication mode of whatever API you are using for communication, and whether it supports synchronous or asynchronous IO. synchronous (blocking) API If the communication is synchronous such as pyserial or QSerialPort (blocking mode) then use Approach1 without the sleep,... | 3 | 1 |
79,036,818 | 2024-9-29 | https://stackoverflow.com/questions/79036818/how-can-i-filter-a-list-within-a-polars-column | Say for example I have data like this: import polars as pl df = pl.DataFrame( { "subject": ["subject1", "subject2"], "emails": [ ["samATxyz.com", "janeATxyz.com", "jimATcustomer.org"], ["samATxyz.com", "zaneATxyz.com", "basATcustomer.org", "jimATcustomer.org"], ], } ) df shape: (2, 2) ┌──────────┬─────────────────────... | You were on the right track with pl.Expr.list.eval. It can be combined with pl.Expr.filter to achieve the desired result as follows. df.with_columns( pl.col("emails").list.eval( pl.element().filter(pl.element().str.ends_with("ATxyz.com")) ) ) shape: (2, 2) ┌──────────┬───────────────────────────────────┐ │ subject ┆ e... | 3 | 3 |
79,032,143 | 2024-9-27 | https://stackoverflow.com/questions/79032143/multidimensional-matrix-permutation-julia-vs-python-disagreement | I have noticed a difference in behavior between python's numpy.permute_dims and julia's Base.permutedims. On an input 3x3x3 matrix containing elements 0:26, inclusive in both languages, they agree for the axes argument (1,2,0) but disagree for (0,2,1). As far as I can tell from the docs, these functions should be equiv... | It looks like your problem comes from the fact that numpy does not adhere to the "natural" mental model for indexing. In the natural mental model, if you want to address the number 20 in a 3d matrix like this a = np.arange(2*3*4).reshape(2, 3, 4) array([[[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]], [[12, 13, 14, 15... | 2 | 1 |
79,035,467 | 2024-9-29 | https://stackoverflow.com/questions/79035467/unable-to-install-pygobject-in-pycharm-meson-build5115-error-python-depende | I'm attempting to install the PyGObject library in pycharm following this guide https://pygobject.gnome.org/getting_started.html attempting to do step 3 on the Ubuntu / Debian section: pip3 install pycairo and this is what is returned: × Preparing metadata (pyproject.toml) did not run successfully. │ exit code: 1 ╰─>... | Unless you need a new version Ubuntu packages it (as the docs say): sudo apt install python3-gi python3-gi-cairo gir1.2-gtk-4.0 Otherwise don’t skip step 2: sudo apt install libgirepository1.0-dev gcc libcairo2-dev pkg-config python3-dev gir1.2-gtk-4.0 | 2 | 1 |
79,020,783 | 2024-9-25 | https://stackoverflow.com/questions/79020783/how-to-make-ruff-ignore-comments-in-measuring-the-line-length | The line demo_code = print("foo bar") # some comments and this line length exceed 79 that i config. is being formatted by ruff format to demo_code = print( "foo bar" ) # some comments and this line length exceed 79 that i config. as it exceeds the value defined in line-length. I want to make ruff count only command c... | The best (unique?) solution to ignore lengthy code line errors (E501) with ruff is using codetags in you code: # pyproject.toml [tool.ruff.lint.pycodestyle] ignore-overlong-task-comments = true [tool.ruff.lint] task-tags = ["HACK"] demo_code = print("foo bar") # HACK: That is a so savvy solution. Now, I can write very... | 1 | 1 |
79,029,563 | 2024-9-27 | https://stackoverflow.com/questions/79029563/how-to-scrape-all-customer-reviews | I am trying to scrape all reviews in this website - https://www.backmarket.com/en-us/r/l/airpods/345c3c05-8a7b-4d4d-ac21-518b12a0ec17. The website says there are 753 reviews, but when I try to scrape all reviews, I get only 10 reviews. So, I am not sure how to scrape all 753 reviews from the page, Here is my code- # im... | based on your expectations, I think using the requests library and a little bit of code can fetch your desired result, here is my mindmap: we can use this https://www.backmarket.com/reviews/product-landings/345c3c05-8a7b-4d4d-ac21-518b12a0ec17/products/reviews API endpoint to fetch all of your expected information rela... | 4 | 0 |
79,034,296 | 2024-9-28 | https://stackoverflow.com/questions/79034296/filter-a-lazyframe-by-row-index | Is there an idiomatic way to get specific rows from a LazyFrame? There's two methods I could figure out. Not sure which is better, or if there's some different method I should use. import polars as pl df = pl.DataFrame({"x": ["a", "b", "c", "d"]}).lazy() rows = [1, 3] # method 1 ( df.with_row_index("row_number") .filte... | pl.Expr.gather is the idiomatic way to take values by index. df.select(pl.all().gather(rows)).collect() For completeness, method 1 can be refined by using an expression for the index. This way no temporary column is created and dropped again. # method 1.1 df.filter(pl.int_range(pl.len()).is_in(rows)).collect() | 2 | 2 |
79,026,472 | 2024-9-26 | https://stackoverflow.com/questions/79026472/get-x-and-y-radius-of-a-hexagon-no-matter-the-angle | I created a hexagon blur that gives this kind of results: To make the code a bit cleaner, I created a hexagon class. I'm now implementing different methods inside. My constructor look to this for now: def __init__(self, radius, center_x, center_y, angle=0): self._dmin = np.sqrt(3)/2 self._radius = radius self._radius_... | As far as your code goes, you don't need to use anything besides core Python for the geometric computations. The math module provides the trigonometric and transcendental functions you need: from math import sin, cos, sqrt, degrees, radians, pi No need for NumPy: to convert from degrees to radians, use radians. E.g. ... | 3 | 2 |
79,032,931 | 2024-9-27 | https://stackoverflow.com/questions/79032931/scipy-curve-fit-covariance-of-the-parameters-could-not-be-estimated | I am trying to estimate the Schott coefficients of a glass material given only its n_e(refraction index at e line) and V_e(Abbe number at e line). Schott is one way to represent the dispersion of a material, which is the different index of refraction (RI) at different wavelength. In the figure above, the horizontal ax... | Don't use sqrt during fitting, and don't fit this as a nonlinear model. Fit it as a linear model: import numpy as np from matplotlib import pyplot as plt schott_powers = np.arange(2, -9, -2) def inv_schott(lambd: np.ndarray, a: np.ndarray) -> np.ndarray: return np.sqrt(inv_schott_squared(lambd, a)) def inv_schott_squar... | 1 | 3 |
79,032,225 | 2024-9-27 | https://stackoverflow.com/questions/79032225/aggregating-output-from-langchain-lcel-elements | I have two chains, one that generates a document and one that creates a short document resume. I want to chain them, using the output from the first on inside the other one. But I want to get both outputs in the result. Before LCEL, I could do it using LLMChain's output_key parameter. With LCEL, there seems to be a Run... | Perhaps the following is what you want. It feeds the output of the first chain into second chain as input. from langchain_core.runnables import RunnablePassthrough aggregated_chain = generate_document_chain | { "first_chain_output": RunnablePassthrough(), "second_chain_output": resume_document_chain } content = aggrega... | 2 | 1 |
79,032,873 | 2024-9-27 | https://stackoverflow.com/questions/79032873/how-to-arbitrarily-nest-some-data-in-a-django-rest-framework-serializer | An existing client is already sending data in a structure like… { "hive_metadata": {"name": "hive name"}, "bees": [{"name": "bee 1", "name": "bee 2", ...}] } For models like: class Hive(models.Model): name = models.CharField(max_length=32, help_text="name") class Bee(models.Model): name = models.CharField(max_length=3... | You can use a string literal with an asterisk ('*'), as specified in the documentation [drf-doc]: The value source='*' has a special meaning, and is used to indicate that the entire object should be passed through to the field. This can be useful for creating nested representations, or for fields which require access ... | 2 | 3 |
79,032,221 | 2024-9-27 | https://stackoverflow.com/questions/79032221/rcparams-not-being-applied-to-custom-matplotlib-class | I am trying to write a custom figure class around matplotlib.figure.Figure which among other things, automatically applies the correct formatting. Here's the current configuration: import matplotlib from matplotlib.axes import Axes from matplotlib.figure import Figure from matplotlib.backends.backend_qtagg import Figur... | If I understood your question correctly, your code does set the params as needed except for the figure title. That is because you are using a subplot which has 'suptitle'. So the parameter you set for figure.titlesize will not work! Check this instead: import matplotlib from matplotlib.axes import Axes from matplotlib.... | 2 | 1 |
79,028,509 | 2024-9-26 | https://stackoverflow.com/questions/79028509/how-can-i-quickly-generate-a-large-list-of-random-numbers-given-a-list-of-seed | I need to make a function that takes in an array of integers and returns a list of random numbers with the same length as the array. However, there is the restriction that the output random number corresponding to a given entry in the input array should always be the same based upon that entry. For example, if input_a ... | It may be good enough to implement a simple pseudo random number generator where each int in the array acts as a seed. Splitmix 64 is pretty simple and consecutive integer seeds generate very different results. Or explore other pseudo random options. import numpy as np TWO53 = 1 << 53 def sm64( arr ): """ Splitmix 64 P... | 1 | 1 |
79,031,709 | 2024-9-27 | https://stackoverflow.com/questions/79031709/display-javascript-fetch-for-jsonresponse-2-tables-on-html | I'm learning JavaScript right now and I'm trying to display data from 2 tables, which is profile and posts of the user profile. Here is the API view API I tried to display the data on index.html using JavaScript. index.js function load_profile(author_id) { // Load posts list fetch(`/profile/${author_id}`) .then(respons... | Example function load() { fetch('https://my/api/call') .then(response => response.json()) .then(data => { // do something with data.profile return data }) .then(data => { // do something with data.posts }) } | 2 | 0 |
79,030,673 | 2024-9-27 | https://stackoverflow.com/questions/79030673/message-session-not-created-this-version-of-chromedriver-only-supports-chrome | I'm using selenium and ChromeDriver, worked with it several times and have no errors. Suddenly today I got this warning: The chromedriver version (114.0.5735.90) detected in PATH at C:\Work\Scrape\chromedriver.exe might not be compatible with the detected chrome version (129.0.6668.60); currently, chromedriver 129.0.6... | Your chrome browser seems to have upgraded recently to v129. You need to use matching chromedriver in your selenium code. Option 1: Download latest ChromeDriver(v129) from the following link: https://googlechromelabs.github.io/chrome-for-testing/#stable And use this chromedriver.exe in your driver path. (C:\Work\Scrape... | 5 | 2 |
79,030,706 | 2024-9-27 | https://stackoverflow.com/questions/79030706/python-numpy-and-the-cacheline | I try to follow https://igoro.com/archive/gallery-of-processor-cache-effects/ in python using numpy. Though it does not work and I don't quite understand why... numpy has fixed size dtypes, such as np.int64 which takes up 8 bytes. So with a cacheline of 64 bytes, 8 array values should be held in cache. Thus, when doing... | I am quite confused about what I am observing. You are mainly observing the overhead of the interpreter and the one of Numpy. Indeed, arr[idx] = 0 is interpreted and calls a function of the arr object which performs type checks, reference counting, certainly creates an internal Numpy generator and many other expensiv... | 2 | 4 |
79,029,798 | 2024-9-27 | https://stackoverflow.com/questions/79029798/str-of-a-dict-subclass-does-not-return-per-the-mro | With a class that inherits from dict, why does str() not use dict.__str__ when dict is earlier in the MRO of the class? Python 3.10.12 (main, Sep 11 2024, 15:47:36) [GCC 11.4.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> class A: ... def __str__(self): ... return "A" ... >>> cla... | dict.__str__ is inherited from object, not implemented by dict. (The implementation is basically return repr(self) - it's not dict-specific.) dict might come before A in B.__mro__, but A comes before object, so A's __str__ implementation is found before object's implementation. | 3 | 0 |
79,029,736 | 2024-9-27 | https://stackoverflow.com/questions/79029736/issue-while-installing-selenium-wire | I wanted to use selenium-wire to intercept requests from Selenium to remote host. I tried to install it using PIP, it installed successfully without any issues, but when I went to import it on my project its giving me error as follows: no module named 'blinker._saferef I tried to dig in the issue, but found nothing. I ... | You seem to be facing issue which is not related to the library itself but the dependency of the library. Please uninstall the version of blinker._saferef, issue the command below: pip uninstall selenium-wire pip uninstall blinker once its uninstall use the blinker version which is less than 1.8.0, use following comma... | 1 | 10 |
79,029,290 | 2024-9-26 | https://stackoverflow.com/questions/79029290/how-to-draw-a-shaded-area-which-tightly-includes-all-the-points-in-scatter-plot | I've pairs of y and z locations which I'm plotting as a scatter plot as shown below. Looking at the plot, we can visualize a tight boundary which includes all of the points. My question is how do we draw this boundary in python? Ideally, I would like to have a filled region representing this area. I've taken a look at... | Thanks to the users for pointing me to alphashape. As the alphashape code provided by Keerthan draws piecewise linear boundaries, I wasn't completely satisfied with it. Here's how I managed to generate a smooth curve. Continuing from Keerthan's answer from scipy.interpolate import splprep, splev # Instead of ax.add_pat... | 1 | 1 |
79,021,544 | 2024-9-25 | https://stackoverflow.com/questions/79021544/removing-strange-special-characters-from-outputs-llama-3-1-model | Background: I'm using Hugging Face's transformers package and Llama 3.1 8B (Instruct). Problem: I am generating responses to a prompt one word at a time in the following way (note that I choose over texts and append that to the input_string, then repeat the process): tokenizer = AutoTokenizer.from_pretrained(model_path... | TL;DR Use this instead of rolling out your own detokenizer. tokenizer.batch_decode(input_ids) In Long The official Llama 3.1 has some approval process that might take some time, so this answer will use a proxy model that shares the same tokenizer as llama 3.1 Without using the model or passing through the forward func... | 3 | 3 |
79,029,223 | 2024-9-26 | https://stackoverflow.com/questions/79029223/python-virtual-environment-and-sys-path | I created a virtual environment using python -m venv venv Now I'm opening a Python shell without activating the virtual environment by running import sys print(sys.path, sys.prefix) I get ['', '/usr/lib/python312.zip', '/usr/lib/python3.12', '/usr/lib/python3.12/lib-dynload', '/usr/lib/python3.12/site-packages'] /usr... | Is this true? No. The system packages are at /usr/lib/python3.12/site-packages, which is not present at all when you're "inside" the venv. The paths before the venv-site (which is /home/myname/mypath/venv/lib/python3.12/site-packages in your case) are for standard library imports. For example, if you import csv or so... | 2 | 3 |
79,028,838 | 2024-9-26 | https://stackoverflow.com/questions/79028838/polars-rolling-mean-fill-start-of-window-with-null-instead-of-shortened-window | My question is whether there is a way to have null until the full window can be filled at the start of a rolling window in polars. For example: dates = [ "2020-01-01", "2020-01-02", "2020-01-03", "2020-01-04", "2020-01-05", "2020-01-06", "2020-01-01", "2020-01-02", "2020-01-03", "2020-01-04", "2020-01-05", "2020-01-06"... | Can you check the length? (df.rolling(index_column="dt", period="2d", group_by="b") .agg( pl.when(pl.len() > 1) .then(pl.col("a").mean()) .alias("ma_2d") ) ) shape: (12, 3) ┌─────┬────────────┬───────┐ │ b ┆ dt ┆ ma_2d │ │ --- ┆ --- ┆ --- │ │ str ┆ date ┆ f64 │ ╞═════╪════════════╪═══════╡ │ Yes ┆ 2020-01-01 ┆ null │ ... | 3 | 2 |
79,027,662 | 2024-9-26 | https://stackoverflow.com/questions/79027662/slightly-wrong-color-in-mp4-videos-written-by-pyav | I am writing MP4 video files with the following PyAV-based code (getting input frames represented as numpy arrays - the sort produced by imageio.imread - as input): class MP4: def __init__(self, fname, width, height, fps): self.output = av.open(fname, 'w', format='mp4') self.stream = self.output.add_stream('h264', str(... | Adding frame = frame.reformat(format='yuv420p', dst_colorspace=av.video.reformatter.Colorspace.ITU709) before the call to encode fixes the problem. I don't know why both the format and the dst_colorspace arguments are needed for this to work, empirically they are. | 1 | 2 |
79,028,082 | 2024-9-26 | https://stackoverflow.com/questions/79028082/polars-pivot-dataframe-an-count-the-cumulative-uniques-id | I have a polars dataframe that contains and ID, DATE and OS. For each day i would like to count how many uniques ID are until that day. import polars as pl df = ( pl.DataFrame( { "DAY": [1,1,1,2,2,2,3,3,3], "OS" : ["A","B","A","B","A","B","A","B","A"], "ID": ["X","Y","Z","W","X","J","K","L","X"] } ) ) Desired Output: ... | You can use Expr.is_first_distinct mark each of the first distinct entries of 'ID' within each 'OS'. Then you can pivot those results and take their cumulative sum. import polars as pl df = ( pl.DataFrame( { "DAY": [1,1,1,2,2,2,3,3,3], "OS" : ["A","B","A","B","A","B","A","B","A"], "ID": ["X","Y","Z","W","X","J","K","L"... | 3 | 4 |
79,027,200 | 2024-9-26 | https://stackoverflow.com/questions/79027200/how-to-change-a-list-element-by-index-in-a-list-column | I have a column of lists in my polars dataframe. I would like to access and change a value by list index. Example input df = pl.DataFrame({ "values": [ [10, 20, 30, 40], [50, 60, 70, 80], [90, 100, 110, 120], ], }) Pseudocode df = df.with_columns( pl.col("values").list.eval(pl.element(3) = 1).alias("values2") ) Expec... | take first 3 elements with list.head(). add 1 add remaining elements of list with list.tail() using -4 to get all elements except first 4. concat_list() to concat elements together. df.with_columns( pl.concat_list( pl.col.values.list.head(3), 1, pl.col.values.list.tail(-4) ) ) shape: (3, 1) ┌───────────────────┐ │ v... | 3 | 3 |
79,026,693 | 2024-9-26 | https://stackoverflow.com/questions/79026693/numpy-error-implicit-conversion-to-a-numpy-array-is-not-allowed-please-use | I 'am trying to find similar vector with spacy and numpy. I found the code following url : Mapping word vector to the most similar/closest word using spaCy But I'm getting type error import numpy as np your_word = "country" ms = nlp.vocab.vectors.most_similar( np.asarray([nlp.vocab.vectors[nlp.vocab.strings[your_word]]... | From the Reference - Mapping word vector to the most similar/closest word using spaCy Reference - https://docs.cupy.dev/en/stable/reference/ndarray.html You need to convert CuPy arrays to be explicitly converted to NumPy arrays before operations on the CPU Edit lets make reshape the word vector into a 2D array with one... | 2 | 2 |
79,026,038 | 2024-9-26 | https://stackoverflow.com/questions/79026038/handling-file-in-a-generator-function | I'm to create a generator that accepts a name of the file or a fileobject, words that we're looking for in a line and stop words that tell us that we should skip this line as soon as we meet them. I wrote a generator function, but I paid attenttion that in my realisation I can't be sure that if I open a file it will be... | You could write a context managed class that is iterable like this: from pathlib import Path from collections.abc import Iterator from typing import TextIO, Self class Reader: def __init__(self, filename: Path, lookups: list[str], stopwords: list[str]): self._lookups: set[str] = {e.lower() for e in lookups} self._stopw... | 1 | 3 |
79,026,053 | 2024-9-26 | https://stackoverflow.com/questions/79026053/how-to-correctly-add-columns-to-the-original-multi-index-dataframe-after-groupby | There is a DataFrame with option tickers at the zero level, prices (open, close, high, and low) at the first level, and option types at the second level (header structure: 'Ticker', 'open/close/high/low', 'Type'). The task: for each ticker, calculate the average price, then add columns with the average prices (header s... | The issue is that you modify the original index since columns_name = df_f_avg.loc[:, pd.IndexSlice[:, 'open']].columns is making a reference to it. You must make a deep copy: columns_name = df_f_avg.loc[:, pd.IndexSlice[:, 'open']].columns.copy(deep=True) You could also rename Price and groupby all levels: out = df_f_... | 1 | 3 |
79,025,966 | 2024-9-26 | https://stackoverflow.com/questions/79025966/docker-compose-failing-to-build-container-when-using-postgresql | I have been trying to build a docker-compose container for my back-end service using Fastapi.The issue is docker-compose container logs keep returning that my database engine fails. I am using asyncpg for async connection in postgresql. ╰─λ sudo docker-compose logs db-1 | The files belonging to this database system wi... | You need to install an async driver for PostgreSQL, and tell SQLAlchemy to use it. asyncpg is one such driver. So after adding to your requirements file and installing it, you then have to tell SQLAlchemy to use it. You do this by modifying the database URL. ie. DATABASE_URL=postgresql+asyncpg://admin:adminpass@db:5432... | 1 | 3 |
79,024,937 | 2024-9-25 | https://stackoverflow.com/questions/79024937/applying-function-to-filtered-columns-in-pandas | I have a Pandas Dataframe with 4 different columns: an ID, country, team and a color that is assigned to each player following a specific order. I want to create a new column that contains a number based on the team and the country that simply counts up following the color order, however colors may appear more than onc... | Convert the color column to ordered categorical type then group the dataframe by the combination of Country, Team and Color then use ngroup to assign ordered group numbers to each unique combination. Then for each Country rank the group numbers using dense method df['Color'] = pd.Categorical(df['Color'], colorcode, ord... | 2 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.