question_id int64 59.5M 79.7M | creation_date stringdate 2020-01-01 00:00:00 2025-07-15 00:00:00 | link stringlengths 60 163 | question stringlengths 53 28.9k | accepted_answer stringlengths 26 29.3k | question_vote int64 1 410 | answer_vote int64 -9 482 |
|---|---|---|---|---|---|---|
71,942,122 | 2022-4-20 | https://stackoverflow.com/questions/71942122/creating-python-zip-for-aws-lambda-using-bazel | I've a monorepo that contains a set of Python AWS lambdas and I'm using Bazel for building and packaging the lambdas. I'm now trying to use Bazel to create a zip file that follows the expected AWS Lambdas packaging and that I can upload to Lambda. Wondering what's the best way to do this with Bazel? Below are a few dif... | Below are the changes I made to the previous answer to generate the lambda zip. Thanks @jvolkman for the original suggestion. project/BUILD.bazel: Added rule to generate requirements_lock.txt from project/requirements.txt load("@rules_python//python:pip.bzl", "compile_pip_requirements") compile_pip_requirements( name =... | 5 | 2 |
72,019,169 | 2022-4-26 | https://stackoverflow.com/questions/72019169/what-is-the-function-of-the-errors-parameter-to-subprocess-popen | The python subprocess docs only mention the errors parameter in passing: If encoding or errors are specified, or universal_newlines is true, file objects for stdin, stdout and stderr are opened in text mode using the specified encoding and errors or the io.TextIOWrapper default. I understand the usage of text and uni... | The errors parameter is described in the linked documentation for io.TextIOWrapper: errors is an optional string that specifies how encoding and decoding errors are to be handled. Pass 'strict' to raise a ValueError exception if there is an encoding error (the default of None has the same effect), or pass 'ignore' to ... | 5 | 5 |
72,001,505 | 2022-4-25 | https://stackoverflow.com/questions/72001505/how-to-get-unique-elements-and-their-firstly-appeared-indices-of-a-pytorch-tenso | Assume a 2*X(always 2 rows) pytorch tensor: A = tensor([[ 1., 2., 2., 3., 3., 3., 4., 4., 4.], [43., 33., 43., 76., 33., 76., 55., 55., 55.]]) torch.unique(A, dim=1) will return: tensor([[ 1., 2., 2., 3., 3., 4.], [43., 33., 43., 33., 76., 55.]]) But I also need the indices of every unique elements where they firstly... | One possible way to gain such indicies: unique, idx, counts = torch.unique(A, dim=1, sorted=True, return_inverse=True, return_counts=True) _, ind_sorted = torch.sort(idx, stable=True) cum_sum = counts.cumsum(0) cum_sum = torch.cat((torch.tensor([0]), cum_sum[:-1])) first_indicies = ind_sorted[cum_sum] For tensor A in ... | 7 | 8 |
72,002,559 | 2022-4-25 | https://stackoverflow.com/questions/72002559/converting-object-to-dictionary-key | I was wondering if there is an easy way to essentially have multiple keys in a dictionary for one value. An example of what I would like to achieve is as following: class test: key="test_key" def __str__(self): return self.key tester = test() dictionary = {} dictionary[tester] = 1 print(dictionary[tester]) print(dictio... | Personally, I think it's better to explicitly cast the object to a string, e.g. dictionary[str(tester)] = 1 That being said, if you're really really REALLY sure you want to do this, define the __hash__ and __eq__ dunder methods. No need to create a new data structure or change the existing code outside of the class de... | 6 | 4 |
71,973,392 | 2022-4-22 | https://stackoverflow.com/questions/71973392/importerror-cannot-import-rendering-from-gym-envs-classic-control | I'm working with RL agents, and was trying to replicate the finding of the this paper, wherein they make a custom parkour environment based on Gym open AI, however when trying to render this environment I run into. import numpy as np import time import gym import TeachMyAgent.environments env = gym.make('parametric-con... | I got (with help from a fellow student) it to work by downgrading the gym package to 0.21.0. Performed the command pip install gym==0.21.0 for this. Update, from Github issue: Based on https://github.com/openai/gym/issues/2779 This should be a problem of gymgrid, there is an open PR: wsgdrfz/gymgrid#1 If you want to us... | 10 | 8 |
72,001,132 | 2022-4-25 | https://stackoverflow.com/questions/72001132/python-typing-tuplestr-vs-tuplestr | What's the difference between tuple[str, ...] vs tuple[str]? (python typing) | giving a tuple type with ellipsis means that number of elements in this tuple is not known, but type is known: x: tuple[str, ...] = ("hi",) #VALID x: tuple[str, ...] = ("hi", "world") #ALSO VALID not using ellipsis means a tuple with specific number of elements, e.g.: y: tuple[str] = ("hi", "world") # Type Warning: Ex... | 17 | 20 |
71,949,467 | 2022-4-21 | https://stackoverflow.com/questions/71949467/pydantic-validation-error-for-basesettings-model-with-local-env-file | I'm developing a simple FastAPI app and I'm using Pydantic for storing app settings. Some settings are populated from the environment variables set by Ansible deployment tools but some other settings are needed to be set explicitly from a separate env file. So I have this in config.py class Settings(BaseSettings): # Pr... | If the environment file isn't being picked up, most of the time it's because it isn't placed in the current working directory. In your application in needs to be in the directory where the application is run from (or if the application manages the CWD itself, to where it expects to find it). In particular when running ... | 7 | 11 |
71,996,380 | 2022-4-25 | https://stackoverflow.com/questions/71996380/how-to-assign-a-function-to-a-route-functionally-without-a-route-decorator-in-f | In Flask, it is possible to assign an arbitrary function to a route functionally like: from flask import Flask app = Flask() def say_hello(): return "Hello" app.add_url_rule('/hello', 'say_hello', say_hello) which is equal to (with decorators): @app.route("/hello") def say_hello(): return "Hello" Is there such a simp... | You can use the add_api_route method to add a route to a router or an app programmtically: from fastapi import FastAPI, APIRouter def foo_it(): return {'Fooed': True} app = FastAPI() router = APIRouter() router.add_api_route('/foo', endpoint=foo_it) app.include_router(router) app.add_api_route('/foo-app', endpoint=foo_... | 4 | 8 |
71,996,274 | 2022-4-25 | https://stackoverflow.com/questions/71996274/upsampling-entire-groups-in-python | Suppose I have a dataframe like this import pandas as pd df = pd.DataFrame({'ID':[1,1,1,1,1,2,2,2,2], 'Order':[1,2,3,4,5,1,2,3,4]}) df ID Order 0 1 1 1 1 2 2 1 3 3 1 4 4 1 5 5 2 1 6 2 2 7 2 3 8 2 4 I need to upsample by entire blocks, so essentially creating new copies of the block for ID == 1, and ID == 2. So the ups... | So basically all you need to do is to get a copy of your data frame and concat it to the original one: df = pd.concat([df, df], ignore_index=True) | 4 | 2 |
71,969,299 | 2022-4-22 | https://stackoverflow.com/questions/71969299/how-to-disable-code-formatting-in-ipython | IPython has this new feature that reformats my prompt. Unfortunately, it is really buggy, so I want to disable it. I managed to do it when starting IPython from the command line by adding the following line in my ipython_config.py: c.TerminalInteractiveShell.autoformatter = None However, it does not work when I run it... | Apparently, the answer is: c.InteractiveShellEmbed.autoformatter = None | 8 | 1 |
71,990,420 | 2022-4-24 | https://stackoverflow.com/questions/71990420/how-do-i-efficiently-find-which-elements-of-a-list-are-in-another-list | I want to know which elements of list_1 are in list_2. I need the output as an ordered list of booleans. But I want to avoid for loops, because both lists have over 2 million elements. This is what I have and it works, but it's too slow: list_1 = [0,0,1,2,0,0] list_2 = [1,2,3,4,5,6] booleans = [] for i in list_1: boole... | If you want to use a vector approach you can also use Numpy isin. It's not the fastest method, as demonstrated by oda's excellent post, but it's definitely an alternative to consider. import numpy as np list_1 = [0,0,1,2,0,0] list_2 = [1,2,3,4,5,6] a1 = np.array(list_1) a2 = np.array(list_2) np.isin(a1, a2) # array([Fa... | 46 | 15 |
71,962,260 | 2022-4-22 | https://stackoverflow.com/questions/71962260/reading-data-in-vertex-ai-pipelines | This is my first time using Google's Vertex AI Pipelines. I checked this codelab as well as this post and this post, on top of some links derived from the official documentation. I decided to put all that knowledge to work, in some toy example: I was planning to build a pipeline consisting of 2 components: "get-data" (... | With some suggestions provided in the comments, I think I managed to make my demo pipeline work. I will first include the updated code: from kfp.v2 import compiler from kfp.v2.dsl import pipeline, component, Dataset, Input, Output from datetime import datetime from google.cloud import aiplatform from typing import Name... | 4 | 4 |
71,993,231 | 2022-4-24 | https://stackoverflow.com/questions/71993231/how-to-type-a-tuple-with-many-elements-in-python | I am experimenting with the typing module and I wanted to know how to properly type something like a Nonagon (a 9 point polygon), which should be a Tuple and not a List because it should be immutable. In 2D space, it would be something like this: Point2D = Tuple[float, float] Nonagon = Tuple[Point2D, Point2D, Point2D, ... | You can use the types module. All type hints come from types.GenericAlias. From the doc: Represent a PEP 585 generic type E.g. for t = list[int], t.__origin__ is list and t.__args__ is (int,). This means that you can make your own type hinting by passing the type arguments to the class itself. >>> Point2D = tuple[flo... | 9 | 4 |
71,990,386 | 2022-4-24 | https://stackoverflow.com/questions/71990386/calculating-divergence-and-curl-from-optical-flow-and-plotting-it | I'm using flow = cv2.calcOpticalFlowFarneback() to calculate optical flow in a video and it gives me a numpy array with a shape of (height, width, 2) that contains the Fx and Fy values for each pixel (flow[:,:,0] = Fx and flow[:,:,1] = Fy). For calculating the divergence I'm using np.gradient like this: def divergence_... | If I understand the way you've set up your axes correctly, you're missing a flow = np.swapaxes(flow, 0, 1) at the top of both divergence_npgrad and curl_npgrad. I tried applying your curl and divergence functions to simple functions where I already knew the correct curl and divergence. For example, I tried this functio... | 4 | 5 |
71,985,442 | 2022-4-24 | https://stackoverflow.com/questions/71985442/pycharm-is-generating-language-errors-for-python-version-3-6-although-interprete | The language interpreter is set to a Python 3.9 version: But a Python scratch file is being parsed by some kind of 3.6 interpreter: Note that I created in two different scratch files and the same error occurs. Why would this happen and is there a workaround [short of creating an entirely new project from scratch]? I ... | Following up on @bad_coder 's attempt to fix that will be paraphrased as: check the Run Configuration for pointing to a different python interpreter than the project level one That fix worked for me: Bring up the Run [Context menu] | Edit Configurations Change the Python interpreter to the appropriate one: Shown ... | 6 | 1 |
71,944,041 | 2022-4-20 | https://stackoverflow.com/questions/71944041/using-modern-typing-features-on-older-versions-of-python | So, I was writing an event emitter class using Python. Code currently looks like this: from typing import Callable, Generic, ParamSpec P = ParamSpec('P') class Event(Generic[P]): def __init__(self): ... def addHandler(self, action : Callable[P, None]): ... def removeHandler(self, action : Callable[P, None]): ... def fi... | I don't know if there was any reason to reinvent the wheel, but typing_extensions module is maintained by python core team, supports python3.7 and later and is used exactly for this purpose. You can just check python version and choose proper import source: import sys if sys.version_info < (3, 10): from typing_extensio... | 6 | 12 |
71,987,196 | 2022-4-24 | https://stackoverflow.com/questions/71987196/decrypt-in-go-what-was-encrypted-with-aes-in-cfb-mode-in-python | Issue I want to be able to decrypt in Go what was encrypted in Python. The encrypting/decrypting functions work respectively in each language but not when I am encrypting in Python and decrypting in Go, I am guessing there is something wrong with the encoding because I am getting gibberish output: Rx����d��I�K|�ap���k�... | The CFB mode uses a segment size which corresponds to the bits encrypted per encryption step, see CFB. Go only supports a segment size of 128 bits (CFB128), at least without deeper modifications (s. here and here). In contrast, the segment size in PyCryptodome is configurable and defaults to 8 bits (CFB8), s. here. The... | 4 | 7 |
71,986,643 | 2022-4-24 | https://stackoverflow.com/questions/71986643/userwarning-failed-to-initialize-numpy-module-compiled-against-api-version-0xf | (my2022) C:\Users\donhu>pip3 install torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/cu113 Looking in indexes: https://pypi.org/simple, https://download.pytorch.org/whl/cu113 Requirement already satisfied: torch in d:\programdata\anaconda3\envs\my2022\lib\site-packages (1.10.2) Collectin... | The problem cause by Use latest version of PyTorch (too new) Use latest version of conda (No support NumPy what PyTorch 1.11.0 need), then run Python from conda's virtual environment. Solution: Download Python 3.10.4 at https://www.python.org/ Install PyTorch like the command in the question, instlal Jupyter noteboo... | 11 | -2 |
71,986,268 | 2022-4-24 | https://stackoverflow.com/questions/71986268/pandas-constant-values-after-each-zero-value | Say I have the following dataframe: values 0 4 1 0 2 2 3 3 4 0 5 8 6 5 7 1 8 0 9 4 10 7 I want to find a pandas vectorized function (preferably using groupby) that would replace all nonzero values with the first nonzero value in that chunk of nonzero values, i.e. something that would give me values new 0 4 4 1 0 0 2... | Make a boolean mask to select the rows having zero and its following row, then use this boolean mask with where to replace remaining values with NaN, then use forward fill to propagate the values in forward direction. m = df['values'].eq(0) df['new'] = df['values'].where(m | m.shift()).ffill().fillna(df['values']) Res... | 5 | 4 |
71,984,449 | 2022-4-23 | https://stackoverflow.com/questions/71984449/how-to-add-an-extra-middle-step-into-a-list-comprehension | Let's say I have a list[str] object containing timestamps in "HH:mm" format, e.g. timestamps = ["22:58", "03:11", "12:21"] I want to convert it to a list[int] object with the "number of minutes since midnight" values for each timestamp: converted = [22*60+58, 3*60+11, 12*60+21] ... but I want to do it in style and us... | You could use an inner generator expression to do the splitting: [int(hh)*60 + int(mm) for hh, mm in (ts.split(':') for ts in timestamps)] Although personally, I'd rather use a helper function instead: def timestamp_to_minutes(timestamp: str) -> int: hh, mm = timestamp.split(":") return int(hh)*60 + int(mm) [timestam... | 26 | 33 |
71,984,170 | 2022-4-23 | https://stackoverflow.com/questions/71984170/pandas-dataframe-get-maximum-with-respect-to-other-entries | I have a Dataframe like this: name phase value BOB 1 .9 BOB 2 .05 BOB 3 .05 JOHN 2 .45 JOHN 3 .45 JOHN 4 .05 FRANK 1 .4 FRANK 3 .6 I want to find which entry in column 'phase' has the maximum value in column 'value'. If more than one share the same maximum value keep the first or a random valu... | You don't need to use groupby. Sort values by value and phase (adjust the order if necessary) and drop duplicates by name: out = (df.sort_values(['value', 'phase'], ascending=[False, True]) .drop_duplicates('name') .sort_index(ignore_index=True)) print(out) # Output name phase value 0 BOB 1 0.90 1 JOHN 2 0.45 2 FRANK 3... | 4 | 4 |
71,978,756 | 2022-4-23 | https://stackoverflow.com/questions/71978756/keras-symbolic-inputs-outputs-do-not-implement-len-error | I want to make an AI playing my custom environment, unfortunately, when I run my code, following error accrues: File "C:\Program Files\JetBrains\PyCharm Community Edition 2021.2\plugins\python-ce\helpers\pydev\_pydev_bundle\pydev_umd.py", line 198, in runfile pydev_imports.execfile(filename, global_vars, local_vars) #... | As mentioned here, you need to install a newer version of keras-rl: !pip install keras-rl2 You also need to add an extra dimension to your input shape and a Flatten layer at the end, since Keras expects this when working with the DQN agent: def build_model(states, actions): model = tf.keras.Sequential() model.add(Dens... | 4 | 8 |
71,973,225 | 2022-4-22 | https://stackoverflow.com/questions/71973225/generating-indices-of-a-2d-numpy-array | I want to generate a 2D numpy array with elements calculated from their positions. Something like the following code: import numpy as np def calculate_element(i, j, other_parameters): # do something return value_at_i_j def main(): arr = np.zeros((M, N)) # (M, N) is the shape of the array for i in range(M): for j in ran... | You can use np.indices() to generate the desired output: For example, np.indices((3, 4)) outputs: [[[0 0 0 0] [1 1 1 1] [2 2 2 2]] [[0 1 2 3] [0 1 2 3] [0 1 2 3]]] | 4 | 4 |
71,971,105 | 2022-4-22 | https://stackoverflow.com/questions/71971105/importerror-cannot-import-name-x-from-y | (ldm) C:\WBC\latent-diffusion-main>python scripts/txt2img.py --prompt "a sunset behind a mountain range, vector image" --ddim_eta 1.0 --n_samples 1 --n_iter 1 --H 384 --W 1024 --scale 5.0 Loading model from models/ldm/text2img-large/model.ckpt Traceback (most recent call last): File "scripts/txt2img.py", line 108, in <... | Looking at your error, it appears get_num_classes doesn't exist anymore. I verified this by looking that their github and docs. It was removed after this commit. | 4 | 4 |
71,967,845 | 2022-4-22 | https://stackoverflow.com/questions/71967845/error-when-using-visual-keras-for-plotting-model | I'm trying to visualize my Deep Learning model using visual keras, but i am getting an error which i am not sure i understand. This is my first time using visual keras, and i am not sure what to do. As an example !pip install visual keras import visualkeras import tensorflow as tf tf.keras.utils.plot_model(model, show_... | It is a bug as you can read here. The author suggests to install a newer version of the library: !pip install git+https://github.com/paulgavrikov/visualkeras --upgrade If for some reason you cannot update the version. Go to the source code of the library (where it was installed) and navigate to visualkeras/layered.py.... | 5 | 5 |
71,956,208 | 2022-4-21 | https://stackoverflow.com/questions/71956208/detect-thick-black-lines-in-image-with-opencv | I have the following image of a lego board with some bricks on it Now I am trying to detect the thick black lines (connecting the white squares) with OpenCV. I have already experimented a lot with HoughLinesP, converted the image to gray or b/w before, applied blur, ... Nonthing led to usable results. # Read image img... | Here I am presenting a repeated segmentation approach using color. This answer is based on the usage of LAB color space 1. Isolating the green lego block img = cv2.imread(image_path) lab = cv2.cvtColor(img, cv2.COLOR_BGR2LAB) a_component = lab[:,:,1] # binary threshold the a-channel th = cv2.threshold(a_component,127,... | 5 | 6 |
71,944,832 | 2022-4-20 | https://stackoverflow.com/questions/71944832/how-to-dump-a-hydra-config-into-yaml-with-target-fields | I instantiate a hydra configuration from a python dataclass. For example from dataclasses import dataclass from typing import Any from hydra.utils import instantiate class Model(): def __init__(self, x=1): self.x = x @dataclass class MyConfig: model: Any param: int static_config = MyConfig(model=Model(x=2), param='what... | See OmegaConf.to_yaml and OmegaConf.save: from omegaconf import OmegaConf # dumps to yaml string yaml_data: str = OmegaConf.to_yaml(my_config) # dumps to file: with open("config.yaml", "w") as f: OmegaConf.save(my_config, f) # OmegaConf.save can also accept a `str` or `pathlib.Path` instance: OmegaConf.save(my_config, ... | 5 | 4 |
71,938,799 | 2022-4-20 | https://stackoverflow.com/questions/71938799/python-asyncio-create-task-really-need-to-keep-a-reference | The documentation of asyncio.create_task() states the following warning: Important: Save a reference to the result of this function, to avoid a task disappearing mid execution. (source) My question is: Is this really true? I have several IO bound "fire and forget" tasks which I want to run concurrently using asyncio ... | There is an open issue at the cpython bug tracker at github about this topic I just found: https://github.com/python/cpython/issues/88831 Quote: asyncio will only keep weak references to alive tasks (in _all_tasks). If a user does not keep a reference to a task and the task is not currently executing or sleeping, the ... | 26 | 20 |
71,953,766 | 2022-4-21 | https://stackoverflow.com/questions/71953766/xarray-create-variables-attributes | I want to create a dataset with xarray and want to add attributes to variables while creating the dataset. The xarray documentation provides a way of adding global attribute. For example, as below: ds = xr.Dataset( data_vars=dict( 'temperature'=(["x", "y", "time"], temperature), 'precipitation'=(["x", "y", "time"], pre... | Yes, you can directly define variable attributes when defining the data_vars. You just need to provide the attributes in a dictionary Form. See also: https://xarray.pydata.org/en/stable/internals/variable-objects.html In your example above that would be: ds = xr.Dataset( data_vars=dict( temperature=(["x", "y", "time"],... | 4 | 9 |
71,949,010 | 2022-4-21 | https://stackoverflow.com/questions/71949010/google-cloud-sdk-python-was-not-found | After I install Google cloud sdk in my computer, I open the terminal and type "gcloud --version" but it says "python was not found" note: I unchecked the box saying "Install python bundle" when I install Google cloud sdk because I already have python 3.10.2 installed. so, how do fix this? Thanks in advance. | As mentioned in the document: Cloud SDK requires Python; supported versions are Python 3 (preferred, 3.5 to 3.8) and Python 2 (2.7.9 or later). By default, the Windows version of Cloud SDK comes bundled with Python 3 and Python 2. To use Cloud SDK, your operating system must be able to run a supported version of Pytho... | 16 | 0 |
71,946,233 | 2022-4-20 | https://stackoverflow.com/questions/71946233/typeerror-textiowrapper-seek-takes-no-keyword-arguments | I wanted to seek to the start of the file of to write from the start. In the documentation of python 3.9 io.IOBase.seek it is displayed seek has a parameter "whence" yet an error is being displayed: TypeError: TextIOWrapper.seek() takes no keyword arguments my code is: with open("t.txt",'a+') as f: f.seek(0,) print(f... | Yeah, it's a little bit weird. Take a look at help(f.seek): Help on built-in function seek: seek(cookie, whence=0, /) method of _io.TextIOWrapper instance Note the / slash. https://stackoverflow.com/a/24735582/8431111 It says "no keywords, please!". You can specify f.seek(0), or f.seek(0, 0). You just can't name that ... | 4 | 5 |
71,934,914 | 2022-4-20 | https://stackoverflow.com/questions/71934914/cannot-import-is-safe-url-from-django-utils-http-alternatives | I am trying to update my code to the latest Django version, The method is_safe_url() seems to be removed from new version of Django (4.0). I have been looking for an alternative for the past few hours with no luck. Does anyone know of any alternatives for the method in Django 4.0? | in Django 3.0 they have renamed is_safe_url to url_has_allowed_host_and_scheme. Here you can read more about it docs | 11 | 21 |
71,933,885 | 2022-4-20 | https://stackoverflow.com/questions/71933885/when-is-finally-run-in-a-python-generator | I think I might misunderstand how the finally clause of a try/except/finally block works in Python, for generators. In the following block of code, a generator starts a thread, and if the caller exits for any reason, the thread is cleaned up. That's the intention, at least. However, I've noticed that in some strange si... | finally in a generator is run under the same conditions as in any other code: when the execution of the try block finishes, as well as execution of any except block that got triggered, the finally runs. However, relative to most non-generator code, it is much easier in a generator for these conditions to just not happe... | 5 | 5 |
71,904,575 | 2022-4-17 | https://stackoverflow.com/questions/71904575/matplotlib-3d-scatter-plot-alpha-varies-when-viewing-different-angles | When creating 3D scatter plots with matplotlib I noticed that when the alpha (transparency) of the points is varied it will draw them differently depending on how you rotate the view. The example images below are the same plot rotated slightly, which causes the alpha values to mysteriously reverse. Is anyone familiar w... | UPDATE: a fix has been added to matplotlib as part of the future 3.11.0 release (not yet released at time of writing) I also posted this on the matplotlib github to see what the developers think. It appears to be a bug with a very low priority, per their latest response: "We have limited core developer resources and mp... | 5 | 2 |
71,898,644 | 2022-4-17 | https://stackoverflow.com/questions/71898644/how-to-use-python-typing-annotated | I'm having a hard time understanding from the documentation exactly what typing.Annotated is good for and an even harder time finding explanations/examples outside the documentation. Or does it "being good for something" depend entirely on what third party libraries you're using? In what (real-world) context would you ... | Annotated in python allows developers to declare the type of a reference and provide additional information related to it. name: Annotated[str, "first letter is capital"] This tells that name is of type str and that name[0] is a capital letter. On its own Annotated does not do anything other than assigning extra infor... | 142 | 143 |
71,882,419 | 2022-4-15 | https://stackoverflow.com/questions/71882419/fastapi-how-to-get-the-response-body-in-middleware | Is there any way to get the response content in a middleware? The following code is a copy from here. @app.middleware("http") async def add_process_time_header(request: Request, call_next): start_time = time.time() response = await call_next(request) process_time = time.time() - start_time response.headers["X-Process-T... | The response body is an iterator, which once it has been iterated through, it cannot be re-iterated again. Thus, you either have to save all the iterated data to a list (or bytes variable) and use that to return a custom Response, or initiate the iterator again. The options below demonstrate both approaches. In case yo... | 18 | 41 |
71,897,602 | 2022-4-16 | https://stackoverflow.com/questions/71897602/sqlalchemy-exc-programmingerror-psycopg2-programmingerror-cant-adapt-type-r | I created a database with 3 tables using PostgreSQL and flask-sqlalchemy. I am querying 3 tables to get only their ids then I check their ids to see if there's any similar one then add the similar one to the third table but anytime i run it i get this error sqlalchemy.exc.ProgrammingError: (psycopg2.ProgrammingError) c... | id is a query result. ids is a query row. To get one value from that row, you need to tell it which column (even if there is only one column): ids['student_id']. | 9 | 10 |
71,905,671 | 2022-4-17 | https://stackoverflow.com/questions/71905671/how-to-go-through-all-pydantic-validators-even-if-one-fails-and-then-raise-mult | Is it possible to call all validators to get back a full list of errors? @validator('password', always=True) def validate_password1(cls, value): password = value.get_secret_value() min_length = 8 if len(password) < min_length: raise ValueError('Password must be at least 8 characters long.') return value @validator('pas... | You can't raise multiple Validation errors/exceptions for a specific field in the way this is demonstrated in your question. Suggested solutions are given below. Option 1 Update Note that in Pydantic V2, @validator has been deprecated and was replaced by @field_validator. Please have a look at this answer for more deta... | 8 | 6 |
71,915,358 | 2022-4-18 | https://stackoverflow.com/questions/71915358/spark-read-bigquery-external-table | Trying to Read a external table from BigQuery but gettint a error SCALA_VERSION="2.12" SPARK_VERSION="3.1.2" com.google.cloud.bigdataoss:gcs-connector:hadoop3-2.2.0, com.google.cloud.spark:spark-bigquery-with-dependencies_2.12:0.24.2' table = 'data-lake.dataset.member' df = spark.read.format('bigquery').load(table) df... | As external tables are not supported in queries by spark, i tried the other way and got! def read_query_bigquery(project, query): df = spark.read.format('bigquery') \ .option("parentProject", "{project}".format(project=project))\ .option('query', query)\ .option('viewsEnabled', 'true')\ .load() return df project = 'da... | 4 | 4 |
71,861,779 | 2022-4-13 | https://stackoverflow.com/questions/71861779/mwaa-airflow-pythonvirtualenvoperator-requires-virtualenv | I am using AWS's MWAA service (2.2.2) to run a variety of DAGs, most of which are implemented with standard PythonOperator types. I bundle the DAGs into an S3 bucket alongside any shared requirements, then point MWAA to the relevant objects & versions. Everything runs smoothly so far. I would now like to implement a DA... | Airflow uses shutil.which to look for virtualenv. The installed virtualenv via requirements.txt isn't on the PATH. Adding the path to virtualenv to PATH solves this. The doc here is wrong https://docs.aws.amazon.com/mwaa/latest/userguide/samples-virtualenv.html import os from airflow.plugins_manager import AirflowPlugi... | 7 | 9 |
71,866,688 | 2022-4-14 | https://stackoverflow.com/questions/71866688/visualize-decision-tree-with-not-only-training-set-tag-distribution-but-also-te | We can visualize decision tree with training set distribution, for example from matplotlib import pyplot as plt from sklearn import datasets from sklearn.tree import DecisionTreeClassifier from sklearn import tree # Prepare the data data, can do row sample and column sample here iris = datasets.load_iris() X = iris.dat... | I don't think there is an sklearn method to do this (yet). Option 1: Changing the annotation plot of the tree by adding X_test information You can use the custom function below: def plot_tree_test(clf, tree_plot, X_test, y_test): n = len(tree_plot) cat = clf.n_classes_ # Getting the path for each item in X_test path = ... | 6 | 1 |
71,850,888 | 2022-4-13 | https://stackoverflow.com/questions/71850888/finding-cdrs-in-ngs-data | I have millions of sequences in fasta format and want to extract CDRs (CDR1, CDR2 and CDR3).I chose only one sequence as an example and tried to extract CDR1 but not able to extract CDR1. sequence:-'FYSHSAVTLDESGGGLQTPGGGLSLVCKASGFTFSSYGMMWVRQAPGKGLEYVAGIRNDA GDKRYGSAVQGRATISRDNGQSTVRLQLNNLRAEDTGTYFCAKESGCYWDSTHCIDAWGH... | I got it by the following method which works absolutely fine for me to find CDR1,2 and 3. All I need to define 3 different dictionaries having the definition ie prefix, suffix, max pin, fix position and pass them to the following code. Here I have performed this to find the CDR1, which gives me the desired output. dict... | 4 | 2 |
71,873,314 | 2022-4-14 | https://stackoverflow.com/questions/71873314/getting-error-value-is-not-a-valid-dict-when-using-pydantic-models-in-fastapi | I'm trying to use Pydantic models with FastAPI to make multiple predictions (for a list of inputs). The problem is that one can't pass Pydantic models directly to model.predict() function, so I converted it to a dictionary, however, I'm getting the following error: AttributeError: 'list' object has no attribute 'dict' ... | First, there are unecessary commas , at the end of both f1 and f2 attributes of your schema, as well as in the JSON payload you are sending. Hence, your schema should be: class Inputs(BaseModel): id: int f1: float f2: float f3: str Second, the 422 error is due to that the JSON payload you are sending does not match yo... | 5 | 3 |
71,907,619 | 2022-4-18 | https://stackoverflow.com/questions/71907619/python-not-found-for-node-gyp | I am trying to npm install for a project in my mac but for some reason it says python not found even though python3 command is working fine and I also set alias python to python3 in by ~/.zshrc and ~/.bash-profile and restarted several times but still the same issue. Screenshot of the issue. NOTE: See comments for the... | The problem is that Python is required in the system path to operate this command. Solutions: Install pyenv Install either Python 2.7 or Python 3.x: pyenv install 2.7.18 or pyenv install 3.9.11 (for example) If you have more than one python version, ensure one of them is set as global: pyenv global 3.9.11 Add pyenv to... | 6 | 15 |
71,915,309 | 2022-4-18 | https://stackoverflow.com/questions/71915309/token-used-too-early-error-thrown-by-firebase-admin-auths-verify-id-token-metho | Whenever I run from firebase_admin import auth auth.verify_id_token(firebase_auth_token) It throws the following error: Token used too early, 1650302066 < 1650302067. Check that your computer's clock is set correctly. I'm aware that the underlying google auth APIs do check the time of the token, however as outlined h... | This is how the firebase_admin.verify_id_token verifies the token: verified_claims = google.oauth2.id_token.verify_token( token, request=request, audience=self.project_id, certs_url=self.cert_url) and this is the definition of google.oauth2.id_token.verify_token(...) def verify_token( id_token, request, audience=None,... | 12 | 17 |
71,858,814 | 2022-4-13 | https://stackoverflow.com/questions/71858814/could-not-find-a-working-python-interpreter-unity-firebase | Could not find a working python interpreter. Please make sure one of the following is in your PATH: python python3 python3.8 python3.7 python2.7 python2 I installed python 3.10.4 Path is set in environment variables. Still not working. | How to set path: Find the path to install Python on your computer. To do this, open the Windows search bar and type python.exe. Select the Open file location option. Copy path of python folder. To add Python To PATH In User Variables: Open My Computer\Properties\Advanced system settings\Advanced Environment Variables\... | 6 | 6 |
71,895,146 | 2022-4-16 | https://stackoverflow.com/questions/71895146/pandas-to-latex-how-to-make-column-names-bold | When I'm using the pandas.to_latex function to create latex table, the column names are unfortunately not bold. What can I do to make it bold? | Update I have been told on GitHub that this is allready possible with plain pandas but there is some missing documentation, which will be updated soon. You can use the line below. result = df.style.applymap_index( lambda v: "font-weight: bold;", axis="columns" ).to_latex(convert_css=True) Old answer Here is a complete... | 5 | 3 |
71,915,551 | 2022-4-18 | https://stackoverflow.com/questions/71915551/prevent-mypy-errors-in-platform-dependent-python-code | I have something akin to the following piece of python code: import platform if platform.system() == "Windows": import winreg import win32api def do_cross_platform_thing() -> None: if platform.system() == "Windows": # do some overly complicated windows specific thing with winreg and win32api else: # do something reason... | Ok, after checking the Docs as @SUTerliakov so kindly suggested, it seems that i have to change my if platform.system() == "Windows" to this, semantically identical check: if sys.platform == "win32" Only this second version triggers some magic builtin mypy special case that identifies this as a platform check and ign... | 4 | 4 |
71,915,400 | 2022-4-18 | https://stackoverflow.com/questions/71915400/how-do-i-superimpose-an-image-in-the-back-of-a-matplotlib-plot | I'm trying to superimpose an image in the back of a matplotlib plot. It is being rendered as HTML in a flask website so I am saving the plot as an image before inserting it. The plot without the background image looks like this: The code that produces the above output is here: fname = 'scatter_averages.png' url_full ... | ax.imshow(image, extent=[x_min, x_max, y_min, y_max], aspect="auto") This will fix it. | 7 | 6 |
71,923,704 | 2022-4-19 | https://stackoverflow.com/questions/71923704/new-color-terminal-prograss-bar-in-pip | I find the new version pip(package installer for Python) has a colorful progress bar to show the downloading progress. How can I do that? Like this: | pip itself is using the rich package! In particular, their progress bar docs show this example: from rich.progress import track for n in track(range(n), description="Processing..."): do_work(n) | 7 | 13 |
71,925,980 | 2022-4-19 | https://stackoverflow.com/questions/71925980/cannot-perform-operation-another-operation-is-in-progress-in-pytest | I want to test some function, that work with asyncpg. If I run one test at a time, it works fine. But if I run several tests at a time, all tests except the first one crash with the error asyncpg.exceptions._base.InterfaceError: cannot perform operation: another operation is in progress. Tests: @pytest.mark.asyncio asy... | Okay, thanks to @Adelin I realized that I need to run each asynchronous test synchronously. I I'm new to asyncio so I didn't understand it right away and found a solution. It was: @pytest.mark.asyncio async def test_...(*args): result = await <some_async_func> assert result == excepted_result It become: def test_...(*... | 8 | 4 |
71,862,398 | 2022-4-13 | https://stackoverflow.com/questions/71862398/install-python-3-6-on-mac-m1 | I'm trying to run an old app that requires python < 3.7. I'm currently using python 3.9 and need to use multiple versions of python. I've installed pyenv-virtualenv and pyenv and successfully installed python 3.7.13. However, when I try to install 3.6.*, I get this: $ pyenv install 3.6.13 python-build: use openssl@1.1 ... | Copying from a GitHub issue. I successfully installed Python 3.6 on an Apple M1 MacBook Pro running Monterey using the following setup. There is probably some things in here that can be removed/refined... but it worked for me! #Install Rosetta /usr/sbin/softwareupdate --install-rosetta --agree-to-license # Install x86... | 16 | 30 |
71,922,124 | 2022-4-19 | https://stackoverflow.com/questions/71922124/python-convert-punycode-back-to-unicode | I'm trying to add contacts to Sendgrid from a db which occasionally is storing the user email in punycode example-email@xn--yaho-sqa.com which translates to example-email@yahóo.com in Unicode. Anyway if I try and add the ascii version there's an error because sendgrid doesn't accept it - however it does accept the Unic... | There is the xn-- ACE prefix in your encoded e-mail address: The ACE prefix for IDNA is "xn--" or any capitalization thereof. So apply the idna encoding (see Python Specific Encodings): codec idna Implement RFC 3490, see also encodings.idna. Only errors='strict' is supported. Result: 'yahóo.com'.encode('idna').deco... | 9 | 12 |
71,922,261 | 2022-4-19 | https://stackoverflow.com/questions/71922261/typeerror-setup-got-an-unexpected-keyword-argument-stage | I am trying to train my q&a model through pytorch_lightning. However while running the command trainer.fit(model,data_module) I am getting the following error: --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-72-b9cdaa88efa7> in <modu... | You need to add an extra argument stage=None to your setup method: def setup(self, stage=None): self.train_dataset = BioQADataset( self.train_df, self.tokenizer, self.source_max_token_len, self.target_max_token_len ) self.test_dataset = BioQADataset( self.test_df, self.tokenizer, self.source_max_token_len, self.target_... | 4 | 10 |
71,918,897 | 2022-4-19 | https://stackoverflow.com/questions/71918897/why-is-mypy-trying-to-instantiate-my-abstract-class-in-python | If I have a Python module like this: from abc import ABC, abstractmethod class AbstractClass(ABC): @abstractmethod def method(self): pass class ConcreteClass1(AbstractClass): def method(self): print("hello") class ConcreteClass2(AbstractClass): def method(self): print("hello") class ConcreteClass3(AbstractClass): def m... | The problem appears similar to mypy issues with abstract classes and dictionaries - for some reason, mypy can't typecheck this properly without a type annotation on the list: classes: list[Type[AbstractClass]] = [ ConcreteClass1, ConcreteClass2, ConcreteClass3, ] (Change list to List if you're on Python 3.8 or below) ... | 5 | 5 |
71,927,889 | 2022-4-19 | https://stackoverflow.com/questions/71927889/parse-yaml-with-dots-delimiter-in-keys | We use YAML configuration for services scaling. Usually it goes like this: service: scalingPolicy: capacity: min: 1 max: 1 So it's easy to open with basic PyYAML and parse as an dict to get config['service']['scalingPolicy']['capacity']['min'] result as 1. Problem is that some configs are built with dots delimiter e.g... | This is not trivial, it is much more easy to split a lookup with a key with dots into recursing into a nested data structure. Here you have a nested data structure and different [key] lookups mean different things at different levels. If you use ruamel.yaml in the default round-trip mode, you can add a class-variable t... | 4 | 3 |
71,920,941 | 2022-4-19 | https://stackoverflow.com/questions/71920941/how-to-obtain-a-token-for-a-user-with-payload-using-django-simple-jwt | I can get a correct token when calling the URL /token/ but I wish to create a token manually for the user when /login/ is called. urls.py: from django.urls import path from . import views from .views import MyTokenObtainPairView from rest_framework_simplejwt.views import ( TokenRefreshView, TokenVerifyView ) urlpatter... | Actually after Googling for an hour I finally got a solution from another post... Proper way to do this: refresh = RefreshToken.for_user(user) refresh['user_name'] = user.username refresh['first_name'] = user.first_name refresh['last_name'] = user.last_name refresh['full_name'] = user.get_full_name() return { 'refresh... | 4 | 9 |
71,914,320 | 2022-4-18 | https://stackoverflow.com/questions/71914320/mutex-lock-in-python3 | I'm using mutex for blocking part of code in the first function. Can I unlock mutex in the second function? For example: import threading mutex = threading.Lock() def function1(): mutex.acquire() #do something def function2(): #do something mutex.release() #do something | You certainly can do what you're asking, locking the mutex in one function and unlocking it in another one. But you probably shouldn't. It's bad design. If the code that uses those functions calls them in the wrong order, the mutex may be locked and never unlocked, or be unlocked when it isn't locked (or even worse, wh... | 4 | 4 |
71,916,052 | 2022-4-18 | https://stackoverflow.com/questions/71916052/tkinter-use-for-loop-to-display-multiple-images | I am trying to display multiple images (as labels) to the window but only the last images is displayed from tkinter import * from PIL import ImageTk, Image root = Tk() f = open("data/itemIDsList.txt") ids = [] for line in f: line = line.rstrip("\n") ids.append(line) f.close() for i in range(10): img = ImageTk.PhotoImag... | Each time you reassign img in the loop, the data of the previous image gets destroyed and can no longer be displayed. To fix this, add the images to a list to store them permanently: from tkinter import * from PIL import ImageTk, Image root = Tk() f = open("data/itemIDsList.txt") ids = [] for line in f: line = line.rst... | 4 | 5 |
71,914,660 | 2022-4-18 | https://stackoverflow.com/questions/71914660/subtract-columns-from-two-dfs-based-on-matching-condition | Suppose I have the following two DFs: DF A: First column is a date, and then there are columns that start with a year (2021, 2022...) Date 2021.Water 2021.Gas 2022.Electricity may-04 500 470 473 may-05 520 490 493 may-06 540 510 513 DF B: First column is a date, and then there are columns that start with a year (2021,... | Try this: dfai = dfa.set_index('Date') dfai.columns = dfai.columns.str.split('.', expand=True) dfbi = dfb.set_index('Date').rename(columns = lambda x: x.split('.')[0]) df_out = dfai.div(dfbi, level=0).round(1) df_out.columns = df_out.columns.map('.'.join) df_out.reset_index() Output: Date 2021.Water 2021.Gas 2022.Ele... | 4 | 2 |
71,911,077 | 2022-4-18 | https://stackoverflow.com/questions/71911077/python-multiprocessing-progress-approach | I've been busy writing my first multiprocessing code and it works, yay. However, now I would like some feedback of the progress and I'm not sure what the best approach would be. What my code (see below) does in short: A target directory is scanned for mp4 files Each file is analysed by a separate process, the process ... | I read all kinds of info about queues, pools, tqdm and I'm not sure which way to go. Could anyone point to an approach that would work in this case? Here's a very simple way to get progress indication at minimal cost: from multiprocessing.pool import Pool from random import randint from time import sleep from tqdm im... | 5 | 1 |
71,902,156 | 2022-4-17 | https://stackoverflow.com/questions/71902156/why-we-declare-metaclass-abc-abcmeta-when-use-abstract-class-in-python | When I was reading the code online, I have encountered the following cases of using abstract classes: from abc import abstractmethod,ABCMeta class Generator(object,metaclass=ABCMeta): @abstractmethod def generate(self): raise NotImplementedError("method not implemented") generator=Generator() generator.generate() The ... | You "need" the metaclass=ABCMeta to enforce the rules at instantiation time. generator=Generator() # Errors immediately when using ABCMeta generator.generate() # Only errors if and when you call generate otherwise Imagine if the class had several abstract methods, only some of which were implemented in a child. It mig... | 4 | 6 |
71,904,130 | 2022-4-17 | https://stackoverflow.com/questions/71904130/how-to-add-type-hints-in-pycharm | I often find myself having to start a debugging session in PyCharm only in order to inspect a variable and look up its class with something.__class__ so that I can insert the type hint into the code in order to make it more readable. Is there a way to do it automatically in PyCharm via a context action, in VSCode or ma... | Have you tried Adding type hints in the PyCharm? The VSCode-Python has not supported this feature, and I have submitted a feature request on GitHub. | 4 | 2 |
71,902,946 | 2022-4-17 | https://stackoverflow.com/questions/71902946/numba-no-implementation-of-function-functionbuilt-in-function-getitem-found | I´m having a hard time implementing numba to my function. Basically, I`d like to concatenate to arrays with 22 columns, if the new data hasn't been added yet. If there is no old data, the new data should become a 2d array. The function works fine without the decorator: @jit(nopython=True) def add(new,original=np.array(... | The main issue is that Numba assumes that original is a 1D array while this is not the case. The pure-Python code works because the interpreter it never execute the body of the loop for raw in original but Numba need to compile all the code before its execution. You can solve this problem using the following function p... | 6 | 8 |
71,902,175 | 2022-4-17 | https://stackoverflow.com/questions/71902175/create-venn-diagram-in-python-with-4-circles | How can I create a venn diagram in python from 4 sets? Seems like the limit in matplotlib is only 3? from matplotlib_venn import venn3 v = venn3( [ set(ether_list), set(bitcoin_list), set(doge_list), ], ) | Venn diagrams with circles can work only with <4 sets, because the geometrical properties of intersections (some won't be possible to show). Some python libraries that allow you to show venn diagrams with more exotic shapes are: pyvenn venn | 10 | 9 |
71,885,891 | 2022-4-15 | https://stackoverflow.com/questions/71885891/urllib3-exceptions-maxretryerror-httpconnectionpoolhost-localhost-port-5958 | At dawn my code was working perfectly, but today when I woke up it is no longer working, and I didn't change any line of code, I also checked if Firefox updated, and no, it didn't, and I have no idea what maybe, I've been reading the urllib documentation but I couldn't find any information from asyncio.windows_events i... | This error message... MaxRetryError(_pool, url, error or ResponseError(cause))urllib3.exceptions.MaxRetryError: HTTPConnectionPool(host='localhost', port=59587): Max retries exceeded with url: /session/b38be2fe-6d92-464f-a096-c43183aef6a8/element (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object ... | 10 | 12 |
71,894,769 | 2022-4-16 | https://stackoverflow.com/questions/71894769/keras-attributeerror-adam-object-has-no-attribute-name | I want to compile my DQN Agent but I get error: AttributeError: 'Adam' object has no attribute '_name', DQN = buildAgent(model, actions) DQN.compile(Adam(lr=1e-3), metrics=['mae']) I tried adding fake _name but it doesn't work, I'm following a tutorial and it works on tutor's machine, it's probably some new update cha... | Your error came from importing Adam with from keras.optimizer_v1 import Adam, You can solve your problem with tf.keras.optimizers.Adam from TensorFlow >= v2 like below: (The lr argument is deprecated, it's better to use learning_rate instead.) # !pip install keras-rl2 import tensorflow as tf from keras.layers import De... | 5 | 4 |
71,893,002 | 2022-4-16 | https://stackoverflow.com/questions/71893002/how-to-make-flask-handle-25k-request-per-second-like-express-js | So i am making a big social media app but i have a problem which framework to choose flask or express.js i like flask so much but it cant handle too much requests. Express.js can handle about 25k request per second (google). So is there anyway to make flask handle 25k request per second using gunicorn currently i am us... | You can use multithreads or gevent to increase gunicorn's concurrency. Option1 multithreads eg: gunicorn -w 4 --threads 100 -b 0.0.0.0:5000 your_project:app --threads 100 means 100 threads per process. -w 4 means 4 processes, so -w 4 --threads 100 means 400 requests at a time Option2 gevent worker eg: pip install geve... | 4 | 6 |
71,893,082 | 2022-4-16 | https://stackoverflow.com/questions/71893082/how-can-i-send-results-of-a-test-as-a-parameter-to-my-python-script | I created a scheduled task and my cypress script is being run once an hour. But after that I want to execute a python script and pass the result data there. Run the script and get the "results" as failed or success. $ cypress run --spec "cypress/integration/myproject/myscript.js" And pass the "results" data to a pytho... | There is a subprocess module which is able to run external commands, here is the example: import subprocess def get_test_output(): filepath = './cypress/integration/myproject/myscript.js' res = subprocess.run( ['echo', filepath], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, ) # In your case it will be: # res = sub... | 4 | 5 |
71,886,600 | 2022-4-15 | https://stackoverflow.com/questions/71886600/algorithm-for-ordering-data-so-that-neighbor-elements-are-as-identical-as-possib | I have a (potentially large) list data of 3-tuples of small non-negative integers, like data = [ (1, 0, 5), (2, 4, 2), (3, 2, 1), (4, 3, 4), (3, 3, 1), (1, 2, 2), (4, 0, 3), (0, 3, 5), (1, 5, 1), (1, 5, 2), ] I want to order the tuples within data so that neighboring tuples (data[i] and data[i+1]) are "as similar as p... | This isn't exact algorithm, just heuristic, but should be better that naive sorting: # you can sort first the data for lower total average score: # data = sorted(data) out = [data.pop(0)] while data: idx, t = min(enumerate(data), key=lambda k: dissimilar(out[-1], k[1])) out.append(data.pop(idx)) print(score(out)) Tes... | 47 | 10 |
71,888,628 | 2022-4-15 | https://stackoverflow.com/questions/71888628/allocate-an-integer-randomly-across-k-bins | I'm looking for an efficient Python function that randomly allocates an integer across k bins. That is, some function allocate(n, k) will produce a k-sized array of integers summing to n. For example, allocate(4, 3) could produce [4, 0, 0], [0, 2, 2], [1, 2, 1], etc. It should be randomly distributed per item, assignin... | Adapting Michael Szczesny's comment based on numpy's new paradigm: def allocate(n, k): return np.random.default_rng().multinomial(n, [1 / k] * k) This notebook verifies that it returns the same distribution as my brute-force approach. | 4 | 1 |
71,883,661 | 2022-4-15 | https://stackoverflow.com/questions/71883661/pytube-error-get-throttling-function-name-could-not-find-match-for-multiple | I am trying to download YouTube playlist from url "https://www.youtube.com/watch?v=uyVYfSNb_Pc&list=PLBxwSeQlMDNiNt72UmSvKBLsxPgGY_Jy-", but getting the error 'get_throttling_function_name: could not find match for multiple'. Code block is: ` from pytube import Playlist play_list = Playlist('https://www.youtube.com/wat... | Becuase youtube changed something on its end, and now you have to change pytube's ciper.py's function_patterns to the following r'a\.[a-zA-Z]\s*&&\s*\([a-z]\s*=\s*a\.get\("n"\)\)\s*&&\s*' r'\([a-z]\s*=\s*([a-zA-Z0-9$]{2,3})(\[\d+\])?\([a-z]\)' And you also have to change line 288 to this: nfunc=re.escape(function_matc... | 5 | 7 |
71,889,136 | 2022-4-15 | https://stackoverflow.com/questions/71889136/python-pandas-weighted-average-with-the-use-of-groupby-agg | I want the ability to use custom functions in pandas groupby agg(). I Know there is the option of using apply but doing several aggregations is what I want. Below is my test code that I tried to get working for the weighted average. Python Code import pandas as pd import numpy as np def weighted_avg(df, values, weights... | You can use x you have in lambda (specifically, use it's .index to get values you want). For example: import pandas as pd import numpy as np def weighted_avg(group_df, whole_df, values, weights): v = whole_df.loc[group_df.index, values] w = whole_df.loc[group_df.index, weights] return (v * w).sum() / w.sum() dfr = pd.D... | 4 | 2 |
71,882,225 | 2022-4-15 | https://stackoverflow.com/questions/71882225/slicing-of-a-scanned-image-based-on-large-white-spaces | I am planning to split the questions from this PDF document. The challenge is that the questions are not orderly spaced. For example the first question occupies an entire page, second also the same while the third and fourth together make up one page. If I have to manually slice it, it will be ages. So, I thought to sp... | We may solve it using (mostly) morphological operations: Read the input image as grayscale. Apply thresholding with inversion. Automatic thresholding using cv2.THRESH_OTSU is working well. Apply opening morphological operation for removing small artifacts (using the kernel np.ones(1, 3)) Dilate horizontally with very ... | 5 | 8 |
71,878,323 | 2022-4-14 | https://stackoverflow.com/questions/71878323/adaptive-resizing-for-a-tkinter-text-widget | I have been attempting to create a application that contains two Text() widgets, both of which can dynamically resize when the window size is changed. Before I have always used the root.pack() manager, with fill='both' and expand=True. While this works for LabelFrames and most other widgets, it does not work when a Tex... | Tkinter will try to honor the requested size of a text widget. Since you didn't specify a size, the text widget will request a size of 80x24. When you resize the window smaller, pack tries to make room for everything at its requested size, and it does so in stacking order. As the window shrinks, there's room for all of... | 4 | 3 |
71,875,067 | 2022-4-14 | https://stackoverflow.com/questions/71875067/adding-text-labels-to-a-plotly-scatter-plot-for-a-subset-of-points | I have a plotly.express.scatter plot with thousands of points. I'd like to add text labels, but only for outliers (eg, far away from a trendline). How do I do this with plotly? I'm guessing I need to make a list of points I want labeled and then pass this somehow to plotly (update_layout?). I'm interested in a good way... | You have the right idea: you'll want to have the coordinates of your outliers, and use Plotly's text annotations to add text labels to these points. I am not sure how you want to determine outliers, but the following is an example using the tips dataset. import pandas as pd from sklearn import linear_model import plotl... | 4 | 4 |
71,858,905 | 2022-4-13 | https://stackoverflow.com/questions/71858905/does-urllib3-support-http-2-requests-will-it | I know the following about various python HTTP libraries: Requests does not support HTTP/2 requests. Hyper does support HTTP/2 requests, but is archived as of early 2021 and wouldn't be a good choice for new projects. HTTPX does support HTTP/2, but this support is optional, requires installing extra dependencies, and ... | I asked about this in the urllib3 discord, and got an answer from one of the maintainers that corroborates what Tim Roberts commented; Proper HTTP/2 implementations require async/await to take advantage of the main different feature in HTTP/2, which is making requests in parallel. urllib3 in particular is not planning... | 10 | 9 |
71,867,872 | 2022-4-14 | https://stackoverflow.com/questions/71867872/checking-if-the-number-is-a-decimal-decimal-type-in-python | Variable 'a' could be of type - int/float/decimal.Decimal (but not a string) I want to check if its a decimal.Decimal type. Following works: import decimal a = decimal.Decimal(4) if type(a) is decimal.Decimal: print('yes decimal') else: print('not decimal') But, is there a righter way of doing the same? tnx. | Use isinstance which outputs True or False. result = isinstance(a, decimal.Decimal) print(result) | 5 | 6 |
71,864,620 | 2022-4-13 | https://stackoverflow.com/questions/71864620/pandas-how-to-avoid-map-converting-int-to-floats | I have a dictionary: matches = {282: 285, 266: 277, 276: 293, 263: 264, 286: 280, 356: 1371, 373: 262, 314: 327, 294: 290, 285: 282, 277: 266, 293: 276, 264: 263, 280: 286, 1371: 356, 262: 373, 327: 314, 290: 294} And a df, like so: team_id 0 327 1 293 2 373 3 282 4 314 5 263 6 280 7 354 8 264 9 294 10 1371 11 262 12... | This is because the np.nan or NaN (they are not exact same) values you see in the dataframe are of type float. It is a limitation that pitifully can't be avoided as long as you have NaN values in your code. Kindly read more in pandas' documentation here. Because NaN is a float, a column of integers with even one missi... | 5 | 5 |
71,863,508 | 2022-4-13 | https://stackoverflow.com/questions/71863508/cant-get-react-and-flask-cors-to-work-locally | I'm trying to get an application with a React/NodeJS frontend and a Flask backend to run locally for development purposes. I've been scouring StackOverflow for the last hour, but I can't seem to get past the CORS-issue. I have: import json from flask import Flask, request from flask_cors import CORS, cross_origin app =... | Turns out when working with JSON, it's important to make sure you let the other side know that you're sending application/json data. Modifying the fetch like this solved it: var jsonData = { "lastConversations": [this.state.chatInput] } console.log("Sending Chat: " + JSON.stringify(jsonData, null, 2)); fetch('http://my... | 7 | 0 |
71,862,034 | 2022-4-13 | https://stackoverflow.com/questions/71862034/how-to-add-type-hint-for-all-protocol-buffer-objects-in-python-functions | I want to add type hints for arguments in functions that accept any google protocol buffer object. def do_something(protobuf_obj: WHAT_IS_HERE): # protobuf_obj can be any protocol buffer instance pass What class should I put there from the google.protobuf library? | I ended up using the Message abstract base class. From the docs: class google.protobuf.message.Message Abstract base class for protocol messages. Protocol message classes are almost always generated by the protocol compiler. These generated types subclass Message and implement the methods shown below. So, now it look... | 4 | 8 |
71,860,253 | 2022-4-13 | https://stackoverflow.com/questions/71860253/how-to-deploy-a-python-dash-application-on-an-internal-company-server | I have written a Python Dash Application and it works completely fine on my local computer. Now, I want to be able to deploy this application on a server within the corporate network. I do NOT want to deploy this on Heroku etc because the datasource is an internal API. How do I go about deploying this application on th... | The code you are referring to, waitress-serve, is a command-line wrapper bound to the function waitress.serve provided by Waitress. You run it in your terminal or from a shell script. Waitress is a production-quality pure-Python WSGI server with very acceptable performance. It has no dependencies except ones which liv... | 4 | 3 |
71,857,720 | 2022-4-13 | https://stackoverflow.com/questions/71857720/how-to-put-a-matplotlib-figure-and-a-seaborn-figure-into-one-combined-matplotlib | I create 2 figures. One is a Seaborn figure and one is a matplotlib figure. Now I would like to combined those 2 figures into 1 combined figure. While the matplotlib figure is being displayed on the left hand side, the seaborn figure is not displayed. Here is the code #Plot the seaborn figure fig, ax = plt.subplots(fig... | Some hopefully clarifying comments: A figure is the top-level container for all plot elements. It's misleading/incorrect to refer to a matplotlib figure or seaborn figure, when really you're referring to an Axes. This creates one figure with two subplots. fig, ax = plt.subplots(1,2, figsize=(12,6)) Pure matplotlib plo... | 4 | 4 |
71,855,414 | 2022-4-13 | https://stackoverflow.com/questions/71855414/goeopandas-plot-shape-and-apply-opacity-outside-shape | I am plotting a city boundary (geopandas dataframe) to which I added a basemap using contextily. I would like to apply opacity to the region of the map outside of the city limits. The below example shows the opposite of the desired effect, as the opacity should be applied everywhere except whithin the city limits. impo... | You can create a new polygon that is a buffer on the total bounds of your geometry minus your geometry import osmnx as ox import geopandas as gpd import contextily as cx import matplotlib.pyplot as plt from shapely.geometry import box berlin = ox.geocode_to_gdf("Berlin,Germany") notberlin = gpd.GeoSeries( [ box(*box(*b... | 4 | 4 |
71,851,010 | 2022-4-13 | https://stackoverflow.com/questions/71851010/geopandas-plot-two-geo-dataframes-over-each-other-on-a-map | I am new to using Geopandas and plotting maps from Geo Dataframe. I have two Geo DataFrames which belong to the same city. But they are sourced from different sources. One contains the Geometry data for houses and another for Census tracts. I want to plot the houses' boundary on top of the tract boundry. Below is the f... | You probably need to set the correct coordinate reference system (crs). More info here An easy fix might be f, ax = plt.subplots() tract_data.to_crs(house_data.crs).plot(ax=ax) house_data.plot(ax=ax) | 5 | 6 |
71,775,175 | 2022-4-7 | https://stackoverflow.com/questions/71775175/convert-pandas-pivot-table-function-into-polars-pivot-function | I'm trying to convert some python pandas into polars. I'm stuck trying to convert pandas pivot_table function into polars. The following is the working pandas code. I can't seem to get the same behavior with the Polars pivot function. The polars pivot function forces the column parameter and uses the column values as h... | In Polars, we would not use a pivot table for this. Instead, we would use the group_by and agg functions. Using your data, it would be: import polars as pl df = pl.from_pandas(df) df.group_by("obj").agg(pl.all().n_unique()) shape: (2, 4) ┌──────┬───────┬───────┬──────┐ │ obj ┆ price ┆ value ┆ date │ │ --- ┆ --- ┆ --- ... | 5 | 7 |
71,808,640 | 2022-4-9 | https://stackoverflow.com/questions/71808640/filling-null-values-of-a-column-with-another-column | I want to fill the null values of a column with the content of another column of the same row in a lazy data frame in Polars. Is this possible with reasonable performance? | There's a function for this: fill_null. Let's say we have this data: import polars as pl df = pl.DataFrame({'a': [1, None, 3, 4], 'b': [10, 20, 30, 40] }).lazy() print(df.collect()) shape: (4, 2) ┌──────┬─────┐ │ a ┆ b │ │ --- ┆ --- │ │ i64 ┆ i64 │ ╞══════╪═════╡ │ 1 ┆ 10 │ │ null ┆ 20 │ │ 3 ┆ 30 │ │ 4 ┆ 40 │ └──────┴... | 6 | 8 |
71,850,031 | 2022-4-12 | https://stackoverflow.com/questions/71850031/polars-how-to-filter-using-in-and-not-in-like-in-sql | How can I achieve the equivalents of SQL's IN and NOT IN? I have a list with the required values. Here's the scenario: import pandas as pd import polars as pl exclude_fruit = ["apple", "orange"] df = pl.DataFrame( { "A": [1, 2, 3, 4, 5, 6], "fruits": ["banana", "banana", "apple", "apple", "banana", "orange"], "B": [5, ... | You were close. df.filter(~pl.col('fruits').is_in(exclude_fruit)) shape: (3, 5) ┌─────┬────────┬─────┬────────┬──────────┐ │ A ┆ fruits ┆ B ┆ cars ┆ optional │ │ --- ┆ --- ┆ --- ┆ --- ┆ --- │ │ i64 ┆ str ┆ i64 ┆ str ┆ i64 │ ╞═════╪════════╪═════╪════════╪══════════╡ │ 1 ┆ banana ┆ 5 ┆ beetle ┆ 28 │ │ 2 ┆ banana ┆ 4 ┆ ... | 21 | 35 |
71,837,398 | 2022-4-12 | https://stackoverflow.com/questions/71837398/pydantic-validations-for-extra-fields-that-not-defined-in-schema | I am using pydantic for schema validations and I would like to throw an error when any extra field that isn't defined is added to a schema. from typing import Literal, Union from pydantic import BaseModel, Field, ValidationError class Cat(BaseModel): pet_type: Literal['cat'] meows: int class Dog(BaseModel): pet_type: L... | Pydantic v2 You can use the extra field in the model_config class attribute to forbid extra attributes during model initialisation (by default, additional attributes will be ignored). For example: from pydantic import BaseModel, ConfigDict class Pet(BaseModel): model_config = ConfigDict(extra="forbid") name: str data =... | 45 | 67 |
71,769,359 | 2022-4-6 | https://stackoverflow.com/questions/71769359/how-to-use-python-poetry-to-install-package-to-a-virtualenv-in-a-standalone-fash | I've recently migrated to poetry for my dependencies management so pardon if my question is out of the scope of poetry here. Final goal My final goal is to create a RPM package that contains a virtualenv with my software installed along with all its dependencies. This RPM would then provide my software in isolation wit... | I'm late to the party, but I want to suggest a way to accomplish this. While poetry is amazing at managing your project's main and dev dependencies and locking their versions, I wouldn't rely on it while deploying on your situation. Here's a way to solve it: # export your dependencies in the requirements.txt format usi... | 6 | 16 |
71,814,658 | 2022-4-10 | https://stackoverflow.com/questions/71814658/python-typing-does-typeddict-allow-additional-extra-keys | Does typing.TypedDict allow extra keys? Does a value pass the typechecker, if it has keys which are not present on the definition of the TypedDict? | It depends. PEP-589, the specification of TypedDict, explicitely forbids extra keys: Extra keys included in TypedDict object construction should also be caught. In this example, the director key is not defined in Movie and is expected to generate an error from a type checker: m: Movie = dict( name='Alien', year=1979, ... | 18 | 15 |
71,805,911 | 2022-4-9 | https://stackoverflow.com/questions/71805911/elastic-transport-tlserror-tls-error-caused-bytlserrortls-error-caused-by-ss | Getting this error Trying to connect elasticsearch docker container with elasticsearch-python client. /home/raihan/dev/aims_lab/ai_receptionist/env/lib/python3.6/site-packages/elasticsearch/_sync/client/__init__.py:379: SecurityWarning: Connecting to 'https://localhost:9200' using TLS with verify_certs=False is insecu... | #disable certificate es = Elasticsearch(hosts="https://localhost:9200", basic_auth=(USER, PASS), verify_certs=False) #if getting an issue relevant to the certificate then: es = Elasticsearch(hosts="https://localhost:9200", basic_auth=(USER, PASS), ca_certs=CERTIFICATE, verify_certs=False) # I hope you know where to fin... | 10 | 19 |
71,831,415 | 2022-4-11 | https://stackoverflow.com/questions/71831415/downgrade-python-version-in-virtual-environment | I am always getting the same error regarding TensorFlow: ModuleNotFoundError: No module named 'tensorflow.contrib'. I am actually using Python version 3.9 but, reading online, it seems that version 3.7 is the last stable one that can work with TensorFlow version >2.0. Unfortunately I have started my project in a venv w... | Building on @chepner's comment above, since venvs are just directories, you can save your current state and start a fresh virtual environment instead. # Save current installs (venv) -> pip freeze -r > requirements.txt # Shutdown current env (venv) -> deactivate # Copy it to keep a backup -> mv venv venv-3.9 # Ensure yo... | 14 | 8 |
71,800,133 | 2022-4-8 | https://stackoverflow.com/questions/71800133/how-to-return-a-custom-404-not-found-page-using-fastapi | I am making a rick roll site for Discord and I would like to redirect to the rick roll page on 404 response status codes. I've tried the following, but didn't work: @app.exception_handler(fastapi.HTTPException) async def http_exception_handler(request, exc): ... | Update A more elegant solution would be to use a custom exception handler, passing the status code of the exception you would like to handle, as shown below: from fastapi.responses import RedirectResponse from fastapi.exceptions import HTTPException @app.exception_handler(404) async def not_found_exception_handler(requ... | 6 | 8 |
71,835,308 | 2022-4-11 | https://stackoverflow.com/questions/71835308/how-to-use-python-docx-template-to-insert-bullet-points | I'm trying to insert bullet point text with docx-template. I know that it can be done with the standard docx like below; document.add_paragraph('text to be bulleted', style='List Bullet') But I just can't get the same thing to work on docx-template; rt = RichText() rt.add('text to be bulleted', style='List Bullet') T... | Until this is officially supported (open issue), you might use a workaround (but only fixed indentations): In your word document add this (with a real single bullet list item): {% for bullet in bullets %} ● {{ bullet }}{% endfor %} Note that the {% endfor %} must be in the same line to avoid blank lines between the bu... | 4 | 5 |
71,768,274 | 2022-4-6 | https://stackoverflow.com/questions/71768274/how-to-extract-all-youtube-comments-using-youtube-api-python | Let's say I have a video_id having 8487 comments. This code returns only 4309 comments. def get_comments(youtube, video_id, comments=[], token=''): video_response=youtube.commentThreads().list(part='snippet', videoId=video_id, pageToken=token).execute() for item in video_response['items']: comment = item['snippet']['to... | From the answer of commentThreads, you have to add the replies parameter in order to retrieve the replies the comments might have. So, your request should look like this: video_response=youtube.commentThreads().list(part='id,snippet,replies', videoId=video_id, pageToken=token).execute() Then, modify your code accordin... | 8 | 6 |
71,764,921 | 2022-4-6 | https://stackoverflow.com/questions/71764921/how-to-delete-an-element-in-a-json-file-python | I am trying to delete an element in a json file, here is my json file: before: { "names": [ { "PrevStreak": false, "Streak": 0, "name": "Brody B#3719", "points": 0 }, { "PrevStreak": false, "Streak": 0, "name": "XY_MAGIC#1111", "points": 0 } ] } after running script: { "names": [ { "PrevStreak": false, "Streak": 0, "... | You will have to read the file, convert it to python native data type (e.g. dictionary), then delete the element and save the file. In your case something like this could work: import json filepath = 'data.json' with open(filepath, 'r') as fp: data = json.load(fp) del data['names'][1] with open(filepath, 'w') as fp: js... | 4 | 5 |
71,811,731 | 2022-4-9 | https://stackoverflow.com/questions/71811731/how-do-you-get-vs-code-to-write-debug-stdout-to-the-debug-console | I am trying to debug my Python Pytest tests in VS Code, using the Testing Activity on the left bar. I am able to run my tests as expected, with some passing and some failing. I would like to debug the failing tests to more accurately determine what is causing the failures. When I run an individual test in debug mode VS... | So After a lot of frustrating "debugging" I found a solution that worked for me (if you are using pytest as me): tldr Two solutions: downgrade your vscode python extension to v2022.2.1924087327 that will do the trick (or any version that had the debugpy<=1.5.1). Or, Launch the debbuger from the debug tab not the tes... | 13 | 16 |
71,824,282 | 2022-4-11 | https://stackoverflow.com/questions/71824282/sqlfluff-always-returns-templating-parsing-errors | I am trying to set up sqlfluff but for all of our queries it always returns this when running sqlfluff fix [1 templating/parsing errors found] Is there any way how I can force it to tell me the error that occurs? I tried running it on highes verbosity level but no useful information logged. | Use the command sqlfluff parse, which will give you the line numbers of where the parse violations are occurring. Once you've rectified all parse violations, run sqlfluff fix again. | 12 | 10 |
71,768,061 | 2022-4-6 | https://stackoverflow.com/questions/71768061/huggingface-transformers-classification-using-num-labels-1-vs-2 | question 1) The answer to this question suggested that for a binary classification problem I could use num_labels as 1 (positive or not) or 2 (positive and negative). Is there any guideline regarding which setting is better? It seems that if we use 1 then probability would be calculated using sigmoid function and if we... | Well, it probably is kind of late. But I want to point out one thing, according to the Hugging Face code, if you set num_labels = 1, it will actually trigger the regression modeling, and the loss function will be set to MSELoss(). You can find the code here. Also, in their own tutorial, for a binary classification prob... | 5 | 11 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.