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 |
|---|---|---|---|---|---|---|
65,412,984 | 2020-12-22 | https://stackoverflow.com/questions/65412984/using-pandas-data-frame-as-a-type-in-pydantic | I'm using pydantic and want to create classes which contain pandas dataframes. I was looking for this online for quite a time and did not find anything. My code for the custom types looks as following. I named the type for dataframes pd.DataFrame but obviously its not correct. Does anyone know how to declare a pandas d... | You can activate Arbitrary Types Allowed: import pandas as pd from pydantic import BaseModel class SubModelInput(BaseModel): a: pd.DataFrame b: pd.DataFrame class Config: arbitrary_types_allowed = True class ModelInput(BaseModel): SubModelInput: SubModelInput a: pd.DataFrame b: pd.DataFrame c: pd.DataFrame class Config... | 8 | 13 |
65,316,863 | 2020-12-16 | https://stackoverflow.com/questions/65316863/is-asyncio-to-thread-method-different-to-threadpoolexecutor | I see that asyncio.to_thread() method is been added @python 3.9+, its description says it runs blocking codes on a separate thread to run at once. see example below: def blocking_io(): print(f"start blocking_io at {time.strftime('%X')}") # Note that time.sleep() can be replaced with any blocking # IO-bound operation, s... | Source code of to_thread is quite simple. It boils down to awaiting run_in_executor with a default executor (executor argument is None) which is ThreadPoolExecutor. In fact, yes, this is traditional multithreading, сode intended to run on a separate thread is not asynchronous, but to_thread allows you to await for its ... | 37 | 53 |
65,322,928 | 2020-12-16 | https://stackoverflow.com/questions/65322928/cv2-imwrite-systemerror-built-in-function-imwrite-returned-null-without-set | I'm tring to save an np array as an image. The problem is that, if I write the path in the imwrite function it works, but if i store it in a variable and then use this variable as path it doesn't work and returns an error. This works: cv2.imwrite('my/path/to/image.png', myarray[...,::-1]) This doesn't work new_image_p... | The method cv2.imwrite does not work with the Path object. Simply convert it to string when you call the method: cv2.imwrite(str(new_image_path), myarray[...,::-1]) | 7 | 11 |
65,331,736 | 2020-12-16 | https://stackoverflow.com/questions/65331736/how-can-i-publish-python-packages-to-codeartifact-using-poetry | Trying to publish a Poetry package to AWS CodeArtifact. It supports pip which should indicate that it supports poetry as well since poetry can upload to PyPi servers. I've configured the domain like so: export CODEARTIFACT_AUTH_TOKEN=`aws codeartifact get-authorization-token --domain XXXX --domain-owner XXXXXXXXXXXX --... | The problem is the /simple/ at the end of the repo url. This part should only be added when pulling from that repo, not when publishing to it. If you look closely to the documentation of AWS CodeArtifact on how to publish with twine, you'll see that it's also not there. This works: # This will give the repo url without... | 16 | 26 |
65,394,319 | 2020-12-21 | https://stackoverflow.com/questions/65394319/boto3-how-to-interract-with-digitalocean-s3-spaces-when-cdn-is-enabled | I'm working with DigitalOcean Spaces (S3 storage protocol) which has enabled CDN. Any file on s3 can be accessed via direct URL in the given form: https://my-bucket.fra1.digitaloceanspaces.com/<file_key> If CDN is enabled, the file can be accessed via additional CDN URL: https://my-bucket.fra1.cdn.digitaloceanspaces.c... | Based on @Amit Singh's answer, I've made an additional research of this issue. Answers that helped me were found here and here. To make boto3 presigned URLs work, I've made the following update to client and generate_presigned_url() params. s3_client = boto3.client('s3', region_name=configs['default_region'], endpoint_... | 7 | 2 |
65,379,879 | 2020-12-20 | https://stackoverflow.com/questions/65379879/define-a-ipython-magic-which-replaces-the-content-of-the-next-cell | The %load line-magic command loads the content of a given file into the current cell, for instance, executing: [cell 1] %load hello_world.py ... transform the cell into: [cell 1] # %load hello_world.py print("hello, world") I would like to create a %load_next line-magic command which would instead load this file into... | You can run below script. There is no way to get all cells, so I decided to run javascript code to remove the next cell. Js part finds all cells and remove the next cell from the current cell. I have tested on Jupyter Notebook and Jupyter Lab. from IPython.display import display, HTML, Javascript from IPython.core.magi... | 6 | 2 |
65,349,950 | 2020-12-17 | https://stackoverflow.com/questions/65349950/how-to-make-python-telegram-bot-send-a-message-without-getting-a-commad | I'm Making a telegram bot using Python-Telegram-bot. I wanna make it send a message to one specific user (myself in this case) to select an option. after that, it should take that option as a command and work as usual. but after 30 min... it should send me the same message making me choose an option just like before. H... | You can get the bot object either from the updater or the dispatcher: updater = Updater('<bot-token>') updater.bot.sendMessage(chat_id='<user-id>', text='Hello there!') # alternative: updater.dispatcher.bot.sendMessage(chat_id='<user-id>', text='Hello there!') | 11 | 19 |
65,411,425 | 2020-12-22 | https://stackoverflow.com/questions/65411425/running-two-dask-ml-imputers-simultaneously-instead-of-sequentially | I can impute the mean and most frequent value using dask-ml like so, this works fine: mean_imputer = impute.SimpleImputer(strategy='mean') most_frequent_imputer = impute.SimpleImputer(strategy='most_frequent') data = [[100, 2, 5], [np.nan, np.nan, np.nan], [70, 7, 5]] df = pd.DataFrame(data, columns = ['Weight', 'Age',... | You can used dask.delayed as suggested in docs and Dask Toutorial to parallelise the computation if entities are independent of one another. Your code would look like: from dask.distributed import Client client = Client(n_workers=4) from dask import delayed import numpy as np import pandas as pd from dask_ml import imp... | 6 | 2 |
65,380,093 | 2020-12-20 | https://stackoverflow.com/questions/65380093/is-there-an-essential-difference-between-await-and-async-with-while-doing-reques | My question is about the right way of making response in aiohttp Official aiohttp documentation gives us the example of making an async query: session = aiohttp.ClientSession() async with session.get('http://httpbin.org/get') as resp: print(resp.status) print(await resp.text()) await session.close() I cannot understan... | Explicitly managing a response via async with, is not necessary but advisable. The purpose of async with for response objects is to safely and promptly release resources used by the response (via a call to resp.release()). That is, even if an error occurs the resources are freed and available for further requests/respo... | 9 | 3 |
65,321,798 | 2020-12-16 | https://stackoverflow.com/questions/65321798/how-to-config-completer-use-jedi-to-false-in-juypter-notebook-permanently | Every time a new jupyter notebook instance is opened, it requires %config Completer.use_jedi = False command to be run, before autocomplete functionality starts working. This is tiring every time, to config use_jedi to False before coding. kindly suggest if there is a permanent fix to have autocomplete in juypter noteb... | I launch my jupyterlab from docker and catch this problem. I solved like this: COPY ipython_kernel_config.py /root/.ipython/profile_default/ipython_kernel_config.py Content ipython_kernel_config.py: c.Completer.use_jedi = False idea: https://github.com/ipython/ipython/issues/11530 | 8 | 6 |
65,339,479 | 2020-12-17 | https://stackoverflow.com/questions/65339479/if-you-store-optional-functionality-of-a-base-class-in-a-secondary-class-should | I know the title is probably a bit confusing, so let me give you an example. Suppose you have a base class Base which is intended to be subclassed to create more complex objects. But you also have optional functionality that you don't need for every subclass, so you put it in a secondary class OptionalStuffA that is al... | What I can get from your problem is that you want to have different functions and properties based on different condition, that sounds like good reason to use MetaClass. It all depends how complex your each class is, and what are you building, if it is for some library or API then MetaClass can do magic if used rightly... | 8 | 2 |
65,369,447 | 2020-12-19 | https://stackoverflow.com/questions/65369447/how-to-intercept-the-first-value-of-a-generator-and-transparently-yield-from-the | Update: I've started a thread on python-ideas to propose additional syntax or a stdlib function for this purpose (i.e. specifying the first value sent by yield from). So far 0 replies... :/ How do I intercept the first yielded value of a subgenerator but delegate the rest of the iteration to the latter using yield fro... | If you're trying to implement this generator wrapper as a generator function using yield from, then your question basically boils down to whether it is possible to specify the first value sent to the "yielded from" generator. Which it is not. If you look at the formal specification of the yield from expression in PEP 3... | 12 | 2 |
65,413,501 | 2020-12-22 | https://stackoverflow.com/questions/65413501/annoying-diff-format-for-long-strings-using-pytest-pycharm | Hi have this very basic test: def test_long_diff(): long_str1 = "ABCDEFGHIJ " * 10 long_str2 = "ABCDEFGHIJ " * 5 + "* " + "ABCDEFGHIJ " * 5 assert long_str1 == long_str2 Using: Python 3.8.5, pytest-6.2.1, PyCharm 2020.2, MacOs Running with pytest from a shell, the output is "useable" and the error message will point o... | So it turns out this is an hard-coded behaviour of the pytest plugin used by PyCharm. The plugin always applies pprint.pformat() to the left and right values. The behaviour described in the question then occurs when the strings are longer than 80 characters and contain white spaces. One possible workaround is to overri... | 6 | 3 |
65,366,434 | 2020-12-19 | https://stackoverflow.com/questions/65366434/discrepancy-between-two-hosts-running-the-same-docker-commands | A colleague and I have a big Docker puzzle. When we run the following commands we get different results. docker run -it python:3.8.6 /bin/bash pip install fbprophet For me, it installs perfectly, while for him it produces an error and fails to install. I thought the whole point of docker is to prevent this kind of iss... | How do we fix it? Your error reports a GCC / compilation problem. A quick search shows mostly problems related to python / gcc version (one, two, three). But you are right, this doesn't look like as it could happen inside a one particular container. What it does look like is some kind of OOM problem. Also, is this a V... | 7 | 13 |
65,410,758 | 2020-12-22 | https://stackoverflow.com/questions/65410758/problem-formatting-python-when-using-prettier-in-vscode | In vscode I want to use Prettier as my default formatter, but not for Python, where I will just use autopep8. I have the following settings now: { "workbench.iconTheme": "vscode-icons", "workbench.editorAssociations": [ { "viewType": "jupyter.notebook.ipynb", "filenamePattern": "*.ipynb" } ], "git.confirmSync": false, ... | If I disabled Prettier as the default formatter, it would not format on save anymore, but my Python would be formatted by autopep8 on save. With this in mind, the following solution worked for me to have both Prettier working for other languages and autopep8 for Python: { "workbench.iconTheme": "vscode-icons", "workben... | 19 | 40 |
65,383,964 | 2020-12-20 | https://stackoverflow.com/questions/65383964/typeerror-could-not-build-a-typespec-with-type-kerastensor | I am a newbie to deep learning so while I am trying to build a Masked R-CNN model for training my Custom Dataset I am getting an error which reads: TypeError: Could not build a TypeSpec for <KerasTensor: shape=(None, None, 4) dtype=float32 (created by layer 'tf.math.truediv')> with type KerasTensor Below is the PYTHON... | You should using Tensorflow 1.x. Change TF version on colab using %tensorflow_version 1.x After that I think you will get other problem with keras version, add command to install keras 2.1.5. !pip install keras==2.1.5 | 14 | 2 |
65,408,027 | 2020-12-22 | https://stackoverflow.com/questions/65408027/how-to-correctly-use-cross-entropy-loss-vs-softmax-for-classification | I want to train a multi class classifier using Pytorch. Following the official Pytorch doc shows how to use a nn.CrossEntropyLoss() after a last layer of type nn.Linear(84, 10). However, I remember this is what Softmax does. This leaves me confused. How to train a "standard" classification network in the best way? If... | I think that it's important to understand softmax and cross-entropy, at least from a practical point of view. Once you have a grasp on these two concepts then it should be clear how they may be "correctly" used in the context of ML. Cross Entropy H(p, q) Cross-entropy is a function that compares two probability distrib... | 8 | 26 |
65,369,567 | 2020-12-19 | https://stackoverflow.com/questions/65369567/import-rest-framework-could-not-be-resolved-but-i-have-installed-djangorestfr | Here's my settings.py: INSTALLED_APPS = [ 'rest_framework', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'api.apps.ApiConfig' ] | If you are using VSCode, Ctrl + Shift + P -> Type and select 'Python: Select Interpreter' and enter into your projects virtual environment. This is what worked for me. | 29 | 102 |
65,398,794 | 2020-12-21 | https://stackoverflow.com/questions/65398794/what-does-this-mean-warningrootpyarrow-ignore-timezone-environment-variabl | I am working in Python on a Jupyter Notebook, and I got this warning: WARNING:root:'PYARROW_IGNORE_TIMEZONE' environment variable was not set. I tried to remove it, but I couldn't. I tried to set PYARROW_IGNORE_TIMEZONE to 1, as I saw on some forums but it didn't work. Here is my code : PYARROW_IGNORE_TIMEZONE=1 impor... | If you want to set environment variable, you should use os. Otherwise you're just setting the variable in Python, but it doesn't get exported to the environment. import os os.environ["PYARROW_IGNORE_TIMEZONE"] = "1" | 11 | 20 |
65,398,299 | 2020-12-21 | https://stackoverflow.com/questions/65398299/proper-inputs-for-scikit-learn-roc-auc-score-and-roc-plot | I am trying to determine roc_auc_score for a fit model on a validation set. I am seeing some conflicting information on function inputs. Documentation says: "y_score array-like of shape (n_samples,) or (n_samples, n_classes) Target scores. In the binary and multilabel cases, these can be either probability estimates or... | model.predict(...) will give you the predicted label for each observation. That is, it will return an array full of ones and zeros. model.predict_proba(...)[:, 1] will give you the probability for each observation being equal to one. That is, it will return an array full of numbers between zero and one, inclusive. A RO... | 7 | 10 |
65,396,901 | 2020-12-21 | https://stackoverflow.com/questions/65396901/what-is-the-difference-between-pycrypto-and-crypto-packages-in-python | I am new to encryption and hashing in python. I need this for authentication in one of my flask project. So my friend told me to use crypto package but when i searched it up i got crypto and pycrypto packages in the result. The thing is I know both of them are for encryption utility but I am confused as to which one to... | These two packages serve very different goals: crypto is a command line utility, which is intended to encrypt files, while pycrypto is a Python library which can be used from within Python to perform a number of different cryptographic operations (hashing, encryption/decryption, etc). pycrypto would be the more appropr... | 6 | 6 |
65,396,538 | 2020-12-21 | https://stackoverflow.com/questions/65396538/python-requests-jsondecodeerror | I have this code: import requests r = requests.get('https://www.instagram.com/p/CJDxE7Yp5Oj/?__a=1') data = r.json()['graphql']['shortcode_media'] Why do I get an error like this? C:\ProgramData\Anaconda3\envs\test\python.exe C:/Users/Solba/PycharmProjects/test/main.py Traceback (most recent call last): File "C:/Users... | r.json() expects a JSON string to be returned by the API. The API should explicitly say it is responding with JSON through response headers. In this case, the URL you are requesting is either not responding with a proper JSON or not explicitly saying it is responding with a JSON. You can first check the response sent b... | 10 | 9 |
65,385,500 | 2020-12-20 | https://stackoverflow.com/questions/65385500/valueerror-invalid-literal-for-int-with-base-10-30-0-when-running-unittest | I'm trying to run a test that was previously working but has suddenly stopped running but now i seem to get an error on all my tests e.g. from httmock import HTTMock from unittest import TestCase from unittest.mock import patch, call, mock_open, MagicMock, Mock, ANY import os.path import os from src.operators import In... | The DAGBAG_IMPORT_TIMEOUT had been upgraded in the config files to float for 2.0 and for 1.10.14 it needed to be float. Deleted airflow completely including cfg files and re-installed the version | 15 | 10 |
65,388,539 | 2020-12-21 | https://stackoverflow.com/questions/65388539/using-python-i-cant-access-shared-drive-folders-from-google-drive-api-v3 | I can get mydrive folders, but I can't access shared drive folders from Google Drive API. This is my code.(almost same to the Guides' code here) I followed the Guides, finished "Enable the Drive API", execute the pip command on VScode, and put credentials.json to the working directory. (I got no error, only got filenam... | Notice that the API has the includeItemsFromAllDrives parameter in order to determine whether shared drive items show up or not in the results. The Python API V3 wrapper also has this parameter included on it's list method implementation that needs to be included when calling the list() method: ... service = build('dri... | 6 | 14 |
65,387,500 | 2020-12-21 | https://stackoverflow.com/questions/65387500/insert-a-png-image-in-a-matplotlib-figure | I'm trying to insert a png image in matplotlib figure (ref) import matplotlib.pyplot as plt import numpy as np from matplotlib.figure import Figure from matplotlib.offsetbox import OffsetImage, AnnotationBbox ax = plt.subplot(111) ax.plot( [1, 2, 3], [1, 2, 3], 'go-', label='line 1', linewidth=2 ) arr_img = plt.imread(... | You can zoom the image and the set the box alignment to the lower right corner (0,1) plus some extra for the margins: im = OffsetImage(arr_img, zoom=.45) ab = AnnotationBbox(im, (1, 0), xycoords='axes fraction', box_alignment=(1.1,-0.1)) You may also want to use data coordinates, which is the default, and use the def... | 8 | 9 |
65,388,213 | 2020-12-21 | https://stackoverflow.com/questions/65388213/why-is-pathlib-path-file-parent-parent-sensitive-to-my-working-directory | I have a script that's two directories down. ❯ tree . └── foo └── bar └── test.py ❯ cd foo/bar ❯ cat test.py from pathlib import Path print(Path(__file__).parent) print(Path(__file__).parent.parent) When I run it from the directory that contains it, PathLib thinks that the file's grandparent is the same as its parent.... | You need to call Path.resolve() to make your path absolute (a full path including all parent directories and removing all symlinks) from pathlib import Path print(Path(__file__).resolve().parent) print(Path(__file__).resolve().parent.parent) This will cause the results to include the entire path to each directory, but... | 7 | 10 |
65,383,467 | 2020-12-20 | https://stackoverflow.com/questions/65383467/can-conda-be-configured-to-use-a-private-pypi-repo | I have users that create both conda and pip packages- I have no control over this I use artifactory to host private conda and pip repos, for example this is how a private pip repo works: https://www.jfrog.com/confluence/display/JFROG/PyPI+Repositories Sometimes there is a private pip package a conda environment or pack... | Conda won't search PyPI or alternative pip-compatible indexes automatically, but one can still use the --index-url or --extra-index-url flags when using pip install. E.g., Ad Hoc Installation # activate environment conda activate foo # ensure it has `pip` installed conda list pip # install with `pip` pip install --extr... | 12 | 16 |
65,357,675 | 2020-12-18 | https://stackoverflow.com/questions/65357675/a-function-to-return-the-frequency-counts-of-all-or-specific-columns | I can return the frequency of all columns in a nice dataframe with a total column. for column in df: df.groupby(column).size().reset_index(name="total") Count total 0 1 423 1 2 488 2 3 454 3 4 408 4 5 343 Precipitation total 0 Fine 7490 1 Fog 23 2 Other 51 3 Raining 808 Month total 0 1 717 1 2 648 2 3 710 3 4 701 I pu... | Based on your comment, you just want to return a list of dataframe: def count_all_columns_freq(df): return [df.groupby(column).size().reset_index(name="total") for column in df] You can select columns in many ways in pandas, e.g. by slicing or by passing a list of columns like in df[['colA', 'colB']]. You don't need t... | 6 | 2 |
65,381,289 | 2020-12-20 | https://stackoverflow.com/questions/65381289/what-is-the-purpose-of-the-pyautogui-failsafe | So, I was just messing around with pyautogui moving the mouse to random positions on the screen, when I manually moved the mouse to the top left corner of the screen and ran the program, it raised a pyautogui failsafe. I do know how to disable it and all that, but I want to know why is is there in the first place and p... | According to pyautogui docs It’s hard to use the mouse to close a program if the mouse cursor is moving around on its own. As a safety feature, a fail-safe feature is enabled by default. When a PyAutoGUI function is called, if the mouse is in any of the four corners of the primary monitor, they will raise a pyautogui.... | 7 | 10 |
65,379,408 | 2020-12-20 | https://stackoverflow.com/questions/65379408/pandas-groupby-and-find-difference-between-max-and-min | I have a dataframe. I have aggregated as below. But, I want to difference them as max value - min values dnm=df.groupby('Type').agg({'Vehicle_Age': ['max','min']}) Expect: | You can use np.ptp, this does the max - min calculation for you: df.groupby('Type').agg({'Vehicle_Age': np.ptp}) Or, df.groupby('Type')['Vehicle_Age'].agg(np.ptp) If you a Series as the output. | 5 | 12 |
65,317,215 | 2020-12-16 | https://stackoverflow.com/questions/65317215/using-unittest-mocks-patch-in-same-module-getting-does-not-have-the-attribute | I have what should've been a simple task, and it has stumped me for a while. I am trying to patch an object imported into the current module. Per the answers to Mock patching from/import statement in Python I should just be able to patch("__main__.imported_obj"). However, this isn't working for me. Please see my below ... | You are assuming that the module the test is running in is __main__, but that would only be the case if it were called via main. This is usually the case if you are using unittest. With pytest, the tests live in the module they are defined in. You have to patch the current module, the name of which is accessible via __... | 6 | 6 |
65,372,252 | 2020-12-19 | https://stackoverflow.com/questions/65372252/selenium-python-page-down-unknown-error-neterr-name-not-resolved | So I'm currently working on a python scraper to collect website info with selenium in python. The issue I'm having is if I head to a page that isn't live I get the error: unknown error: net::ERR_NAME_NOT_RESOLVED I haven't used python in a while so my knowledge isn't the best. Here is my code driver = webdriver.Chrome(... | If you want to catch the error you have to change your except to what selenium is raising for you. In this case: selenium.common.exceptions.WebDriverException. So first import it: from selenium.common.exceptions import WebDriverException Then you can catch: try: driver.get('http://www.whitefoxcatering.co.uk') except W... | 6 | 8 |
65,369,612 | 2020-12-19 | https://stackoverflow.com/questions/65369612/unknown-distribution-format-when-uploading-to-pypi-via-twine | I am trying to update the version of infixpy using twine. Here is my ~/.pypirc: index-servers = pypi pypitest [pypi] repository: https://upload.pypi.org/legacy/ username: myuser password: mypassword [pypitest] repository: https://upload.testpypi.org/legacy username: myuser password: mypassword Here is the command line... | Per the docs for twine upload (emphasis mine): positional arguments: dist The distribution files to upload to the repository (package index). Usually dist/* . May additionally contain a .asc file to include an existing signature with the file upload. You've passed a directory, not files - as the docs suggest, you pro... | 7 | 10 |
65,367,298 | 2020-12-19 | https://stackoverflow.com/questions/65367298/python-while-loop-breakout-issues | The question I have is about the flag I have here for the while loop. This works but not like I think it should. I assume I'm not understanding something so if someone is able to explain, that would be great. From my understanding this should break out of the loop as soon as one of my conditionals is met. So if I input... | The condition of the while loop is only checked between iterations of the loop body, so if you change the condition in the middle of the loop, the current iteration will finish before the loop terminates. If you want to break a loop immediately, you need to either break (which automatically breaks the loop regardless o... | 8 | 12 |
65,362,524 | 2020-12-18 | https://stackoverflow.com/questions/65362524/in-json-created-from-a-pydantic-basemodel-exclude-optional-if-not-set | I want to exclude all the Optional values that are not set when I create JSON. In this example: from pydantic import BaseModel from typing import Optional class Foo(BaseModel): x: int y: int = 42 z: Optional[int] print(Foo(x=3).json()) I get {"x": 3, "y": 42, "z": null}. But I would like to exclude z. Not because its ... | You could exclude only optional model fields that unset by making of union of model fields that are set and those that are not None. Pydantic provides the following arguments for exporting method model.dict(...): exclude_unset: whether fields which were not explicitly set when creating the model should be excluded fro... | 21 | 25 |
65,357,462 | 2020-12-18 | https://stackoverflow.com/questions/65357462/can-you-have-an-empty-string-for-a-python-enum-attribute | I'd really like to use Python enum types for this model I'm working on. The problem is one of the potential values from the data provider is an empty string. Given this model... from sqlalchemy import Column, Enum class Events(Base): __tablename__ = 'events' ... restriction_code = Column(Enum(RestrictionCode)) ... ...... | No, each Enum member must have a name. The intended way to use Enums in this scenario would be to have the value of the member be the value stored in the database, so your Enum should look like: class RestrictionCode(Enum): A = 'A' B = 'B' C = 'C' D = 'D' NONE = '' If you want a description as well, you'll need to des... | 6 | 4 |
65,360,692 | 2020-12-18 | https://stackoverflow.com/questions/65360692/python-patching-new-method | I am trying to patch __new__ method of a class, and it is not working as I expect. from contextlib import contextmanager class A: def __init__(self, arg): print('A init', arg) @contextmanager def patch_a(): new = A.__new__ def fake_new(cls, *args, **kwargs): print('call fake_new') return new(cls, *args, **kwargs) # her... | You've run into a complicated part of Python object instantiation - in which the language opted for a design that would allow one to create a custom __init__ method with parameters, without having to touch __new__. However, the in the base of class hierarchy, object, both __new__ and __init__ take one single parameter ... | 8 | 6 |
65,359,261 | 2020-12-18 | https://stackoverflow.com/questions/65359261/can-you-get-all-estimators-from-an-sklearn-grid-search-gridsearchcv | I recently tested many hyperparameter combinations using sklearn.model_selection.GridSearchCV. I want to know if there is a way to call all previous estimators that were trained in the process. search = GridSearchCV(estimator=my_estimator, param_grid=parameters) # `my_estimator` is a gradient boosting classifier object... | No, none of the tested models are saved, except (optionally, but by default) one final one trained on the entire training set, your best_estimator_. Especially when models store significant amounts of data (e.g. KNNs), saving all the fitted estimators would be very memory-expensive, and usually not of much use. (cross_... | 6 | 10 |
65,357,665 | 2020-12-18 | https://stackoverflow.com/questions/65357665/how-to-skip-lines-in-pycharm-debug-mode-with-python | Let's say I put a breakpoint in the first line. I see no option to simply skip the 2nd line and jump straight to the print statement. Is there any hidden option? If not, what is the most non-intrusive way? Commenting out the lines I don't wanna run is not elegant. a = 3 a = 4 print(a) | You can do right click on the third statement and Jump to Cursor. This is a manual action though... I don't think there is a mode to only run breakpointed lines... | 8 | 12 |
65,352,682 | 2020-12-18 | https://stackoverflow.com/questions/65352682/python-asyncio-pythonic-way-of-waiting-until-condition-satisfied | I need to wait until a certain condition/equation becomes True in a asynchronous function in python. Basically it is a flag variable which would be flagged by a coroutine running in asyncio.create_task(). I want to await until it is flagged in the main loop of asyncio. Here's my current code: import asyncio flag = Fals... | Using of asyncio.Event is quite straightforward. Sample below. Note: Event should be created from inside coroutine for correct work. import asyncio async def bg_tsk(flag): await asyncio.sleep(3) flag.set() async def waiter(): flag = asyncio.Event() asyncio.create_task(bg_tsk(flag)) await flag.wait() print("After waitin... | 11 | 14 |
65,349,787 | 2020-12-17 | https://stackoverflow.com/questions/65349787/how-to-find-the-range-of-dates-from-a-datetime-column-in-a-dataframe | Wondering how to print the range of dates in a dataframe. Seems like it would be very simple but I can't find answers anywhere. Is there an easy way to do this with pandas datetime module? So if this was a small version of the dataframe for example: Date Id Value 2020-09-23 14:00:00 4752764 12212 2020-10-25 0... | Try this df['Date'] = pd.to_datetime(df['Date']) # If your Date column is of the type object otherwise skip this date_range = str(df['Date'].dt.date.min()) + ' to ' +str(df['Date'].dt.date.max()) | 12 | 20 |
65,344,578 | 2020-12-17 | https://stackoverflow.com/questions/65344578/how-to-check-if-a-model-is-in-train-or-eval-mode-in-pytorch | How to check from within a model if it is currently in train or eval mode? | From the Pytorch forum, with a small tweak: use if self.training: # it's in train mode else: # it's in eval mode Always better to have a stack overflow answer than to look at forums. Explanation about the modes | 24 | 34 |
65,343,377 | 2020-12-17 | https://stackoverflow.com/questions/65343377/adam-optimizer-with-warmup-on-pytorch | In the paper Attention is all you need, under section 5.3, the authors suggested to increase the learning rate linearly and then decrease proportionally to the inverse square root of steps. How do we implement this in PyTorch with Adam optimizer? Preferably without additional packages. | PyTorch provides learning-rate-schedulers for implementing various methods of adjusting the learning rate during the training process. Some simple LR-schedulers are are already implemented and can be found here: https://pytorch.org/docs/stable/optim.html#how-to-adjust-learning-rate In your special case you can - just l... | 24 | 16 |
65,334,215 | 2020-12-17 | https://stackoverflow.com/questions/65334215/how-can-request-param-be-annotated-in-indirect-parametrization | In the Indirect parametrization example I want to type hint request.param indicating a specific type, a str for example. The problem is since the argument to fixt must be the request fixture there seems to be no way to indicate what type the parameters passed through the "optional param attribute" should be (quoting th... | As of now (version 6.2), pytest doesn't provide any type hint for the param attribute. If you need to just type param regardless of the rest of FixtureRequest fields and methods, you can inline your own impl stub: from typing import TYPE_CHECKING if TYPE_CHECKING: class FixtureRequest: param: str else: from typing impo... | 11 | 16 |
65,337,641 | 2020-12-17 | https://stackoverflow.com/questions/65337641/switching-python-version-3-9-%e2%86%92-3-8-installed-by-homebrew | It’s a very similar situation like described here, but vice versa. I have Python 3.8 installed via Homebrew and updated that to 3.9: % brew list --formula | grep python python@3.8 python@3.9 I want to use Python 3.8 as my default version with python3 command and tried – inspired by this answer – the following: brew un... | Well, sometimes it helps to ask the question to find the solution on your own – one of the great things of StackOverflow, by the way. The hint is in the warning of pipenv: "Your Pipfile requires python_version 3.9". I simply did rm Pipfile rm Pipfile.lock and then it worked: pipenv install google-ads Well, at least p... | 9 | 1 |
65,326,039 | 2020-12-16 | https://stackoverflow.com/questions/65326039/how-to-handle-job-cancelation-in-slurm | I am using Slurm job manager on an HPC cluster. Sometimes there are situations, when a job is canceled due to time limit and I would like to finish my program gracefully. As far as I understand, the process of cancellation occurs in two stages exactly for a software developer to be able to finish the program gracefully... | In Slurm, you can decide which signal is sent at which moment before your job hits the time limit. From the sbatch man page: --signal=[[R][B]:]<sig_num>[@<sig_time>] When a job is within sig_time seconds of its end time, send it the signal sig_num. So set #SBATCH --signal=B:TERM@05:00 to get Slurm to signal the job ... | 7 | 9 |
65,337,020 | 2020-12-17 | https://stackoverflow.com/questions/65337020/pyspark-filter-dataframe-if-column-does-not-contain-string | I hope it wasn't asked before, at least I couldn't find. I'm trying to exclude rows where Key column does not contain 'sd' value. Below is the working example for when it contains. values = [("sd123","2"),("kd123","1")] columns = ['Key', 'V1'] df2 = spark.createDataFrame(values, columns) df2.where(F.col('Key').contains... | Use ~ as bitwise NOT: df2.where(~F.col('Key').contains('sd')).show() | 18 | 35 |
65,336,695 | 2020-12-17 | https://stackoverflow.com/questions/65336695/python-no-module-named-pip | I use Windows 7 32 bit and Python 3.7. I was trying to install a module with pip and this error came up: cd C:\Windows\System32 pip install pyttsx3 Output: Traceback (most recent call last): File "d:\python\python 3.7\lib\runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "d:\python\python 3.7\lib\... | Could you try? pip3 install pyttsx3 | 16 | 4 |
65,329,555 | 2020-12-16 | https://stackoverflow.com/questions/65329555/standard-library-logging-plus-loguru | Let's say I'm setting up a script or library that has a few dependencies which use Python's standard library logging module but I want to use loguru to capture all logs. My first naive attempt was a complete failure, but I'm not sure how to proceed. To test I have two files main.py: from loguru import logger from base_... | You can use a custom handler to intercept standard logging messages toward your Loguru sinks as documented here. main.py will then look something like this: import logging from loguru import logger from base_log import test_func class InterceptHandler(logging.Handler): def emit(self, record): try: level = logger.level(... | 6 | 6 |
65,331,297 | 2020-12-16 | https://stackoverflow.com/questions/65331297/how-to-make-a-column-based-on-previous-values-in-dataframe | I have a data frame: user_id url 111 google.com 111 youtube.com 111 youtube.com 111 google.com 111 stackoverflow.com 111 google.com 222 twitter.com 222 google.com 222 twitter.com I want to create a column that will show the fact of visiting this URL before. Desired output: user_id url target 111 google.com 0 111 youtu... | Use duplicated: df['target'] = df.duplicated().astype(int) print(df) Output user_id url target 0 111 google.com 0 1 111 youtube.com 0 2 111 youtube.com 1 3 111 google.com 1 4 111 stackoverflow.com 0 5 111 google.com 1 6 222 twitter.com 0 7 222 google.com 0 8 222 twitter.com 1 | 6 | 5 |
65,327,494 | 2020-12-16 | https://stackoverflow.com/questions/65327494/how-to-join-elements-within-an-array-of-strings | I have this array of strings that I have split element wise so I can do stuff to it. Now I want to return them back into a sentence. my_array = (['T', 'e', 's', 't', ' ', 'w', 'o', 'r', 'd', 's', '!']) Is there a way to join them togeter back into a sentence whilst keeping the formatting? Ideal output would be somethi... | Try join: my_array = (['T', 'e', 's', 't', ' ', 'w', 'o', 'r', 'd', 's', '!']) joined_array = ''.join(my_array) Which gives: 'Test words!' | 10 | 15 |
65,323,350 | 2020-12-16 | https://stackoverflow.com/questions/65323350/how-to-sum-rows-in-the-same-column-than-the-category-in-pandas-dataframe-pytho | I have been working on formatting a log file and finally I have arrived to the following dataframe sample, where the categories and numbers I want to add are in the same column: df = pd.DataFrame(dict(a=['Cat. A',1,1,3,'Cat. A',2,2,'Cat. B',3,5,2,6,'Cat. B',1,'Cat. C',4])) >>> a 0 Cat. A 1 1 2 1 3 3 4 Cat. A 5 2 6 2 7 ... | We can use pd.to_numeric to mark non-numeric fields as nan using Series.mask and Series.notna then use for group. Then use GroupBy.sum a = pd.to_numeric(df['a'], errors='coerce') g = df['a'].mask(a.notna()).ffill() a.groupby(g).sum() Cat. A 9.0 Cat. B 17.0 Cat. C 4.0 Name: a, dtype: float64 | 6 | 3 |
65,316,586 | 2020-12-16 | https://stackoverflow.com/questions/65316586/get-the-run-id-for-an-mlflow-experiment-with-the-name | I currently created an experiment in mlflow and created multiple runs in the experiment. from sklearn.ensemble import RandomForestRegressor from sklearn.metrics import mean_squared_error import mlflow experiment_name="experiment-1" mlflow.set_experiment(experiment_name) no_of_trees=[100,200,300] depths=[2,3,4] for tree... | we can get the experiment id from the experiment name and we can use python API to get the best runs. experiment_name = "experiment-1" current_experiment=dict(mlflow.get_experiment_by_name(experiment_name)) experiment_id=current_experiment['experiment_id'] By using the experiment id, we can get all the runs and we can... | 14 | 30 |
65,226,602 | 2020-12-9 | https://stackoverflow.com/questions/65226602/why-is-plus-equals-valid-for-list-and-dictionary | Adding a dictionary to a list using the __iadd__ notation seems to add the keys of the dictionary as elements in the list. Why? For example a = [] b = {'hello': 'world'} a += b print(a) # -> ['hello'] The documentation for plus-equals on collections doesn't imply to me that this should happen: For instance, to execut... | My best guess is that the __iadd__ is invoking extend, which is defined here, and then it tries to iterate over the dictionary, which in turn yields its keys. But this seems... weird? And I don't see any intuition of that coming from the docs. This is the correct answer for why this happens. I've found the relevant d... | 15 | 16 |
65,241,321 | 2020-12-10 | https://stackoverflow.com/questions/65241321/python-shift-enter-not-working-in-vscode-with-jupyter | I have a new install of VS Code Version 1.50.1 with the python extension that now added the Jupyter extension. The Jupyter extension build number is 2020.12.411183115 When I press shift enter on the default it adds a new line below. You can see in the video that shift + enter should work to run the line. At this point ... | Please use the following shortcut key settings: { "key": "shift+enter", "command": "jupyter.execSelectionInteractive", "when": "editorTextFocus" }, This shortcut key is set with the use conditions, and it can be used only when it is confirmed (including the control panel is opened). Therefore, we can remove the use co... | 18 | 7 |
65,230,006 | 2020-12-10 | https://stackoverflow.com/questions/65230006/how-to-create-a-figure-of-subplots-of-grouped-bar-charts-in-python | I want to combine multiple grouped bar charts into one figure, as the image below shows. grouped bar charts in a single figure import matplotlib import matplotlib.pyplot as plt import numpy as np labels = ['G1', 'G2', 'G3'] yesterday_test1_mean = [20, 12, 23] yesterday_test2_mean = [21, 14, 25] today_test1_mean = [18, ... | Well, I tried something. Here's a rough result. Only thing I changed is that rather using axes, I am just using subplot as I learned over time. So with fig and axes as output, there must be a way too. But this is all I've ever used. I've not added the legend and title yet, but I guess you can try it on your own too. He... | 6 | 7 |
65,278,110 | 2020-12-13 | https://stackoverflow.com/questions/65278110/how-does-gunicorn-distribute-requests-across-sync-workers | I am using gunicorn to run a simple HTTP server1 using e.g. 8 sync workers (processes). For practical reasons I am interested in knowing how gunicorn distributes incoming requests between these workers. Assume that all requests take the same time to complete. Is the assignment random? Round-robin? Resource-based? The c... | Gunicorn does not distribute requests. Each worker is spawned with the same LISTENERS (e.g. gunicorn.sock.TCPSocket) in Arbiter.spawn_worker(), and calls listener.accept() on its own. The assignment in the blocking OS calls to the socket's accept() method — i.e. whichever worker is later woken up by the OS kernel and g... | 13 | 9 |
65,290,242 | 2020-12-14 | https://stackoverflow.com/questions/65290242/pythons-platform-mac-ver-reports-incorrect-macos-version | I'm using Python platform module to identify the MacOS version like this: import platform print(platform.mac_ver()) Output: In [1]: import platform In [2]: platform.mac_ver() Out[2]: ('10.16', ('', '', ''), 'x86_64') I have updated to BigSur and the version is incorrect, it should be 11.0.1 I looked at the source co... | In the Known Issues section of the Big Sur release notes, the following is present: Some third-party scripts might produce unexpected results due to the change in macOS version from 10.x to 11. (62477208) Workaround: Set SYSTEM_VERSION_COMPAT=1 in the calling environment, for example: $ SYSTEM_VERSION_COMPAT=1 legacy_... | 9 | 12 |
65,292,230 | 2020-12-14 | https://stackoverflow.com/questions/65292230/reply-to-a-message-discord-py | I want to make my bot react to a users message when they type a certain sentence. My code to reply: await ctx.message.reply("I just replied to you") I get the error: ctx.message has no attribute "reply" What code can I do to make the bot reply to the message? When I say reply, I mean the same as a user can press repl... | To any new user here, as of the 1.6.0 discord.py-rewrite update, you are now able to reply! Every message or context now has a reply attribute. To reply, simply use await ctx.reply('Hello!') You can also not mention the author in the reply with mention_author=False await ctx.reply('Hello!', mention_author=False) Yo... | 14 | 32 |
65,248,401 | 2020-12-11 | https://stackoverflow.com/questions/65248401/why-is-my-confusion-matrix-returning-only-one-number | I'm doing a binary classification. Whenever my prediction equals the ground truth, I find sklearn.metrics.confusion_matrix to return a single value. Isn't there a problem? from sklearn.metrics import confusion_matrix print(confusion_matrix([True, True], [True, True]) # [[2]] I would expect something like: [[2 0] [0 0]... | You should fill-in labels=[True, False]: from sklearn.metrics import confusion_matrix cm = confusion_matrix(y_true=[True, True], y_pred=[True, True], labels=[True, False]) print(cm) # [[2 0] # [0 0]] Why? From the docs, the output of confusion_matrix(y_true, y_pred) is: C: ndarray of shape (n_classes, n_classes) The... | 10 | 13 |
65,235,535 | 2020-12-10 | https://stackoverflow.com/questions/65235535/how-long-does-the-event-loop-live-in-a-django-3-1-async-view | I am playing around with the new async views from Django 3.1. Some benefits I would love to have is to do some simple fire-and-forget "tasks" after the view already gave its HttpResponse, like sending a push notification or sending an email. I am not looking for solutions with third-party packages like celery! To test ... | Django (which does not provide an ASGI server) does not limit the lifetime of the event loop. In the case of this question: ASGI server: Uvicorn Event loop: either the built-in asyncio event loop or uvloop (both do not limit their lifetime) For Uvicorn: How long does the event loop live? The event loop lives as long... | 9 | 4 |
65,273,118 | 2020-12-13 | https://stackoverflow.com/questions/65273118/why-is-tensorflow-not-recognizing-my-gpu-after-conda-install | I am new to deep learning and I have been trying to install tensorflow-gpu version in my pc in vain for the last 2 days. I avoided installing CUDA and cuDNN drivers since several forums online don't recommend it due to numerous compatibility issues. Since I was already using the conda distribution of python before, I w... | August 2021 Conda install may be working now, as according to @ComputerScientist in the comments below, conda install tensorflow-gpu==2.4.1 will give cudatoolkit-10.1.243 and cudnn-7.6.5 The following was written in Jan 2021 and is out of date Currently conda install tensorflow-gpu installs tensorflow v2.3.0 and does N... | 30 | 50 |
65,271,060 | 2020-12-12 | https://stackoverflow.com/questions/65271060/is-there-a-built-in-way-to-use-inline-c-code-in-python | Even if numba, cython (and especially cython.inline) exist, in some cases, it would be interesting to have inline C code in Python. Is there a built-in way (in Python standard library) to have inline C code? PS: scipy.weave used to provide this, but it's Python 2 only. | Directly in the Python standard library, probably not. But it's possible to have something very close to inline C in Python with the cffi module (pip install cffi). Here is an example, inspired by this article and this question, showing how to implement a factorial function in Python + "inline" C: from cffi import FFI ... | 6 | 7 |
65,278,555 | 2020-12-13 | https://stackoverflow.com/questions/65278555/typeerror-nan-inf-not-supported-in-write-number-without-nan-inf-to-errors-w | I want to save X (ndarray) with dimensions (3960, 225) in excel file (.xlsx). In X I have some missing values (nan). I made a code for it. However, I am getting the error. Here is the Code: workbook = xlsxwriter.Workbook('arrays.xlsx') worksheet = workbook.add_worksheet() row = 0 for col, data in enumerate(X): workshee... | Filling NaN values with zero, does not solve the problem, If you want to keep NaN values as NaN, you should skip filling value in like that: row = 0 for col, data in enumerate(X): try: worksheet.write_column(row, col, data) except: pass | 8 | 10 |
65,263,059 | 2020-12-12 | https://stackoverflow.com/questions/65263059/sampling-a-fixed-length-sequence-from-a-numpy-array | I have a data matrix a and I have list of indices stored in array idx. I would like to get 10-length data starting at each of the indices defined by idx . Right now I use a for loop to achieve this. But it is extremely slow as I have to do this data fetch about 1000 times in an iteration. Below is a minimum working exa... | (Thanks to suggestion from @MadPhysicist) This should work: a[idx.reshape(-1, 1) + np.arange(10)] Output: Shape (L,10), where L is the length of idx Notes: This does not check for index-out-of-bound situations. I suppose it's easy to first ensure that idx doesn't contain such values. Using np.take(a, idx.reshape(-1,... | 7 | 7 |
65,279,115 | 2020-12-13 | https://stackoverflow.com/questions/65279115/how-to-use-collate-fn-with-dataloaders | I am trying to train a pretrained roberta model using 3 inputs, 3 input_masks and a label as tensors of my training dataset. I do this using the following code: from torch.utils.data import TensorDataset, DataLoader, RandomSampler, SequentialSampler batch_size = 32 # Create the DataLoader for our training set. train_da... | Basically, the collate_fn receives a list of tuples if your __getitem__ function from a Dataset subclass returns a tuple, or just a normal list if your Dataset subclass returns only one element. Its main objective is to create your batch without spending much time implementing it manually. Try to see it as a glue that ... | 45 | 78 |
65,272,408 | 2020-12-13 | https://stackoverflow.com/questions/65272408/plotly-how-to-embed-a-fully-interactive-plotly-figure-in-excel | I'm trying to embed an interactive plotly (or bokeh) plot into excel. To do this I've tried the following three things: embed a Microsoft Web Browser UserForm into excel, following: How do I embed a browser in an Excel VBA form? This works and enables both online and offline html to be loaded creating a plotly htm... | Finally, I have managed to bring the interactive plot to excel after a discussion from Microsoft QnA and Web Browser Control & Specifying the IE Version To insert a Microsoft webpage to excel you have to change the compatibility Flag in the registry editor Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Office\ClickToRu... | 11 | 1 |
65,314,235 | 2020-12-15 | https://stackoverflow.com/questions/65314235/how-should-i-configure-my-headers-to-make-an-http-2-post-to-apns-to-avoid-recei | I'm pretty new to HTTP stuff, primarily stick to iOS so please bear with me. I'm using the httpx python library to try and send a notification to an iPhone because I have to make an HTTP/2 POST to do so. Apple's Documentation says it requires ":method" and ":path" headers but I when I try to make the POST with these he... | Just need to append '/3/device/{}'.format(deviceToken) to the devServer url as the path, and the ":path" pseudo-header will be automatically set to it. that is, devServer = 'https://api.sandbox.push.apple.com:443/3/device/{}'.format(deviceToken) Explanation: The ":path", ":method" and ":scheme" pseudo-headers generall... | 7 | 4 |
65,305,864 | 2020-12-15 | https://stackoverflow.com/questions/65305864/understanding-weightedkappaloss-using-keras | I'm using Keras to try to predict a vector of scores (0-1) using a sequence of events. For example, X is a sequence of 3 vectors comprised of 6 features each, while y is a vector of 3 scores: X [ [1,2,3,4,5,6], <--- dummy data [1,2,3,4,5,6], [1,2,3,4,5,6] ] y [0.34 ,0.12 ,0.46] <--- dummy data I want to adress the pro... | Let we separate the goal to two sub-goals, we walk through the purpose, concept, mathematical details of Weighted Kappa first, after that we summarize the things to note when we try to use WeightedKappaLoss in tensorflow PS: you can skip the understand part if you only care about usage Weighted Kappa detailed explanat... | 6 | 11 |
65,304,455 | 2020-12-15 | https://stackoverflow.com/questions/65304455/something-wrong-when-implementing-svm-one-vs-all-in-python | I was trying to verify that I had correctly understood how SVM - OVA (One-versus-All) works, by comparing the function OneVsRestClassifier with my own implementation. In the following code, I implemented num_classes classifiers in the training phase, and then tested all of them on the testset and selected the one retur... | Is there something wrong in my own implementation of SVM - OVA? You have unique classes array([3, 4, 5, 6, 7, 8, 9]), however the line Y_pred = prob_table.argmax(axis=1) assumes they are 0-indexed. Try refactoring your code to be less error prone to assumptions like that: from sklearn.svm import SVC from sklearn.metr... | 5 | 6 |
65,233,000 | 2020-12-10 | https://stackoverflow.com/questions/65233000/how-to-find-an-existing-html-element-with-python-selenium-in-a-jupyterhub-page | I have the following construct in a HTML page and I want to select the li element (with python-selenium): <li class="p-Menu-item p-mod-disabled" data-type="command" data-command="notebook:run-all-below"> <div class="p-Menu-itemIcon"></div> <div class="p-Menu-itemLabel" style="">Run Selected Cell and All Below</div> <di... | You were close enough. Factually your entire program had only a single issue as follows: The xpath_runall = "//li[@data-command='notebook:run-all-below']" doesn't identify the visible element with text as Run Selected Cell and All Below uniquely as the first matched element is a hidden element. Additional considerat... | 6 | 4 |
65,296,604 | 2020-12-14 | https://stackoverflow.com/questions/65296604/how-to-return-a-htmlresponse-with-fastapi | Is it possible to display an HTML file at the endpoint? For example the home page then the user is visiting "/"? | Yes, it's possible FastAPI has HTMLResponse. You can return a HTMLResponse from fastapi import FastAPI from fastapi.responses import HTMLResponse app = FastAPI() @app.get("/", response_class=HTMLResponse) async def read_items(): html_content = """ <html> <head> <title>Some HTML in here</title> </head> <body> <h1>Look m... | 33 | 56 |
65,315,077 | 2020-12-15 | https://stackoverflow.com/questions/65315077/interpreter-crashes-trying-to-use-tkinter-library | I have tried to staring the application in VSCODE by Python3. This is the code: from tkinter import * window = Tk() window.mainloop() only 3 lines :)), but when I'm trying to execute the file in terminal it will give me an error, which you can see below. arash@Arash-MacBook-Pro tkinter % python3 main.py macOS 11 or la... | This is an issue in the way brew installs Python (source). If you install Python directly via the official installer here then tkinter should work as expected. | 8 | 12 |
65,216,292 | 2020-12-9 | https://stackoverflow.com/questions/65216292/how-to-define-a-dataclass-so-each-of-its-attributes-is-the-list-of-its-subclass | I have this code: from dataclasses import dataclass from typing import List @dataclass class Position: name: str lon: float lat: float @dataclass class Section: positions: List[Position] pos1 = Position('a', 52, 10) pos2 = Position('b', 46, -10) pos3 = Position('c', 45, -10) sec = Section([pos1, pos2 , pos3]) print(sec... | You could create a new field after __init__ was called: from dataclasses import dataclass, field, fields from typing import List @dataclass class Position: name: str lon: float lat: float @dataclass class Section: positions: List[Position] _pos: dict = field(init=False, repr=False) def __post_init__(self): # create _po... | 6 | 6 |
65,298,241 | 2020-12-15 | https://stackoverflow.com/questions/65298241/what-does-this-tensorflow-message-mean-any-side-effect-was-the-installation-su | I just installed tensorflow v2.3 on anaconda python. I tried to test out the installation using the python command below; $ python -c "import tensorflow as tf; x = [[2.]]; print('tensorflow version', tf.__version__); print('hello, {}'.format(tf.matmul(x, x)))" I got the following message; 2020-12-15 07:59:12.411952: I... | An important part of Tensorflow is that it is supposed to be fast. With a suitable installation, it works with CPUs, GPUs, or TPUs. Part of going fast means that it uses different code depending on your hardware. Some CPUs support operations that other CPUs do not, such as vectorized addition (adding multiple variables... | 159 | 302 |
65,311,659 | 2020-12-15 | https://stackoverflow.com/questions/65311659/getting-the-latest-python-3-version-programmatically | I want to get the latest Python source from https://www.python.org/ftp/python/. While posting this, the latest version is 3.9.1. I do not want to hardcode 3.9.1 in my code to get the latest version and keep on updating the version when a new version comes out. I am using Ubuntu 16.04. Is there a programmatic way to get... | I had a similar problem and couldn't find anything better than scraping the downloads page. You mentioned curl, so I'm assuming you want a shell script. I ended up with this: url='https://www.python.org/ftp/python/' curl --silent "$url" | sed -n 's!.*href="\([0-9]\+\.[0-9]\+\.[0-9]\+\)/".*!\1!p' | sort -rV | while read... | 6 | 5 |
65,289,591 | 2020-12-14 | https://stackoverflow.com/questions/65289591/stacked-grouped-bar-chart | I'm trying to create a bar chart using plotly in python, which is both stacked and grouped. Toy example (money spent and earned in different years): import pandas as pd import plotly.graph_objs as go data = pd.DataFrame( dict( year=[2000,2010,2020], var1=[10,20,15], var2=[12,8,18], var3=[10,17,13], var4=[12,11,20], ) )... | There doesn't seem to be a way to create both stacked and grouped bar charts in Plotly, but there is a workaround that might resolve your issue. You will need to create subgroups, then use a stacked bar in Plotly to plot the bars one at a time, plotting var1 and var2 with subgroup1, and var3 and var4 with subgroup2. Th... | 9 | 8 |
65,271,399 | 2020-12-13 | https://stackoverflow.com/questions/65271399/vs-code-pylance-pylint-cannot-resolve-import | The Summary I have a python import that works when run from the VS Code terminal, but that VS Code's editor is giving warnings about. Also, "Go to Definition" doesn't work. The Problem I have created a docker container from the image tensorflow/tensorflow:1.15.2-py3, then attach to it using VS Code's "Remote- Container... | tldr; TensorFlow defines some of its modules in a way that pylint & pylance aren't able to recognize. These errors don't necessarily indicate an incorrect setup. To Fix: pylint: The pylint warnings are safely ignored. Intellisense: The best way I know of at the moment to fix Intellisense is to replace the imports with... | 17 | 9 |
65,301,875 | 2020-12-15 | https://stackoverflow.com/questions/65301875/how-to-understand-creating-leaf-tensors-in-pytorch | From PyTorch documentation: b = torch.rand(10, requires_grad=True).cuda() b.is_leaf False # b was created by the operation that cast a cpu Tensor into a cuda Tensor e = torch.rand(10).cuda().requires_grad_() e.is_leaf True # e requires gradients and has no operations creating it f = torch.rand(10, requires_grad=True, d... | When a tensor is first created, it becomes a leaf node. Basically, all inputs and weights of a neural network are leaf nodes of the computational graph. When any operation is performed on a tensor, it is not a leaf node anymore. b = torch.rand(10, requires_grad=True) # create a leaf node b.is_leaf # True b = b.cuda() #... | 11 | 17 |
65,300,649 | 2020-12-15 | https://stackoverflow.com/questions/65300649/the-command-pip-install-upgrade-pip-install-all-version-of-pip | When I run this command, pip install --upgrade pip, all version of pip is installed (in Linux/2.9.16) I just want to update pip that I'm using to the latest. How could I resolve this? Below is what I got from the command pip install --upgrade pip Requirement already satisfied: pip in /opt/python/run/venv/lib/python3.6/... | I answer my question myself. To find the cause of the problem, I created and tested a new virtualenv within the beanstalk instance. At first, pip install --upgrade setuptools, pip install --upgrade pip works properly. But after upgrading pip to the latest (2020.3.2), pip install --upgrade setuptools make the same probl... | 7 | 6 |
65,293,813 | 2020-12-14 | https://stackoverflow.com/questions/65293813/whats-the-best-way-to-find-lines-on-a-very-poor-quality-image-knowing-the-angl | i'm trying to find theses two horizontal lines with the Houghlines transform. As you can see, the picture is very noisy ! Currently my workflow looks like this : crop the image blur it low the noise (for that, I invert the image, and then substract the blured image to the inverted one) open it and dilate it with an... | the issue is the noise and the faint signal. you can subdue the noise with averaging/integration, while maintaining the signal because it's replicated along a dimension (signal is a line). your approach using a very wide but narrow kernel can be extended to simply integrating along the whole image. rotate the image so... | 5 | 9 |
65,295,837 | 2020-12-14 | https://stackoverflow.com/questions/65295837/turn-string-representation-of-interval-into-actual-interval-in-pandas | My problem is kind of simple, but I'm not sure there's a way to do what I'm looking for: I had to store in a SQL database some data, that includes some intervals that will later be used. Because of this, I had to store it as a string, like this: variable interval A (-0.001, 2.0] A (2.0, 6.0] So, then, I want to use s... | IIUC, you could parse the string by hand, then convert bins to IntervalIndex: import ast import pandas as pd def interval_type(s): """Parse interval string to Interval""" table = str.maketrans({'[': '(', ']': ')'}) left_closed = s.startswith('[') right_closed = s.endswith(']') left, right = ast.literal_eval(s.translate... | 6 | 9 |
65,285,516 | 2020-12-14 | https://stackoverflow.com/questions/65285516/ipython-display-how-to-change-width-height-and-resolution-of-a-displayed-image | I am displaying an image of a molecule using IPython.display in Jupyter. The resolution of the image is quite low. Is there a way to specify the width and height of the displayed image and its resolution? I googled it and could not find anything. All I need is something like this: display(moleSmilemol, format='svg', w... | Try changing the variables in the rdkit.Chem.Draw.IPythonConsole module: from rdkit.Chem.Draw import IPythonConsole IPythonConsole.molSize = (800, 800) # Change image size IPythonConsole.ipython_useSVG = True # Change output to SVG mol = Chem.MolFromSmiles('N#Cc1cccc(-c2nc(-c3cccnc3)no2)c1') display(mol) Otherwise, yo... | 6 | 3 |
65,284,942 | 2020-12-14 | https://stackoverflow.com/questions/65284942/what-is-a-python-pandas-equivalent-to-rs-with | In R I can have a data.frame or a list with several arguments, and I can operate on them using the with function. For example: d <- data.frame(x = 1:3, y = 2:4, z = 3:5) # I can use: d$x+d$y*d$z-5 # Or, more simply, I can use: with(d, x+y*z-5) # [1] 2 9 18 In pandas DataFrame I can use: d = {'x': [1, 2, 3], 'y': [2, 3... | One idea is use DataFrame.eval if need processing some columns names some simple arithmetic operations: print (df.x+df.y*df.z-5) 0 2 1 9 2 18 dtype: int64 print (df.eval('x+y*z-5')) 0 2 1 9 2 18 dtype: int64 | 8 | 8 |
65,233,882 | 2020-12-10 | https://stackoverflow.com/questions/65233882/among-the-many-python-file-copy-functions-which-ones-are-safe-if-the-copy-is-in | As seen in How do I copy a file in Python?, there are many file copy functions: shutil.copy shutil.copy2 shutil.copyfile (and also shutil.copyfileobj) or even a naive method: with open('sourcefile', 'rb') as f, open('destfile', 'wb') as g: while True: block = f.read(16*1024*1024) # work by blocks of 16 MB if not bl... | Assuming that destfile does not exist prior to the copy, the naive method is safe, per your definition of safe. shutil.copyfileobj() and shutil.copyfile() are close second in the ranking. shutils.copy() is next, and shutils.copy2() would be last. Explanation: It is a filesystem's job to guarantee consistency based on a... | 15 | 8 |
65,282,049 | 2020-12-14 | https://stackoverflow.com/questions/65282049/local-scope-vs-relative-imports-inside-init-py | I've noticed that asyncio/init.py from python 3.6 uses the following construct: from .base_events import * ... __all__ = (base_events.__all__ + ...) The base_events symbol is not imported anywhere in the source code, yet the module still contains a local variable for it. I've checked this behavior with the following c... | This behavior is defined in The import system documentation section 5.4.2 Submodules When a submodule is loaded using any mechanism (e.g. importlib APIs, the import or import-from statements, or built-in import()) a binding is placed in the parent module’s namespace to the submodule object. For example, if package spa... | 9 | 8 |
65,280,790 | 2020-12-13 | https://stackoverflow.com/questions/65280790/install-newer-version-of-sqlite3-on-aws-lambda | I want to use Window functions on sqlite3 on my python3.8 code running on AWS Lambda. They are available since version 3.25. Unfortunately, on AWS Lambda Python3.8, sqlite3 library is outdated: >>> sqlite3.sqlite_version '3.7.17' while locally, on my homebrew install of Python3.8: (working) >>> import sqlite3 >>> sqli... | I found a way: I used the external package pysqlite3, in the binary version. in my requirements.txt pysqlite3-binary==0.4.4 in the code try: import pysqlite3 as sqlite3 except ModuleNotFoundError: import sqlite3 # for local testing because pysqlite3-binary couldn't be installed on macos | 6 | 5 |
65,270,624 | 2020-12-12 | https://stackoverflow.com/questions/65270624/how-to-connect-to-a-sqlite3-db-file-and-fetch-contents-in-fastapi | I have a sqlite.db file which has 5 columns and 10million rows. I have created a api using fastapi, now in one of the api methods I want to connect to that sqlite.db file and fetch content based on certain conditions (based on the columns present). I mostly will be using SELECT and WHERE. How can I do it by also taking... | You are missing a point here, defining a function with async is not enough. You need to use an asynchronous Database Driver to taking the advantage of using a coroutine. Encode's Databases library is great for this purpose. pip install databases You can also install the required database drivers with: pip install data... | 6 | 15 |
65,252,463 | 2020-12-11 | https://stackoverflow.com/questions/65252463/mypy-class-forward-references-in-type-alias-gives-error-when-in-other-module | I want to keep my type aliases in one module, say my_types, to be able to use them anywhere in my application (similar to the standard typing module). But mypy complains that the forward reference to class X is not defined. If I define class X later in that same module, it’s okay, but if it defined in another one, mypy... | I’m gonna share the solution I found in the mypy documentation common issues section here: It is necessary for mypy to have access to the definition of X. To avoid an import cycle, the mypy documentation recommends a trick - only import the definition that would create a cyclic import when type checking. It goes like t... | 6 | 12 |
65,263,061 | 2020-12-12 | https://stackoverflow.com/questions/65263061/selecting-multiple-columns-to-plot-with-plotly-python | I have the following code: def campaign_plot(col1,col2): grouper = df.groupby(['Day','Campaign']).agg({col1: 'sum', col2: 'mean'}).unstack() result = grouper.fillna(0) fig = go.Figure() fig.add_trace(go.Scatter( x = result.index, y = result.iloc[:, [0, 4]], #<--- name = '1', line = dict( color = ('rgb(205, 12, 24)'), w... | Another approach would be to melt you dataframe. Here is an example of how you could do this.Suppose that you have the following dataframe: Date High Low Open Close Volume \ 0 2019-01-02 19.000000 17.980000 18.010000 18.830000 87148700 1 2019-01-03 18.680000 16.940001 18.420000 17.049999 117277600 2 2019-01-04 19.0700... | 6 | 5 |
65,258,942 | 2020-12-11 | https://stackoverflow.com/questions/65258942/remove-duplicate-value-from-list-of-tuples-based-on-values-from-another-list | I have 2 lists similar to these: l1 = [('zero', 0),('one', 2),('two', 3),('three', 3),('four', 5)] l2 = [('zero', 0),('one', 3),('four', 2),('ten', 3),('twelve', 8)] I want to compare the lists and remove duplicates from both if both values are the same if the first value is a match remove the tuple from the list whe... | You could do: d1 = dict(l1) d2 = dict(l2) l3 = [(k, v) for k, v in d1.items() if k not in d2 or d2[k] < v] l4 = [(k, v) for k, v in d2.items() if k not in d1 or d1[k] < v] print(l3) print(l4) Output [('two', 3), ('three', 3), ('four', 5)] [('one', 3), ('ten', 3), ('twelve', 8)] The idea is to use dictionaries for fas... | 7 | 6 |
65,247,307 | 2020-12-11 | https://stackoverflow.com/questions/65247307/find-the-minimum-possible-difference-between-two-arrays | I am struggling to figure out an efficient algorithm to perform the following task: Given two arrays A and B with equal length, the difference between the two arrays is defined as: diff = |a[0]-b[0]| + |a[1]-b[1]| +...+|a[a.length-1]-b[b.length-1]| I am required to find the minimum possible difference between A and B,... | I'll implement Shridhar's suggestion of identifying the best modification for each element individually in O(n log n) time and taking the best one. import bisect def abs_diff(x, y): return abs(x - y) def find_nearest(sorted_a, y): i = bisect.bisect(sorted_a, y) return min( sorted_a[max(i - 1, 0) : min(i + 1, len(sorted... | 9 | 3 |
65,246,703 | 2020-12-11 | https://stackoverflow.com/questions/65246703/how-does-max-length-padding-and-truncation-arguments-work-in-huggingface-bertt | I am working with Text Classification problem where I want to use the BERT model as the base followed by Dense layers. I want to know how does the 3 arguments work? For example, if I have 3 sentences as: 'My name is slim shade and I am an aspiring AI Engineer', 'I am an aspiring AI Engineer', 'My name is Slim' SO what... | What you have assumed is almost correct, however, there are few differences. max_length=5, the max_length specifies the length of the tokenized text. By default, BERT performs word-piece tokenization. For example the word "playing" can be split into "play" and "##ing" (This may not be very precise, but just to help you... | 27 | 35 |
65,244,798 | 2020-12-11 | https://stackoverflow.com/questions/65244798/in-python-how-do-i-type-hint-has-attribute | Consider this contrived example; @dataclass class A: name: str = "John" .... @dataclass class B: name: str = "Doe" Q: How do I type hint an object that has an attribute, such as the following? def print_name(obj: HasAttr['name']) print(obj.name) I understand the SO rule on showing what you have tried. The best I can ... | So, what you are describing is structural typing. This is distinct from the class-based nominal subtyping that the python typing system is based on. However, structural subtyping is sort of the statically typed version of Python's dynamic duck typing. Python's typing system allows a form of this through typing.Protocol... | 9 | 11 |
65,240,677 | 2020-12-10 | https://stackoverflow.com/questions/65240677/django-admin-interface-how-to-change-user-password | In Django: I have created a super user and can view all the users I have also implemented forgot password for my user, who can input their email and a password reset link is sent to their email and then the user can reset his password But how can admin change some users password from the admin dashboard | This answer is just an extension of answer by @kunal Sharma To change user password from Django admin Go into the user and click this form, and a form below will be shown, change password there | 19 | 7 |
65,233,123 | 2020-12-10 | https://stackoverflow.com/questions/65233123/adding-percentage-of-count-to-a-stacked-bar-chart-in-plotly | Given the following chart created in plotly. I want to add the percentage values of each count for M and F categories inside each block. The code used to generate this plot. arr = np.array([ ['Dog', 'M'], ['Dog', 'M'], ['Dog', 'F'], ['Dog', 'F'], ['Cat', 'F'], ['Cat', 'F'], ['Cat', 'F'], ['Cat', 'M'], ['Fox', 'M'], ['... | As far as I know histograms in Plotly don't have a text attribute. But you could generate the bar chart yourself and then add the percentage via the text attribute. import numpy as np import pandas as pd import plotly.express as px arr = np.array([ ['Dog', 'M'], ['Dog', 'M'], ['Dog', 'F'], ['Dog', 'F'], ['Cat', 'F'], [... | 5 | 16 |
65,238,459 | 2020-12-10 | https://stackoverflow.com/questions/65238459/templatedoesnotexist-at-users-register-bootstrap5-uni-form-html | I am building a registration form for my django project, and for styling it I am using crispy forms. But, when I run my server and go to my registration page, I see this error: Internal Server Error: /users/register/ Traceback (most recent call last): File "C:\Users\Dell\Desktop\Django\microblog\venv\lib\site-packages... | Based on the latest crispy form doc, it seems that there is no built-in bootstrap5 for it. Are you sure you are using bootstrap5? Currently, there are only bootstrap, bootstrap3, bootstrap4, and uni-form. You can take a look at your file structure if you even see bootstrap5 folder. | 14 | 4 |
65,234,748 | 2020-12-10 | https://stackoverflow.com/questions/65234748/what-is-the-numpy-equivalent-of-expand-in-pytorch | Suppose I have a numpy array x of shape [1,5]. I want to expand it along axis 0 such that the resulting array y has shape [10,5] and y[i:i+1,:] is equal to x for each i. If x were a pytorch tensor I could simply do y = x.expand(10,-1) But there is no expand in numpy and the ones that look like it (expand_dims and repe... | You can achieve that with np.broadcast_to. But you can't use negative numbers: >>> import numpy as np >>> x = np.array([[ 1.3306, 0.0627, 0.5585, -1.3128, -1.4724]]) >>> print(np.broadcast_to(x,(10,5))) [[ 1.3306 0.0627 0.5585 -1.3128 -1.4724] [ 1.3306 0.0627 0.5585 -1.3128 -1.4724] [ 1.3306 0.0627 0.5585 -1.3128 -1.47... | 6 | 13 |
65,231,702 | 2020-12-10 | https://stackoverflow.com/questions/65231702/how-to-pass-multiple-parameters-to-azure-durable-activity-function | My orchestrator receives a payload, with that payload it contains instructions that need to be passed along with other sets of data to activity functions. how do I pass multiple parameters to an activity function? Or do I have to mash all my data together? def orchestrator_function(context: df.DurableOrchestrationConte... | Seems there's no text-book way to do it. I have opted to give my single parameter a generic name like parameter or payload. Then when passing in the value in the orchestrator I do it like so: payload = {"value_1": some_var, "value_2": another_var} something = yield context.call_activity("activity", payload) then withi... | 16 | 18 |
65,222,106 | 2020-12-9 | https://stackoverflow.com/questions/65222106/running-into-java-lang-outofmemoryerror-java-heap-space-when-using-topandas | I'm trying to transform a pyspark dataframe of size [2734984 rows x 11 columns] to a pandas dataframe calling toPandas(). Whereas it is working totally fine (11 seconds) when using an Azure Databricks Notebook, I run into a java.lang.OutOfMemoryError: Java heap space exception when i run the exact same code using datab... | This is likely because Databricks-connect is executing the toPandas on the client machine which can then run out of memory. You could increase the local driver memory by setting spark.driver.memory in the (local) config file ${spark_home}/conf/spark-defaults.conf where ${spark_home} can be obtained with databricks-conn... | 8 | 10 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.