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
69,319,437
2021-9-24
https://stackoverflow.com/questions/69319437/decode-firebase-jwt-in-python-using-pyjwt
I have written the following code : def check_token(token): response = requests.get("https://www.googleapis.com/robot/v1/metadata/x509/securetoken@system.gserviceaccount.com") key_list = response.json() decoded_token = jwt.decode(token, key=key_list, algorithms=["RS256"]) print(f"Decoded token : {decoded_token}") I am...
The 2nd parameter key in decode() seems to take a string value instead of list. The Google API request returns a dict/map containing multiple keys. The flow goes like: Fetch public keys from the Google API endpoint Then read headers without validation to get the kid claim then use it to get appropriate key from that d...
6
8
69,320,328
2021-9-24
https://stackoverflow.com/questions/69320328/rust-loop-performance-same-as-python
I was working on mandelbrot algorithm to learn Rust and I found out that empty 25mil(approx 6k image) loop takes 0.5s. I found it quite slow. So I went to test it in python and found out, it takes almost the same time. Has really python's for loop almost zero cost abstraction? Is this really the best I can get with int...
If you're doing performance testing always build with --release. By default Cargo builds with debugging information enabled and optimizations disabled. The optimizer will completely eliminate these loops. On the Playground it drops from 975ms to 1.25µs. Let's take a look at the assembly on Godbolt for just the loops, n...
4
13
69,313,876
2021-9-24
https://stackoverflow.com/questions/69313876/how-to-get-points-of-the-svg-paths
I have an SVG file, for example, this <svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg"> <path fill="none" stroke="red" d="M 10,30 A 20,20 0,0,1 50,30 A 20,20 0,0,1 90,30 Q 90,60 50,90 Q 10,60 10,30 z" /> </svg> How can I get the list of the points (x, y) for those paths? I have seen that answer but it's n...
Here you can change the scale, offset, and density of the points: from svg.path import parse_path from xml.dom import minidom def get_point_at(path, distance, scale, offset): pos = path.point(distance) pos += offset pos *= scale return pos.real, pos.imag def points_from_path(path, density, scale, offset): step = int(pa...
8
5
69,306,799
2021-9-23
https://stackoverflow.com/questions/69306799/why-does-the-lines-count-differently-using-two-different-way-to-load-text
import pathlib file_path = 'vocab.txt' vocab = pathlib.Path(file_path).read_text().splitlines() print(len(vocab)) count = 0 with open(file_path, 'r', encoding='utf8') as f: for line in f: count += 1 print(count) The two counts are 2122 and 2120. Shouldn't they be same?
So, looking at the documentation for str.splitlines, we see that the line delimiters for this method are a superset of "universal newlines": This method splits on the following line boundaries. In particular, the boundaries are a superset of universal newlines. Representation Description \n Line Feed \r Car...
9
7
69,292,855
2021-9-23
https://stackoverflow.com/questions/69292855/why-do-i-get-an-unprocessable-entity-error-while-uploading-an-image-with-fasta
I am trying to upload an image but FastAPI is coming back with an error I can't figure out. If I leave out the "file: UploadFile = File(...)" from the function definition, it works correctly. But when I add the file to the function definition, then it throws the error. Here is the complete code. @router.post('/', respo...
The problem is that your route is expecting 2 types of request body: request: schemas.Item This is expecting POSTing an application/json body See the Request Body section of the FastAPI docs: "Read the body of the request as JSON" file: UploadFile = File(...) This is expecting POSTing a multipart/form-data See the...
5
5
69,285,679
2021-9-22
https://stackoverflow.com/questions/69285679/setting-pythonwarnings-to-disable-python-warnings-seems-to-do-nothing
I'm currently running the openstack executable and it generates python deprecation warnings. After some searching I did find this howto. The relevant part is here: Use the PYTHONWARNINGS Environment Variable to Suppress Warnings in Python We can export a new environment variable in Python 2.7 and up. We can export PYT...
PYTHONWARNINGS certainly does suppress python's warnings. Try running: PYTHONWARNINGS="ignore" python -c "import warnings; warnings.warn('hi')" But in this case you are not calling python, but openstack, which is apparently not inheriting the same environment. Without looking at the source I can't say why. It may even...
5
6
69,297,409
2021-9-23
https://stackoverflow.com/questions/69297409/serializers-validated-data-fields-got-changed-with-source-value-in-drf
I am trying to create an api, where user can create programs and add rules to them. Rules has to be executed in order of priority. I am using Django rest framework to achieve this and I am trying to achieve this using Serializer without using ModelSerializer. Provide your solution using serializers.Serializer class One...
Solution 1: The fields in validated data is renamed with the source attribute. You can use the renamed attribute in create method of serializer. For nested serializers, seems the validated data contains OrderedDict. You can convert it to regular Dict, and can get the rule id. class ProgramSerializer(serializers.Seriali...
5
3
69,299,294
2021-9-23
https://stackoverflow.com/questions/69299294/can-we-call-a-pytest-fixture-conditionally
My use case is to call fixture only if a certain condition is met. But since we need to call the pytest fixture as an argument to a test function it gets called every time I run the test. I want to do something like this: @pytest.parameterize("a", [1, 2, 3]) def test_method(a): if a == 2: method_fixture
Yes, you can use indirect=True for a parameter to have the parameter refer to a fixture. import pytest @pytest.fixture def thing(request): if request.param == 2: return func() return None @pytest.mark.parametrize("thing", [1, 2, 3], indirect=True) def test_indirect(thing): pass # thing will either be the retval of `fun...
5
4
69,289,547
2021-9-22
https://stackoverflow.com/questions/69289547/how-to-remove-dynamically-fields-from-a-dataclass
I want to inherit my dataclass but remove some of its fields. How can I do that in runtime so I don't need to copy all of the members one by one? Example: from dataclasses import dataclass @dataclass class A: a: int b: int c: int d: int @remove("c", "d") class B(A): pass Such that A would have a, b, c, d defined and B...
We can remove the particular fields from the __annotations__ dictionary as well as from __dataclass_fields__ and then rebuild our class using dataclasses.make_dataclass: def remove(*fields): def _(cls): fields_copy = copy.copy(cls.__dataclass_fields__) annotations_copy = copy.deepcopy(cls.__annotations__) for field in ...
5
2
69,297,600
2021-9-23
https://stackoverflow.com/questions/69297600/why-isnt-my-dockerignore-file-ignoring-files
When I build the container and I check the files that should have been ignored, most of them haven't been ignored. This is my folder structure. Root/ data/ project/ __pycache__/ media/ static/ app/ __pycache__/ migrations/ templates/ .dockerignore .gitignore .env docker-compose.yml Dockerfile requirements.txt manage.py...
You're actually injecting your source code using volumes:, not during the image build, and this doesn't honor .dockerignore. Running a Docker application like this happens in two phases: You build a reusable image that contains the application runtime, any OS and language-specific library dependencies, and the applica...
9
17
69,291,738
2021-9-22
https://stackoverflow.com/questions/69291738/how-to-encode-all-logged-messages-as-utf-8-in-python
I have a little logger function that returns potentially two handlers to log to a RotatingFileHandler and sys.stdout simultaneously. import os, logging, sys from logging.handlers import RotatingFileHandler from config import * def get_logger(filename, log_level_stdout=logging.WARNING, log_level_file=logging.INFO, echo=...
Set the encoding while instantiating the handler instead of encoding the message explicitly. file_handler = RotatingFileHandler( PATH + '/Logs/' + filename, maxBytes=1048576, backupCount=3, encoding='utf-8' ) help(RotatingFileHandler) is your best friend. Help on class RotatingFileHandler in module logging.handlers: ...
8
6
69,278,251
2021-9-22
https://stackoverflow.com/questions/69278251/plotly-including-additional-data-in-hovertemplate
hovertemplate= 'Continent: %{df['continent']}'+ 'Country: %{df['country']}'+ 'gdpPercap: %{x:,.4f} '+ 'lifeExp: %{y}'+ '' I'm trying to use hovertemplate to customize hover information. However I can't get it to display what I want. I am getting x & y to work well. I can't figure out how to add other fields to the hov...
See below for an additional example of how to use customdata with multiple traces based on the code included in your question. Note that you actually need to add the customdata to the figure traces in order to use it in the hovertemplate, this was also shown in Derek O's answer. import numpy as np import pandas as pd i...
14
19
69,289,275
2021-9-22
https://stackoverflow.com/questions/69289275/web-parser-in-javascript-like-beautiful-soup-in-python
Python has a library called Beautiful Soup that you can use to parse an HTML tree without creating 'get' requests in external web pages. I'm looking for the same in JavaScript, but I've only found jsdom and JSSoup (which seems unused) and if I'm correct, they only allow you to make requests. I want a library in JavaScr...
In a browser context, you can use DOMParser: const html = "<h1>title</h1>"; const parser = new DOMParser(); const parsed = parser.parseFromString(html, "text/html"); console.log(parsed.firstChild.innerText); // "title" and in node you can use node-html-parser: import { parse } from 'node-html-parser'; const html = "<h...
11
8
69,287,269
2021-9-22
https://stackoverflow.com/questions/69287269/installing-ruamel-yaml-clib-with-docker
I have a small project in django rest framework and I want to dockerize it. In my requirements.txt file there is a package called ruamel.yaml.clib==0.2.6. While downloading all other requirements is successfull, there is a problem when it tries to download this package. #11 208.5 Collecting ruamel.yaml.clib==0.2.6 #11 ...
I think the problem is with the way your Dockerfile tries to install ruamel.yaml.clib. It should be installed using pip (just as documented for the ruamel.yaml). I suggest you take it out of the requirements.txt and explicitly do a pip install -U pip setuptools wheel ruamel.yaml.clib==0.2.6 in your Dockerfile instead...
4
3
69,285,056
2021-9-22
https://stackoverflow.com/questions/69285056/python-locate-elements-in-sublists
given these sublists lst=[['a', 'b', 'c', 'd', 'e'], ['f', 'g', 'h']] I am trying to find the location of its elements, for instance, the letter 'a' is located at 0,0 but this line print(lst.index('a')) instead produces the following error: ValueError: 'a' is not in list
You can use list comprehension: >>> lst=[['a', 'b', 'a', 'd', 'a'], ['f', 'g', 'a'], ['a','a','b']] >>> [(i,j) for i in range(len(lst)) for j in range(len(lst[i])) if lst[i][j]=='a'] [(0, 0), (0, 2), (0, 4), (1, 2), (2, 0), (2, 1)]
5
0
69,284,018
2021-9-22
https://stackoverflow.com/questions/69284018/euler-mascheroni-constant
In programming, I used only Integers. But this time for some calculations. I need to calculate Euler-Mascheroni Constant γ . up to n-th decimal.{Though n ∈ [30, 150] is enough for me. [x] = gif(x) = math.floor(x) But, I doubt the precision Numerical Algorithm I need higher degree of accuracy using Python.
From the French Wikipedia discussion page, an approximation to 6 decimal places: import math as m EulerMascheroniApp = round( (1.-m.gamma(1+1.e-8))*1.e14 )*1.e-6 print(EulerMascheroniApp) # 0.577216 This constant is also available in the sympy module, under the name EulerGamma: >>> import sympy >>> sympy.EulerGamma Eu...
5
4
69,279,865
2021-9-22
https://stackoverflow.com/questions/69279865/how-to-get-second-highest-value-from-a-column-pyspark
I have a PySpark DataFrame and I would like to get the second highest value of ORDERED_TIME (DateTime Field yyyy-mm-dd format) after a groupBy applied to 2 columns, namely CUSTOMER_ID and ADDRESS_ID. A customer can have many orders associated with an address and I would like to get the second most recent order for a (c...
Here is another way to do it. Using collect_list import pyspark.sql.functions as F from pyspark.sql import Window sorted_order_times = Window.partitionBy("CUSTOMER_ID", "ADDRESS_ID").orderBy(F.col('ORDERED_TIME').desc()).rangeBetween(Window.unboundedPreceding, Window.unboundedFollowing) df2 = ( df .withColumn("second_r...
5
5
69,276,878
2021-9-22
https://stackoverflow.com/questions/69276878/pytest-unittest-mock-patch-function-from-module
Given a folder structure like such: dags/ **/ code.py tests/ dags/ **/ test_code.py conftest.py Where dags serves as the root of the src files, with 'dags/a/b/c.py' imported as 'a.b.c'. I want to test the following function in code.py: from dag_common.connections import get_conn from utils.database import dbtypes def ...
Yeah. I also fought with this initially when I learned patching and mocking and know how frustrating it is as you seem to be doing everything right, but it does not work. I sympathise with you! This is actually how mocking of imported stuff works, and once you realise it, it actually makes sense. The problem is that im...
16
38
69,277,713
2021-9-22
https://stackoverflow.com/questions/69277713/how-to-change-the-grid-line-color-in-plotly-scatter-plot
I use plotly dash to draw the following scatter charts, and how can I change the grid line color
To customize the grid in plotly, do the following. This will allow you to display the grid on the xy axis, set the line width and line color. fig.update_xaxes(showgrid=True, gridwidth=1, gridcolor='LightPink') fig.update_yaxes(showgrid=True, gridwidth=1, gridcolor='LightPink')
5
10
69,276,894
2021-9-22
https://stackoverflow.com/questions/69276894/str-isdigit-behaviour-when-handling-strings
Assuming the following: >>> square = '²' # Superscript Two (Unicode U+00B2) >>> cube = '³' # Superscript Three (Unicode U+00B3) Curiously: >>> square.isdigit() True >>> cube.isdigit() True OK, let's convert those "digits" to integer: >>> int(square) Traceback (most recent call last): File "<stdin>", line 1, in <modul...
str.isdigit doesn't claim to be related to parsability as an int. It's reporting a simple Unicode property, is it a decimal character or digit of some sort: str.isdigit() Return True if all characters in the string are digits and there is at least one character, False otherwise. Digits include decimal characters and d...
17
21
69,270,727
2021-9-21
https://stackoverflow.com/questions/69270727/how-to-solve-typeerror-the-json-object-must-be-str-bytes-or-bytearray-not-t
enter image description here i can not solve .... how to solve : TypeError: the JSON object must be str, bytes or bytearray, not TextIOWrapper
You are using loads when you need load. json.load is for file-like objects, and json.loads is for strings. (You could also load the string into memory and then parse it with json.load, but you don't want to do that).
8
22
69,213,098
2021-9-16
https://stackoverflow.com/questions/69213098/python-aws-sqs-mocking-with-moto
I am trying to mock an AWS SQS with moto, below is my code from myClass import get_msg_from_sqs from moto import mock_sqs #from moto.sqs import mock_sqs @mock_sqs def test_get_all_msg_from_queue(): #from myClass import get_msg_from_sqs conn = boto3.client('sqs', region_name='us-east-1') queue = conn.create_queue(QueueN...
Your queue variable is a dict returned by create_queue: queue = conn.create_queue(QueueName='Test') It is not a queue and thus you cannot call sendMessage on it. To do that, you need to create a queue object: conn = boto3.client('sqs') sqs = boto3.resource('sqs') response = conn.create_queue(QueueName='Test') queue_ur...
6
4
69,240,815
2021-9-19
https://stackoverflow.com/questions/69240815/i-am-trying-to-importfrom-torchtext-legacy-data-import-field-bucketiterator-it
I am trying to execute the following code for a nlp proj import torchtext from torchtext.legacy.data import Field, BucketIterator, Iterator from torchtext.legacy import data ----> 6 from torchtext.legacy.data import Field, BucketIterator, Iterator 7 from torchtext.legacy import data 8 ModuleNotFoundError: No module nam...
Before you import torchtext.legacy, you need to !pip install torchtext==0.10.0. Maybe legacy was removed in version 0.11.0.
7
12
69,205,085
2021-9-16
https://stackoverflow.com/questions/69205085/how-to-make-isort-always-produce-multi-line-output-when-there-are-multiple-impor
I'm currently using isort --profile=black --line-length=79 as a linter in my project for python files. This produces the Vertical Hanging Indent (mode 3 in isort's documentation kind of output: from third_party import ( lib1, lib2, lib3, lib4, ) This multiline mode only applies if the line is longer than 79 characters...
You should use the --force-grid-wrap 2 flag in the CLI or set in the settings file like pyproject.toml option force_grid_wrap = 2. This would force isort to produce multiline output for 2 or more imports, regardless of line length. More info about this option
10
10
69,250,540
2021-9-20
https://stackoverflow.com/questions/69250540/how-to-read-decode-secure-qr-code-on-indian-aadhaar-card-image
I am trying to extract the complete Aadhar number (12 digits) from the image of an Aadhar card (India) I am able to identify the region with QR code. To extract the info - I have been looking into python libraries that read and decode Secure QR codes on Indian Aadhaar cards. These 2 libraries seem particularly useful ...
Thanks for posting the question. I am the author of aadhaar-py, the code raises an exception because the data passed to the lib cannot be parsed. It has to be of a certain type in order for it to be parsable. Please refer the following link for an example: https://uidai.gov.in/te/ecosystem-te/authentication-devices-doc...
8
1
69,239,403
2021-9-19
https://stackoverflow.com/questions/69239403/type-hinting-parameters-with-a-sentinel-value-as-the-default
I currently use this strategy when I cannot assign default arguments in a function's signature and/or None already has meaning. from typing import Optional DEFAULT = object() # `None` already has meaning. def spam(ham: Optional[list[str]] = DEFAULT): if ham is DEFAULT: ham = ['prosciutto', 'jamon'] if ham is None: prin...
Something I like to do — which is only a slight variation on @Blckknght's answer — is to use a metaclass to give my sentinel class a nicer repr and make it always-falsey. sentinel.py from typing import Literal class SentinelMeta(type): def __repr__(cls) -> str: return f'<{cls.__name__}>' def __bool__(cls) -> Literal[F...
12
6
69,265,924
2021-9-21
https://stackoverflow.com/questions/69265924/cloud-run-flask-api-container-running-shutit-enters-a-sleep-loop
The issue has appeared recently and the previously healthy container now enters a sleep loop when a shutit session is being created. The issue occurs only on Cloud Run and not locally. Minimum reproducible code: requirements.txt Flask==2.0.1 gunicorn==20.1.0 shutit Dockerfile FROM python:3.9 # Allow statements and log...
I have reproduced your issue and we have discussed several possibilities, I think the issue is your Cloud Run not being able to process requests and hence preparing to shut down(sigterm). I am listing some possibilities for you to look at and analyse. A good reason for your Cloud Run service failing to start is that t...
6
2
69,224,969
2021-9-17
https://stackoverflow.com/questions/69224969/how-to-avoid-to-start-hundreds-of-threads-when-starting-very-short-actions-at
I use this method to launch a few dozen (less than thousand) of calls of do_it at different timings in the future: import threading timers = [] while True: for i in range(20): t = threading.Timer(i * 0.010, do_it, [i]) # I pass the parameter i to function do_it t.start() timers.append(t) # so that they can be cancelled...
As I understand it, you want a single worker thread that can process submitted tasks, not in the order they are submitted, but rather in some prioritized order. This seems like a job for the thread-safe queue.PriorityQueue. from dataclasses import dataclass, field from threading import Thread from typing import Any fro...
5
6
69,263,078
2021-9-21
https://stackoverflow.com/questions/69263078/pandas-dataframe-to-excel-cell-alignment
I noticed that for string in Dataframe will keep left align in Excel and for numerical value will keep right align in Excel. How do we set the desired alignment we wanted when exporting DataFrame to Excel? Example: Center Alignment df = pd.DataFrame({"colname1": ["a","b","c","d"], "colname2": [1,2,3,4]}) with pd.ExcelW...
You can set the styles of the dataframe using the Styler object, which uses the same conventions as CSS. The documentation has a great primer on the different ways of styling your dataframes. For a simple solution to your example, you can set the desired alignment by first creating a function: def align_center(x): retu...
9
8
69,262,697
2021-9-21
https://stackoverflow.com/questions/69262697/divide-group-data-base-on-select-columns-values
df ts_code type close 0 861001.TI 1 648.399 1 861001.TI 20 588.574 2 861001.TI 30 621.926 3 861001.TI 60 760.623 4 861001.TI 90 682.313 ... ... ... ... 8328 885933.TI 5 1083.141 8329 885934.TI 1 951.493 8330 885934.TI 5 1011.346 8331 885935.TI 1 1086.558 8332 885935.TI 5 1028.449 Goal ts_code l5d_close l20d_close …… ...
Use sort_values to make sure type == 1 is the first row per group and extract them with groupby.transform('first'): df = df.sort_values(['ts_code', 'type']) close1 = df.groupby('ts_code')['close'].transform('first') df['close'] = close1 / df['close'] # ts_code type close # 0 861001.TI 1 1.000000 # 1 861001.TI 20 1.1016...
5
5
69,234,978
2021-9-18
https://stackoverflow.com/questions/69234978/how-to-visualize-gensim-word2vec-embeddings-in-tensorboard-projector
Following gensim word2vec embedding tutorial, I have trained a simple word2vec model: from gensim.test.utils import common_texts from gensim.models import Word2Vec model = Word2Vec(sentences=common_texts, size=100, window=5, min_count=1, workers=4) model.save("/content/word2vec.model") I would like to visualize it usi...
Saving the model in the original C word2vec implementation format resolves the issue: model.wv.save_word2vec_format("/content/word2vec.model"): from gensim.test.utils import common_texts from gensim.models import Word2Vec model = Word2Vec(sentences=common_texts, size=100, window=5, min_count=1, workers=4) model.wv.save...
5
1
69,212,337
2021-9-16
https://stackoverflow.com/questions/69212337/pandas-using-apply-lambda-with-two-different-operators
This question is very similar to one I posted before with just one change. Instead of doing just the absolute difference for all the columns I also want to find the magnitude difference for the 'Z' column, so if the current Z is 1.1x greater than prev than keep it. (more context to the problem) Pandas using the previou...
I have modified mozway's function so that it works according to your requirements. # comparing 'equal' float values, may go wrong, that's why I am using this constant DELTA=0.1**12 def check_previous_group(rank, d, groups): if not rank-1 in groups.groups: # check if a previous group exists, else flag all rows False (i....
6
1
69,262,618
2021-9-21
https://stackoverflow.com/questions/69262618/why-is-this-code-able-to-use-the-sklearn-function-without-import-sklearn
So I just watched a tutorial that the author didn't need to import sklearn when using predict function of pickled model in anaconda environment (sklearn installed). I have tried to reproduce the minimal version of it in Google Colab. If you have a pickled-sklearn-model, the code below works in Colab (sklearn installed)...
There's a few questions being asked here, so let's go through them one by one: So, how does it work? as far as I understand pickle doesn't depend on scikit-learn. There is nothing particular to scikit-learn going on here. Pickle will exhibit this behaviour for any module. Here's an example with Numpy: will@will-deskt...
7
11
69,262,518
2021-9-21
https://stackoverflow.com/questions/69262518/problem-with-simpleeval-installationuse-2to3-invalid
We are using poetry to upgrade packages and deploy to our servers but some issue is stopping us from deploying our work continuously to our servers.The code below is the stacktrack where our code stops. $ poetry update Creating virtualenv kpbackend-ad2VTdyQ-py3.9 in /root/.cache/pypoetry/virtualenvs Updating dependenci...
I encountered the same error some time ago. The issue seems to be connected with the latest upgrade of setuptools package (https://setuptools.pypa.io/en/latest/history.html#v58-0-0). The workaround that is working for me is to use setuptools<=57.5.0.
4
8
69,190,210
2021-9-15
https://stackoverflow.com/questions/69190210/django-django-rest-how-do-i-save-user-device-to-prevent-tedious-2fa-on-every-log
Hello I have been working with Django Rest Framework with JWT as authentication framework and I successfully made Two factor authentication Login based on Email OTP but one thing I want to improve is I want to improve login and save user's device so that repeated 2FA(Two factor Authentcation) can be minimized? here is ...
TLDR; At a very high level: tokenize the OTP (exchange the otp for a JWT). Explanation A JWT is nothing more than a JSON signed payload with some standardized fields exp (expiration), nbf (not before), etc.... The signature (symmetric or asymmetric) assures integrity, authenticity, and non-repudiation (eg the token has...
5
3
69,254,006
2021-9-20
https://stackoverflow.com/questions/69254006/tuple-with-multiple-numbers-of-arbitrary-but-equal-type
Currently, I am checking for tuples with multiple (e.g. three) numbers of arbitrary but equal type in the following form: from typing import Tuple, Union Union[Tuple[int, int, int], Tuple[float, float, float]] I want to make this check more generic, also allowing numpy number types. I.e. I tried to use numbers.Number:...
You can use TypeVar with bound argument. It allows restricting types to subtypes of a given type. In your case, the types should be the subtypes of Number: from numbers import Number from typing import TypeVar T = TypeVar('T', bound=Number) Tuple[T, T, T] Why does it work? TypeVar is a variable that allows to use a pa...
11
9
69,260,592
2021-9-20
https://stackoverflow.com/questions/69260592/construct-graph-connectivity-matrices-in-coo-format
I have faced the following subtask while working with graph data: I need to construct graph connectivity matrices in COO format for graphs with several fully-connected components from arrays of "border" indices. As an example, given array borders = [0, 2, 5] the resulting COO matrix should be coo_matrix = [[0, 0, 1, 1...
Since your goal is a faster solution than what you have, you can explore itertools for solving this efficiently. This approach benchmarks approximately 25 times faster than your current approach as tested on larger border lists. import numpy as np from itertools import product, chain def get_coo(borders): edges = chain...
5
5
69,260,530
2021-9-20
https://stackoverflow.com/questions/69260530/panel-data-regression-with-fixed-effects-using-python
I have the following panel stored in df: state district year y constant x1 x2 time 0 01 01001 2009 12 1 0.956007 639673 1 1 01 01001 2010 20 1 0.972175 639673 2 2 01 01001 2011 22 1 0.988343 639673 3 3 01 01002 2009 0 1 0 33746 1 4 01 01002 2010 1 1 0.225071 33746 2 5 01 01002 2011 5 1 0.450142 33746...
I dug around the documentation and the solution turned out to be quite simple. After setting the indexes and turning the fixed effect columns to pandas.Categorical types (see question above): # Import model from linearmodels.panel import PanelOLS # Model m = PanelOLS(dependent=df['y'], exog=df[['constant','x1','x2']], ...
7
9
69,274,391
2021-9-21
https://stackoverflow.com/questions/69274391/how-to-convert-tokenized-words-back-to-the-original-ones-after-inference
I'm writing a inference script for already trained NER model, but I have trouble with converting encoded tokens (their ids) into original words. # example input df = pd.DataFrame({'_id': [1], 'body': ['Amazon and Tesla are currently the best picks out there!']}) # calling method that handles inference: ner_model = NER(...
Provided you only want to "merge" company names one could do that in a linear time with pure Python. Skipping the beginning of sentence token [CLS] for brevity: tokens = tokens[1:] tags = tags[1:] The function below will merge company tokens and increase pointer appropriately: def merge_company(tokens, tags): generate...
6
2
69,270,836
2021-9-21
https://stackoverflow.com/questions/69270836/whats-the-point-of-using-object-instance-self
I was checking the code of the toolz library's groupby function in Python and I found this: def groupby(key, seq): """ Group a collection by a key function """ if not callable(key): key = getter(key) d = collections.defaultdict(lambda: [].append) for item in seq: d[key(item)](item) rv = {} for k, v in d.items(): rv[k] ...
This is a somewhat confusing trick to save a small amount of time: We are creating a defaultdict with a factory function that returns a bound append method of a new list instance with [].append. Then we can just do d[key(item)](item) instead of d[key(item)].append(item) like we would have if we create a defaultdict tha...
40
40
69,276,393
2021-9-21
https://stackoverflow.com/questions/69276393/is-the-sqlalchemy-text-function-exposed-to-sql-injection
I'm learning how to use SQL Alchemy, and I'm trying to re-implement a previously defined API but now using Python. The REST API has the following query parameter: myService/v1/data?range=time:2015-08-01:2015-08-02 So I want to map something like field:FROM:TO to filter a range of results, like a date range, for exampl...
If queries are constructed using string formatting then sqlalchemy.text will not prevent SQL injection - the "injection" will already be present in the query text. However it's not difficult to build queries dynamically, in this case by using getattr to get a reference to the column. Assuming that you are using the ORM...
7
9
69,276,288
2021-9-21
https://stackoverflow.com/questions/69276288/why-is-this-python-code-faster-than-its-equivalent-clojure-code
I've been told, and I believe, that Clojure is faster than Python. Why does this Python code run faster than this seemingly equivalent Clojure code? Is Python doing some optimizations at compile time? def find_fifty(n,memory=1,count=0): if memory < 0.5: return count else: return find_fifty(n,memory*(1 - count/n),count+...
Clojure's division operator, when applied to integers, does exact rational division. It does not round down to the next lowest integer as Python's does. Your algorithm involves memory becoming a very complex fraction, despite yielding a simple integer. I've amended your function to print its intermediate values before ...
6
10
69,272,911
2021-9-21
https://stackoverflow.com/questions/69272911/altair-chart-show-less-lines-in-the-grid
I'm working on a chart using Altair, and I'm trying to figure out how to have less lines in the background grid. Is there a term for that background grid? Here's a chart that looks like mine, that I took from the tutorial: Let's say that I want to have half as many grid lines on the X axis. How could I do that?
Grid lines are drawn at the location of ticks, so to adjust the grid lines you can adjust the ticks. For example: import altair as alt import numpy as np import pandas as pd x = np.arange(100) source = pd.DataFrame({ 'x': x, 'f(x)': np.sin(x / 5) }) alt.Chart(source).mark_line().encode( x=alt.X('x', axis=alt.Axis(tickC...
5
3
69,273,242
2021-9-21
https://stackoverflow.com/questions/69273242/dynamically-create-function-with-typehint-in-memory
I'd like to dynamically create a function in memory, with a type hint of the argument. I do have some working code, but it feels extremely hacky and fragile. import typing func_name = 'some_function_name' req_type=int a = None exec(f'''def {func_name}(my_argument:{req_type.__name__}): pass a = {func_name}''') print(a) ...
You can use FunctionType to create new functions. You can copy a template function and change its type hints and name. You also can change the code of the function object with compile Python function. I made an example that copy and change the name and the type hint of template function (without changing code) import t...
5
3
69,266,375
2021-9-21
https://stackoverflow.com/questions/69266375/different-access-time-to-a-value-of-a-dictionary-when-mixing-int-and-str-keys
Let's say I have two dictionaries and I know want to measure the time needed to check if a key is in the dictionary. I tried to run this piece of code: from timeit import timeit dct1 = {str(i): 1 for i in range(10**7)} dct2 = {i: 1 for i in range(10**7)} print(timeit('"7" in dct1', setup='from __main__ import dct1', nu...
Let me try to answer my own question. The dict implementation in CPython is optimised for lookups of str keys. Indeed, there are two different functions that are used to perform lookups: lookdict is a generic dictionary lookup function that is used with all types of keys lookdict_unicode is a specialised lookup functi...
9
5
69,263,878
2021-9-21
https://stackoverflow.com/questions/69263878/adding-water-to-stack-of-glasses
I always wanted to know if there is any real-world application of Pascal's triangle than just coefficients of the binomial expansion. I tried to solve this problem: But, What if I am adding K units of water and wants to find a glass which has the least water in it: Where, Glass will be found as: c-th glass in r-th ro...
For such small K constraint simple row-by-row filling is enough (we can store only two rows, here 2D list is used for simplicity) def fillGlasses(k, row, col): gl = [[k]] level = 1 overflow_occured = True while overflow_occured: # also can stop when at needed row print(gl[level-1]) #before overflow level += 1 overflow_...
6
1
69,261,606
2021-9-20
https://stackoverflow.com/questions/69261606/how-can-i-make-a-key-dynamic-in-a-pydantic-model
i have an api entrypoint: @app.get('/dealers_get_users/', response_model = schemas.SellSideUserId, status_code=200) def getdata(db: database.SessionLocal = _Depends(database.get_db)): result = {} i = db.query(models.sellSideUser).all() for dealer_users in i: result[str(dealer_users.user_id)] = { 'user_name' : dealer_us...
You can easily make a model with dynamic keys using a dict as custom root type: class User(BaseModel): name: str password: str class ProductModel(BaseModel): __root__: Dict[str, User] Moreover, you can constrain dictionary keys using constr сapabilities, such as regex pattern: UserId = constr(regex=r'^\d+$') class Pro...
4
10
69,240,807
2021-9-19
https://stackoverflow.com/questions/69240807/how-to-change-colors-of-the-tracking-points-and-connector-lines-on-the-output-vi
I am referring to 33 body points and connector lines between them. I'd like to change the colors of those, especially of the white default color of the connector lines. Here's my code, I have created a class module for mediapipe which I can import and use in my other programs import cv2 import mediapipe as mp class pos...
So as per the documentation, this is the code for draw_landmarks mp_drawing.draw_landmarks( image: numpy.ndarray, landmark_list: mediapipe.framework.formats.landmark_pb2.NormalizedLandmarkList, connections: Optional[List[Tuple[int, int]]] = None, landmark_drawing_spec: mediapipe.python.solutions.drawing_utils.DrawingSp...
4
8
69,262,878
2021-9-21
https://stackoverflow.com/questions/69262878/what-are-the-differences-between-pickle-dump-load-and-pickle-dumps-loads
I've started to learn about the pickle module used for object serialization and deserialization. I know that pickle.dump is used to store the code as a stream of bytes (serialization), and pickle.load is essentially the opposite, turning a stream of bytes back into a python object. (deserialization). But what are pickl...
The difference between dump and dumps is that dump writes the pickled object to an open file, and dumps returns the pickled object as bytes. The file must be opened for writing in binary mode. The pickled version of the object is exactly the same with both dump and dumps. So, if you did the following for object obj: wi...
11
22
69,260,910
2021-9-20
https://stackoverflow.com/questions/69260910/better-help-for-argparse-subcommands
Given the following code snippet: import argparse import sys parser = argparse.ArgumentParser() subparsers = parser.add_subparsers(help="subcommand help") command1 = subparsers.add_parser("foo", description="Run foo subcommand") command2 = subparsers.add_parser("bar", description="Run bar subcommand") opts = parser.par...
You need to set the help parameter, not the description parameter, to get the output you desire: import argparse import sys parser = argparse.ArgumentParser() subparsers = parser.add_subparsers(help="subcommand help") command1 = subparsers.add_parser("foo", help="Run foo subcommand") command2 = subparsers.add_parser("b...
5
6
69,254,808
2021-9-20
https://stackoverflow.com/questions/69254808/the-simplest-interface-to-let-subprocess-output-to-both-file-and-stdout-stderr
I want something have similar effect of cmd > >(tee -a {{ out.log }}) 2> >(tee -a {{ err.log }} >&2) in python subporcess without calling tee. Basically write stdout to both stdout and out.log files and write stderr to both stderr and err.log. I knew I could use a loop to handle it. But since I have lots of Popen, subp...
No simple way as far as I can tell, but here is a way: import os class Tee: def __init__(self, *files, bufsize=1): files = [x.fileno() if hasattr(x, 'fileno') else x for x in files] read_fd, write_fd = os.pipe() pid = os.fork() if pid: os.close(read_fd) self._fileno = write_fd self.child_pid = pid return os.close(write...
5
2
69,257,426
2021-9-20
https://stackoverflow.com/questions/69257426/meson-finds-python3-binary-fails-to-find-python3-dependency
I'm trying to build a certain repository using meson on Cygwin. This is what happens: $ meson build_dir The Meson build system Version: 0.58.2 Source dir: /home/joeuser/src/meld-3.21.0 Build dir: /home/joeuser/src/meld-3.21.0/build_dir Build type: native build Project name: meld Project version: 3.21.0 Host machine cpu...
meson will find python3 if you also install the python3-devel package using the Cygwin installer.
6
4
69,246,880
2021-9-19
https://stackoverflow.com/questions/69246880/notifications-in-postgresql-with-pythonpsycopg2-does-not-work
I want to be notified when there is a new entry in a specific table "FileInfos" in PostgreSQL 12, so I wrote the following trigger: create trigger trigger1 after insert or update on public."FileInfos" for each row execute procedure notify_id_trigger(); and the following function: create or replace function notify_id_t...
According to NOTIFY syntax, channel is an identifier. That means that new_Id in LISTEN new_Id is automaticaly converted to new_id. Unfortunately, pg_notify('new_Id'::text, new."Id"::text) notifies on channel new_Id. You have two options. Change the channel in the trigger: perform pg_notify('new_id'::text, new."Id"::te...
5
5
69,247,270
2021-9-19
https://stackoverflow.com/questions/69247270/argument-unpacking-with-custom-getitem-method-never-terminates
Could someone explain what is going on under the hood and why this program does not finish? class A: def __getitem__(self, key): return 1 print(*A())
This program doesn't finish because the class you defined is iterable, using the old sequence iteration protocol. Basically, __getitem__ is called with integers increasing from 0, ..., n until an IndexError is raised. >>> class A: ... def __getitem__(self, key): ... return 1 ... >>> it = iter(A()) >>> next(it) 1 >>> ne...
4
7
69,246,724
2021-9-19
https://stackoverflow.com/questions/69246724/python-append-a-list-to-a-list
I'm doing some exercises in Python and I came across a doubt. I have to set a list containing the first three elements of list, with the .append method. The thing is, I get an assertion error, lists don't match. If I print list_first_3 I get "[['cat', 3.14, 'dog']]", so the double square brackets are the problem. But h...
append can only add a single value. I think what you may be thinking of is the extend method (or the += operator) list1 = ["cat", 3.14, "dog", 81, 6, 41] list_first_3 = [] list_first_3.extend(list1[:3]) assert list_first_3 == ["cat", 3.14, "dog"] or list1 = ["cat", 3.14, "dog", 81, 6, 41] list_first_3 = [] list_first_...
6
11
69,243,145
2021-9-19
https://stackoverflow.com/questions/69243145/error-when-trying-to-produce-a-graph-in-plotly-dash
When trying to produce a figure with the following code @app.callback( [ Output("selected-plot", "figure") ], [ Input("submit-selected-plotting", "n_clicks"), State("table", "data") ], ) def plot(button_clicked, data) fig = go.Scatter(x=data["index"], y=data["result"], mode='lines', name='result') return fig and dbc....
The error is due to the fact that the app expects a figure object, you can fix it by updating the callback as follows: @app.callback( [ Output("selected-plot", "figure") ], [ Input("submit-selected-plotting", "n_clicks"), State("table", "data") ], ) def plot(button_clicked, data) trace = go.Scatter( x=data["index"], y=...
4
12
69,234,878
2021-9-18
https://stackoverflow.com/questions/69234878/using-shared-dockerfile-for-multiple-dockerfiles
What I have, are multi similar and simple dockerfiles But what I want is to have a single base dockerfile and my dockerfiles pass their variables into it. In my case the only difference between dockerfiles are simply their EXPOSE, so I think it's better to keep a base dockerfile and other dockerfiles only inject that v...
as yasen said, it's impossible to have import directive. finally what I have did is as follow: link to github repository create a template text file with EXPOSE ${{ EXPOSED_PORT }}: FROM golang:1.17 AS builder WORKDIR /app COPY . . RUN go mod download && make ent-generate RUN go build -o /bin/app ./cmd/root.go FROM a...
4
2
69,233,701
2021-9-18
https://stackoverflow.com/questions/69233701/finding-the-coordinates-of-pixels-over-a-line-in-an-image
I have an image represented as a 2D array. I would like to get the coordinates of pixels over a line from point 1 to point 2. For example, let's say I have an image with size 5x4 like in the image below. And I have a line from point 1 at coordinates (0, 2) to point 2 at (4, 1). Like the red line on the image below: So...
You can do this with scikit-image: from skimage.draw import line # Get coordinates, r=rows, c=cols of your line rr, cc = line(0,2,4,1) print(list(zip(rr,cc))) [(0, 2), (1, 2), (2, 1), (3, 1), (4, 1)] The source code to see the implemented algorithm: https://github.com/scikit-image/scikit-image/blob/main/skimage/draw/_...
7
4
69,230,525
2021-9-17
https://stackoverflow.com/questions/69230525/why-does-poetry-build-raise-moduleorpackagenotfound-exception
I want to use poetry to build and distribute Python source packages, but after poetry init I get an error running poetry build. ModuleOrPackageNotFound No file/folder found for package mdspliter.tree
Reason The reason it can't be found is most likely because the directory hierarchy is incorrect. The released package is not directly the source code folder, there are many things in it that are not needed in the final package such as version control, testing and dependency management. You should put this folder with t...
28
33
69,232,157
2021-9-18
https://stackoverflow.com/questions/69232157/checking-if-elements-in-an-array-exist-in-a-pandas-dataframe
I have a pandas Dataframe and a pandas Series that looks like below. df0 = pd.DataFrame({'col1':['a','b','c','d'],'col2':['b','c','e','f'],'col3':['d','f','g','a']}) col1 col2 col3 0 a b d 1 b c f 2 c e g 3 d f a df1 = pd.Series(['b','g','g'], index=['col1','col2','col3']) col1 b col2 g col3 g dtype: object As you can...
You can make use of broadcasting: (df0 == df1).any().values It also works with NumPy ndarrays: assert (df0.columns == df1.columns).all() (df0.values == df1.values).any(axis=0) Output: array([ True, False, True])
8
0
69,229,901
2021-9-17
https://stackoverflow.com/questions/69229901/changed-properties-do-not-trigger-signal
For a subclass of QObject I'd like to define a property. On change, a signal should be emitted. According to the documentation, something like this: p = Property(int, _get_p, _set_p, notify=p_changed) should work, but the signal is not emitted by the change. Full example here: from PySide2.QtCore import QObject, Proper...
That you associate a signal to a QProperty does not imply that it will be emitted automatically but that you have to emit it explicitly. def _set_p(self, v): if self._p != v: print(f"Setting new p: {v}") self._p = v self.p_changed.emit() For more information read The Property System.
4
3
69,224,622
2021-9-17
https://stackoverflow.com/questions/69224622/get-fastapi-to-handle-requests-in-parallel
Here is my trivial fastapi app: from datetime import datetime import asyncio import uvicorn from fastapi import FastAPI app = FastAPI() @app.get("/delayed") async def get_delayed(): started = datetime.now() print(f"Starting at: {started}") await asyncio.sleep(10) ended = datetime.now() print(f"Ending at: {ended}") retu...
It works in parallel as expected - it is just a browser thing: chrome on detecting the same endpoint being requested in different tabs, will wait for the first to be completly resolved to check if the result can be cached. If instead you place 3 http requests from different processes in the shell, the results are as ex...
6
6
69,227,434
2021-9-17
https://stackoverflow.com/questions/69227434/how-to-get-aws-glue-schema-registry-schema-definition-using-boto3
My goal is to receive csv files in S3, convert them to avro, and validate them against the appropriate schema in AWS. I created a series of schemas in AWS Glue Registry based on the .avsc files I already had: { "namespace": "foo", "type": "record", "name": "bar.baz", "fields": [ { "name": "column1", "type": ["string", ...
After some more digging I found the somewhat confusingly named get_schema_version() method that I had been overlooking which returns the SchemaDefinition: { 'SchemaVersionId': 'string', 'SchemaDefinition': 'string', 'DataFormat': 'AVRO'|'JSON', 'SchemaArn': 'string', 'VersionNumber': 123, 'Status': 'AVAILABLE'|'PENDING...
5
4
69,223,702
2021-9-17
https://stackoverflow.com/questions/69223702/python-tkinter-how-can-i-make-ttk-notebook-tabs-change-their-order
Is it possible to do this: with ttk.Notebook widget?
Yes, it is possible. You have to bind B1-Motion to a function, then use notebook.index("@x,y") to get the index of the tab at mouse position. You can then make use of notebook.insert() to insert at a particular position. import tkinter as tk from tkinter import ttk def reorder(event): try: index = notebook.index(f"@{ev...
5
12
69,222,860
2021-9-17
https://stackoverflow.com/questions/69222860/pip3-command-to-upgrade-all-packages-that-is-careful-about-dependency-conflicts
So far, I have used (via How to upgrade all Python packages with pip) pip3 list --format freeze --outdated | cut -d= -f1 | xargs pip3 install --upgrade-strategy eager --upgrade to upgrade all of my Python pip packages. It has so far worked fine for me - except for once, when I got a sort of a conflict message, unfortu...
Upgrading packages in python is never easy due to overlapping (sub)dependencies. There are some tools out there that try and help you manage. At my current job we use pip-tools. And in some projects we use poetry but I'm less happy about it's handling. For pip-tools you define your top-level packages in requirements.in...
6
8
69,220,221
2021-9-17
https://stackoverflow.com/questions/69220221/use-of-torch-stack
t1 = torch.tensor([1,2,3]) t2 = torch.tensor([4,5,6]) t3 = torch.tensor([7,8,9]) torch.stack((t1,t2,t3),dim=1) When implementing the torch.stack(), I can't understand how stacking is done for different dim. Here stacking is done for columns but I can't understand the details as to how it is done. It becomes more compl...
Imagine have n tensors. If we stay in 3D, those correspond to volumes, namely rectangular cuboids. Stacking corresponds to combining those n volumes on an additional dimension: here a 4th dimension is added to host the n 3D volumes. This operation is in clear contrast with concatenation, where the volumes would be comb...
10
17
69,216,791
2021-9-17
https://stackoverflow.com/questions/69216791/creating-an-edge-list-from-a-pandas-dataframe
I'd like to create an edge list with weights as an attribute (counts number of pair occurrences - e.g., how many months have the pair a-b been together in the same group). The dataframe contains a monthly snapshot of people in a particular team (there are no duplicates on the monthly groups) monthyear name jun2...
Assuming that there are no duplicates within each monthyear group, you can get all 2-combinations of names within each group and then group by the node names to obtain the weight. from itertools import combinations def get_combinations(group): return pd.DataFrame([sorted(e) for e in list(combinations(group['name'].valu...
7
3
69,205,577
2021-9-16
https://stackoverflow.com/questions/69205577/fill-gaps-in-time-series-pandas-dataframe
I have a pandas dataframe with gaps in time series. It looks like the following: Example Input -------------------------------------- Timestamp Close 2021-02-07 09:30:00 124.624 2021-02-07 09:31:00 124.617 2021-02-07 10:04:00 123.946 2021-02-07 16:00:00 123.300 2021-02-09 09:04:00 125.746 2021-02-09 09:05:00 125.646 20...
You can achieve what you need with a combination of df.groupby() (over dates) and resampling using rule = "1Min". Try this - df_new = (df.assign(date=df.Timestamp.dt.date) #create new col 'date' from the timestamp .set_index('Timestamp') #set timestamp as index .groupby('date') #groupby for each date .apply(lambda x: x...
4
7
69,214,628
2021-9-16
https://stackoverflow.com/questions/69214628/invoking-a-constructor-in-a-with-statement
I have the following code: class Test: def __init__(self, name): self.name = name def __enter__(self): print(f'entering {self.name}') def __exit__(self, exctype, excinst, exctb) -> bool: print(f'exiting {self.name}') return True with Test('first') as test: print(f'in {test.name}') test = Test('second') with test: print...
The __enter__ method should return the context object. with ... as ... uses the return value of __enter__ to determine what object to give you. Since your __enter__ returns nothing, it implicitly returns None, so test is None. with Test('first') as test: print(f'in {test.name}') test = Test('second') with test: print(f...
51
61
69,200,881
2021-9-15
https://stackoverflow.com/questions/69200881/how-to-get-python-unittest-to-show-log-messages-only-on-failed-tests
Issue I've been trying to use the unittest --buffer flag to suppress logs for successful tests and show them for failing tests. But it seems to show the log output regardless. Is this a quirk of the logging module? How can I get the log output only on failing tests? Is there a special config on the logger that is requi...
A Solution for the Sample Code Just before the test runs we need to update the stream on the log handler to point to the buffer unittest has set up for capturing the test output. import logging import unittest import sys logger = logging.getLogger('abc') logging.basicConfig( format = '%(asctime)s %(module)s %(levelname...
5
6
69,185,877
2021-9-15
https://stackoverflow.com/questions/69185877/should-i-use-python-native-multithread-or-multiple-tasks-in-airflow
I'm refactoring a .NET application to airflow. This .NET application uses multiple threads to extract and process data from a mongoDB (Without multiple threads the process takes ~ 10hrs, with multi threads i can reduce this) . In each documment on mongoDB I have a key value namedprocess. This value is used to control w...
It really depends on the nature of your processing. Multi-threading in Python can be limiting because of GIL (Global Interpreter Lock) - there are some operations that require exclusive lock, and this limit the parallelism it can achieve. Especially if you mix CPU and I/O operations the effects might be that a lot of t...
5
3
69,205,854
2021-9-16
https://stackoverflow.com/questions/69205854/iterating-over-dictionary-in-python-and-using-each-value
I am trying to iterate over a dictionary that looks like this: account_data = {"a": "44196397", "b": "2545086098", "c": "210623431", "d": "1374059147440820231", "e": "972970759416111104", "f": "1060627757812641792", "g": "1368361032796700674", "h": "910899153772916736", "i": "887748030304329728", "j": "1381341090", "k"...
Use for loop for iteration. dict = {'a': 1, 'b': 2, 'c': 3} for key, value in dict.items(): print(key+" "+ str(value)) for key in dict: print(key+ " "+str(dict[key])) The first one iterates over items and gives you keys and values. The second one iterates over keys and then it is accessing value from the dictionary us...
22
47
69,192,732
2021-9-15
https://stackoverflow.com/questions/69192732/default-python-paths-when-using-vscode-interactive-window
Suppose the Python package mypackage is at a non-standard location on my machine and I am running Python code in the VSCode interactive window. If I type import mypackage it will not be found. This can be remedied by doing sys.path.append("/path/to/mypackage"). However, I would like to set things up so that within a gi...
You can do this to modify the PYTHONPATH: Add these in the settings.json file to Modify the PYTHONPATH in the terminal: "terminal.integrated.env.windows": { "PYTHONPATH": "xxx/site-packages" } Create a .env file under your workspace, and add these settings in it to modify the PYTHONPATH for the extension and debugger...
6
3
69,201,761
2021-9-16
https://stackoverflow.com/questions/69201761/python-selenium-chrome-driver-ssl-certificate-verify-failed-unable-to-get-local
When trying to run undetected-chromedriver I was running into the following error: urllib.error.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate
If you're using macOS go to Macintosh HD > Applications > Python3.9 folder (or whatever version of python you're using) > double click on "Install Certificates.command" file.
4
13
69,201,168
2021-9-16
https://stackoverflow.com/questions/69201168/modulenotfounderror-no-module-named-project-when-using-sys-path-append
I'm trying to import models from a folder in the parent directory. Im using sys.path.append(). My project structure: -Project folder1 file1.py ... folder2 file2.py ... In file1.py file: sys.path.append('../Project') from Project.folder2 import file2 I then get a: ModuleNotFoundError: No module named Project I...
2 errors in your code: The Project directory is not just 1-level up. From the point of view of file1.py, it is actually 2 levels up. See this: $ cd .. (venv) nponcian 1$ tree . └── Project ├── folder1 │ └── file1.py └── folder2 └── file2.py (venv) nponcian 1$ cd Project/folder1/ (venv) nponcian folder1$ ls .. folder1...
6
6
69,198,303
2021-9-15
https://stackoverflow.com/questions/69198303/sets-the-default-value-of-a-parameter-based-on-the-value-of-another-parameter
So I want to create a function that generates consecutive numbers from 'start' to 'end' as many as 'size'. For the iteration, it will be calculated inside the function. But I have problem to set default value of parameter 'end'. Before I explain further, here's the code: # Look at this ------------------------------- #...
This is a pretty standard pattern: def consecutive_generator(size=20, start=0, end=None): if end is None: end = size + start
6
6
69,193,013
2021-9-15
https://stackoverflow.com/questions/69193013/adding-a-column-with-one-single-categorical-value-to-a-pandas-dataframe
I have a pandas.DataFrame df and would like to add a new column col with one single value "hello". I would like this column to be of dtype category with the single category "hello". I can do the following. df["col"] = "hello" df["col"] = df["col"].astype("category") Do I really need to write df["col"] three times in ...
We can explicitly build the Series of the correct size and type instead of implicitly doing so via __setitem__ then converting: df['col'] = pd.Series('hello', index=df.index, dtype='category') Sample Program: import pandas as pd df = pd.DataFrame({'a': [1, 2, 3]}) df['col'] = pd.Series('hello', index=df.index, dtype='...
6
4
69,186,176
2021-9-15
https://stackoverflow.com/questions/69186176/determine-if-subclass-has-a-base-classs-method-implemented-in-python
I have a class that extends a base class. Upon instantiation, I want to check if the subclass has one of the classes implemented from its base, but I'm not sure the best way. hasattr(self, '[method]') returns the method from super if not implemented by the child, so I'm trying to tell the difference. Here is an example...
I'm not sure I understand correctly, but it sounds like you might be looking for Abstract Base Classes. (Documentation here, tutorial here.) If you specify an abstractmethod in a base class that inherits from abc.ABC, then attempting to instantiate a subclass will fail unless that subclass overrides the abstractmethod....
5
4
69,188,655
2021-9-15
https://stackoverflow.com/questions/69188655/how-to-add-a-row-in-a-special-form
I have a pandas.DataFrame of the form index df df1 0 0 111 1 1 111 2 2 111 3 3 111 4 0 111 5 2 111 6 3 111 7 0 111 8 2 111 9 3 111 10 0 111 11 1 111 12 2 111 13 3 111 14 0 111 15 1 111 16 2 111 17 3 111 18 1 111 19 2 111 20 3 111 I want to create a dataframe in which column df repeats 0,1,2,3. But there is something m...
Using @Mozway's idea, and combining with some helper functions from pyjanitor, the missing values can be made explicit, and later filled. Again, this is just another option : # pip install pyjanitor import pandas as pd import janitor as jn (df.assign(temp = df.df.diff().le(0).cumsum()) .complete('df', 'temp') # helper ...
5
5
69,188,743
2021-9-15
https://stackoverflow.com/questions/69188743/how-to-use-a-service-account-to-authorize-google-sheets
I am trying to open a private google sheet using python. The end goal here is to read that private sheet data into a json object. I have made sure to create a google cloud project, enable the API's, and service account. The service account email has been shared and added as an editor. I also created OAuth keys for a de...
All you need to do is supply the library with the location of the clientSecret.json file you should have downloaded from Google cloud console. This method should build the service for you and you can make the requests to the api. It will handle all the authorization. from apiclient.discovery import build from oauth2cli...
6
6
69,188,132
2021-9-15
https://stackoverflow.com/questions/69188132/how-to-convert-all-float64-columns-to-float32-in-pandas
Is there a generic way to convert all float64 values in a pandas dataframe to float32 values? But not changing uint16 to float32? I don't know the signal names in advance but just want to have no float64. Something like: if float64, then convert to float32, else nothing? The structure of the data is: DF.dtypes Counter...
Try this: df[df.select_dtypes(np.float64).columns] = df.select_dtypes(np.float64).astype(np.float32)
16
16
69,187,685
2021-9-15
https://stackoverflow.com/questions/69187685/getting-attributeerror-module-base64-has-no-attribute-decodestring-error-wh
Issue description: Getting AttributeError: module 'base64' has no attribute 'decodestring' error while running on python 3.9.6 Steps to reproduce: Below is a dummy program, while running on python 3.9.6, I am getting `AttributeError: module 'base64' has no attribute 'decodestring'`` error: from ldif3 import LDIFParser ...
From the docs for Python 3.8, base64.decodestring() is described as a: Deprecated alias of decodebytes(). It looks like the base64.decodestring() function has been deprecated since Python 3.1, and removed in Python 3.9. You will want to use the bas64.decodebytes() function instead.
15
32
69,186,311
2021-9-15
https://stackoverflow.com/questions/69186311/python-input-function-not-working-in-vs-code
balance = 100 print('Current Balance: ', balance) while balance > 0: print('1. WITHDRAW') print('2. DEPOSIT') choice = input("Select an option... ") if (choice == 1): print('1') elif (choice == 2): print('2') else: print('test') When I run the code with the code runner extension the code shows in the terminal however...
Code Runner shows results in OUTPUT and doesn't accept inputs by default. Add "code-runner.runInTerminal": true in Settings.json, then you can input data.
9
18
69,186,179
2021-9-15
https://stackoverflow.com/questions/69186179/2d-alpha-shape-concave-hull-problem-in-python
I have a large set of 2D points that I've downsampled into a 44x2 numpy array (array defined later). I am trying to find the bounding shape of those points which are effectively a concave hull. In the 2nd image I've manually marked an approximate bounding shape that I am hoping to get. I have tried using alphashape a...
The plots that you attached are misleading, since the scales on the x-axis and the y-axis are very different. If you set both axes to the same scale, you obtain the following plot: . Since differences between x-coordinates of points are on the average much larger than differences between y-coordinates, you cannot obtai...
5
5
69,137,780
2021-9-10
https://stackoverflow.com/questions/69137780/provide-additional-custom-metric-to-lightgbm-for-early-stopping
I running a binary classification in LightGBM using the training API and want to stop on a custom metric while still tracking one or more builtin metrics. It's not clear if this is possible, though. Here we can disable the default binary_logloss metric and only track our custom metric: import lightgbm as lgb def my_eva...
If you are asking "how do I perform early stopping based on a custom evaluation metric function?", that can be achieved by setting parameter metric to the string "None". That will lead LightGBM to skip the default evaluation metric based on the objective function (binary_logloss, in your example) and only perform early...
5
14
69,183,922
2021-9-14
https://stackoverflow.com/questions/69183922/playwright-auto-scroll-to-bottom-of-infinite-scroll-page
I am trying to automate the scraping of a site with "infinite scroll" with Python and Playwright. The issue is that Playwright doesn't include, as of yet, a scroll functionnality let alone an infinite auto-scroll functionnality. From what I found on the net and my personnal testing, I can automate an infinite or finite...
The new Playwright version has a scroll function. it's called mouse.wheel(x, y). In the below code, we'll be attempting to scroll through youtube.com which has an "infinite scroll": from playwright.sync_api import Playwright, sync_playwright import time def run(playwright: Playwright) -> None: browser = playwright.chro...
19
17
69,140,016
2021-9-11
https://stackoverflow.com/questions/69140016/grayscale-image-different-in-cv2-imshow-and-matplotlib-pyplot-show
import cv2 import numpy as np import math import sys import matplotlib.pyplot as plt import utils as ut imgGray = cv2.imread(imgfile, cv2.IMREAD_GRAYSCALE) plt.imshow(imgGray, cmap = 'gray') plt.show() cv2.imshow("",imgGray) cv2.waitKey(0) cv2.destroyAllWindows() sys.exit() plt.show() result cv2.imshow() result I th...
This is the behavior of matplotlib. It finds the minimum and maximum of your picture, makes those black and white, and scales everything in between. This is useful for arbitrary data that may have integer or floating point types, and value ranges between 0.0 and 1.0, or 0 .. 255, or anything else. You can set those lim...
4
7
69,145,633
2021-9-11
https://stackoverflow.com/questions/69145633/how-to-initialize-a-database-connection-only-once-and-reuse-it-in-run-time-in-py
I am currently working on a huge project, which constantly executes queries. My problem is, that my old code always created a new database connection and cursor, which decreased the speed immensivly. So I thought it's time to make a new database class, which looks like this at the moment: class Database(object): _insta...
Explanation The keyword here is clearly class variables. Taking a look in the official documentation, we can see that class variables, other than instance variables, are shared by all class instances regardless of how many class instances exists. Generally speaking, instance variables are for data unique to each insta...
9
18
69,142,306
2021-9-11
https://stackoverflow.com/questions/69142306/auto-format-flake8-linting-errors-in-vscode
I'm using the flake8 linter for Python and I have many code formats issues like blank line contains whitespace flake8(W293) I'm trying to auto fix these linting issues. I have these settings: "python.linting.enabled": true, "python.linting.flake8Enabled": true, "python.linting.lintOnSave": true, "python.linting.flake8...
I would suggest using a formatter, black for instance, to fix the issues detected by your linter. If so, pip install it and add this to your settings.json: "python.formatting.provider": "black" Then, pressing Alt+ShifT+F or Ctrl+S should trigger the formatting of your script.
14
12
69,159,247
2021-9-13
https://stackoverflow.com/questions/69159247/camera-calibration-focal-length-value-seems-too-large
I tried a camera calibration with python and opencv to find the camera matrix. I used the following code from this link https://automaticaddison.com/how-to-perform-camera-calibration-using-opencv/ import cv2 # Import the OpenCV library to enable computer vision import numpy as np # Import the NumPy scientific computing...
Your misconception is about "focal length". It's an overloaded term. "focal length" (unit mm) in the optical part: it describes the distance between the lens plane and image/sensor plane, assuming a focus to infinity "focal length" (unit pixels) in the camera matrix: it describes a scale factor for mapping the real wo...
4
17
69,117,617
2021-9-9
https://stackoverflow.com/questions/69117617/how-to-find-the-lag-between-two-time-series-using-cross-correlation
Say the two series are: x = [4,4,4,4,6,8,10,8,6,4,4,4,4,4,4,4,4,4,4,4,4,4,4] y = [4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,6,8,10,8,6,4,4] Series x clearly lags y by 12 time periods. However, using the following code as suggested in Python cross correlation: import numpy as np c = np.correlate(x, y, "full") lag = np.argmax(c) ...
If you want to do it the easy way you should simply use scipy correlation_lags Also, remember to subtract the mean from the inputs. import numpy as np from scipy import signal x = [4,4,4,4,6,8,10,8,6,4,4,4,4,4,4,4,4,4,4,4,4,4,4] y = [4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,6,8,10,8,6,4,4] correlation = signal.correlate(x-np.me...
7
9
69,181,347
2021-9-14
https://stackoverflow.com/questions/69181347/stable-baselines3-log-rewards
How can I add the rewards to tensorboard logging in Stable Baselines3 using a custom environment? I have this learning code model = PPO( "MlpPolicy", env, learning_rate=1e-4, policy_kwargs=policy_kwargs, verbose=1, tensorboard_log="./tensorboard/")
You can access the local variables available to the logger callback using self.locals. Any variables exposed in your custom environment will be accessible via locals dict. The example below shows how to access a key in a custom dictionary called my_custom_info_dict in vectorized environments. import numpy as np from st...
9
9
69,143,423
2021-9-11
https://stackoverflow.com/questions/69143423/is-there-a-way-to-write-two-in-statements-in-one
Is there a short version of n = [5, 3, 17] if 5 in n and 17 in n: print("YES") something like that doesn't seem to work if (5 and 17) in n: print("YES") Any suggestions?
You could use something like this instead: n = [5,3,7] if all(item in n for item in [5,7]): print("YES")
4
3
69,149,494
2021-9-12
https://stackoverflow.com/questions/69149494/how-to-build-an-aab-using-buildozer-via-docker
I have just seen that support for AAB files have just been introduced in Python for Android (p4a). Considering that, fom August 2021, new apps are required to publish with the Android App Bundle on Google Play, this is a crucial addition for any Python dev working on Android apps. Since I'm currently using Buildozer vi...
The community has finally completed the AAB support for Buildozer. Although it is still a pending pull request, it is already possible to create the AAB, and I have figured out how to do it using Docker. I have found two very interesting gists that helped me a lot (this one about creating an AAB with Buildozer on Ubunt...
5
2
69,170,874
2021-9-14
https://stackoverflow.com/questions/69170874/how-to-plot-a-regression-line-on-a-timeseries-line-plot
I have a question about the value of the slope in degrees which I have calculated below: import pandas as pd import yfinance as yf import matplotlib.pyplot as plt import datetime as dt import numpy as np df = yf.download('aapl', '2015-01-01', '2021-01-01') df.rename(columns = {'Adj Close' : 'Adj_close'}, inplace= True)...
The implementation in the OP is not the correct way to determine, or plot a linear model. As such, the question about determining the angle to plot the line is bypassed, and a more rigorous approach to plotting the regression line is shown. A regression line can be added by converting the datetime dates to ordinal. Th...
4
9
69,100,275
2021-9-8
https://stackoverflow.com/questions/69100275/error-while-downloading-the-requirements-using-pip-install-setup-command-use-2
version pip 21.2.4 python 3.6 The command: pip install -r requirements.txt The content of my requirements.txt: mongoengine==0.19.1 numpy==1.16.2 pylint pandas==1.1.5 fawkes The command is failing with this error ERROR: Command errored out with exit status 1: command: /Users/*/Desktop/ml/*/venv/bin/python -c 'import i...
It looks like setuptools>=58 breaks support for use_2to3: setuptools changelog for v58 So you should update setuptools to setuptools<58 or avoid using packages with use_2to3 in the setup parameters. I was having the same problem, pip==19.3.1
108
205
69,097,732
2021-9-8
https://stackoverflow.com/questions/69097732/what-is-the-meaning-of-in-python-grammar
I was going through the python grammer specification and find the following statement for_stmt: | 'for' star_targets 'in' ~ star_expressions ':' [TYPE_COMMENT] block [else_block] What does ~ means in this grammar rule?. The other symbols used in the grammer(like &, !, |) are already documented but not ~. The notatio...
It's documented in PEP 617 under Grammar Expressions: ~ Commit to the current alternative, even if it fails to parse. rule_name: '(' ~ some_rule ')' | some_alt In this example, if a left parenthesis is parsed, then the other alternative won’t be considered, even if some_rule or ‘)’ fail to be parsed. The ~ basically ...
7
9
69,176,092
2021-9-14
https://stackoverflow.com/questions/69176092/how-to-change-font-size-of-jupyter-notebook-in-vs-code
I am using jupyter notebook to create python notes(sort of) for a virtual lecture. I like to use vscode instead of jupyter lab. But unfortunately the font size of the markdown output is too small(to see on participants' screen on virtual call). While using jupyter lab, i used to zoom the whole browser. But i can't do t...
A new setting is being added to vscode: notebook.markup.fontSize Should be in the Insiders Build v1.63 soon. See https://github.com/microsoft/vscode/issues/126294#issuecomment-964601412
5
18
69,131,840
2021-9-10
https://stackoverflow.com/questions/69131840/how-to-invoke-a-cloud-function-from-google-cloud-composer
For a requirement I want to call/invoke a cloud function from inside a cloud composer pipeline but I cant find much info on it, I tried using SimpleHTTP airflow operator but I get this error: [2021-09-10 10:35:46,649] {taskinstance.py:1503} ERROR - Task failed with exception Traceback (most recent call last): File "/op...
I faced the same issue as you, but I managed to figure it out by studying the Airflow 2.0 provider packages for Google and using a PythonOperator instead. from airflow.providers.google.common.utils import id_token_credentials as id_token_credential_utils import google.auth.transport.requests from google.auth.transport....
6
7
69,109,980
2021-9-8
https://stackoverflow.com/questions/69109980/unclear-why-groupby-with-single-group-produces-row-dataframe
Here's two groupby operations on a pandas.DataFrame: import pandas d = pandas.DataFrame({"a": [1, 2, 3, 4, 5, 6], "b": [1, 2, 4, 3, -1, 5]}) grp1 = pandas.Series([1, 1, 1, 1, 1, 1]) ans1 = d.groupby(grp1).apply(lambda x: x.a * x.b.iloc[0]) grp2 = pandas.Series([1, 1, 1, 2, 2, 2]) ans2 = d.groupby(grp2).apply(lambda x: ...
A simple solution is to return a DataFrame from apply: import pandas d = pandas.DataFrame({"a": [1, 2, 3, 4, 5, 6], "b": [1, 2, 4, 3, -1, 5]}) grp1 = pandas.Series([1, 1, 1, 1, 1, 1]) ans1 = d.groupby(grp1).apply(lambda x: x[['a']] * x.b.iloc[0]) grp2 = pandas.Series([1, 1, 1, 2, 2, 2]) ans2 = d.groupby(grp2).apply(lam...
9
2