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
63,860,576
2020-9-12
https://stackoverflow.com/questions/63860576/asyncio-event-loop-is-closed-when-using-asyncio-run
I'm getting started to AsyncIO and AioHTTP, and i'm writing some basic code to get familiar with the syntax. I tried the following code that should perform 3 requests concurrently: import time import logging import asyncio import aiohttp import json from aiohttp import ClientSession, ClientResponseError from aiocfscrap...
Update Originally I was recommending Greg's answer below: import asyncio import sys if sys.platform: asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy()) Turned out, using WindowsSelectorEventLoop has functionality issues such as: Can't support more than 512 sockets Can't use pipe Can't use subproc...
11
14
63,837,315
2020-9-10
https://stackoverflow.com/questions/63837315/change-environment-variables-saved-in-env-file-with-python-and-dotenv
I am trying to update .env environment variables with python. With os.environ I am able to view and change local environment variables, but I want to change the .env file. Using python-dotenv I can load .env entries into local environment variables .env File key=value test.py from dotenv import load_dotenv, find_doten...
Use dotenv.set_key. import dotenv dotenv_file = dotenv.find_dotenv() dotenv.load_dotenv(dotenv_file) print(os.environ["key"]) # outputs "value" os.environ["key"] = "newvalue" print(os.environ['key']) # outputs 'newvalue' # Write changes to .env file. dotenv.set_key(dotenv_file, "key", os.environ["key"])
19
53
63,906,100
2020-9-15
https://stackoverflow.com/questions/63906100/python-module-vs-sub-module-vs-package-vs-sub-package
In Python, What is the differences between module, sub-module, package and a sub-package?
package |-- __init__.py |-- module.py |-- sub_package |-- __init__.py |-- sub_module.py Consider packages and sub-packages as folders and sub-folders containing init.py file with other python files. modules are the python files inside the package. sub-modules are the python files inside the sub-package.
15
24
63,886,762
2020-9-14
https://stackoverflow.com/questions/63886762/tensorflow-none-of-the-mlir-optimization-passes-are-enabled-registered-1
I am using a very small model for testing purposes using tensorflow 2.3 and keras. Looking at my terminal, I get the following warning: I tensorflow/compiler/mlir/mlir_graph_optimization_pass.cc:118] None of the MLIR optimization passes are enabled (registered 1) However, the code works as expected. But what does this...
MLIR is being used as another solution to implementing and optimizing Tensorflow logic. This informative message is benign and is saying MLIR was not being used. This is expected as in TF 2.3, the MLIR based implementation is still being developed and proven, so end users are generally not expected to use the MLIR impl...
77
82
63,812,311
2020-9-9
https://stackoverflow.com/questions/63812311/how-to-create-children-with-uuid-with-pydantic
I try to create children of Foo, each should have its own uuid. In the real code no Instance of Foo will be created only it's children. The children will be saved in a database later, the uuid is to retrieve right objects from the database. In the first code snippet I tried to use the init method, which results in an A...
You could use the default_factory parameter: class Foo(BaseModel): id_: UUID = Field(default_factory=uuid4)
15
30
63,829,680
2020-9-10
https://stackoverflow.com/questions/63829680/type-assertion-in-mypy
Some functions like numpy.intersect1d return differents types (in this case an ndarray or a tuple of three ndarrays) but the compiler can only infer one of them, so if I like to make: intersection: np.ndarray = np.intersect1d([1, 2, 3], [5, 6, 2]) It throws a type warning: Expected type 'ndarray', got 'Tuple[ndarray, ...
According to the MyPy documentation, there are two ways to do type assertions: As an inline expression, you can use the typing.cast(..., ...) function. The docs say this is "usually" done to cast from a supertype to a subtype, but doesn't say you can't use it in other cases. As a statement, you can use assert isinstan...
11
19
63,872,924
2020-9-13
https://stackoverflow.com/questions/63872924/how-can-i-send-an-http-request-from-my-fastapi-app-to-another-site-api
I am trying to send 100 requests at a time to a server http://httpbin.org/uuid using the following code snippet from fastapi import FastAPI from time import sleep from time import time import requests import asyncio app = FastAPI() URL= "http://httpbin.org/uuid" # @app.get("/") async def main(): r = requests.get(URL) ...
requests is a synchronous library. You need to use an asyncio-based library to make requests asynchronously. httpx httpx is typically used in FastAPI applications to request external services. It provides synchronous and asynchronous clients which can be used in def and async def path operations appropriately. It is al...
63
97
63,876,013
2020-9-13
https://stackoverflow.com/questions/63876013/using-next-on-an-async-generator
A generator can be iterated step by step by using the next() built-in function. For example: def sync_gen(n): """Simple generator""" for i in range(n): yield i**2 sg = sync_gen(4) print(next(sg)) # -> 0 print(next(sg)) # -> 1 print(next(sg)) # -> 4 Using next() on an asynchronous generator does not work: import asynci...
Since Python 3.10 there are aiter(async_iterable) and awaitable anext(async_iterator) builtin functions, analogous to iter and next, so you don't have to rely on the async_iterator.__anext__() magic method anymore. This piece of code works in python 3.10: import asyncio async def async_gen(n): for i in range(n): yield ...
18
21
63,859,803
2020-9-12
https://stackoverflow.com/questions/63859803/cant-install-xmlsec-using-pip-command
pip install xmlsec commands throws the below error. ERROR: Command errored out with exit status 1: command: /home/xxx/PycharmProjects/saml_impl/saml_impl/venv/bin/python /home/sathia/PycharmProjects/saml_impl/saml_impl/venv/lib/python3.8/site-packages/pip/_vendor/pep517/_in_process.py build_wheel /tmp/tmpu_b5m5vz cwd: ...
Xmlsec listed here https://pypi.org/project/xmlsec/. The below command should install for download required native libraries. sudo apt-get install pkg-config libxml2-dev libxmlsec1-dev libxmlsec1-openssl
16
24
63,829,128
2020-9-10
https://stackoverflow.com/questions/63829128/how-can-i-make-bandit-skip-b101-within-tests
I'm using bandit to check my code for potential security issues: bandit -r git-repository/ However, the most common item found by bandit is B101. It is triggered by assert statements within tests. I use pytest, so this is not a concern, but a good practice. I've now created a .bandit file with [bandit] skips: B101 Bu...
A possible solution is to tell bandit to skip tests altogether. Assuming your code lives in a src subfolder, run bandit --configfile bandit.yaml --recursive src with the following bandit.yaml in the project's root directory # Do not check paths including `/tests/`: # they use `assert`, leading to B101 false positives....
30
9
63,827,339
2020-9-10
https://stackoverflow.com/questions/63827339/how-to-build-a-custom-data-generator-for-keras-tf-keras-where-x-images-are-being
I am working on Image Binarization using UNet and have a dataset of 150 images and their binarized versions too. My idea is to augment the images randomly to make them look like they are differentso I have made a function which inserts any of the 4-5 types of Noises, skewness, shearing and so on to an image. I could ha...
Custom Image Data Generator load Directory data into dataframe for CustomDataGenerator def data_to_df(data_dir, subset=None, validation_split=None): df = pd.DataFrame() filenames = [] labels = [] for dataset in os.listdir(data_dir): img_list = os.listdir(os.path.join(data_dir, dataset)) label = name_to_idx[dataset] for...
7
5
63,849,023
2020-9-11
https://stackoverflow.com/questions/63849023/find-replace-in-vs-code-jupyter-notebooks
Is there a way to find and replace text for Jupyter Notebooks in Visual Studio Code. I can do it for a specific cell by clicking to that cell and pressing Ctrl+H. But I cannot find a way to do it for all the cells in the entire notebook. This is how it looks like when I press Ctrl+H for specific cells:
This issue no longer exists in Visual Studio Code as of Version 1.59.1. You can use Ctrl + H to find/replace in the whole Jupyter Notebook.
18
4
63,889,494
2020-9-14
https://stackoverflow.com/questions/63889494/testing-for-mongodb-functionality-using-motor-asyncio-and-pytest
So I am trying to write several tests to test my functions that use an async MongoDB connection. To connect to MongoDB I use Motor with asyncio. I need help with mocking the Motor connection. My Code: commons.py mongo = None blacklist.py import commons class Blacklist(object): async def check_if_blacklisted(self, word...
You can mock the async MongoDB database with pytest-async-mongodb but have in mind that it's outdated and has dependency errors so you have to fix the dependencies versions as followings: mongomock==3.12.0 pyyaml==3.13 pytest-asyncio==0.10.0 pytest==3.6.4 With pytest-async-mongodb you can get the mocked DB in the test...
15
6
63,865,209
2020-9-12
https://stackoverflow.com/questions/63865209/plotly-how-to-show-both-a-normal-distribution-and-a-kernel-density-estimation-i
For a plotly figure factory distribution plot, the default distribution is kde (kernel density estimation): You can override the default by setting curve = 'normal' to get: But how can you show both kde and the normal curve in the same plot? Assigning a list like curve_type = ['kde', 'normal'] will not work. Complete...
The easiest thing to do is build another figure fig2 with curve_type = 'normal' and pick up the values from there using: fig2 = ff.create_distplot(hist_data, group_labels, curve_type = 'normal') normal_x = fig2.data[1]['x'] normal_y = fig2.data[1]['y'] And then inlclude those values in the first fig using fid.add_trac...
7
8
63,909,243
2020-9-15
https://stackoverflow.com/questions/63909243/what-is-the-correct-boilerplate-for-explicit-relative-imports
In PEP 366 - Main module explicit relative imports which introduced the module-scope variable __package__ to allow explicit relative imports in submodules, there is the following excerpt: When the main module is specified by its filename, then the __package__ attribute will be set to None. To allow relative imports wh...
The correct boilerplate is none, just write the explicit relative import and let the exception escape if someone tries to run the module as a script or has sys.path misconfigured: from . import baz The boilerplate given in PEP 366 is just there to show that the proposed change is sufficient to allow users to make dire...
7
5
63,816,790
2020-9-9
https://stackoverflow.com/questions/63816790/youtube-dl-error-youtube-said-unable-to-extract-video-data
I'm making a little graphic interface with Python 3 which should download a youtube video with its URL. I used the youtube_dl module for that. This is my code : import youtube_dl # Youtube_dl is used for download the video ydl_opt = {"outtmpl" : "/videos/%(title)s.%(ext)s", "format": "bestaudio/best"} # Here we give so...
Updating youtube-dl helped me. Depending on the way you installed it, here are the commands: youtube-dl --update (self-update) pip install -U youtube-dl (via python) brew upgrade youtube-dl (macOS + homebrew) choco upgrade youtube-dl (Windows + Chocolatey)
134
208
63,867,581
2020-9-13
https://stackoverflow.com/questions/63867581/install-python-3-7-via-google-colab-as-default-python
I need to use python3.7 as default python version to use in google colab(via this notebook ) for testing the faceswap GitHub project, by this codes: %cd "/content/faceit" !rm -rf faceswap !git clone https://github.com/deepfakes/faceswap.git %cd faceswap !python setup.py The reason is that,when i try to install faceswa...
According to this post, there are different ways to run a specific version of Python on Colab: Installing Anaconda Adding (fake) google.colab library Starting Jupyterlab Accessing it with ngrok The code sample is below # install Anaconda3 !wget -qO ac.sh https://repo.anaconda.com/archive/Anaconda3-2020.07-Linux-x86_6...
7
9
63,863,449
2020-9-12
https://stackoverflow.com/questions/63863449/oserror-cannot-load-library-c-program-files-r-r-4-0-2-bin-x64-r-dll-error-0
I am trying to import the rpy2 library into a Jupyter Notebook but I cannot get past this error. The PATH 'C:\Program Files\R\R-4.0.2\bin\x64' has been added. This is the only version of R installed on my computer. I have completely uninstalled and reinstalled R/Rstudio/Anaconda with no luck. Here is the full error: --...
1 - Windows + IDE For those not using Anaconda, add the following in Windows' environment variables PATH: C:\Program Files\R\R-4.0.3\bin\x64 Your R version may differ from "R-4.0.3" 2 - Anaconda Otherwise, check Grayson Felt's reply: I found a solution here. Adding the PATH C:\Users\username\Anaconda2;C:\Users\userna...
7
3
63,811,550
2020-9-9
https://stackoverflow.com/questions/63811550/plotly-how-to-display-graph-after-clicking-a-button
I want to use plotly to display a graph only after a button is clicked but am not sure how to make this work. My figure is stored in the following code bit fig1 = go.Figure(data=plot_data, layout=plot_layout) I then define my app layout with the following code bit: app.layout = html.Div([ #button html.Div(className='...
SUGGESTION 3 - dcc.Store() and dcc.Loading This suggestion uses a dcc.Store() component, a html.Button() and a dcc.Loading component to produce what I now understand to be the desired setup: Launch an app that only shows a button. Click a button to show a loading icon, and then display a figure. Click again to show t...
8
5
63,823,964
2020-9-10
https://stackoverflow.com/questions/63823964/importerror-cannot-import-name-sysconfig-from-distutils-usr-lib-python3-8
I installed pip3 using sudo apt-get install python3-pip after that when I run the following command to install django sudo pip3 install django I get this error: Traceback (most recent call last): File "/usr/bin/pip3", line 9, in from pip import main File "/usr/lib/python3/dist-packages/pip/init.py", line 14, in from p...
I have tried recently manually installing python3.9 version in my Ubuntu from 3.6 version using apt install python3.9. Then pip3 was broken. The issue is because distutils were not build for the 3.9 version. So in my case I ran apt install python3.9-distutils to resolve my issue. In your case make sure to modify 3.x ve...
33
75
63,871,252
2020-9-13
https://stackoverflow.com/questions/63871252/source-file-found-twice-error-with-mypy-0-780-in-python-for-vscode
In my python project, after upgrading mypy from 0.770 to 0.782 an error is received in files where there were previously no type errors: my_pkg_name\__init__.py: error: Source file found twice under different module names: 'top_pkg.my_pkg_name' and 'my_pkg_name' Found 1 error in 1 file (checked 1 source file) I'm pret...
I had a similar issue, but not via VSCode. The fix in my case was to remove an __init__.py file from a directory that was being included by adding it to the MYPYPATH, and so wasn't actually being treated as a module (so it shouldn't really have had the __init__.py file). You said you tried adding the --namespace-packag...
40
32
63,833,593
2020-9-10
https://stackoverflow.com/questions/63833593/how-to-run-fastapi-uvicorn-in-google-colab
I am trying to run a "local" web app on Google Colab using FastAPI / Uvicorn like some of the Flask app sample code I've seen but cannot get it to work. Has anyone been able to do this? Appreciate it. Installed FastAPI & Uvicorn successfully !pip install FastAPI -q !pip install uvicorn -q Sample app from fastapi impor...
You can use ngrok to export a port as an external url. Basically, ngrok takes something available/hosted on your localhost and exposes it to the internet with a temporary public URL. First install the dependencies !pip install fastapi nest-asyncio pyngrok uvicorn Create your app from fastapi import FastAPI from fastap...
15
36
63,885,007
2020-9-14
https://stackoverflow.com/questions/63885007/implementation-of-kleptography-in-python-setup-attack
My task is to reproduce the plot below: It comes from this journal (pg 137-145) In this article, the authors describe a kleptographic attack called SETUP against Diffie-Hellman keys exchange. In particular, they write this algorithm: Now, in 2 the authors thought "Maybe we can implement honest DHKE and malicious DHKE...
The problem is most easily understood using a concrete example: Alice has a device that generates Diffie-Hellman keys for her. On this device the malicious Diffie Hellman variant is implemented. Implementation of the malicious DH variant / SETUP The malicious DH variant is defined as follows, s. here, sec. 3.1: MDH1: F...
18
11
63,856,340
2020-9-12
https://stackoverflow.com/questions/63856340/vs-code-cant-open-ipynb-file
Have everyone already had this problem, where VS Code keeps loading all the time and won't open a ipynb file? I've tried to use python 3.7 but same problem. Also tried to reinstall both VS Code and Anaconda, no success. Here is my environment data: VS Code version: 1.49.0 Python extension version:v2020.8.108011 OS an...
In their official GitHub page, they are tracking this issue already. There is also a solution (kind of) right now. You have to maximize the terminal panel below and then restore the panel size (basically max and min with the arrow button). Then the Notebook loads and everything works fine. :D The workaround was in this...
20
3
63,829,991
2020-9-10
https://stackoverflow.com/questions/63829991/qt-qpa-plugin-could-not-load-the-qt-platform-plugin-xcb-in-even-though-it
I have installed gqcnn, Pyrep and autolab_core. After that, I executed the code that my coworker wrote and, it ran fine on his computer. However, I cannot run the code. The occurred error was python3.7/site-packages/cv2/qt/plugins/platforms" ... QFactoryLoader::QFactoryLoader() looking at "/home/bak/anaconda3/envs/pyre...
Finally, I find the solution! https://github.com/stepjam/PyRep/issues/76 The problem was loading Qt in the conda environment. When I typed qmake -version, the terminal window showed me the qt in anaconda. After I followed the first answer at the above URL, I can fix the problem.
11
4
63,901,755
2020-9-15
https://stackoverflow.com/questions/63901755/customizing-the-flask-admin-row-actions
I want to add another button next to the edit and delete icons on flask admin list view. In addition, I want to send that row data to a route as a post request. I know that I have to edit the admin/model/list.html template, but I am not getting how to add this functionalities. Can you provide any guidance?
You need to define custom action buttons for your view. This process is not described in the Flask-Admin tutorial but it is mentioned in the API description. POST method If you need to create a button for a POST method you should implement a jinja2 macro like this delete_row action. It may look like this (I named the f...
10
16
63,877,261
2020-9-14
https://stackoverflow.com/questions/63877261/how-to-group-a-dataframe-by-4-time-periods-and-key
I have a dataset that looks something like this: date area_key total_units timeatend starthour timedifference vps 2020-01-15 08:22:39 0 9603 2020-01-15 16:32:39 8 29400.0 0.32663265306122446 2020-01-13 08:22:07 0 10273 2020-01-13 16:25:08 8 28981.0 0.35447362064801075 2020-01-23 07:16:55 3 5175 2020-01-23 14:32:44 7 26...
First Data (Note: the further parts relates to the updates) Data is very limited, probably due to the complexity to simplify it, so I shall make some assumptions and write this as generic as possible, so you can customize it fast to your needs. Assumptions: You want to group by hours-windows ("hour_code") the data (th...
7
5
63,880,119
2020-9-14
https://stackoverflow.com/questions/63880119/numpy-create-array-of-the-max-of-consecutive-pairs-in-another-array
I have a numpy array: A = np.array([8, 2, 33, 4, 3, 6]) What I want is to create another array B where each element is the pairwise max of 2 consecutive pairs in A, so I get: B = np.array([8, 33, 33, 4, 6]) Any ideas on how to implement? Any ideas on how to implement this for more then 2 elements? (same thing but for...
A loop-free solution is to use max on the windows created by skimage.util.view_as_windows: list(map(max, view_as_windows(A, (2,)))) [8, 33, 33, 4, 6] Copy/pastable example: import numpy as np from skimage.util import view_as_windows A = np.array([8, 2, 33, 4, 3, 6]) list(map(max, view_as_windows(A, (2,))))
15
8
63,813,922
2020-9-9
https://stackoverflow.com/questions/63813922/what-is-the-difference-between-aiosqlite-and-sqlite-in-multi-threaded-mode
I'm trying to asynchronously process multiple files, and processing each file requires some reads and writes to an SQLite database. I've been looking at some options, and I found the aiosqlite module here. However, I was reading the SQLite documentation here, and it says that it supports multi-threaded mode. In fact, t...
First of all about threads: Sqlite ... can be used by multiple threads at one time It will still be not the same time because of GIL, Threads are always running concurrently (not in parallel). The only thing that with GIL you don't know when thread will be interrupted. But asyncio allows you to switch between threads...
11
7
63,881,231
2020-9-14
https://stackoverflow.com/questions/63881231/prefect-modulenotfounderror-when-running-from-ui
I'm following the Prefect tutorial available at: https://docs.prefect.io/core/tutorial/01-etl-before-prefect.html. The code can be downloaded from the git: https://github.com/PrefectHQ/prefect/tree/master/examples/tutorial The tutorials have a dependency to aircraftlib which is a directory under tutorials. I can execut...
This depends partially on the type of Flow Storage and Agent you are using. Since you are running with Prefect Server, I assume you are using Local Storage + a Local Agent; in this case, you need to make sure the aircraftlib directory is on your local importable Python PATH. There are a few ways of doing this: run you...
10
17
63,906,805
2020-9-15
https://stackoverflow.com/questions/63906805/why-is-self-not-type-hinted-in-python
I've been looking into type hinting my code but noticed that Python programmers typically do not type hint self in their programs Even when I look at the docs, they do not seem to type hint self, see here. This is from version 3.10 post forward declarations def __init__(self, value: T, name: str, logger: Logger) -> No...
mypy usually handles the type of self without needing an explicit annotation. You're running into a different problem - a method with no argument or return type annotations is not type-checked at all. For a method with no non-self arguments, you can avoid this by annotating self, but you can also avoid it by annotating...
7
9
63,901,790
2020-9-15
https://stackoverflow.com/questions/63901790/celery-how-to-get-task-name-by-task-id
Celery - bottom line: I want to get the task name by using the task id (I don't have a task object) Suppose I have this code: res = chain(add.s(4,5), add.s(10)).delay() cache.save_task_id(res.task_id) And then in some other place: task_id = cache.get_task_ids()[0] task_name = get_task_name_by_id(task_id) #how? print(f...
Finally found an answer. For anyone wondering: You can solve this by enabling result_extended = True in your celery config. Then: result = AsyncResult(task_id, app=celery_app) result.task_name #tasks.add
10
9
63,903,668
2020-9-15
https://stackoverflow.com/questions/63903668/beautiful-soup-extract-everything-between-two-tags
I am using BeautifulSoup to extract data from HTML files. I want to get all of the information between two tags. This means that if I have an HTML section like this: <h1></h1> Text <i>here</i> has no tag <div>This is in a div</div> <h1></h1> Then if I wanted all of the information between the first h1 and the second h...
One solution is to .extract() all content in front of first <h1> and after second <h1> tag: from bs4 import BeautifulSoup html_doc = ''' This I <b>don't</b> want <h1></h1> Text <i>here</i> has no tag <div>This is in a div</div> <h1></h1> This I <b>don't</b> want too ''' soup = BeautifulSoup(html_doc, 'html.parser') for...
7
4
63,892,211
2020-9-14
https://stackoverflow.com/questions/63892211/do-i-need-apt-get-update-and-upgrade-in-my-python-dockerfile
I have a very minimalist Dockerfile for my production Django application: FROM python:3.8 ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 RUN apt-get update && apt-get -y upgrade WORKDIR /app COPY requirements.txt ./ RUN pip install --upgrade pip && \ pip install -r requirements.txt COPY . . EXPOSE 8000 CMD [ "gun...
The base Docker Hub Linux distribution images like ubuntu:18.04 actually update themselves fairly regularly: if you docker pull ubuntu:18.04, wait a week, and repeat it, you will get a newer image. You're somewhat dependent on intermediate images, like python:3.8, doing the same thing. It is unusual, but not unheard-of...
19
18
63,891,547
2020-9-14
https://stackoverflow.com/questions/63891547/how-to-connect-amls-to-adls-gen-2
I would like to register a dataset from ADLS Gen2 in my Azure Machine Learning workspace (azureml-core==1.12.0). Given that service principal information is not required in the Python SDK documentation for .register_azure_data_lake_gen2(), I successfully used the following code to register ADLS gen2 as a datastore: fro...
According to this documentation,you need to enable the service principal. 1.you need to register your application and grant the service principal with Storage Blob Data Reader access. 2.try this code: adlsgen2_datastore = Datastore.register_azure_data_lake_gen2(workspace=ws, datastore_name=adlsgen2_datastore_name, acc...
10
13
63,888,136
2020-9-14
https://stackoverflow.com/questions/63888136/checking-if-a-blob-exist-in-python-azure
Since the new update of azure-storage-blob, the blockblobservice is depreciated How can I check that a blob exist ? This answer is not working with the new version of azure-storage-blob Faster Azure blob name search with python? I found this issue on GitHub : https://github.com/Azure/azure-sdk-for-python/issues/12744
Version 12.5.0 released on 2020-09-10 has now the exists method in the new SDK. For example, Sync: from azure.storage.blob import BlobClient blob = BlobClient.from_connection_string(conn_str="my_connection_string", container_name="mycontainer", blob_name="myblob") exists = blob.exists() print(exists) Async: import asy...
8
16
63,889,627
2020-9-14
https://stackoverflow.com/questions/63889627/is-python-a-functional-programming-language-or-an-object-oriented-language
According to tutorialspoint.com, Python is a functional programming language. "Some of the popular functional programming languages include: Lisp, Python, Erlang, Haskell, Clojure, etc." https://www.tutorialspoint.com/functional_programming/functional_programming_introduction.htm But other sources say Python is an obje...
Python, like many others, is a multi-paradigm language. You can use it as a fairly strictly imperative language, you can use it in a more object-oriented way, and you can use it in a more functional way. One important thing to note though is that functional is generally contrasted with imperative, object-oriented tends...
7
23
63,838,078
2020-9-10
https://stackoverflow.com/questions/63838078/plotting-networkx-graph-how-to-change-node-position-instead-of-resetting-every
I'm working on a project where I need to create a preview of nx.Graph() which allows to change position of nodes dragging them with a mouse. My current code is able to redraw whole figure immediately after each motion of mouse if it's clicked on specific node. However, this increases latency significantly. How can I up...
To expand on my comment above, in netgraph, your example can be reproduced with import numpy as np import matplotlib.pyplot as plt; plt.ion() import networkx as nx import netgraph nodes = np.array(['A', 'B', 'C', 'D', 'E', 'F', 'G']) edges = np.array([['A', 'B'], ['A', 'C'], ['B', 'D'], ['B', 'E'], ['C', 'F'], ['C', 'G...
7
4
63,873,082
2020-9-13
https://stackoverflow.com/questions/63873082/converting-a-simple-python-requests-post-to-rust-reqwest
I'm trying to use parts of this Python script (taken from here) in a Rust program I'm writing. How can I construct a reqwest request with the same content? def login(login_url, username, password=None, token=None): """Log in to Kattis. At least one of password or token needs to be provided. Returns a requests.Response ...
You are not using it, but with requests you'd use a session object to handle cookie persistence. You already found the equivalent in reqwest; a ClientBuilder has a cookie store method which enables the same functionality. Use the builder configured with this to create both requests, and any cookies on one response then...
8
16
63,854,588
2020-9-11
https://stackoverflow.com/questions/63854588/test-with-fastapi-testclient-returns-422-status-code
I try to test an endpoint with the TestClient from FastAPI (which is the Scarlett TestClient basically). The response code is always 422 Unprocessable Entity. This is my current Code: from typing import Dict, Optional from fastapi import APIRouter from pydantic import BaseModel router = APIRouter() class CreateRequest(...
You don't need to set headers manualy. You can use json argument insteed of data in client.post method. def test_create_50_users(): client = TestClient(router) body = { "number": 50, "ttl": 2.0 } response = client.post('/create', json=body) If you still want to use data attribute, you need to use json.dumps def test_c...
12
8
63,883,654
2020-9-14
https://stackoverflow.com/questions/63883654/typeerror-numpy-float64-object-is-not-callable-while-printing-f1-score
I am trying to run below code on Jupyter Notebook: lr = LogisticRegression(class_weight='balanced') lr.fit(X_train,y_train) y_pred = lr.predict(X_train) acc_log = round(lr.score(X_train, y_train) * 100, 2) prec_log = round(precision_score(y_train,y_pred) * 100,2) recall_log = round(recall_score(y_train,y_pred) * 100,2)...
Somewhere in your code (not shown here), there is a line which says f1_score = ... (with the written type being numpy.float64) so you're overriding the method f1_score with a variable f1_score (which is not callable, hence the error message). Rename one of the two to resolve the error.
7
17
63,880,081
2020-9-14
https://stackoverflow.com/questions/63880081/how-to-convert-a-torch-tensor-into-a-byte-string
I'm trying to serialize a torch tensor using protobuf and it seems using BytesIO along with torch.save() doesn't work. I have tried: import torch import io x = torch.randn(size=(1,20)) buff = io.BytesIO() torch.save(x, buff) print(f'buffer: {buff.read()}') to no avail as it results in b'' in the output! How should I b...
You need to seek to the beginning of the buffer before reading: import torch import io x = torch.randn(size=(1,20)) buff = io.BytesIO() torch.save(x, buff) buff.seek(0) # <-- this is what you were missing print(f'buffer: {buff.read()}') gives you this magnificent output: buffer: b'PK\x03\x04\x00\x00\x08\x08\x00\x00\x...
10
19
63,813,378
2020-9-9
https://stackoverflow.com/questions/63813378/how-to-json-normalize-a-column-in-pandas-with-empty-lists-without-losing-record
I am using pd.json_normalize to flatten the "sections" field in this data into rows. It works fine except for rows where the "sections" is an empty list. This ID gets completely ignored and is missing from the final flattened dataframe. I need to make sure that I have at least one row per unique ID in the data (some ID...
The best way to resolve the issue, is fix the dict If sections is an empty list, fill it with [{'answers': [{}]}] for i, d in enumerate(sample): if not d['sections']: sample[i]['sections'] = [{'answers': [{}]}] df = pd.json_normalize(sample) df2 = pd.json_normalize(df.to_dict(orient="records"), meta=["_id", "created_...
8
8
63,873,363
2020-9-13
https://stackoverflow.com/questions/63873363/how-to-use-log-scale-for-the-axes-of-a-seaborn-relplot
I tried drawing a relplot with log scaled axes. Making use of previous answers, I tried: import matplotlib.pyplot as plt import seaborn as sns f, ax = plt.subplots(figsize=(7, 7)) ax.set(xscale="log", yscale="log") tips = sns.load_dataset("tips") sns.relplot(x="total_bill", y="tip", hue='smoker', data=tips) plt.show() ...
You can use scatterplot and dont forget to mention your axes in your plot import matplotlib.pyplot as plt import seaborn as sns f, ax = plt.subplots(figsize=(7, 7)) tips = sns.load_dataset("tips") ax.set(xscale="log", yscale="log") sns.scatterplot(x="total_bill", y="tip", hue='smoker', data=tips,ax=ax) plt.show() Edit...
12
1
63,872,530
2020-9-13
https://stackoverflow.com/questions/63872530/change-specific-values-in-dataframe-if-one-cell-in-a-row-is-null
I have the following dataframe in pandas: >>>name food beverage age 0 Ruth Burger Cola 23 1 Dina Pasta water 19 2 Joel Tuna water 28 3 Daniel null soda 30 4 Tomas null cola 10 I want to put condistion that if value in food column is null, the age and beverage will change into ' ' (blank as well), I have wrote this cod...
Try with mask df[['beverage','age']] = df[['beverage','age']].mask(df['food'].isna(),'') df Out[86]: name food beverage age 0 Ruth Burger Cola 23 1 Dina Pasta water 19 2 Joel Tuna water 28 3 Daniel NaN 4 Tomas NaN
11
8
63,853,813
2020-9-11
https://stackoverflow.com/questions/63853813/how-to-create-routes-with-fastapi-within-a-class
So I need to have some routes inside a class, but the route methods need to have the self attr (to access the class' attributes). However, FastAPI then assumes self is its own required argument and puts it in as a query param This is what I've got: app = FastAPI() class Foo: def __init__(y: int): self.x = y @app.get("/...
For creating class-based views you can use @cbv decorator from fastapi-utils. The motivation of using it: Stop repeating the same dependencies over and over in the signature of related endpoints. Your sample could be rewritten like this: from fastapi import Depends, FastAPI from fastapi_utils.cbv import cbv from fast...
40
18
63,869,134
2020-9-13
https://stackoverflow.com/questions/63869134/converting-tensorflow-tensor-into-numpy-array
Problem Description I am trying to write a custom loss function in TensorFlow 2.3.0. To calculate the loss, I need the y_pred parameter to be converted to a numpy array. However, I can't find a way to convert it from <class 'tensorflow.python.framework.ops.Tensor'> to numpy array, even though there seem to TensorFlow f...
y_pred.numpy() works in TF 2 but AttributeError: 'Tensor' object has no attribute 'make_ndarray indicates that there are parts of your code that you are not running in Eager mode as you would otherwise not have a Tensor object but an EagerTensor. To enable Eager Mode, put this at the beginning of your code before anyth...
10
9
63,816,481
2020-9-9
https://stackoverflow.com/questions/63816481/faster-method-for-creating-spatially-correlated-noise
In my current project, I am interested in calculating spatially correlated noise for a large model grid. The noise should be strongly correlated over short distances, and uncorrelated over large distances. My current approach uses multivariate Gaussians with a covariance matrix specifying the correlation between all ce...
Faster approach: Generate spatially uncorrelated noise. Blur with Gaussian filter kernel to make noise spatially correlated. Since the filter kernel is rather large, it is a good idea to use a convolution method based on Fast Fourier Transform. import numpy as np import scipy.signal import matplotlib.pyplot as plt # ...
7
7
63,804,883
2020-9-9
https://stackoverflow.com/questions/63804883/including-and-distributing-third-party-libraries-with-a-python-c-extension
I'm building a C Python extension which makes use of a "third party" library— in this case, one that I've built using a separate build process and toolchain. Call this library libplumbus.dylib. Directory structure would be: grumbo/ include/ plumbus.h lib/ libplumbus.so grumbo.c setup.py My setup.py looks approximately...
The goal of this post is to have a setup.py which would create a source distribution. That means after running python setup.py sdist the resulting dist/grumbo-1.0.tar.gz could be used for installation via pip install grumbo-1.0.tar.gz We will start for a setup.py for Linux/MacOS, but then tweak to make it work for Wi...
7
14
63,858,511
2020-9-12
https://stackoverflow.com/questions/63858511/using-threads-in-combination-with-asyncio
I was looking for a way to spawn different threads (in my actual program the number of threads can change during execution) to perform a endless-running operation which would block my whole application for (at worst) a couple of seconds during their run. Because of this, I'm using the standard thread class and asyncio...
I would recommend creating a single event loop in a background thread and have it service all your async needs. It doesn't matter that your coroutines never end; asyncio is perfectly capable of executing multiple such functions in parallel. For example: def _start_async(): loop = asyncio.new_event_loop() threading.Thre...
7
12
63,862,118
2020-9-12
https://stackoverflow.com/questions/63862118/what-is-the-meaning-of-s-in-python
I see like this %(asctime)s in the logging module What is the meaning of %()s instead of %s? I only know %s means "string" and I can't find other information about %()s on the internet.
This is a string formatting feature when using the % form of Python string formatting to insert values into a string. The case you're looking at allows named values to be taken from a dictionary by providing the dictionary and specifying keys into that dictionary in the format string. Here's an example: values = {'city...
15
16
63,856,540
2020-9-12
https://stackoverflow.com/questions/63856540/how-to-check-to-make-sure-all-items-in-a-list-are-of-a-certain-type
I want to enforce that all items in a list are of type x. What would be the best way to do this? Currently I am doing an assert like the following: a = [1,2,3,4,5] assert len(a) == len([i for i in a if isinstance(i, int)]) Where int is the type I'm trying to enforce here. Is there a better way to do this?
I think you are making it a little too complex. You can just use all(): a = [1,2,3,4,5] assert all(isinstance(i, int) for i in a) a = [1,2,3,4,5.5] assert all(isinstance(i, int) for i in a) # AssertionError
17
13
63,853,854
2020-9-11
https://stackoverflow.com/questions/63853854/python-requirements-txt-specify-module-with-two-version-ranges
I'd like to specify the versions of tensorflow in a Python module. The agreeable versions are: (version >= 1.14.0 and version < 2.0) or (version >= 2.2) Does anyone know how to express this strange situation in a requirements.txt file? I believe there's a syntax for forbidding specific versions of a module, but I have...
From PEP 440 Version Specifiers: tensorflow >=1.14.0,!=2.0.*,!= 2.1.* The comma , represents a logical and. Note that requirements.txt files are used for pinning a deployment, I would generally only expect to ever see == specifiers used in those files.
7
10
63,840,851
2020-9-11
https://stackoverflow.com/questions/63840851/compare-current-row-value-to-previous-row-values
I have login history data from User A for a day. My requirement is that at any point in time the User A can have only one valid login. As in the samples below, the user may have attempted to login successfully multiple times, while his first session was still active. So, any logins that happened during the valid sessio...
Map the time like values in columns start_time and end_time to pandas TimeDelta objects and subtract 1 seconds from the 00:00:00 timedelta values in end_time column. c = ['start_time', 'end_time'] s, e = df[c].astype(str).apply(pd.to_timedelta).to_numpy().T e[e == pd.Timedelta(0)] += pd.Timedelta(days=1, seconds=-1) T...
8
2
63,851,453
2020-9-11
https://stackoverflow.com/questions/63851453/typeerror-singleton-array-arraytrue-cannot-be-considered-a-valid-collection
I want split the dataset that I have into test/train while also ensuring that the distribution of classified labels are same in both test/train. To do this I am using the stratify option but it is throwing an error as follows: X_full_train, X_full_test, Y_full_train, Y_full_test = train_test_split(X_values_full, Y_valu...
Per the sklearn documentation: stratifyarray-like, default=None If not None, data is split in a stratified fashion, using this as the class labels. Thus, it does not accept a boolean value like True or False, but the class labels themselves. So, you need to change: X_full_train, X_full_test, Y_full_train, Y_full_test...
20
45
63,823,043
2020-9-10
https://stackoverflow.com/questions/63823043/custom-names-for-pytest-parametrized-tests
I've got a pytest test that's parametrized with a @pytest.mark.parametrize decorator using a custom function load_test_cases() that loads the test cases from a yaml file. class SelectTestCase: def __init__(self, test_case): self.select = test_case['select'] self.expect = test_case['expect'] def __str__(self): # also tr...
You can define how your parametrized test names look using the ids parameter. This can be a list of strings, or a function that takes the current parameter as argument and returns the ID to be shown in the test name. So, in your case it is sufficient to use str as that function, as you have already implemented __str__ ...
7
10
63,826,328
2020-9-10
https://stackoverflow.com/questions/63826328/torch-nn-functional-vs-torch-nn-pytorch
While adding loss in Pytorch, I have the same function in torch.nn.Functional as well as in torch.nn. what is the difference ? torch.nn.CrossEntropyLoss() and torch.nn.functional.cross_entropy
Putting same text from PyTorch discussion forum @Alban D has given answer to similar question. F.cross entropy vs torch.nn.Cross_Entropy_Loss There isn’t much difference for losses. The main difference between the nn.functional.xxx and the nn.Xxx is that one has a state and one does not. This means that for a linear l...
14
16
63,821,633
2020-9-10
https://stackoverflow.com/questions/63821633/pandas-version-is-not-updated-after-installing-a-new-version-on-databricks
I am trying to solve a problem of pandas when I run python3.7 code on databricks. The error is: ImportError: cannot import name 'roperator' from 'pandas.core.ops' (/databricks/python/lib/python3.7/site-packages/pandas/core/ops.py) the pandas version: pd.__version__ 0.24.2 I run from pandas.core.ops import roperator...
It's really recommended to install libraries via cluster initialization script. The %sh command is executed only on the driver node, but not on the executor nodes. And it also doesn't affect Python instance that is already running. The correct solution will be to use dbutils.library commands, like this: dbutils.library...
9
8
63,821,179
2020-9-10
https://stackoverflow.com/questions/63821179/extract-images-from-pdf-in-high-resolution-with-python
I have managed to extract images from several PDF pages with the below code, but the resolution is quite low. Is there a way to adjust that? import fitz pdffile = "C:\\Users\\me\\Desktop\\myfile.pdf" doc = fitz.open(pdffile) for page_index in range(doc.pageCount): page = doc.loadPage(page_index) pix = page.getPixmap() ...
As stated in this issue for PyMuPDF, you have to use a matrix: issue on Github. The example given is: zoom = 2 # zoom factor mat = fitz.Matrix(zoom, zoom) pix = page.getPixmap(matrix = mat, <...>) Indicated in the issue is also that the default resolution is 72 dpi if you don't use a matrix which likely explains your ...
13
16
63,820,683
2020-9-9
https://stackoverflow.com/questions/63820683/with-pre-commit-how-to-use-some-hooks-before-commit-and-others-before-push
Some hooks can take a while to run, and I would like to run those before I push, but not before each particular commit (for example, pylint can be a bit slow). I've seen the following: Question: Using hooks at different stages mesos-commits mailing list archives Feature request: pre-commit or pre-push only hooks But ...
your configuration is correct, except that the whitespace hooks in pre-commit/pre-commit-hooks set stages themselves so they won't be affected by default_stages adjusting your configuration slightly: repos: - repo: https://github.com/pre-commit/pre-commit-hooks rev: v3.1.0 hooks: - id: end-of-file-fixer stages: [commit...
25
38
63,818,045
2020-9-9
https://stackoverflow.com/questions/63818045/python-frozen-dataclass-immutable-with-object-setattr
I used namedtuples for immutable data structures until I came across dataclasses, which I prefer in my use-cases (not relevant to the question). Now I learned that they are not immutable! At least not strictly speaking. setattr(frozen_dc_obj, "prop", "value") raises an exception. ok. But why does object.__setattr__(fro...
namedtuple defines __slots__ = () and hence you can't set any attribute (it doesn't have a __dict__). Frozen dataclasses on the other hand perform a manual check in their __setattr__ method and raise an exception if it's a frozen instance. Compare the following: >>> class Foo: ... __slots__ = () ... >>> f = Foo() >>> f...
7
6
63,808,915
2020-9-9
https://stackoverflow.com/questions/63808915/is-there-any-way-to-define-a-python-function-with-leading-optional-arguments
As we know, optional arguments must be at the end of the arguments list, like below: def func(arg1, arg2, ..., argN=default) I saw some exceptions in the PyTorch package. For example, we can find this issue in torch.randint. As it is shown, it has a leading optional argument in its positional arguments! How could be po...
A single function is not allowed to have only leading optional parameters: 8.6. Function definitions [...] If a parameter has a default value, all following parameters up until the “*” must also have a default value — this is a syntactic restriction that is not expressed by the grammar. Note this excludes keyword-onl...
7
2
63,809,051
2020-9-9
https://stackoverflow.com/questions/63809051/how-to-disable-pylint-warnings-and-messages-in-visual-studio-code
I am using a Mac and programming with Python on VS Code. After installing pylint, I had a bunch of warnings and messages. How do I disable these? I know about adding some lines to the pylintrc file, but I don't know where to find it or how to create it on a Mac.
Fully disable the linting Here is a link that explain how to do it : Disable Linting on VsCode. To do so, type Command + Shift + P (or Ctrl + Shift + P on PC) in VsCode. This will open a command prompt at the top of the window. Then type the command Python: Enable Linting, and select off. Another option is to choose no...
21
29
63,756,623
2020-9-5
https://stackoverflow.com/questions/63756623/how-to-remove-or-hide-y-axis-ticklabels-from-a-plot
I made a plot that looks like this I want to turn off the ticklabels along the y axis. And to do that I am using plt.tick_params(labelleft=False, left=False) And now the plot looks like this. Even though the labels are turned off the scale 1e67 still remains. Turning off the scale 1e67 would make the plot look bette...
seaborn is used to draw the plot, but it's just a high-level API for matplotlib. The functions called to remove the y-axis labels and ticks are matplotlib methods. After creating the plot, use .set(). .set(yticklabels=[]) should remove tick labels. This doesn't work if you use .set_title(), but you can use .set(ti...
13
27
63,738,389
2020-9-4
https://stackoverflow.com/questions/63738389/pandas-sampling-from-a-dataframe-according-to-a-target-distribution
I have a Pandas DataFrame containing a dataset D of instances drawn from a distribution x. x may be a uniform distribution for example. Now, I want to draw n samples from D, sampled according to some new target_distribution, such as a gaussian, that is in general different than x. How can I do this efficiently? Right n...
Rather than generating new points and finding a closest neighbor in df.x, define the probability that each point should be sampled according to your target distribution. You can use np.random.choice. A million points are sampled from df.x in a second or so for a gaussian target distribution like this: x = np.sort(df.x)...
8
11
63,793,662
2020-9-8
https://stackoverflow.com/questions/63793662/how-to-give-a-pydantic-list-field-a-default-value
I want to create a Pydantic model in which there is a list field, which left uninitialized has a default value of an empty list. Is there an idiomatic way to do this? For Python's built-in dataclass objects you can use field(default_factory=list), however in my own experiments this seems to prevent my Pydantic models f...
For pydantic you can use mutable default value, like: class Foo(BaseModel): defaulted_list_field: List[str] = [] f1, f2 = Foo(), Foo() f1.defaulted_list_field.append("hey!") print(f1) # defaulted_list_field=['hey!'] print(f2) # defaulted_list_field=[] It will be handled correctly (deep copy) and each model instance wi...
78
120
63,763,375
2020-9-6
https://stackoverflow.com/questions/63763375/python3-sqlalchemy-delete-duplicates
I'm using SQLAlchemy to manage a database and I'm trying to delete all rows that contain duplicates. The table has an id (primary key) and domain name. Example: ID| Domain 1 | example-1.com 2 | example-2.com 3 | example-1.com In this case I want to delete 1 instance of example-1.com. Sometimes I will need to delete mor...
Assuming your model looks something like this: import sqlalchemy as sa from sqlalchemy import orm Base = orm.declarative_base() class Domain(Base): __tablename__ = 'domain_names' id = sa.Column(sa.Integer, primary_key=True) domain = sa.Column(sa.String) Then you can delete the duplicates like this: # Create a query th...
6
4
63,753,584
2020-9-5
https://stackoverflow.com/questions/63753584/django-rest-framework-list-object-has-no-attribute-values
I have the code and error stacktrace below. I am trying to access localhost:8000/fundamentals/ but I get the error 'list' object has no attribute 'values' error web_1 | Traceback (most recent call last): web_1 | File "/usr/local/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner web_1 | r...
The issue here is with the BalanceSheetSerializer. The fields must be defined within class Meta instead of defining it as class variable. class BalanceSheetSerializer(serializers.ModelSerializer): class Meta: fields = [your_fields]
9
22
63,710,551
2020-9-2
https://stackoverflow.com/questions/63710551/how-to-format-the-y-or-x-axis-labels-in-a-seaborn-facetgrid
I want to format y-axis labels in a seaborn FacetGrid plot, with a number of decimals, and/or with some text added. import seaborn as sns import matplotlib.pyplot as plt sns.set(style="ticks") exercise = sns.load_dataset("exercise") g = sns.catplot(x="time", y="pulse", hue="kind", col="diet", data=exercise) #g.xaxis.se...
xaxis and yaxis are attributes of the plot axes, for a seaborn.axisgrid.FacetGrid type. In the linked answer, the type is matplotlib.axes._subplots.AxesSubplot p in the lambda expression is the tick label number. seaborn: Building structured multi-plot grids matplotlib: Creating multiple subplots Tested and working...
13
22
63,792,528
2020-9-8
https://stackoverflow.com/questions/63792528/boxplot-custom-width-in-seaborn
I am trying to plot boxplots in seaborn whose widths depend upon the log of the value of x-axis. I am creating the list of widths and passing it to the widths=widths parameter of seaborn.boxplot. However, I am getting that raise ValueError(datashape_message.format("widths")) ValueError: List of boxplot statistics and `...
Seaborn's boxplot doesn't seem to understand the widths= parameter. Here is a way to create a boxplot per x value via matplotlib's boxplot which does accept the width= parameter. The code below supposes the data is organized in a panda's dataframe. from matplotlib import pyplot as plt import numpy as np import pandas a...
9
5
63,748,542
2020-9-4
https://stackoverflow.com/questions/63748542/convert-docx-bytestream-to-pdf-bytestream-python
I currently have a program that generates a .docx document using the python-docx library. Upon completing the building of the .docx file I save it into a Bytestream as so file_stream = io.BytesIO() document.save(file_stream) file_stream.seek(0) Now, I need to convert this word document into a PDF. I have looked at a f...
This method is a little convoluted, but it works entirely in memory, and you get the option to add custom CSS to style the final document. Convert the DOCX bytestream to HTML using mammoth, and the resulting HTML to PDF using pdfkit. Here's an example # create a dummy docx file from docx import Document document = Docu...
8
7
63,757,304
2020-9-5
https://stackoverflow.com/questions/63757304/resizing-video-using-opencv-and-saving-it
I'm trying to re-size the video using opencv and then save it back to my system.The code works and does not give any error but output video file is corrupted. The fourcc I am using is mp4v works well with .mp4 but still the output video is corrupted. Need Help. import numpy as np import cv2 import sys import re vid="" ...
The problem is the VideoWriter initialization. You initialized: out = cv2.VideoWriter('Video_output.mp4', fourcc, FPS, FrameSize, 0) The last parameter 0 means, isColor = False. You are telling, you are going to convert frames to the grayscale and then saves. But there is no conversion in your code. Also, you are resi...
6
9
63,752,613
2020-9-5
https://stackoverflow.com/questions/63752613/asyncio-improperly-warns-about-streams-objects-are-garbage-collected-call-stre
I was implementing asynchronous MySQL query execution using python3.8's inbuilt asyncio package and an installed aiomysql package. Even though I have closed properly all the open cursor and connection, an error message keep on appearing on my console as follows. An open stream object is being garbage collected; call "s...
It seems like you may have just forgotten to close the event loop—in addition to await conn.wait_closed(), which @VPfB advised above. You must close the event loop when manually using lower level method calls such as asyncio.get_event_loop(). Specifically, self.loop.close() must be called. #db.py import asyncio class A...
7
1
63,737,969
2020-9-4
https://stackoverflow.com/questions/63737969/how-to-find-pid-of-a-process-by-python
friends: I am running a script in Linux: I can use the ps command get the process. ps -ef | grep "python test09.py&" but, how can I know the pid of the running script by given key word python test09.py& using python code? EDIT-01 I mean, I want to use the python script to find the running script python test09.py&'s p...
If you just want the pid of the current script, then use os.getpid: import os pid = os.getpid() However, below is an example of using psutil to find the pids of python processes running a named python script. This could include the current process, but the main use case is for examining other processes, because for th...
6
8
63,779,259
2020-9-7
https://stackoverflow.com/questions/63779259/enviroment-variables-in-pyenv-virtualenv
I have created a virtual environment with pyenv virtualenv 3.5.9 projectname for developing a django project. How can I set environment variables for my code to use? I tried to add the environment variable DATABASE_USER in /Users/developer/.pyenv/versions/projectname/bin/activate like this: export DATABASE_USER="dbuser...
I was wondering a similar thing, and I stumbled across a reddit thread where someone else had asked the same question, and eventually followed up noting some interesting finds. As you noticed, pyenv doesn't seem to actually use the bin/activate file. They didn't say what the activation method is, but like you, adding e...
7
4
63,775,893
2020-9-7
https://stackoverflow.com/questions/63775893/how-to-get-an-amazon-ecr-container-uri-for-a-specific-model-image-in-sagemaker
I want to know if it's possible to get an Amazon ECR container URI for a specific image programmatically (using AWS CLI or Python). For example, if I need the URL for the latest linear-learner (built-in model) image for the eu-central-1 region. Expected result: 664544806723.dkr.ecr.eu-central-1.amazonaws.com/linear-lea...
The newer versions of SageMaker SDK have a more centralized API for getting the URIs: import sagemaker sagemaker.image_uris.retrieve("linear-learner", "eu-central-1") which gives the expected result: 664544806723.dkr.ecr.eu-central-1.amazonaws.com/linear-learner:1
6
4
63,783,154
2020-9-7
https://stackoverflow.com/questions/63783154/how-to-type-hint-a-matplotlib-axes-subplots-axessubplots-object-in-python3
I was wondering how is the "best" way to type-hint the axis-object of matplotlib-subplots. running from matplotlib import pyplot as plt f, ax = plt.subplots() print(type(ax)) returns <class 'matplotlib.axes._subplots.AxesSubplot'> and running from matplotlib import axes print(type(axes._subplots)) print(type(axes._su...
As described in Type hints for context manager : import matplotlib.pyplot as plt def plot_func(ax: plt.Axes): ...
31
34
63,702,536
2020-9-2
https://stackoverflow.com/questions/63702536/jupyter-starting-a-kernel-in-a-docker-container
I want to switch my notebook easily between different kernels. One use case is to quickly test a piece of code in tensorflow 2, 2.2, 2.3, and there are many similar use cases. However I prefer to define my environments as dockers these days, rather than as different (conda) environments. Now I know that you can start j...
Full disclosure: I'm the author of Dockernel. By using Dockernel Put the following in a file called Dockerfile, in a separate directory. FROM python:3.7-slim-buster RUN pip install --upgrade pip ipython ipykernel CMD python -m ipykernel_launcher -f $DOCKERNEL_CONNECTION_FILE Then issue the following commands: docker b...
11
19
63,728,800
2020-9-3
https://stackoverflow.com/questions/63728800/how-to-deal-with-different-state-space-size-in-reinforcement-learning
I'm working in A2C reinforcement learning where my environment has an increasing and decreasing in the number of agents. As a result of the increasing and decreasing the number of agents, the state space will also change. I have tried to solve the problem of changing the state space this way: If the state space exceed...
I solve the problem using different solutions but I found that the encoding is the best solution for my problem Select the model with pre-estimate maximum state space and If the state space is less than the maximum state, we padded the state space with zeros Consider only the state of the agents itself without any sha...
10
2
63,724,890
2020-9-3
https://stackoverflow.com/questions/63724890/how-can-i-install-python-3-9-from-the-anaconda-prompt
Python 3.9.0rc1 has been released today, according to the official website. Is there a way I can use it in an Anaconda environment? I tried conda create --name python39 python==3.9 But it says: ERROR: Could not find a version that satisfies the requirement python==3.9 (from versions: none) ERROR: No matching distribu...
It's preferable to update Conda before installing Python 3.9: conda update -n base -c defaults conda Then install a Python 3.9 environment. This works now: conda create --name python39 python==3.9
7
6
63,775,936
2020-9-7
https://stackoverflow.com/questions/63775936/keras-no-good-way-to-stop-and-resume-training
After a lot of research, it seems like there is no good way to properly stop and resume training using a Tensorflow 2 / Keras model. This is true whether you are using model.fit() or using a custom training loop. There seem to be 2 supported ways to save a model while training: Save just the weights of the model, usin...
tf.keras.callbacks.experimental.BackupAndRestore API for resuming training from interruptions has been added for tensorflow>=2.3. It works great in my experience. Reference: https://www.tensorflow.org/api_docs/python/tf/keras/callbacks/experimental/BackupAndRestore
7
5
63,723,514
2020-9-3
https://stackoverflow.com/questions/63723514/userwarning-fixedformatter-should-only-be-used-together-with-fixedlocator
I have used for a long time small subroutines to format axes of charts I'm plotting. A couple of examples: def format_y_label_thousands(): # format y-axis tick labels formats ax = plt.gca() label_format = '{:,.0f}' ax.set_yticklabels([label_format.format(x) for x in ax.get_yticks().tolist()]) def format_y_label_percent...
WORKAROUND: The way to avoid the warning is to use FixedLocator (that is part of matplotlib.ticker). Below I show a code to plot three charts. I format their axes in different ways. Note that the "set_ticks" silence the warning, but it changes the actual ticks locations/labels (it took me some time to figure out that F...
118
79
63,760,734
2020-9-6
https://stackoverflow.com/questions/63760734/valueerror-input-0-of-layer-sequential-is-incompatible-with-the-layer-expect
I'm working in a project that isolate vocal parts from an audio. I'm using the DSD100 dataset, but for doing tests I'm using the DSD100subset dataset from I only use the mixtures and the vocals. I'm basing this work on this article First I process the audios to extract a spectrogram and put it on a list, with all the a...
It's probably an issue with specifying input data to Keras' fit() function. I would recommend using a tf.data.Dataset as input to fit() like so: import tensorflow as tf train_data = tf.data.Dataset.from_tensor_slices((trainMixed, trainVocals)) valid_data = tf.data.Dataset.from_tensor_slices((testMixed, testVocals)) mod...
13
12
63,743,839
2020-9-4
https://stackoverflow.com/questions/63743839/infinite-scroll-bar-is-not-working-with-django
It has been a long time when I asked this question and still didn't get an answers. I am trying to add infinite scroll down with Django but it is not working fine with the following code. I just paginating post by 10 and then its just showing me loading icon .it is not working when i am scrolling down. Can you guys fig...
I was missing loading the static so load that by adding {% load static%} below the content block <script src="{% static '/static/js/jquery-2.2.4.min.js'%}"></script> <script src="{% static '/static/js/jquery.waypoints.min.js'%}"></script> <script src="{% static '/static/js/infinite.min.js'%}"></script>
6
4
63,705,803
2020-9-2
https://stackoverflow.com/questions/63705803/merge-related-words-in-nlp
I'd like to define a new word which includes count values from two (or more) different words. For example: Words Frequency 0 mom 250 1 2020 151 2 the 124 3 19 82 4 mother 81 ... ... ... 10 London 6 11 life 6 12 something 6 I would like to define mother as mom + mother: Words Frequency 0 mother 331 1 2020 151 2 the 124...
UPDATE 10-21-2020 I decided to build a Python module to handle the tasks that I outlined in this answer. The module is called wordhoard and can be downloaded from pypi I have attempted to use Word2vec and WordNet in projects where I needed to determine the frequency of a keyword (e.g. healthcare) and the keyword's syn...
23
15
63,715,045
2020-9-3
https://stackoverflow.com/questions/63715045/how-to-catch-the-stop-button-in-pycharm-on-windows
I want to create a program that does something in which someone terminates the script by clicking the stop button in PyCharm. I tried from sys import exit def handler(signal_received, frame): # Handle any cleanup here print('SIGINT or CTRL-C detected. Exiting gracefully') exit(0) if __name__ == '__main__': signal(SIGIN...
I don't think it's a strange question at all. On unix systems, pycham sends a SIGTERM, waits one second, then send a SIGKILL. On windows, it does something else to end the process, something that seems untrappable. Even during development you need a way to cleanly shut down a process that uses native resources. In my c...
6
4
63,749,267
2020-9-5
https://stackoverflow.com/questions/63749267/how-to-efficiently-find-the-indices-of-max-values-in-a-multidimensional-array-of
Background It is common in machine learning to deal with data of a high dimensionality. For example, in a Convolutional Neural Network (CNN) the dimensions of each input image may be 256x256, and each image may have 3 color channels (Red, Green, and Blue). If we assume that the model takes in a batch of 16 images at a ...
The Approach We are going to take advantage of the Numpy community and libraries, as well as the fact that Pytorch tensors and Numpy arrays can be converted to/from one another without copying or moving the underlying arrays in memory (so conversions are low cost). From the Pytorch documentation: Converting a torch Te...
6
5
63,780,573
2020-9-7
https://stackoverflow.com/questions/63780573/trying-to-understand-fb-prophet-cross-validation
I have a dataset with 84 Monthly Sales (from 01/2013 to 12/2019) - just months, not days. Month 01 | Sale 1 Month 02 | Sale 2 Month 03 | Sale 3 .... | ... Month 84 | Sale 84 By visualization it looks like that the model fits very well... but I need to check it.... So what I understood is that cross val does not suppor...
I struggled with this for a while as well. But here is how it works. The initial model will be trained on the first 1,825 days of data. It will forecast the next 60 days of data (because horizon is set to 60). The model will then train on the initial period + the period (1,825 + 30 days in this case) and forecast the n...
17
52
63,785,105
2020-9-7
https://stackoverflow.com/questions/63785105/how-to-setup-two-pypi-indices
I have a local GitLab installation that comes with a local PyPI server to store company internal Python packages. How can I configure my PyPI to search packages in both index servers? I read about .pypirc / pip/pip.ini and found various settings but no solution so far. Most solutions permanently switch all searches to...
Goal pip install should install/update packages from GitLab as well as PyPi repo. If same package is present in both, PyPi is preferred. pip install should support authentication. Preferred, if somehow we can make it read from a config file so that we don't need to specify it repeatatively. Theory pip install suppor...
12
11
63,716,543
2020-9-3
https://stackoverflow.com/questions/63716543/plotly-how-to-update-redraw-a-plotly-express-figure-with-new-data
During debugging or computationally heavy loops, i would like to see how my data processing evolves (for example in a line plot or an image). In matplotlib the code can redraw / update the figure with plt.cla() and then plt.draw() or plt.pause(0.001), so that i can follow the progress of my computation in real time or ...
So i think i essentially figured it out. The trick is to not use go.Figure() to create a figure, but go.FigureWidget() Which is optically the same thing, but behind the scenes it's not. documentation youtube video demonstration Those FigureWidgets are exactly there to be updated as new data comes in. They stay dynamic,...
14
16
63,754,359
2020-9-5
https://stackoverflow.com/questions/63754359/correct-way-to-mock-patch-smtplib-smtp
Trying to mock.patch a call to smtplib.SMTP.sendmail in a unittest. The sendmail method appears to be successfully mocked and we can query it as MagicMock, but the called and called_args attributes of the sendmail mock are not correctly updated. It seems likely I'm not applying the patch correctly. Here's a simplified ...
I had the same issue today and forgot that I'm using a context, so just change mock.sendmail.assert_called() to mock.return_value.__enter__.return_value.sendmail.assert_called() That looks messy but here's my example: msg = EmailMessage() msg['From'] = 'no@no.com' msg['To'] = 'no@no.com' msg['Subject'] = 'subject' ms...
9
14
63,751,319
2020-9-5
https://stackoverflow.com/questions/63751319/django-rest-framework-get-field-of-related-model-in-serializer
I'm new to Django Rest Framework. I'm trying to get my ListAPI to show various fields of my Quiz (and related) models. It's working fine, except for my attempt_number field. I'm getting the right queryset, but I'm not sure how to get only the relevant value for every query. Users can take every quiz as many times as th...
If I correctly understood you, you want the list of attempts added to each quiz object. { "id": 4, "attempts": [{ "id": 1, "attempt_number": 1, }, { "id": 2, "attempt_number": 2, }...] } In that case, you should have a separate serializer for the QuizTaker model and serialize the objects in the SerializerMethodField. ...
6
6
63,713,575
2020-9-2
https://stackoverflow.com/questions/63713575/pytest-issues-with-a-session-scoped-fixture-and-asyncio
I have multiple test files, each has an async fixture that looks like this: @pytest.fixture(scope="module") def event_loop(request): loop = asyncio.get_event_loop_policy().new_event_loop() yield loop loop.close() @pytest.fixture(scope="module") async def some_fixture(): return await make_fixture() I'm using xdist for...
Eventually got it to work using the following conftest.py: import asyncio import pytest @pytest.fixture(scope="session") def event_loop(): return asyncio.get_event_loop()
8
7
63,763,809
2020-9-6
https://stackoverflow.com/questions/63763809/error-when-converting-xml-files-to-tfrecord-files
I am following the TensorFlow 2 Object Detection API Tutorial on a Macbook Here's what I got when running the given script for converting xmls to TFrecords Traceback (most recent call last): File "generate_tfrecord.py", line 62, in <module> label_map_dict = label_map_util.get_label_map_dict(label_map) File "/usr/local/...
It seems the problem can be resolved by replacing label_map = label_map_util.load_labelmap(args.labels_path) label_map_dict = label_map_util.get_label_map_dict(label_map) as label_map_dict = label_map_util.get_label_map_dict(args.labels_path)
6
17
63,738,900
2020-9-4
https://stackoverflow.com/questions/63738900/pylint-raise-missing-from
I have a pylint message (w0707) on this piece of code (from https://www.django-rest-framework.org/tutorial/3-class-based-views/): class SnippetDetail(APIView): """ Retrieve, update or delete a snippet instance. """ def get_object(self, pk): try: return Snippet.objects.get(pk=pk) except Snippet.DoesNotExist: raise Http4...
The link in the comment on your question above outlines the issue and provides a solution, but for clarity of those landing straight on this page like myself, without having to go off to another thread, read and gain context, here is the answer to your specific problem: TL;DR; This is simply solved by aliasing the Exce...
103
160
63,788,083
2020-9-8
https://stackoverflow.com/questions/63788083/how-to-check-if-a-cookie-is-set-in-fastapi
I defined an optional cookie parameter and now want to check if the cookie was set. Unfortunately, the variable does not equal to None but to an empty Cookie object. How can I check the cookie object if it is set? Here's how I defined the cookie parameter: @app.route("/graphcall") def graphcall(request: Request, ads_id...
I assume you tried this via SwaggerUI. Setting Cookie values currently does not work via SwaggerUI due to browser security restrictions. @app.get("/items/") async def read_items(ads_id: Optional[str] = Cookie(None)): if ads_id: answer = "set to %s" % ads_id else: answer = "not set" return {"ads_id": answer} works perf...
7
10
63,802,819
2020-9-8
https://stackoverflow.com/questions/63802819/hide-a-line-on-plotly-line-graph
Imagine I have lines A, B, C, D, and E. I want lines A, B, and C to appear on the plotly line chart. I want the user to have the option to add lines D and E but D and E should be hidden by default. Any suggestions on how to do this? Example, how would I hide Australia by default. import plotly.express as px df = px.dat...
You need to play with the parameter visible setting it as legendonly within every trace import plotly.express as px countries_to_hide = ["Australia"] df = px.data.gapminder().query("continent=='Oceania'") fig = px.line(df, x="year", y="lifeExp", color='country') fig.for_each_trace(lambda trace: trace.update(visible="le...
8
20
63,796,920
2020-9-8
https://stackoverflow.com/questions/63796920/nested-list-of-dictionary-with-nested-list-of-dictionary-into-a-pandas-dataframe
I need help with converting a nested list of dictionaries with a nested list of dictionaries inside of it to a dataframe. At the end, I want something that looks like (the dots are for other columns in between): id | isbn | isbn13 | .... | average_rating| 30278752 |1594634025|9781594634024| .... |3.92 | 34006942 |1501...
If you key is always books pd.concat([pd.DataFrame(i['books']) for i in review_stat]) id isbn isbn13 ratings_count reviews_count text_reviews_count work_ratings_count work_reviews_count work_text_reviews_count average_rating 0 30278752 1594634025 9781594634024 4832 8435 417 2081902 3313007 109912 3.92 0 34006942 15011...
10
7
63,785,319
2020-9-7
https://stackoverflow.com/questions/63785319/pytorch-torch-no-grad-versus-requires-grad-false
I'm following a PyTorch tutorial which uses the BERT NLP model (feature extractor) from the Huggingface Transformers library. There are two pieces of interrelated code for gradient updates that I don't understand. (1) torch.no_grad() The tutorial has a class where the forward() function creates a torch.no_grad() block ...
This is an older discussion, which has changed slightly over the years (mainly due to the purpose of with torch.no_grad() as a pattern. An excellent answer that kind of answers your question as well can be found on Stackoverflow already. However, since the original question is vastly different, I'll refrain from markin...
14
13
63,757,763
2020-9-5
https://stackoverflow.com/questions/63757763/timeit-and-its-default-timer-completely-disagree
I benchmarked these two functions (they unzip pairs back into source lists, came from here): n = 10**7 a = list(range(n)) b = list(range(n)) pairs = list(zip(a, b)) def f1(a, b, pairs): a[:], b[:] = zip(*pairs) def f2(a, b, pairs): for i, (a[i], b[i]) in enumerate(pairs): pass Results with timeit.timeit (five rounds, ...
As Martijn commented, the difference is Python's garbage collection, which timeit.timeit disables during its run. And zip creates 10 million iterator objects, one for each of the 10 million iterables it's given. So, garbage-collecting 10 million objects simply takes a lot of time, right? Mystery solved! Well... no. Tha...
53
61