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
73,406,105
2022-8-18
https://stackoverflow.com/questions/73406105/my-code-caused-the-kernel-to-restart-why-is-the-kernel-restarting
I wrote this for python code and got an unexpected output. The output was a number of zeros then it said "restarting kernel". Why is the kernel restarting? def countdown(n): for n in range(0,5): print(n) countdown(n-1) countdown(2) On the other hand, I tried with if and there was no problem: def countdown(n): if n == ...
> def countdown(n): > for n in range(0,5): > print(n) > countdown(n-1) > countdown(2) In your code above, each function call will call itself recursively 5 times. So the first call is 5, second call there will be 25 calls, third call 125 calls, and the recursive calls went exponentially high, causing the Kernel to res...
4
3
73,381,902
2022-8-17
https://stackoverflow.com/questions/73381902/running-unittest-with-modules-that-must-import-other-modules
Our Python 3.10 unit tests are breaking when the modules being tested need to import other modules. When we use the packaging techniques recommended by other posts and articles, either the unit tests fail to import modules, or the direct calls to run the app fail to import modules. The other posts and articles we have ...
Creating an "alias" for modules Update the contents of repoName\app\__init__.py to: print('inside app __init__.py') __all__ = ['first', 'second', 'third'] import sys import repoName.app.second as second sys.modules['second'] = second import repoName.app.third as third sys.modules['third'] = third import repoName.app.fi...
4
4
73,421,579
2022-8-19
https://stackoverflow.com/questions/73421579/list-comprehension-instead-of-extend-in-loop
Can I write this code in one line? I tried use chain in list comprehension. def divisors(n): result = [] for div in range(1, int(sqrt(n)) + 1): if n % div == 0: result.extend([div, n / div]) return list(set(result))
Are you looking for something like this ? from math import sqrt import itertools def divisors(n): return list(set(itertools.chain.from_iterable([[div, n / div] for div in range(1, int(sqrt(n)) + 1) if n % div == 0])))
3
2
73,419,138
2022-8-19
https://stackoverflow.com/questions/73419138/how-to-change-annotations-in-one-column-of-seaborn-heatmap
I plotted a heatmap using seaborn as shown below. I want to change the highlighted column into "Thousands K and Million M" values (shown in the table below). I tried it doing it but the column is changing into string and giving me an error when I am trying to plot those values on the heatmap. Is there a way I can chang...
Using the lesser known texts attribute of matplotlib.Axes object: import pandas as pd import seaborn as sns import matplotlib.pyplot as plt heatmap_df = pd.DataFrame( [ {"colA": 662183343.70, "colB": 0.9976, "colC": 0.9962}, {"colA": 155567736.90, "colB": 1.0000, "colC": 1.0000}, {"colA": 77777.70, "colB": 0.9976, "col...
3
2
73,420,018
2022-8-19
https://stackoverflow.com/questions/73420018/how-do-i-construct-a-self-referential-recursive-sqlmodel
I want to define a model that has a self-referential (or recursive) foreign key using SQLModel. (This relationship pattern is also sometimes referred to as an adjacency list.) The pure SQLAlchemy implementation is described here in their documentation. Let's say I want to implement the basic tree structure as described...
The sqlmodel.Relationship function allows explicitly passing additional keyword-arguments to the sqlalchemy.orm.relationship constructor that is being called under the hood via the sa_relationship_kwargs parameter. This parameter expects a mapping of strings representing the SQLAlchemy parameter names to the values we ...
8
17
73,407,527
2022-8-18
https://stackoverflow.com/questions/73407527/installing-ssl-package-with-pip-requires-ssl-package-to-be-already-installed
CentOS 7 (strict requirement) Python 3.11 (strict requirement) I had to upgrage a software and it requires now Python 3.11. I followed instructions from Internet (https://linuxstans.com/how-to-install-python-centos/), and now Python 3.11 is installed, but cannot download anything, so all the programs that have someth...
How to get PIP and other HTTPS-based Python programs to work after upgrading to Python 3.11: First of all: you don't necessarily need any magical tools like pyenv. May be pyenv would do these steps, but I'd like to understand what is happening. (Ok, I admit that make is also a "magic" tool) Briefly describing: during c...
7
23
73,411,073
2022-8-19
https://stackoverflow.com/questions/73411073/how-to-find-index-of-the-first-unique-elements-in-pandas-dataframe
Consider df1 = pd.DataFrame("Name":["Adam","Joseph","James","James","Kevin","Kevin","Kevin","Peter","Peter"]) I want to get the index of the unique values in the dataframe. When I do df1["Name"].unique() I get the output as ['Adam','Joseph','James','Kevin','Peter'] But I want to get the location of the first occurren...
I would suggest to use numpy.unique with the return_index as True. np.unique(df1, return_index=True) Out[13]: (array(['Adam', 'James', 'Joseph', 'Kevin', 'Peter'], dtype=object), array([0, 2, 1, 4, 7], dtype=int64))
4
2
73,405,368
2022-8-18
https://stackoverflow.com/questions/73405368/rust-function-as-slow-as-its-python-counterpart
I am trying to speed up Python programs using Rust, a language in which I am a total beginner. I wrote a function that counts the occurrences of each possible string of length n within a larger string. For instance, if the main string is "AAAAT" and n=3, the outcome would be a hashmap {"AAA":2,"AAT":1}. I use pyo3 to c...
You are computing hash function multiple times, this may matter for large n values. Try using entry function instead of manual inserts: while current_pos+n <= seq.len() { let en = counts.entry(&seq[current_pos..current_pos+n]).or_default(); *en += 1; current_pos +=1; } Complete code here Next, make sure you are runnin...
5
2
73,400,563
2022-8-18
https://stackoverflow.com/questions/73400563/pip-install-e-local-git-branch-for-development-environment
I'm trying to set up the development environment for modifying a Python library. Currently, I have a fork of the library, I cloned it from remote and installed it with pip install -e git+file:///work/projects/dev/git_project@branch#egg=git_project However, it seems that instead of creating a symbolic link with pip inst...
pip install -e git+URL means "clone the repository from the URL locally and install". If you already have the repository cloned locally and want to simply install from it: just install without Git: cd /work/projects/dev/git_project git checkout branch pip install -e .
3
6
73,396,611
2022-8-18
https://stackoverflow.com/questions/73396611/how-can-you-include-path-parameters-in-nested-router-w-fastapi
How can I include one APIRouter inside another AND specify that some path param is a required prefix? For context: Let's say I have the concept of an organization and a user. A user only belongs to one organization. My web app could be structured as follows: ├── web_app ├── endpoints ├── __init__.py # produces main_rou...
I am not sure why you are getting this error, but the thing that you are requesting (using path parameters in APIRoute prefix) is absolutely possible. When you include the APIRoute to the app instance, it will evaluate all routes and appends them from your dedicated APIRoute to the main APIRoute. The latter is always p...
4
7
73,397,515
2022-8-18
https://stackoverflow.com/questions/73397515/in-python-how-can-i-check-if-an-array-contains-all-elements-of-another-array-li
There appear to be several ways to determine if a set is a subset of another set, but I haven't been able to find something concise that determines whether all elements of a list (or array), including duplicate values, appear in another list (or array). For example, for the hypothetical function contains_all(A, B) whic...
You are correct, collections.Counter is a good way to go. You just need to go over the B counter and check if the the value is smaller or equal. Do it in all() to check all the key-value pairs def contains_all(a, b): counter_a = Counter(a) counter_b = Counter(b) return all(v <= counter_a[k] for k, v in counter_b.items(...
3
2
73,396,488
2022-8-18
https://stackoverflow.com/questions/73396488/is-there-a-way-to-use-python-argparse-with-nargs-choices-and-default
My use case is multiple optional positional arguments, taken from a constrained set of choices, with a default value that is a list containing two of those choices. I can't change the interface, due to backwards compatibility issues. I also have to maintain compatibility with Python 3.4. Here is my code. You can see th...
The behavior noted as incorrect is caused by the fact that the raw default value ['a', 'd'] is not inside the specified choices (see: relevant code as found in Python 3.4.10; this check method is effectively unchanged as of Python 3.10.3). I will reproduce the code from the Python argparse.py source code: def _check_v...
4
2
73,396,203
2022-8-18
https://stackoverflow.com/questions/73396203/how-to-use-trained-pytorch-model-for-prediction
I have a pretrained pytorch model which is saved in .pth format. How can i use it for prediction on new dataset in a separate python file. I need a detailed guide.
To use a pretrained model you should load the state on a new instance of the architecture as explained in the docs/tutorials: Here models is imported beforehand: model = models.vgg16() model.load_state_dict(torch.load('model_weights.pth')) # This line uses .load() to read a .pth file and load the network weights on to ...
3
6
73,395,864
2022-8-17
https://stackoverflow.com/questions/73395864/how-do-i-wait-when-all-threadpoolexecutor-threads-are-busy
My understanding of how a ThreadPoolExecutor works is that when I call #submit, tasks are assigned to threads until all available threads are busy, at which point the executor puts the tasks in a queue awaiting a thread becoming available. The behavior I want is to block when there is not a thread available, to wait un...
One approach might be to keep track of your currently running threads via a set of Futures: active_threads = set() def pop_future(future): active_threads.pop(future) with concurrent.futures.ThreadPoolExecutor(max_workers=CONCURRENCY) as executor: while True: while len(active_threads) >= CONCURRENCY: time.sleep(0.1) # ...
4
2
73,394,593
2022-8-17
https://stackoverflow.com/questions/73394593/aws-lambda-function-returns-errormessage-errno-30-read-only-file-system
I get the following error { "errorMessage": "[Errno 30] Read-only file system: '/home/sbx_user1051'", "errorType": "OSError", "stackTrace": [ " File \"/var/lang/lib/python3.8/imp.py\", line 234, in load_module\n return load_source(name, filename, file)\n", " File \"/var/lang/lib/python3.8/imp.py\", line 171, in load_so...
AWS Lambda is not a generic docker runner. The docker containers you deploy to Lambda have to comply with the AWS Lambda runtime environment. The docker image you are using is trying to write to the path /home/sbx_user1051 apparently. On AWS Lambda the file system is always read-only except for the /tmp path. You will ...
4
11
73,392,878
2022-8-17
https://stackoverflow.com/questions/73392878/access-data-in-python3-associative-arrays
I'd like how to create and print associative arrays in python3... like in bash I do: declare -A array array["alfa",1]="text1" array["beta",1]="text2" array["alfa",2]="text3" array["beta",2]="text4" In bash I can do echo "${array["beta",1]}" to access data to print "text2". How can I define a similar array in python3 a...
It looks like you want a dictionary with compound keys: adict = { ("alfa", 1): "text1", ("beta", 1): "text2", ("alfa", 2): "text3", ("beta", 2): "text4" } print(adict[("beta", 1)])
3
3
73,392,385
2022-8-17
https://stackoverflow.com/questions/73392385/can-f-strings-auto-pad-to-the-next-even-number-of-digits-on-output
Based on this answer (among others) it seems like f-strings is [one of] the preferred ways to convert to hexadecimal representation. While one can specify an explicit target length, up to which to pad with leading zeroes, given a goal of an output with an even number of digits, and inputs with an arbitrary # of bits, I...
Here's a postprocessing alternative that uses assignment expressions (Python 3.8+): print((len(hx:=f"{val:x}") % 2) * '0' + hx) If you still want a one-liner without assignment expressions you have to evaluate your f-string twice: print((len(f"{val:x}") % 2) * '0' + f"{val:x}") As a two-liner hx = f"{val:x}" print((l...
5
1
73,388,357
2022-8-17
https://stackoverflow.com/questions/73388357/poetry-lock-empty-hashes
I am doing poetry lock Then I open the poetry.lock file and see that the metadata.files block does not contain hashes: [metadata.files] aiohttp = [] aiosignal = [] apscheduler = [] ... Before, it wasn't like that. What could be the reasons for empty hashes?
You are probably running into this issue https://github.com/python-poetry/poetry/issues/5970 Just upgrade to poetry 1.1.14 or the prereleases for the 1.2 series.
5
3
73,385,797
2022-8-17
https://stackoverflow.com/questions/73385797/can-i-naively-check-if-a-b-c-d
I was doing leetcode when I had to do some arithmetic with rational numbers (both numerator and denominator integers). I needed to count slopes in a list. In python collections.Counter( [ x/y if y != 0 else "inf" for (x,y) in points ] ) did the job, and I passed all the tests with it. ((edit: they've pointed out in th...
It's not safe, and I've seen at least one LeetCode problem where you'd fail with that (maybe Max Points on a Line). Example: a = 94911150 b = 94911151 c = 94911151 d = 94911152 print(a/b == c/d) print(a/b) print(c/d) Both a/b and c/d are the same float value even though the slopes actually differ (Try it online!): Tru...
3
5
73,383,458
2022-8-17
https://stackoverflow.com/questions/73383458/login-authentication-failed-with-gmail-smtp-updated
When trying to login into a Gmail account using SMTP, this error message occurs: SMTPAuthenticationError(code, resp) smtplib.SMTPAuthenticationError: (535, b'5.7.8 Username and Password not accepted. Code causing the error: import smtplib server = smtplib.SMTP("smtp.gmail.com", 587) server.starttls() server.login("sen...
Google has disabled the ability to enable less secure apps as of May 2022. Because of this, the previous solution of enabling less secure apps is no longer valid. Steps: Go into your sending email address and make your way to the settings. Find two-step authentication and enable it. Under two-step authentication there...
4
12
73,382,163
2022-8-17
https://stackoverflow.com/questions/73382163/filtering-out-rows-based-on-other-rows-using-pandas
I have a dataframe that looks like this: dict = {'companyId': {0: 198236, 1: 198236, 2: 900814, 3: 153421, 4: 153421, 5: 337815}, 'region': {0: 'Europe', 1: 'Europe', 2: 'Asia-Pacific', 3: 'North America', 4: 'North America', 5:'Africa'}, 'value': {0: 560, 1: 771, 2: 964, 3: 217, 4: 433, 5: 680}, 'type': {0: 'actual', ...
You can use a groupby and transform to create boolean indexing: #Your condition i.e. retain the rows which are not duplicated and those # which are duplicated but only type==actual. Lets express that as a lambda. to_filter = lambda x: (len(x) == 1) | ((len(x) > 1) & (x == 'actual')) #then create a boolean indexing mask...
3
2
73,381,897
2022-8-17
https://stackoverflow.com/questions/73381897/how-can-%c4%b1-use-geoadd-in-python-redis
I want the store geospatial information in Redis. I am executing the following code from redis import Redis redis_con = Redis(host="localhost", port=6379) redis_con.geoadd("Sicily", 13.361389, 38.115556, "Palermo") But ı got error like that raise DataError("GEOADD allows either 'nx' or 'xx', not both") redis.exception...
This will work for you: from redis import Redis redis_con = Redis(host="localhost", port=6379) coords = (13.361389, 38.115556, "Palermo") redis_con.geoadd("Sicily", coords) The signature for geoadd is: geoadd(name, values, nx=False, xx=False, ch=False) name: Union[bytes, str, memoryview] values: Sequence[Union[bytes, ...
3
7
73,365,780
2022-8-15
https://stackoverflow.com/questions/73365780/why-is-not-recommended-to-install-poetry-with-homebrew
Poetry official documentation strictly recommends sticking with the official installer. However, homebrew has poetry formulae. brew install poetry Usually, I like to keep everything I can in homebrew to manage installations easily. What is the drawback and risks of installing poetry using homebrew instead of the recom...
The drawback is that poetry will be unable to upgrade itself (I've no idea what'd actually happen), and you'll not be able to install specific poetry versions. Homebrew installed poetry will probably also use the Homebrew-installed Python environment, etc, instead of having its own isolated venv to execute from. If you...
32
29
73,340,211
2022-8-12
https://stackoverflow.com/questions/73340211/getting-no-develop-install-with-pip-install-e-unless-i-delete-pyproject-to
I have the following situation that pip install -e . does not build the develop version unless I delete the pyproject.toml which does not contain packaging information, but black configuration. Does somebody know what to do in order to get the develop build. my pyproject.toml looks like this: # Source https://github.co...
These are both development installs. The difference in the pip output here is because the presence (or absence) of a pyproject.toml file causes pip to use the build backend hooks (or not). From PEP 517: If the pyproject.toml file is absent ... the source tree is not using this specification, and tools should revert to...
6
3
73,338,942
2022-8-12
https://stackoverflow.com/questions/73338942/how-to-install-a-new-font-in-altair-and-specifying-it-in-alt-titleparams
I am wondering if it's possible to install fonts to use in altair to use in alt.TitleParams. For this example, without font specified, I get a default font and size. import altair as alt import pandas as pd source = pd.DataFrame({ 'a': ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'], 'b': [28, 55, 43, 91, 81, 53, 19, 87,...
fontStyle refers to the style of the font, such as "bold", "italic", etc. If you want to specify a font by name, use the font parameter: alt.Chart( source, title=alt.Title( # Since altair 5 you can use just Title instead of TitleParams text='Example Chart', fontSize=24, fontStyle='italic', font='Times' ) ).mark_bar().e...
4
5
73,316,102
2022-8-11
https://stackoverflow.com/questions/73316102/fastai-fastcore-patch-decorator-vs-simple-monkey-patching
I'm trying to understand the value-added of using fastai's fastcore.basics.patch_to decorator. Here's the fastcore way: from fastcore.basics import patch_to class _T3(int): pass @patch_to(_T3) def func1(self, a): return self + a And here's the simple monkey-patching approach: class simple_T3(int): pass def func1(self,...
TL;DR More informative debugging messages, better IDE support. Answer patch and patch_to are decorators in the fastcore basics module that are helpful to make the monkey_patched method to look more like as if it was a method originally placed inside the Class, the classical way (pun intended). If you create a function...
7
5
73,351,280
2022-8-14
https://stackoverflow.com/questions/73351280/what-is-the-difference-between-threadpoolexecutor-and-threadpool
Is there a difference between ThreadPoolExecutor from concurrent.futures and ThreadPool from multiprocessing.dummy? This article suggests that ThreadPool queries the "threads" (task) to the different "threads" of the CPU. Does concurrent.futures do the same or will the "threads" (tasks) query to a single "thread" of a ...
The multiprocessing.dummy.ThreadPool is a copy of the multiprocessing.Pool API which uses threads rather than processes, which leads to some weirdness since thread and processes are very different, including returning a AsyncResult type which only it understands. The concurrent.futures.ThreadPoolExecutor is a subclass ...
9
11
73,315,599
2022-8-11
https://stackoverflow.com/questions/73315599/skipping-analyzing-feedparser-util-module-is-installed-but-missing-library-s
How do I fix this error? It seems feedparser does not support mypy typings? I could not find a typeshed implementation for feedparser UPDATE 1 I see an option called ignore_missing_imports that I can add to pyproject.toml. Isn't it a bad idea to do this?
I see an option called ignore_missing_imports that I can add to pyproject.toml. Isn't it a bad idea to do this? Yes, it usually is a bad idea to enable this on all modules. Consider using a more constrained approach: You can ignore missing imports only for this specific package by adding a [tools.mypy.override] secti...
11
14
73,361,664
2022-8-15
https://stackoverflow.com/questions/73361664/asyncio-get-event-loop-deprecationwarning-there-is-no-current-event-loop
I'm building an SMTP server with aiosmtpd and used the examples as a base to build from. Below is the code snippet for the entry point to the program. if __name__ == '__main__': loop = asyncio.get_event_loop() loop.create_task(amain(loop=loop)) try: loop.run_forever() except KeyboardInterrupt: pass When I run the prog...
Your code will run on Python3.10 but as of 3.11 it will be an error to call asyncio.get_event_loop when there is no running loop in the current thread. Since you need loop as an argument to amain, apparently, you must explicitly create and set it. It is better to launch your main task with asyncio.run than loop.run_for...
53
66
73,329,011
2022-8-12
https://stackoverflow.com/questions/73329011/use-pip-install-psutil-on-docker-image-python3-9-13-alpine3-16-error-linux-e
I tried to install python module psutil in docker python:3.9.13-alpine3.16 But it reported the following mistake: Building wheels for collected packages: psutil Building wheel for psutil (pyproject.toml) ... error error: subprocess-exited-with-error × Building wheel for psutil (pyproject.toml) did not run successfully....
You need to add the linux-headers package. apk add build-base linux-headers python -m pip install psutil Update 0 Great, you need the linux-headers package. But, why do you need the linux-headers package? This package provides data structures and the signatures for functions in the kernel source. This information is ...
14
26
73,334,557
2022-8-12
https://stackoverflow.com/questions/73334557/how-do-you-get-tkinter-to-work-with-asyncio
How do you get tkinter to work with asyncio? My studies suggest this general question does resolve into the specific problem of getting tkinter to await a coroutine function. Context If tkinter's event loop is blocked the loop will freeze until the blocking function returns. If the event loop also happens to be running...
Tkinter's Problem with Blocking IO Calls The statement asyncio.sleep(60) will block tkinter for a minute if both are running in the same thread. Blocking coroutine functions cannot run in the same thread as tkinter. Similarly, the statement time.sleep(60) will block both tkinter and asyncio for a minute if all three ar...
4
2
73,362,588
2022-8-15
https://stackoverflow.com/questions/73362588/type-hinting-a-decorator-that-adds-a-parameter-with-default-value
Motivation: I realised I had a lot of class methods that were also being used as TKinter callbacks, which pass a tk.Event object as the first (non-self) argument. If my application wants to call them normally as well, this event argument should be None by default... class Writer: # very unwieldy second parameter... def...
This question boils down to: How do I type hint a decorator which adds an argument to a class method? Inspired by the docs for typing.Concatenate, I've come up with a solution which works when the first parameter of the function being decorated is self. I've simplified your example a bit, to use an optional string in...
4
1
73,318,724
2022-8-11
https://stackoverflow.com/questions/73318724/mitigating-tcp-connection-resets-in-aws-fargate
I am using Amazon ECS on AWS Fargate, My instances can access the internet, but the connection drops after 350 seconds. On average, out of 100 times, my service is getting ConnectionResetError: [Errno 104] Connection reset by peer error approximately 5 times. I found a couple of suggestions to fix that issue on my serv...
Posting solution for the future user who will face this issue while working on AWS Farget + NAT, We need to set the TCP keepalive settings to the values dictated by our server-side configuration, this PR helps me a lot to fix my issue: https://github.com/customerio/customerio-python/pull/70/files import socket from url...
5
1
73,363,627
2022-8-15
https://stackoverflow.com/questions/73363627/pass-a-macro-as-a-parameter-jinja-dbt
{{ today_date_milliseconds() }} - is my macro in the project. How to redirect this macro as a parameter, so it will be by default and I could in yml write another macro? {% test valid_date(model, column_name, exclude_condition = '1=1') %} SELECT {{ column_name }} FROM {{ model }} WHERE (CAST( {{ column_name }} AS BIGIN...
I love this question -- I just learned something looking into it (and I've wanted to do this in another project, so I'm glad I did!). First, a caveat that this is undocumented and probably not encouraged, and could probably break at any time. The good news is that unbound macros act like python functions, so you can as...
5
6
73,322,507
2022-8-11
https://stackoverflow.com/questions/73322507/how-to-pass-a-fixture-that-returns-a-variable-length-iterable-of-values-to-pytes
I have a pytest fixture that produces an iterable and I would like to parameterize a test using the items in this iterable, but I cannot figure out the correct syntax. Does anyone know how to parametrize a test using the values of a fixture? Here is some dummy code that shows my current approach: import pytest @pytest....
The short answer is pytest doesn't support passing fixtures to parametrize. The out-of-the-box solution provided by pytest is to either use indirect parametrization or define your own parametrization scheme using pytest_generate_tests as described in How can I pass fixtures to pytest.mark.parameterize? These are the wo...
4
4
73,320,669
2022-8-11
https://stackoverflow.com/questions/73320669/celery-kombu-exceptions-contentdisallowed-in-docker
I am using celery with a fastAPI. Getting Can't decode message body: ContentDisallowed('Refusing to deserialize untrusted content of type json (application/json)') while running in docker. When running the same in local machine without docker there is not issue. The configuration for the same is as below. celery_app = ...
Configuring the celery_app with the accept_content type seems to fix the issue: celery_app.conf.accept_content = ['application/json', 'application/x-python-serialize', 'pickle']
6
5
73,318,552
2022-8-11
https://stackoverflow.com/questions/73318552/django-orm-query-optimisation-with-multiple-joins
In my app, I can describe an Entity using different Protocols, with each Protocol being a collection of various Traits, and each Trait allows two or more Classes. So, a Description is a collection of Expressions. E.g., I want to describe an entity "John" with the Protocol "X" that comprises the following two Traits and...
First you should avoid multiple joins by aggregating desired filters upfront: filters = [ {'trait': 1, 'class': [2, 3]}, {'trait': 2, 'class': [6,]}, ] queryset = Description.objects.all() class_filter = [] for filter_entry in filters: class_filter.append(filter_entry["class"]) queryset = queryset.filter(expression_set...
4
2
73,343,529
2022-8-13
https://stackoverflow.com/questions/73343529/django-google-kubernetes-client-not-running-exe-inside-the-job
I have a docker image that I want to run inside my django code. Inside that image there is an executable that I have written using c++ that writes it's output to google cloud storage. Normally when I run the django code like this: container = client.V1Container(name=container_name, command=["//usr//bin//sleep"], args=[...
Apparently for anyone having a similar issue, we fixed it by adding the command we want to run at the end of the Dockerfile instead of passing it as a parameter inside django's container call like this: cmd["entrypoint.sh"] entrypoint.sh: xvfb-run -a "path/to/exe" Instead of calling it inside django like we did befor...
6
4
73,302,347
2022-8-10
https://stackoverflow.com/questions/73302347/how-to-handle-files-imported-using-import-in-pyinstaller
Here's an example of the file-structure of my app, which I'm trying to turn into a standalone distributable one-dir application using auto-py-to-exe: - plugins/file1.py - plugins/file2.py - plugins/... - plugins/display/file1.py - plugins/display/... - main.py - UI.py The files which are under the plugins directory ar...
I’ve managed to solve this by adding the absolute path of the plugins folder to paths and adding file1, file2, etc. to the —-hidden-import option. I also had to get rid of the if statement that checks if the file is a Python one and replaced that block with a loop that looks something like this: modules = [‘file1’, ‘fi...
4
0
73,363,017
2022-8-15
https://stackoverflow.com/questions/73363017/cannot-connect-to-mongodb-when-tunneling-ssh-connection
I am developing a GUI using Flask. I am running Ubuntu 20.04. The data that I need is from MongoDB, which is running on a Docker container on a server. My Mongo URI is "mongodb://<USERNAME>:<PASSWORD>@localhost:9999/<DB>?authSource=<AUTHDB>". First I tunnel the SSH connection to the server: ssh -L 9999:localhost:27017 ...
I discovered that pymongo isn't setting the port correctly, possibly due to a bug in the package. Even though I specify the port as 9999, it thinks it should connect to 27017. If I set the URI to "mongodb://<USERNAME>:<PASSWORD>@garbage:9999/<DB>?authSource=<AUTHDB>", then it will actually try to connect to port 9999. ...
4
2
73,378,545
2022-8-16
https://stackoverflow.com/questions/73378545/pip-install-gives-error-on-some-packages
Some packages give errors when I try to install them using pip install. This is the error when I try to install chatterbot, but some other packages give this error as well: pip install chatterbot Collecting chatterbot Using cached ChatterBot-1.0.5-py2.py3-none-any.whl (67 kB) Collecting pint>=0.8.1 Downloading Pint-0.1...
The real error in your case is: ImportError: cannot import name 'msvccompiler' from 'distutils' It occured because setuptools has broken distutils in version 65.0.0 (and has already fixed it in version 65.0.2). According to your log, the error occured in your global setuptools installation (see the path in error messa...
12
9
73,371,336
2022-8-16
https://stackoverflow.com/questions/73371336/setup-pys-install-requires-how-do-i-specify-python-version-range-for-a-specif
I'm working on a python project and the package supports python 3.6 - 3.10. There were these 2 lines in the install_requires list in setup.py: "numpy>=1.18.5, <=1.19.5; python_version=='3.6'", "numpy>=1.19.5; python_version>='3.7'", And I tried to change them to "numpy>=1.18.5, <=1.19.5; python_version=='3.6'", "num...
Referring to Complete Grammar, you can use and to achieve your purpose. "numpy>=1.18.5, <=1.19.5; python_version=='3.6'", "numpy>=1.23.1; python_version>='3.10'", "numpy>=1.19.5; python_version>='3.7' and python_version<'3.10'",
6
5
73,375,390
2022-8-16
https://stackoverflow.com/questions/73375390/how-to-override-env-file-during-tests
I'm reading env variables from .prod.env file in my config.py: from pydantic import BaseSettings class Settings(BaseSettings): A: int class Config: env_file = ".prod.env" env_file_encoding = "utf-8" settings = Settings() in my main.py I'm creating the app like so: from fastapi import FastAPI from app.config import set...
You can override the env file you use by creating a Settings instance with the _env_file keyword argument. From documentation: Passing a file path via the _env_file keyword argument on instantiation (method 2) will override the value (if any) set on the Config class. If the above snippets were used in conjunction, pro...
6
3
73,376,661
2022-8-16
https://stackoverflow.com/questions/73376661/saving-jupyter-notebook-session
I am currently trying to save my whole Jupyter Notebook environment (working throught Anaconda 3). By environment, I mean, all the objects created (dataframes, lists, tuples, models, ...). Unfortunately I don't have Linux even though there seemed to be Linux command solutions. I tried finding a solution with pickle as ...
You can use Dill to store your session pip install dill Save a Notebook session: import dill dill.dump_session('notebook_env.db') Restore a Notebook session: import dill dill.load_session('notebook_env.db')
3
6
73,375,944
2022-8-16
https://stackoverflow.com/questions/73375944/is-there-a-python-function-to-compute-minimal-l2-norm-between-2-matrices-up-to-c
I have two sets of column vectors X = (X_1 ... X_n), Y = (Y_1 ... Y_n) of same shape. I would like to compute something like this: i.e the minimal L2 norm between X and Y up to column permutation. Is it possible to do it in less than O(n!)? Is it already implemented in Numpy for instance? Thank you in advance.
Apply scipy.optimize.linear_sum_assignment to the matrix A where Aij = ‖Xi − Yj‖.
3
5
73,373,275
2022-8-16
https://stackoverflow.com/questions/73373275/modifying-horizontal-bar-size-in-subplot
I am trying to add a horizontal bar at the bottom of each pie chart in a figure. I am using subplots to achieve this, but I don't know how to customise the subplots with the horizontal bars. import matplotlib.pyplot as plt fig, axes = plt.subplots(28, 11) countery=0 for y in range(1,15): counterx=0 for x in range(1,12)...
You can set the box_aspect of the bar charts. Also, using 14 rows with subgridspecs of 2 rows each is slightly faster than the 28 rows gridspec: import matplotlib.pyplot as plt fig = plt.figure() gs = fig.add_gridspec(14, 11) for y in range(gs.nrows): for x in range(gs.ncols): ax_pie, ax_bar = gs[y, x].subgridspec(2, 1...
3
3
73,371,934
2022-8-16
https://stackoverflow.com/questions/73371934/how-to-center-and-coloured-the-button
I have an app which convert the image into pencil sketch in that app i need three changes in the buttons Need to align the both buttons into center Need to give some colour to the buttons The both button should be in same size Sample Code: import streamlit as st #web app and camera import numpy as np # for image pro...
I have modified the above code. Hope it helps customized_button = st.markdown(""" <style > .stDownloadButton, div.stButton {text-align:center} .stDownloadButton button, div.stButton > button:first-child { background-color: #ADD8E6; color:#000000; padding-left: 20px; padding-right: 20px; } .stDownloadButton button:hover...
4
7
73,361,556
2022-8-15
https://stackoverflow.com/questions/73361556/error-discord-errors-notfound-404-not-found-error-code-10062-unknown-inter
I'm making a discord bot that sends a message with two buttons. Both buttons sends a message with a picture/gif when pressed. One of them works but the other one gives an error: raise NotFound(response, data) discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction Here is the full code: import...
With discord API you need to send an initial response within 3 seconds and afterward, you have 15 minutes to send the follow-up message. You should look into deferring. You're uploading an image that might take some time and you might need to defer the message. Instead of doing : Interaction.response.send_message() ...
5
12
73,367,220
2022-8-15
https://stackoverflow.com/questions/73367220/pythons-requests-triggers-cloudflares-security-while-accessing-etherscan-io
I am trying to parse/scrape https://etherscan.io/tokens website using requests in Python but I get the following error: etherscan.io Checking if the site connection is secure etherscan.io needs to review the security of your connection before proceeding. Ray ID: 73b56fc71bc276ed Performance & security by Cloudflare N...
The website is under cloudflare protection. So you can use cloudscraper instead of requests to get rid of the protection. Now it's working fine. Example: from bs4 import BeautifulSoup import cloudscraper scraper = cloudscraper.create_scraper(delay=10, browser={'custom': 'ScraperBot/1.0',}) url = 'https://etherscan.io/t...
6
4
73,364,802
2022-8-15
https://stackoverflow.com/questions/73364802/qt-creator-design-mode-disabled-for-qt-quick-pyside6-project
In newly installed Qt Creator 8.0.1, the Design Mode is disabled. I can only code in QML in Edit Mode. I can easily reproduce the problem by just creating a new Python Qt Quick Project as shown below. The Design Button on the left menu is always disabled. I tried to add all modules related to the Design Mode with Qt m...
You can enable the QmlDesigner by going to Help > About Plugins... and using the filter to find QmlDesigner. Activate the CheckBox and restart QtCreator. https://www.qt.io/blog/qt-creator-6-released The integrated Qt Quick Designer is now disabled by default. Qt Creator will open .ui.qml files in Qt Design Studio. Thi...
3
6
73,366,049
2022-8-15
https://stackoverflow.com/questions/73366049/extract-substring-from-dot-untill-colon-with-python-regex
I have a string that resembles the following string: 'My substring1. My substring2: My substring3: My substring4' Ideally, my aim is to extract 'My substring2' from this string with Python regex. However, I would also be pleased with a result that resembles '. My substring2:' So far, I am able to extract '. My substri...
You can use non-greedy regex (with ?): import re s = "My substring1. My substring2: My substring3: My substring4" print(re.search(r"\.\s*(.*?):", s).group(1)) Prints: My substring2
3
3
73,356,688
2022-8-15
https://stackoverflow.com/questions/73356688/average-and-sums-task
Basic task of making code that can find the sum & average of 10 numbers from the user. My current situation so far: Sum = 0 print("Please Enter 10 Numbers\n") for i in range (1,11): num = int(input("Number %d =" %i)) sum = Sum + num avg = Sum / 10 However, I want to make it so that if the user inputs an answer such as...
You can output an error message and prompt for re-entry of the ith number by prompting in a loop which outputs an error message and reprompts on user input error. This can be done by handling the ValueError exception that is raised when the input to the int() function is an invalid integer object string initializer suc...
3
3
73,335,410
2022-8-12
https://stackoverflow.com/questions/73335410/how-to-read-sys-stdin-containing-binary-data-in-python-ignore-errors
How do I read sys.stdin, but ignoring decoding errors? I know that sys.stdin.buffer exists, and I can read the binary data and then decode it with .decode('utf8', errors='ignore'), but I want to read sys.stdin line by line. Maybe I can somehow reopen the sys.stdin file but with errors='ignore' option?
Found three solutions from here as Mark Setchell mentioned. import sys import io def first(): with open(sys.stdin.fileno(), 'r', errors='ignore') as f: return f.read() def second(): sys.stdin = io.TextIOWrapper(sys.stdin.buffer, errors='ignore') return sys.stdin.read() def third(): sys.stdin.reconfigure(errors='ignore'...
4
1
73,347,010
2022-8-13
https://stackoverflow.com/questions/73347010/why-do-i-get-an-error-when-trying-to-read-a-file-in-geopandas-included-datasets
I've just installed Anaconda in my new laptop, and created an environment with geopandas installed in it. I've tried to upload the world map that comes with geopandas through the following code: import geopandas as gpd world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres')) But I obtain the following error...
This is caused by incompatibility of shapely 1.7 and numpy 1.23. Either update shapely to 1.8 or downgrade numpy, otherwise it won't work.
6
14
73,353,612
2022-8-14
https://stackoverflow.com/questions/73353612/why-is-cython-slower-than-pythonnumpy-here
I want to implement some fast convex analysis operations - proximal operators and the like. I'm new to Cython and thought that this would be the right tool for the job. I have implementations both in pure Python and in Cython (mwe_py.py and mwe_c.pyx below). However, when I compare them, the Python + Numpy version is s...
The main issue is that you compare an optimized Numpy code with a less-optimized Cython code. Indeed, Numpy makes use of SIMD instructions (like SSE and AVX/AVX2 on x86-64 processors) that are able to compute many items in a row. Cython use the default -O2 optimization level by default which do not enable any auto-vect...
5
6
73,353,608
2022-8-14
https://stackoverflow.com/questions/73353608/why-does-argparse-not-accept-as-argument
My script takes -d, --delimiter as argument: parser.add_argument('-d', '--delimiter') but when I pass it -- as delimiter, it is empty script.py --delimiter='--' I know -- is special in argument/parameter parsing, but I am using it in the form --option='--' and quoted. Why does it not work? I am using Python 3.7.3 Her...
This looks like a bug. You should report it. This code in argparse.py is the start of _get_values, one of the primary helper functions for parsing values: if action.nargs not in [PARSER, REMAINDER]: try: arg_strings.remove('--') except ValueError: pass The code receives the -- argument as the single element of a list ...
22
19
73,347,065
2022-8-13
https://stackoverflow.com/questions/73347065/pyspark-data-frames-when-to-use-select-vs-withcolumn
I'm new to PySpark and I see there are two ways to select columns in PySpark, either with ".select()" or ".withColumn()". From what I've heard ".withColumn()" is worse for performance but otherwise than that I'm confused as to why there are two ways to do the same thing. So when am I supposed to use ".select()" instead...
Using: df.withColumn('new', func('old')) where func is your spark processing code, is equivalent to: df.select('*', func('old').alias('new')) # '*' selects all existing columns As you see, withColumn() is very convenient to use (probably why it is available), however as you noted, there are performance implications. ...
3
6
73,346,395
2022-8-13
https://stackoverflow.com/questions/73346395/unexpected-keyword-argument-when-running-lightgbm-on-gpu
When running the code below: import lightgbm as lgb params = {'num_leaves': 38, 'min_data_in_leaf': 50, 'objective': 'regression', 'max_depth': -1, 'learning_rate': 0.1, 'device': 'gpu' } trn_data = lgb.Dataset(x_train, y_train) val_data = lgb.Dataset(x_test, y_test) model = lgb.train(params, trn_data, 20000, valid_set...
For Lightgbm on GPU you can check the official documentation. On documentation there are no configuration option as vebose_ecal and early_stopping_rounds Official Documentation Also you can check this link Running LightGBM on GPU with python
3
2
73,344,242
2022-8-13
https://stackoverflow.com/questions/73344242/converting-float32-to-float64-takes-more-than-expected-in-numpy
I had a performance issue in a numpy project and then I realized that about 3 fourth of the execution time is wasted on a single line of code: error = abs(detected_matrix[i, step] - original_matrix[j, new]) and when I have changed the line to error = abs(original_matrix[j, new] - detected_matrix[i, step]) the problem h...
TL;DR: Please use Numpy >= 1.23.0. This problem has been fixed in Numpy 1.23.0 (more specifically the version 1.23.0-rc1). This pull request rewrites the scalar math logic so to make it faster in many cases including in your specific use-case. With version 1.22.4, the former code is 10 times slower than the second one....
6
3
73,332,655
2022-8-12
https://stackoverflow.com/questions/73332655/how-to-use-value-in-the-python-implementation-of-protobuf
I have a proto file defined as: syntax = "proto3"; import "google/protobuf/struct.proto"; package generic.name; message Message { uint32 increment = 1; google.protobuf.Value payload = 2; } I have figured out how to make this work if I swap the payload type from Value for Struct: struct = Struct() struct.update({"a": ...
Here's an example: from foo_pb2 import Bar from google.protobuf.struct_pb2 import Struct bar = Bar() bar.payload.string_value="Freddie" print(bar) print(bar.SerializeToString()) bar.payload.bool_value=True print(bar) print(bar.SerializeToString()) # No need to initialize the Struct bar.payload.struct_value.update({"foo...
4
3
73,333,044
2022-8-12
https://stackoverflow.com/questions/73333044/change-elements-of-a-numpy-array-based-on-a-return-value-of-a-function-to-which
I have an array of RGBA values that looks something like this: # Not all elements are [0, 0, 0, 0] array([[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], ..., [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]) I also have a function which returns one of 5 values that a certain RGBA value is closest to (green, red, orange, brown, wh...
I would rewrite your function to be a bit more vectorized. First, you really don't need to loop through the entire dictionary of CSS colors for every pixel: the lookup table can be trivially precomputed. Second, you can map the five colors you want to RGBA values without using the names as an intermediary. This will ma...
3
3
73,323,222
2022-8-11
https://stackoverflow.com/questions/73323222/error-in-azure-storage-explorer-with-azurite-the-first-argument-must-be-of-typ
I'm running an Azure function locally, from VSCode, that outputs a string to a blob. I'm using Azurite to emulate the output blob container. My function looks like this: import azure.functions as func def main(mytimer: func.TimerRequest, outputblob:func.Out[str]): outputblob.set("hello") My function.json: { "scriptFil...
It looks like this is a known issue with the latest release (v1.25.0) of Azure Storage Explorer version see: https://github.com/microsoft/AzureStorageExplorer/issues/6008 Simplest solution is to uninstall and re-install an earlier version: https://github.com/microsoft/AzureStorageExplorer/releases/tag/v1.24.3
4
6
73,336,136
2022-8-12
https://stackoverflow.com/questions/73336136/does-having-a-wrapper-object-return-value-e-g-integer-cause-auto-boxing-in-ja
I couldn't find a definitive answer for this seemingly simple question. If I write a method like this: public Integer getAnInt() { int[] i = {4}; return i[0]; } is the return value autoboxed into an Integer, or does it depend on what happens to the value after it's returned (e.g. whether the variable it is assigned to...
Yes, boxed It will be (auto)boxed in the bytecode (.class file) because it's part of the public API, so other code might depend on the return value being an Integer. The boxing and unboxing might be removed at runtime by the JITter under the right circumstances, but I don't know if it does that sort of thing.
9
8
73,320,708
2022-8-11
https://stackoverflow.com/questions/73320708/set-run-description-programmatically-in-mlflow
Similar to this question, I'd like to edit/set the description of a run via code, instead of editing it via UI. To clarify, I don't want to set the description of my entire experiment, only of a single run.
There are two ways to set the description. 1. description parameter You can set a description using a markdown string for your run in mlflow.start_run() using description parameter. Here is an example. if __name__ == "__main__": # load dataset and other stuff run_description = """ ### Header This is a test **Bold**, *i...
5
14
73,332,533
2022-8-12
https://stackoverflow.com/questions/73332533/django-4-error-no-time-zone-found-with-key
After rebuild of my Django 4 Docker container the web service stopped working with this error: zoneinfo._common.ZoneInfoNotFoundError: 'No time zone found with key Asia/Hanoi' My setup is: Python 3.10 Django 4.0.5 Error: web_1 Traceback (most recent call last): web_1 File "/usr/local/lib/python3.10/zoneinfo/_common...
Downgrading the pytz version from 2022.2 to 2022.1 seems to have solved this issue for me.
17
16
73,316,644
2022-8-11
https://stackoverflow.com/questions/73316644/usage-of-direct-references-in-pyproject-toml-with-hatchling-backend
If I understand the documentation for hatchling correctly, in a pyproject.toml with hatchling as a backend, I should be able to to add a local package within the package folder by using the local direct reference schema <NAME> @ {root:uri}/pkg_inside_project. Here is a minimal non-working example where in the stackover...
From the issue tracker I received the answer, that I just have to add the following two lines to the pyproject.toml. See the documentation. [tool.hatch.metadata] allow-direct-references = true
12
18
73,315,383
2022-8-11
https://stackoverflow.com/questions/73315383/in-spacy-add-a-span-docab-as-entity-in-a-spacy-doc-python
I am using regex over a whole document to catch the spans in which such regex occurs: import spacy import re nlp = spacy.load("en_core_web_sm") doc = nlp("The United States of America (USA) are commonly known as the United States (U.S. or US) or America.") expression = r"[Uu](nited|\.?) ?[Ss](tates|\.?)" for match in r...
The most flexible way to add spans as entities to a doc is to use Doc.set_ents: from spacy.tokens import Span span = doc.char_span(start, end, label="ENT") doc.set_ents(entities=[span], default="unmodified") Use the default option to specify how to set all the other tokens in the doc. By default the other tokens are s...
4
5
73,322,634
2022-8-11
https://stackoverflow.com/questions/73322634/how-to-call-an-api-endpoint-from-a-different-api-endpoint-in-the-same-fastapi-ap
(I did find the following question on SO, but it didn't help me: Is it possible to have an api call another api, having them both in same application?) I am making an app using Fastapi with the following folder structure main.py is the entry point to the app from fastapi import FastAPI from fastapi.middleware.cors imp...
Refactor your code to have the common part as a function you call - you'd usually have this in a module external to your controller. # this function could live as LineService.get_random_line for example # its responsibility is to fetch a random line from a file def get_random_line(path="netflix_list.txt"): lines = open...
4
1
73,329,642
2022-8-12
https://stackoverflow.com/questions/73329642/unittests-for-mypy-reveal-type
I have some points in legacy code (python library: music21) that uses a lot of overloading and Generic variables to show/typecheck that all subelements in a t.Sequence belong to a particular type. There are a lot of @overload decorators to show how different attributes can return different values. At this point the fun...
The function you are looking for actually exists. But it is called differently: First, define a type test: from typing_extensions import assert_type def function_to_test() -> int: pass # this is a positive test: we want the return type to be int assert_type(function_to_test(), int) # this is a negative test: we don't w...
4
5
73,326,570
2022-8-11
https://stackoverflow.com/questions/73326570/why-is-the-float-int-multiplication-faster-than-int-float-in-cpython
Basically, the expression 0.4 * a is consistently, and surprisingly, significantly faster than a * 0.4. a being an integer. And I have no idea why. I speculated that it is a case of a LOAD_CONST LOAD_FAST bytecode pair being "more specialized" than the LOAD_FAST LOAD_CONST and I would be entirely satisfied with this ex...
It's CPython's implementation of the BINARY_MULTIPLY opcode. It has no idea what the types are at compile-time, so everything has to be figured out at run-time. Regardless of what a and b may be, BINARY_MULTIPLY ends up inoking a.__mul__(b). When a is of int type int.__mul__(a, b) has no idea what to do unless b is als...
8
9
73,325,131
2022-8-11
https://stackoverflow.com/questions/73325131/how-to-set-all-elements-of-pytorch-tensor-to-zero-after-a-certain-index-in-the-g
I've two PyTorch tensors mask = torch.ones(1024, 64, dtype=torch.float32) indices = torch.randint(0, 64, (1024, )) For every ith row in mask, I want to set all the elements after the index specified by ith element of indices to zero. For example, if the first element of indices is 50, then I want to set mask[0, 50:]=0...
You can first generate a tensor of size (1024x64) where each row has numbers arranged from 0 to 63. Then apply a logical operation using the indices reshaped as (1024x1) mask = torch.ones(1024, 64, dtype=torch.float32) indices = torch.randint(0, 64, (1024, 1)) # Note the dimensions mask[torch.arange(0, 64, dtype=torch....
9
6
73,302,356
2022-8-10
https://stackoverflow.com/questions/73302356/how-to-make-pip-fail-early-when-one-of-the-requested-requirements-does-not-exist
Minimal example: pip install tensorflow==2.9.1 non-existing==1.2.3 Defaulting to user installation because normal site-packages is not writeable Looking in indexes: https://pypi.org/simple, https://pypi.ngc.nvidia.com Collecting tensorflow==2.9.1 Downloading tensorflow-2.9.1-cp310-cp310-manylinux_2_17_x86_64.manylinux...
I'm afraid there's no straightforward way of handling it. I ended up writing a simple bash script where I check the availability of packages using pip's index command: check_packages_availability () { while IFS= read -r line || [ -n "$line" ]; do package_name="${line%%=*}" package_version="${line#*==}" if ! pip index v...
6
3
73,306,792
2022-8-10
https://stackoverflow.com/questions/73306792/dundered-global-variable-cannot-be-accessed-inside-a-class-method
I am experiencing an obscure (to me) effect of dundered scoping, and trying to work out the rule for it: #!/usr/bin/env python3 stuff = "the things" __MORE_STUFF = "even more" class Thing: def __init__(self): global __MORE_STUFF # doesn't help print(stuff) # is OK print(__MORE_STUFF) # fail! Thing() results in $ pytho...
The documentation refers to such names as class-private names: __* Class-private names. Names in this category, when used within the context of a class definition, are re-written to use a mangled form to help avoid name clashes between “private” attributes of base and derived classes. See section Identifiers (Names). ...
6
4
73,302,071
2022-8-10
https://stackoverflow.com/questions/73302071/nonetype-error-when-trying-to-use-pdb-via-formmatedtb
When executing the following code: from IPython.core import ultratb sys.excepthook = ultratb.FormattedTB(mode='Verbose', color_scheme='Linux', call_pdb=1) In order to catch exceptions, I receive the following error: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/Users/dinari/miniconda3/e...
Downgrading IPython to 7.34.0 solved this.
6
1
73,302,473
2022-8-10
https://stackoverflow.com/questions/73302473/pyqt5-delete-a-qlistwidgetitem-when-button-in-widget-is-pressed
I have a listWidget that contains multiple QListWidgetItem and for simplicity's sake, let's assume that each QListWidgetItem consists of a QWidget with a QPushButton called delete. This is assembled with this code: class widgetItem(QtWidgets.QWidget): def __init__(self, parent): super(widgetItem, self).__init__() uic.l...
You can remove listitems using the takeItem method and delete widgets using the deleteLater method. I wasn't to fond of your chosen process for creating the widgets and adding them to the list, so I went ahead and created a minimal example but using QPushButton instead of QWidgets for the itemWidgets. Example: from PyQ...
5
2
73,302,291
2022-8-10
https://stackoverflow.com/questions/73302291/is-it-legal-to-use-more-parameters-than-expected-when-calling-a-function
Context: I have written a Red Black tree implementation in C language. To allow it to use variable types, it only handles const void * elements, and initialisation of a tree must be given a comparison function with a signature int (*comp)(const void *, const void *). So far, so good, but I now try to use that C code to...
I think it invokes Undefined Behavior. From 6.5.2.2p6: If the expression that denotes the called function has a type that does not include a prototype, the integer promotions are performed on each argument, and arguments that have type float are promoted to double. These are called the default argument promotions. If ...
4
7
73,234,675
2022-8-4
https://stackoverflow.com/questions/73234675/how-to-download-a-file-after-posting-data-using-fastapi
I am creating a web application that receives some text, converts the text into speech, and returns an mp3 file, which is saved to a temporary directory. I want to be able to download the file from the html page (i.e., the frontend), but I don't know how to do that properly. I know with Flask you can do this: from app ...
Use the Form keyword to define Form-data in your endpoint, and more specifically, use Form(...) to make a parameter required, instead of using await request.form() and manually checking if the user submitted the required parameters. After processing the received data and generating the audio file, you can use FileRespo...
4
6
73,241,883
2022-8-4
https://stackoverflow.com/questions/73241883/multiple-pipenv-virtual-environments-in-single-project
The scenario: I have a locally cloned github repo with multiple branches. Each branch needs potentially different dependencies. The question: I would like to switch between these branches as I work and therefore would like multiple pipenv virtual environments (one per branch). How can I achieve this, given that pipenv ...
Check out each branch into a separate directory (e.g., using git worktree). Because each branch would have a separate directory, pipenv would work without any additional changes. Assuming that you're currently in your work tree (let's say on the main branch), and you have additional branches named branch1 and branch2, ...
4
3
73,289,360
2022-8-9
https://stackoverflow.com/questions/73289360/how-can-i-run-several-test-files-with-pytest
I have a pytest project and a want to run tests from TWO python files. The project structure looks like this: at the root of the project there is a "tests" folder, it contains several folders "test_api1", "test_api2", "test_api3", each of them contains conftest.py and a test file. tests: test_api1: conftest.py, test_a...
Just add files that you want to run as positional arguments, e.g.: python -m pytest tests/test_api1.py tests/test_api2.py NOTE: you need to run pytest without -k flag and hence use paths to the files instead of just filenames.
4
7
73,257,387
2022-8-6
https://stackoverflow.com/questions/73257387/how-to-un-pyinstaller-converted-python-app-with-shiny-for-python
I downloaded and installed Python 3.10.6 on windows 10 pro, installed Shiny for Python, created the sample app and run it. This worked fine. I installed pyinstaller and converted the app to an exe. I tried to run the app it threw (please see below). Does anyone know if this can work and if so how? This is the file2.spe...
New Answer Since writing my original answer I have discovered an even simpler means of using pyinstaller to create a shiny application executable. This is a simplified step by step: Steps 1-4 are the same as the original answer (see below) and simply involve opening a new directory and creating a virtual environment fo...
4
3
73,260,250
2022-8-6
https://stackoverflow.com/questions/73260250/how-do-i-type-hint-opencv-images-in-python
I get that in Python OpenCV images are numpy arrays, that correspond to cv::Mat in c++. This question is about what type-hint to put into python functions to properly restrict for OpenCV images (maybe even for a specific kind of OpenCV image). What I do now is: import numpy as np import cv2 Mat = np.ndarray def my_fun(...
UPD: As mentioned in another answer, now, OpenCV has cv2.typing.MatLike. Then, the code would be: import cv2 def my_fun(img: cv2.typing.MatLike) -> None: pass You can specify it as numpy.typing.NDArray with an entry type. For example, import numpy as np Mat = np.typing.NDArray[np.uint8] def my_fun(img: Mat): pass
13
8
73,287,475
2022-8-9
https://stackoverflow.com/questions/73287475/how-to-specify-pip-extra-index-url-in-environment-yml
Conda can create an environment.yml that specifies both conda packages & pip packages. The problem is, I want to specify a pip package (torch==1.12.1+cu116), that is only available in the following index: https://download.pytorch.org/whl/cu116. How can I specify this in the environment.yml? Or at the very least, when r...
This configuration should work, see the advanced-pip-example for other options. name: foo channels: - defaults dependencies: - python - pip - pip: - --extra-index-url https://download.pytorch.org/whl/cu116 - torch==1.12.1+cu116 See also Combining conda environment.yml with pip requirements.txt Can conda be configured...
17
27
73,282,411
2022-8-8
https://stackoverflow.com/questions/73282411/how-to-add-background-tasks-when-request-fails-and-httpexception-is-raised-in-fa
I was trying to generate logs when an exception occurs in my FastAPI endpoint using a Background task as: from fastapi import BackgroundTasks, FastAPI app = FastAPI() def write_notification(message=""): with open("log.txt", mode="w") as email_file: content = f"{message}" email_file.write(content) @app.post("/send-notif...
The way to do this is to override the HTTPException error handler, and since there is no BackgroundTasks object in the exception_handler, you can add a background task to a response in the way that is described in Starlette documentation (FastAPI is actually Starlette underneath). On a side note, FastAPI will run a bac...
7
13
73,226,501
2022-8-3
https://stackoverflow.com/questions/73226501/how-to-move-or-remove-the-legend-from-a-seaborn-jointgrid-or-jointplot
How to remove the legend in the seaborn.JoingGrid plot? The reference code is like below: import matplotlib.pyplot as plt import seaborn as sns penguins = sns.load_dataset("penguins") g = sns.JointGrid(data=penguins, x="bill_length_mm", y="bill_depth_mm", hue="species") g.plot_joint(sns.scatterplot) sns.boxplot(data=pe...
To remove the legend, the correct part of the sns.JointGrid must be accessed. In this case g.ax_joint is where the legend is located. As stated in a comment by mwaskom, Matplotlib axes have .legend (a method that creates a legend) and .legend_ (the resulting object). Don't access variables that start with an unders...
5
3
73,257,839
2022-8-6
https://stackoverflow.com/questions/73257839/setup-py-install-is-deprecated-warning-shows-up-every-time-i-open-a-terminal-i
Every time I boot up terminal on VSCode, I get the following prompt. This does not happen on Terminal.app. /usr/local/lib/python3.9/site-packages/setuptools/command/install.py:34: SetuptoolsDeprecationWarning: setup.py install is deprecated. Use build and pip and other standards-based tools. How do I resolve this?
Install the setuptools 58.2.0 version using the following command: pip install setuptools==58.2.0
40
40
73,297,326
2022-8-9
https://stackoverflow.com/questions/73297326/how-to-validate-keys-with-whitespaces-in-pydantic
I have a json key with whitespace in it: My_dict = {"my key": 1} I want to create a Model to model it: from pydantic import BaseModel class MyModel(BaseModel): mykey: int # my key isn't a legit variable name # my_key is, but like mykey - it doesn't catch the correct key from the json MyModel(**my_dict) This doesn't w...
Yes, it's possible by using Field's aliases: from pydantic import BaseModel, Field class MyModel(BaseModel): mykey: int = Field(alias='my key') class Config: allow_population_by_field_name = True print(MyModel(**{"my key": 1})) print(MyModel(**{"mykey": 1})) [Edit @Omer Iftikhar] For Pydantic V2: You need to use popul...
5
11
73,245,011
2022-8-5
https://stackoverflow.com/questions/73245011/are-abstract-base-classes-redundant-since-protocol-classes-were-introduced
I'm learning how to use Protocol classes that have been introduced in Python 3.8 (PEP 544). So typing.Protocol classes are subclasses from ABCMeta and they are treated just like abstract classes are with the added benefit of allowing to use structural subtyping. I was trying to think of what I would use abstract base c...
I prefer ABCs beacuse they're explicit. With a Protocol someone reading the code may not know your class is intended to implement an interface in another module or deep in a dependency. Similarly, you can accidentally conform to a Protocol's signature, without conforming to its contract. For example, if a function acce...
17
10
73,241,420
2022-8-4
https://stackoverflow.com/questions/73241420/how-to-align-yticklabels-when-combining-a-barplot-with-heatmap
I have similar problems as this question; I am trying to combine three plots in Seaborn, but the labels on my y-axis are not aligned with the bars. My code (now a working copy-paste example): import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt from matplotlib.colors import LogNo...
See here that none of the y-axis ticklabels are aligned because multiple dataframes are used for plotting. It will be better to create a single dataframe, violations, with the aggregated data to be plotted. Start with the sum of amounts by violation, and then add a new percent column. This will insure the two bar plot...
7
7
73,297,673
2022-8-9
https://stackoverflow.com/questions/73297673/what-is-the-difference-between-queryset-last-and-latest-in-django
I want to get data which inserted in the last so I used a django code user = CustomUser.objects.filter(email=email).last() So it gives me the last user detail. But then experimentally I used: user = CustomUser.objects.filter(email=email).latest() Then It didn't give me a user object. Now, what is the difference between...
There are several differences between .first() [Django-doc]/.last() [Django-doc] and .earliest(…) [Django-doc]/.latest(…) [Django-doc]. The main ones are: .first() and .last() do not take field names (or orderable expressions) to order by, they do not have parameters, .earliest(…) and .latest(…) do; .first() and .last...
8
18
73,274,526
2022-8-8
https://stackoverflow.com/questions/73274526/how-to-integrate-torch-into-a-docker-image-while-keeping-image-size-reasonable
So I've a Flask web app that will be exposing some deep learning models. I built the image and everything works fine. the problem is the size of this image is 5.58GB! which is a bit ridiculous. I have some deep learning models that are copied during the build, I thought they might be the culprit but their size combined...
By default torch will package CUDA packages and stuff. Add --extra-index-url https://download.pytorch.org/whl/cpu and --no-cache-dir to pip install command if you do not require CUDA. RUN pip install --no-cache-dir -r requirements.txt --extra-index-url https://download.pytorch.org/whl/cpu Also it's good practice to rem...
5
10
73,268,995
2022-8-7
https://stackoverflow.com/questions/73268995/typeerror-when-calling-super-in-dataclassslots-true-subclass
I am trying to call a a superclass method from a dataclass with slots=True in Python 3.10.5. from dataclasses import dataclass @dataclass(slots=True) class Base: def hi(self): print("Hi") @dataclass(slots=True) class Sub(Base): def hi(self): super().hi() Sub().hi() I get the following error. Traceback (most recent cal...
As seen here, the dataclass decorator creates a new class object, and so the __closure__ attached to hi() is different to the one attached to the decorated class, and therefore the super() call cannot work without arguments due to relying on the __closure__. Therefore, you need to change super().hi() to super(Sub, self...
13
16
73,267,607
2022-8-7
https://stackoverflow.com/questions/73267607/how-to-train-model-with-multiple-gpus-in-pytorch
My server has two GPUs, How can I use two GPUs for training at the same time to maximize their computing power? Is my code below correct? Does it allow my model to be properly trained? class MyModel(nn.Module): def __init__(self): super(MyModel, self).__init__() self.bert = pretrained_model # for param in self.bert.par...
There are two different ways to train on multiple GPUs: Data Parallelism = splitting a large batch that can't fit into a single GPU memory into multiple GPUs, so every GPU will process a small batch that can fit into its GPU Model Parallelism = splitting the layers within the model into different devices is a bit tric...
8
11
73,275,243
2022-8-8
https://stackoverflow.com/questions/73275243/vs-code-debugger-immediately-exits
I use VS Code for a python project but recently whenever I launch the debugger it immediately exits. The debug UI will pop up for half a second then disappear. I can't hit a breakpoint no matter where it's placed in the current file. The project has the expected normal behavior when run in non-debug mode. I vaguely rem...
Please install Python 3.7 or later. If you must use Python 3.6 or earlier, rollback the Python extension to version 2022.08.0.
8
7
73,241,595
2022-8-4
https://stackoverflow.com/questions/73241595/why-is-vscode-on-ubuntu-searching-for-the-python-dist-packages-directory-in-a-us
I'm running vscode release (1.69.2 dated 7/18/22) with the python extension on Ubuntu 20.04. When I try to run some code with the debugger I get an exception because it can't find my_venv_dir/lib/python3.8/dist-packages. I've read a bit about Ubuntu's use of dist-packages and site-packages but I haven't found any infor...
It looks like something was corrupted in the vscode configuration. I tried uninstalling and reinstalling vscode but noticed that when I started up again, vscode remembered where I left off. When I deleted the ~/.config/Code directory the problem was fixed. I suspect that the corruption happened when I updated to a newe...
6
2
73,238,082
2022-8-4
https://stackoverflow.com/questions/73238082/pip-install-returning-a-valueerror
I recently tried to install a library using Pip, and I received this error message. I am unable to install any packages, as the same error message keeps popping up. I notice this problem in both my main enviroment, and my venv Virtual Environment. Any help will be much appreciated. WARNING: Ignoring invalid distributio...
I was able to fix the problem by hard-coding in a 1, instead of having CERT_NONE being passed to verify_mode. The error message gave me the location of the code: File "C:\Users\name\AppData\Local\Programs\Python\Python310\lib\ssl.py", line 738, in verify_mode super(SSLContext, SSLContext).verify_mode.__set__(self, 0) ...
7
2
73,234,123
2022-8-4
https://stackoverflow.com/questions/73234123/how-copy-file-to-clipboard-using-python-or-cl-to-paste-it-using-strgv-later-on
I am trying to copy (using python or a CL command which I then can call using python) a file to the clipboard to later paste it using STRG+V. As far as I understand it, files are not "moved" into the clipboard, but rather the clipboard holds the path and an argument/flag that tells the OS "this is a file". I am happy w...
Configurations The clipboard is part of the Window Management and not of the Linux operating system itself. Different configurations with different distributions behave differently and therefore require different variants. Meanwhile, Wayland is increasingly on the way to successively replace X, which means there are th...
6
6
73,269,000
2022-8-7
https://stackoverflow.com/questions/73269000/efficient-logic-to-pad-tensor
I'm trying to pad a tensor of some shape such that the total memory used by the tensor is always a multiple of 512 E.g. Tensor shape 16x1x1x4 of type SI32 (Multiply by 4 to get total size) The total elements are 16x4x1x1 = 64 Total Memory required 64x**4** = 256 (Not multiple of 512) Padded shape would be 32x1x1x4 = 51...
If you want the total memory to be a multiple of 512 then the number of elements in the tensor must be a multiple of 512 // DATA_TYPE_MULTIPLIER, e.g. 128 in your case. Whatever that number is, it will have a prime factorization of the form 2**n. The number of elements in the tensor is given by s[0]*s[1]*...*s[d-1] whe...
7
5
73,275,868
2022-8-8
https://stackoverflow.com/questions/73275868/what-is-the-best-way-to-perform-value-estimation-on-a-dataset-with-discrete-con
What is the best approach to this regression problem, in terms of performance as well as accuracy? Would feature importance be helpful in this scenario? And how do I process this large range of data? Please note that I am not an expert on any of this, so I may have bad information or theories about why things/methods d...
For modeling right-skewed targets such as prices I'd try other distributions than Gaussian, like gamma or log-normal. The algo can be made less restrictive. GBDTs offer best trade-off in terms of accuracy for such tabular data, and should be able to capture some non-linearities. They even accept categorical variables...
5
1
73,219,378
2022-8-3
https://stackoverflow.com/questions/73219378/python-pptx-how-to-replace-keyword-across-multiple-runs
I have two PPTs (File1.pptx and File2.pptx) in which I have the below 2 lines XX NOV 2021, Time: xx:xx – xx:xx hrs (90mins) FY21/22 / FY22/23 I wish to replace like below a) NOV 2021 as NOV 2022. b) FY21/22 / FY22/23 as FY21/22 or FY22/23. But the problem is my replacement works in File1.pptx but it doesn't work in Fi...
As one can find in python-pptx's documentation at https://python-pptx.readthedocs.io/en/latest/api/text.html a text frame is made up of paragraphs and a paragraph is made up of runs and specifies a font configuration that is used as the default for it's runs. runs specify part of the paragraph's text with a certain fo...
4
4
73,269,424
2022-8-7
https://stackoverflow.com/questions/73269424/interpreting-the-effect-of-lk-norm-with-different-orders-on-training-machine-lea
Both the RMSE and the MAE are ways to measure the distance between two vectors: the vector of predictions and the vector of target values. Various distance measures, or norms, are possible. Generally speaking, calculating the size or length of a vector is often required either directly or as part of a broader vector or...
Another python implementation for the np.linalg is: def my_norm(array, k): return np.sum(np.abs(array) ** k)**(1/k) To test our function, run the following: array = np.random.randn(10) print(np.linalg.norm(array, 1), np.linalg.norm(array, 2), np.linalg.norm(array, 3), np.linalg.norm(array, 10)) # And print(my_norm(arr...
7
2