question_id
int64
59.5M
79.7M
creation_date
stringdate
2020-01-01 00:00:00
2025-07-15 00:00:00
link
stringlengths
60
163
question
stringlengths
53
28.9k
accepted_answer
stringlengths
26
29.3k
question_vote
int64
1
410
answer_vote
int64
-9
482
71,271,759
2022-2-25
https://stackoverflow.com/questions/71271759/how-to-change-markupsafe-version-in-virtual-environment
I am trying to make an application using python and gRPC as shown in this article - link I am able to run the app successfully on my terminal but to run with a frontend I need to run it as a flask app, codebase. And I am doing all this in a virtual environment. when I run my flask command FLASK_APP=marketplace.py flask...
If downgrading will solve the issue for you try the following code inside your virtual environment. pip install MarkupSafe==2.0.1
11
20
71,272,151
2022-2-25
https://stackoverflow.com/questions/71272151/return-generator-instead-of-list-from-df-to-dict
I am working on a large Pandas DataFrame which needs to be converted into dictionaries before being processed by another API. The required dictionaries can be generated by calling the .to_dict(orient='records') method. As stated in the docs, the returned value depends on the orient option: Returns: dict, list or colle...
There is not a way to get a generator directly from to_dict(orient='records'). However, it is possible to modify the to_dict source code to be a generator instead of returning a list comprehension: from pandas.core.common import standardize_mapping from pandas.core.dtypes.cast import maybe_box_native def dataframe_reco...
5
4
71,271,825
2022-2-25
https://stackoverflow.com/questions/71271825/how-to-get-setup-cfg-metadata-at-the-command-line-python
When you have a setup.py file, you can get the name of the package via the command: C:\some\dir>python setup.py --name And this would print the name of the package to the command line. In an attempt to adhere to best practice, I'm trying to migrate away from setup.py by putting everything in setup.cfg since everything...
Maybe using the ConfigParser Python module ? python -c "from configparser import ConfigParser; cf = ConfigParser(); cf.read('setup.cfg'); print(cf['metadata']['name'])"
10
4
71,265,214
2022-2-25
https://stackoverflow.com/questions/71265214/github-actions-issue-error-process-completed-with-exit-code-2
I have following piece of code for github actions: name: Python application on: push: branches: [ main ] jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Install dependencies run: / python -m pip install --upgrade pip python -m pip install numpy pytest if [ -f requirements.txt ]; then pip ...
Yes - you have a simple mistake there :) To have multiple commands under run you have to use: run: | not \ \ is used later on to have one bash command split into multiple lines name: Python application on: push: branches: [ main ] jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Install de...
5
6
71,253,495
2022-2-24
https://stackoverflow.com/questions/71253495/how-to-annotate-the-type-of-arguments-forwarded-to-another-function
Let's say we have a trivial function that calls open() but with a fixed argument: def open_for_writing(*args, **kwargs): kwargs['mode'] = 'w' return open(*args, **kwargs) If I now try to call open_for_writing(some_fake_arg = 123), no type checker (e.g. mypy) can tell that this is an incorrect invocation: it's missing ...
I think out of the box this is not possible. However, you could write a decorator that takes the function that contains the arguments you want to get checked for (open in your case) as an input and returns the decorated function, i.e. open_for_writing in your case. This of course only works with python 3.10 or using ty...
19
11
71,261,347
2022-2-25
https://stackoverflow.com/questions/71261347/runtimeerror-dataloader-worker-exited-unexpectedly
I am new to PyTorch and Machine Learning so I try to follow the tutorial from here: https://medium.com/@nutanbhogendrasharma/pytorch-convolutional-neural-network-with-mnist-dataset-4e8a4265e118 By copying the code step by step I got the following error for no reason. I tried the program on another computer and it gives...
If you are working on jupyter notebook. The problem is more likely to be num_worker. You should set num_worker=0. You can find here some solutions to follow. Because unfortunately, jupyter notebook has some issues with running multiprocessing.
6
6
71,261,860
2022-2-25
https://stackoverflow.com/questions/71261860/what-does-q-means-in-pip-install-q-package-name
In the below example, I am trying to install gradio package but I have seen -q flag is used in some tutorials to install packages.What does '-q' flag means in pip install -q ? pip install -q gradio
Running pip3 --help gives you this: -q, --quiet Give less output. Option is additive, and can be used up to 3 times (corresponding to WARNING, ERROR, and CRITICAL logging levels). So the -q option reduces the output produced by pip. It does not affect the installation process. It is a general option.
7
10
71,257,947
2022-2-24
https://stackoverflow.com/questions/71257947/what-is-the-scope-of-the-as-binding-in-an-except-statement-or-context-manage
I know that in general python only makes new scopes for classes, functions etc., but I'm confused by the as statement in a try/except block or context manager. Variables assigned inside the block are accessible outside it, which makes sense, but the variable bound with as itself is not. So this fails: try: raise Runtim...
As explained in PEP 3110, as well as current documentation, variables bound with as in an except block are explicitly and specially cleared at the end of the block, even though they share the same local scope. This improves the immediacy of garbage collection. The as syntax was originally not available for exceptions i...
7
8
71,242,328
2022-2-23
https://stackoverflow.com/questions/71242328/renv-venv-jupyterlab-irkernel-will-it-blend
Short version What is the simple and elegant way to use renv, venv and jupyterlab with IRkernel together? In particular, how to automatically activate renv from jupyter notebook that is not in the root directory? Long version I'm embracing a "polyglot" data science style, which means using both python and R in tandem. ...
I opened this question as an issue in the renv github repo, and maintainers kindly provided a workaround. The contents of the notebooks/.Rprofile should be as follows: owd <- setwd(".."); source("renv/activate.R"); setwd(owd) It blends! 🎉
5
8
71,245,281
2022-2-23
https://stackoverflow.com/questions/71245281/sqlalchemy-how-to-escape-a-bind-parameter-inside-of-text
How can I escape a : inside of a string passed to text() to prevent SQLAlchemy from treating it like a bindparameter? conn.execute(text("select 'My favorite emoticon is :p' from dual")).fetchone() Will result in: sqlalchemy.exc.StatementError: (sqlalchemy.exc.InvalidRequestError) A value is required for bind parameter...
As mentioned in the docs: For SQL statements where a colon is required verbatim, as within an inline string, use a backslash to escape But remember that the backslash is also the escape character in Python string literals, so text("select 'My favorite emoticon is \:p' from dual") is incorrect because Python will wan...
9
5
71,242,919
2022-2-23
https://stackoverflow.com/questions/71242919/pip-install-results-in-this-error-cl-exe-failed-with-exit-code-2
I've read all of the other questions on this error and frustratingly enough, none give a solution that works. If I run pip install sentencepiece in the cmd line, it gives me the following output. src/sentencepiece/sentencepiece_wrap.cxx(2809): fatal error C1083: Cannot open include file: 'sentencepiece_processor.h': N...
I haven't seen this problem in Windows, but for Linux, I would normally reinstall Python after installing the dependencies (such as the MSVC thing). In that case this is especially helpful because I'm often rebuilding (compiling and other related steps) Python/Pip. Could also just be an error specific to the module and...
9
4
71,244,250
2022-2-23
https://stackoverflow.com/questions/71244250/why-is-numpy-cartesian-product-slower-than-pure-python-version
Input import numpy as np import itertools a = np.array([ 1, 6, 7, 8, 10, 11, 13, 14, 15, 19, 20, 23, 24, 26, 28, 29, 33, 34, 41, 42, 43, 44, 45, 46, 47, 52, 54, 58, 60, 61, 65, 70, 75]).astype(np.uint8) b = np.array([ 2, 3, 4, 10, 12, 14, 16, 20, 22, 26, 28, 29, 30, 31, 34, 36, 37, 38, 39, 40, 41, 46, 48, 49, 50, 52, 5...
Why current implementations are slow While the first solution is faster than the second one, it is quite inefficient since it creates a lot of temporary CPython objects (at least 6 per item of itertools.product). Creating a lot of objects is expensive because they are dynamically allocated and reference-counted by CPyt...
5
3
71,244,472
2022-2-23
https://stackoverflow.com/questions/71244472/keep-getting-cors-policy-no-access-control-allow-origin-even-with-fastapi-cor
I am working on a project that has a FastAPI back end with a React Frontend. When calling the back end via fetch I sometimes get the following: Access to fetch at 'http://localhost:8000/get-main-query-data' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is p...
When a server side error occurs (a response code of 5xx), the CORS middleware doesn't get to add their headers since the request is effectively terminated, making it impossible for the browser to read the response. For your second problem, you should use a separate session for each invocation of your API. The reference...
5
9
71,238,056
2022-2-23
https://stackoverflow.com/questions/71238056/msedge-failed-to-start-crashed-chrome-not-reachable
I am a beginner to Selenium python. I have tried to invoke the Edge browser with an existing profile(Default) with the following code. But it is throwing the following exception as soon as the execution starts. Can someone please help me with this? Am I missing something? edge_options = webdriver.EdgeOptions() edge_opt...
I came across the issue before, that's because there're running Edge processes in the background. The solution is you can back up your User Data folder in the same path and use that folder in selenium: Back up your User Data folder in the same path. Here for example, I back up the User Data folder as User Data1: Use...
6
8
71,241,494
2022-2-23
https://stackoverflow.com/questions/71241494/is-it-safe-to-use-functions-from-numpy-core
To motivate the question: In recent NumPy versions there is a performance issue with numpy.clip and in the corresponding issue a suggested workaround is to use numpy.core.umath.clip. I couldn't really find anything about the purpose of the numpy.core.umath or more generally the numpy.core.* modules. pydoc shows documen...
The documentation of numpy.core states: Please note that this module is private. All functions and objects are available in the main numpy namespace - use that instead. This submodule is apparently not meant to be used by end-users. This is also why there is almost no online documentation about it. The functions in t...
5
5
71,232,996
2022-2-23
https://stackoverflow.com/questions/71232996/str-object-has-no-attribute-tag-error-in-django-tutorial
I am following the Django Tutorial to learn how to work with it, but I have encountered an error very early in it and I'm not sure how to fix it. It happened while creating the django project and doing the 'Write your first view' section: https://docs.djangoproject.com/en/dev/intro/tutorial01/#write-your-first-view Aft...
So, I've found the mistake I've made. In the tutorial there's a point where you add to mysite/urls.py this snippet: from django.contrib import admin from django.urls import include, path urlpatterns = [ path('polls/', include('polls.urls')), path('admin/', admin.site.urls), ] The autocomplete feature for python in vsc...
6
28
71,239,764
2022-2-23
https://stackoverflow.com/questions/71239764/how-to-cache-poetry-install-for-gitlab-ci
Is there a way to cache poetry install command in Gitlab CI (.gitlab-ci.yml)? For example, in node yarn there is a way to cache yarn install (https://classic.yarnpkg.com/lang/en/docs/install-ci/ Gitlab section) this makes stages a lot faster.
GitLab can only cache things in the working directory and Poetry stores packages elsewhere by default: Directory where virtual environments will be created. Defaults to {cache-dir}/virtualenvs ({cache-dir}\virtualenvs on Windows). On my machine, cache-dir is /home/chris/.cache/pypoetry. You can use the virtualenvs.in...
15
21
71,238,822
2022-2-23
https://stackoverflow.com/questions/71238822/why-is-setuptools-not-available-in-environment-ubuntu-docker-image-with-python
I'm trying to build a Ubuntu 18.04 Docker image running Python 3.7 for a machine learning project. When installing specific Python packages with pip from requirements.txt, I get the following error: Collecting sklearn==0.0 Downloading sklearn-0.0.tar.gz (1.1 kB) Preparing metadata (setup.py): started Preparing metadata...
As mentioned in comment, install setuptools with pip before running pip install -r requirements.txt. It is different than putting setuptools higher in the requirements.txt because it forces the order while the requirements file collect all the packages and installs them after so you don't control the order.
7
13
71,162,915
2022-2-17
https://stackoverflow.com/questions/71162915/conditional-call-of-a-fastapi-model
I have a multilang FastAPI connected to MongoDB. My document in MongoDB is duplicated in the two languages available and structured this way (simplified example): { "_id": xxxxxxx, "en": { "title": "Drinking Water Composition", "description": "Drinking water composition expressed in... with pesticides.", "category": "...
Option 1 A solution would be the following: Define lang as Query paramter and add a regular expression that the parameter should match. In your case, that would be ^(fr|en)$, meaning that only fr or en would be valid inputs. Thus, if no match was found, the request would stop there and the client would receive a "strin...
8
4
71,152,069
2022-2-17
https://stackoverflow.com/questions/71152069/how-to-run-python-code-directly-on-a-webpage
My problem is as follows: I have written a python code, and I need to run it on a web page.Basically I need that whatever is on the console should be displayed as it is. I have no experience in web development and similar libraries, and I need to get this done in a short time. Kindly tell how should I proceed? Note: I ...
ERROR: type should be string, got " https://brython.info/ https://skulpt.org/ https://pyodide.org/en/stable/ There are multiple python implementations in the browser: some are WebAssembly (WASM) and some are JavaScript. Is it a good idea to run python on browser as a replacement for JavaScript in 2022? No it is not; learn JavaScript. No in-browser python implementation can match JavaScript and its performance as of today and most probably ever."
7
6
71,196,737
2022-2-20
https://stackoverflow.com/questions/71196737/how-to-filter-a-polars-dataframe-by-date
df.filter(pl.col("MyDate") >= "2020-01-01") does not work like it does in pandas. I found a workaround df.filter(pl.col("MyDate") >= pl.datetime(2020,1,1)) but this does not solve a problem if I need to use string variables.
You can turn the string into a date type e.g. with .str.to_date() Building on the example above: import polars as pl from datetime import datetime df = pl.DataFrame({ "dates": [datetime(2021, 1, 1), datetime(2021, 1, 2), datetime(2021, 1, 3)], "vals": range(3) }) df.filter(pl.col('dates') >= pl.lit(my_date_str).str.to_...
10
10
71,172,212
2022-2-18
https://stackoverflow.com/questions/71172212/find-enum-value-by-enum-name-in-string-python
I'm struggling with Python enums. I created an enum class containing various fields: class Animal(Enum): DOG = "doggy" CAT = "cute cat" I know that I can access this enum with value i.e. by passing Animal("doggy") I will have Animal.DOG. However I would like to achieve the same but the other way around, let's say I ha...
As per the manual: >>> Animal.DOG.value 'doggy' >>> Animal.DOG.name 'DOG' >>> # For more programmatic access, with just the enum member name as a string: >>> Animal['DOG'].value 'doggy'
16
26
71,195,740
2022-2-20
https://stackoverflow.com/questions/71195740/vs-code-text-output-unreadable-format-in-new-window
I was using a jupyter notebook inside VSCode and used ?? on the object to look the source code. The output showed : Output exceeds the size limit. Open the full output data in a text editor But when I click on it it opens the output in another window but everything is illegible. What's going on here? What are those...
Those are ANSI escape codes- particularly ones for colouring. If ANSI color support in edit buffer #38834 gets implemented, then this problem will sort of "go away" by default (though I imagine it could lead to different kinds of confusion). The IPython configuration docs have a section on terminal colours: Interactiv...
11
6
71,140,633
2022-2-16
https://stackoverflow.com/questions/71140633/how-to-save-the-best-estimator-in-gridsearchcv
When faced with a large dataset, I need to spend a day using GridSearchCV() to train an SVM with the best parameters. How can I save the best estimator so that I can use this trained estimator directly when I start my computer next time?
By default, GridSearchCV does not expose or store the best model instance it only returns the parameter set that led to the highest score. If you want the best predictor, you have to specify refit=True, or if you are using multiple metrics refit=name-of-your-decider-metric. This will run a final training step using the...
5
12
71,146,731
2022-2-16
https://stackoverflow.com/questions/71146731/using-loc-in-pandas-without-discarding-the-outer-levels
I have a dataframe like df = pd.DataFrame({ 'level0': [0,1,2], 'level1': ['a', 'b', 'b'], 'level2':['x', 'x', 'x'], 'data': [0.12, 0.34, 0.45]} ).set_index(['level0', 'level1', 'level2']) level0 level1 level 2 data 0 a x 0.12 1 b x 0.34 2 b x 0.56 If level0, level1, and level2 are the index levels, I w...
You can use the output of MultiIndex.get_locs in iloc: >>> df.iloc[df.index.get_locs((2, 'b'))] data level0 level1 level2 2 b x 0.45
6
5
71,192,894
2022-2-20
https://stackoverflow.com/questions/71192894/python-multiprocessing-terminate-other-processes-after-one-process-finished
I have some programm in which multiple processes try to finish some function. My aim now is to stop all the other processes after one process has successfully finished the function. The python program shown below unfortunately waits until all the processes successfully solved the question given in find function. How ca...
Use an Event to govern if the processes should keep running. Basically, it replaces succ with something that works over all processes. import multiprocessing import random FIND = 50 MAX_COUNT = 1000 def find(process, initial, return_dict, run): while run.is_set(): start = initial while start <= MAX_COUNT: if FIND == st...
6
6
71,220,697
2022-2-22
https://stackoverflow.com/questions/71220697/python-dash-plotly-websockets
I'm a n00b with Dash and I'm trying to update a DashTable from websocket feeds. The code appears to work when there aren't too many feeds, but once there are, Chrome starts spamming my server with fetch requests (from dash_update_component) Is there any way to make this more performant ? import dash_bootstrap_component...
One thing you can do to improve performance is to convert your callbacks into clientside callbacks: symbols = ["ETHBUSD", "BNBUSDT", "BTCUSDT"] # ... app.clientside_callback( """ function(value) { const symbols = ['ETHBUSD', 'BTCUSDT', 'BNBUSDT'] const subMsg = { 'method': 'SUBSCRIBE', 'params': [], 'id': 1 }; for (con...
6
0
71,203,579
2022-2-21
https://stackoverflow.com/questions/71203579/how-to-return-a-csv-file-pandas-dataframe-in-json-format-using-fastapi
I have a .csv file that I would like to render in a FastAPI app. I only managed to render the .csv file in JSON format as follows: def transform_question_format(csv_file_name): json_file_name = f"{csv_file_name[:-4]}.json" # transforms the csv file into json file pd.read_csv(csv_file_name ,sep=",").to_json(json_file_na...
The below shows four different ways of returning the data stored in a .csv file/Pandas DataFrame (for solutions without using Pandas DataFrame, have a look here). Related answers on how to efficiently return a large dataframe can be found here and here as well. Option 1 The first option is to convert the file data into...
13
13
71,193,095
2022-2-20
https://stackoverflow.com/questions/71193095/questions-on-pyproject-toml-vs-setup-py
Reading up on pyproject.toml, python -m pip install, poetry, flit, etc - I have several questions regarding replacing setup.py with pyproject.toml. My biggest question was - how does a toml file replace a setup.py. Meaning, a toml file can't do everything a py file can. Reading into it, poetry and flit completely repla...
Currently I am investigating this feature too. I found this experimental feature explanation of setuptools which should just refer to the pyproject.toml without any need of setup.py in the end. Regarding dynamic behavior of setup.py, I figured out that you can set a dynamic behavior for fields under the [project] metad...
22
13
71,168,274
2022-2-18
https://stackoverflow.com/questions/71168274/create-custom-data-type-in-python
Hopefully the title isn't too misleading, I'm not sure the best way to phrase my question. I'm trying to create a (X, Y) coordinate data type in Python. Is there a way to create a "custom data type" so that I have an object with a value, but also some supporting attributes? So far I've made this simple class: class Poi...
I am not sure what you want to do with the tuple. p will always be an instance of Point. What you intend to do there won't work. If you just don't want to use the dot notation, you could use a namedtuple or a dataclass instead of a class. Then cast their instances to a tuple using tuple() and astuple(). Using a namedt...
8
7
71,200,479
2022-2-21
https://stackoverflow.com/questions/71200479/plotly-dash-zmqerror-address-already-in-use
I am testing Plotly Dash as a possible dashboarding tool. I am trying to run one of the charts found in the documentation: https://plotly.com/python/bar-charts/ import dash from dash import dcc from dash import html from dash.dependencies import Input, Output import plotly.express as px df = px.data.tips() days = df.da...
If you are running it from jupyter-notebook or jupyter-lab, you should run the app server as: app.run_server(debug=True, port=8049, use_reloader=False)
5
5
71,168,930
2022-2-18
https://stackoverflow.com/questions/71168930/change-pystray-tray-notification-title
I have an issue with finding a way to change the pystray tray notification title. It appears that it's taking a default value of "Python" from somewhere. See the image below: In the documentation, there are no additional parameters to change the notification icon title. How can I find a way to change the title value t...
Python is an interpreted language, which means that it executes code line by line rather than compiling the entire program into a standalone executable. This means that your program does not have a standalone existence until you compile it. In a Windows environment, the commands you have written are executed by python....
6
7
71,175,293
2022-2-18
https://stackoverflow.com/questions/71175293/make-built-in-lru-cache-skip-caching-when-function-returns-none
Here's a simplified function for which I'm trying to add a lru_cache for - from functools import lru_cache, wraps @lru_cache(maxsize=1000) def validate_token(token): if token % 3: return None return True for x in range(1000): validate_token(x) print(validate_token.cache_info()) outputs - CacheInfo(hits=0, misses=1000,...
You are missing the two lines marked here: def handle_exception(func): @wraps(func) def function_wrapper(*args, **kwargs): try: value = func(*args, **kwargs) return value except KeyError: return None function_wrapper.cache_info = func.cache_info # Add this function_wrapper.cache_clear = func.cache_clear # Add this retu...
9
5
71,196,661
2022-2-20
https://stackoverflow.com/questions/71196661/what-is-the-equivalent-of-dataframe-drop-duplicates-from-pandas-in-polars
What is the equivalent of drop_duplicates() from pandas in polars? import polars as pl df = pl.DataFrame({"a":[1,1,2], "b":[2,2,3], "c":[1,2,3]}) df Output: shape: (3, 3) ┌─────┬─────┬─────┐ │ a ┆ b ┆ c │ │ --- ┆ --- ┆ --- │ │ i64 ┆ i64 ┆ i64 │ ╞═════╪═════╪═════╡ │ 1 ┆ 2 ┆ 1 │ │ 1 ┆ 2 ┆ 2 │ │ 2 ┆ 3 ┆ 3 │ └─────┴─────...
The right function name is .unique() import polars as pl df = pl.DataFrame({"a":[1,1,2], "b":[2,2,3], "c":[1,2,3]}) df.unique(subset=["a","b"]) And this delivers the right output: shape: (2, 3) ┌─────┬─────┬─────┐ │ a ┆ b ┆ c │ │ --- ┆ --- ┆ --- │ │ i64 ┆ i64 ┆ i64 │ ╞═════╪═════╪═════╡ │ 1 ┆ 2 ┆ 1 │ ├╌╌╌╌╌┼╌╌╌╌╌┼╌╌╌╌...
41
53
71,205,417
2022-2-21
https://stackoverflow.com/questions/71205417/what-to-do-when-pip-dependency-resolver-wants-to-use-conflicting-django-plotly-d
So I'm trying to integrate plotly with my django app however I'm having an issue rendering a chart. I was using VSCode which did not pick up the dependency conflict. However when i started to use Pycharm. It said my Dash was version 1.11 which satisfies the django-plotly-dash but did not satisfy the dash_bootstrap_comp...
As django-plotly-dash is on the latest version, i've decided to install dash 1.20 and downgrade by dash-bootstrap-components to 0.13.0 (https://github.com/facultyai/dash-bootstrap-components/releases?page=2) This has worked like a charm.. weirdly - Pycharm has a reference error for the imports but visual studio code do...
10
1
71,187,944
2022-2-19
https://stackoverflow.com/questions/71187944/dlopen-libcrypt-so-1-cannot-open-shared-object-file-no-such-file-or-directory
I use EndeavourOS and have updated my system on February 17 2022 using sudo pacman -Syu Eversince, when I run docker-compose, I get this error message: [4221] Error loading Python lib '/tmp/_MEIgGJQGW/libpython3.7m.so.1.0': dlopen: libcrypt.so.1: cannot open shared object file: No such file or directory Some forum t...
The underlying issue here is that you use docker-compose instead of docker compose, which are two different binaries. docker-compose is also known as V1, and is deprecated since April 26, 2022. Since then, it does not receive updates or patches, other than high-severity security patches. So, to fix your issue, use dock...
32
3
71,220,825
2022-2-22
https://stackoverflow.com/questions/71220825/what-is-the-difference-between-subprocess-run-subprocess-check-output
I am trying to send two simple commands using subprocess.run & trying to store results in a variable then print it but for one arg the output is coming for subprocess.run & for other its empty Arg are "help" & "adb devices" command I am sending which returns the output result = subprocess.run("help", capture_output=Tru...
It is because from the python documentation here: run method run method accepts the first parameter as arguments and not string. So you can try passing the arguments in a list as: result = subprocess.run(['abd', 'devices'], capture_output=True, text=True, universal_newlines=True) Also, check_output method accepts args...
13
8
71,183,960
2022-2-19
https://stackoverflow.com/questions/71183960/short-way-to-get-all-field-names-of-a-pydantic-class
Minimal example of the class: from pydantic import BaseModel class AdaptedModel(BaseModel): def get_all_fields(self, alias=False): return list(self.schema(by_alias=alias).get("properties").keys()) class TestClass(AdaptedModel): test: str The way it works: dm.TestClass.get_all_fields(dm.TestClass) Is there a way to ma...
What about just using __fields__: from pydantic import BaseModel class AdaptedModel(BaseModel): parent_attr: str class TestClass(AdaptedModel): child_attr: str TestClass.__fields__ Output: {'parent_attr': ModelField(name='parent_attr', type=str, required=True), 'child_attr': ModelField(name='child_attr', type=str, req...
38
60
71,162,459
2022-2-17
https://stackoverflow.com/questions/71162459/why-does-anaconda-install-pytorch-cpuonly-when-i-install-cuda
I have created a Python 3.7 conda virtual environment and installed the following packages using this command: conda install pytorch torchvision torchaudio cudatoolkit=11.3 matplotlib scipy opencv -c pytorch They install fine, but then when I come to run my program I get the following error which suggests that a CUDA e...
I believe I had the following things wrong that prevented me from using Cuda. Despite having cuda installed the nvcc --version command indicated that Cuda was not installed and so what I did was add it to the path using this answer. Despite doing that and deleting my original conda environment and using the conda insta...
11
5
71,144,242
2022-2-16
https://stackoverflow.com/questions/71144242/which-arguments-is-futurewarning-use-of-kwargs-is-deprecated-use-engine-kwa
I got the following waring from that code: file = r'.\changed_activities.xlsx' with pd.ExcelWriter(file, engine='openpyxl', mode='a', if_sheet_exists='new') as writer: df.to_excel(writer, sheet_name=activity[0:30]) FutureWarning: Use of **kwargs is deprecated, use engine_kwargs instead. with pd.ExcelWriter(file, What...
Use pd.ExcelWriter('out.xlsx', engine='xlsxwriter', engine_kwargs={'options':{'strings_to_urls': False}}) Instead of pd.ExcelWriter('out.xlsx', engine='xlsxwriter', options={'strings_to_urls': False}})
6
11
71,194,918
2022-2-20
https://stackoverflow.com/questions/71194918/when-i-use-docker-compose-to-install-a-fastapi-project-i-got-assertionerror
when I use docker-compose to install a fastapi project, I got AssertionError: jinja2 must be installed to use Jinja2Templates but when I use env to install it, that will be run well. my OS: Ubuntu18.04STL my requirements.txt: fastapi~=0.68.2 starlette==0.14.2 pydantic~=1.8.1 uvicorn~=0.12.3 SQLAlchemy~=1.4.23 # WSGI We...
I had a same problem on heroku, the error comes from Jinja2 version 2.11.x and it run locally but not in Heroku. Just install latest version of jinja2 it will work fine in your case too. pip install Jinja2==3.1.2 or pip install Jinja2 --upgrade
9
3
71,164,259
2022-2-17
https://stackoverflow.com/questions/71164259/tensorflow-augmentation-layers-not-working-after-importing-from-tf-keras-applica
I am currently using a model from tf.keras.applications for training. And a data augmentation layer along with it. Wierdly, after I import the model from applications, the augmentation layer does not work. The augmentation layer does work before I import it. What is going on? Also, this has only started happening recen...
I noticed same issue with tf 2.8. It can be solved by add training =True , when you test the augmentation layer: aug = data_augmentation(image,training=True) The reason is that the augmentation layer behaves differently in training and predicting (inference), i.e. it will do augmentation in training but do nothing in ...
6
12
71,226,654
2022-2-22
https://stackoverflow.com/questions/71226654/how-can-i-use-groupby-with-multiple-values-in-a-column-in-pandas
I've a dataframe like as follows, import pandas as pd data = { 'brand': ['Mercedes', 'Renault', 'Ford', 'Mercedes', 'Mercedes', 'Mercedes', 'Renault'], 'model': ['X', 'Y', 'Z', 'X', 'X', 'X', 'Q'], 'year': [2011, 2010, 2009, 2010, 2012, 2020, 2011], 'price': [None, 1000.4, 2000.3, 1000.0, 1100.3, 3000.5, None] } df = p...
def fill_it(x): return df[(df.brand==df.iat[x,0])&(df.model==df.iat[x,1])&((df.year==df.iat[x,2]-1)|(df.year==df.iat[x,2]+1))].price.mean() df = df.apply(lambda x: x.fillna(fill_it(x.name)), axis=1) df Output 1: brand model year price 0 Mercedes X 2011 1050.15 1 Renault Y 2010 1000.40 2 Ford Z 2009 2000.30 3 Mercedes X...
5
1
71,221,412
2022-2-22
https://stackoverflow.com/questions/71221412/dag-run-not-found-when-unit-testing-a-custom-operator-in-airflow
I've written a custom operator (DataCleaningOperator), which corrects JSON data based on a provided schema. The unit tests previously worked when I didn't have to instatiate a TaskInstance and provide the operator with a context. However, I've updated the operator recently to take in a context (so that it can use xcom_...
The code have written is using Airflow 2.0 format of unit test. So when you upgraded to Airflow 2.2.3, the unit test requires you to create a dagrun before you create a test run. Below is the sample code which worked for me: import unittest import pendulum from airflow import DAG from airflow.utils.state import DagRunS...
7
7
71,178,416
2022-2-18
https://stackoverflow.com/questions/71178416/can-you-safely-change-a-python-objects-type-in-a-c-extension
Question Suppose that I have implemented two Python types using the C extension API and that the types are identical (same data layouts/C struct) with the exception of their names and a few methods. Assuming that all methods respect the data layout, can you safely change the type of an object from one of these types in...
The supported way It is officially possible to change an object's type in Python, as long as the memory layouts are compatible... but this is mostly limited to types not implemented in C. With some restrictions, it is possible to do # Python attribute assignment, not C struct member assignment obj.__class__ = some_new_...
7
5
71,150,313
2022-2-16
https://stackoverflow.com/questions/71150313/python-docx-adding-bold-and-non-bold-strings-to-same-cell-in-table
I'm using python-docx to create a document with a table I want to populate from textual data. My text looks like this: 01:02:10.3 a: Lorem ipsum dolor sit amet, b: consectetur adipiscing elit. a: Mauris a turpis erat. 01:02:20.4 a: Vivamus dignissim aliquam b: Nam ultricies (etc.) I need to organize it in a table like...
You need to add run in the cell's paragraph. This way you can control the specific text you wish to bold Full example: from docx import Document from docx.shared import Inches import os import re def is_timestamp(line): # it's flaky, I saw you have your own method and probably you did a better job parsing this. return ...
7
5
71,145,982
2022-2-16
https://stackoverflow.com/questions/71145982/django-form-doesnt-display
I'm trying to develop a simple Django app of a contact form and a thanks page. I'm not using Django 'admin' at all; no database, either. Django 3.2.12. I'm working on localhost using python manage.py runserver I can't get the actual form to display at http://127.0.0.1:8000/contact/contact; all I see is the submit butto...
Your form action needs to point to <form action="/contact/contact/".... or better <form action="{% url 'contactform:contact' %}" ...)
5
1
71,229,685
2022-2-22
https://stackoverflow.com/questions/71229685/packages-installed-with-poetry-fail-to-import
Having a simple yet confusing issue: a package I added with poetry fails to import when I try to use it in a module. Steps taken: poetry add sendgrid In a module, import sendgrid Error: Import "sendgrid" could not be resolved PylancereportMissingImports Troubleshooting I've tried: I checked my project's poetry venv ...
Well, it turns out it's a matter of VSCode not playing nice and failing to recognize Poetry's virtual environment. I had to run the Python: Select Interpreter command and change the venv directory to the one my project is using, then it was able to recognize the installed packages. See here for more details on how to d...
8
19
71,228,643
2022-2-22
https://stackoverflow.com/questions/71228643/mwaa-airflow-2-2-2-dag-object-has-no-attribute-update-relative
So I was upgrading DAGs from airflow version 1.12.15 to 2.2.2 and DOWNGRADING python from 3.8 to 3.7 (since MWAA doesn't support python 3.8). The DAG is working fine on the previous setup but shows this error on the MWAA setup: Broken DAG: [/usr/local/airflow/dags/google_analytics_import.py] Traceback (most recent call...
For Airflow>=2.0.0 Assigning task to a DAG using bitwise shift (bit-shift) operators are no longer supported. Trying to do: dag = DAG("my_dag") dummy = DummyOperator(task_id="dummy") dag >> dummy Will not work. Dependencies should be set only between operators. You should use context manager: with DAG("my_dag") as dag...
8
4
71,166,789
2022-2-17
https://stackoverflow.com/questions/71166789/huggingface-valueerror-expected-sequence-of-length-165-at-dim-1-got-128
I am trying to fine-tune the BERT language model on my own data. I've gone through their docs, but their tasks seem to be not quite what I need, since my end goal is embedding text. Here's my code: from datasets import load_dataset from transformers import BertTokenizerFast, AutoModel, TrainingArguments, Trainer import...
I fixed this solution by changing the tokenize function to: def tokenize_function(examples): return tokenizer(examples['text'], padding='max_length', truncation=True, max_length=max_length) (note the padding argument). Also, I used a data collator like so: data_collator = DataCollatorForLanguageModeling( tokenizer=tok...
13
19
71,217,530
2022-2-22
https://stackoverflow.com/questions/71217530/i-want-to-get-the-address-from-mnemonic-with-the-proper-derivation-path
I am very new to blockchain programming and programming in general. I want to generate my SOL address using the mnemonic seed phrase with the derivation path "m/44'/501'/0'/0". I can't find a proper BIP44 module for python where you can specify the derivation path.
After a long search through the internet, I have finally found a way of solving my problem that I want to share with you. from bip_utils import * MNEMONIC = "...12 words phrase..." seed_bytes = Bip39SeedGenerator(MNEMONIC).Generate("") bip44_mst_ctx = Bip44.FromSeed(seed_bytes, Bip44Coins.SOLANA) bip44_acc_ctx = bip44_...
5
6
71,225,872
2022-2-22
https://stackoverflow.com/questions/71225872/why-does-numpy-viewbool-makes-numpy-logical-and-significantly-faster
When passing a numpy.ndarray of uint8 to numpy.logical_and, it runs significantly faster if I apply numpy.view(bool) to its inputs. a = np.random.randint(0, 255, 1000 * 1000 * 100, dtype=np.uint8) b = np.random.randint(0, 255, 1000 * 1000 * 100, dtype=np.uint8) %timeit np.logical_and(a, b) 126 ms ± 1.17 ms per loop (me...
This is a performance issue of the current Numpy implementation. I can also reproduce this problem on Windows (using an Intel Skylake Xeon processor with Numpy 1.20.3). np.logical_and(a, b) executes a very-inefficient scalar assembly code based on slow conditional jumps while np.logical_and(a.view(bool), b.view(bool)) ...
7
5
71,225,952
2022-2-22
https://stackoverflow.com/questions/71225952/try-each-function-of-a-class-with-functools-wraps-decorator
I'm trying to define a decorator in order to execute a class method, try it first and, if an error is detected, raise it mentioning the method in which failed, so as to the user could see in which method is the error. Here I show a MRE (Minimal, Reproducible Example) of my code. from functools import wraps def trier(fu...
As an alternative to Stefan's answer, the following simply uses @trier without any parameters to decorate functions, and then when printing out the error message we can get the name with func.__name__. from functools import wraps def trier(func): """Decorator for trying A-class methods""" @wraps(func) def inner_func(se...
6
4
71,189,819
2022-2-19
https://stackoverflow.com/questions/71189819/importerror-cannot-import-name-json-from-itsdangerous
I am trying to get a Flask and Docker application to work but when I try and run it using my docker-compose up command in my Visual Studio terminal, it gives me an ImportError called ImportError: cannot import name 'json' from itsdangerous. I have tried to look for possible solutions to this problem but as of right now...
I just put itsdangerous==2.0.1 in my requirements.txt .Then updated my virtualenv using pip install -r requirements.txt and then docker-compose up --build . Now everything fine for me. Didnot upgrade the flask version.
71
34
71,211,053
2022-2-21
https://stackoverflow.com/questions/71211053/what-tensorflows-flat-map-window-batch-does-to-a-dataset-array
I'm following one of the online courses about time series predictions using Tensorflow. The function used to convert Numpy array (TS) into a Tensorflow dataset used is LSTM-based model is already given (with my comment lines): def windowed_dataset(series, window_size, batch_size, shuffle_buffer): # creating a tensor fr...
I would break down the operations into smaller parts to really understand what is happening, since applying window to a dataset actually creates a dataset of windowed datasets containing tensor sequences: import tensorflow as tf window_size = 2 dataset = tf.data.Dataset.range(7) dataset = dataset.window(window_size + 1...
6
9
71,209,619
2022-2-21
https://stackoverflow.com/questions/71209619/pandas-groupby-and-apply-aggregate-function-across-rows
I'm having difficulties applying customs functions to a groupby operation in pandas. Let's suppose that I have the following DataFrame to work with: import pandas as pd df = pd.DataFrame( { "id": [1, 1, 2, 2], "flag": ["A", "A", "B", "B"], "value1": [520, 250, 180, 360], "value2": [11, 5, 7, 2], } ) print(df) id flag v...
groupby().agg. only takes in values of one columns. With custom functions involving several columns, I would do something like this: groupby = df.groupby(['id','flag']) out = pd.DataFrame({ 'value1': groupby['value1'].mean(), 'value2': groupby['value2'].sum(), 'value3': groupby.apply(lambda x: (x['value1'] * x['value2'...
5
7
71,198,478
2022-2-20
https://stackoverflow.com/questions/71198478/counting-all-combinations-of-values-in-multiple-columns
The following is an example of items rated by 1,2 or 3 stars. I am trying to count all combinations of item ratings (stars) per month. In the following example, item 10 was rated in month 1 and has two ratings equal 1, one rating equal 2 and one rating equal 3. inp = pd.DataFrame({'month':[1,1,1,1,1,2,2,2], 'item':[10,...
This seems like a nice problem for pd.get_dummies: new_df = ( pd.concat([df, pd.get_dummies(df['star'])], axis=1) .groupby(['month', 'item'], as_index=False) [df['star'].unique()] .sum() ) Output: >>> new_df month item 1 2 3 0 1 10 2 1 1 1 1 20 0 0 1 2 2 20 0 2 1 Renaming, too: u = df['star'].unique() new_df = ( pd.c...
9
1
71,184,699
2022-2-19
https://stackoverflow.com/questions/71184699/filter-a-dictionary-of-lists
I have a dictionary of the form: {"level": [1, 2, 3], "conf": [-1, 1, 2], "text": ["here", "hel", "llo"]} I want to filter the lists to remove every item at index i where an index in the value "conf" is not >0. So for the above dict, the output should be this: {"level": [2, 3], "conf": [1, 2], "text": ["hel", "llo"]} ...
I solved it with this: from typing import Dict, List, Any, Set d = {"level":[1,2,3], "conf":[-1,1,2], "text":["-1", "hel", "llo"]} # First, we create a set that stores the indices which should be kept. # I chose a set instead of a list because it has a O(1) lookup time. # We only want to keep the items on indices where...
21
4
71,195,208
2022-2-20
https://stackoverflow.com/questions/71195208/creating-a-unique-id-in-a-python-dataclass
I need a unique (unsigned int) id for my python data class. This is very similar to this so post, but without explicit ctors. import attr from attrs import field from itertools import count @attr.s(auto_attribs=True) class Person: #: each Person has a unique id _counter: count[int] = field(init=False, default=count()) ...
Use a default factory instead of just a default. This allows to define a call to get the next id on each instantiation. A simple means to get a callable that counts up is to use count().__next__, the equivalent of calling next(...) on a count instance.1 The common "no explicit ctor" libraries attr and dataclasses both ...
9
17
71,193,740
2022-2-20
https://stackoverflow.com/questions/71193740/typeerror-encoders-require-their-input-to-be-uniformly-strings-or-numbers-got
I already referred the posts here, here and here. Don't mark it as duplicate. I am working on a binary classification problem where my dataset has categorical and numerical columns. However, some of the categorical columns has a mix of numeric and string values. Nontheless, they only indicate the category name. For ins...
Cause of the problem SMOTE requires the values in each categorical/numerical column to have uniform datatype. Essentially you can not have mixed datatypes in any of the column in this case your biz_category column. Also merely casting the column to categorical type does not necessarily mean that the values in that colu...
8
7
71,193,085
2022-2-20
https://stackoverflow.com/questions/71193085/creating-nested-columns-in-python-dataframe
I have 3 columns namely Models(should be taken as index), Accuracy without normalization, Accuracy with normalization (zscore, minmax, maxabs, robust) and these are required to be created as: ------------------------------------------------------------------------------------ | Models | Accuracy without normalization ...
There's a dirty way to do this, I'll write about it till someone answers with a better idea. Here we go: import pandas as pd # I assume that you can read raw data named test.csv by pandas and # set header = None cause you mentioned the Test data without any headers, so: df = pd.read_csv("test.csv", header = None) # The...
6
3
71,191,907
2022-2-20
https://stackoverflow.com/questions/71191907/no-module-named-x-main-x-is-a-package-and-cannot-be-directly-executed-w
I have this CLI tool called Rackfocus. I've published to PyPI, and I'm reasonably sure it worked just fine before. When I try to run it with current versions of Python on Mac, I get the error: No module named rackfocus.__main__; 'rackfocus' is a package and cannot be directly executed All I want is one package with on...
entry_points = { 'console_scripts': [ 'rackfocus=rackfocus.run:main' ] } This tells the packaging system to create a wrapper executable named rackfocus. That executable will automatically handle all the necessary steps to get Python off the ground, find the run module in the rackfocus package, find its main function a...
13
11
71,186,546
2022-2-19
https://stackoverflow.com/questions/71186546/python-call-generator-function-from-other-function
For the below code # A simple generator function def infinite_sequence(): num = 1 while True: yield num num += 1 aaa = infinite_sequence() bbb = infinite_sequence() ccc = infinite_sequence() print(next(aaa)) print(next(aaa)) print(next(bbb)) print(next(bbb)) print(next(ccc)) print(next(ccc)) the output is: 1 2 1 2 1 2...
The problem is you call next on all values every time you call switchAction, since you define the dict over and over again. A solution to your problem can be as follows: # A simple generator function def infinite_sequence(): num = 1 while True: yield num num += 1 aaa = infinite_sequence() bbb = infinite_sequence() ccc ...
5
3
71,184,380
2022-2-19
https://stackoverflow.com/questions/71184380/how-to-create-typing-literal-from-multiple-lists-of-values-in-python
I have two lists. I want to create a Literal using both these lists category1 = ["image/jpeg", "image/png"] category2 = ["application/pdf"] SUPPORTED_TYPES = typing.Literal[category1 + category2] Is there any way to do this? I have seen the question typing: Dynamically Create Literal Alias from List of Valid Values bu...
Use the same technique as in the question you linked: build the lists from the literal types, instead of the other way around: SUPPORTED_IMAGE_TYPES = typing.Literal["image/jpeg", "image/png"] SUPPORTED_OTHER_TYPES = typing.Literal["application/pdf"] SUPPORTED_TYPES = typing.Literal[SUPPORTED_IMAGE_TYPES, SUPPORTED_OTH...
9
12
71,180,148
2022-2-18
https://stackoverflow.com/questions/71180148/fastapi-and-slowapi-limit-request-under-all-path
I'm having a problem with SlowAPI. All requests are limited according to the middleware, but I cannot manage to jointly limit all requests under the path /schools/ My code: from fastapi import FastAPI, Request, Response, status from fastapi.middleware.cors import CORSMiddleware from slowapi import Limiter, _rate_limit_...
Option 1 Define application_limits when instantiating the Limiter class, as shown below. As per the documentation, application_limits: a variable list of strings or callables returning strings for limits that are applied to the entire application (i.e., a shared limit for all routes) Thus, the below would apply a sha...
5
6
71,175,486
2022-2-18
https://stackoverflow.com/questions/71175486/how-to-get-caller-name-inside-pytest-fixture
Assume we have: @pytest.fixture() def setup(): print('All set up!') return True def foo(setup): print('I am using a fixture to set things up') setup_done=setup I'm looking for a way to get to know caller function name (in this case: foo) from within setup fixture. So far I have tried: import inspect @pytest.fixture() ...
You can use the built-in request fixture in your own fixture: The request fixture is a special fixture providing information of the requesting test function. Its node attribute is the Underlying collection node (depends on current request scope). import pytest @pytest.fixture() def setup(request): return request.no...
5
8
71,174,306
2022-2-18
https://stackoverflow.com/questions/71174306/expected-in-usr-lib-libc-1-dylib-installing-tensorflow-on-m1-macbook-pro
I am trying to install Tensorflow on my MacBook Pro with the M1 chip. The operating system of my MacBook is MacOS Big Sur Version 11.0. In order to install Tensorflow to use it with Python, I have followed this tutorial, which says that I have to do the following: Install Homebrew. Download MiniForge3 for macOS arm6...
check the message details: (which was built for Mac OS X 12.3) you need to upgrade macOS to 12.3
5
6
71,171,777
2022-2-18
https://stackoverflow.com/questions/71171777/python-pip3-cannot-install-zoneinfo-on-linux-debian
How can zoneinfo be installed on a Linux Debian 10 machine? our script is working just fine on Mac. When pushed to Linux Debian and run, the script returns the error: myemail@repo-name:~/path-to/mainfolder$ python3 main_cbb_v2.py Traceback (most recent call last): File "main_cbb_v2.py", line 3, in <module> from utils i...
zoneinfo is new in python 3.9, so the undelying issue is probably that you have different python versions on different systems. You can either upgrade your python version or you use the backports module which you already have installed, but then your code needs to be: from backports.zoneinfo import ZoneInfo
6
18
71,169,948
2022-2-18
https://stackoverflow.com/questions/71169948/where-does-pytests-mocker-come-from
I am following this mini-tutorial/blog on pytest-mock. I can not understand how the mocker is working since there is no import for it - in particular the function declaration def test_mocking_constant_a(mocker): import mock_examples.functions from mock_examples.functions import double def test_mocking_constant_a(mocker...
The mocker variable is a Pytest fixture. Rather than using imports, fixtures are supplied using dependency injection - that is, Pytest takes care of creating the mocker object for you and supplies it to the test function when it runs the test. Pytest-mock defines the "mocker" fixture here, using the Pytest fixture deco...
5
4
71,162,169
2022-2-17
https://stackoverflow.com/questions/71162169/how-to-find-svg-element-with-selenium
I'm building a python Instagram bot, and I'm trying to get it to click on the DMs icon, but I'm not sure how to select it. I tried selecting by Xpath, but I can't seem to be able to navigate it to the icon. Here's Instagram's html code for the DMs icon: <svg aria-label="Messenger" class="_8-yf5 " color="#262626" fill="...
You have to apply a slightly different locator strategy to find svg. Here is what works: driver.find_element(By.XPATH, "//*[name()='svg']") assuming that this is the only svg element (as provided in your query) Combination of more than one attribute from the same DOM line: //*[name()='svg' and @aria-label='Messenger']...
5
10
71,146,287
2022-2-16
https://stackoverflow.com/questions/71146287/how-token-sort-ratio-works
Can someone explain me how this function of the library fuzzywuzzy in Python works? I know how the Levenshtein distance works but I don't understand how the ratio is computed. b = fuzz.token_sort_ratio('controlled', 'comparative') The result is 38
Levenshtein distance As you probably already know the Levenshtein distance is the minimum amount of insertions / deletions / substitutions to convert one sequence into another sequence. It can be normalized as dist / max_dist, where max_dist is the maximum distance possible given the two sequence lengths. In the case o...
5
11
71,151,966
2022-2-17
https://stackoverflow.com/questions/71151966/python-grammar-correct-in-a-loop
"I was doing the follow exercise: A gymnast can earn a score between 1 and 10 from each judge. Print out a series of sentences, "A judge can give a gymnast _ points." Don't worry if your first sentence reads "A judge can give a gymnast 1 points." However, you get 1000 bonus internet points if you can use a for loop, an...
Heres another way of doing it. The answer above may(I don't know) be more efficient, in my opinion this is more readable for future developers. scores = (tuple(range(1,11))) for score in scores: if score == 1: print ('A judge can give a gymnast 1 point.') else: print (f'A judge can give a gymnast {score} points.')
5
2
71,151,093
2022-2-17
https://stackoverflow.com/questions/71151093/using-constant-variables-in-python-match-statement
I am writing a program and python and want to use the match-case statement allowed in python 3.10 to be able to switch on 'enum' values i.e: match token.type: case TOK_INT: #0 # do stuff case TOK_STRING: #1 # do stuff etc... however trying to do this causes python to throw a SyntaxError: name capture 'TOK_INT' makes r...
This will work with any dotted name (like math.pi). However an unqualified name (i.e. a bare name with no dots) will be always interpreted as a capture pattern, so avoid that ambiguity by always using qualified constants in patterns. you can refer here
5
4
71,146,740
2022-2-16
https://stackoverflow.com/questions/71146740/fastapi-create-auth-for-all-endpoints
I followed this documentation to setup up a single user: https://fastapi.tiangolo.com/advanced/security/http-basic-auth/ But I only get prompted for user/pass for that one end point, "/users/me". How do I ensure that all endpoints are behind auth?
You can configure FastAPI with a set of dependencies that needs to be resolved for any endpoint by giving the paramter directly when creating the FastAPI application (i.e. global dependencies): security = HTTPBasic() app = FastAPI(dependencies=[Depends(security)]) If you want some endpoints to be authenticated and som...
9
15
71,148,612
2022-2-16
https://stackoverflow.com/questions/71148612/type-hinting-list-of-strings
In python, if I am writing a function, is this the best way to type hint a list of strings: def sample_def(var:list[str]):
I would use the typing module from typing import List def foo(bar: List[str]): pass The reason is typing contains so many type hints and the ability to create your own, specify callables, etc. Definitely check it out. Edit: I guess as of Python 3.9 typing is deprecated (RIP). Instead it looks like you can use collecti...
9
16
71,147,799
2022-2-16
https://stackoverflow.com/questions/71147799/create-new-boolean-fields-based-on-specific-bigrams-appearing-in-a-tokenized-pan
Looping over a list of bigrams to search for, I need to create a boolean field for each bigram according to whether or not it is present in a tokenized pandas series. And I'd appreciate an upvote if you think this is a good question! List of bigrams: bigrams = ['data science', 'computer science', 'bachelors degree'] D...
You could also try using numpy and nltk, which should be quite fast: import pandas as pd import numpy as np import nltk bigrams = ['data science', 'computer science', 'bachelors degree'] df = pd.DataFrame(data={'job_description': [['data', 'science', 'degree', 'expert'], ['computer', 'science', 'degree', 'masters'], ['...
5
3
71,138,693
2022-2-16
https://stackoverflow.com/questions/71138693/running-one-python-script-within-another-script-using-subprocess
I am working on a script to walk over a directory, and convert all the python2 files to python3. There is a utitliy (2to3.py) to acheive that. ( I am using python2.7 interpreter) I have the following code: import os import subprocess import pathlib APP_FOLDER = 'C:/Users/XXXX/Test/' for dirpath, dirnames, filenames in ...
Try using, cmd ="py C:\Python27\Tools\Scripts\\2to3.py "+file_path+" -w"
5
3
71,102,658
2022-2-13
https://stackoverflow.com/questions/71102658/how-can-i-return-a-numpy-array-using-fastapi
I have a TensorFlow Keras deep learning model in the form of an h5 file. How can I upload an image and return a NumPy array in FastAPI? import numpy as np import cv2 from fastapi import FastAPI, File, UploadFile import numpy as np from tensorflow.keras.models import load_model import tensorflow as tf model=load_model("...
The error is thrown when returning the response (i.e., prediction in your case) from your endpoint. It looks like FastAPI is trying to convert the NumPy array into a dict, using the jsonable_encoder, which is used internally by FastAPI when returning a value from an endpoint, and which seems to call Python's vars() met...
6
7
71,106,690
2022-2-14
https://stackoverflow.com/questions/71106690/polars-specify-dtypes-for-all-columns-at-once-in-read-csv
In Polars, how can one specify a single dtype for all columns in read_csv? According to the docs, the schema_overrides argument to read_csv can take either a mapping (dict) in the form of {'column_name': dtype}, or a list of dtypes, one for each column. However, it is not clear how to specify "I want all columns to be ...
Reading all data in a csv to any other type than pl.String likely fails with a lot of null values. We can use expressions to declare how we want to deal with those null values. If you read a csv with infer_schema_length=0, polars does not know the schema and will read all columns as pl.String as that is a super type of...
15
21
71,103,393
2022-2-13
https://stackoverflow.com/questions/71103393/fastapi-swagger-ui-does-not-render-because-of-custom-middleware
So I have a custom middleware like this: Its objective is to add some meta_data fields to every response from all endpoints of my FastAPI app. @app.middelware("http") async def add_metadata_to_response_payload(request: Request, call_next): response = await call_next(request) body = b"" async for chunk in response.body...
Here's how you could do that (inspired by this). Make sure to check the Content-Type of the response (as shown below), so that you can modify it by adding the metadata, only if it is of application/json type. For the OpenAPI (Swagger UI) to render (both /docs and /redoc), make sure to check whether openapi key is not p...
5
5
71,102,876
2022-2-13
https://stackoverflow.com/questions/71102876/in-ipython-how-do-i-accept-and-use-an-autocomplete-suggestion
I'm using Python 3.8.9 with IPython 8.0.1 on macOS. When I type anything whatsoever, it displays a predicted suggestion based on past commands. Cool. However, how do I actually accept that suggestion? I tried the obvious: tab, which does not accept the suggestion, but rather opens up a menu with different suggestions, ...
CTRL-E, CTRL-F, or Right Arrow Key https://ipython.readthedocs.io/en/8.13.2/config/shortcuts/index.html Alternatively, the End key, as suggested by Richard Berg (below).
71
76
71,086,453
2022-2-11
https://stackoverflow.com/questions/71086453/how-to-combine-the-elements-of-two-lists-using-zip-function-in-python
I have two different lists and I would like to know how I can get each element of one list print with each element of another list. I know I could use two for loops (each for one of the lists), however I want to use the zip() function because there's more that I will be doing in this for loop for which I will require p...
I believe the function you are looking for is itertools.product: lasts = ['x', 'y', 'z'] firsts = ['a', 'b', 'c'] from itertools import product for last, first in product(lasts, firsts): print (last, first) x a x b x c y a y b y c z a z b z c Another alternative, that also produces an iterator is to use a nested compr...
6
7
71,132,469
2022-2-15
https://stackoverflow.com/questions/71132469/appending-row-to-dataframe-with-concat
I have defined an empty data frame with df = pd.DataFrame(columns=['Name', 'Weight', 'Sample']) and want to append rows in a for loop like this: for key in my_dict: ... row = {'Name':key, 'Weight':wg, 'Sample':sm} df = pd.concat(row, axis=1, ignore_index=True) But I get this error cannot concatenate object of type '<...
You can transform your dict in pandas DataFrame import pandas as pd df = pd.DataFrame(columns=['Name', 'Weight', 'Sample']) for key in my_dict: ... #transform your dic in DataFrame new_df = pd.DataFrame([row]) df = pd.concat([df, new_df], axis=0, ignore_index=True)
24
36
71,092,850
2022-2-12
https://stackoverflow.com/questions/71092850/how-to-install-uwsgi-on-windows
I'm trying to install uwsgi for a django project inside a virtual environment; I'm using windows 10. I did pip install uwsgi & I gotCommand "python setup.py egg_info". So to resolve the error I followed this SO answer As per the answer I installed cygwin and gcc compiler for windows following this. Also changed the os....
Step 1: Download this stable release of uWSGI Step 2: Extract the tar file inside the site-packages folder of the virtual environment. For example the extracted path to uwsgi should be: \my_env\lib\site-packages\uwsgi-2.0.19.1 Step 3: Open uwsgi-2.0.19.1\uwsgiconfig.py And do the following edits: import platform ... ...
7
6
71,125,094
2022-2-15
https://stackoverflow.com/questions/71125094/debug-a-python-c-c-pybind11-extension-in-vscode-linux
Problem Statement I want to run and debug my own C++ extensions for python in "hybrid mode" in VSCode. Since defining your own python wrappers can be quite tedious, I want to use pybind11 to link C++ and python. I love the debugging tools of vscode, so I would like to debug both my python scripts as well as the C++ fun...
TLDR I think the C++ code was not build with debug information. Adding the keyword argument extra_compile_args=["-g"] to the Pybind11Extension in the setup.py may be enough to solve it. Regardless read on for my solution proposal, that worked for me. Steps I could make this work by using the Python C++ Debugger extensi...
9
7
71,109,838
2022-2-14
https://stackoverflow.com/questions/71109838/numpy-typing-with-specific-shape-and-datatype
Currently i'm trying to work more with numpy typing to make my code clearer however i've somehow reached a limit that i can't currently override. Is it possible to specify a specific shape and also the corresponding data type? Example: Shape=(4,) datatype= np.int32 My attempts so far look like the following (but all j...
Currently, numpy.typing.NDArray only accepts a dtype, like so: numpy.typing.NDArray[numpy.int32]. You have some options though. Use typing.Annotated typing.Annotated allows you to create an alias for a type and to bundle some extra information with it. In some my_types.py you would write all variations of shapes you wa...
46
56
71,068,392
2022-2-10
https://stackoverflow.com/questions/71068392/group-and-create-three-new-columns-by-condition-low-hit-high
I have a large dataset (~5 Mio rows) with results from a Machine Learning training. Now I want to check to see if the results hit the "target range" or not. Lets say this range contains all values between -0.25 and +0.25. If it's inside this range, it's a Hit, if it's below Low and on the other side High. I now would c...
You could use cut to define the groups and pivot_table to reshape: (df.assign(group=pd.cut(df['Value'], [float('-inf'), -0.25, 0.25, float('inf')], labels=['Low', 'Hit', 'High'])) .pivot_table(index='Type', columns='group', values='Value', aggfunc='count') .reset_index() .rename_axis(None, axis=1) ) Or crosstab: (pd.c...
9
11
71,048,280
2022-2-9
https://stackoverflow.com/questions/71048280/upgrade-python-to-3-10-in-windows-do-i-have-to-reinstall-all-site-packages-manu
I have in windows 10 64 bit installed python 3.9 with site-packages. I would like to install python 3.10.2 on windows 10 64 bit and find a way to install packages automatically in python 3.10.2, the same ones I currently have installed in python 3.9. I am also interested in the answer to this question for windows 11 64...
I upgraded to python 3.10.2 in windows 10 64 bit. To properly install the packages, install the appropriate version of the Microsoft Visual C++ compiler if necessary. Details can be read https://wiki.python.org/moin/WindowsCompilers . With the upgrade to python 3.10.2 from 3.9, it turned out that I had to do it, due to...
7
10
71,118,601
2022-2-14
https://stackoverflow.com/questions/71118601/saving-a-plotly-image-not-working-with-kaleido-even-though-it-is-installed
I am trying to save a simple plotly figure to a directory. I understand it needs kaleido (I have version '0.2.1') and also at least plotly '5.3.1' which are installed. However trying to save the image I get the following error: fig.write_image(path) ValueError: Image export using the "kaleido" engine requires the kalei...
I've got exactly the same issue on google colab. Even after installation kaleido, the same error. Accidentally I've found fix, it seems necesarry to import kaleido first: !pip install kaleido import kaleido #required kaleido.__version__ #0.2.1 import plotly plotly.__version__ #5.5.0 #now this works: import plotly.graph...
12
10
71,049,155
2022-2-9
https://stackoverflow.com/questions/71049155/generate-graph-from-a-list-of-connected-components
Setup Let's assume the following undirected graph: import networkx as nx G = nx.from_edgelist([(0, 3), (0, 1), (2, 5), (0, 3)]) G.add_nodes_from(range(7)) or even adding the (1, 3) edge (it doesn't matter here): The connected components are: list(nx.connected_components(G)) # [{0, 1, 3}, {2, 5}, {4}, {6}] Question ...
An alternative to itertools.pairwise is networkx.path_graph. An alternative to itertools.combinations is networkx.complete_graph. These two networkx functions return a new graph, not a list of edges, so you can combine them with networkx.compose_all. Note also union_all and disjoint_union_all as alternatives to compose...
6
11
71,046,200
2022-2-9
https://stackoverflow.com/questions/71046200/how-do-you-export-a-pydantic-model-to-yaml-using-anchors
I would like to export a Pydantic model to YAML, but avoid repeating values and using references (anchor+aliases) instead. Here's an example: from typing import List from ruamel.yaml import YAML # type: ignore import yaml from pydantic import BaseModel class Author(BaseModel): id: str name: str age: int class Book(Base...
When you traverse a nested Python data structure in order to convert it, you have to deal with the possibility of self-reference, otherwise your code will get in an endless loop if the data is self-referential. The way ruamel.yaml (and the standard library json.dump() ) deal with that is keeping a list of id()s of the ...
6
4
71,090,408
2022-2-12
https://stackoverflow.com/questions/71090408/how-to-use-release-branch-to-increment-version-using-setuptools-scm
I am looking at https://github.com/pypa/setuptools_scm and I read this part https://github.com/pypa/setuptools_scm#version-number-construction and i quote Semantic versioning for projects with release branches. The same as guess-next-dev (incrementing the pre-release or micro segment) if on a release branch: a branch ...
Branches main and v0.1.0 don't have pyproject.toml, so you need to add that file. version_scheme should be under [tool.setuptools_scm] instead of [build-system]: # pyproject.toml [build-system] requires = ["setuptools>=45", "setuptools_scm[toml]>=6.2"] [tool.setuptools_scm] version_scheme = "release-branch-semver" Thi...
6
4
71,119,083
2022-2-14
https://stackoverflow.com/questions/71119083/python-interpreter-version-not-showing-in-status-bar-of-vs-code-on-mac
My python interpreter version does not show up at the bottom of the status bar on VS code on my Mac, it used to but suddenly stopped. Everything works but it just doesn’t show, I tried many possible solutions such as: right clicking the bar to have the Python Extension checked (which I don’t even have an option to che...
Turned out it was placed to a new place in the status bar. Here's how to pin it on the status bar now: Hover over the {} next to the Python language chooser Click the pin icon The selection of the Python environment becomes pinned to the status bar on the right hand side
22
42
71,106,940
2022-2-14
https://stackoverflow.com/questions/71106940/cannot-import-name-centered-from-scipy-signal-signaltools
Unable to import functions from scipy module. Gives error : from scipy.signal.signaltools import _centered Cannot import name '_centered' from 'scipy.signal.signaltools' scipy.__version__ 1.8.0
If you need to use that specific version of statsmodels 0.12.x with scipy 1.8.0 I have the following hack. Basically it just re-publishes the existing (but private) _centered function as a public attribute to the module already imported in RAM. It is a workaround, and if you can simply upgrade your dependencies to the ...
21
16
71,087,502
2022-2-11
https://stackoverflow.com/questions/71087502/datetime-timestamp-using-python-with-microsecond-level-accuracy
I am trying to get timestamps that are accurate down to the microsecond on Windows OS and macOS in Python 3.10+. On Windows OS, I have noticed Python's built-in time.time() (paired with datetime.fromtimestamp()) and datetime.datetime.now() seem to have a slower clock. They don't have enough resolution to differentiate ...
That's almost as good as it gets, since the C module, if available, overrides all classes defined in the pure Python implementation of the datetime module with the fast C implementation, and there are no hooks. Reference: python/cpython@cf86e36 Note that: There's an intrinsic sub-microsecond error in the accuracy equa...
5
6
71,104,848
2022-2-13
https://stackoverflow.com/questions/71104848/mapping-complex-json-to-pandas-dataframe
BackgroundI have a complex nested JSON object, which I am trying to unpack into a pandas df in a very specific way. JSON Objectthis is an extract, containing randomized data of the JSON object, which shows examples of the hierarchy (inc. children) for 1x family (i.e. 'Falconer Family'), however there is 100s of them in...
jsonpath-ng can parse even such a nested json object very easily. You can install this convenient library by the following command: pip install --upgrade jsonpath-ng Code: import json import jsonpath_ng as jp import pandas as pd def unpack_response(r): # Create a dataframe from extracted data expr = jp.parse('$..child...
10
6
71,116,130
2022-2-14
https://stackoverflow.com/questions/71116130/ipykernel-throwing-typeerror-object-nonetype-cant-be-used-in-await-expressi
I know that several similar questions exist on this topic, but to my knowledge all of them concern an async code (wrongly) written by the user, while in my case it comes from a Python package. I have a Jupyter notebook whose first cell is ! pip install numpy ! pip install pandas and I want to automatically play the no...
Seems to be a bug in ipykernel 6.9.0 - options that worked for me: upgrade to 6.9.1 (latest version as of 2022-02-22); e.g. via pip install ipykernel --upgrade downgrade to 6.8.0 (if upgrading messes with other dependencies you might have); e.g. via pip install ipykernel==6.8.0
6
2
71,049,497
2022-2-9
https://stackoverflow.com/questions/71049497/visual-studio-code-is-not-loading-my-python-interpreters
I've been using a python interpreter that I set in my venv the whole time for this project. Recently I changed my python interpreter which I've set as a default interpreter in my user settings like the vs docs vs code python environments describes it and also set in my JSON settings file refuses to load instead. I'm ge...
I think you should use the \ instead of the / in the path. For safety just copy paste the path from the windows explorer. Another Solution : Writing the path in Json should definitely work. But I prefer using the functionality vscode provides. Now come to my solution. press ctrl+shift+p to open the search bar. now typ...
5
1
71,099,132
2022-2-13
https://stackoverflow.com/questions/71099132/how-to-set-schema-translate-map-in-sqlalchemy-object-in-flask-app
My app.py file from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask import Flask from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'postgres:////tmp/test.db' db = SQLAlchemy(app) # refer https://flask-sqlalchemy.palletsprojects.com/en/2.x/api/#fl...
I found a way to accomplish it. This is what needed db = SQLAlchemy(app, session_options={ "autocommit": True, "autoflush": False }, engine_options={ "execution_options": { "schema_translate_map": { None: "public", "abc": "xyz" } } } )
5
5
71,121,056
2022-2-15
https://stackoverflow.com/questions/71121056/plotly-python-update-figure-with-dropmenu
i am currently working with plotly i have a function called plotChart that takes a dataframe as input and plots a candlestick chart. I am trying to figure out a way to pass a list of dataframes to the function plotChart and use a plotly dropdown menu to show the options on the input list by the stock name. The drop dow...
I adapted an example from the plotly community to your example and created the code. The point of creation is to create the data for each subplot and then switch between them by means of buttons. The sample data is created using representative companies of US stocks. one issue is that the title is set but not displayed...
6
2