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
72,282,253
2022-5-18
https://stackoverflow.com/questions/72282253/using-conda-activate-or-specifying-python-path-in-bash-script
I'm running some python scripts on some Linux clusters using SGE or SLURM. I already have my conda environment set up properly using the login node. I have been writing something like source ~/.bashrc module purge #Kill all active modules conda init bash conda deactivate conda deactivate conda activate my_env python my...
Programmatic execution with an environment is usually better done through the conda run subcommand. E.g., my_slurm_script.sh #!/bin/bash -l conda run -n my_env python my_script.py Read the conda run --help for details.
4
5
72,214,347
2022-5-12
https://stackoverflow.com/questions/72214347/how-to-document-default-none-null-in-openapi-swagger-using-fastapi
Using a ORM, I want to do a POST request letting some fields with a null value, which will be translated in the database for the default value specified there. The problem is that OpenAPI (Swagger) docs, ignores the default None and still prompts a UUID by default. from fastapi import FastAPI from pydantic import BaseM...
When you declare Optional parameters, users shouldn't include those parameters in the request specified with null or None (in Python), in order to be None. By default, the value of such parameters will be None, unless the user specifies some other value when sending the request. Hence, all you have to do is to declare ...
5
11
72,245,243
2022-5-15
https://stackoverflow.com/questions/72245243/polars-how-to-add-a-column-with-numerical
In pandas, we can just assign directly: import pandas as pd df = pd.DataFrame({"a": [1, 2]}) # add a single value df["b"] = 3 # add an existing Series df["c"] = pd.Series([4, 5]) a b c 0 1 3 4 1 2 3 5 Notice that the new numerical Series is not in the original df, it is a result of some computation. How do we do the...
Let's start with this DataFrame: import polars as pl df = pl.DataFrame( { "col1": [1, 2, 3, 4, 5], } ) shape: (5, 1) ┌──────┐ │ col1 │ │ --- │ │ i64 │ ╞══════╡ │ 1 │ │ 2 │ │ 3 │ │ 4 │ │ 5 │ └──────┘ To add a scalar (single value) Use polars.lit. my_scalar = -1 df.with_columns(pl.lit(my_scalar).alias("col_scalar")) s...
14
23
72,275,772
2022-5-17
https://stackoverflow.com/questions/72275772/what-is-a-valid-binding-name-for-azure-function
When I try to run the azure function defined below, I get the following error log The 'my_function' function is in error: The binding name my_function_timer is invalid. Please assign a valid name to the binding. What is the format of a valid binding name for Azure Function ? Function definition I have two files in my_...
I couldn't find anything in the documentation either, but looking at the source code of azure-functions-host(which contains code for the runtime host used by the Azure Functions service), it uses following regex to validate the binding name. ^([a-zA-Z][a-zA-Z0-9]{0,127}|\$return)$ This means that, for a valid binding ...
16
25
72,232,875
2022-5-13
https://stackoverflow.com/questions/72232875/python-should-i-save-pypi-packages-offline-as-a-backup
My Python projects heavily depends on PyPi packages. I want to make sure that: in any time in the future: the packages required by my apps will always be available online on PyPi. For example:- I found a project on Github that requires PyQt4. when I tried to run it on my Linux machine, it crashed on startup because it ...
Short version: YES, if you want availability... The next big question is how best to keep a backup version of the dependencies? There are some suggestions at the end of this answer. Long version: Your question touches on the concept of "Availability" which is one of the three pillars of Information Assurance (or Inform...
8
5
72,274,613
2022-5-17
https://stackoverflow.com/questions/72274613/how-to-type-overload-functions-with-multiple-optional-args
I have a function with multiple kwargs with defaults. One of them (in the middle somewhere) is a boolean toggle that controls the return type. I would like to create two overloads for this method with Literal[True/False] but keeping the default value. My idea was the following: from typing import overload, Literal @ove...
It is an old problem. The reason is that you specify default value in both branches, so x() is possible in both and return type is undefined. I have the following pattern for such cases: from typing import overload, Literal @overload def x(a: int = ..., t: Literal[True] = True, b: int = ...) -> int: ... @overload def x...
9
16
72,214,043
2022-5-12
https://stackoverflow.com/questions/72214043/how-to-debug-python-2-7-code-with-vs-code
For work I have to use Python 2.7. But when I use the "debug my python file" function in VS Code, I get an error. Even with a simple program, like : print()
As rioV8 said in a comment, you have to install a previous version of the Python extension, because in the meanwhile support for Python 2 has been dropped. To install a previous version you have to: Open the Extensions pane from the bar on the left and find Python Click on the gear icon and select "Install another ver...
9
31
72,212,413
2022-5-12
https://stackoverflow.com/questions/72212413/how-to-replace-a-number-in-a-string-in-python
I need to search a string and check if it contains numbers in its name. If it does, I want to replace it with nothing. I've started doing something like this but I didn't find a solution for my problem. table = "table1" if any(chr.isdigit() for chr in table) == True: table = table.replace(chr, "_") print(table) # The o...
You could do this in many different ways. Here's how it could be done with the re module: import re table = 'table1' table = re.sub(r'\d+', '', table)
5
8
72,270,548
2022-5-17
https://stackoverflow.com/questions/72270548/how-to-ignore-pylance-type-checking-on-notebooks
I have a python project in which I have python files and notebooks. I use strict typing in my project but I would like to remove it only on notebooks. I use VScode with setting: "python.analysis.typeCheckingMode": "strict" I know how to ignore type on a python file: But it seems it does not work on notebooks: I get ...
That is a Pylance error. You can create a pyrightconfig.json file at the root of your workspace and define the files to be exclude-d from analysis or completely ignore-d: { "ignore": [ "**/*.ipynb", ], } You can even list up specific filenames: { "ignore": [ "notimportant.ipynb", "test.ipynb", ], } Historical Notes:...
7
8
72,239,693
2022-5-14
https://stackoverflow.com/questions/72239693/why-get-pip-install-error-when-run-docker-build-on-only-m1-mac
I'm using Intel and Apple Silicon chip Mac. When I build dockerfile on Intel Mac, it is success. How ever when I build same file on M1 Mac I get This error. #10 3.254 ERROR: Could not find a version that satisfies the requirement google-python-cloud-debugger (from versions: none) #10 3.255 ERROR: No matching distribut...
I solved this problem! When we build dockerfile on M1 Mac, we need specify platform. So you need to add --platform=linux/x86_64 after FROM on dockerfile. Example FROM --platform=linux/x86_64 python:3.9-buster or you can also add the option when you build. docker build . --platform=linux/x86_64 -t my_tag If linux/x86_...
5
10
72,278,311
2022-5-17
https://stackoverflow.com/questions/72278311/performancewarning-dropping-on-a-non-lexsorted-multi-index-without-a-level-para
I have the following line of code end_df['Soma Internet'] = end_df.iloc[:,end_df.columns.get_level_values(1) == 'Internet'].drop('site',axis=1).sum(axis=1) It basically, filts my multi index df by a specific level 1 column. Drops a few not wanted columns. And does the sum, of all the other ones. I took a glance, at a...
Let's try with an example (without data for simplicity): import pandas as pd # Column MultiIndex. idx = pd.MultiIndex(levels=[['Col1', 'Col2', 'Col3'], ['subcol1', 'subcol2']], codes=[[2, 1, 0], [0, 1, 1]]) df = pd.DataFrame(columns=range(len(idx))) df.columns = idx print(df) Col3 Col2 Col1 subcol1 subcol2 subcol2 C...
7
9
72,255,562
2022-5-16
https://stackoverflow.com/questions/72255562/cannot-import-name-dtensor-from-tensorflow-compat-v2-experimental
I am having problems trying to run TensorFlow on my Windows 10 machine. Code runs fine on my MacOS machine. Traceback (most recent call last): File "c:\Users\Fynn\Documents\GitHub\AlpacaTradingBot\ai.py", line 15, in <module> from keras.models import Sequential, load_model File "C:\Users\Fynn\AppData\Local\Programs\Pyt...
I tried many solutions to no avail, in the end this worked for me! pip3 uninstall tensorflow absl-py astunparse flatbuffers gast google-pasta grpcio h5py keras keras-preprocessing libclang numpy opt-einsum protobuf setuptools six tensorboard tensorflow-io-gcs-filesystem termcolor tf-estimator-nightly typing-extensions ...
21
0
72,217,828
2022-5-12
https://stackoverflow.com/questions/72217828/fastapi-how-to-get-raw-url-path-from-request
I have a GET method with requested parameter in path: @router.get('/users/{user_id}') async def get_user_from_string(user_id: str): return User(user_id) Is it possible to get base url raw path (i.e., '/users/{user_id}') from the request? I have tried to use the following way: path = [route for route in request.scope['...
You can use the APIRout object property in the request to get the actual path example: raw_path = request.scope['route'].path #'/user/{id}'
6
-2
72,199,354
2022-5-11
https://stackoverflow.com/questions/72199354/python-type-hinting-for-a-generic-mutable-tuple-fixed-length-sequence-with-mul
I am currently working on adding type hints to a project and can't figure out how to get this right. I have a list of lists, with the nested list containing two elements of type int and float. The first element of the nested list is always an int and the second is always a float. my_list = [[1000, 5.5], [1432, 2.2], [1...
I think the question highlights a fundamental difference between statically typed Python and dynamically typed Python. For someone who is used to dynamically typed Python (or Perl or JavaScript or any number of other scripting languages), it's perfectly normal to have diverse data types in a list. It's convenient, flex...
8
5
72,202,728
2022-5-11
https://stackoverflow.com/questions/72202728/conda-to-poetry-environment
I have a conda environment that I would like to convert to a poetry environment. What I have tried is to translate the environment.yaml of the conda environment into a pyproject.toml file that poetry can read. Here you have the steps: Generate the yaml file conda env export --from-history > environment.yaml The --from...
No, there is not a better way. Conda is a generic package manager and does not discern Python versus non-Python packages, therefore this has to be done with manual curation. Additionally, package names might also differ. For example py-opencv(conda-forge) vs opencv-python (PyPi). Tips In addition to pulling down the --...
11
5
72,243,852
2022-5-14
https://stackoverflow.com/questions/72243852/pyinstaller-cant-find-a-module-error-loading-python-dll
I compiled my program with pyinstaller, and it works fine on my computer, but whenever I ty to run it in another computer (with no python), I get the following error: Error loading Python DLL 'C:\Users\perez\AppData\Local\Temp\_MEI28162\python310.dll'. LoadLibrary: Cannot find specified module What can I do? I'm not a...
Ok, it was not working because I compiled the script with pyinstaller having python 3.10, but Windows 7's maximum python version is 3.8
4
2
72,224,866
2022-5-13
https://stackoverflow.com/questions/72224866/how-to-get-time-taken-for-each-layer-in-pytorch
I want to know the inference time of a layer in Alexnet. This code measures the inference time of the first fully connected layer of Alexnet as the batch size changes. And I have a few questions about this. Is it possible to measure the inference time accurately with the following code? Is there a time difference beca...
I found a way to measure inference time by studying the AMP document. Using this, the GPU and CPU are synchronized and the inference time can be measured accurately. import torch, time, gc # Timing utilities start_time = None def start_timer(): global start_time gc.collect() torch.cuda.empty_cache() torch.cuda.reset_ma...
6
0
72,233,773
2022-5-13
https://stackoverflow.com/questions/72233773/import-in-jupyter-notebook-to-use-a-method-from-another-file
I am using jupyter notebook. I have 3 jupyter source files written in python in a folder in the same directory: parser, preprocess, and temp. I am trying to import parser and import preprocess in the temp file so that I can use the methods written in those files. Example: there is method named extract in parser file. I...
The easiest way is to change the files you need to import as py files. As an example, parser.ipynb can be converted to a python file parser.py, and you can import it from another notebook file. If you want to use a function named extract() from parser.py, just import from parser import extract
5
2
72,279,755
2022-5-17
https://stackoverflow.com/questions/72279755/python-gstreamer-bindings-with-pygobject-only-has-core-modules-no-plugins
I have gstreamer installed on OSX 12.0.1 Monterey. I just installed the python bindings inside of a virtual environment running python 3.9 with: pip3 install pycairo PyGObject I can import gi and gi.repository.Gst without an issue. However it seems that almost all gstreamer plugins are missing. This is my test script: ...
I found the registry paths used from python are different to those used by the gst command line tools. You can check this as follows. Run gst-inspect-1.0 playbin and check the path in the "Filename" line - this was /usr/local/lib/gstreamer-1.0/ on the Mac I used. But this didn't match the path from Python. Run this sni...
5
2
72,202,295
2022-5-11
https://stackoverflow.com/questions/72202295/how-to-apply-max-length-to-truncate-the-token-sequence-from-the-left-in-a-huggin
In the HuggingFace tokenizer, applying the max_length argument specifies the length of the tokenized text. I believe it truncates the sequence to max_length-2 (if truncation=True) by cutting the excess tokens from the right. For the purposes of utterance classification, I need to cut the excess tokens from the left, i....
Tokenizers have a truncation_side parameter that should set exactly this. See the docs.
5
6
72,244,046
2022-5-14
https://stackoverflow.com/questions/72244046/use-or-for-compatibilty-across-systems
My goal is a simple and proper way to export my venv. In the optimal case, the resulting requirements.txt works on all compatible systems. At the moment I use pip freeze > requirements.txt. This uses the == "Version matching clause". On an other system the file might not work due to conflicting versions, although it wa...
Your question is not simple to answer and touches on some nuances in the social dynamics around versioning. Easy stuff first: sometimes versions use a terminal suffix to indicate something like prerelease builds, and if you're dependent on a prerelease build or some other situation where you expect the terminal suffix ...
10
13
72,251,787
2022-5-15
https://stackoverflow.com/questions/72251787/permission-artifactregistry-repositories-downloadartifacts-denied-on-resource
While the artifact repository was successfully creating, running a docker push to push the image to the google artifact registry fails with a permissions error even after granting all artifact permissions to the accounting I am using on gcloud cli. Command used to push image: docker push us-central1-docker.pkg.dev/proj...
I was able to recreate your use case. This happens when you are trying to push an image on a repository in which its specific hostname (associated with it's repository location) is not yet added to the credential helper configuration for authentication. You may refer to this Setting up authentication for Docker as als...
27
58
72,225,191
2022-5-13
https://stackoverflow.com/questions/72225191/how-can-i-apply-gettext-translations-to-string-literals-in-case-statements
I need to add gettext translation to all the string literals in our code, but it doesn't work with literals in case statements. This failed attempt gives SyntaxError: Expected ':': from gettext import gettext as _ direction = input(_('Enter a direction: ')) # <-- This works match direction: case _('north'): # <-- This ...
What does the error mean? The grammar for the match/case statement treats the _ as a wildcard pattern. The only acceptable token that can follow is a colon. Since your code uses an open parenthesis, a SyntaxError is raised. How to fix it Switch from a literal pattern such as case "north": ... to a value pattern such as...
18
18
72,204,649
2022-5-11
https://stackoverflow.com/questions/72204649/single-file-history-format-library-for-binary-files
My application is going to edit a bunch of large files, completely unrelated to each other (belonging to different users), and I need to store checkpoints of the previous state of the files. Delta compression should work extremely well on this file format. I only need a linear history, not branches or merges. There are...
From RCS manual (1. Overview) [RCS] can handle text as well as binary files, although functionality is reduced for the latter. RCS seems a good option worth to try. I work for a Foundation which has been using RCS to keep under version control tens of thousands of completely unrelated files (git or hg are not an opti...
6
4
72,249,268
2022-5-15
https://stackoverflow.com/questions/72249268/pandas-drop-rows-lower-then-others-in-all-colums
I have a dataframe with a lot of rows with numerical columns, such as: A B C D 12 7 1 0 7 1 2 0 1 1 1 1 2 2 0 0 I need to reduce the size of the dataframe by removing those rows that has another row with all values bigger. In the previous example i need to remove the last row because the first row has...
An more memory-efficient and faster solution than the one proposed so far is to use Numba. There is no need to create huge temporary array with Numba. Moreover, it is easy to write a parallel implementation that makes use of all CPU cores. Here is the implementation: import numba as nb @nb.njit def is_dominated(arr, k)...
8
7
72,199,498
2022-5-11
https://stackoverflow.com/questions/72199498/error-in-importing-cats-vs-dogs-dataset-in-google-colab
While trying to download the "Cats_vs_Dogs" TensorFlow dataset using the tfds module, I get the following error 👇 DownloadError Traceback (most recent call last) <ipython-input-2-244305a07c33> in <module>() 7 split=['train[:80%]', 'train[80%:90%]', 'train[90%:]'], 8 with_info=True, ----> 9 as_supervised=True, 10 ) 21 ...
You can add this before loading to set the new URL : setattr(tfds.image_classification.cats_vs_dogs, '_URL',"https://download.microsoft.com/download/3/E/1/3E1C3F21-ECDB-4869-8368-6DEBA77B919F/kagglecatsanddogs_5340.zip")
8
12
72,249,616
2022-5-15
https://stackoverflow.com/questions/72249616/module-dlt-has-no-attribute-table-databricks-and-delta-live-tables
I am new to databricks and delta live tables. I have problem with creating delta live table in python. How to create delta live table from json files in filestore?
It is a decorator, so I think you also need a function after. Meaning @dlt.table(comment="your comment") def get_bronze(): df=spark.sql("""select * from myDb.MyRegisterdTable""") #If you wanna check logs: #print("bronze",df.take(5),"end") return df In silver function then you can read it as: @dlt.table def get_silver(...
7
3
72,236,497
2022-5-14
https://stackoverflow.com/questions/72236497/how-to-deal-with-pythons-requirements-txt-while-using-a-docker-development-envi
Suppose I wrote a docker-compose.dev.yml file to set the development environment of a Flask project (web application) using Docker. In docker-compose.dev.yml I have set up two services, one for the database and one to run the Flask application in debug mode (which allows me to do hot changes without having to recreate/...
For something like this I use multi-layer docker images. Disclaimer: The below examples are not tested. Please consider it as a mere description written in pseudo code ;) As a very simple example, this approach could look like this: # Make sure all layers are based on the same python version. FROM python:3.10-slim-bust...
5
6
72,230,151
2022-5-13
https://stackoverflow.com/questions/72230151/how-to-open-a-secure-channel-in-python-grpc-client-without-a-client-ssl-certific
I have a grpc server (in Go) that has a valid TLS certificate and does not require client side TLS. For some reason I can not implement the client without mTLS in Python, even though I can do so in Golang. In Python I have os.environ["GRPC_VERBOSITY"] = "DEBUG" # os.environ["GRPC_DEFAULT_SSL_ROOTS_FILE_PATH"] = "/etc/s...
https://grpc.github.io/grpc/python/_modules/grpc.html#secure_channel has the docs for channel = grpc.secure_channel(ORBIUM_ADDR, grpc.ssl_channel_credentials()). This function relies on the class channel, see docs https://grpc.github.io/grpc/python/_modules/grpc/aio/_channel.html. Basically, class Channel wraps C code ...
8
4
72,200,552
2022-5-11
https://stackoverflow.com/questions/72200552/fastapi-firebase-authentication-with-jwts
I'm trying to use fastapi to return some basic ML models to users. Currently, I secure user details with firebase auth. I want to use the JWT's users have when using the basic application to authenticate their request for the ML model. With fastapi, there doesn't seem to be a straightforward answer to doing this. I've ...
I hope this will help: Create functions to work with Firebase admin, create credentials from Firebase as JSON file: from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials from fastapi import Depends, HTTPException, status, Response from firebase_admin import auth, credentials, initialize_app credential...
6
13
72,277,284
2022-5-17
https://stackoverflow.com/questions/72277284/retrieve-pytest-results-programmatically-when-run-via-pytest-main
I'd like to run pytest and then store results and present them to users on demand (e.g. store pytest results to a db and then expose them through web service). I could run pytest from the command line with an option to save the results report into file, then find and parse the file, but it feels silly to have the resul...
Write a small plugin that collects and stores reports for each test. Example: import time import pytest class ResultsCollector: def __init__(self): self.reports = [] self.collected = 0 self.exitcode = 0 self.passed = 0 self.failed = 0 self.xfailed = 0 self.skipped = 0 self.total_duration = 0 @pytest.hookimpl(hookwrappe...
10
9
72,277,275
2022-5-17
https://stackoverflow.com/questions/72277275/how-to-monitor-per-process-network-usage-in-python
I'm looking to troubleshoot my internet issue so I need a way to track both my latency and which application is using how much network bandwidth. I've already sorted out checking latency, but now I need a way to monitor each process' network usage (KB/s), like how it appears in Windows Task Manager. Before you suggest ...
Following the third section of this guide provided me with all of the information listed in the post, minus latency. Given that you said you already had measuring latency figured out, I assume this isn't an issue. Logging this to csv/json/whatever is pretty easy, as all of the information is stored in panda data frames...
7
4
72,250,629
2022-5-15
https://stackoverflow.com/questions/72250629/draw-text-with-background-color
I want to know how can I draw text like this check image As you can see text is on a green image and text has pink color background My code, this is part of my code I'm using PIL draw = ImageDraw.Draw(background) font = ImageFont.truetype("assets/font2.ttf", 40) font2 = ImageFont.truetype("assets/font2.ttf", 70) aria...
You can use the draw.textbbox method to get a bounding box for your text string and fill it using the draw.rectangle method. from PIL import Image, ImageDraw, ImageFont image = Image.new("RGB", (500, 100), "white") font = ImageFont.truetype("segoeui.ttf", 40) draw = ImageDraw.Draw(image) position = (10, 10) text = "Hel...
8
20
72,215,976
2022-5-12
https://stackoverflow.com/questions/72215976/pypdf2-errors-pdfreaderror-pdf-starts-with-but-pdf-expected
I have a folder containing a lot of sub-folders, with PDF files inside. It's a real mess to find information in these files, so I'm making a program to parse these folders and files, searching for a keyword in the PDF files, and returning the names of the PDF files containing the keyword. And it's working. Almost, actu...
disclaimer: I am the author of borb, the library mentioned in this answer PDF documents caught in the wild will sometimes start with non-pdf bytes (a header that is not really part of the PDF spec). This can cause all kinds of problems. PDF will (internally) keep track of all the byte offsets of objects in the file (e....
5
6
72,262,763
2022-5-16
https://stackoverflow.com/questions/72262763/detect-whether-package-is-being-run-as-a-program-within-init-py
I have a Python package with an __init__.py that imports some things to be exposed as the package API. # __init__.py from .mymodule import MyClass # ... I also want to be able to use the package as a command-line application, as in python -m mypackage, so I have a __main__.py file for that purpose: # __main__.py if __...
It might make sense to add a separate entry point for running your code as a script, rather than using __main__.py, which as you've noticed, can only be run after the package's __init__.py is fully loaded. A simple script like run_mypackage.py located at the top level could contain the environment variable tweaking cod...
5
1
72,280,762
2022-5-17
https://stackoverflow.com/questions/72280762/pip-broke-after-downlading-python-certifi-win32
I have downloaded python for the first time in a new computer(ver 3.10.4). I have download the package python-certifi-win32, after someone suggested it as a solution to a SSL certificate problem in a similar question to a problem I had. Since then, pip has completely stopped working, to the point where i can't not run ...
I found the answer in another question - PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: after installing python-certifi-win32 basically, you should remove two files that initialize python-certifi-win32 when running pip. the files are located in the directo...
9
12
72,221,091
2022-5-12
https://stackoverflow.com/questions/72221091/im-trying-to-type-annotate-around-boto3-but-module-botocore-client-has-no-at
I'm writing my own wrapper around boto3 for quick firing functions. I'm trying to type annotate what boto3.session().client('ec2') returns. Debugger says it's <class 'botocore.client.EC2'>, but if I write it down like that, python crashes with a runtime error ec2: botocore.client.EC2 AttributeError: module 'botocore.cl...
Try mypy-boto3 mypy plugin. You can install it via python -m pip install 'boto3-stubs[ec2]' import boto3 from mypy_boto3_ec2 import EC2Client def foo(ec2_client: EC2Client) -> None: ... ec2_client = boto3.client("ec2") foo(ec2_client) # OK
6
7
72,280,858
2022-5-17
https://stackoverflow.com/questions/72280858/rotate-axis-labels
I have a plot that looks like this (this is the famous Wine dataset): As you can see, the x-axis labels overlap and thus I need to be rotated. NB! I am not interested in rotating the x-ticks (as explained here), but the label text, i.e. alcohol, malic_acid, etc. The logic of creating the plot is the following: I creat...
Based on the documentation set_xlabel accepts text arguments, of which rotation is one. The example I used to test this is shown below, though . import matplotlib.pyplot as plt import numpy as np plt.plot() plt.gca().set_xlabel('Test', rotation='vertical')
4
5
72,280,047
2022-5-17
https://stackoverflow.com/questions/72280047/how-can-i-override-a-special-method-defined-in-a-metaclass-with-a-custom-classme
As an example, consider the following: class FooMeta(type): def __len__(cls): return 9000 class GoodBar(metaclass=FooMeta): def __len__(self): return 9001 class BadBar(metaclass=FooMeta): @classmethod def __len__(cls): return 9002 len(GoodBar) -> 9000 len(GoodBar()) -> 9001 GoodBar.__len__() -> TypeError (missing 1 req...
The __len__ defined in the class will always be ignored when using len(...) for the class itself: when executing its operators, and methods like "hash", "iter", "len" can be roughly said to have "operator status", Python always retrieve the corresponding method from the class of the target, by directly acessing the mem...
6
1
72,280,007
2022-5-17
https://stackoverflow.com/questions/72280007/pandas-convert-columns-of-lists-into-a-single-list
I have a dataframe of lists that looks similar to the one below (fig a). There is a single key column followed by n columns containing lists. My goal is that for each row, I will combine the lists from each column (excluding the key) into a single list in the new column, combined. An example of my desired result is bel...
You can use a nested list comprehension: dataSet['combined'] = [[e for l in x for e in l] for _,x in dataSet.filter(like='value').iterrows()] Output: key valueA valueB valueN combined 0 1_1 [1, 2, 3, 4, 5, 6] [1, 2, 3, 4, 5, 6] [1, 2, 3, 4, 5, 6] [1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6] 1 1_2 [7, 8, 9, ...
6
2
72,269,651
2022-5-17
https://stackoverflow.com/questions/72269651/numpy-way-of-splitting-array-when-cumaltive-sum-x
Data Lets take the following 2d array: starts = [0, 4, 10, 13, 23, 27] ends = [4, 10, 13, 23, 27, 32] lengths = [4, 6, 3, 10, 4, 5] arr = np.array([starts, ends, lengths]).T Thus looking like: [[ 0 4 4] [ 4 10 6] [10 13 3] [13 23 10] [23 27 4] [27 32 5]] Goal Now I want to "loop" through the lengths and as soon as s...
Numpy is not designed for solving efficiently such a problem. You can still solve this using some tricks or the usual combination of cumsum + division + diff + where or similar ones (like @Kevin proposed), but AFAIK they are all inefficient. Indeed, they require many temporary arrays and expensive operations. Temporary...
6
1
72,266,207
2022-5-16
https://stackoverflow.com/questions/72266207/django-filter-error-meta-fields-must-not-contain-non-model-field-names
I am working with Django REST framework and django-filters and and I'd like to use the reverse relationship annotation_set as one of filters for a GET API that uses the model Detection. The models are the following: class Detection(models.Model): image = models.ImageField(upload_to="detections/images") def local_image_...
Apparently I had to explicitly state the name of the reverse relationship: class Annotation(models.Model): detection = models.ForeignKey(Detection, on_delete=models.CASCADE, related_name='annotation_set') attribute = models.CharField(max_length=255) If anybody knows why, I'd love to know it! Thanks!
5
2
72,238,460
2022-5-14
https://stackoverflow.com/questions/72238460/python-importerror-sys-meta-path-is-none-python-is-likely-shutting-down
When using __del__ datetime.date.today() throws ImportError: sys.meta_path is None, Python is likely shutting down import datetime import time import sys class Bug(object): def __init__(self): print_meta_path() def __del__(self): print_meta_path() try_date('time') try_date('datetime') def print_meta_path(): print(f'met...
Using atexit provide the same behavior as __del__ but works import datetime import time import sys import atexit class Bug(object): def __init__(self): print_meta_path() atexit.register(self.__close) def __close(self): print_meta_path() try_date('time') try_date('datetime') def print_meta_path(): print(f'meta_path: {sy...
8
4
72,206,141
2022-5-11
https://stackoverflow.com/questions/72206141/mypy-item-none-of-optionalcustomattrsmodel-has-no-attribute-country
When I run mypy checkings I am getting an error. I am no able to ignore it or turn it off the strict optional checking. It there a way to solve this. Here is the line that is throwing the error: if tree.data.attributes.custom != JAPAN: where attributes is declared as: class TreeAttributesModel(BaseModel): id: Optiona...
I had to tweak your snippets a bit to get a MWE, but here we go: import enum import dataclasses from datetime import datetime from typing import Optional, Union class StatusEnum(enum.Enum): OK = enum.auto() NOK = enum.auto() class CountryEnum(enum.Enum): JAPAN = enum.auto() RAPTURE = enum.auto() @dataclasses.dataclass ...
8
11
72,274,073
2022-5-17
https://stackoverflow.com/questions/72274073/python-count-files-in-a-directory-and-all-its-subdirectories
I am trying to count all the files in a folder and all its subfolders For exemple, if my folder looks like this: file1.txt subfolder1/ ├── file2.txt ├── subfolder2/ │ ├── file3.txt │ ├── file4.txt │ └── subfolder3/ │ └── file5.txt └── file6.txt file7.txt I would like get the number 7. The first thing I tried is a recu...
IIUC, you can just do sum(len(files) for _, _, files in os.walk('path/to/folder')) or perhaps, to avoid the len for probably slightly better performance: sum(1 for _, _, files in os.walk('folder_test') for f in files)
5
3
72,260,211
2022-5-16
https://stackoverflow.com/questions/72260211/importerror-cannot-import-name-document-from-borb-pdf-document
I have installed the 'borb' library using pip install borb and after installation, I got the following message: Requirement already satisfied: borb in c:\users\dell\appdata\local\programs\python\python37\lib\site-packages (2.0.25) WARNING: You are using pip version 22.0.3; however, version 22.0.4 is available. You shou...
Please import Document Class from borb.pdf usage: from borb.pdf import Document
4
10
72,258,087
2022-5-16
https://stackoverflow.com/questions/72258087/unexpected-keyword-argument-tenant-id-while-accessing-azure-key-vault-in-pytho
I was trying to accessing my key vault, but I got always the same error: AppServiceCredential.get_token failed: request() got an unexpected keyword argument 'tenant_id' ManagedIdentityCredential.get_token failed: request() got an unexpected keyword argument 'tenant_id' This was the code I used in an Azure Machine Lear...
This error is because of a bug that has since been fixed in azure-identity's ManagedIdentityCredential. Key Vault clients in recent packages include a tenant ID in token requests to support cross-tenant authentication, but some azure-identity credentials didn't correctly handle this keyword argument until the bug was f...
5
9
72,260,808
2022-5-16
https://stackoverflow.com/questions/72260808/mismatch-between-statsmodels-and-sklearn-ridge-regression
I'm exploring ridge regression. While comparing statsmodels and sklearn, I found that the two libraries result in different output for ridge regression. Below is an simple example of the difference import numpy as np import pandas as pd import statsmodels.api as sm from sklearn.linear_model import Lasso, Ridge np.rando...
After digging around a little more, I discovered the answer as to why they differ. The difference is that sklearn's Ridge scales the penalty term as alpha / n where n is the number of observations. statsmodels does not apply this scaling of the tuning parameter. You can have the ridge implementations match if you re-sc...
5
6
72,239,086
2022-5-14
https://stackoverflow.com/questions/72239086/pytorch-gather-failed-with-sparse-grad-true
With even very simple example, backward() cannot work if sparse_grad=True, please see the error below. Is this error expected, or I'm using gather in a wrong way? In [1]: import torch as th In [2]: x = th.rand((3,3), requires_grad=True) # sparse_grad = False, the backward could work as expetecd In [3]: th.gather(x @ x,...
I think torch.gather does not support sparse operators: torch.gather(x, 1, torch.LongTensor([[0], [1]]).to_sparse()) Results with: NotImplementedError: Could not run 'aten::gather.out' with arguments from the 'SparseCPU' backend. I think you should open an issue or a feature request on pytorch's github.
5
2
72,232,152
2022-5-13
https://stackoverflow.com/questions/72232152/visual-studio-code-freezes-after-short-while-the-window-is-not-responding
Problem: I can open VS code and start typing but after ~30s (sometimes minutes) the window freezes showing this message: I am using python on a jupyter notebook with only a couple of unspectacular lines which I don't show because I tried different content. Last time it crashed after about 2 min of just import pandas a...
This is caused by the latest Pylance extension. You can revert to earlier Pylance extension to solve the problem. This problem will be fixed in a new version in a few days according to the github.
7
2
72,244,540
2022-5-14
https://stackoverflow.com/questions/72244540/why-win32com-doesnt-show-me-all-emails
I want to parse emails in python through the Outlook application. Running this code I get only a few of my emails. import win32com.client outlook = win32com.client.Dispatch('outlook.application') mapi = outlook.GetNamespace("MAPI") inbox= mapi.GetDefaultFolder(6) messages= inbox.Items for i in messages: message=i.subje...
Emails were not visible beacuse they were on the server! File-> Account Settings-> Account Settings...-> double click on your Exchange account-> set the Mail to keep offline slider to: All. Found it here !
4
3
72,248,577
2022-5-15
https://stackoverflow.com/questions/72248577/find-the-minimum-number-of-steps-to-half-the-sum-of-elements-in-a-list-where-eac
I came across an interview question that went like this: There are factories in an area which produce a pollutive gas and filters are to be installed at each factory to reduce the pollution. Each filter installed would half the pollution in that factory. Each factory can have multiple filters. There is a list of N int...
Maybe you could utilize a max heap to retrieve the worst factory more efficiently than you are right now, i.e., using a heap would allow for an O(N log N) solution: import heapq def filters_required(factories: list[int]) -> int: """Returns minimum filters required to halve pollution.""" current_pollution = sum(factorie...
6
4
72,245,490
2022-5-15
https://stackoverflow.com/questions/72245490/while-loop-not-working-function-and-time-sleep
My while loop prints nothing when it is running. import os import time place = 10 running = True def Write(): j = 1 for i in range(place - 1): print("-", end = "") j += 1 print("a", end = "") for k in range(10 - j): print("-", end = "") while running: Write() time.sleep(5) if place > 1: place -= 1 os.system("clear") W...
I got puzzled by what you discovered, and now found a solution to this interesting behavior; you can use flush=True parameter to force flushing: import os import time place = 10 running = True def Write(): j = 1 for i in range(place - 1): print("-", end = "") j += 1 print("a", end = "", flush=True) for k in range(10 - ...
4
5
72,243,349
2022-5-14
https://stackoverflow.com/questions/72243349/problems-with-pip-und-command-line
I am trying to create a Python pip package. This works also well. I can successfully upload and download the package and use it in the Python code. What I can't do is to use the Python package via the command line. In another StackOverflow post I found the link to a tutorial. I tried to follow it. Obviously I made a mi...
In your setup.py file you have this line... entry_points={'console_scripts': ['hello-world=riffecs:hello_world',]}, This is the entry point to calling you package via command line. This configuration is asking the entry point to be hello-world, which I tried and it runs fine. In your image however you run riffecx whic...
6
1
72,240,674
2022-5-14
https://stackoverflow.com/questions/72240674/how-do-i-use-pyscript-in-my-html-code-and-return-output
I am trying to call my python function created. But not getting any output and no resource how to achieve. Code : <!DOCTYPE html> <html> <head> <link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" /> <script defer src="https://pyscript.net/alpha/pyscript.js"></script> </head> <body> <p>Click on the "Ch...
When writing Python in the browser, you must rethink how actions are performed. Typically, Python programs are procedural. Browser-based applications are asynchronous. The first step is to enable asynchronous features: import asyncio Browser based programs cannot directly access the local file system. Your code is not...
6
5
72,235,819
2022-5-13
https://stackoverflow.com/questions/72235819/how-can-i-redirect-module-imports-with-modern-python
I am maintaining a python package in which I did some restructuring. Now, I want to support clients who still do from my_package.old_subpackage.foo import Foo instead of the new from my_package.new_subpackage.foo import Foo, without explicitly reintroducing many files that do the forwarding. (old_subpackage still exist...
On import of your package's __init__.py, you can place whatever objects you want into sys.modules, the values you put in there will be returned by import statements: from . import new_package from .new_package import module1, module2 import sys sys.modules["my_lib.old_package"] = new_package sys.modules["my_lib.old_pac...
8
9
72,243,698
2022-5-14
https://stackoverflow.com/questions/72243698/python-3-10-type-hinting-causes-syntax-error
I have defined two classes. A Bookshelf class and a Book class and have defined each with its own methods and type hints. When I run the below code in VS Code using python 3.10 it comes up with the following error: class Bookshelf: SyntaxError: Invalid syntax Which is referring to the init of the BookShelf class below...
It is not a SyntaxError, It is a NameError because Book class is not defined yet when you are using it in your type hints. 1. First solution is moving the definition of Book class before the BookShelf. 2. Second solution is use the string instead of the book itself: def __init__(self, books: list["Book"]): I think in ...
4
3
72,240,803
2022-5-14
https://stackoverflow.com/questions/72240803/shap-not-working-with-lightgbm-categorical-features
My model uses LGBMClassifier. I'd like to use Shap (Shapley) to interpret features. However, Shap gave me errors on categorical features. For example, I have a feature "Smoker" and its values include "Yes" and "No". I got an error from Shap: ValueError: could not convert string to float: 'Yes'. Am I missing any settin...
Let's try slightly different: from lightgbm import LGBMClassifier import shap X_train = pd.DataFrame({ "Age": [50, 20, 60, 30], "Smoker": ["Yes", "No", "No", "Yes"]} ) X_train["Smoker"] = X_train["Smoker"].astype("category") y_train = [1, 0, 0, 0] X_test = pd.DataFrame({"Age": [50], "Smoker": ["Yes"]}) X_test["Smoker"]...
7
3
72,236,445
2022-5-14
https://stackoverflow.com/questions/72236445/how-can-i-wrap-a-python-function-in-a-way-that-works-with-with-inspect-signature
Some uncontroversial background experimentation up front: import inspect def func(foo, bar): pass print(inspect.signature(func)) # Prints "(foo, bar)" like you'd expect def decorator(fn): def _wrapper(baz, *args, *kwargs): fn(*args, **kwargs) return _wrapper wrapped = decorator(func) print(inspect.signature(wrapped)) #...
You can use __signature__ (PEP) attribute to modify returned signature of wrapped object. For example: import inspect def func(foo, bar): pass def decorator(fn): def _wrapper(baz, *args, **kwargs): fn(*args, **kwargs) f = inspect.getfullargspec(fn) fn_params = [] if f.args: for a in f.args: fn_params.append( inspect.Pa...
7
3
72,203,899
2022-5-11
https://stackoverflow.com/questions/72203899/how-can-i-see-the-service-account-that-the-python-bigquery-client-uses
To create a default bigquery client I use: from google.cloud import bigquery client = bigquery.Client() This uses the (default) credentials available in the environment. But how I see then which (default) service account is used?
While you can interrogate the credentials directly (be it json keys, metadata server, etc), I have occasionally found it valuable to simply query bigquery using the SESSION_USER() function. Something quick like this should suffice: client = bigquery.Client() query_job = client.query("SELECT SESSION_USER() as whoami") r...
4
3
72,239,193
2022-5-14
https://stackoverflow.com/questions/72239193/how-to-trigger-aws-lambda-functions-manually-which-is-already-scheduled-using-ev
I am using event bridge to trigger a lambda function at 8 everyday to perform some ETL operations. At times i receive requests to trigger the lambda manually ondemand. How can i achieve that using the same lambda function.
There are many ways to run the Lambda on demand like running it in the AWS Console, connecting it to an API Gateway and triggering it from the API Gateway etc. But the easiest way is to use Lambda URLs It will give you an URL that you can envoke that will run the Lambda.
5
6
72,238,384
2022-5-14
https://stackoverflow.com/questions/72238384/how-to-plot-pairs-in-different-subplots-with-difference-on-the-side
I want to make a plot in seaborn but I am having some difficulties. The data has 2 variable: time (2 levels) and state (2 levels). I want to plot time on the x axis and state as different subplots, showing individual data lines. Finally, to the right of these I want to show a difference plot of the difference between t...
The problem is that sns.relplot operates at a figure level. This means it creates its own figure object and we cannot control the axes it uses. If you want to leverage seaborn for the creation of the lines without using "pure" matplotlib, you can copy the lines on matplotlib axes: import numpy as np import pandas as pd...
6
2
72,238,058
2022-5-14
https://stackoverflow.com/questions/72238058/can-not-import-nvidia-smi
I'm tending to collect my GPU status during my python code is running. I need to import nvidia_smi in my code to do this. but even by installing it by pip install nvidia_smi hit this error: No module named 'nvidia_smi' Any Idea?
I found the answer here just pip install nvidia-ml-py3: and: import nvidia_smi nvidia_smi.nvmlInit() handle = nvidia_smi.nvmlDeviceGetHandleByIndex(0)
5
11
72,230,915
2022-5-13
https://stackoverflow.com/questions/72230915/django-how-to-get-url-by-its-name
I want to get url by name specified in urls.py. Like {% url 'some_name' %} in template, but in Python. My urls.py: urlpatterns = [ ... path('admin_section/transactions/', AdminTransactionsView.as_view(), name='admin_transactions'), ... ] I want to something like: Input: url('admin_transactions') Output: '/admin_sectio...
Django has the reverse() utility function for this. Example from the docs: given the following url: from news import views path('archive/', views.archive, name='news-archive') you can use the following to reverse the URL: from django.urls import reverse reverse('news-archive') The documentation goes further into func...
8
14
72,230,363
2022-5-13
https://stackoverflow.com/questions/72230363/how-to-format-very-small-numbers-in-python
How to format 1.3435434533e-8 into 1.34e-8 in python? Keep only two digits. The round() method will round this number to zero.
The "g" formatting suffix on string mini-format language, used both by f-strings, and the .format method will do that: In [1]: a = 1.34434325435e-8 In [2]: a Out[2]: 1.34434325435e-08 In [4]: f"{a:.03g}" Out[4]: '1.34e-08' # in contrast with: In [5]: f"{a:.03f}" Out[5]: '0.000'
5
10
72,228,607
2022-5-13
https://stackoverflow.com/questions/72228607/pycaret-time-series-tsforecastingexperiment-importerror-cannot-import-name-ch
I am getting the below error, while importing Pycaret time-series(beta) module in the databricks (we were running successfully earlier). Request your help in solving the issues. pycaret version in use: import pycaret pycaret.__version__ # Out[1]: '3.0.0' python version in use: import sys sys.version #Out[9]: '3.8.10 (...
This is due to the use of a private method from sklearn in the sktime dependency. Since sklearn updated to 1.1.0, this private method was removed/moved, hence it is breaking. The sktime team is working on fixing this. In the meantime, you can fix this by force installing sklearn 1.0.2. Please see the details in the Git...
5
7
72,223,046
2022-5-12
https://stackoverflow.com/questions/72223046/how-to-apply-a-list-of-functions-sequentially-to-a-string-using-python-reduce-or
Problem Statement I would like to apply a list of functions fs = [ f, g, h ] sequentially to a string text=' abCdEf ' Something like f( g( h( text) ) ). This could easily be accomplished with the following code: # initial text text = ' abCDef ' # list of functions to apply sequentially fs = [str.rstrip, str.lstrip, str...
reduce can take three arguments: reduce(function, iterable, initializer) What are these three arguments in general? function is a function of two arguments. Let's call these two arguments t and f. the first argument, t, will start as initializer; then will continue as the return value of the previous call of function...
6
8
72,225,655
2022-5-13
https://stackoverflow.com/questions/72225655/extracting-multiple-sets-of-rows-columns-from-a-2d-numpy-array
I have a 2D numpy array from which I want to extract multiple sets of rows/ columns. # img is 2D array img = np.arange(25).reshape(5,5) array([[ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19], [20, 21, 22, 23, 24]]) I know the syntax to extract one set of row/ column. The following will e...
IIUC, you can use numpy.r_ to generate the indices from the slice: img[np.r_[0,2:4][:,None],2] output: array([[ 2], [12], [17]]) intermediates: np.r_[0,2:4] # array([0, 2, 3]) np.r_[0,2:4][:,None] # variant: np.c_[np.r_[0,2:4]] # array([[0], # [2], # [3]])
4
4
72,222,059
2022-5-12
https://stackoverflow.com/questions/72222059/difference-between-cupy-asnumpy-and-get
Given a CuPy array a, there are two ways to get a numpy array from it: a.get() and cupy.asnumpy(a). Is there any practical difference between them? import cupy as cp a = cp.random.randint(10, size=(4,5,6,7)) b = a.get() c = cp.asnumpy(a) assert type(b) == type(c) and (b == c).all()
cp.asnumpy is a wrapper calling ndarray.get. You can see that in the code of cp.asnumpy: def asnumpy(a, stream=None, order='C', out=None): """Returns an array on the host memory from an arbitrary source array. Args: a: Arbitrary object that can be converted to :class:`numpy.ndarray`. stream (cupy.cuda.Stream): CUDA str...
6
3
72,200,654
2022-5-11
https://stackoverflow.com/questions/72200654/how-to-get-client-secret-in-keycloak-with-admin-user-in-different-realm-using-py
I have this workflow in place which works. I get a token from keycloak with admin username/password to this endpoint auth/realms/master/protocol/openid-connect/token With this token I request about client-secret of a specific client which is connected to another realms, not master. So, I request to this endpoint provid...
Maybe I am wrong, but I would expect that the following would work: keycloak_admin = KeycloakAdmin(server_url=serv_url, username='user', password='pass', realm_name='{realm_name}', user_realm_name='master', verify=True) Get the client client_id = keycloak_admin.get_client_id("{client_name}") Get the Secret: secret = ...
4
3
72,206,932
2022-5-11
https://stackoverflow.com/questions/72206932/why-do-any-and-all-not-appear-to-use-short-circuit-evaluation-here
Does all() return False right after finding a False in a sequence? Try to run this code: def return_true(): print('I have just been printed') return True print(all((False, return_true()))) As you can see, I have just been printed is printed even though there is False before it. Another example: def return_false(): pri...
Yes, all() and any() both short circuit the way you describe. all() will return early if any item is false-y, and any() will if any item is truthy. The reason you're seeing the printouts is because return_true() and return_false() are being called before all and any are even invoked. They must be. A function's argument...
5
8
72,206,172
2022-5-11
https://stackoverflow.com/questions/72206172/what-is-the-time-complexity-of-numpy-linalg-det
The documentation for numpy.linalg.det states that The determinant is computed via LU factorization using the LAPACK routine z/dgetrf. I ran the following run time tests and fit polynomials of degrees 2, 3, and 4 because that covers the least worst options in this table. That table also mentions that an LU decomposit...
TL;DR: it is between O(n^2.81) and O(n^3) regarding the target BLAS implementation. Indeed, Numpy uses a LU decomposition (in the log space). The actual implementation can be found here. It indeed uses the sgetrf/dgetrf primitive of LAPACK. Multiple libraries provides such a libraries. The most famous is the one of Net...
6
3
72,205,522
2022-5-11
https://stackoverflow.com/questions/72205522/glibcxx-3-4-29-not-found
I am trying to install mujuco onto my linux laptop and everything works until I try to import it into a python file. When I try to import it/run a python script that already has mujuco in it I get the following errors: Import error. Trying to rebuild mujoco_py. running build_ext building 'mujoco_py.cymj' extension gcc ...
Where does /home/daniel/miniconda3/envs/mujoco_py/lib/libstdc++.so.6 come from? Something bundles a version of libstdc++.so.6 which is older than your system version, and other system libraries depend on the newer version. You should be able to fix this issue by just deleting the file in your home directory.
4
11
72,195,236
2022-5-11
https://stackoverflow.com/questions/72195236/link-github-repo-with-package-on-pypi
I uploaded a python package on Pypi, but I'd also like to upload it to Github, so it can be opensource and anyone can contribute. Is is possible to link the github repo with the already uploaded package on Pypi, so whenever I push something to the master branch, it also updates on Pypi?
In your Github repository there is a tab called Actions (next to Pull requests) where there are several actions like "Publish Python Package". Selecting it will automatically add the relevant Code to your repository. You then only need to store your credentials, like username & password. You can do so under Settings >...
5
7
72,133,316
2022-5-5
https://stackoverflow.com/questions/72133316/libssl-so-1-1-cannot-open-shared-object-file-no-such-file-or-directory
I've just updated to Ubuntu 22.04 LTS and my libs using OpenSSL just stopped working. Looks like Ubuntu switched to the version 3.0 of OpenSSL. For example, poetry stopped working: Traceback (most recent call last): File "/home/robz/.local/bin/poetry", line 5, in <module> from poetry.console import main File "/home/rob...
This fixes it (a problem with packaging in 22.04): wget http://nz2.archive.ubuntu.com/ubuntu/pool/main/o/openssl/libssl1.1_1.1.1f-1ubuntu2.23_amd64.deb sudo dpkg -i libssl1.1_1.1.1f-1ubuntu2.23_amd64.deb PS: If the link is expired, check http://nz2.archive.ubuntu.com/ubuntu/pool/main/o/openssl/?C=M;O=D for a valid one...
136
287
72,157,487
2022-5-8
https://stackoverflow.com/questions/72157487/group-by-result-is-inconsistent-in-polars
Based on the example from the Aggregation section of the User Guide import polars as pl from datetime import date def compute_age() -> pl.Expr: return date(2021, 1, 1).year - pl.col("birthday").dt.year() def avg_birthday(gender: str) -> pl.Expr: return compute_age().filter( pl.col("gender") == gender ).mean().alias(f"a...
Use maintain_order=True on group_by. maintain_order: Ensure that the order of the groups is consistent with the input data. This is slower than a default group by. Setting this to True blocks the possibility to run on the streaming engine.
4
4
72,181,600
2022-5-10
https://stackoverflow.com/questions/72181600/is-it-possible-to-run-game-made-with-pygame-on-browser-using-pyscript
I have made a small space invader game using pygame and I was wondering if I could play it on the browser using pyscript. Is this even possible ? Do I have to rewrite everything ?
No, Pygame is not supported in PyScript at this time. I'm not sure what is the best way to find out what packages are supported, but I have managed to piece together the following: PyScript uses Pyodide to load packages, so only packages supported by Pyodide will be loadable in PyScript. That means either packages bui...
7
8
72,163,312
2022-5-8
https://stackoverflow.com/questions/72163312/python-run-shell-command-get-stdout-and-stderr-as-a-variable-but-hide-from-u
I would like to have my Python script run a Linux shell command and store the output in a variable, without the command's output being shown to the user. I have tried this with os.system, subprocess.check_output, subprocess.run, subprocess.Popen, and os.popen with no luck. My current method is running os.system("ls -l ...
You can use the subprocess.run function. One update as @Ashley Kleynhans say "The results of stdout and stderr are bytes objects so you will need to decode them if you want to handle them as strings" For this, you do not need to decode stdout or stderr because in the run method you can pass one more argument to get ...
7
10
72,170,947
2022-5-9
https://stackoverflow.com/questions/72170947/how-to-use-ordinalencoder-to-set-custom-order
I have a column in my Used cars price prediction dataset named "Owner_Type". It has four unique values which are ['First', 'Second', 'Third', 'Fourth']. Now the order that makes the most sense is First > Second > Third > Fourth as the price decreases with respect to this order. How can I give this order to the values w...
OrdinalEncoder has a categories parameter which accepts a list of arrays of categories. Here is a code example: from sklearn.preprocessing import OrdinalEncoder enc = OrdinalEncoder(categories=[['first','second','third','forth']]) X = [['third'], ['second'], ['first']] enc.fit(X) print(enc.transform([['second'], ['firs...
5
14
72,167,802
2022-5-9
https://stackoverflow.com/questions/72167802/adding-version-attribute-to-python-module
I am building a Python module with a structure like: mypackage/ mypackage/ __init__.py etc.py setup.py setup.cfg pyproject.toml To build it, I am running $ python -m build. I noticed that version numbers weren't available (e.g. mypackage.__version__ is undefined after installing), and currently I am just setting it ma...
Do you really need/want a __version__ attribute at all? Keeping a __version__ attribute available in the module namespace is a popular convention, but it's possibly falling out of fashion these days because stdlib importlib.metadata is no longer provisional. The one obvious place for a version string is in the package ...
11
17
72,157,296
2022-5-8
https://stackoverflow.com/questions/72157296/what-is-the-difference-between-type-hinting-a-variable-as-an-iterable-versus-a-s
I don't understand the difference when hinting Iterable and Sequence. What is the main difference between those two and when to use which? I think set is an Iterable but not Sequence, are there any built-in data type that is Sequence but not Iterable? def foo(baz: Sequence[float]): ... # What is the difference? def bar...
The Sequence and Iterable abstract base classes (can also be used as type annotations) mostly* follow Python's definition of sequence and iterable. To be specific: Iterable is any object that defines __iter__ or __getitem__. Sequence is any object that defines __getitem__ and __len__. By definition, any sequence is an...
92
88
72,191,674
2022-5-10
https://stackoverflow.com/questions/72191674/modx-in-event-state-in-tkinter
I've been figuring out how to parse tkinter events via event.state to reduce the number of times that I have to call root.bind() (e.g., I can avoid binding both "<ButtonPress-1>" and "<Shift-ButtonPress-1>" by finding if shift was pressed via event.state). Of course, I've relied heavily on the tkinter source code (spec...
ModX represents a modification, a Modifier Key. In computing, a modifier key is a special key (or combination) on a computer keyboard that temporarily modifies the normal action of another key when pressed together. By themselves, modifier keys usually do nothing; that is, pressing any of the ⇧ Shift, Alt, or Ctrl key...
5
5
72,162,359
2022-5-8
https://stackoverflow.com/questions/72162359/skip-django-allauth-you-are-about-to-sign-in-using-a-third-party-account-from
How can I skip the page and automatically logged in users, when they clicked on Login in With Google.
You need to set up SOCIALACCOUNT_LOGIN_ON_GET=True in your configuration (by default it's False). according to https://django-allauth.readthedocs.io/en/latest/configuration.html: SOCIALACCOUNT_LOGIN_ON_GET (=False) Controls whether or not the endpoints for initiating a social login (for example, “/accounts/google/logi...
11
22
72,119,683
2022-5-4
https://stackoverflow.com/questions/72119683/import-modules-to-pyscript
When we are coding python code, we typically use packages and modules that we import. For example, when we are coding we may write: import numpy import requests from bs4 import BeautifulSoup When we are trying to integrate python with html with Pyscript (https://pyscript.net/), it just says that it doesn’t have the pa...
At this time, bs4 is not supported. You will receive an error ValueError: Couldn't find a pure Python 3 wheel for 'bs4' You will also have problems using the requests package in pyscript. Usepyfetch instead of requests.get. To import numpy and requests, use <py-env> before <py-script>. Example: <body> <py-env> - nump...
7
14
72,122,939
2022-5-5
https://stackoverflow.com/questions/72122939/resourceexhaustederror-graph-execution-error-when-trying-to-train-tensorflow
A few days back, I got the same error at 12th epoch. This time, it happens at the 1st. I have no idea why that is happening as I did not make any changes to the model. I only normalized the input to give X_train.max() as 1 after scaling like it should be. Does it have something to do with patch size? Should I reduce it...
I had the same error as you ,it's a resource exhausted problem, resolved by just reducing batch_size value(I had a Model which try to learn from dataset of big images I reduce it's value from 32 to 16) .and it's worked fine
4
11
72,193,393
2022-5-10
https://stackoverflow.com/questions/72193393/find-the-value-of-variables-to-maximize-return-of-function-in-python
I'd want to achieve similar result as how the Solver-function in Excel is working. I've been reading of Scipy optimization and been trying to build a function which outputs what I would like to find the maximal value of. The equation is based on four different variables which, see my code below: import pandas as pd imp...
Solution I will use optuna library to give you a solution to the type of problem you are trying to solve. I have tried using scipy.optimize.minimize and it appears that the loss-landscape is probably quite flat in most places, and hence the tolerances enforce the minimizing algorithm (L-BFGS-B) to stop prematurely. Op...
7
3
72,169,984
2022-5-9
https://stackoverflow.com/questions/72169984/how-do-i-find-the-repetition-size-in-a-scanned-texture
Given the scan of a fabric (snippet included here, it could easily be A4 size at 600 dpi) what would be the best method for finding the repetition pattern in the scan? I have tried: splitting the image in 4 quarters and trying to find points via SIFT and OpenCV FFT as suggested here I am aware of other answers on sta...
The image's 2D autocorrelation is a good generic way to find repeating structures, as others have commented. There are some details to doing this effectively: For this analysis, it is often fine to just convert the image to grayscale; that's what the code snippet below does. To extend this to a color-aware analysis, y...
4
2
72,142,248
2022-5-6
https://stackoverflow.com/questions/72142248/inserting-rows-into-microsoft-sql-server-using-pandas-raises-precision-error
I am trying to insert data into a mssql database. I needed as fast method for this so I set the fast_executemany param to true. The upload works fine for most part but if one of the column is a datetime with timezone it crashes raising: (pyodbc.Error) ('HY104', '[HY104] [Microsoft][ODBC Driver 17 for SQL Server]Invalid...
This issue can be reproduced using SQLAlchemy 1.4.0. It was fixed in SQLAlchemy 1.4.1.
7
0
72,166,259
2022-5-9
https://stackoverflow.com/questions/72166259/werkzeug-server-is-shutting-down-in-django-application
after updating the Werkzeug version from 2.0.3 to 2.1.0, I keep getting errors every time I run the server, and here is the error log: Exception happened during processing of request from ('127.0.0.1', 44612) Traceback (most recent call last): File "/usr/lib/python3.8/socketserver.py", line 683, in process_request_thre...
Literally just ran into this today. According to their (git repo issue 1715) and assuming you are running runserver_plus, there are three options that worked for some users. The first worked for me: Not altering your files and adding the option --keep-meta-shutdown. My full command looks like python manage.py runserve...
15
25
72,191,842
2022-5-10
https://stackoverflow.com/questions/72191842/python-attrs-inheriting-from-class-which-values-have-default-values-raises-erro
I have a situation where attrs class inherits from another class which attributes have default value. This raises ValueError. Here's an example: from attrs import define @define class A: a: int = 1 @define class B(A): b: int test = B(b=1) >>> ValueError: No mandatory attributes allowed after an attribute with a default...
You're running into a limitation of Python. The __init__ you're asking attrs to write for you looks like this: def __init__(self, b=1, a): self.b = b self.a = a which can't exist. You can work around that by either declaring class B or attribute b keyword-only: from attrs import define, field @define class A: a: int =...
5
8
72,191,298
2022-5-10
https://stackoverflow.com/questions/72191298/what-is-the-pythonic-way-of-iterating-over-a-single-item
I come across this issue often, and I would be surprised if there wasn't some very simple and pythonic one-liner solution to it. Suppose I have a method or a function that takes a list or some other iterable object as an argument. I want for an operation to be performed once for each item in the object. Sometimes, only...
The short answer is nope, there is no simple built-in. And yep, if you want str (or bytes or bytes-like stuff or whatever) to act as a scalar value, it gets uglier. Python expects callers to adhere to the interface contract; if you say you accept sequences, say so, and it's on the caller to wrap any individual argument...
5
3
72,187,949
2022-5-10
https://stackoverflow.com/questions/72187949/extracting-start-and-end-indices-of-a-token-using-spacy
I am looking at lots of sentences and looking to extract the start and end indices of a word in a given sentence. For example, the input is as follows: "This is a sentence written in English by a native English speaker." And What I want is the span of the word 'English' which in this case is : (30,37) and (50, 57). Not...
You can do this with re in pure python: s="This is a sentence written in english by a native English speaker." import re [(i.start(), i.end()) for i in re.finditer('ENGLISH', s.upper())] #output [(30, 37), (50, 57)] You can do in spacy as well: import spacy nlp=spacy.load("en_core_web_sm") doc=nlp("This is a sentence ...
5
1
72,176,662
2022-5-9
https://stackoverflow.com/questions/72176662/problem-authorizing-client-with-django-oauth-toolkit-authorization-code-flow
I have been following the django-oAuth-toolkit documentation. In the Authorization Code step, I have registered an application as shown in the screenshot. But then the next step is given like this: To start the Authorization code flow go to this URL which is the same as shown below: http://127.0.0.1:8000/o/authorize/...
After debugging for so many hours I came to this, please include it in your settings.py file and it works. Maybe it is a bug since we defined our app as confidential with authorization_code grant type but oauth_provider is thinking it as public and trying to validate for pkce. OAUTH2_PROVIDER = { "PKCE_REQUIRED": False...
7
13
72,180,701
2022-5-10
https://stackoverflow.com/questions/72180701/one-of-many-recursive-calls-of-a-function-found-the-correct-result-but-it-cant
Recently, I was experimenting with writing a function to find a primitive value anywhere within an arbitrarily deeply nested sequence, and return the path taken to get there (as a list of indices inside each successive nested sequence, in order). I encountered a very unexpected obstacle: the function was finding the re...
Your first attempt is almost perfect, the only mistake is that you return the result of searching through the first list/tuple at the current depth, regardless of whether the item was found or not. Instead, you need to check for a positive result, and only return if it is one. That way you keep iterating through the cu...
4
4
72,179,103
2022-5-9
https://stackoverflow.com/questions/72179103/xarray-select-the-data-at-specific-x-and-y-coordinates
When selecting data with xarray at x,y locations, I get data for any pair of x,y. I would like to have a 1-D array not a 2-D array from the selection. Is there an efficient way to do this? (For now I am doing it with a for-loop...) x = [x1,x2,x3,x4] y = [y1,y2,y3,y4] DS = 2-D array subset = Dataset.sel(longitude=x, lat...
A list of points can be selected along multiple indices if the indexers are DataArrays with a common dimension. This will result in the array being reindexed along the indexers' common dimension. Straight from the docs on More Advanced Indexing: In [78]: da = xr.DataArray(np.arange(56).reshape((7, 8)), dims=['x', 'y'])...
6
12
72,175,135
2022-5-9
https://stackoverflow.com/questions/72175135/mypy-how-to-mark-line-as-unreachable
I've got a function of the form: def get_new_file(prefix: str) -> pathlib.Path: for i in itertools.count(0): p = pathlib.Path(f'{prefix}_{i}') if not p.is_file(): return p # This line is unreachable. mypy understandably complains that the function is missing a return statement. Is there a way to mark a line so as to i...
This was raised as an issue. The recommended solution is assert False. def get_new_file(prefix: str) -> pathlib.Path: for i in itertools.count(0): p = pathlib.Path(f'{prefix}_{i}') if not p.is_file(): return p assert False
9
9
72,148,941
2022-5-7
https://stackoverflow.com/questions/72148941/how-to-tag-and-store-files-by-metadata-in-python
I want to build a manual file tagging system like this. Given that a folder contains these files: data/ budget.xls world_building_budget.txt a.txt b.exe hello_world.dat world_builder.spec I want to write a tagging system where executing py -3 tag_tool.py -filter=world -tag="World-Building Tool" will output These files...
First, I am not clear if this is actually homework, but my first recommendation is always to see if it's already done (and it seems to be): https://pypi.org/project/pytaggit/ If I were to ignore that and build it myself, I would consider what a tagging systems structure is. Long story (skip ahead if not interested): co...
4
2
72,161,257
2022-5-8
https://stackoverflow.com/questions/72161257/exclude-default-fields-from-python-dataclass-repr
Summary I have a dataclass with 10+ fields. print()ing them buries interesting context in a wall of defaults - let's make them friendlier by not needlessly repeating those. Dataclasses in Python Python's @dataclasses.dataclass() (PEP 557) provides automatic printable representations (__repr__()). Assume this example, b...
You could do it like this: import dataclasses from dataclasses import dataclass from operator import attrgetter @dataclass(repr=False) class InventoryItem: name: str unit_price: float = 1.00 quantity_on_hand: int = 0 def __repr__(self): nodef_f_vals = ( (f.name, attrgetter(f.name)(self)) for f in dataclasses.fields(sel...
8
8
72,140,681
2022-5-6
https://stackoverflow.com/questions/72140681/matplotlib-set-up-font-computer-modern-and-bold
I would like to have a plot where the font are in "computer modern" (i.e. Latex style) but with x-ticks and y-ticks in bold. Due to the recent upgrade of matplotlib my previous procedure does not work anymore. This is my old procedure: plt.rc('font', family='serif',size=24) matplotlib.rc('text', usetex=True) matplotlib...
You still can use your old procedure, but with a slight change. The MatplotlibDeprecationWarning that you get states that the parameter expects a str value but it's getting something else. In this case what is happening is that you are passing it as a list. Removing the brackets will do the trick: import matplotlib imp...
4
3
72,166,020
2022-5-9
https://stackoverflow.com/questions/72166020/how-to-install-multiple-packages-in-one-line-using-conda
I need to install below multiple packages using conda. I am not sure what is conda-forge? some uses conda-forge, some doesn't use it. Is it possible to install them in one line without installing them one by one? Thanks conda install -c conda-forge dash-daq conda install -c conda-forge dash-core-components conda instal...
Why some packages have to be installed through conda forge: Conda official repository only feature a few verified packages. A vast portion of python packages that are otherwise available through pip are installed through community led channel called conda-forge. You can visit their site to learn more about it. How to i...
16
17