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
71,365,594
2022-3-5
https://stackoverflow.com/questions/71365594/how-to-make-a-proxy-object-with-typing-as-underlying-object-in-python
I have a proxy class with an underlying object. I wish to pass the proxy object to a function that expects and underlying object type. How do I make the proxy typing match the underlying object? class Proxy: def __init__(self, obj): self.obj = obj def __getattribute__(self, name): return getattr(self.obj, name) def __s...
Credit to @SUTerliakov for actually providing the essence of this answer in the comment on the question. The code should look something along the lines of the following: from typing import TYPE_CHECKING from my_module import MyClass if TYPE_CHECKING: base = MyClass else: base = object class Proxy(base): def __init__(se...
6
6
71,319,523
2022-3-2
https://stackoverflow.com/questions/71319523/django-rest-framework-drf-yasg-swagger-multiple-file-upload-error-for-listfield
I am trying to make upload file input from swagger (with drf-yasg), but when I use MultiPartParser class it gives me the below error: drf_yasg.errors.SwaggerGenerationError: FileField is supported only in a formData Parameter or response Schema My view: class AddExperience(generics.CreateAPIView): parser_classes = [Mu...
The OpenAPISchema (OAS) 2 doesn't support the multiple file upload (see issue #254); but OAS 3 supports it (you can use this YML spec on a live swagger editer (see this result)). Comes to the real issue, there is a section in the drf-yasg's doc, If you are looking to add Swagger/OpenAPI support to a new project you mi...
7
5
71,316,246
2022-3-2
https://stackoverflow.com/questions/71316246/fill-missing-dates-in-a-pandas-dataframe
I’ve a lot of DataFrames with 2 columns, like this: Fecha unidades 0 2020-01-01 2.0 84048 2020-09-01 4.0 149445 2020-10-01 11.0 532541 2020-11-01 4.0 660659 2020-12-01 2.0 1515682 2021-03-01 9.0 1563644 2021-04-01 2.0 1759823 2021-05-01 1.0 2226586 2021-07-01 1.0 As it can be seen, there ar...
You could create a date range and use "Fecha" column to set_index + reindex to add missing months. Then fillna + reset_index fetches the desired outcome: df['Fecha'] = pd.to_datetime(df['Fecha']) df = (df.set_index('Fecha') .reindex(pd.date_range('2020-01-01', '2021-12-01', freq='MS')) .rename_axis(['Fecha']) .fillna(0...
5
9
71,371,909
2022-3-6
https://stackoverflow.com/questions/71371909/how-to-calculate-when-ones-10000-day-after-his-or-her-birthday-will-be
I am wondering how to solve this problem with basic Python (no libraries to be used): How can I calculate when one's 10000 day after their birthday will be (/would be)? For instance, given Monday 19/05/2008, the desired day is Friday 05/10/2035 (according to https://www.durrans.com/projects/calc/10000/index.html?dob=19...
Using base Python packages only On the basis that "no special packages" means you can only use base Python packages, you can use datetime.timedelta for this type of problem: import datetime start_date = datetime.datetime(year=2008, month=5, day=19) end_date = start_date + datetime.timedelta(days=10000) print(end_date.d...
19
20
71,396,605
2022-3-8
https://stackoverflow.com/questions/71396605/how-can-i-specify-several-examples-for-the-fastapi-docs-when-response-model-is-a
I am writing a FastAPI app in python and I would like to use the openapi docs which are automatically generated. In particular, I would like to specify examples for the response value. I know how to do it when the response_model is a class that inherits from pydantic's BaseModel, but I am having trouble when it is a li...
You can specify your example in responses parameter: @app.get('/people', response_model=List[Person], responses={ 200: { "description": "People successfully found", "content": { "application/json": { "example": [ { "name": "Alice", "age": 83 }, { "name": "Bob", "age": 77 } ] } } }, 404: {"description": "People not foun...
8
13
71,352,354
2022-3-4
https://stackoverflow.com/questions/71352354/sklearn-kmeans-is-not-working-as-i-only-get-nonetype-object-has-no-attribute
I don't know what is wrong but suddenly KMeans from sklearn is not working anymore and I don't know what I am doing wrong. Has anyone encountered this problem yet or knows how I can fix it? from sklearn.cluster import KMeans kmeanModel = KMeans(n_clusters=k, random_state=0) kmeanModel.fit(allLocations) allLocations lo...
Downgrading numpy to 1.21.4 made it work again
42
15
71,362,488
2022-3-5
https://stackoverflow.com/questions/71362488/apply-transformation-on-a-paramspec-variable
Is there any way for me to apply a transformation on a ParamSpec? I can illustrate the problem with an example: from typing import Callable def as_upper(x: str): return x.upper() def eventually(f: Callable[P, None], *args: P.args, **kwargs: P.kwargs): def inner(): def transform(a): return a() if isinstance(a, Callable)...
This decorator cannot be properly typed with currently available tools (Python 3.10). Two main problems here: ParamSpec and Concatenate for now only allow us to modify a fixed number of parameters. We cannot concatenate keyword-only arguments (which makes transforming **kwargs: P.kwargs impossible) However, under the...
4
5
71,356,388
2022-3-4
https://stackoverflow.com/questions/71356388/how-to-connect-to-user-data-stream-binance
I need to listen to User Data Stream, whenever there's an Order Event - order execution, cancelation, and so on - I'd like to be able to listen to those events and create notifications. So I got my "listenKey" and I'm not sure if it was done the right way but I executed this code and it gave me something like listenKey...
You can create a basic async user socket connection from the docs here along with other useful info for the Binance API. Here is a simple example: import asyncio from binance import AsyncClient, BinanceSocketManager async def main(): client = await AsyncClient.create(api_key, api_secret, tld='us') bm = BinanceSocketMan...
7
1
71,337,173
2022-3-3
https://stackoverflow.com/questions/71337173/django-4-connection-to-postgresql-using-passfile-fe-sendauth-no-password-supp
Hello SO & Django community, My problem is related to Django 4, as the feature to use passfile to connect to Postgres has appeared in this version. Though I have went through the similar error message related questions about previous versions, I had no success in solving my problem. What I am trying to do I want to con...
Created the following DATABASES entry in settings.py of the Django project: 'default': { 'ENGINE': 'django.db.backends.postgresql', 'OPTIONS': { 'service': 'db_service', 'passfile': '.pgpass', }, } } In user home directory, created file ~/.pg_service.conf with following information: [db_service] host=localhost po...
5
9
71,376,207
2022-3-7
https://stackoverflow.com/questions/71376207/latex-math-text-in-pil-imagedraw-text
I'm trying to annotate a few figures I created in python. So, I'm generating an image containing the specified text (using PIL ImageDraw) and concatenating it with the image. Now, I want to include a math notation into the text. Is there a way to write text in latex math when creating the image of text? This answer sug...
I found an alternative with sympy here import sympy sympy.preview(r'frame $f_n$', dvioptions=["-T", "tight", "-z", "0", "--truecolor", "-D 600"], viewer='file', filename='test.png', euler=False)
5
0
71,399,847
2022-3-8
https://stackoverflow.com/questions/71399847/runtimeerror-0d-or-1d-target-tensor-expected-multi-target-not-supported-i-was
*My Training Model* def train(model,criterion,optimizer,iters): epoch = iters train_loss = [] validaion_loss = [] train_acc = [] validation_acc = [] states = ['Train','Valid'] for epoch in range(epochs): print("epoch : {}/{}".format(epoch+1,epochs)) for phase in states: if phase == 'Train': model.train() *training the ...
Your problem is that labels have the correct shape to calculate the loss. When you add .unsqueeze(1) to labels you made your labels with this shape [32,1] which is not consistent to the requirment to calcualte the loss. To fix the problem, you only need to remove .unsqueeze(1) for labels. If you read the documentation ...
8
14
71,370,656
2022-3-6
https://stackoverflow.com/questions/71370656/special-number-count
It is a number whose gcd of (sum of quartic power of its digits, the product of its digits) is more than 1. eg. 123 is a special number because hcf of(1+16+81, 6) is more than 1. I have to find the count of all these numbers that are below input n. eg. for n=120 their are 57 special numbers between (1 and 120) I have d...
Here's an O(log n) algorithm for actually counting special numbers less than or equal to n. It builds digit strings one at a time, keeping track of whether 2, 3, 5 and 7 divide that digit string's product, and the remainder modulo 2, 3, 5, and 7 of the sum of fourth powers of those digits. The logic for testing whether...
9
4
71,402,387
2022-3-8
https://stackoverflow.com/questions/71402387/the-rationale-of-functools-partial-behavior
I'm wondering what the story -- whether sound design or inherited legacy -- is behind these functools.partial and inspect.signature facts (talking python 3.8 here). Set up: from functools import partial from inspect import signature def bar(a, b): return a / b All starts well with the following, which seems compliant ...
Using partial with a Positional Argument f = partial(bar, 3) By design, upon calling a function, positional arguments are assigned first. Then logically, 3 should be assigned to a with partial. It makes sense to remove it from the signature as there is no way to assign anything to it again! when you have f(a=2, b=6), ...
6
5
71,391,946
2022-3-8
https://stackoverflow.com/questions/71391946/does-raku-have-pythons-union-type
In Python, Python has Union type, which is convenient when a method can accept multi types: from typing import Union def test(x: Union[str,int,float,]): print(x) if __name__ == '__main__': test(1) test('str') test(3.1415926) Raku probably doesn't have Union type as Python, but a where clause can achieve a similar effe...
My answer (which is very similar to your first solution ;) would be: subset Union where Int | Rat | Str; sub test(Union \x) { say(x) } sub MAIN() { test(1); test('str'); test(pi); } Constraint type check failed in binding to parameter 'x'; expected Union but got Num (3.141592653589793e0) (or you can put a where clause...
10
7
71,370,107
2022-3-6
https://stackoverflow.com/questions/71370107/how-to-change-input-keyboard-layout-programmatically-in-pyqt5
Is it possible to change the Input Keyboard Layouts by programmatically in Pyqt5? My first and second text box accepts Tamil letters. IN Tamil So many keyboard Layouts available. By default in Windows 10, Tamil Phonetic, Tamil99 and Tamil Traditional Keyboards are available. Now I want to select Keybaord layouts progra...
So Qt doesn't offer this, but you can ask your OS to do it for you. Assuming you're just looking at Windows, you can change the current keyboard layout in python using pywin32, which lets you easily access the Windows API from your script. Once installed into your Python environment you can import win32api and then use...
6
6
71,367,526
2022-3-6
https://stackoverflow.com/questions/71367526/nextcord-slash-command-nextcord-errors-httpexception-400-bad-request-error-c
I was migrating my bot from discord.py to nextcord and I changed my help command to a slash command, but it kept showing me this error: nextcord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body It said that the error was caused by exceeding 2000 characters in the web. Full Error: Ignoring ...
Explanation From the discord dev docs: CHAT_INPUT command names and command option names must match the following regex ^[\w-]{1,32}$ The regex essentially translates to: If there is a lowercase variant of any letters used, you must use those In this case, your option name, 'Command' has an uppercase 'C', which is ...
4
4
71,344,780
2022-3-3
https://stackoverflow.com/questions/71344780/importerror-dll-load-failed-while-importing-gdal-the-specified-module-could-n
I have a python script that previously worked but that now throws the error:ImportError: DLL load failed while importing _gdal: The specified module could not be found. I am trying to upload a shapefile using fiona and originally the message read: ImportError: DLL load failed while importing _fiona: The specified modul...
I was struggling badly with the same problem for the last couple of days. Using conda, I've tried everything I found on the internet such as: conda update gdal conda update -n base -c defaults conda Creating new environments (over and over again). Despite it's not recommended I even tried it with pip install... but n...
5
5
71,395,504
2022-3-8
https://stackoverflow.com/questions/71395504/input-0-of-layer-model-is-incompatible-with-the-layer-expected-shape-none-5
I am training a Unet segmentation model for binary class. The dataset is loaded in tensorflow data pipeline. The images are in (512, 512, 3) shape, masks are in (512, 512, 1) shape. The model expects the input in (512, 512, 3) shape. But I am getting the following error. Input 0 of layer "model" is incompatible with th...
Use train_batches in model.fit and not train_images. Also, you do not need to use repeat(), which causes an infinite dataset if you do not specify how many times you want to repeat your dataset. Regarding your labels error, try rewriting your model like this: import tensorflow as tf inputs = tf.keras.layers.Input((512,...
5
2
71,380,024
2022-3-7
https://stackoverflow.com/questions/71380024/coverage-py-vs-pytest-cov
The documentation of coverage.py says that Many people choose to use the pytest-cov plugin, but for most purposes, it is unnecessary. So I would like to know what is the difference between these two? And which one is the most efficient ? Thank you in advance
pytest-cov uses coverage.py, so there's no different in efficiency, or basic behavior. pytest-cov auto-configures multiprocessing settings, and ferries data around if you use pytest-xdist.
32
31
71,386,332
2022-3-7
https://stackoverflow.com/questions/71386332/how-do-i-specify-extra-bracket-dependencies-in-a-pyproject-toml
I'm working on a project that specifies its dependencies using Poetry and a pyproject.toml file to manage dependencies. The documentation for one of the libraries I need suggests pip-installing with an "extra" option to one of the dependencies, like this: pip install google-cloud-bigquery[opentelemetry] How should I r...
You can add it by poetry add "google-cloud-bigquery[opentelemetry]". This will result in: [tool.poetry.dependencies] ... google-cloud-bigquery = {extras = ["opentelemetry"], version = "^2.34.2"}
33
44
71,373,337
2022-3-6
https://stackoverflow.com/questions/71373337/invalidentrypoint-for-aws-lambda-with-python-docker-container
I've built an image for Lambda using public.ecr.aws/lambda/python:3.8 but always get this error. Tried changing up the function and file names, but not getting any more details for debugging. Also I've run the function locally and the entrypoint/cmd works. START RequestId: cb4ba88c-c347-4e7d-b1ca-031a2e02fde4 Version: ...
Turned out to be an architecture compatibility issue - Needed to make sure the arch matched between the lambda function, and the docker image. Locally I was building on an M1 with arm64 but the function is configured by default to use amd64 I changed my build command to docker buildx build --platform linux/amd64 -t <im...
29
47
71,372,066
2022-3-6
https://stackoverflow.com/questions/71372066/docker-fails-to-install-cffi-with-python3-9-alpine-in-dockerfile
Im trying to run the below Dockerfile using docker-compose. I searched around but I couldnt find a solution on how to install cffi with python:3.9-alpine. I also read this post which states that pip 21.2.4 or greater can be a possible solution but it didn't work out form me https://www.pythonfixing.com/2021/09/fixed-wh...
@Klaus D.'s comment helped a lot. I updated Dockerfile: RUN apk add --update --no-cache --virtual .tmp-build-deps \ gcc libc-dev linux-headers postgresql-dev \ && apk add libffi-dev
14
23
71,366,868
2022-3-6
https://stackoverflow.com/questions/71366868/django-how-to-pass-variable-to-include-tag-from-url-tag
So right now I hardcode to url, which is a bit annoying if you move endpoints. This is my current setup for my navbar items. # in base.html {% include 'components/navbar/nav-item.html' with title='Event Manager' url='/eventmanager/' %} # in components/navbar/nav-item.html <li> <a href="{{ url }}">{{ title }}</a> </li>...
You can pass it as a variable not django's url tag, use like this: {% url 'event_manager:index' as myurl %} {% include 'components/navbar/link.html' with myurl %} Now you can pass it to include tag.
4
9
71,366,566
2022-3-5
https://stackoverflow.com/questions/71366566/how-to-play-audio-in-jupyter-notebook-with-vscode
Using a jupyter notebook in VSCode, I'm trying to run the following code from this documentation: import numpy as np from IPython.display import Audio framerate = 44100 t = np.linspace(0,5,framerate*5) data = np.sin(2*np.pi*220*t) + np.sin(2*np.pi*224*t) Audio(data, rate=framerate) However, I only get this If I press...
As of today, it seems VSCode Jupyter extension does not support audio. You can track the issue here on their Github. One solution can be merging this pull request and rebuilding VSCode, which is not suggested. The preferred alternate solution is using jupyter lab instead of VSCode for such use cases.
4
5
71,365,904
2022-3-5
https://stackoverflow.com/questions/71365904/how-to-print-all-the-routes-used-in-django
I want to display all the Routes in an app built with Django, something like what Laravel does with the command: php artisan route:list Is there a way to get all the Routes?
django-extensions has command show_urls, sou after instalation you can do: python manage.py show_urls
4
8
71,357,427
2022-3-4
https://stackoverflow.com/questions/71357427/how-to-pass-a-rust-function-as-a-callback-to-python-using-pyo3
I am using Pyo3 to call Rust functions from Python and vice versa. I am trying to achieve the following: Python calls rust_function_1 Rust function rust_function_1 calls Python function python_function passing Rust function rust_function_2 as a callback argument Python function python_function calls the callback, wh...
The comment from PitaJ led me to the solution. Rust code that works: use pyo3::prelude::*; #[pyclass] struct Callback { #[allow(dead_code)] // callback_function is called from Python callback_function: fn() -> PyResult<()>, } #[pymethods] impl Callback { fn __call__(&self) -> PyResult<()> { (self.callback_function)() }...
4
6
71,362,928
2022-3-5
https://stackoverflow.com/questions/71362928/average-values-over-all-offset-diagonals
I'm trying to compute average values of shifted diagonals of a square array. Given input matrix like (in reality much larger than 3x3): [[a, b, c], [d, e, f], [g, h, i]] correct answer would be [g, (d+h)/2, (a+e+i)/3, (b+f)/2, c] A code to compute such average could be: import numpy as np def offset_diag_mean(mat): n...
On efficient solution is to accumulate lines of the input 2D array directly in the output array at a specific position and then perform the division. The idea is to zero-initialize an output array, then add [a, b, c] to output[2:5], then add [d, e, f] to output[1:4] and then add [g, h, i] to output[0:3]. Finally, we ca...
4
3
71,359,897
2022-3-5
https://stackoverflow.com/questions/71359897/why-does-python-point-to-my-systems-default-python-interpreter-instead-of-my
python points to my system's default python interpreter, instead of my pyenv python interpreter. I created the python virtual environment and activated it as follows: pyenv virtualenv 3.8.12 test3 pyenv activate test3 Then, running python gives me a python 3.7 interpreter (which is my system's default python interpret...
Given the new informations you gave us it is most likely that your a missing a eval "$(pyenv init --path)" in your ~/.profile (or in your Dockerfile as you are using K8s) as /root/.pyenv/shim is not part of $PATH. Old answer: Two possible solutions here: Either you did not select your 3.8.12 binary as a system default ...
4
2
71,357,872
2022-3-4
https://stackoverflow.com/questions/71357872/boto3-how-to-assume-iam-role-to-access-other-account
Looking for some guidance with regards to uploading files into AWS S3 bucket via a python script and an IAM role. I am able to upload files using BOTO3 and an aws_access_key_id & aws_secret_access_key for other scripts. However, I have now been given an IAM role to login to a certain account. I have no issue using AWS ...
You should create an entry for the IAM Role in ~/.aws/credentials that refers to a set of IAM User credentials that have permission to assume the role: [my-user] aws_access_key_id = AKIAxxx aws_secret_access_key = xxx [my-role] source_profile = my-user role_arn = arn:aws:iam::123456789012:role/the-role Add an entry to...
4
8
71,356,827
2022-3-4
https://stackoverflow.com/questions/71356827/retrieve-latest-file-with-pathlib
I primarily use pathlib over os for paths, however there is one thing I have failed to get working on pathlib. If for example I require the latest created .csv within a directory I would use glob & os import glob import os target_dir = glob.glob("/home/foo/bar/baz/*.csv") latest_csv = max(target_dir, key=os.path.getcti...
You can achieve it in just pathlib by doing the following: A Path object has a method called stat() where you can retrieve things like creation and modify date. from pathlib import Path files = Path("./").glob("*.py") latest_file = max([f for f in files], key=lambda item: item.stat().st_ctime) print(latest_file)
5
8
71,344,648
2022-3-3
https://stackoverflow.com/questions/71344648/how-to-define-str-for-dataclass-that-omits-default-values
Given a dataclass instance, I would like print() or str() to only list the non-default field values. This is useful when the dataclass has many fields and only a few are changed. @dataclasses.dataclass class X: a: int = 1 b: bool = False c: float = 2.0 x = X(b=True) print(x) # Desired output: X(b=True)
The solution is to add a custom __str__() function: @dataclasses.dataclass class X: a: int = 1 b: bool = False c: float = 2.0 def __str__(self): """Returns a string containing only the non-default field values.""" s = ', '.join(f'{field.name}={getattr(self, field.name)!r}' for field in dataclasses.fields(self) if getat...
11
12
71,353,113
2022-3-4
https://stackoverflow.com/questions/71353113/polars-how-to-reorder-columns-in-a-specific-order
I cannot find how to reorder columns in a polars dataframe in the polars DataFrame docs.
Turns out it is the same as pandas: df = df[['PRODUCT', 'PROGRAM', 'MFG_AREA', 'VERSION', 'RELEASE_DATE', 'FLOW_SUMMARY', 'TESTSUITE', 'MODULE', 'BASECLASS', 'SUBCLASS', 'Empty', 'Color', 'BINNING', 'BYPASS', 'Status', 'Legend']]
27
-2
71,343,002
2022-3-3
https://stackoverflow.com/questions/71343002/downloading-files-from-public-google-drive-in-python-scoping-issues
Using my answer to my question on how to download files from a public Google drive I managed in the past to download images using their IDs from a python script and Google API v3 from a public drive using the following bock of code: from google_auth_oauthlib.flow import Flow, InstalledAppFlow from googleapiclient.disco...
Well thanks to the security update released by Google few months before. This makes the link sharing stricter and you need resource key as well to access the file in-addition to the fileId. As per the documentation , You need to provide the resource key as well for newer links, if you want to access it in the header X-...
6
4
71,351,209
2022-3-4
https://stackoverflow.com/questions/71351209/why-does-map-hide-a-stopiteration
I found a case when map() usage isn't equivalent to a list comprehension. It happens when next used as the first argument. For example: l1 = [1, 2] l2 = ['hello', 'world'] iterators = [iter(l1), iter(l2)] # list comprehension values1 = [next(it) for it in iterators] # values1 = [1, "hello"] values2 = [next(it) for it i...
Try calling next on map: >>> >>> m = map(next, iterators) >>> next(m) 1 >>> next(m) 'hello' >>> next(m) Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration It's list that sees StopIteration and uses it to stop building the list from what map yields. The list comprehension, on the other...
8
7
71,349,515
2022-3-4
https://stackoverflow.com/questions/71349515/how-to-find-all-possible-uniform-substrings-of-a-string
I have a string like aaabbbbcca And I'd like to parse all possible uniform substrings from that. So my expected substrings for this string are ['a', 'aa', 'aaa', 'b', 'bb', 'bbb', 'bbbb', 'c', 'cc', 'a'] I tried the following import re print(re.findall(r"([a-z])(?=\1*)", "aaabbbbcca")) # Output: ['a', 'a', 'a', 'b', ...
You can achieve what you need without a regex here: result = [] text = "aaabbbbcca" prev = '' for c in text: if c == prev: result.append(result[-1] + c) else: result.append(c) prev = c print(result) # => ['a', 'aa', 'aaa', 'b', 'bb', 'bbb', 'bbbb', 'c', 'cc', 'a'] See the Python demo. In short, you can iterate over th...
12
7
71,348,706
2022-3-4
https://stackoverflow.com/questions/71348706/pycharm-code-completion-does-not-work-for-simplenamespace
Why SimpleNamespace code completion does not work in pycharm editor? from types import SimpleNamespace sn= SimpleNamespace(param_a = '1') sn. # pressing '.' dot I'm NOT offered param_a This does work in pycharm python console, suggesting SimpleNamespace instance must be somehow 'computed' at runtime first. However if ...
Why SimpleNamespace code completion does not work in pycharm editor? Because PyCharm doesn't have enough smarts to handle SimpleNamespaces specially (i.e. to know that the kwargs are just assigned into instance attributes). This does work in pycharm python console, suggesting SimpleNamespace instance must be somehow...
5
5
71,333,997
2022-3-3
https://stackoverflow.com/questions/71333997/set-name-execution-in-descriptor
I have came across a code that it is including descriptors. As I understand, __set_name__ is a method that is called when the class is created. Then, if the class is called twice I'd get two calls. In the following snippet I would expect to get the call in __set_name__ twice, but I am getting just one call. Why this be...
TL;DR By the time __set_name__ methods are called, current_tag refers to an instance of property, not an instance of SharedAttribute. __set_name__ is called after the class has been defined (so that the class can be passed as the owner argument), not immediately after the assignment is made. However, you changed the v...
4
4
71,340,374
2022-3-3
https://stackoverflow.com/questions/71340374/how-can-i-set-the-frequency-of-a-pandas-index
So this is my code basically: df = pd.read_csv('XBT_60.csv', index_col = 'date', parse_dates = True) df.index.freq = 'H' I load a csv, set the index to the date column and want to set the frequency to 'H'. But this raises this error: ValueError: Inferred frequency None from passed values does not conform to passed fre...
You can't set frequency if you have missing index values: >>> df val 2019-09-15 0 2019-09-16 1 2019-09-18 3 >>> df.index.freq = 'D' ... ValueError: Inferred frequency None from passed values does not conform to passed frequency D To find missing index, use: >>> df = df.resample('D').first() val 2019-09-15 0.0 2019-09-...
6
8
71,332,870
2022-3-3
https://stackoverflow.com/questions/71332870/pylint-not-an-iterable-error-when-subclassing-listint
Code example: from typing import List class MyList(List[int]): def total(self) -> int: return sum(i for i in self) a = MyList([1,2,3]) print(f'{a.total()=:}') When I run it, it works a.total()=6 But when I use pylint, I get the following error ... toy.py:5:30: E1133: Non-iterable value self is used in an iterating co...
I upgraded pylint to a more recent version. pylint --version pylint 2.9.6 astroid 2.6.6 Python 3.8.2 (default, Mar 15 2021, 10:18:42) and the error is gone. Due to system constraints, I can't upgrade to the very latest version.
5
1
71,336,795
2022-3-3
https://stackoverflow.com/questions/71336795/is-there-a-quicker-method-for-iterating-over-rows-in-python-to-calculate-a-featu
I have a Pandas Dataframe df that details Names of players that play a game. The Dataframe has 2 columns of 'Date' they played a game and their name, sorted by Date. Date Name 1993-03-28 Tom 1993-03-28 Joe 1993-03-29 Tom 1993-03-30 Joe What I am trying to accomplish is to time-efficiently calculate th...
Any time you write "for" and "pandas" anywhere close together you are probably doing something wrong. It seems to me you want the cumulative count: df["prev_games"] = df.sort_values('Date').groupby('Name').cumcount()
4
4
71,333,786
2022-3-3
https://stackoverflow.com/questions/71333786/what-is-the-mechanism-between-max-requests-and-max-requests-jitter-in-gunicorn
According to the official guide https://docs.gunicorn.org/en/latest/settings.html#settings a worker will restart when it has handled max_requests requests. But when max_requests_jitter is set, a worker will restart when it has handled randint(0, max_requests_jitter) request, to stagger worker restarts to avoid all work...
From the docs - The jitter causes the restart per worker to be randomized by randint(0, max_requests_jitter). This is intended to stagger worker restarts to avoid all workers restarting at the same time. What I understand is that the jitter is a random addition to each worker and the term max_requests_jitter should b...
5
7
71,331,483
2022-3-3
https://stackoverflow.com/questions/71331483/alive-progress-bar-not-working-on-pycharm
I am trying to use the alive_progress alive_bar on PyCharm but it only appears in the console once the whole process has finished. Instead, I want it to display and progress as the for loop operates. Toy example: from alive_progress import alive_bar import time bar_l = 100 with alive_bar(bar_l) as bar: for i in range(b...
There is a option to force enable it and see alive-progress in PyCharm. It's "force_tty=True" with alive_bar(1000, force_tty=True) as bar: for i in range(1000): time.sleep(.01) bar()
5
10
71,331,496
2022-3-3
https://stackoverflow.com/questions/71331496/object-assign-equivalent-in-python
Is there an equivalent for Javascript's Object.assign(targetDict, srcDict) in python, which takes all the items from one dictionary into another, replacing as we go? (Cleaner than a for-in loop, anyhow) ------ Context --------- I use Object.assign in javascript to expand out settings-dictionary parameters in large func...
Python has a dict1.update(dict2) method which will do exactly that. :)
5
6
71,328,089
2022-3-2
https://stackoverflow.com/questions/71328089/pandas-extract-all-regex-matches-from-column-join-with-delimiter
I need to extract all matches from a string in a column and populate a second column. The matches will be delimited by a comma. df2 = pd.DataFrame([[1000, 'Jerry', 'string of text BR1001_BR1003_BR9009 more string','BR1003',''], [1001, '', 'BR1010_BR1011 random text', 'BR1010',''], ['', '', 'test to discardBR3009', 'BR2...
You need to use >>> df2['REGEX string'].str.findall(r'BR\d{4}').str.join(", ") 0 BR1001, BR1003, BR9009 1 BR1010, BR1011 2 BR3009 3 BR4009 4 Name: REGEX string, dtype: object With Series.str.findall, you extract all occurrences of the pattern inside a string value, it returns a "Series/Index of lists of strings". To c...
6
6
71,324,949
2022-3-2
https://stackoverflow.com/questions/71324949/import-selenium-could-not-be-resolved-pylance-reportmissingimports
I am editing a file in VS code. VS code gives the following error: Import "selenium" could not be resolved Pylance (reportMissingImports). This is the code from metachar: # Coded and based by METACHAR/Edited and modified for Microsoft by Major import sys import datetime import selenium import requests import time as t ...
PyLance looks for the "selenium" python package and cannot find it in the configured python installation. Since you're using VSCode, make sure you've configured the python extension properly. When you open a .py file in VSCode, you should see a python setting in the status bar down below on the left. Select the install...
14
2
71,324,369
2022-3-2
https://stackoverflow.com/questions/71324369/does-time-complexity-change-when-two-nested-loops-are-re-written-into-a-single-l
Is the time complexity of nested for, while, and if statements the same? Suppose a is given as an array of length n. for _ in range(len(a)): for _ in range(len(a)): do_something The for statement above will be O(n²). i = 0 while i < len(a) * len(a): do_something i += 1 At first glance, the above loop can be thought o...
Am I right? Yes! The double loop: for _ in range(len(a)): for _ in range(len(a)): do_something has a time complexity of O(n) * O(n) = O(n²) because each loop runs until n. The single loop: i = 0 while i < len(a) * len(a): do_something i += 1 has a time complexity of O(n * n) = O(n²), because the loop runs until i =...
23
50
71,322,568
2022-3-2
https://stackoverflow.com/questions/71322568/create-dictionary-from-several-columns-based-on-position-of-values
I have a dataframe like this import pandas as pd df = pd.DataFrame( { 'C1': list('aabbab'), 'C2': list('abbbaa'), 'value': range(11, 17) } ) C1 C2 value 0 a a 11 1 a b 12 2 b b 13 3 b b 14 4 a a 15 5 b a 16 and I would like to generate a dictionary like this: {'C1': {'a': {1: 11, 2: 12, 3: 15}, 'b': {1: 13, 2: 14, 3: ...
You could use a groupby and a nested dict comprehension: import pandas as pd df = pd.DataFrame( { 'C1': list('aabbab'), 'C2': list('abbbaa'), 'value': range(11, 17) } ) d = { c: {k: dict(enumerate(g["value"], 1)) for k, g in df.groupby(c)} for c in ["C1", "C2"] } Which outputs: {'C1': {'a': {1: 11, 2: 12, 3: 15}, 'b':...
4
5
71,319,929
2022-3-2
https://stackoverflow.com/questions/71319929/how-to-find-and-replace-text-in-a-single-cell-when-using-jupyter-extension-insid
As the title says, how to find and replace text inside a single jupyter cell when using the jupyter extension in Visual Studio Code? I am familiar with ctr+h but that will replace all the occurrences in the entire jupyter notebook file. This is a really important feature for me, as I am using it a lot in jupyter on the...
You can select the first occurrence and then use Ctrl+D. It will select the next occurence in the cell. Repeat that until you go back to the first ocurrence and then type the new value. It will replace all the values your circled on. In case you have changed that keyboard shortcut or if it is different you can find the...
12
6
71,320,044
2022-3-2
https://stackoverflow.com/questions/71320044/why-does-the-sortwith-key-function-not-work-as-intended
# A function that returns the frequency of each value: def myFunc(e): return cars.count(e) cars = ['Ford', 'Ford', 'Ford', 'Mitsubishi','Mitsubishi', 'BMW', 'VW'] cars.sort(key=myFunc) print(cars) Output: ['Ford', 'Ford', 'Ford', 'Mitsubishi', 'Mitsubishi', 'BMW', 'VW'] What I expect: ['BMW', 'VM', 'Mitsubishi', 'Mit...
The problem is that you are using cars inside the key function, but .sort is in-place. This causes cars to be unreliable in intermediate calls to the key function. We can see the problem if we print cars inside the key function: def myFunc(e): print(cars) return cars.count(e) cars = ['Ford', 'Ford', 'Ford', 'Mitsubishi...
4
4
71,316,065
2022-3-2
https://stackoverflow.com/questions/71316065/aws-cdk-secrets-manger-getting-the-full-arn-python
I am trying to create a canary resource that uses a script that needs a secret. I'm trying to add a policy statement to the canary role (which I'm creating as part of the cdk). To do this I need to get the secrets full arn, I can get the partial arn with secret_from_name = secretsmanager.Secret.from_secret_name_v2 the...
Secret ARNs have a dash and 6 random characters at the end. Define the IAM policy statement's resource with a -?????? wildcard suffix to grant your role access to all versions of the secret name. { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": "secretsmanager:GetSecretValue", "Resource": [ "arn...
6
11
71,298,179
2022-2-28
https://stackoverflow.com/questions/71298179/fastapi-how-to-get-app-instance-inside-a-router
I want to get the app instance in my router file, what should I do ? My main.py is as follows: # ... app = FastAPI() app.machine_learning_model = joblib.load(some_path) app.include_router(some_router) # ... Now I want to use app.machine_learning_model in some_router's file , what should I do ?
Since FastAPI is actually Starlette underneath, you could store the model on the application instance using the generic app.state attribute, as described in Starlette's documentation (see State class implementation too). Example: app.state.ml_model = joblib.load(some_path) As for accessing the app instance (and subseq...
18
35
71,256,853
2022-2-24
https://stackoverflow.com/questions/71256853/how-do-i-install-python2-on-centos-9-stream
I am trying to figure out how to install python2 on centos9 stream. I am getting the errors below. Any suggestions? sudo dnf install python2 Last metadata expiration check: 0:04:48 ago on Thu 24 Feb 2022 01:43:10 PM EST. No match for argument: python2 Error: Unable to find a match: python2
how to install python2 on centos9 stream You cannot do that from any repo. No available repo / no packages. Reason: python2.7 had End Of Life January 1, 2020. https://endoflife.date/python
7
2
71,278,961
2022-2-26
https://stackoverflow.com/questions/71278961/how-can-i-decompile-pyc-files-from-python-3-10
I did try uncompyle6, decompyle3, and others, but none of them worked with Python 3.10. Is it even possible to do this right now?
Use pycdc. Github: https://github.com/zrax/pycdc git clone https://github.com/zrax/pycdc cd pycdc cmake . make make check pycdc C:\Users\Bobby\example.pyc
8
21
71,250,418
2022-2-24
https://stackoverflow.com/questions/71250418/call-the-generated-init-from-custom-constructor-in-dataclass-for-defaults
Is it possible to benefit from dataclasses.field, especially for default values, but using a custom constuctor? I know the @dataclass annotation sets default values in the generated __init__, and won't do it anymore if I replace it. So, is it possible to replace the generated __init__, and to still call it inside? @dat...
As I perceive it, the cleaner approach there is to have an alternative classmethod to use as your constructor: this way, the dataclass would work exactly as intended and you could just do: from dataclasses import dataclass, field from typing import Optional @dataclass class A: l: list[int] = field(default_factory=list)...
7
4
71,239,268
2022-2-23
https://stackoverflow.com/questions/71239268/passing-commands-to-the-wsl-shell-from-a-windows-python-script
I'm on Windows using PowerShell and WSL 'Ubuntu 20.04 LTS'. I have no native Linux Distro, and I cant use virtualisation because of nested device reasons. My purpose is to use a Windows Python script in PowerShell to call WSL to decrypt some avd-snapshots into raw-images. I already tried os.popen, subprocess.Popen/run/...
There are a few ways of running WSL scripts/commands from Windows Python, but a SendKeys-based approach is usually the last resort, IMHO, since it's: Often non-deterministic Lacks any control logic Also, avoid the ubuntu2004.exe (or, for other users who find this, the deprecated bash.exe command). The much more capab...
6
9
71,236,391
2022-2-23
https://stackoverflow.com/questions/71236391/pytorch-lightning-print-accuracy-and-loss-at-the-end-of-each-epoch
In tensorflow keras, when I'm training a model, at each epoch it print the accuracy and the loss, I want to do the same thing using pythorch lightning. I already create my module but I don't know how to do it. import torch import torch.nn as nn from residual_block import ResidualBlock import pytorch_lightning as pl fro...
self.log("train_loss", loss, prog_bar=True, on_step=False, on_epoch=True) The above code logs train_loss to the progress bar. https://pytorch-lightning.readthedocs.io/en/stable/extensions/logging.html#automatic-logging Or you can use this if on one device: def training_step(self, batch, batch_idx): ... loss = nn.functi...
7
12
71,268,169
2022-2-25
https://stackoverflow.com/questions/71268169/optional-query-parameters-in-fastapi
I don't understand optional query parameters in FastAPI. How is it different from default query parameters with a default value of None? What is the difference between arg1 and arg2 in the example below where arg2 is made an optional query parameter as described in the above link? @app.get("/info/") async def info(arg1...
This is covered in the FastAPI reference manual, albeit just as a small note: async def read_items(q: Optional[str] = None): FastAPI will know that the value of q is not required because of the default value = None. The Optional in Optional[str] is not used by FastAPI, but will allow your editor to give you better su...
24
31
71,263,405
2022-2-25
https://stackoverflow.com/questions/71263405/run-bash-command-via-subprocess-in-python-without-bandit-warning-b404-and-b603
Since the pre-commit hook does not allow even warnings and commits issued by bandit, I need to find a way to execute bash commands from python scripts without bandit complaining. Using the subprocess python package, bandit has always complained so far, no matter what I did. I used ".run()", ".check_call()", ".Popen()"...
In order for the code to be secure, you need to know that source_dir target_bucket_name profile_name aren't malicious: e.g. can an untrusted user pass .ssh as the value to be copied? Once you know the subprocess line is secure, you can add # nosec comment to tell bandit not to give a warning about the line: subprocess....
6
3
71,312,665
2022-3-1
https://stackoverflow.com/questions/71312665/you-may-have-failed-to-include-the-related-model-in-your-api-or-incorrectly-con
I'm trying to setup the lookup field between two entities, but I can't fix this error. I've already tried these solutions but none of them worked for me(What am I doing wrong?): Django Rest Framework, improperly configured lookup field Django Rest Framework - Could not resolve URL for hyperlinked relationship using vie...
Defining the lookup_field attribute for the options in the CategorySerializer solved the problem. Here's the CategorySerializer class: class CategorySerializer(serializers.HyperlinkedModelSerializer): options = serializers.HyperlinkedRelatedField( view_name='option-detail', lookup_field = 'slug', many=True, read_only=T...
5
7
71,306,070
2022-3-1
https://stackoverflow.com/questions/71306070/do-you-need-to-put-eos-and-bos-tokens-in-autoencoder-transformers
I'm starting to wrap my head around the transformer architecture, but there are some things that I am not yet able to grasp. In decoder-free transformers, such as BERT, the tokenizer includes always the tokens CLS and SEP before and after a sentence. I understand that CLS acts both as BOS and as a single hidden output ...
First, a little about BERT - BERT word embeddings allow for multiple vector representations for the same word, based on the context in which the word was used. In this sense, BERT embeddings are context-dependent. BERT explicitly takes the index position of each word in the sentence while calculating its embedding. The...
5
5
71,248,521
2022-2-24
https://stackoverflow.com/questions/71248521/why-numexpr-defaulting-to-8-threads-warning-message-shown-in-python
I am trying to use the lux library in python to get visualization recommendations. It shows warnings like NumExpr defaulting to 8 threads.. import pandas as pd import numpy as np import opendatasets as od pip install lux-api import lux import matplotlib And then: link = "https://www.kaggle.com/noordeen/insurance-premi...
This is not really something to worry about in most cases. The warning comes from this function, here the most important part: ... env_configured = False n_cores = detect_number_of_cores() if 'NUMEXPR_MAX_THREADS' in os.environ: # The user has configured NumExpr in the expected way, so suppress logs. env_configured = T...
12
11
71,258,548
2022-2-24
https://stackoverflow.com/questions/71258548/how-to-convert-dataframe-append-to-pandas-concat
In pandas 1.4.0: append() was deprecated, and the docs say to use concat() instead. FutureWarning: The frame.append method is deprecated and will be removed from pandas in a future version. Use pandas.concat instead. Codeblock in question: def generate_features(data, num_samples, mask): """ The main function for gene...
You can store the DataFrames generated in the loop in a list and concatenate them with features once you finish the loop. In other words, replace the loop: for count in range(num_samples): # .... code to produce `input_vars` features = features.append(input_vars) # remove this `DataFrame.append` with the one below: tm...
21
18
71,311,507
2022-3-1
https://stackoverflow.com/questions/71311507/modulenotfounderror-no-module-named-app-fastapi-docker
FROM python:3.8 WORKDIR /app COPY requirements.txt / RUN pip install --requirement /requirements.txt COPY ./app /app EXPOSE 8000 CMD ["uvicorn", "app.main:app", "--host=0.0.0.0" , "--reload" , "--port", "8000"] when i used docker-compose up -d ModuleNotFoundError: No module named 'app' the folders in Fastapi framew...
CMD ["uvicorn", "main:app", "--host=0.0.0.0" , "--reload" , "--port", "8000"] Your work directory is /app and the main.py file is already there. So you don't need to call app.main module. Just call main.py script directly in CMD.
5
13
71,302,366
2022-3-1
https://stackoverflow.com/questions/71302366/how-can-i-programmatically-trigger-an-event-with-pysimplegui
For example, the "Show" event in the example below is tied to clicking the "Show" button. Is there a way to programmatically fire off the "Show" event without actually clicking the button? The goal is to automate clicking a series of buttons and filling text boxes by just clicking one other button instead, like a brows...
From martineau's comment above: You can generate a click of the button as if the user clicked on it by calling its click() method. See the docs. Aditionally, you can fire a specific event with: write_event_value(key, value)
4
6
71,285,719
2022-2-27
https://stackoverflow.com/questions/71285719/python-loop-to-run-after-n-minutes-from-start-time
I am trying to create a while loop which will iterate between 2 time objects, while datetime.datetime.now().time() <= datetime.datetime.now() +relativedelta(hour=1): but on every n minutes or second interval. So if the starting time was 1:00 AM, the next iteration should begin at 1:05 AM with n being 5 mins. So the ite...
I believe this could be considered an object-oriented "canonical" solution which creates a Thread subclass instance that will call a specified function repeatedly every datetime.timedelta units until canceled. The starting and how long it's left running are not details the class concerns itself with, and are left to th...
5
2
71,279,968
2022-2-26
https://stackoverflow.com/questions/71279968/getting-a-prediction-from-an-onnx-model-in-python
I can't find anyone who explains to a layman how to load an onnx model into a python script, then use that model to make a prediction when fed an image. All I could find were these lines of code: sess = rt.InferenceSession("onnx_model.onnx") input_name = sess.get_inputs()[0].name label_name = sess.get_outputs()[0].name...
Let's first start by going over the code you provided, to make everything clear. sess = ort.InferenceSession("onnx_model.onnx") This line loads the model into a session object. This means that the layers, functions and weights used in the model are made ready to perform inferences. input_name = sess.get_inputs()[0].na...
6
7
71,288,513
2022-2-27
https://stackoverflow.com/questions/71288513/how-can-i-determine-validation-loss-for-faster-rcnn-pytorch
I followed this tutorial for object detection: https://pytorch.org/tutorials/intermediate/torchvision_tutorial.html and their GitHub repository that contains the following train_one_epoch and evaluate functions: https://github.com/pytorch/vision/blob/main/references/detection/engine.py However, I want to calculate loss...
So it turns out no stages of the pytorch fasterrcnn return losses when model.eval() is set. However, you can just manually use the forward code to generate the losses in evaluation mode: from typing import Tuple, List, Dict, Optional import torch from torch import Tensor from collections import OrderedDict from torchvi...
4
8
71,263,622
2022-2-25
https://stackoverflow.com/questions/71263622/sslcertverificationerror-when-downloading-pytorch-datasets-via-torchvision
I am having trouble downloading the CIFAR-10 dataset from pytorch. Mostly it seems like some SSL error which I don't really know how to interpret. I have also tried changing the root to various other folders but none of them works. I was wondering whether it is a permission type setting on my end but I am inexperienced...
Turn off the ssl verification. import ssl ssl._create_default_https_context = ssl._create_unverified_context
6
13
71,262,481
2022-2-25
https://stackoverflow.com/questions/71262481/how-to-avoid-roundoff-errors-in-numpy-random-choice
Say x_1, x_2, ..., x_n are n objects and one wants to pick one of them so that the probability of choosing x_i is proportional to some number u_i. Numpy provides a function for that: x, u = np.array([x_1, x_2, ..., x_n]), np.array([u_1, ..., u_n]) np.random.choice(x, p = u/np.sum(u)) However, I have observed that this...
After reading the answer https://stackoverflow.com/a/60386427/6087087 to the question pointed by @Pychopath, I have found the following solution, inspired by the documentation of numpy.random.multinomial https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.random.multinomial.html Say p is the array of prob...
4
6
71,260,969
2022-2-25
https://stackoverflow.com/questions/71260969/changing-overlap-order-of-a-line-chart-in-altair
I generate a line chart in Altair. I'd like to control which lines are "on top" of the stack of lines. In my example here, I wish for the red line to be on top (newest date) and then descend down to the yellow (oldest date) to be on the bottom. I tried to control this with the sort parameter of of alt.Color but regard...
By default, graphical marks are plotted in the order they occur in the dataframe (as you noted), which means that the elements last in the dataframe will be plotted last and end up on top in the chart (called the highest "layer" or the highest "z-order"): import pandas as pd import altair as alt df = pd.DataFrame({ 'a'...
5
4
71,299,591
2022-2-28
https://stackoverflow.com/questions/71299591/why-is-typing-mapping-not-a-protocol
As described here, some built-in generic types are Protocols. This means that as long as they implement certain methods, type-checkers will mark them as being compatible with the type: If a class defines a suitable __iter__ method, mypy understands that it implements the iterable protocol and is compatible with Iterab...
It appears to be deliberate, and basically boils down to 'we think that type is too complex to be a protocol.' See https://www.python.org/dev/peps/pep-0544/#changes-in-the-typing-module. Note that you can get this effect by having your own class extend abc.Mapping
5
5
71,255,965
2022-2-24
https://stackoverflow.com/questions/71255965/403-error-returned-from-python-get-requests-but-auth-works-in-postman
I'm trying to return a GET request from an API using HTTPBasicAuth. I've tested the following in Postman, and received the correct response URL:"https://someapi.data.io" username:"username" password:"password" And this returns me the data I expect, and all is well. When I've tried this in python however, I get kicked ...
You have not conveyed all the required parameters. And postman is doing this automatically for you. To be able to use in python requests just specify all the required parameters. headers = { 'Host': 'sub.example.com', 'User-Agent': 'Chrome v22.2 Linux Ubuntu', 'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate, br', 'C...
5
5
71,300,294
2022-2-28
https://stackoverflow.com/questions/71300294/how-to-terminate-pythons-processpoolexecutor-when-parent-process-dies
Is there a way to make the processes in concurrent.futures.ProcessPoolExecutor terminate if the parent process terminates for any reason? Some details: I'm using ProcessPoolExecutor in a job that processes a lot of data. Sometimes I need to terminate the parent process with a kill command, but when I do that the proces...
You can start a thread in each process to terminate when parent process dies: def start_thread_to_terminate_when_parent_process_dies(ppid): pid = os.getpid() def f(): while True: try: os.kill(ppid, 0) except OSError: os.kill(pid, signal.SIGTERM) time.sleep(1) thread = threading.Thread(target=f, daemon=True) thread.star...
9
15
71,292,505
2022-2-28
https://stackoverflow.com/questions/71292505/tk-python-checkbutton-rtl
I have a checkbutton: from tkinter import * master = Tk() Checkbutton(master, text="Here...").grid(row=0, sticky=W) mainloop() Which looks like this: I tried to move the checkbutton to the other side (to support RTL languages), so it'll be like: Here...[] I know that I can draw a label next to the checkbutton, but th...
You can bind the left mouse button click event of the label, to a lambda construct that toggles the checkbutton -: label.bind("<Button-1>", lambda x : check_button.toggle()) The label can then be placed before the checkbutton using grid(as mentioned in the OP at the end) -: from tkinter import * master = Tk() l1 = Lab...
6
5
71,306,092
2022-3-1
https://stackoverflow.com/questions/71306092/how-to-login-manually-to-telegram-account-with-pyrogram-without-interactive-cons
I'm using Python's pyrogram lib to login to multiple accounts. I need to create a function just to send verification code to account and then read it from other user input (not the default pyrogram login prompt). When I use send_code it sends code and waits for user input from console and that what I don't want it to d...
I found a way to do it but with Telethon : client = TelegramClient('sessionfile',api_id,api_hash) def getcode(): code = ... # get the code from somewhere ( bot, file etc.. ) return code client.start(phone=phone_number,password=password,code_callback=getcode) this will login , gets confirmation code from specific funct...
5
3
71,313,812
2022-3-1
https://stackoverflow.com/questions/71313812/pattern-matching-to-check-a-protocol-getting-typeerror-called-match-pattern-mu
I need to match cases where the input is iterable. Here's what I tried: from typing import Iterable def detector(x: Iterable | int | float | None) -> bool: match x: case Iterable(): print('Iterable') return True case _: print('Non iterable') return False That is producing this error: TypeError: called match pattern mu...
The problem is the typing.Iterable is only for type hints and is not considered a "type" by structural pattern matching. Instead, you need to use an abstract base class for detecting iterability: collections.abc.Iterable. The solution is distinguish the two cases, marking one as being a type hint and the other as a cla...
5
8
71,312,712
2022-3-1
https://stackoverflow.com/questions/71312712/why-the-latest-python-3-8-x-release-provides-no-windows-installer
I need to install Python 3.8 on a Windows computer and hope to use the latest minor version of 3.8.12. The official release web page provides tarball files of the source code but no Windows installer. Python 3.8.10 provides Windows installers, but it is not the latest version. I am wondering: Why v3.8.12 does not prov...
https://devguide.python.org/#status-of-python-branches provides a summary of the various release statuses. features new features, bugfixes, and security fixes are accepted. prerelease feature fixes, bugfixes, and security fixes are accepted for the upcoming feature release. bugfix bugfixes and security fixes are acce...
7
5
71,290,699
2022-2-28
https://stackoverflow.com/questions/71290699/is-it-possible-to-connect-to-auradb-with-neomodel
Is it possible to connect to AuraDB with neomodel? AuraDB connection URI is like neo4j+s://xxxx.databases.neo4j.io. This is not contained user/password information. However, connection config of neomodel is bolt and it is contained user/password information. config.DATABASE_URL = 'bolt://neo4j:password@localhost:7687'
Connecting to neo4j Aura uses neo4j+s protocol so you need to use the provided uri by Aura. Reference: https://neo4j.com/developer/python/#driver-configuration In example below; you can set the database url by setting the userid and password along with the uri. It works for me so it should also work for you. from neomo...
7
6
71,309,179
2022-3-1
https://stackoverflow.com/questions/71309179/how-to-check-if-named-capture-group-exists
I'm wondering what is the proper way to test if a named capture group exists. Specifically, I have a function that takes a compiled regex as an argument. The regex may or may not have a specific named group, and the named group may or may not be present in a string being passed in: some_regex = re.compile("^foo(?P<idx>...
You can check the groupdict of the match object: import re some_regex = re.compile("^foo(?P<idx>[0-9]*)?$") match = some_regex.match('foo11') print(True) if match and 'idx' in match.groupdict() else print(False) # True match = some_regex.match('bar11') print(True) if match and 'idx' in match.groupdict() else print(Fals...
6
1
71,301,504
2022-2-28
https://stackoverflow.com/questions/71301504/accumulate-the-grouped-sum-of-values-across-trillions-of-values
I have a data reduction issue that is proving to be very difficult to solve. Essentially, I have a program that calculates incremental values (floating point) for pairs of keys from a set of about 60 million keys total. The program will generate values for about 53 trillion pairs 'relatively' quickly (simply iterating ...
As Frank Yellin observes, there's a one-round MapReduce algorithm. The mapper produces key-value pairs with key key1,key2 and value val. The MapReduce framework groups these pairs by key (the shuffle). The reducer sums the values. In order to control the memory usage, MapReduce writes the intermediate data to disk. Tra...
5
3
71,290,916
2022-2-28
https://stackoverflow.com/questions/71290916/vs-code-pylance-works-slow-with-much-delay
When I try to use the autocomplete using Pylance it is stuck there for some time and After Some time like 3 ~ 5 seconds the pop up with auto-complete shows up Python Language Server is already set to Pylance What I've tried so far. Reinstall Python Extension. Reinstall VS Code Restarted Python Language Server Reset VS ...
It works well on my computer, how do you open this python file? Try moving your code to its own folder and opening that up instead of opening up some big folder that contains a lot of files. This does show a performance hole where large workspaces take a while to load. You can refer to this page for more details.
18
3
71,305,358
2022-3-1
https://stackoverflow.com/questions/71305358/python-default-value-of-function-as-a-function-argument
Suppose I have the function: def myF(a, b): return a*b-2*b and let's say that I want a default value for b to be a-1. If I write: def myF(a, b=a-1): return a*b-2*b I get the error message: NameError: name 'a' is not defined I can use the code below: def myF(a, b): return a*b-2*b def myDefaultF(a): return myF(a, a-1)...
You can do the following: def myF(a, b=None): if b is None: b = a - 1 return a * b - 2 * b
5
9
71,298,402
2022-2-28
https://stackoverflow.com/questions/71298402/is-there-a-better-way-to-search-a-sorted-list-if-the-other-list-is-sorted-too
In the numpy library, one can pass a list into the numpy.searchsorted function, whereby it searched through a different list one element at a time and returns an array of the same sizes as the indices needed to preserve order. However, it seems to be wasting performance if both lists are sorted. For example: m=[1,3,5,7...
AFAIK, this is not possible to do that in linear time only with Numpy without making additional assumptions on the inputs (eg. the integer are small and bounded). An alternative solution is to use Numba to do the merge manually: import numba as nb # Note: Numba requires a function signature with well defined array type...
4
2
71,297,994
2022-2-28
https://stackoverflow.com/questions/71297994/django-query-annotate-values-get-list-from-reverse-foreign-key
I have a simple model like class Author(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Blog(models.Model): title = models.CharField(max_length=100) author = models.ForeignKey(Author, on_delete=models.CASCADE) Here I want to queryall authors with the title of all the bl...
If you are using a postgres as a database, then you can use an ArrayAgg function: from django.contrib.postgres.aggregates import ArrayAgg authors = Author.objects.annotate(blogs=ArrayAgg('blog_set__title'))
4
4
71,297,697
2022-2-28
https://stackoverflow.com/questions/71297697/modulenotfounderror-when-running-a-simple-pytest
Python version 3.6 I have the following folder structure . ├── main.py ├── tests/ | └── test_Car.py └── automobiles/ └── Car.py my_program.py from automobiles.Car import Car p = Car("Grey Sedan") print(p.descriptive_name()) Car.py class Car(): description = "Default" def __init__(self, message): self.description = me...
You have 2 options: Run python -m pytest instead of pytest, which will also add the current directory to sys.path (see official docs for details). Add a __init__.py file under tests/, then you can simply run pytest. This basically enables pytest to discover the tests if they live outside of the application code. You ...
5
6
71,287,607
2022-2-27
https://stackoverflow.com/questions/71287607/how-to-make-a-normal-distribution-graph-from-data-frame-in-python
my question is how to make a normal distribution graph from data frame in Python. I can find many information to make such a graph from random numbers, but I don't know how to make it from data frame. First, I generated random numbers and made a data frame. import numpy as np import pandas from pandas import DataFrame ...
I found one solution to make a normal distribution graph from data frame. #Library import numpy as np import pandas as pd import matplotlib.pyplot as plt import scipy.stats as stats #Generating data frame x = np.random.normal(50, 3, 1000) source = {"Genotype": ["CV1"]*1000, "AGW": x} df = pd.DataFrame(source) # Calcula...
4
6
71,297,077
2022-2-28
https://stackoverflow.com/questions/71297077/python-regex-replace-every-2nd-occurrence-in-a-string
I have a string with data that looks like this: str1 = "[2.4],[5],[2.54],[4],[3.36],[4.46],[3.36],[4],[3.63],[4.86],[4],[4.63]" I would want to replace every second iteration of "],[" with "," so it will look like this: str2 = "[2.4,5],[2.54,4],[3.36,4.46],[3.36,4],[3.63,4.86],[4,4.63]" Here is was I have so far: str...
You can use import re from itertools import count str1 = "[2.4],[5],[2.54],[4],[3.36],[4.46],[3.36],[4],[3.63],[4.86],[4],[4.63]" c = count(0) print( re.sub(r"],\[", lambda x: "," if next(c) % 2 == 0 else x.group(), str1) ) # => [2.4,5],[2.54,4],[3.36,4.46],[3.36,4],[3.63,4.86],[4,4.63] See the Python demo. The regex ...
6
6
71,297,090
2022-2-28
https://stackoverflow.com/questions/71297090/can-i-unpack-destructure-a-typing-namedtuple
This is a simple question so I'm surprised that I can't find it asked on SO (apologies if I've missed it), and it always pops into my mind as I contemplate a refactor to replace a tuple by a NamedTuple. Can I unpack a typing.NamedTuple as arguments or as a destructuring assignment, like I can with a tuple?
Yes you certainly can. from typing import NamedTuple class Test(NamedTuple): a: int b: int t = Test(1, 2) # destructuring assignment a, b = t # a = 1 # b = 2 def f(a, b): return f"{a}{b}" # unpack f(*t) # '12' Unpacking order is the order of the fields in the definition.
5
5
71,272,721
2022-2-25
https://stackoverflow.com/questions/71272721/why-does-creating-a-variable-name-for-an-exception-raised-in-a-python-function-a
I've defined two simple Python functions that take a single argument, raise an exception, and handle the raised exception. One function uses a variable to refer to the exception before raising/handling, the other does not: def refcount_unchanged(x): try: raise Exception() except: pass def refcount_increases(x): e = Exc...
It is a side effect of the "exception -> traceback -> stack frame -> exception" reference cycle from the __traceback__ attribute on exception instances introduced in PEP-344 (Python 2.5), and resolved in cases like refcount_unchanged in PEP-3110 (Python 3.0). In refcount_increases, the reference cycle can be observed b...
4
5
71,291,252
2022-2-28
https://stackoverflow.com/questions/71291252/how-to-pass-multiple-arguments-in-multiprocessing-executor-map-function
I have been watching several videos on Multiprocessing map function. I know that I can send one list as an argument to the function I want to target with Multiprocessing, and that will call the same function n times (dependent upon the size of that passed list). What I am struggling to do is what if I want to pass mult...
If your second and third arguments to your worker function (i.e. the first argument to map), then you can use method functools.partial to have the second and third arguments specified without resorting to the use of global variables. If your worker functions is, for example, foo, then: from concurrent.futures import Pr...
5
2
71,295,840
2022-2-28
https://stackoverflow.com/questions/71295840/python-pip-error-legacy-install-failure
I want to install gensim python package via pip install gensim But this error occurs and I have no idea what should I do to solve it. running build_ext building 'gensim.models.word2vec_inner' extension error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudi...
If you fail to install plugins, you can download it from other repositories like this one: repository depends on the version of python and the system. for example: for windows 11(x64) and python 3.10 you should take this file: gensim‑4.1.2‑cp310‑cp310‑win_amd64.whl
31
11
71,294,619
2022-2-28
https://stackoverflow.com/questions/71294619/json-to-markdown-table-formatting
I'm trying to build out a function to convert JSON data into a list to then be used as base for building out markdown tables. I have a first prototype: #!/usr/bin/env python3 import json data = { "statistics": { "map": [ { "map_name": "Location1", "nan": "loc1", "dont": "ignore this", "packets": "878607764338" }, { "ma...
If you are at a liberty to use pandas, this is quite straight forward. The markdown feature is readily available. See example below. import pandas df = pandas.DataFrame.from_dict(data['statistics']['map']).rename(columns={'map_name':'Name', 'nan':'NaN', 'packets':'Packages'}) df.drop(['dont'], axis=1, inplace=True) pri...
7
9
71,294,521
2022-2-28
https://stackoverflow.com/questions/71294521/tkinter-window-appears-black-upon-running-in-pycharm
Tkinter background appears black upon running script no matter how I attribute the background colour. I'm using PyCharm CE 2021.3.2 on macOS 12.2.1. Python Interpreter = Python 3.8 with 5 packages (as follows): Pillow 9.0.1 future 0.18.2 pip 22.0.3 setuptools 57.0.0 wheel 0.36.2 Window looks like this: Black, blank T...
Thanks to @typedecker Issue was with Python 3.8 and the Monterey update. Fix: First install Python 3.10 then follow this tutorial: Creating Python 3.10 Virtual Env Then simply select the newly created virtual env in PyCharms and run.
6
4
71,281,717
2022-2-27
https://stackoverflow.com/questions/71281717/connecting-elasticsearch-to-django-using-django-elasticsearch-dsl-results-in-c
I am trying to call a local ES instance running on docker. I used the following instructions to setup my ES instance: https://www.elastic.co/guide/en/elasticsearch/reference/current/getting-started.html https://www.elastic.co/guide/en/elasticsearch/reference/current/docker.html#docker-cli-run-dev-mode I am able to play...
I figured that it was an issue with my certificate. I needed to add some additional config param to the ELASTICSEARCH_DSL variable. Adding this solves the issue: from elasticsearch import RequestsHttpConnection # Elasticsearch configuration in settings.py ELASTICSEARCH_DSL = { 'default': { 'hosts': 'localhost:9200', 'u...
5
8
71,289,347
2022-2-27
https://stackoverflow.com/questions/71289347/pytesseract-improving-ocr-accuracy-for-blurred-numbers-on-an-image
Example of numbers I am using the standard pytesseract img to text. I have tried with digits only option 90% of the time it is perfect but above is a example where it goes horribly wrong! This example produced no characters at all As you can see there are now letters so language option is of no use, I did try adding s...
Here's a simple approach using OpenCV and Pytesseract OCR. To perform OCR on an image, it's important to preprocess the image. The idea is to obtain a processed image where the text to extract is in black with the background in white. To do this, we can convert to grayscale, then apply a sharpening kernel using cv2.fil...
4
6
71,287,550
2022-2-27
https://stackoverflow.com/questions/71287550/repeatedly-removing-the-maximum-average-subarray
I have an array of positive integers. For example: [1, 7, 8, 4, 2, 1, 4] A "reduction operation" finds the array prefix with the highest average, and deletes it. Here, an array prefix means a contiguous subarray whose left end is the start of the array, such as [1] or [1, 7] or [1, 7, 8] above. Ties are broken by taki...
This problem has a fun O(n) solution. If you draw a graph of cumulative sum vs index, then: The average value in the subarray between any two indexes is the slope of the line between those points on the graph. The first highest-average-prefix will end at the point that makes the highest angle from 0. The next highest-a...
29
34
71,287,630
2022-2-27
https://stackoverflow.com/questions/71287630/how-do-i-get-tqdm-working-on-pandas-apply
Tqdm documentation shows an example of tqdm working on pandas apply using progress_apply. I adapted the following code from here https://tqdm.github.io/docs/tqdm/ on a process that regularly take several minutes to perform (func1 is a regex function). from tqdm import tqdm tqdm.pandas() df.progress_apply(lambda x: func...
Utilizing tqdm with pandas Generally speaking, people tend to use lambdas when performing operations on a column or row. This can be done in a number of ways. Please note: that if you are working in jupyter notebook you should use tqdm_notebook instead of tqdm. Also I'm not sure what your code looks like but if you're...
8
20
71,232,879
2022-2-23
https://stackoverflow.com/questions/71232879/how-to-speed-up-async-requests-in-python
I want to download/scrape 50 million log records from a site. Instead of downloading 50 million in one go, I was trying to download it in parts like 10 million at a time using the following code but it's only handling 20,000 at a time (more than that throws an error) so it becomes time-consuming to download that much d...
Bottleneck: number of simultaneous connections First, the bottleneck is the total number of simultaneous connections in the TCP connector. That default for aiohttp.TCPConnector is limit=100. On most systems (tested on macOS), you should be able to double that by passing a connector with limit=200: # async with aiohttp....
9
20
71,277,957
2022-2-26
https://stackoverflow.com/questions/71277957/how-to-zip-a-file-in-python
I have been trying to make a python script to zip a file with the zipfile module. Although the text file is made into a zip file, It doesn't seem to be compressing it; testtext.txt is 1024KB whilst testtext.zip (The code's creation) is also equal to 1024KB. However, if I compress testtext.txt manually in File Explorer,...
Well that's odd. Python's zipfile defaults to the stored compression method, which does not compress! (Why would they do that?) You need to specify a compression method. Use ZIP_DEFLATED, which is the most widely supported. import zipfile zip = zipfile.ZipFile("stuff.zip", "w", zipfile.ZIP_DEFLATED) zip.write("test.txt...
7
12
71,277,420
2022-2-26
https://stackoverflow.com/questions/71277420/type-annotation-hint-for-index-in-pandas-dataframe-iterrows
I am trying to add type annotations/hints in a Python script for running mypy checks. I have a pandas.DataFrame object, which I iterate like this: someTable: pandas.DataFrame = pandas.DataFrame() # ... # adding some data to someTable # ... for index, row in someTable.iterrows(): #reveal_type(index) print(type(index)) p...
You could hint index as Optional[int], but then x + 1 won't type check. I'm not sure where Union[typing.Hashable, None] comes from; iterrows itself returns an Iterable[tuple[Hashable, Series]]. But it seems like you can safely assert that if index is assigned a value, then it will not be None. index: Optional[int] for ...
6
6