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 |
|---|---|---|---|---|---|---|
70,866,415 | 2022-1-26 | https://stackoverflow.com/questions/70866415/how-to-install-python-specific-version-on-docker | I need to install python 3.8.10 in a container running ubuntu 16.04. 16.04 has no support anymore, so I need a way to install it there manually. | This follows from here Add the following to your dockerfile, and change the python version as needed. When the docker is up, python3.8 will be available in /usr/local/bin/python3.8 # compile python from source - avoid unsupported library problems RUN apt update -y && sudo apt upgrade -y && \ apt-get install -y wget bui... | 16 | 23 |
70,874,423 | 2022-1-27 | https://stackoverflow.com/questions/70874423/fastapi-importerror-attempted-relative-import-with-no-known-parent-package | I am new to FastAPI and I've been having this problem with importing my other files. I get the error: from . import schemas ImportError: attempted relative import with no known parent package For context, the file I am importing from is a Folder called Blog. I saw certain StackOverflow answers saying that instead ... | Since your schemas.py and models.py files are in the same directory as your main.py file, you should import those two modules as follows, instead of using from Blog import schemas, models: import schemas, models For more details and examples please have a look at this answer, as well as this answer and this answer. | 10 | 9 |
70,884,910 | 2022-1-27 | https://stackoverflow.com/questions/70884910/converting-dates-into-a-specific-format-in-side-a-csv | I am new to python and Iam trying to manipulate some data but it keeps showing me this erro message UserWarning: Parsing '13/01/2021' in DD/MM/YYYY format. Provide format or specify infer_datetime_format=True for consistent parsing. cache_array = _maybe_cache(arg, format, cache, convert_listlike) This is my code impo... | In your case you need to set the dayfirst param to true, like this: pd.to_datetime(dataLake.day, dayfirst=True) or you can set a format (but you don't need to in your case), like this: pd.to_datetime(dataLake.day, format="%d/%m/%y") | 7 | 17 |
70,862,894 | 2022-1-26 | https://stackoverflow.com/questions/70862894/vscode-pylance-doesnt-work-via-ssh-connection | There is a problem: Pylance (IntelliSense) does not work on the remote server. At the same time it works locally. Pylance itself is installed both locally and on the server. Imports are just white and only "Loading..." pops up when I hover over it. "Go to definition" also doesn't work. Have a such properties: Python: ... | Basically, the problem was that if a large workspace is selected in VSCode, it will try to index it all, and until it finishes, the highlighting won't turn on. In my case, I had several AWS buckets mounted and since there was about 100TB of data, the file indexing simply never finished. If I select a specific project f... | 6 | 3 |
70,911,608 | 2022-1-30 | https://stackoverflow.com/questions/70911608/plot-3d-cube-and-draw-line-on-3d-in-python | I know, for those who know Python well piece of cake a question. I have an excel file and it looks like this: 1 7 5 8 2 4 6 3 1 7 4 6 8 2 5 3 6 1 5 2 8 3 7 4 My purpose is to draw a cube in Python and draw a line according to the order of these numbers. Note: There is no number greater than 8 in arrays. I can explain b... | First, it looks like you are using pandas with pd.read_csv without importing it. Since, you are not reading the headers and just want a list of values, it is probably sufficient to just use the numpy read function instead. Since I don't have access to your csv, I will define the vertex lists as variables below. vertice... | 5 | 6 |
70,870,041 | 2022-1-26 | https://stackoverflow.com/questions/70870041/cannot-import-name-mutablemapping-from-collections | I'm getting the following error: File "/home/ron/rzg2l_bsp_v1.3/poky/bitbake/lib/bb/compat.py", line 7, in <module> from collections import MutableMapping, KeysView, ValuesView, ItemsView, OrderedDict ImportError: cannot import name 'MutableMapping' from 'collections' (/usr/lib/python3.10/collections/__init__.py) and... | You need to import collections.abc Here the link to doc >>> from collections import MutableMapping Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: cannot import name 'MutableMapping' from 'collections' (/usr/lib/python3.10/collections/__init__.py) >>> from collections.abc import Muta... | 36 | 41 |
70,893,521 | 2022-1-28 | https://stackoverflow.com/questions/70893521/how-to-sort-a-pyarrow-table | How do I sort an Arrow table in PyArrow? There does not appear to be a single function that will do this, the closest is sort_indices. | PyArrow includes Table.sort_by since 7.0.0, no need to manually call the compute functions (reference) table = pa.table([ pa.array(["a", "a", "b", "b", "b", "c", "d", "d", "e", "c"]), pa.array([15, 20, 3, 4, 5, 6, 10, 1, 14, 123]), ], names=["keys", "values"]) sorted_table = table.sort_by([("values", "ascending")]) | 5 | 4 |
70,878,545 | 2022-1-27 | https://stackoverflow.com/questions/70878545/vs-code-how-to-launch-an-interactive-python-terminal-while-debugging | I have recently started using VS code for Python development. I am unable to figure out how to launch an interactive terminal while debugging, with the program state loaded-in . For example, consider the following code, import numpy as np A = np.array([1, 2, 3]) B = np.zeros() C = A/B \\ <--- Breakpoint here I want to... | There's the Python debugging console in VSCode. When your code stops on a breakpoint, you can click on the debug console button to open an interactive Python console with your current program state loaded in. | 24 | 22 |
70,944,716 | 2022-2-1 | https://stackoverflow.com/questions/70944716/pydantic-sqlalchemy-how-to-work-with-enums | What is the best way to convert a sqlalchemy model to a pydantic schema (model) if it includes an enum field? Sqlalchemy import enum from sqlalchemy import Enum, Column, String from sqlalchemy.orm import declarative_base Base = declarative_base() class StateEnum(enum.Enum): CREATED = 'CREATED' UPDATED = 'UPDATED' class... | Pydantic requires that both enum classes have the same type definition. In your case, StateEnum inherits from enum.Enum, but StateEnumDTO inherits from both str and enum.Enum. You can fix this issue by changing your SQLAlchemy enum definition: class StateEnum(str, enum.Enum): CREATED = 'CREATED' UPDATED = 'UPDATED' | 5 | 3 |
70,948,998 | 2022-2-1 | https://stackoverflow.com/questions/70948998/how-to-re-use-the-return-values-of-matplotlib-axes-hist | Suppose I want to plot a histogram of the same data twice: import matplotlib.pyplot as plt fig = plt.figure(figsize=(8,6)) ax1,ax2 = fig.subplots(nrows=2,ncols=1) ax1.hist(foo) ax2.hist(foo) ax2.set_yscale("log") ax2.set_xlabel("foo") fig.show() Note that I call Axes.hist twice, and it could be expensive. I wonder if ... | In the ax.hist docs, there is a related example of reusing np.histogram output: The weights parameter can be used to draw a histogram of data that has already been binned by treating each bin as a single point with a weight equal to its count. counts, bins = np.histogram(data) plt.hist(bins[:-1], bins, weights=counts)... | 5 | 5 |
70,946,151 | 2022-2-1 | https://stackoverflow.com/questions/70946151/how-to-set-default-on-update-current-timestamp-in-postgres-with-sqlalchemy | This is a sister question to How to set DEFAULT ON UPDATE CURRENT_TIMESTAMP in mysql with sqlalchemy?, but focused on Postgres instead of MySQL. Say we want to create a table users with a column datemodified that updates by default to the current timestamp whenever a row is updated. The solution given in the sister PR ... | Eventually I implemented this using triggers as suggested by a_horse_with_no_name in the comments. Full SQLAlchemy implementation and integration with Alembic follow. SQLAlchemy implementation # models.py class User(Base): __tablename__ = "user" id = Column(Integer, primary_key=True) name = Column(Text) created_at = Co... | 5 | 8 |
70,903,401 | 2022-1-29 | https://stackoverflow.com/questions/70903401/how-do-i-get-mobile-status-for-discord-bot-by-directly-modifying-identify-packet | Apparently, discord bots can have mobile status as opposed to the desktop (online) status that one gets by default. After a bit of digging I found out that such a status is achieved by modifying the IDENTIFY packet in discord.gateway.DiscordWebSocket.identify modifying the value of $browser to Discord Android or Disco... | The following works by subclassing the relevant class, and duplicating code with the relevant changes. We also have to subclass the Client class, to overwrite the place where the gateway/websocket class is used. This results in a lot of duplicated code, however it does work, and requires neither dirty monkey-patching n... | 10 | 1 |
70,864,474 | 2022-1-26 | https://stackoverflow.com/questions/70864474/uvicorn-async-workers-are-still-working-synchronously | Question in short I have migrated my project from Django 2.2 to Django 3.2, and now I want to start using the possibility for asynchronous views. I have created an async view, setup asgi configuration, and run gunicorn with a Uvicorn worker. When swarming this server with 10 users concurrently, they are served synchron... | Your ApiLoggerMiddleware is a synchronous middleware. From https://docs.djangoproject.com/en/4.0/topics/async/#async-views, emphasis mine: You will only get the benefits of a fully-asynchronous request stack if you have no synchronous middleware loaded into your site. If there is a piece of synchronous middleware, the... | 10 | 5 |
70,883,863 | 2022-1-27 | https://stackoverflow.com/questions/70883863/poetry-install-fails-on-macos-11-6-xcode-13-dyld-library-not-loaded-executab | New poetry install fails on macOS 11.6/Xcode 13, using official installer: u@s-MacBook-Pro ~ % curl -sSL https://install.python-poetry.org | python3 - Retrieving Poetry metadata # Welcome to Poetry! This will download and install the latest version of Poetry, a dependency and package manager for Python. It will add the... | I worked through this by installing a non-system version of python3, then installing poetry. brew install pyenv pyenv install 3.8.12 pyenv local 3.8.12 curl -sSL https://install.python-poetry.org | python3 - | 7 | 5 |
70,934,699 | 2022-2-1 | https://stackoverflow.com/questions/70934699/how-to-fix-error-when-building-conda-package-related-to-icon-file | I honestly can't figure out what is happening with this error. I thought it was something in my manifest file but apparently it's not. Note, this directory is in my Google Drive. Here is my MANIFEST.in file: graft soothsayer_utils include setup.py include LICENSE.txt include README.md global-exclude Icon* global-exclud... | there are a few symptoms I would like to suggest looking into: There is a WARNING in your error log SetuptoolsDeprecationWarning: setup.py install is deprecated. Use build and pip and other standards-based tools. You have MANIFEST.in, setup.py and setup.cfg probably conflicting between them. Because setup.py is the bu... | 6 | 2 |
70,876,473 | 2022-1-27 | https://stackoverflow.com/questions/70876473/kubernetespodoperator-how-to-use-cmds-or-cmds-and-arguments-to-run-multiple-comm | I'm using GCP composer to run an algorithm and at the end of the stream I want to run a task that will perform several operations copying and deleting files and folders from a volume to a bucket I'm trying to perform these copying and deleting operations via a kubernetespodoperator. I'm having hardship finding the righ... | I found a technic for running multiple commands. First I found the relations between Kubernetespodoperator cmds and arguments properties to Docker's ENTRYPOINT and CMD. Kubernetespodoperator cmds overwrite the docker original ENTRYPOINT and Kubernetespodoperator arguments is equivalent to docker's CMD. And so in order ... | 5 | 4 |
70,882,092 | 2022-1-27 | https://stackoverflow.com/questions/70882092/can-we-make-1-2-true | Python ints are objects that encapsulate the actual number value. Can we mess with that value, for example setting the value of the object 1 to 2? So that 1 == 2 becomes True? | Yes, we can. But don't do this at home. Seriously, the 1 object is used in many places and I have no clue what this might break and what that might do to your computer. I reject all responsibility. But I found it interesting to learn about these things. The id function gives us the memory address and the ctypes module ... | 101 | 163 |
70,946,286 | 2022-2-1 | https://stackoverflow.com/questions/70946286/pip-compile-raising-assertionerror-on-its-logging-handler | I have a dockerfile that currently only installs pip-tools FROM python:3.9 RUN pip install --upgrade pip && \ pip install pip-tools COPY ./ /root/project WORKDIR /root/project ENTRYPOINT ["tail", "-f", "/dev/null"] I build and open a shell in the container using the following commands: docker build -t brunoapi_image .... | It is a bug, you can downgrade using: pip install "pip<22" https://github.com/jazzband/pip-tools/issues/1558 | 32 | 7 |
70,861,001 | 2022-1-26 | https://stackoverflow.com/questions/70861001/annotate-dataclass-class-variable-with-type-value | We have a number of dataclasses representing various results with common ancestor Result. Each result then provides its data using its own subclass of ResultData. But we have trouble to annotate the case properly. We came up with following solution: from dataclasses import dataclass from typing import ClassVar, Generic... | At the end I just replaced the variable in _data_cls annotation with the base class and fixed the annotation of subclasses as noted by @rv.kvetch in his answer. The downside is the need to define the result class twice in every subclass, but in my opinion it is more legible than extracting the class in property. The co... | 6 | 2 |
70,897,060 | 2022-1-28 | https://stackoverflow.com/questions/70897060/py2-to-py3-add-future-imports | I need to make a old code base compatible with Python3. The code needs to support Python2.7 and Python3 for some months. I would like to add this in very file: # -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unic... | From the docs: Only those __future__ imports deemed necessary will be added unless the --all-imports command-line option is passed to futurize, in which case they are all added. If you want futurize to add all those imports unconditionally, you need to pass it the --all-imports flag. | 5 | 4 |
70,932,129 | 2022-1-31 | https://stackoverflow.com/questions/70932129/how-to-extract-bold-text-from-pdf-using-python | The list below provides examples of items and services that should not be billed separately. Please note that the list is not all inclusive. 1. Surgical rooms and services – To include surgical suites, major and minor, treatment rooms, endoscopy labs, cardiac cath labs, X-ray. 2. Facility Basic Charges - pulmonary and ... | Use This Code: import pdfplumber import re demo = [] with pdfplumber.open('HCSC IL Inpatient_Outpatient Unbundling Policy- Facility.pdf') as pdf: for i in range(0, 50): try: text = pdf.pages[i] clean_text = text.filter(lambda obj: obj["object_type"] == "char" and "Bold" in obj["fontname"]) demo.append(str(re.findall(r'... | 6 | 2 |
70,938,215 | 2022-2-1 | https://stackoverflow.com/questions/70938215/why-does-mypy-flag-item-none-has-no-attribute-x-error-even-if-i-check-for-none | Trying to do Python (3.8.8) with type hinting and getting errors from mypy (0.931) that I can't really understand. import xml.etree.ElementTree as ET tree = ET.parse('plant_catalog.xml') # read in file and parse as XML root = tree.getroot() # get root node for plant in root: # loop through children if plant.find("LIGHT... | mypy doesn't know that plant.find("LIGHT") always returns the same value, so it doesn't know that your test is a proper guard. So you need to assign it to a variable. As far as mypy is concerned, the variable can't change from one object to another without being reassigned, and its contents can't change if you don't pe... | 7 | 9 |
70,935,209 | 2022-2-1 | https://stackoverflow.com/questions/70935209/how-to-explode-dynamically-using-pandas-column | I have a dataframe that looks like this import pandas as pd import numpy as np # Create data set. dataSet = {'id': ['A', 'A', 'B'], 'id_2': [1, 2, 1] , 'number': [320, 169, 120], 'add_number' : [4,6,3]} # Create dataframe with data set and named columns. df = pd.DataFrame(dataSet, columns= ['id', 'id_2','number', 'add_... | You try using np.arange and explode: df['range'] = df.apply(lambda x: np.arange(x['number'], x['number']+x['add_number']+1), axis=1) df.explode('range') or df['range'] = [np.arange(n, n+a+1) for n, a in zip(df['number'],df['add_number'])] df.explode('range') Output: id id_2 number add_number range 0 A 1 320 4 320 0 ... | 6 | 2 |
70,927,513 | 2022-1-31 | https://stackoverflow.com/questions/70927513/replacing-whole-string-is-faster-than-replacing-only-its-first-character | I tried to replace a character a by b in a given large string. I did an experiment - first I replaced it in the whole string, then I replaced it only at its beginning. import re # pattern = re.compile('a') pattern = re.compile('^a') string = 'x' * 100000 pattern.sub('b', string) I expected that replacing the beginning... | The functions provided in the Python re module do not optimize based on anchors. In particular, functions that try to apply a regex at every position - .search, .sub, .findall etc. - will do so even when the regex can only possibly match at the beginning. I.e., even without multi-line mode specified, such that ^ can on... | 11 | 4 |
70,931,002 | 2022-1-31 | https://stackoverflow.com/questions/70931002/pandas-get-cell-value-by-row-index-and-column-name | Let's say we have a pandas dataframe: name age sal 0 Alex 20 100 1 Jane 15 200 2 John 25 300 3 Lsd 23 392 4 Mari 21 380 Let's say, a few rows are now deleted and we don't know the indexes that have been deleted. For example, we delete row index 1 using df.drop([1]). And now the data frame comes down to this: fname a... | Use .loc to get rows by label and .iloc to get rows by position: >>> df.loc[3, 'age'] 23 >>> df.iloc[2, df.columns.get_loc('age')] 23 More about Indexing and selecting data | 15 | 25 |
70,927,544 | 2022-1-31 | https://stackoverflow.com/questions/70927544/saving-a-pymupdf-fitz-object-to-s3-as-a-pdf | I am trying to crop a pdf and save it to s3 with same name using lambda. I am getting error on the data type being a fitz.fitz.page import os import json import boto3 from urllib.parse import unquote_plus import fitz, sys from io import BytesIO OUTPUT_BUCKET_NAME = os.environ["OUTPUT_BUCKET_NAME"] OUTPUT_S3_PREFIX = os... | This is happening because the page1 object is defined using fitz.fitz.page and the type expected by S3 put object is bytes. In order to solve the issue, you can use the write function of the new PDF (doc) and get the output of it which is in bytes format that you could pass to S3 then. # Save fil first. new_bytes = doc... | 5 | 2 |
70,923,969 | 2022-1-31 | https://stackoverflow.com/questions/70923969/how-to-remove-the-user-agent-header-when-send-request-in-python | I'm using python requests library, I need send a request without a user-agent header. I found this question, but it's for Urllib2. I'm trying to simulate an Android app which does this when calling a private API. I try to set User-Agent to None as in the following code, but it doesn't work. It still sends User-Agent: p... | The requests library is built on top of the urllib3 library. So, when you pass None User-Agent header to the requests's post method, the urllib3 set their own default User-Agent import requests r = requests.post("https://httpbin.org/post", headers={ "User-Agent": None, }) print(r.json()["headers"]["User-Agent"]) Outpu... | 10 | 9 |
70,910,391 | 2022-1-29 | https://stackoverflow.com/questions/70910391/seaborn-lineplot-connecting-dots-of-scatterplot | I have problem with sns lineplot and scatterplot. Basically what I'm trying to do is to connect dots of a scatterplot to present closest line joining mapped points. Somehow lineplot is changing width when facing points with tha same x axis values. I want to lineplot to be same, solid line all the way. The code: import ... | Ok, I have finally figured it out. The reason lineplot was so messy is because data was not properly sorted. When I sorted dataframe data by 'Y' values, the outcome was satisfactory. data = {'X': [13, 13, 13, 12, 11], 'Y':[14, 11, 13, 15, 20], 'NumberOfPlanets':[2, 5, 2, 1, 2]} cts = pd.DataFrame(data=data) cts = cts.s... | 5 | 1 |
70,916,649 | 2022-1-30 | https://stackoverflow.com/questions/70916649/how-to-change-the-x-axis-and-y-axis-labels-in-plotly | How can I change the x and y-axis labels in plotly because in matplotlib, I can simply use plt.xlabel but I am unable to do that in plotly. By using this code in a dataframe: Date = df[df.Country=="India"].Date New_cases = df[df.Country=="India"]['7day_rolling_avg'] px.line(df,x=Date, y=New_cases, title="India Daily Ne... | simple case of setting axis title update_layout( xaxis_title="Date", yaxis_title="7 day avg" ) full code as MWE import pandas as pd import io, requests df = pd.read_csv( io.StringIO( requests.get( "https://raw.githubusercontent.com/owid/covid-19-data/master/public/data/vaccinations/vaccinations.csv" ).text ) ) df["D... | 35 | 54 |
70,905,872 | 2022-1-29 | https://stackoverflow.com/questions/70905872/overflowerror-when-reading-from-s3-signed-integer-is-greater-than-maximum | Reading a large file from S3 ( >5GB) into lambda with the following code: import json import boto3 s3 = boto3.client('s3') def lambda_handler(event, context): response = s3.get_object( Bucket="my-bucket", Key="my-key" ) text_bytes = response['Body'].read() ... return { 'statusCode': 200, 'body': json.dumps('Hello from ... | As mentioned in the bug you linked to, the core issue in Python 3.8 is the bug with reading more than 1gb at a time. You can use a variant of the workaround suggested in the bug to read the file in chunks. import boto3 s3 = boto3.client('s3') def lambda_handler(event, context): response = s3.get_object( Bucket="-exampl... | 5 | 7 |
70,858,169 | 2022-1-26 | https://stackoverflow.com/questions/70858169/networkx-entropy-of-subgraphs-generated-from-detected-communities | I have 4 functions for some statistical calculations in complex networks analysis. import networkx as nx import numpy as np import math from astropy.io import fits Degree distribution of graph: def degree_distribution(G): vk = dict(G.degree()) vk = list(vk.values()) # we get only the degree values maxk = np.max(vk) mi... | Using the code I provided as an answer to your question here to create graphs from communities. You can first create different graphs for each of your communities (based on the community edge attribute of your graph). You can then compute the entropy for each community with your shannon_entropy and degree_distribution ... | 5 | 3 |
70,904,128 | 2022-1-29 | https://stackoverflow.com/questions/70904128/print-a-hyperlink-in-the-terminal | I can use this special escape sequence to print a hyperlink in bash: echo -e '\e]8;;http://example.com\e\\This is a link\e]8;;\e\\\n' Result (Link I can click on): This is a link Now I want to generate this in Python: print('\e]8;;http://example.com\e\\This is a link\e]8;;\e\\\n') \e]8;;http://example.com\e\This is a... | From This answer, after some tries: print('\x1b]8;;' + 'http://example.com' + '\x1b\\' + 'This is a link' + '\x1b]8;;\x1b\\\n' ) Then better: print( '\x1b]8;;%s\x1b\\%s\x1b]8;;\x1b\\' % ( 'http://example.com' , 'This is a link' ) ) | 6 | 3 |
70,896,932 | 2022-1-28 | https://stackoverflow.com/questions/70896932/simultaneously-reassign-values-of-two-variables-in-c | Is there a way in C++ of emulating this python syntax a,b = b,(a+b) I understand this is trivially possible with a temporary variable but am curious if it is possible without using one? | You can use the standard C++ function std::exchange like #include <utility> //... a = std::exchange( b, a + b ); Here is a demonstration program #include <iostream> #include <utility> int main() { int a = 1; int b = 2; std::cout << "a = " << a << '\n'; std::cout << "b = " << b << '\n'; a = std::exchange( b, a + b ); s... | 4 | 8 |
70,895,037 | 2022-1-28 | https://stackoverflow.com/questions/70895037/how-many-times-can-a-list-be-split-in-a-way-that-every-element-on-the-left-is-sm | For example if the list is: [2,1,2,5,7,6,9] there's 3 possible ways of splitting: [2,1,2] [5,7,6,9] [2,1,2,5] [7,6,9] [2,1,2,5,7,6] [9] I'm supposed to calculate how many times the list can be split in a way that every element on the left is smaller than every element on the right. So with this list, the output would b... | Here's my final answer: def count(t): c = 0 maxx = max(t) right = [0]*len(t) left = [0]*len(t) maxx = t[0] for i in range(0, len(t)): if maxx >= t[i]: left[i] = maxx if maxx < t[i]: maxx = t[i] left[i] = maxx minn = t[-1] for i in range(len(t)-1,-1,-1): if minn <= t[i]: right[i] = minn if minn > t[i]: minn = t[i] right... | 5 | 1 |
70,894,409 | 2022-1-28 | https://stackoverflow.com/questions/70894409/pyspark-get-element-from-array-column-of-struct-based-on-condition | I have a spark df with the following schema: |-- col1 : string |-- col2 : string |-- customer: struct | |-- smt: string | |-- attributes: array (nullable = true) | | |-- element: struct | | | |-- key: string | | | |-- value: string df: #+-------+-------+----------------------------------------------------------------... | You can use filter function to filter the array of structs then get value: from pyspark.sql import functions as F df2 = df.withColumn( "B", F.expr("filter(customer.attributes, x -> x.key = 'B')")[0]["value"] ) | 8 | 10 |
70,891,225 | 2022-1-28 | https://stackoverflow.com/questions/70891225/how-to-get-outer-html-from-python-playwright-locator-object | I could not find any method that returns outer html from python playwright page.locator(selector, **kwargs). Am I missing something? locator.inner_html(**kwargs) do exists. However, I am trying to use pandas.read_html and it fails on table locator inner html as it trips table tag. What I'm currently doing is using bs4... | There is no outer_html out of the box. But it's not hard to implement it: locator.evaluate("el => el.outerHTML") | 7 | 10 |
70,892,143 | 2022-1-28 | https://stackoverflow.com/questions/70892143/psycopg2-connection-sql-database-to-pandas-dataframe | I am working on a project where I am using psycopg2 connection to fetch the data from the database like this, cursor = connection.execute("select * from table") cursor.fetchall() Now after getting the data from the table, I am running some extra operations to convert the data from cursor to pandas dataframe. I am look... | You can use pandas sqlio module to run and save query within pandas dataframe. Let's say you have a connection of psycopg2 connection then you can use pandas sqlio like this. import pandas.io.sql as sqlio data = sqlio.read_sql_query("SELECT * FROM table", connection) # Now data is a pandas dataframe having the results ... | 6 | 10 |
70,887,626 | 2022-1-28 | https://stackoverflow.com/questions/70887626/python-type-hinting-a-classmethod-that-returns-an-instance-of-the-class-for-a | Consider the following: from __future__ import annotations class A: def __init__(self): print("A") self.hello = "hello" # how do I type this so that the return type is A for A.bobo() # and B for B.bobo()? @classmethod def bobo(cls) -> UnknownType: return cls() class B(A): def __init__(self): print("B") super().__init__... | You will have to use a TypeVar, thankfully, in Python 3.11 the typing.Self type is coming out. This PEP describes it in detail. It also specifies how to use the TypeVar until then. | 14 | 6 |
70,863,543 | 2022-1-26 | https://stackoverflow.com/questions/70863543/can-a-python-docstring-be-calculated-f-string-or-expression | Is it possible to have a Python docstring calculated? I have a lot of repetitive things in my docstrings, so I'd like to either use f-strings or a %-style format expression. When I use an f-string at the place of a docstring importing the module invokes the processing but when I check the __doc__ of such a function it... | Docstrings in Python must be regular string literals. This is pretty easy to test - the following program does not show the docstring: BAR = "Hello world!" def foo(): f"""This is {BAR}""" pass assert foo.__doc__ is None help(foo) The Python syntax docs say that the docstring must be a "string literal", and the tail en... | 30 | 28 |
70,882,733 | 2022-1-27 | https://stackoverflow.com/questions/70882733/how-to-display-two-decimal-points-in-python-when-a-number-is-perfectly-divisibl | Currently I am trying to solve a problem, where I am supposed to print the answer upto two decimal points without rounding off. I have used the below code for this purpose import math a=1.175 #value of a after some division print(math.floor(a*100)/100) The output we get is: 1.17 #Notice value which has two decimal poi... | The division works and returns adequate precision in result. So your problem is just about visualization or exactly: string-representation of floating-point numbers Formatting a decimal You can use string-formatting for that. For example in Python 3, use f-strings: twoFractionDigits = f"{result:.2f}" or print(f"{resu... | 5 | 17 |
70,882,944 | 2022-1-27 | https://stackoverflow.com/questions/70882944/no-such-file-or-directory-dev-fd-11-during-pytest-collection-in-docker | I have a simple Dockerfile with Python and NodeJS. I install pytest, a local library and run tests: FROM nikolaik/python-nodejs:latest ADD . . RUN pip3 install --upgrade pip RUN pip3 install -e . RUN pip3 install pytest CMD ["pytest"] However, pytest collection fails: ============================= test session starts ... | I found a solution on pytest GitHub: https://github.com/pytest-dev/pytest/issues/8960 your working directory is / so pytest is attempting to recurse through everything in the filesystem (probably not what you want!) Added WORKDIR /tests/ to the Dockerfile and the issue is fixed. | 7 | 9 |
70,864,604 | 2022-1-26 | https://stackoverflow.com/questions/70864604/websockets-exceptions-connectionclosedok-code-1000-ok-no-reason | I am trying to receive data from a website which use websocket. This acts like this: websocket handshaking Here is the code to catch data: async def hello(symb_id: int): async with websockets.connect("wss://ws.bitpin.ir/", extra_headers = request_header, timeout=15) as websocket: await websocket.send('{"method":"sub_... | I solved this error by creating a task for sending PING. async def hello(symb_id: int): async with websockets.connect("wss://ws.bitpin.ir/", extra_headers = request_header, timeout=10, ping_interval=None) as websocket: await websocket.send('{"method":"sub_to_price_info"}') recv_msg = await websocket.recv() if recv_msg ... | 7 | 5 |
70,876,394 | 2022-1-27 | https://stackoverflow.com/questions/70876394/async-generator-object-is-not-iterable | I need to return a value in async function. I tried to use synchronous form of return: import asyncio async def main(): for i in range(10): return i await asyncio.sleep(1) print(asyncio.run(main())) output: 0 [Finished in 204ms] But it just return value of the first loop, which is not expexted. So changed the code as ... | You need to use an async for which itself needs to be inside an async function: async def get_result(): async for i in main(): print(i) asyncio.run(get_result()) | 17 | 28 |
70,865,732 | 2022-1-26 | https://stackoverflow.com/questions/70865732/faster-numpy-isin-alternative-for-strings-using-numba | I'm trying to implement a faster version of the np.isin in numba, this is what I have so far: import numpy as np import numba as nb @nb.njit(parallel=True) def isin(a, b): out=np.empty(a.shape[0], dtype=nb.boolean) b = set(b) for i in nb.prange(a.shape[0]): if a[i] in b: out[i]=True else: out[i]=False return out For n... | Strings are barely supported by Numba (like bytes although the support is slightly better). Set and dictionary are supported with some strict restriction and are quite experimental/new. Sets of strings are not supported yet regarding the documentation: Sets must be strictly homogeneous: Numba will reject any set conta... | 5 | 2 |
70,865,699 | 2022-1-26 | https://stackoverflow.com/questions/70865699/what-is-different-between-dataloader-and-dataloader2-in-pytorch | I developed a custom dataset by using the PyTorch dataset class. The code is like that: class CustomDataset(torch.utils.data.Dataset): def __init__(self, root_path, transform=None): self.path = root_path self.mean = mean self.std = std self.transform = transform self.images = [] self.masks = [] for add in os.listdir(se... | You should definitely not use it DataLoader2. torch.utils.data.DataLoader2 (actually torch.utils.data.dataloader_experimental.DataLoader2) was added as an experimental "feature" as a future replacement for DataLoader. It is defined here. Currently, it is only accessible on the master branch (unstable) and is of course ... | 6 | 3 |
70,864,887 | 2022-1-26 | https://stackoverflow.com/questions/70864887/how-to-create-batches-using-pytorch-dataloader-such-that-each-example-in-a-given | Suppose I have a list, datalist which contains several examples (which are of type torch_geometric.data.Data for my use case). Each example has an attribute num_nodes For demo purpose, such datalist can be created using the following snippet of code import torch from torch_geometric.data import Data # each example is o... | If your underlying dataset is map-style, you can use define a torch.utils.data.Sampler which returns the indices of the examples you want to batch together. An instance of this will be passed as a batch_sampler kwarg to your DataLoader and you can remove the batch_size kwarg as the sampler will form batches for you dep... | 5 | 3 |
70,862,692 | 2022-1-26 | https://stackoverflow.com/questions/70862692/how-to-use-pythons-structural-pattern-matching-to-test-built-in-types | I'm trying to use SPM to determine if a certain type is an int or an str. The following code: from typing import Type def main(type_to_match: Type): match type_to_match: case str(): print("This is a String") case int(): print("This is an Int") case _: print("\nhttps://en.meming.world/images/en/0/03/I%27ve_Never_Met_Thi... | If you just pass a type directly, it will consider it to be a "name capture" rather than a "value capture." You can coerce it to use a value capture by importing the builtins module, and using a dotted notation to check for the type. import builtins from typing import Type def main(type_: Type): match (type_): case bui... | 11 | 22 |
70,863,757 | 2022-1-26 | https://stackoverflow.com/questions/70863757/python-send-message-to-specific-telegram-user | I would like to send a message to a specific telegram-user - So I create a bot called Rapid1898Bot and get the api-key for it. I also send a message in the bot and get with https://api.telegram.org/bot<Bot\_token>/getUpdates the chat-id With the following code it is now working that I send a message to the bot - what ... | you already have a bot and its token after that you need to get the chat_id: write message in the chat Visit https://api.telegram.org/bot<YourBOTToken>/getUpdates and get the chat_id under the key message['chat']['id'] import requests def telegram_bot_sendtext(bot_message): bot_token = '' bot_chatID = '' send_text =... | 6 | 4 |
70,862,614 | 2022-1-26 | https://stackoverflow.com/questions/70862614/how-does-python-dict-comprehension-work-with-lambda-functions-inside | My goal is to aggregate a pandas DataFrameGroupBy Object using the agg function. In order to do that, I am generating a dictionary that I'm going to unpack to kwargs using dict unpacking through **dict. This dictionary is required to contain the new column name as the key and a tuple as the value. The first value of th... | This is a classic Python trap. When you use a free variable (cat_name, in this case) in a lambda expression, the lambda captures which variable the name refers to, not the value of that variable. So in this case, the lambda "remembers" that cat_name was "the loop variable of that dict comprehension". When the lambda is... | 5 | 7 |
70,860,798 | 2022-1-26 | https://stackoverflow.com/questions/70860798/how-can-i-reach-a-spark-cluster-in-a-docker-container-with-spark-submit-and-a-py | I've created a Spark cluster with one master and two slaves, each one on a Docker container. I launch it with the command start-all.sh. I can reach the UI from my local machine at localhost:8080 and it shows me that the cluster is well launched : Screenshot of Spark UI Then I try to submit a simple Python script from m... | When you specify .setMaster('spark://spark-master:7077') it means "reach spark cluster at DNS address "spark-master" and port 7077 which local machine cannot resolve. So it order for your host machine to reach the cluster you must instead specify the Docker DNS / IP address of your Spark cluster, check "docker0" interf... | 7 | 2 |
70,859,757 | 2022-1-26 | https://stackoverflow.com/questions/70859757/how-to-add-vertically-centered-labels-in-bar-chart-matplotlib | I have a problem which I simplified as below, I would love if anyone suggest me the code in seaborn like what I want to achieve. import matplotlib.pyplot as plt a = [2000, 4000, 3000, 8000, 6000, 3000, 3000, 4000, 2000, 4000, 3000, 8000, 6000, 3000, 3000, 4000, 2000, 4000, 3000, 8000, 6000, 3000, 3000, 4000] b = [0.8, ... | As of matplotlib 3.4.0, use Axes.bar_label: label_type='center' places the labels at the center of the bars rotation=90 rotates them 90 deg Since this is a regular bar chart, we only need to label one bar container ax1.containers[0]: ax1.bar_label(ax1.containers[0], label_type='center', rotation=90, color='white') B... | 5 | 7 |
70,809,438 | 2022-1-22 | https://stackoverflow.com/questions/70809438/python-dataclasses-with-optional-attributes | How do you make Optional attr's of a dataclass? from dataclasses import dataclass @dataclass class CampingEquipment: knife: bool fork: bool missing_flask_size: # what to write here? kennys_stuff = { 'knife': True, 'fork': True } print(CampingEquipment(**kennys_stuff)) I tried field(init=False), but it gave me: TypeErr... | It's not possible to use a dataclass to make an attribute that sometimes exists and sometimes doesn't because the generated __init__, __eq__, __repr__, etc hard-code which attributes they check. However, it is possible to make a dataclass with an optional argument that uses a default value for an attribute (when it's n... | 62 | 85 |
70,772,733 | 2022-1-19 | https://stackoverflow.com/questions/70772733/how-to-post-a-json-having-a-single-body-parameter-in-fastapi | I have a file called main.py in which I put a POST call with only one input parameter (integer). Simplified code is given below: from fastapi import FastAPI app = FastAPI() @app.post("/do_something/") async def do_something(process_id: int): # some code return {"process_id": process_id} Now, if I run the code for the ... | The error, basically, says that the required query parameter process_id is missing. The reason for that error is that you send a POST request with request body, i.e., JSON payload; however, your endpoint expects a query parameter. To receive the data in JSON format instead, one needs to create a Pydantic BaseModel—as s... | 10 | 13 |
70,799,693 | 2022-1-21 | https://stackoverflow.com/questions/70799693/repeat-python-function-at-every-system-clock-minute | I've seen that I can repeat a function with python every x seconds by using a event loop library in this post: import sched, time s = sched.scheduler(time.time, time.sleep) def do_something(sc): print("Doing stuff...") # do your stuff s.enter(60, 1, do_something, (sc,)) s.enter(60, 1, do_something, (s,)) s.run() But I... | Use schedule. import schedule import time schedule.every().minute.at(':00').do(do_something, sc) while True: schedule.run_pending() time.sleep(.1) If do_something takes more than a minute, turn it into a thread before passing it to do. import threading def do_something_threaded(sc): threading.Thread(target=do_somethin... | 5 | 7 |
70,792,895 | 2022-1-20 | https://stackoverflow.com/questions/70792895/python-3-type-dict-with-required-and-arbitrary-keys | I'm trying to type a function that returns a dictionary with one required key, and some additional ones. I've run into TypedDict, but it is too strict for my purpose. At the same time Dict is too lenient. To give some examples with what I have in mind: class Schema(PartiallyTypedDict): name: str year: int a: Schema = {... | Since PEP 655 there is a solution for this problem. In Python 3.11+ there are typing.Required and typing.NotRequired. This means we have two ways to do this. typing.Required approach The typing.Required type qualifier is used to indicate that a variable declared in a TypedDict definition is a required key. This means... | 5 | 1 |
70,851,048 | 2022-1-25 | https://stackoverflow.com/questions/70851048/does-it-make-sense-to-use-conda-poetry | Does it make sense to use Conda + Poetry for a Machine Learning project? Allow me to share my (novice) understanding and please correct or enlighten me: As far as I understand, Conda and Poetry have different purposes but are largely redundant: Conda is primarily a environment manager (in fact not necessarily Python),... | 2024-04-05 update: It looks like my tips proved to be useful to many people, but they are not needed anymore. Just use Pixi. It's still alpha, but it works great, and provides the features of the Conda + Poetry setup in a simpler and more unified way. In particular, Pixi supports: installing packages both from Conda c... | 198 | 241 |
70,771,319 | 2022-1-19 | https://stackoverflow.com/questions/70771319/determining-if-object-is-of-typing-literal-type | I need to check if object is descendant of typing.Literal, I have annotation like this: GameState: Literal['start', 'stop'] And I need to check GameState annotation type: def parse_values(ann) if isinstance(ann, str): # do sth if isinstance(ann, int): # do sth if isinstance(ann, Literal): # do sth But it causes error... | typing.get_origin(tp) is the proper way It was implemented in Python 3.8 (Same as typing.Literal) The docstring is thoroughly instructive: def get_origin(tp): """Get the unsubscripted version of a type. This supports generic types, Callable, Tuple, Union, Literal, Final, ClassVar and Annotated. Return None for unsuppor... | 8 | 2 |
70,815,197 | 2022-1-22 | https://stackoverflow.com/questions/70815197/how-to-do-structural-pattern-matching-in-python-3-10-with-a-type-to-match | I am trying to match a type in Python 3.10 using the console: t = 12.0 match type(t): case int: print("int") case float: print("float") And I get this error: File "<stdin>", line 2 SyntaxError: name capture 'int' makes remaining patterns unreachable How can I fix this issue? | First, let's explain the code in the question: t = 12.0 match type(t): case int: print("int") case float: print("float") In Python, the match statement operates by trying to fit the subject (the value of type(t), i.e. float) into one of the patterns. The above code has two patterns (case int: and case float:). These p... | 16 | 8 |
70,793,490 | 2022-1-20 | https://stackoverflow.com/questions/70793490/how-do-i-calculate-square-root-in-python | I need to calculate the square root of some numbers, for example √9 = 3 and √2 = 1.4142. How can I do it in Python? The inputs will probably be all positive integers, and relatively small (say less than a billion), but just in case they're not, is there anything that might break? Note: This is an attempt at a canonic... | Option 1: math.sqrt() The math module from the standard library has a sqrt function to calculate the square root of a number. It takes any type that can be converted to float (which includes int) and returns a float. >>> import math >>> math.sqrt(9) 3.0 Option 2: Fractional exponent The power operator (**) or the buil... | 57 | 98 |
70,821,737 | 2022-1-23 | https://stackoverflow.com/questions/70821737/webdriverexception-message-service-geckodriver-unexpectedly-exited-status-cod | For some tests, I've set up a plain new TrueNAS 12.3 FreeBSD Jail and started it, then installed python3, firefox, geckodriver and pip using the following commands: pkg install python3 firefox geckodriver py38-pip pip install --upgrade pip setenv CRYPTOGRAPHY_DONT_BUILD_RUST 1 pip install cryptography==3.4.7 pip instal... | This error message... selenium.common.exceptions.WebDriverException: Message: Service geckodriver unexpectedly exited. Status code was: 64 and the GeckoDriver log... geckodriver: error: Found argument '--websocket-port' which wasn't expected, or isn't valid in this context ...implies that the GeckoDriver was unable t... | 17 | 26 |
70,816,149 | 2022-1-22 | https://stackoverflow.com/questions/70816149/vscode-intellisense-not-working-for-modules-when-using-sys-path-append-to-add-pa | I am adding path that are higher up or in a sibling directories using following code. And I am not getting IntelliSense for modules inside these folders. Any idea how to get this IntelliSense? The function colorPrint is defined inside LoggingHelper module in Utility folder. | I solved it as following. I am adding parent folder and resolving all modules inside the parent folder. This way, I get IntelliSense HERE = Path(__file__).parent sys.path.append(str(HERE / '..')) from Utility.LoggingKotakHelper import (colorPrint, logKotakInfo, logKotakWarning) | 5 | 3 |
70,826,659 | 2022-1-23 | https://stackoverflow.com/questions/70826659/bar-labels-with-new-f-string-format-style | As of matplotlib 3.4.0, Axes.bar_label method allows for labelling bar charts. However, the labelling format option works with old style formatting, e.g. fmt='%g' How can I make it work with new style formatting that would allow me to do things like percentages, thousands separators, etc: '{:,.2f}', '{:.2%}', ... The f... | How can I make bar_label work with new style formatting like percentages, thousands separators, etc? As of matplotlib 3.7 The fmt param now directly supports {}-based format strings, e.g.: # >= 3.7 plt.bar_label(bars, fmt='{:,.2f}') # ^no f here (not an actual f-string) Prior to matplotlib 3.7 The fmt param does n... | 6 | 18 |
70,837,669 | 2022-1-24 | https://stackoverflow.com/questions/70837669/how-can-i-parse-package-in-a-urdf-file-path | I have a robot URDF that points to mesh files using "package://". <geometry> <mesh filename="package://a1_rw/meshes/hip.dae" scale="1 1 1"/> </geometry> I would like to use urdfpy to parse this URDF. However, it is unable to interpret the meaning of "package://". import os from urdfpy import URDF a1_rw = { "model": "... | The behavior you're observing is expected. The documentation for urdfpy.URDF.load() specifically states: Any paths in the URDF should be specified as relative paths to the .urdf file instead of as ROS resources. If you want to keep using the same library, the only way to sort this out is to replace the strings in the... | 5 | 1 |
70,783,994 | 2022-1-20 | https://stackoverflow.com/questions/70783994/reload-routes-in-fastapi-during-runtime | I have a FastAPI app in which routes are dynamically generated based on an DB config. However, once the routes are defined and the app running, if the config changes, there seems to be no way to reload the config so that the routes could reflect the config. The only solution I have for now is manually restart the asgi ... | It is possible to modify routes at runtime. FastAPI apps have the method add_api_route which allows you to dynamically define new endpoints. To remove an endpoint you will need to fiddle directly with the routes of the underlying Router. The following code shows how to dynamically add and remove routes. import fastapi ... | 10 | 8 |
70,808,757 | 2022-1-21 | https://stackoverflow.com/questions/70808757/pydantic-inconsistent-and-automatic-conversion-between-float-and-int | I am using pydantic python package in FastAPI for a web app, and I noticed there is some inconsistent float-int conversions with different typing checks. For example: class model(BaseModel): data: Optional[Union[int, float]] = None m = model(data=3.33) m.data --> 3.33 class model(BaseModel): data: Optional[Union[int, f... | To understand what happened there we have to know how the Union works and how pydantic uses typing to validate values. Union According to the documentation: Union type; Union[X, Y] is equivalent to X | Y and means either X or Y. OR means that at least one element has to be true to make the whole sentence true. So, if... | 6 | 3 |
70,780,898 | 2022-1-20 | https://stackoverflow.com/questions/70780898/pydantic-set-variables-from-a-list | Is there a way to set a pydantic model from a list? I tried this and it didn't work for me. If it's not possible with pydantic, what is the best way to do this if I still need type validation and conversion, constraints, etc.? Order is important here. from pydantic import BaseModel from datetime import date class User(... | I partially answered it here: Initialize FastAPI BaseModel using non-keywords arguments (a.k.a *args) but I'll give here more dynamic options. Option 1: use the order of the attributes Your case has the problem that Pydantic does not maintain the order of all fields (depends at least on whether you set the type). If yo... | 6 | 5 |
70,806,778 | 2022-1-21 | https://stackoverflow.com/questions/70806778/python-selenium-proxy-network | Overview I am using a proxy network and want to configure it with Selenium on Python. I have seen many post use the HOST:PORT method, but proxy networks uses the "URL method" of http://USER:PASSWORD@PROXY:PORT SeleniumWire I found SeleniumWire to be a way to connect the "URL method" of proxy networks to a Selenium Scra... | Selenium Extension: A proxy network, or "URL" proxy, can be configured with Selenium as an extension. Create the following JS script and JSON file: JS script ("background.js") var config = { mode: "fixed_servers", rules: { singleProxy: { scheme: "http", host: "<PROXY>", port: parseInt(<PORT>) }, bypassList: ["foobar.co... | 5 | 1 |
70,787,868 | 2022-1-20 | https://stackoverflow.com/questions/70787868/how-to-change-youtube-dl-output-location-with-python | I wrote a python script to download a list of YouTube URLs, and I want to change the output folder by the subject I'm downlaoding. For example, When I'm downloading a playlist, I want the videos in this playlist be downloaded into a folder named by the current playlist. But if it's a channel, the videos inside it shoul... | dl_ops = { 'outtmpl': 'd:/YouTube/%(uploader)s/%(title)s.%(ext)s' } You can see that in this line you specify a path to be D:/YouTube/ {uploader name} / {title of the video} . {extension that you specified}. In order to change all the videos to go into the same folder you just need to remove the "/" after the uploader... | 6 | 6 |
70,793,174 | 2022-1-20 | https://stackoverflow.com/questions/70793174/fastapi-schemahidden-true-not-working-when-trying-to-hide-the-schema-sectio | I'm trying to hide the entire schemas section of the FastAPI generated swagger docs. I've checked the docs and tried this but the schema section still shows. @Schema(hidden=True) class theSchema(BaseModel): category: str How do I omit one particular schema or the entire schemas section from the returned swagger docs.... | swagger has the UI parameter "defaultModelsExpandDepth" for controlling models' view in the schema section. This parameter can be forwarded using "swagger_ui_parameters" parameter on FastApi initialization. app = FastAPI(swagger_ui_parameters={"defaultModelsExpandDepth": -1}) Values: -1: schema section hidden 0: sche... | 8 | 12 |
70,839,312 | 2022-1-24 | https://stackoverflow.com/questions/70839312/module-numpy-distutils-config-has-no-attribute-blas-opt-info | I'm trying to study the neural-network-and-deep-learning (http://neuralnetworksanddeeplearning.com/chap1.html). Using the updated version for Python 3 by MichalDanielDobrzanski (https://github.com/MichalDanielDobrzanski/DeepLearningPython). Tried to run it in my command console and it gives an error below. I've tried u... | I had the same issue and solved it downgrading numpy to version 1.20.3 by: pip3 install --upgrade numpy==1.20.3 | 14 | 18 |
70,854,314 | 2022-1-25 | https://stackoverflow.com/questions/70854314/use-fastapi-to-interact-with-async-loop | I am running coroutines of 'workers' whose job it is to wait 5s, get values from an asyncio.Queue() and print them out continually. q = asyncio.Queue() def worker(): while True: await asyncio.sleep(5) i = await q.get() print(i) q.task_done() async def main(q): workers = [asyncio.create_task(worker()) for n in range(10)... | One option would be to add a task that wraps your main coroutine in a on startup event import asyncio @app.on_event("startup") async def startup_event(): asyncio.create_task(main()) This would schedule your main coroutine before the app has been fully started. Important here is that you don't await the created task as... | 8 | 12 |
70,823,915 | 2022-1-23 | https://stackoverflow.com/questions/70823915/random-stealing-calls-to-child-initializer | There's a situation involving sub-classing I can't figure out. I'm sub-classing Random (the reason is besides the point). Here's a basic example of what I have: import random class MyRandom(random.Random): def __init__(self, x): # x isn't used here, but it's necessary to show the problem. print("Before") super().__init... | Instantiating a class causes its __new__ method to be called. It is passed the name of the class and the arguments in the constructor call. So MyRandom([1, 2]) results in the call MyRandom.__new__(MyRandom, [1, 2]). (3.9.10 documentation). Because there isn't a MyRandom.__new__() method, the base classes are searched. ... | 5 | 2 |
70,786,543 | 2022-1-20 | https://stackoverflow.com/questions/70786543/remove-all-the-special-chars-from-a-list | i have a list of strings with some strings being the special characters what would be the approach to exclude them in the resultant list list = ['ben','kenny',',','=','Sean',100,'tag242'] expected output = ['ben','kenny','Sean',100,'tag242'] please guide me with the approach to achieve the same. Thanks | The string module has a list of punctuation marks that you can use and exclude from your list of words: import string punctuations = list(string.punctuation) input_list = ['ben','kenny',',','=','Sean',100,'tag242'] output = [x for x in input_list if x not in punctuations] print(output) Output: ['ben', 'kenny', 'Sean',... | 4 | 11 |
70,812,698 | 2022-1-22 | https://stackoverflow.com/questions/70812698/add-a-python-path-to-a-module-in-visual-studio-code | I'm having difficulty specifying python path containing modules/packages in another directory or even folder of the same project. When I try to import I get the error: ModuleNotFoundError: No module named 'perception' In Spyder this is simply done using the UI to select an additional pythonpath that python will look in... | Instructions for MacOS only. Adding .env files and navigating the setting json files is not as intuitive and simple as adding an additional python path in Spyder. However, this worked for me on VSC: create a .env file in the project folder. add the full path that you want to add to PYTHONPATH as such: PYTHONPATH=/User... | 5 | 3 |
70,844,974 | 2022-1-25 | https://stackoverflow.com/questions/70844974/onnxruntime-vs-onnxruntimeopenvinoep-inference-time-difference | I'm trying to accelerate my model's performance by converting it to OnnxRuntime. However, I'm getting weird results, when trying to measure inference time. While running only 1 iteration OnnxRuntime's CPUExecutionProvider greatly outperforms OpenVINOExecutionProvider: CPUExecutionProvider - 0.72 seconds OpenVINOExecut... | The use of ONNX Runtime with OpenVINO Execution Provider enables the inferencing of ONNX models using ONNX Runtime API while the OpenVINO toolkit runs in the backend. This accelerates ONNX model's performance on the same hardware compared to generic acceleration on Intel® CPU, GPU, VPU and FPGA. Generally, CPU Executio... | 7 | 6 |
70,836,912 | 2022-1-24 | https://stackoverflow.com/questions/70836912/use-mysql-connector-but-get-importerror-missing-optional-dependency-sqlalche | I work on a program for two months. Today I suddenly got an error when connecting to the database while using mysql.connector. Interestingly, this error is not seen when running previous versions. import mysql.connector import pandas as pd mydb = mysql.connector.connect(host="localhost", user="root", password="*****", ... | I just ran into something similar. It looks like Pandas 1.4 was released on January 22, 2022: https://pandas.pydata.org/docs/dev/whatsnew/v1.4.0.html It has an "optional" dependency on SQLAlchemy, which is required to communicate with any database other than sqlite now, as the comment by snakecharmerb mentioned. Once I... | 6 | 9 |
70,848,406 | 2022-1-25 | https://stackoverflow.com/questions/70848406/how-to-approve-github-pull-request-using-access-token | As per API documentation https://docs.github.com/en/rest/reference/pulls#create-a-review-for-a-pull-request We can use a CURL to approve pull request i.e. curl -s -H "Authorization: token ghp_TOKEN" \ -X POST -d '{"event": "APPROVE"}' \ "https://api.github.com/repos/{owner}/{repo}/pulls/{pull_number}/reviews" but I ge... | After bit of experiments, it has worked with API /repos/{owner}/{repo}/pulls/{pull_number}/reviews I must say that Github documentation is very poor that I have to spend almost 3 hours to figure this out. A small but proper CURL would have helped in a few seconds and would have saved my time. Anyway, leaving this solut... | 5 | 6 |
70,846,882 | 2022-1-25 | https://stackoverflow.com/questions/70846882/specialize-the-regex-type-re-pattern | Specializing the type of re.Pattern to re.Pattern[bytes], mypy correctly detects the type error: import re REGEX: re.Pattern[bytes] = re.compile(b"\xab.{2}") def check(pattern: str) -> bool: if str == "xyz": return REGEX.fullmatch(pattern) is not None return True print(check("abcd")) Type mismatch detected: $ mypy ~/m... | The ability to specialize the generic re.Pattern and re.Match types using [str] or [bytes] was added in Python 3.9. It seems you are using an older Python version. For Python versions earlier than 3.8 the typing module provides a typing.re namespace which contains replacement types for this purpose. Since Python 3.8, t... | 5 | 5 |
70,843,273 | 2022-1-25 | https://stackoverflow.com/questions/70843273/is-there-any-way-to-override-inherited-class-attribute-type-in-python-with-mypy | I wrote a defaultdict subclass that can call default_factory with key as argument. from collections import defaultdict from typing import TypeVar, Any, Callable, Generic K = TypeVar('K') class keydefaultdict(defaultdict, Generic[K]): ''' Drop-in replacement for defaultdict accepting key as argument ''' default_factory:... | This is intended behavior, as what you're describing violates the Liskov substitution principle. See the mypy documentation for more details. Using defaultdict as a subclass is a bad idea for this reason. But, if you really want to get around this (not recommended), you can use # type: ignore[override], like so: defaul... | 8 | 7 |
70,766,875 | 2022-1-19 | https://stackoverflow.com/questions/70766875/how-to-fix-x-does-not-have-valid-feature-names-but-isolationforest-was-fitted-w | Here is my code: import numpy as np import pandas as pd import seaborn as sns from sklearn.ensemble import IsolationForest data = pd.read_csv('marks1.csv', encoding='latin-1', on_bad_lines='skip', index_col=0, header=0 ) random_state = np.random.RandomState(42) model = IsolationForest(n_estimators=100, max_samples='aut... | It depends on the version of sklearn you are using. In versions past 1.0, models have a feature_names attribute when trained with dataframes that integrates the column names. There was a bug in this version that threw an error when training with dataframes. https://github.com/scikit-learn/scikit-learn/issues/21577 I'm ... | 10 | 16 |
70,837,397 | 2022-1-24 | https://stackoverflow.com/questions/70837397/good-alternative-to-pandas-append-method-now-that-it-has-been-deprecated | I use the following method a lot to append a single row to a dataframe. However, it has been deprecated. One thing I really like about it is that it allows you to append a simple dict object. For example: # Creating an empty dataframe df = pd.DataFrame(columns=['a', 'b']) # Appending a row df = df.append({ 'a': 1, 'b':... | Create a list with your dictionaries, if they are needed, and then create a new dataframe with df = pd.DataFrame.from_records(your_list). List's "append" method are very efficient and won't be ever deprecated. Dataframes on the other hand, frequently have to be recreated and all data copied over on appends, due to thei... | 179 | 73 |
70,836,444 | 2022-1-24 | https://stackoverflow.com/questions/70836444/no-module-named-symbol | I have problem with my pip . Lately I was getting error when I was trying to install any packages The Error was: ( Pyautogui ) Traceback (most recent call last): File "C:\Users\rati_\OneDrive\Desktop\PyAutoGUI-0.9.53.tar\PyAutoGUI-0.9.53\PyAutoGUI-0.9.53\setup.py", line 4, in <module> from setuptools import setup File ... | Module symbol was a part of the standard library since the dawn of time. It was declared deprecated in Python 3.9 and finally removed in 3.10. For Python 3.10 one has to upgrade any 3rd-party library that imports symbol. In your case the libraries are pip/setuptools: pip install --upgrade pip setuptools If upgrade is ... | 5 | 15 |
70,825,917 | 2022-1-23 | https://stackoverflow.com/questions/70825917/selenium-common-exceptions-webdriverexception-message-unknown-error-devtoolsa | I want to run selenium through chromium. I wrote this code: from selenium import webdriver from selenium.webdriver.chrome.options import Options options = Options() options.add_argument("start-maximized") options.add_argument("disable-infobars") options.add_argument("--disable-extensions") options.add_argument("--disab... | I solved the problem by reinstalling chromium through apt sudo apt install chromium-browser (before that it was installed through snap). My working code looks like this options = Options() options.add_argument("start-maximized") options.add_argument("disable-infobars") options.add_argument("--disable-extensions") optio... | 8 | 7 |
70,833,411 | 2022-1-24 | https://stackoverflow.com/questions/70833411/custom-truncfunc-in-django-orm | I have a Django model with the following structure: class BBPerformance(models.Model): marketcap_change = models.FloatField(verbose_name="marketcap change", null=True, blank=True) bb_change = models.FloatField(verbose_name="bestbuy change", null=True, blank=True) created_at = models.DateTimeField(verbose_name="created ... | I guess it's impossible on DB level (and Trunc is DB level function) as only month, days weeks and so on are supported in Postgres and Oracle. So what I would suggest is to use TruncDay and then add python code to group those by 3 days. | 5 | 1 |
70,790,849 | 2022-1-20 | https://stackoverflow.com/questions/70790849/typeerror-set-ticks-got-an-unexpected-keyword-argument-labels | I am trying to run the example of a heatmap from: https://matplotlib.org/stable/gallery/images_contours_and_fields/image_annotated_heatmap.html When I am running the code in PyCharm (Professional) in an Anaconda3 environment it results in an error message. TypeError: set_ticks() got an unexpected keyword argument 'lab... | There is no need to update matplotlib version if you are using version of matplotlib 3.4.3. Here is the link for matplotlib 3.4.3 documentation and avoid using labels keyword in ax.set_xticks() function as said by JohnC | 10 | 8 |
70,801,888 | 2022-1-21 | https://stackoverflow.com/questions/70801888/ignore-the-first-space-in-csv | I have a CSV file like this: Time Latitude Longitude 2021-09-12 23:13 44.63 -63.56 2021-09-14 23:13 43.78 -62 2021-09-16 23:14 44.83 -54.6 2021-09-12 23:13 is under Time column. I would like to open it using pandas. But there is a problem with the first column. It contains a space. If I open it using: import pandas as... | Ideally you should be parsing the first two parts as a datetime. By using a space as a delimiter, it would imply the header has three columns. The space after the date though is being seen as an extra column. A workaround is to skip the header entirely and supply your own column names. The parse_dates parameter can be ... | 7 | 1 |
70,832,297 | 2022-1-24 | https://stackoverflow.com/questions/70832297/install-poppler-in-aws-base-python-image-for-lambda | I am trying to deploy my docker container on AWS Lambda. However, I use pdf2image package in my code which depends on poppler. To install poppler, I need to insert the following line in the Dockerfile. RUN apt-get install -y poppler-utils This is the full view of the dockerfile. FROM ubuntu:18.04 RUN apt-get update RU... | It uses the yum package manager, so you can do the following instead: FROM public.ecr.aws/lambda/python:3.6 RUN yum install -y poppler-utils | 6 | 17 |
70,818,269 | 2022-1-23 | https://stackoverflow.com/questions/70818269/tensorflow-valueerror-unexpected-result-of-train-function-empty-logs-pleas | I'm trying to make a face detection model with CNN. I used codes that I made for number detection. When I use number images, program work. But, when I use my face images, I get an error that is: Unexpected result of train_function (Empty logs). Please use Model.compile(..., run_eagerly=True), or tf.config.run_functions... | Your input images have a shape of (32,32,3) whil you first conv2D layer sets the inputshape to (32,32,1). Most likely your numbers have only 1 channel since they are grayscale, while you face images have 3 color channels. change: model.add(tf.keras.layers.Conv2D(input_shape = (32,32,1), filters = 8, kernel_size = (5,5)... | 9 | 7 |
70,825,086 | 2022-1-23 | https://stackoverflow.com/questions/70825086/python-lowpass-filter-with-only-numpy | I need to implement a lowpass filter in Python, but the only module I can use is numpy (not scipy). I tried using np.fft.fft() on the signal, then setting all frequencies which are higher than the cutoff frequency to 0 and then using np.fft.ifft(). Howerver this didn't work and I'm not shure how to apply the filter at ... | I see that the comments of @Cris Luengo have already developed your solution into the right direction. The last thing you're missing now is that the spectrum you obtain from np.fft.fft is composed of the positive frequency components in the first half and the 'mirrored' negative frequency components in the second half.... | 8 | 8 |
70,823,561 | 2022-1-23 | https://stackoverflow.com/questions/70823561/aws-cdk-python-passing-multiple-variables-between-stacks | Background I have two Stacks within my CDK App. One is a Stack that defines Network Constructs (such as a VPC, Security Groups, etc), and one is a Stack responsible for creating an EKS cluster. The EKS Cluster needs to be able to consume variables and output from the Networking Stack as part of the cluster provisioning... | Step 1 Change any variable you want to reference to an attribute of the NetworkStack class. So, instead of: controlplane_security_group = ec2.SecurityGroup(self, "ControlPlaneSecurityGroup", vpc=kubernetes_vpc) You should do: self.controlplane_security_group = ec2.SecurityGroup(self, "ControlPlaneSecurityGroup", vpc=k... | 9 | 8 |
70,822,030 | 2022-1-23 | https://stackoverflow.com/questions/70822030/how-to-fix-template-does-not-exist-in-django | I am a beginner in the Django framework. I created my project created my app and test it, it work fine till I decided to add a template. I don't know where the error is coming from because I follow what Django docs say by creating folder name templates in your app folder creating a folder with your app name and lastly ... | It seems that you render the template with Blog/index, but you need to specify the entire file name, so Blog/index.html and without a leading (or trailing) space: def html(request): return render(request, 'Blog/index.html') | 11 | 3 |
70,780,758 | 2022-1-20 | https://stackoverflow.com/questions/70780758/how-to-generate-random-normal-distribution-without-numpy-google-interview | So I have a data science interview at Google, and I'm trying to prepare. One of the questions I see a lot (on Glassdoor) from people who have interviewed there before has been: "Write code to generate random normal distribution." While this is easy to do using numpy, I know sometimes Google asks the candidate to code w... | According to the Central Limit Theorem a normalised summation of independent random variables will approach a normal distribution. The simplest demonstration of this is adding two dice together. So maybe something like: import random import matplotlib.pyplot as plt def pseudo_norm(): """Generate a value between 1-100 i... | 7 | 7 |
70,820,707 | 2022-1-23 | https://stackoverflow.com/questions/70820707/export-module-components-in-python | In Julia, it is possible to export a function (or a variable, struct, etc.) of a module, after which it can be called in another script without the namespace (once it has been imported). For example: # helpers.jl module helpers function ordinary_function() # bla bla bla end function exported_function() # bla bla bla en... | In Python importing is easier than this: # module.py def foo(): pass # file.py from module import foo foo() # file2.py from file import foo foo() This works with classes too. In Python you can also do something like this: import module # You have to call like this: module.foo() When you import a module, all the fun... | 5 | 5 |
70,819,525 | 2022-1-23 | https://stackoverflow.com/questions/70819525/send-long-message-in-telegram-bot-python | I have a telegram bot and I want to send a message in which the error message will be returned to me my code is : path = 'C:\\Bot\\Log\\aaa\\*.log' files = glob.glob(path) nlines= 0 data = "Servers : \n" for name in files: with open(name) as f: for line in f : nlines += 1 if (line.find("Total") >= 0): data += line fo... | its still an open issue, but you can split your request for 4089 chars per send you have 2 options: if len(info) > 4096: for x in range(0, len(info), 4096): bot.send_message(message.chat.id, info[x:x+4096]) else: bot.send_message(message.chat.id, info) or msgs = [message[i:i + 4096] for i in range(0, len(message), 409... | 7 | 8 |
70,813,009 | 2022-1-22 | https://stackoverflow.com/questions/70813009/parsing-env-files | How do safely store passwords and API keys within an .env file and properly parse them? using python? I want to store passwords that I do not wish to push into public repos. | You may parse the key values of an .env file you can use os.getenv(key) where you replace key with the key of the value you want to access Suppose the contents of the .env files are : A=B FOO=BAR SECRET=VERYMUCH You can parse the content like this : import os print(os.getenv("A")) print(os.getenv("FOO")) print(os.gete... | 6 | 7 |
70,820,178 | 2022-1-23 | https://stackoverflow.com/questions/70820178/some-problems-about-python-inherited-classmethod | I have this code: from typing import Callable, Any class Test(classmethod): def __init__(self, f: Callable[..., Any]): super().__init__(f) def __get__(self,*args,**kwargs): print(args) # why out put is (None, <class '__main__.A'>) where form none why no parameter 123 # where was it called return super().__get__(*args,*... | The __get__ method is called when the method b is retrieved from the A class. It has nothing to do with the actual calling of b. To illustrate this, separate the access to b from the actual call of b: print("Getting a reference to method A.b") method = A.b print("I have a reference to the method now. Let's call it.") m... | 5 | 3 |
70,819,937 | 2022-1-23 | https://stackoverflow.com/questions/70819937/using-pd-concat-instead-of-df-append-with-pandas-1-4 | I am using df.append() in my code to append the percentage change across dataframe columns. With df.append() being depreciated in pandas 1.4, I am trying to use pd.concat but I am not able to replicate the output. So here is what I have now: import numpy as np import pandas as pd df = pd.DataFrame({"A": ["foo", "foo", ... | Use pd.concat like this. Convert your inner command to df using Series.to_frame and then transpose it using df.T: In [74]: pd.concat([table, table.iloc[-1].pct_change(periods=1, fill_method=None).fillna('').apply(lambda x: '{:.1%}'.format(x) if x else '').to_frame().T]) Out[74]: C large small All A B bar one 4 5 9 two ... | 5 | 4 |
70,817,125 | 2022-1-22 | https://stackoverflow.com/questions/70817125/poetry-how-to-keep-using-the-old-virtual-environment-when-changing-the-name-of | I am using Poetry in some of my python projects. It's not unusual that at some stage I want to rename the root folder of my project. When I do that and run poetry shell poetry creates a new virtual environment. But I don't want a new virtual environment, I just want to keep using the existing virtual environment. I kno... | One option is to enable the virtualenvs.in-project option, e.g. by running poetry config virtualenvs.in-project true If set to true, the virtualenv wil [sic] be created and expected in a folder named .venv within the root directory of the project. This will cause Poetry to create new environments in $project_root/.v... | 8 | 5 |
70,815,781 | 2022-1-22 | https://stackoverflow.com/questions/70815781/why-does-mypy-strict-not-throw-an-error-in-this-simple-code | I have the following in test.py: def f(x: int) -> float: pass if __name__=="__main__": f(4) When I run mypy --strict test.py, I get no errors. I expected mypy would be able to infer that there is a problem with my definition f. It obviously has no return statement and can never return a float. I feel like there is som... | The syntax you use is recognized as a function stub, not as a function implementation. Normally, a function stub is written as: def f(x: int) -> float: ... but this is merely a convenience for def f(x: int) -> float: pass From the mypy documentation: Function bodies cannot be completely removed. By convention, we re... | 5 | 4 |
70,810,857 | 2022-1-22 | https://stackoverflow.com/questions/70810857/split-geometric-progression-efficiently-in-python-pythonic-way | I am trying to achieve a calculation involving geometric progression (split). Is there any effective/efficient way of doing it. The data set has millions of rows. I need the column "Traded_quantity" Marker Action Traded_quantity 2019-11-05 09:25 0 0 09:35 2 BUY 3 09:45 0 0 09:55 1 BUY 4 10:05 0 ... | This should work def turtle_split(row): global base_quantity if row['Action'] == 'BUY': summation = base_quantity * (turtle ** row['Marker'] - 1) // (turtle - 1) base_quantity = base_quantity * (turtle ** (row['Marker'] - 1))*turtle return summation else: return 0 | 7 | 5 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.