question_id
int64
59.5M
79.7M
creation_date
stringdate
2020-01-01 00:00:00
2025-07-15 00:00:00
link
stringlengths
60
163
question
stringlengths
53
28.9k
accepted_answer
stringlengths
26
29.3k
question_vote
int64
1
410
answer_vote
int64
-9
482
73,037,764
2022-7-19
https://stackoverflow.com/questions/73037764/check-if-string-is-none-empty-or-has-spaces-only
What's the Pythonic way of checking whether a string is None, empty or has only whitespace (tabs, spaces, etc)? Right now I'm using the following bool check: s is None or not s.strip() ..but was wondering if there's a more elegant / Pythonic way to perform the same check. It may seem easy but the following are the dif...
The only difference I can see is doing: not s or not s.strip() This has a little benefit over your original way that not s will short-circuit for both None and an empty string. Then not s.strip() will finish off for only spaces. Your s is None will only short-circuit for None obviously and then not s.strip() will chec...
8
12
73,035,540
2022-7-19
https://stackoverflow.com/questions/73035540/pandas-how-to-expand-a-dataframe-between-dates-and-add-nans-to-new-rows
This is a simple one but it is stumping me. I have a data frame consisting of day-level observations by individuals. However, not all individuals are observed on the same day. I need to create rows including the days in which individuals are not observed (i.e., count NaN or 0), between the dates where they are present....
Create DatetimeIndex by column date first, so possible use custom lambda function with DataFrame.asfreq, remove first level of MultiIndex and convert index to column date, last use Series.dt.strftime for original format DD/MM/YYYY: First is possible test duplicated rows by columns ID, date: print (df[df.duplicated(['ID...
3
2
73,035,677
2022-7-19
https://stackoverflow.com/questions/73035677/new-column-based-on-values-from-other-columns-and-respecting-pre-established-ru
I'm looking for an algorithm to create a new column based on values ​​from other columns AND respecting pre-established rules. Here's an example: artificial data df = data.frame( col_1 = c('No','Yes','Yes','Yes','Yes','Yes','No','No','No','Unknown'), col_2 = c('Yes','Yes','Unknown','Yes','Unknown','No','Unknown','No','...
A solution using Python: import pandas as pd df = pd.DataFrame({ 'col_1': ['No','Yes','Yes','Yes','Yes','Yes','No','No','No','Unknown'], 'col_2': ['Yes','Yes','Unknown','Yes','Unknown','No','Unknown','No','Unknown','Unknown'], 'col_3': ['Unknown','Yes','Yes','Unknown','Unknown','No','No','Unknown','Unknown','Unknown'] ...
4
1
73,033,594
2022-7-19
https://stackoverflow.com/questions/73033594/github-action-using-wrong-version-of-python
I have the following Github action, in which I'm specifying Python 3.10: name: Unit Tests runs-on: ubuntu-latest defaults: run: shell: bash working-directory: app steps: - uses: actions/checkout@v3 - name: Install poetry run: pipx install poetry - uses: actions/setup-python@v3 with: python-version: "3.10" cache: "poetr...
The root cause is the section - uses: actions/setup-python@v3 with: python-version: "3.10" cache: "poetry" with the line caching poetry. Since poetry was previously installed with a pip associated with Python 3.8, the package will be retrieved from the cache associated with that Python version. It needs to be re-insta...
4
5
72,979,303
2022-7-14
https://stackoverflow.com/questions/72979303/why-is-pytorch-inference-non-deterministic-even-when-setting-model-eval
I have fine-tuned a PyTorch transformer model using HuggingFace, and I'm trying to do inference on a GPU. However, even after setting model.eval() I still get slightly different outputs if I run inference multiple times on the same data. I have tried a number of things and have done some ablation analysis and found out...
You can use torch.use_deterministic_algorithms to force non-deterministic modules to perform deterministically, where supported e.g: >>> a = torch.randn(100, 100, 100, device='cuda').to_sparse() >>> b = torch.randn(100, 100, 100, device='cuda') # Sparse-dense CUDA bmm is usually nondeterministic >>> torch.bmm(a, b).eq(...
5
4
73,024,608
2022-7-18
https://stackoverflow.com/questions/73024608/merge-multiple-batchencoding-or-create-tensorflow-dataset-from-list-of-batchenco
In a token labelling task I am using a transformers tokenizer, which outputs objects of the BatchEncoding class. I am tokenizing each text separately because I need to extract the labels from the text and re-arrange them after tokenizing (due to subtokens). However, I can't find a way to either create a tensorflow Data...
You have a few options. You can use a defaultdict: from collections import defaultdict import tensorflow as tf result = defaultdict(list) for d in tokens: for k, v in d.items(): result[k].append(v) dataset = tf.data.Dataset.from_tensor_slices(dict(result)) Or you can use pandas as shown here: import pandas as pd impor...
4
2
72,999,837
2022-7-15
https://stackoverflow.com/questions/72999837/why-how-is-1-0-5-inaccurate
Python computes the imaginary unit i = sqrt(-1) inaccurately: >>> (-1) ** 0.5 (6.123233995736766e-17+1j) Should be exactly 1j (Python calls it j instead of i). Both -1 and 0.5 are represented exactly, the result can be represented exactly as well, so there's no hard reason (i.e., floating point limitations) why Python...
When complex arithmetic is required, your Python implementation likely calculates xy as ey ln x, as might be done with the complex C functions cexp and clog. Those are in turn likely calculated with real functions including ln, sqrt, atan2, sin, cos, and pow, but the details need not concern us. ln −1 is πi. However, π...
4
1
73,029,554
2022-7-18
https://stackoverflow.com/questions/73029554/vs-code-pytest-discovery-error-due-to-modulenotfounderror
I am trying to setup my VS Code debugger for pytest and am getting the error discovering pytests tests from the testing tab. The test I'm running works perfectly when run from the terminal but the VS debugger is not able to run it. In the testing tab, it directs me to the output where it shows a ModuleNotFoundError for...
You are using virtualenv inside terminal. Here is clearly seeing in logs that python is installed inside /Users/.../pypoetry/virtualenvs/... folder. But VSCode using default python (/usr/local/bin/python3) or at least non virtualenv version You have to choose same interpreter in VSCode as terminal's one What is virtual...
5
2
73,025,014
2022-7-18
https://stackoverflow.com/questions/73025014/how-to-return-status-code-in-python-without-actually-exiting-the-process
I'm trying to return a status code without exiting the process of my script. Is there an equivalent to sys.exit() that does not stop execution ? What I'd like to happen : If no exception is raised, status code is by default 0. For minor exceptions, I want to return status code 1, but keep the process running, unless a ...
Wait until the end of your loop to return the 1 exit code. I'd do it like: def process_pdf_dir() -> int: ret = 0 for file in os.listdir('pdf_files/'): if file.endswith('.pdf'): if not anonymiser(file): # remember to return a warning ret = 1 if criticalError: # immediately return a failure return 2 return ret if __name_...
5
3
72,992,588
2022-7-15
https://stackoverflow.com/questions/72992588/how-to-debug-python-unittests-in-visual-studio-code
I have the following directory structure (a friends was so kind to put it on github while he examined it) - code - elements __init__.py type_of_car.py __init__.py car.py - tests __init__.py test_car.py These are my launch.json settings: { "version": "0.2.0", "configurations": [ { "name": "Python: Debug Tests", "type":...
You can modify the car.py and test_car.py files as follows: I only pasted the modified code。 car.py: # your code from code.elements.type_of_car import TypeOfCar # my code from elements.type_of_car import TypeOfCar test_car.py: # your code import unittest from code.car import Car from random import randint from code.e...
3
2
72,996,818
2022-7-15
https://stackoverflow.com/questions/72996818/attributeerror-in-pytest-with-asyncio-after-include-code-in-fixtures
I need to test my telegram bot. To do this I need to create client user to ask my bot. I found telethon library which can do it. First I wrote a code example to ensure that authorisation and connection works and send test message to myself (imports omitted): api_id = int(os.getenv("TELEGRAM_APP_ID")) api_hash = os.gete...
Use @pytest_asyncio.fixture decorator in async fixtures according to documentation https://pypi.org/project/pytest-asyncio/#async-fixtures. Like this: import pytest_asyncio @pytest_asyncio.fixture(scope="session") async def client(): ...
19
42
73,017,267
2022-7-18
https://stackoverflow.com/questions/73017267/syntaxerror-non-utf-8-code-starting-with-xca-in-file-usr-local-bin-python3
I am trying to schedule a crontab job to run a python script and referring to python in /usr/local/bin/python3 but getting this error SyntaxError: Non-UTF-8 code starting with '\xca' in file /usr/local/bin/python3 on line 2 What does this mean and how can I solve it? I can't open the python3 file
you're calling to python twice. Decide which interpreter you want to use and run either: * * * * * /Users/name/opt/anaconda3/envs/myenv/bin/python /Users/name/Desktop/Scrape/scraper.py or * * * * * /usr/local/bin/python3 /Users/name/Desktop/Scrape/scraper.py
3
4
73,013,781
2022-7-17
https://stackoverflow.com/questions/73013781/how-to-enable-autocomplete-when-connect-to-docker-container-through-cli
I created a docker image for my FastAPI application then I created a container from that image. Now When I connect to that container using docker exec -it <container-id> through my terminal, I am able to access it but the problem is that autocomplete doesn't work when I press TAB.
What I have understood from your question is when you enter into the docker environment, you are unable to autocomplete filenames and folders. Usually when you enter into the container via shell, the autocomplete not works properly. Tried to enter into the container using bash environment i.e., docker exec -it <contain...
9
19
73,012,167
2022-7-17
https://stackoverflow.com/questions/73012167/convert-a-text-file-into-a-dictionary-list
I have a text file in this format (in_file.txt): banana 4500 9 banana 350 0 banana 550 8 orange 13000 6 How can I convert this into a dictionary list in Python? Code: in_filepath = 'in_file.txt' def data_dict(in_filepath): with open(in_filepath, 'r') as file: for line in file.readlines(): title, price, count = line.s...
titles = ["title","price","count"] [dict(zip(titles, [int(word) if word.isdigit() else word for word in line.strip().split()])) for line in open("in_file.txt").readlines()] or: titles = ["title","price","count"] [dict(zip(titles, [(data:=line.strip().split())[0], *map(int, data[1:])])) for line in open("in_file.txt")....
3
3
73,007,303
2022-7-16
https://stackoverflow.com/questions/73007303/what-is-the-correct-way-of-accessing-hydras-current-output-directory
Assuming I prevent Hydra from changing the current working directory, how can I still retrieve the job's output directory (i.e., the folder Hydra created for storing the results of the particular job) from main()? Ideally, I'd like a method that works regardless of whether it's a regular run or a multi-run. I know I ca...
Found it. hydra_cfg = hydra.core.hydra_config.HydraConfig.get() hydra_cfg['runtime']['output_dir']
8
11
73,006,164
2022-7-16
https://stackoverflow.com/questions/73006164/communicate-between-two-widgets-not-directly-related
I have a GUI with widgets that has multiple child widgets inside, as you can see in the image: I want to communicate "Widget 2-2" with "Widget 1-1". I have different options, but I don't know which is better. 1. Propagate signal My first idea was propagates the emit to Main Windows and then it propagates the action to...
Singletons, or static initialisation for that matter ought to be the last resort as they can cause all sorts of headaches, especially in multi-threaded environment. Definitely do not go for that in this case. What I have personally done in my project in this case, I emitted a signal in the first widget and then forward...
5
2
73,006,039
2022-7-16
https://stackoverflow.com/questions/73006039/what-is-the-purpose-of-pyvenv-cfg-after-the-creation-of-a-python-virtual-environ
When I create a virtual environment in Python on Windows cmd, in the virtual environment folder, the following files appear: Include Lib Scripts pyvenv.cfg What is the goal of pyvenv.cfg creation? Can I use it in any way?
pyvenv.cfg is a configuration file that stores information about the virtual environment such as standard libraries path Python version interpreter version virtual env flags or any other venv configs If print content of pyvenv.cfg $ cat myenv/pyvenv.cfg home = /usr/bin include-system-site-packages = false version = 3...
11
5
73,001,554
2022-7-16
https://stackoverflow.com/questions/73001554/how-to-define-a-typeddict-class-with-keys-containing-hyphens
How can I create a TypedDict class that supports keys containing hyphens or other characters that are supported in strings, such as "justify-content" in the example below. from typing import TypedDict, Literal from typing_extensions import NotRequired class Attributes(TypedDict): width: NotRequired[str] height: NotRequ...
It is possible with the functional syntax: from typing import TypedDict, Literal from typing_extensions import NotRequired Attributes = TypedDict( "Attributes", { "width": NotRequired[ str, ], "height": NotRequired[ str, ], "direction": NotRequired[ Literal["row", "column"], ], "justify-content": NotRequired[ Literal["...
9
11
73,005,057
2022-7-16
https://stackoverflow.com/questions/73005057/how-to-define-a-function-that-has-a-condition-as-input
I need a function that takes a rule/condition as an input. for example given an array of integers detect all the numbers that are greater than two, and all the numbers greater than four. I know this can be achieved easily without a function, but I need this to be inside a function. The function I would like to have is ...
Functions are first class objects meaning you can treat them as any other variable. import numpy as np def _select(x,rule): outp = rule(x) return outp def rule_2(val): return val > 2 def rule_4(val): return val > 4 L = np.round(np.random.normal(2,4,50),decimals=2) y = _select(x=L,rule=rule_2) print(y) y1 = _select(x=L,...
3
6
72,986,422
2022-7-14
https://stackoverflow.com/questions/72986422/how-to-asynchronously-run-functions-within-a-for-loop-in-python
Hi I was wondering how to asynchronously call a function within a for-loop in Python, allowing the for-loop to execute more quickly. bar() in this case is a time intensive function, which is why I want the calls to it to be nonblocking. Here is what I want to refactor: def bar(item): //manipulate item return newItem ne...
If your tasks are really async you can do it the following way: import asyncio async def bar(item: int) -> int: # manipulate item print("Started") await asyncio.sleep(5) print("Finished") return item ** 2 async def foo(): items = range(1, 10) tasks = [bar(item) for item in items] new_items = await asyncio.gather(*tasks...
4
3
73,000,307
2022-7-15
https://stackoverflow.com/questions/73000307/using-matplotlib-with-dask
Let's say we have pandas dataframe pd and a dask dataframe dd. When I want to plot pandas one with matplotlib I can easily do it: fig, ax = plt.subplots() ax.bar(pd["series1"], pd["series2"]) fig.savefig(path) However, when I am trying to do the same with dask dataframe I am getting Type Errors such as: TypeError: Can...
SultanOrazbayev's is still spot on, here is an answer elaborating on the datashader option (which hvplot call under the hood). Don't use Matplotlib, use hvPlot! If you wish to plot the data while it's still large, I recommend using hvPlot, as it can natively handle dask dataframes. It also automatically provides intera...
3
7
73,001,224
2022-7-16
https://stackoverflow.com/questions/73001224/how-to-specify-the-name-and-location-of-the-output-file-when-using-nbconvert
When using nbconvert, how can I specify the name and directory of the new file?
Use the --output flag to change the name of the converted file Use the --output-dir flag to change the directory of the converted file jupyter nbconvert <path/to/notebook.ipynb> --to <x> --output <"name" (without file extension)> --output-dir <path/to/new/file>
4
5
72,995,215
2022-7-15
https://stackoverflow.com/questions/72995215/matplotlib-specify-custom-colors-for-line-plot-of-numpy-array
I have a 2D numpy array (y_array) with 3 columns (and common x values as a list, x_list) and I want to create a plot with each column plotted as a line. I can do this by simply doing matplotlib.pyplot.plot(x_list, y_array) and it works just fine. However I am struggeling with the colors. I need to assign custom colors ...
You can create a custom cycler and use it to define your colors. You can get more information here import matplotlib.pyplot as plt import numpy as np from cycler import cycler if __name__ == '__main__': my_colors = ['steelblue', 'seagreen', 'firebrick'] custom_cycler = cycler(color=my_colors) x_list = np.linspace(0, 9,...
4
3
72,982,495
2022-7-14
https://stackoverflow.com/questions/72982495/couldnt-install-psycopg2-for-a-fastapi-project-on-macos-10-13-6-python-setup
I tried to install psycopg2 with the command line : pip install psycopg2 and this is what I get Preparing metadata (setup.py) ... error error: subprocess-exited-with-error × python setup.py egg_info did not run successfully. │ exit code: 1 ╰─> [25 lines of output] /Library/Frameworks/Python.framework/Versions/3.10/lib...
After reading some similar questions on Stackoverflow here is the solution that worked for me. First, install Homebrew in case you don't already have it installed /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" then install postgresql : brew install postgresql finally u...
3
4
72,993,611
2022-7-15
https://stackoverflow.com/questions/72993611/python-cant-re-enter-readline
I'm new to python and I'm trying to make a GUI window with Tkinter that executes a command. I wrote the code underneath but it wont work. What is wrong with it? The required imports are imported like tk and ttk. This is the tkinter window code: root = Tk() root.geometry("600x450") root.title("Points") Label(root, text=...
From running the code you share, where the tk window will not run, the first clear error is that you haven't included a root.mainloop() statement below is the code as I have tweaked it to make it run: from tkinter import * from tkinter import ttk PlayerPoints = 100 def AddPoints(): PointsToAdd = int(input("How many poi...
4
3
72,991,324
2022-7-15
https://stackoverflow.com/questions/72991324/how-to-apply-custom-functions-with-multiple-parameters-in-polars
Now I have a dataframe: df = pd.DataFrame({ "a":[1,2,3,4,5], "b":[2,3,4,5,6], "c":[3,4,5,6,7] }) The function: def fun(a,b,shift_len): return a+b*shift_len,b-shift_len Using Pandas, I can get the result by: df[["d","e"]] = df.apply(lambda row:fun(row["a"],row["b"],3),axis=1,result_type="expand") I want to know how c...
Passing arguments with args import pandas as pd df1 = pd.DataFrame({"a":[1,2,3,4,5],"b":[2,3,4,5,6],"c":[3,4,5,6,7]}) def t(df, row1, row2, shift_len): return df[row1] + df[row2] * shift_len, df[row2] - shift_len df1[["d", "e"]] = df1.apply(t, args=("a", "b", 3), axis=1, result_type="expand") print(df1) OUTPUT: a b c d...
4
-1
72,982,568
2022-7-14
https://stackoverflow.com/questions/72982568/indexing-first-n-characters-of-charfield-in-django
How to index a specific number of Characters on Django Charfield? For example, this is how we index fields in Django, but I guess it applies to entire field or all characters. class Meta: indexes = [ models.Index(fields=['last_name', 'first_name',]), models.Index(fields=['-date_of_birth',]), ] So, how to apply index t...
You can create a functional index with the Substr function [Django-doc]: from django.db.models.functions import Substr # … class Meta: indexes = [ models.Index(fields=['last_name', 'first_name']), models.Index(fields=['-date_of_birth']), models.Index(Substr('pub_date', 0, 10), name='part_of_name') ]
3
5
72,989,037
2022-7-15
https://stackoverflow.com/questions/72989037/pandas-array-filter-nan-and-keep-the-first-value-in-group
I have the following pandas dataframe. There are many NaN but there are lots of NaN value (I skipped the NaN value to make it look shorter). 0 NaN ... 26 NaN 27 357.0 28 357.0 29 357.0 30 NaN ... 246 NaN 247 357.0 248 357.0 249 357.0 250 NaN ... 303 NaN 304 58.0 305 58.0 306 58.0 307 58.0 308 58.0 309 58.0 310 58.0 311...
Take only values that aren't nan, but the value before them is nan: df = df[df.col1.notna() & df.col1.shift().isna()] Output: col1 27 357.0 247 357.0 304 58.0 334 237.0 Assuming all values are greater than 0, we could also do: df = df.fillna(0).diff() df = df[df.col1.gt(0)]
3
4
72,984,094
2022-7-14
https://stackoverflow.com/questions/72984094/why-is-my-normal-q-q-plot-of-residuals-a-vertical-line
I am using a Q-Q Plot to test if the residuals of my linear regression follow a normal distribution but the result is a vertical line. It looks like linear regression is a pretty good model for this dataset, so shouldn't the residuals be normally distributed? The points were created randomly: import numpy as np x_va...
Your problem is two-fold here The primary problem is that sklearn (scikit learn) expects your input to be in a 2d columnar array, whereas qqplot from statsmodels expects your data to be in a true 1d array. When you're passing the residuals to qqplot it is attempting to transform each residual individually instead of a...
3
1
72,984,800
2022-7-14
https://stackoverflow.com/questions/72984800/why-does-unpacking-non-identifier-strings-work-on-a-function-call
I've noticed, to my surprise, that in a function call, I could unpack a dict with strings that weren't even valid python identifiers. It's surprising to me since argument names must be identifiers, so allowing a function call to unpack a **kwargs that has non-identifiers, with no run time error, doesn't seem healthy (s...
Looks like this is more of a kwargs issue than an unpacking issue. For example, one wouldn't run into the same issue with foo: def foo(a, b): print(a + b) foo(**{"a": 3, "b": 2}) # 5 foo(**{"a": 3, "b": 2, "c": 4}) # TypeError: foo() got an unexpected keyword argument 'c' foo(**{"a": 3, "b": 2, "not valid": 4}) # TypeE...
7
1
72,983,671
2022-7-14
https://stackoverflow.com/questions/72983671/why-is-my-move-function-not-working-in-pygame
IDK why my player.move() is not working here's my main class: import pygame from player import * pygame.init() WIDTH, HEIGHT = 900, 600 WIN = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("MyGame!") FPS = 60 player_x = 500 player_y = 500 PLAYER_WIDTH = 60 PLAYER_HEIGHT = 60 PLAYER_VEL = 5 WHITE = ...
pygame.key.get_pressed() returns a sequence with the state of each key. If a key is held down, the state for the key is 1, otherwise 0. The contents of the keys_pressed list don't magically change when the state of the keys changes. keys_pressed is not tied to the keys. You need to get the new state of the keys in ever...
3
6
72,968,127
2022-7-13
https://stackoverflow.com/questions/72968127/python-debug-not-working-on-ssh-fs-remote-host
Issue: I am using VSCode version 1.69.1 on Mac (Version details at the bottom). From Mac, I connect to a remote repo using SSH FS When I click on 'run' > 'Start Debugging' or 'Run Without Debugging' on a remote python file, the "Run and Debug pane opens" but the file is not run [![Pane is blank][1]][1] The debugger wor...
Python Debugger version v2022.10.0 seems to be broken for SSH-FS. Using the previous version of Python extension addressed it. To install an older version of an extension, click on gear icon> select "Install another version" and select version to install. I used version v2022.8.1, and that works
4
10
72,975,483
2022-7-14
https://stackoverflow.com/questions/72975483/milliseconds-to-hhmmss-time-format
I'm trying to add the timestamp of a video frame to its own frame name like "frame2 00:00:01:05", using CAP_PROP_POS_MSEC I'm getting the current position of the video file in milliseconds, what I want is to change those milliseconds to the time format "00:00:00:00:". My code currently assigns the name like: "frame2 1....
Just use divmod. It does a division and modulo at the same time. It's more convenient than doing that separately. seconds = 1.05 # or whatever (hours, seconds) = divmod(seconds, 3600) (minutes, seconds) = divmod(seconds, 60) formatted = f"{hours:02.0f}:{minutes:02.0f}:{seconds:05.2f}" # >>> formatted # '00:00:01.05' A...
4
6
72,967,793
2022-7-13
https://stackoverflow.com/questions/72967793/keyboardinterrupt-with-python-multiprocessing-pool
I want to write a service that launches multiple workers that work infinitely and then quit when main process is Ctrl+C'd. However, I do not understand how to handle Ctrl+C correctly. I have a following testing code: import os import multiprocessing as mp def g(): print(os.getpid()) while True: pass def main(): with mp...
The signal that triggers KeyboardInterrupt is delivered to the whole pool. The child worker processes treat it the same as the parent, raising KeyboardInterrupt. The easiest solution here is: Disable the SIGINT handling in each worker on creation Ensure the parent terminates the workers when it catches KeyboardInterru...
5
6
72,965,428
2022-7-13
https://stackoverflow.com/questions/72965428/why-is-a-cnn-model-struggling-to-classify-a-colored-mnist
I'm trying to classify colored MNIST digits with a basic CNN architecture on Keras. Here is the piece of code that colors the original dataset into purely either red, green or blue. def load_norm_data(): ## load basic mnist (x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data() train_images = np.zeros(...
The last part of the model includes a dense -> relu -> softmax. The relu activation should be removed. In addition, you might benefit from adding non-linearities (e.g., relu) in your convolutional blocks. Otherwise, the neural network will end up being a (big) linear function and will not work as well for non-linear da...
4
3
72,966,797
2022-7-13
https://stackoverflow.com/questions/72966797/how-to-debug-on-exceptions-inside-try-except-block
The PyCharm debugger has the feature to set breakpoints at raised exceptions. However if an exception is handled inside a try except block it is not raised. How to deal with this if I want to debug within the try block? I could comment out the try except parts but this seems too cumbersome. Is there a better solution?
In the breakpoints settings (Either the icon in the debug toolbar, or ctrl+shft+F8), you can set exception breakpoints. The "Activation Policy" is usually set by default to "On termination". But since you handle the error, there is no termination. To activate the breakpoint immediately, even if the error is handled, y...
4
3
72,963,015
2022-7-13
https://stackoverflow.com/questions/72963015/replacing-multiple-characters-at-once
Is there any way to replace multiple characters in a string at once, so that instead of doing: "foo_faa:fee,fii".replace("_", "").replace(":", "").replace(",", "") just something like (with str.replace()) "foo_faa:fee,fii".replace(["_", ":", ","], "")
An option that requires no looping or regular expressions is translate: >>> "foo_faa:fee,fii".translate(str.maketrans('', '', "_:,")) "foofaafeefii" Note that for Python 2, the API is slightly different.
5
11
72,881,426
2022-7-6
https://stackoverflow.com/questions/72881426/python-difficulty-understanding-getlogger-name
Im quite confused on the logging docs' explanation of getLogger(__name__) as a best practice. Gonna be explaining my entire thought process, feel free to leave a comment any time I make a mistake The logging docs says A good convention to use when naming loggers is to use a module-level logger, in each module which us...
Assume this simple project: project/ ├── app.py ├── core │ ├── engine.py │ └── __init__.py ├── __init__.py └── utils ├── db.py └── __init__.py Where app.py is: import logging import sys from utils import db from core import engine logger = logging.getLogger() logger.setLevel(logging.INFO) stdout = logging.StreamHandle...
4
7
72,899,105
2022-7-7
https://stackoverflow.com/questions/72899105/how-to-mask-a-polars-dataframe-using-another-dataframe
I have a polars dataframe like so: df = pl.from_repr(""" ┌─────────────────────┬─────────┬─────────┐ │ time ┆ 1 ┆ 2 │ │ --- ┆ --- ┆ --- │ │ datetime[μs] ┆ f64 ┆ f64 │ ╞═════════════════════╪═════════╪═════════╡ │ 2021-10-02 00:05:00 ┆ 2.9048 ┆ 2.8849 │ │ 2021-10-02 00:10:00 ┆ 48224.0 ┆ 48068.0 │ └─────────────────────┴...
Having columns in a single DataFrame has guarantees you don't have when you have data in separate tables. Masking out values by columns in another DataFrame is a potential for errors caused by different lengths. For this reason polars does not encourage such operations and therefore you must first create a single DataF...
3
4
72,920,189
2022-7-9
https://stackoverflow.com/questions/72920189/select-all-columns-where-column-name-starts-with-string
Given the following dataframe, is there some way to select only columns starting with a given prefix? I know I could do e.g. pl.col(column) for column in df.columns if column.startswith("prefix_"), but I'm wondering if I can do it as part of a single expression. df = pl.DataFrame( {"prefix_a": [1, 2, 3], "prefix_b": [1...
Starting from Polars 0.18.1 you can use Selectors(polars.selectors.starts_with) which provides more intuitive selection of columns from DataFrame or LazyFrame objects based on their name, dtype or other properties. >>> import polars as pl >>> import polars.selectors as cs >>> >>> df = pl.DataFrame( ... {"prefix_a": [1,...
10
11
72,897,924
2022-7-7
https://stackoverflow.com/questions/72897924/python-rabbitmq-pika-consumer-how-to-use-async-function-as-callback
I have the following code where I initialize a consumer listening to a queue. consumer = MyConsumer() consumer.declare_queue(queue_name="my-jobs") consumer.declare_exchange(exchange_name="my-jobs") consumer.bind_queue( exchange_name="my-jobs", queue_name="my-jobs", routing_key="jobs" ) consumer.consume_messages(queue="...
I annotated my callback with @sync where sync is: def sync(f): @functools.wraps(f) def wrapper(*args, **kwargs): return asyncio.get_event_loop().run_until_complete(f(*args, **kwargs)) return wrapper (found it here for celery, but it worked with pika too)
6
9
72,909,147
2022-7-8
https://stackoverflow.com/questions/72909147/sqlalchemy-relationships-field-to-pydantic-validation-error
I have some models declared with SQLAlchemy declarative base. Their fields represent some IP addresses. When I try to convert instances of these models to pydantic model via orm_mode, it fails with the following error E pydantic.error_wrappers.ValidationError: 4 validation errors for IpSchema E ip_address -> 0 E value ...
Pydantic does not know how to map each relationship ORM instances to its address field. For that you will need to add a pydantic validator with the pre=True argument in order to map each ORM instance to the address field before pydantic validation. Here is how it should look like class IpSchema(BaseModel): ip_address: ...
4
2
72,954,928
2022-7-12
https://stackoverflow.com/questions/72954928/type-annotations-for-sqlalchemy-model-declaration
I can't figure how i could type annotate my sqlalchemy models code, what kind of type should i use for my model fields. class Email(Model): __tablename__ = 'emails' name: Column[str] = Column(String, nullable=False) sender: Column[str] = Column( String, default=default_sender, nullable=False ) subject: Column[str] = Co...
For SQLAlchemy 2.0 it would be something like: import uuid from sqlalchemy.orm import Mapped, mapped_column from sqlalchemy.dialects.postgresql import UUID class Email(Model): __tablename__ = 'emails' name: Mapped[str] = mapped_column(String, nullable=False) sender: Mapped[str] = mapped_column( String, default=default_...
5
7
72,906,257
2022-7-8
https://stackoverflow.com/questions/72906257/what-is-nondynamicallyquantizablelinear
I found NonDynamicallyQuantizableLinear while reading torch.nn.modules.activation.py in MultiheadAttention class And I have a few questions about it What is the difference between Linear and NonDynamicallyQuantizableLinear? Why is NonDynamicallyQuantizableLinear used for MultiheadAttention?
It is introduced as a temporary cleanup measure to fail immediately when attempting directly quantize torch.nn.MultiheadAttention. This improves upon the baseline behavior of failing silently. See https://github.com/pytorch/pytorch/issues/58969
6
3
72,915,808
2022-7-8
https://stackoverflow.com/questions/72915808/how-to-create-a-custom-sort-order-for-the-api-methods-in-fastapi-swagger-autodoc
How can I set a custom sort order for the API methods in FastAPI Swagger autodocs? This question shows how to do it in Java. My previous question asked how to sort by "Method", which is a supported sorting method. I would really like to take this a step further, so that I can determine which order the methods appear. R...
You can use tags to group your endpoints. To do that, pass the parameter tags with a list of str (commonly just one str) to your endpoints. Use the same tag name for endpoints that use the same HTTP method, so that you can group your endpoints that way. For example, use Get as the tag name for GET operations (Note: Get...
9
7
72,935,514
2022-7-11
https://stackoverflow.com/questions/72935514/cant-solve-systemerror-unknown-opcode
I am executing a notebook on my laptop and I get the following error. XXX lineno: 17, opcode: 120 --------------------------------------------------------------------------- SystemError Traceback (most recent call last) Input In [3], in <cell line: 3>() 1 gym = Gym(0, 0, 0, 0).from_dill(BACKUP) 2 ticker = gym.api.retur...
Code objects (from functions and class methods) serialized with dill are not guaranteed to work across different Python versions, because the list of valid opcodes change from version to version. In cases where there is an opcode unknown to the interpreter deserializing ("unpickling") the code object, the functions and...
3
4
72,950,907
2022-7-12
https://stackoverflow.com/questions/72950907/how-to-fix-userwarning-distutils-was-imported-before-setuptools
When I cloned some packages including python tools, an error occured: Errors << unique_id:cmake /home/scpark/cps_ws/logs/unique_id/build.cmake.001.log CMake Warning (dev) at CMakeLists.txt:2 (project): Policy CMP0048 is not set: project() command manages VERSION variables. Run "cmake --help-policy CMP0048" for policy d...
I had the same problem after upgrading my system to 20.04 and ROS Noetic. As suggested in this answer, upgrading setuptools solves the problem. But I would actually do a user install like this pip3 install --user --upgrade pip setuptools as it avoids conflicts with the system package.
4
1
72,898,620
2022-7-7
https://stackoverflow.com/questions/72898620/trigger-a-dash-dashboard-on-a-button-click
I am working on a dash app, where I try to integrate ExplainerDashboard. If I do it like this: app.config.external_stylesheets = [dbc.themes.BOOTSTRAP] app.layout = html.Div([ html.Button('Submit', id='submit', n_clicks=0), html.Div(id='container-button-basic', children='') ]) X_train, y_train, X_test, y_test = titanic...
The reason why your example doesn't work is that in Dash, callbacks must be registered before the server starts. Hence, you cannot register new callbacks from within a callback. Data pre-processing pipeline I think the cleanest solution would be move the data processing to a pre-processing pipeline. It could be somethi...
5
1
72,942,995
2022-7-11
https://stackoverflow.com/questions/72942995/whats-the-benefit-of-a-shared-build-python-vs-a-static-build-python
This question has been bothering me for two weeks and I've searched online and asked people but couldn't get an answer. Python by default build the library libpythonMAJOR.MINOR.a and statically links it into the interpreter. Also it has an --enable-shared flag, which will build a share library libpythonMAJOR.MINOR.so.1...
It turns out to be that others are talking about the scenario "Embedding Python in Another Application" (https://docs.python.org/3/extending/embedding.html). If that's the case, then "saving disk space" and other mentioned reasons make sense. Because embedding python in another application, either you need to staticall...
4
1
72,901,475
2022-7-7
https://stackoverflow.com/questions/72901475/dynamically-updating-values-of-a-field-depending-on-the-choice-selected-in-anoth
I have two tables. Inventory and Invoice. InventoryModel: from django.db import models class Inventory(models.Model): product_number = models.IntegerField(primary_key=True) product = models.TextField(max_length=3000, default='', blank=True, null=True) title = models.CharField('Title', max_length=120, default='', blank=...
I figured out how to achieve this functionality. I wish I could give the credits to a single person but it's really a combination of many people's answers. in the views.py which returns the HTML page where I want this functionality, I wrote this code, It returns the Product objects to the HTML file: model_data=Inventor...
4
0
72,914,328
2022-7-8
https://stackoverflow.com/questions/72914328/compare-similarity-of-two-names-and-identify-duplicates-with-neural-network
I have a dataset which contains pairs of names, it looks like this: ID; name1; name2 1; Mike Miller; Mike Miler 2; John Doe; Pete McGillen 3; Sara Johnson; Edita Johnson 4; John Lemond-Lee Peter; John LL. Peter 5; Marta Sunz; Martha Sund 6; John Peter; Johanna Petera 7; Joanna Nemzik; Joanna Niemczik I have some cases...
I have read carefully whole your question, but still I don't know why you want a neural network for that. Real, sad answer Tweak edit distance (more general distance than Levenshtein) by adding some weights - idea: swapping characters that are close on the keyboard is more likely than those that are faraway. So distanc...
5
1
72,949,464
2022-7-12
https://stackoverflow.com/questions/72949464/python-ppt-find-and-replace-within-a-chart
I already referred these posts here here, here and here. Please don't mark it as a duplicate. I have a chart embedded inside the ppt like below I wish to replace the axis headers from FY2021 HC to FY1918 HC. Similarly, FY2122 HC should be replaced with FY1718 HC. How can I do this using python pptx? This chart is comi...
You can get to the category labels the following way: from pptx import Presentation from pptx.shapes.graphfrm import GraphicFrame prs = Presentation('chart-01.pptx') for slide in prs.slides: for shape in slide.shapes: print("slide: %s, id: %s, index: %s, type: %s" % (slide.slide_id, shape.shape_id, slide.shapes.index(s...
4
3
72,928,952
2022-7-10
https://stackoverflow.com/questions/72928952/why-cant-the-import-be-resolved
I've seen several answers to this question, albeit none of the solutions have worked for my particular situation. I'm trying to get started building an API with Flask. When I try to import Flask-RESTful, I get an error in VS Code. For context, I am using Windows 11. Here are the first two lines of my .py file: from fla...
Use the Ctrl+Shift+P command, search for and select Python:Select Interpreter(Or click directly on the python version displayed in the lower right corner), and select the correct interpreter.
4
6
72,928,384
2022-7-10
https://stackoverflow.com/questions/72928384/python-subprocess-is-not-scalable-by-default-any-simple-solution-you-can-recomm
I have an application which does this: subprocess.Popen(["python3", "-u", "sub-program-1.py"]) So Python program can start multiple long-lived processes on demand. If I stop main Python program and start again, it knows that sub-program-1.py should be started, because there is a record about status in DB that tells it...
TL;DR - This is a classical monolithic application scaling problem you can easily solve this by redesigning your application to a microservice architecture, since your application functionality is inherently decoupled between components. Once you've done that, it all really boils down to you deploying your application ...
3
7
72,952,005
2022-7-12
https://stackoverflow.com/questions/72952005/how-is-numpy-einsum-implemented
I want to understand how is einsum function in python implemented. I found the source code in numpy/core/src/multiarray/einsum.c.src file but couldn't completely understand it. In particular I want to understand how does it creates the required loops automatically? For example: import numpy as np a = np.random.rand(2,3...
I want to understand how does it creates the required loops automatically? Well, it does not create the loops the way you think it does. In this case, it creates an iterator operating over multiple arrays and then use it in a generic main loop. In the more general case, there are two main loops: one to iterate over t...
8
6
72,909,832
2022-7-8
https://stackoverflow.com/questions/72909832/use-geopandas-shapely-to-find-intersection-area-of-polygons-defined-by-latitud
I have two GeoDataFrames, left and right, with many polygons in them. Now I am trying to find the total intersection area of each polygon in left, with all polygons in right. I've managed to get the indices of the intersecting polygons in right for each polygon in left using gpd.sjoin, so I compute the intersection are...
I fixed it by using the EPSG:6933 projection instead, which is an area preserving map projection and returns the area in square metres (EPSG:4326 does not preserve areas, so is not suitable for area calculations). I could just change my GDF to this projection using gdf.to_crs(espg=6933) And then compute the area in th...
4
3
72,899,754
2022-7-7
https://stackoverflow.com/questions/72899754/django-tailwindcss-wont-load-some-attributes
I'm having issues when it comes to using some attributes with Django and TailwindCSS. Let's take this table for example: <div class="relative overflow-x-auto shadow-md sm:rounded-lg"> <table class="w-full text-lg text-left text-gray-500 rounded-2xl mt-4 dark:text-gray-400"> <thead class="rounded-2xl text-lg text-white...
We finally managed to solve this issue. The problem was that I ran python manage.py collectstatic which created the following directory : static > css > dist > styles.css. django-tailwind created the same repository under the theme folder. Every time I tried to restart the server, the wrong styles.css was taken into ac...
3
4
72,909,466
2022-7-8
https://stackoverflow.com/questions/72909466/class-weight-and-sample-weight-ineffective-for-sklearn-random-forest
I'm new to ML and I've been working with an imbalanced data set where the count of negative samples is twice that of the positive samples. In-order to address these i set scikit-learn Random forest class_weight = 'balanced', which gave me an ROC-AUC score of 0.904 and the recall for class- 1 was 0.86, now when i tried ...
The reason is that you grow the trees out fully, which leads to every leaf node being pure. That will happen regardless of the class weights (though the structure of the tree leading up to those pure nodes will change). The predicted probabilities of each tree will be (almost) all 0 or 1, and so the overall probability...
4
2
72,956,054
2022-7-12
https://stackoverflow.com/questions/72956054/zip-like-function-that-iterates-over-multiple-items-in-lists-and-returns-possibi
In the following code: a = [["2022"], ["2023"]] b = [["blue", "red"], ["green", "yellow"]] c = [["1", "2", "3"], ["4", "5", "6", "7"], ["8", "9", "10", "11"], ["12", "13"]] I would like a function that outputs this, but for any number of variables: [ ["2022", "blue", "1"], ["2022", "blue", "2"], ["2022", "blue", "3"],...
First, you join the first argument, to a list of lists with only one element each. Then for each sublist and its index i in the next argument, you pick the i-th list of the previous iteration res[i] and add to aux len(sublist) lists each of one is the res[i] with one item from sublist. from itertools import chain def f...
7
13
72,956,903
2022-7-12
https://stackoverflow.com/questions/72956903/import-urllib3-could-not-be-resolved-from-sourcepylancereportmissingmodulesour
I am new to Python and writing a lambda function. I installed urllib3 using pip but still getting this following error. I tried restarting vscode/ uninstall and reinstall but still getting the error. this is the result when I run pip show urllib3 what am i missing here?
Maybe there is more than one python environment on your machine, And the location where you installed the package is inconsistent with the python interpreter you are using now. You can use CTRL + SHIFT + P to open the command palette and search Python: Select Interpreter (or click on the interpreter version displayed i...
3
2
72,937,452
2022-7-11
https://stackoverflow.com/questions/72937452/importerror-dlopen-library-not-loaded-rpath-pywrap-tensorflow-internal
I am a beginner at machine learning. I try to use LSTM algorism but when I write from keras.models import Sequential it shows error as below: ImportError: dlopen(/Users/wangzifan/opt/anaconda3/lib/python3.9/site-packages/tensorflow/python/_pywrap_tfe.so, 2): Library not loaded: @rpath/_pywrap_tensorflow_internal.so Ref...
Problem solved. install tensorflow again with sudo pip3 install tensorflow and change the import to from tensorflow.python.keras.models import Sequential
4
1
72,955,005
2022-7-12
https://stackoverflow.com/questions/72955005/x-axis-label-cropped-on-saved-image
So I'm trying to do a bar plot on a data where x is the username (string ) and each x is long enough to overlap each other, so I have to rotate the x label. No problem there. However, when exporting the plot results, the x label on the exported image is cropped. I tried using plt.tight_layout() and worked, but it chang...
You can play around with the rcParams size settings and the plt.subplots_adjust settings until you get your desired image. import matplotlib.pyplot as plt x= ['abc', 'ronaldo', 'melon_killer_123456'] y= [1, 2, 3] plt.rcParams["figure.figsize"] = (5,10) plt.bar(x, y) plt.xticks(rotation = 90) plt.subplots_adjust(top=0.9...
4
2
72,954,047
2022-7-12
https://stackoverflow.com/questions/72954047/how-to-open-a-virtual-environment-created-with-pyenv-with-vscode-editor
I am working on a Linux environment and have created my virtual environment using the pyenv tool. I have set the local virtual environment in my working folder the the one I want with pyenv from command line like this for example : pyenv local my_venv_name which in my case my_venv_name=3.9.9 When I opened VSCode in tha...
Ok so you have to select the correct python interpreter because pyenv could be using multiple python version in different environments. I found two ways to change it: Open the command palette either from the gear icon bottom left corner or by typing Ctrl + Shift + P. Then type select python interpreter and select the ...
14
14
72,953,104
2022-7-12
https://stackoverflow.com/questions/72953104/python-sort-profile-report-by-tottime
Python includes a simple to use profiler: >> import cProfile >> import re >> cProfile.run('re.compile("foo|bar")') 197 function calls (192 primitive calls) in 0.002 seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 0.001 0.001 <string>:1(<module>) 1 0.000 0...
Use the sort=... argument of cProfile.run: >>> import cProfile >>> import time >>> cProfile.run('time.sleep(1); time.monotonic()', sort='tottime') Ordered by: internal time ncalls tottime percall cumtime percall filename:lineno(function) 1 1.001 1.001 1.001 1.001 {built-in method time.sleep} 1 0.000 0.000 1.001 1.001 {...
7
4
72,900,609
2022-7-7
https://stackoverflow.com/questions/72900609/modify-i-th-next-tensor-values-every-time-a-value-1-appears-in-a-tensor
I have two tensors with the same size: a = [1, 2, 3, 4, 5, 10, 11, 12, 13, 20, 21, 22, 23, 24, 25, 26, 27, 28] b = [0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1] Tensor a has three regions which are demarked by consecutive values: region 1 is [1,2,3,4,5], region 2 is [10,11,12,13] and region 3 is [20, 21, 22, ...
Here is a pure Tensorflow approach, which will work in Eager Execution and Graph mode: # copy, paste, acknowledge import tensorflow as tf def split_regions_and_modify(a, b, i): indices = tf.squeeze(tf.where(a[:-1] != a[1:] - 1), axis=-1) + 1 row_splits = tf.cast(tf.cond(tf.not_equal(tf.shape(indices)[0], 0), lambda: tf...
4
2
72,944,235
2022-7-11
https://stackoverflow.com/questions/72944235/plotly-how-to-add-data-labels-to-a-choropleth
I have the following Pandas dataframe df that looks as follows: import pandas as pd df = pd.DataFrame({'state' : ['NY', 'CA', 'FL', 'NJ', 'TX', 'CT', 'MA', 'WA', 'IL', 'GA'], 'user_id' : [10000, 3200, 1600, 1200, 800, 600, 400, 350, 270, 260] }) state user_id 0 NY 10000 1 CA 3200 2 FL 1600 3 NJ 1200 4 TX 800 5 CT 600 6...
You need to also add locationmode="USA-states" to add_scattergeo: fig = px.choropleth( df, locations='state', locationmode="USA-states", scope="usa", color='user_id', color_continuous_scale="blues", ) fig.add_scattergeo( locations=df['state'], locationmode="USA-states", text=df['user_id'], mode='text', ) Output:
3
6
72,943,397
2022-7-11
https://stackoverflow.com/questions/72943397/pulp-program-for-the-the-following-constraint-mina-b-minx-y
Suppose for a moment that I have 4 variables a,b,x,y and one constraint min(a,b) > min(x,y). how can I represent this program in pulp python?
Ok. So, the first answer I posted (deleted) was a bit hasty and the logic was faulty for the relationship described. This is (hopefully) correct! ;) max() and min() are nonlinear, so we need to linearize them somehow (with helper variable) and some logic to relate the 2 minima, which (below) can use a binary helper var...
3
4
72,943,028
2022-7-11
https://stackoverflow.com/questions/72943028/mocking-function-within-a-function-pytest
def func1(): return 5 def func2(param1, param2): var1 = func1() return param1 + param2 + var1 I want to use pytest to test the second function by mocking the first, but I am not sure how to do this. @pytest.fixture(autouse=True) def patch_func1(self): with mock.patch( "func1", return_value= 5, ) as self.mock_func1: yi...
You don't need to change anything. You can use mocker fixture with pytest (requires installation of pytest-mock). don't worry about the mocker argument, it will magically work. def test_func2(mocker): mocked_value = 4 first = 1 second = 2 func1_mock = mocker.patch("func1") func1_mock.return_value = mocked_value actual_...
12
14
72,942,519
2022-7-11
https://stackoverflow.com/questions/72942519/alembic-migration-with-fastapi-docker-connection-to-port-5432-in-localhost-fa
Currently I am trying to learn about Api development with FastAPI and I am trying to dockerize my project. However, when I try to run the database migrations with alembic in Docker by using docker run sm-api_api alembic upgrade head I get the following error: File "/usr/local/lib/python3.10/site-packages/sqlalchemy/eng...
You are connecting to localhost (or 127.0.0.1) which is, from the container point of view, itself. You probably want to change that line in your docker compose as DATABASE_HOSTNAME=postgres, so it refers to the postgres container.
4
3
72,939,233
2022-7-11
https://stackoverflow.com/questions/72939233/whats-the-use-of-values-in-enum-in-python
I'm working with enum lately and I dont really get the utility of them in some cases. I hope my question is not too trivial or too stupid, and I would really love to better understand the logic behind this python structure. One common use I found online or in some pieces of code I have been working on lately is the use...
The members (should) always be named in all uppercase (per the very first note on the enum docs), so if you want them to have "names" that are in some other casing, you can assign strings with arbitrary case, which may be more human-friendly when it comes time to display the values to the user. You can also convert fro...
3
5
72,938,821
2022-7-11
https://stackoverflow.com/questions/72938821/pandas-dataframe-show-duplicate-rows-with-exact-duplicates
I have a big dataframe (120000x40) and I try to find duplicates in every row and display them. Thats what I tried: create dataframe import pandas as pd df = pd.DataFrame({'col1':['1-233','2-766g','6-455','4-356','5-253','2-122','5-531','8-345','1-505','3-127','3-622'], 'col2':['6-998','2-766g','5-955','7-236','5-253','...
To keep the function readable and general, so it works for more or less than three cols, I'd just rely on writing a dedicated function that uses pandas built in functionality for finding duplicates, and applying that to the dataframe rows: import numpy as np import pandas as pd df = pd.DataFrame({'col1':['1-233','2-766...
3
1
72,907,474
2022-7-8
https://stackoverflow.com/questions/72907474/gunicorn-with-gevent-does-not-enforce-timeout
Let's say I have a simple flask app: import time from flask import Flask app = Flask(__name__) @app.route("/") def index(): for i in range(10): print(f"Slept for {i + 1}/{seconds} seconds") time.sleep(1) return "Hello world" I can run it with gunicorn with a 5 second timeout: gunicorn app:app -b 127.0.0.1:5000 -t 5 A...
From https://docs.gunicorn.org/en/stable/settings.html#timeout: Workers silent for more than this many seconds are killed and restarted. For the non sync workers it just means that the worker process is still communicating and is not tied to the length of time required to handle a single request. So timeout is like...
7
7
72,912,762
2022-7-8
https://stackoverflow.com/questions/72912762/setup-py-building-c-extension-with-numpy-dependency
I have created a simple c-function (using the guide here Create Numpy ufunc) and I'm now trying to distribute my package on pypi. For it to work, it needs to compile the c-file(s) into a .so -file, which then can be imported from python and everything is good. To compile it needs the header file numpy/ndarraytypes.h fr...
You can query numpy for the include directory from python via import numpy numpy.get_include() This should return a string (/usr/lib/python3.10/site-packages/numpy/core/include on my system) which you can add to the include_dirs. See here for the docs. As for you question: numpy is a build dependency for you project. ...
3
6
72,907,182
2022-7-8
https://stackoverflow.com/questions/72907182/python-pip-pip-install-cannot-find-a-version-that-satisfies-a-requirement-des
Python3 Pip error + Poetry Packaging I am working in a python library that I am trying to publish to TestPypi. So far, there have been no issues with publishing my Poetry builds. For context, as a beginner, I come from these websites : https://python-poetry.org/docs/ https://packaging.python.org/en/latest/tutorials/pa...
Main Error TLDR; Pip tries to resolve dependencies with TestPypi, but they are in another index (Pypi). Workarounds at end of answer. The fact that I am publishing to TestPypi is the reason this has happened. I will explain why what I did made this error appear, and then I will show how you, from the future, may solve ...
9
5
72,924,307
2022-7-9
https://stackoverflow.com/questions/72924307/creating-new-rows-in-dataframe-based-on-string-values-in-multiple-columns
I ran into this problem where I have a dataframe that looks like the following (the values in the last 3 columns are usually 4-5 alphanumeric codes). import pandas as pd data = {'ID':['P39','S32'], 'Name':['Pipe','Screw'], 'Col3':['Test1, Test2, Test3','Test6, Test7'], 'Col4':['','Test8, Test9'], 'Col5':['Test4, Test5'...
A bit tricky but it should work with melt to flat your dataframe then pivot_table to reshape it: out = (df.reset_index().melt(['ID', 'Name', 'index'], var_name='col', value_name='val') .assign(val=lambda x: x['val'].str.split(', ')).explode('val') .assign(row=lambda x: x.groupby(['index', 'col']).cumcount()) .pivot_tab...
3
1
72,916,381
2022-7-8
https://stackoverflow.com/questions/72916381/read-specific-region-from-pdf
I'm trying to read a specific region on a PDF file. How to do it? I've tried: Using PyPDF2, cropped the PDF page and read only that. It doesn't work because PyPDF2's cropbox only shrinks the "view", but keeps all the items outside the specified cropbox. So on reading the cropped pdf text with extract_text(), it reads ...
PyMuPDF can probably do this. I just answered another question regarding getting the "highlighted text" from a page, but the solution uses the same relevant parts of the PyMuPDF API you want: figure out a rectangle that defines the area of interest extract text based on that rectangle and I say "probably" because I h...
3
3
72,920,010
2022-7-9
https://stackoverflow.com/questions/72920010/pylance-wont-find-stubs-for-native-library-with-submodules
Edit: I also posted this question as an issue on pylance-release github repo, which might be better suited to find an answer. I'm having issues with Visual Studio Code python language server, which cannot find the stubs for a python binding library I am developing (https://github.com/pthom/lg_hello_imgui). I think the ...
I'm answering my own question since I had an answer from the pylance team in the meantime. https://peps.python.org/pep-0484/#stub-files specifies that Modules and variables imported into the stub are not considered exported from the stub unless the import uses the import ... as ... form or the equivalent from ... impo...
3
4
72,912,915
2022-7-8
https://stackoverflow.com/questions/72912915/join-items-in-list-that-occur-before-and-after-keyword-python
I'm using a name entity recognition model to find names in a text string. For hyphenated names like Jane Miller-Smith, the NER model returns the names seperately like this: names = ['Jane','Miller','-','Smith'] What's a simple way to join the items before and after the '-' to one string in this list? So that I have a ...
Scan from right to left, replacing the three-element slices whenever a hyphen is found: >>> names = ['Jane', '-', 'Marie','Miller', '-','Smith'] >>> for i in reversed(range(len(names))): if names[i] == '-': names[i-1: i+2] = [f'{names[i-1]}-{names[i+1]}'] >>> names ['Jane-Marie', 'Miller-Smith'] An alternative is to l...
3
6
72,920,577
2022-7-9
https://stackoverflow.com/questions/72920577/mach-o-file-but-is-an-incompatible-architecture-have-arm64-need-x86-64
I have a problem when I run a .py file on a Macbook Air M1: [Running] python3 -u "/Users/kaiyuwei/Documents/graduation project/metaheuristics/run_CRO.py" Traceback (most recent call last): File "/Users/kaiyuwei/Library/Python/3.8/lib/python/site-packages/numpy/core/__init__.py", line 23, in <module> from . import multi...
I solved the problem by simply uninstalling numpy package: pip3 uninstall numpy and reinstalling it: pip3 install numpy
20
-4
72,914,731
2022-7-8
https://stackoverflow.com/questions/72914731/how-to-permute-dimmensions-in-tensorflow
I am able to permute the dimmension of the tensor: I'm able to do this in pytorch! But not in tensorflow! A = torch.rand(1, 2,5) A = A.permute(0,2,1) A.shape torch.Size([1, 5, 2]) Tensorflow (just a try,I don't know about this): A = tf.random.normal(1, 2,5) A = tf.keras.layers.Permute((0, 2, 1)) Not working
Use tf.transpose: import tensorflow as tf A = tf.random.normal((1, 2, 5)) A_t = tf.transpose(A, perm=[0, 2, 1]) print(A.shape, A_t.shape) # (1, 2, 5) (1, 5, 2)
3
4
72,917,054
2022-7-8
https://stackoverflow.com/questions/72917054/generate-full-page-or-html-fragment-based-on-request-header-htmx
When using HTMX framework with Python Flask, you have to be able to: serve a request as a HTML fragment if it's done by HTMX (via AJAX) server a request as a full page if it's done by the user (e.g. entered directly in the browser URL bar) See Single-page-application with fixed header/footer with HTMX, with browsin...
This solution based on that we can use a dynamic variable when extending a base template. So depending on the type or the request, we use the full base template or a minimal base template that returns only our fragment's content. Lets call our base template for fragments base-fragments.html: {% block container %} {% en...
3
7
72,918,269
2022-7-9
https://stackoverflow.com/questions/72918269/can-i-use-pythons-functools-cache-based-on-identity
I would like to have a Python @cache decorator based on identity, not __hash__/__equal. That is to say, I would like the cached value for an argument ka NOT to be used for a different object ka2, even if ka == ka2. Is there a way to do that? In code: from functools import cache class Key: def __init__(self, value): sel...
Make a wrapper like Key that compares by the identity of its wrapped object, and wrap your caching function in a helper that uses the wrapper: class Id: __slots__="x", def __init__(self,x): self.x=x def __hash__(self): return id(self.x) def __eq__(self,o): return self.x is o.x def cache_id(f): @functools.cache def id_f...
4
2
72,904,923
2022-7-7
https://stackoverflow.com/questions/72904923/how-to-sort-methods-by-method-type-in-fastapi-swagger-api
How can I set a sort order for the API methods in the FastAPI Swagger autodocs? I would like all my methods grouped by type (GET, POST, PUT, DELETE). This answer shows how to do it in Java. How can I do it in Python? from fastapi import FastAPI app = FastAPI() @app.get("/") def list_all_components(): pass @app.get("/{c...
You can configure Swagger UI parameters through the FastAPI constructor. app = FastAPI(swagger_ui_parameters={"operationsSorter": "method"}) The full list of parameters can be found in the swagger documentation.
3
6
72,912,363
2022-7-8
https://stackoverflow.com/questions/72912363/create-a-dag-using-the-rest-api
Is it possible to create, by sending the DAG file contents, to Apache Airflow using the API? For example, it is possible to list all DAGs using the API curl -u "admin:admin" http://localhost:8080/api/v1/dags { "dags": [], "total_entries": 0 }
You can not create new DAGs via API. You can read a discussion about this request in the project https://github.com/apache/airflow/discussions/24744 which also lists the reasons why Airflow won't have it. In simple words by adding such API it means that the machine(s) where DAGs are deployed to need to have credentials...
4
5
72,909,692
2022-7-8
https://stackoverflow.com/questions/72909692/python-how-to-get-all-possible-bin-combinations-from-a-set-of-data-with-a-weigh
I have a list of numbers which all correspond to items of different weight: weights = [50, 40, 30, 100, 150, 12, 150, 10, 5, 4] I need to split the values into two bins with the caveat that the bin sum total cannot exceed 300. e.g. The simplest one I can think of is: bin1 = [150, 150] = 300 bin2 = [50, 40, 30, 100, 12...
one way is brute-forcing it by binning all possible permutations of the list there has to be a better (more clever) way of doing that - it's terribly slow. (but I'm supposed to be doing other things right now ;-)) from itertools import permutations max_bin_size = 300 weights = [50, 40, 30, 100, 150, 12, 150, 10, 5, 4] ...
4
2
72,908,362
2022-7-8
https://stackoverflow.com/questions/72908362/how-to-convert-discord-bot-commands-to-hybrid-command
I'm trying to convert my Discord Bot commands to hybrid commands. When I don't use the hybrid_command decorator, the slash commands work. The error says the callback must be a coroutine. What does it mean? What am I missing in the code? main.py class MyBot(commands.Bot): def __init__(self): intents=discord.Intents.all(...
First of all, your error means that decorators @commands.hybrid_command(...) and @app_commands.command() do not go well together. You either define hybrid command, slash command or text-chat command. Next moment, hybrid commands have commands.Context as their argument so we need to replace interaction parameter with th...
3
6
72,907,685
2022-7-8
https://stackoverflow.com/questions/72907685/idiomatic-way-to-check-if-a-value-is-inside-an-enum
I want to check if some string value exists in the values set of some Enum. Here is what I do: from enum import Enum class Color(str, Enum): RED = "red" GREEN = "green" YELLOW = "yellow" s = "red" # s = "blue" if any(s == c.value for c in Color): print(Color(s)) When I checked the documentation I found that: The Enum...
You can test values against _value2member_map_, a dict attribute of the Enum sub-class that maps values to member classes, if you prefer not to clutter up your code with a try-except block: if s in Color._value2member_map_: print(Color(s))
3
2
72,900,603
2022-7-7
https://stackoverflow.com/questions/72900603/create-non-existent-functions-by-a-single-click-in-vs-code-python
Other IDE's like PyCharm, IntelliJ, etc. have a feature where if it finds a function being called that is undefined, you can right-click it and click 'create method' or something similar to automatically create the function definition. It helps out a lot in TDD. Is there something similar in VS Code?
You can install the My Code Actions extension, here is a simple example: Configure in settings.json file: // settings.json file { "my-code-actions.actions": { "[python]": { "create new methond {{diag:$1}}": { "diagnostics": ["\"(.*?)\" is not defined"], "text": "def {{diag:$1}}():\n pass\n", "where": "afterLast", } } }...
5
6
72,905,444
2022-7-8
https://stackoverflow.com/questions/72905444/calculate-time-difference-between-two-dates-in-the-same-column-in-pandas
I have a column (DATE) with multiple data times and I want to find the difference in minutes from date to date and store it into a new column (time_interval). This is what I have tried: df['time_interval'] = (df['DATE'],axis=0 - df['DATE'],axis=1) * 24 * 60
Depending on how you'd care to store the differences, either df = pd.DataFrame(data=['01-01-2006 00:53:00', '01-01-2006 01:53:00', '01-01-2006 02:53:00', '01-01-2006 03:53:00', '01-01-2006 04:53:00'], columns=['DATE']) df['DATE'] = pd.to_datetime(df['DATE']) df['time_interval'] = df['DATE'].diff().fillna(timedelta(0))....
3
4
72,902,269
2022-7-7
https://stackoverflow.com/questions/72902269/sqlalchemy-pyodbc-how-to-trust-certificate
I have a python script using pyodbc that connects to a remote server with sql server running on it. I have a package I wrote with functions using sqlalchemy that I was able to use on one of my computers. I connected with this string: driver = 'SQL+Server+Native+Client+11.0' engine_string = prefix + '://' + username + '...
The connection error is due to a change in default behavior for the newest versions of SQL Server Drivers (ODBC v18+, JDBC v10+, .Net Microsoft.Data.SqlClient v4.0+). ODBC release notes: https://techcommunity.microsoft.com/t5/sql-server-blog/odbc-driver-18-0-for-sql-server-released/ba-p/3169228 The correct ODBC keyword...
4
7
72,901,860
2022-7-7
https://stackoverflow.com/questions/72901860/effective-way-to-regexp-match-pandas-and-strip-inside-df
Hoping someone on here is kind enough to at least point me in the right direction. Overall, I'm trying to match regex for each row and produce the below output (in 'desired example output'). To elaborate, data is being matched from a 'Device Pool' column from a rather large CSV (all settings from a phone). I need to: ...
You can use df['Device Pool'] = df['Device Pool'].str.replace(r'.*-D(\d+).*', r'\1', regex=True) Or, with Series.str.extract: df['Device Pool'] = df['Device Pool'].str.extract(r'-D(\d+)', expand=False) See a Pandas test: import pandas as pd df = pd.DataFrame({'Device Pool':['YART01-432-D098-00-1', 'VAR05-1435-D099-00...
4
3
72,899,320
2022-7-7
https://stackoverflow.com/questions/72899320/subtract-time-only-from-two-datetime-columns-in-pandas
I am looking to do something like in this thread. However, I only want to subtract the time component of the two datetime columns. For eg., given this dataframe: ts1 ts2 0 2018-07-25 11:14:00 2018-07-27 12:14:00 1 2018-08-26 11:15:00 2018-09-24 10:15:00 2 2018-07-29 11:17:00 2018-07-22 11:00:00 The expected output fo...
You need to set both datetimes to a common date first. One way is to use pandas.DateOffset: o = pd.DateOffset(day=1, month=1, year=2022) # the exact numbers don't matter # reset dates ts1 = df['ts1'].add(o) ts2 = df['ts2'].add(o) # subtract df['ts_delta'] = ts2.sub(ts1) As one-liner: df['ts_delta'] = df['ts2'].add((o:...
4
0
72,893,180
2022-7-7
https://stackoverflow.com/questions/72893180/flask-restful-error-request-content-type-was-not-application-json
I was following this tutorial and it was going pretty well. He then introduced reqparse and I followed along. I tried to test my code and I get this error {'message': "Did not attempt to load JSON data because the request Content-Type was not 'application/json'."} I don't know if I'm missing something super obvious but...
I don't know why you have an issue as far as I can tell you did copy him exactly how he did it. Here's a fix that'll work although I can't explain why his code works and yours doesn't. His video is two years old so it could be deprecated behaviour. import requests import json BASE = "http://127.0.0.1:5000/" payload = {...
9
6
72,881,807
2022-7-6
https://stackoverflow.com/questions/72881807/error-when-pip-installing-apache-flink-due-to-numpy
I'm trying to install Apache Flink with either python3 -m pip install apache-flink or pip3 install apache-flink, but both fail with an exit code 1 error: clang: error: the clang compiler does not support 'faltivec', please use -maltivec and include altivec.h explicitly error: Command "clang -Wno-unused-result -Wsign-co...
PyFlink on a M1 is not yet supported but will be from Flink 1.16 onwards, see https://issues.apache.org/jira/browse/FLINK-25188
3
5
72,899,058
2022-7-7
https://stackoverflow.com/questions/72899058/replace-values-from-a-dataframe-with-values-from-another-with-pandas
I have two dataframes with identical columns, but different values and different number of rows. import pandas as pd data1 = {'Region': ['Africa','Africa','Africa','Africa','Africa','Africa','Africa','Africa','Asia','Asia','Asia','Asia'], 'Country': ['South Africa','South Africa','South Africa','South Africa','South Af...
You can use merge and update: df.update(df.merge(df2, on=['Region', 'Country', 'Product', 'Year'], how='left', suffixes=('_old', None))) NB. the update is in place. output: Region Country Product Year Price 0 Africa South Africa ABC 2016 200.0 1 Africa South Africa ABC 2017 100.0 2 Africa South Africa ABC 2018 30.0 3...
3
4
72,895,097
2022-7-7
https://stackoverflow.com/questions/72895097/python-merging-3-different-dictionary-and-grouping-the-output
I have created 3 different dictionary in python , however I believe this cannot be merged into 1 dictionary e.g. NewDict due to a same Key in all 3 e.g. Name & Company. NewDict1 = {'Name': 'John,Davies', 'Company': 'Google'} NewDict2 = {'Name': 'Boris,Barry', 'Company': 'Microsoft'} NewDict3 = {'Name': 'Humphrey,Smith'...
Use a defaultdict: from collections import defaultdict dicts = [NewDict1, NewDict2, NewDict3] out = defaultdict(list) for d in dicts: out[d['Company']].append(d['Name']) dict(out) output: {'Google': ['John,Davies'], 'Microsoft': ['Boris,Barry', 'Humphrey,Smith']} as printed string for k,v in out.items(): print(f'{k}: ...
3
6
72,885,556
2022-7-6
https://stackoverflow.com/questions/72885556/smallest-i-with-1-i-1-i1
Someone reverse-sorted by 1/i instead of the usual -i and it made me wonder: What is the smallest positive integer case where that fails*? I think it must be where two consecutive integers i and i+1 have the same reciprocal float. The smallest I found is i = 6369051721119404: i = 6369051721119404 print(1/i == 1/(i+1)) ...
Suppose i is between 2^n and 2^(n+1) for some n. Then 1/i is between 2^(-n-1) and 2^-n. Its representation as double-precision floating point is 1.xxx...xxx * 2^(-n-1), where there are 52 x's. The smallest difference that can be expressed at that magnitude is 2^-52 * 2^(-n-1) = 2^(-n-53). 1/i and 1/(i+1) may get rounde...
4
4
72,887,988
2022-7-6
https://stackoverflow.com/questions/72887988/why-is-underscore-not-a-valid-name-in-new-python-match
_ score can be used as a variable name anywhere in Python, such as: _ = 10 print(_) However, it is not accepted here: d = dict(john = 10, owen=12, jenny=13) match d: case {'john' : 10, 'jenny': _}: print('does not work', _) ERROR: print('does not work', _) NameError: name '_' is not defined Yet, perfectly fine to us...
In a match statement, _ is a wildcard pattern. It matches anything without binding any names, so you can use it multiple times in the same case without having to come up with a bunch of different names for multiple values you don't care about.
4
5
72,883,838
2022-7-6
https://stackoverflow.com/questions/72883838/cant-connect-postgresql-database-to-fastapi
So, hi. Everything works with SQLite, but when I try to add PostgreSQL according to the user's guide on FastAPI, nothing works and I get: sqlalchemy.exc.ProgrammingError: (psycopg2.ProgrammingError) invalid dsn: invalid connection option "check_same_thread" My database.py is: from sqlalchemy import create_engine from s...
check_same_thread is an argument specific to sqlite. As you've specified a Postgres URL, you can remove that argument and you should have no issue creating an engine. i.e: from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker SQLALCHEMY_DATABASE_URL = "postgresql://user:passwor...
10
24
72,883,284
2022-7-6
https://stackoverflow.com/questions/72883284/splitting-str-in-list
I'm trying to write a function that returns list of lists with all possible combination. It's supposed to return this: [['Moscow', 'Oslo', 'Boston', 'Berlin'], ['Moscow', 'Oslo', 'Sydney', 'Berlin'], ['Moscow', 'Paris', 'Boston', 'Berlin'], ['Moscow', 'Paris', 'Sydney', 'Berlin']] and when I call the function pathway(...
This will do precisely what you specified: def pathway(city_from, city_array, city_to): return [[city_from, *c, city_to] for c in itertools.product(*city_array)]
4
4