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 |
|---|---|---|---|---|---|---|
76,228,417 | 2023-5-11 | https://stackoverflow.com/questions/76228417/cannot-import-name-event-type-opened-from-watchdog-events | I'm trying to make a REST api (begginer) but when i tried to initialize the server from this code: from flask import Flask app = Flask(__name__) if __name__=='__main__': app.run(debug=True, port=4000) i get this error in the prompt: from watchdog.events import EVENT_TYPE_OPENED ImportError: cannot import name 'EVENT... | Try to do the following: pip install --upgrade watchdog | 20 | 42 |
76,217,189 | 2023-5-10 | https://stackoverflow.com/questions/76217189/create-xarray-dataset-with-observations-and-averages-that-has-combined-index | Suppose I have the following dataarray containing observations for different locations over time: import numpy as np import pandas as pd import xarray as xr np.random.seed(42) data = xr.DataArray( np.random.randint(1,100, (36, 3)), dims=("time", "location"), coords={ "time": pd.date_range("2022-01-01", periods=36, freq... | To get the selection return what you want, I would first compute the monthly averages and repeat them to match the original time-dimension. Then I would create a multi-index, such that you can select either the specific date or the month. #setup test data import numpy as np import pandas as pd import xarray as xr np.ra... | 3 | 2 |
76,226,696 | 2023-5-11 | https://stackoverflow.com/questions/76226696/fastapi-uvicorn-multithreading-how-to-make-web-app-to-work-with-many-reques | I'm new to Python development. (But I have doenet background) I do have a simple FastAPI application from fastapi import FastAPI import time import logging import asyncio import random app = FastAPI() r = random.randint(1, 100) logging.basicConfig(level="INFO", format='%(levelname)s | %(asctime)s | %(name)s | %(message... | Why only one process does work and others don't? I can't reproduce your observation. And in fact I don't know how you deduced that. If I change your logging format and add logging.basicConfig(level="INFO", format='%(process)d | %(levelname)s | %(asctime)s | %(name)s | %(message)s') (note the %(process)d which prin... | 5 | 5 |
76,226,066 | 2023-5-11 | https://stackoverflow.com/questions/76226066/columns-must-be-same-length-as-key-error-when-trying-split | The code below just runs fine with Python 3.8.10 but does not run in Python 3.10. Any idea what could be the problem? import pandas as pd import requests url = "https://coinmarketcap.com/new/" page = requests.get(url,headers={'User-Agent': 'Mozilla/5.0'}, timeout=1) pagedata = page.text usecols = ["Name", "Symbol", "1h... | I think it has to do with one of the values (NOOT (BRC-20)4NOOT) found in the column Name. To handle this, we can try to split on the last number found in each row of this column. Replace this : df[["Name", "Symbol"]] = df["Name"].str.split(r"\d+", expand=True) By this : df[["Name", "Symbol"]] = df["Name"].str.split(r... | 3 | 3 |
76,217,229 | 2023-5-10 | https://stackoverflow.com/questions/76217229/update-plot-in-tkinter-from-user-input-without-lag-using-threading | I'm currently coding my first tkinter GUI. I'm trying to make an interactive plot, using some scales so that the user can set the values of parameters affecting the plot. when I do this it starts lagging and my solution; working with threading is not working as intended. In my real code there are multiple plots so the ... | Even though Tkinter supports manipulating GUI in a thread different than the thread that created the Tcl interpreter(the root Tk instance), it's best to avoid that scenario because the implementation is not perfect and most GUI frameworks do not support that scenario. I recommend to do a data processing work in a backg... | 3 | 2 |
76,225,668 | 2023-5-11 | https://stackoverflow.com/questions/76225668/remove-duplicated-values-appear-in-two-columns-in-dataframe | I have table similar to this one: index name_1 path1 name_2 path2 0 Roy path/to/Roy Anne path/to/Anne 1 Anne path/to/Anne Roy path/to/Roy 2 Hari path/to/Hari Wili path/to/Wili 3 Wili path/to/Wili Hari path/to/Hari 4 Miko path/to/miko Lin path/to/lin 5 Miko path/to/miko Dan path/to/dan 6 Lin path/to/lin Miko path/to/mik... | You can use frozenset to detect duplicates: out = (df[~df[['name_1', 'name_2']].agg(frozenset, axis=1).duplicated()] .loc[lambda x: ~x['path2'].isin(x['path1'])]) # OR out = (df[~pd.DataFrame(np.sort(df.values,axis=1)).duplicated()] .query('~path1.isin(path2)')) Output: >>> out name_1 path1 name_2 path2 0 Roy path/to/... | 3 | 4 |
76,223,870 | 2023-5-11 | https://stackoverflow.com/questions/76223870/parsing-xml-within-html-using-python | I have an HTML file which contains XML at the bottom of it and enclosed by comments, it looks like this: <!DOCTYPE html> <html> <head> *** </head> <body> <div class="panel panel-primary call__report-modal-panel"> <div class="panel-heading text-center custom-panel-heading"> <h2>Report</h2> </div> <div class="panel-body"... | You already have been on the right path. I put your HTML in the file and it works fine like following. import xml.etree.ElementTree as ET with open('extract_xml.html') as handle: content = handle.read() xml = content[content.index('<!--')+4: content.index('-->')] document = ET.fromstring(xml) for element in document.fi... | 4 | 2 |
76,221,461 | 2023-5-10 | https://stackoverflow.com/questions/76221461/how-to-generate-python-type-hints-in-generated-grpc-code | Can PEP compliant type hints be automatically added to generated source code, or dynamically created, for python and gRPC? Specifically in the basics tutorial in the client section for feature = stub.GetFeature(point) I would like my IDE to know and check that point is type Point in the *_pb2.py and feature is type Fea... | Type hints aren't yet (!?) available for Python gRPC, see Issue 29041 You can generate type hints for the Protobuf messages only using the --pyi_out=${PWD} flag when running protoc directly or indirectly with python3 -m grpc.tools.protoc | 3 | 6 |
76,221,322 | 2023-5-10 | https://stackoverflow.com/questions/76221322/exec-fails-when-applied-to-a-code-with-a-new-type | I have a file multiply.py with the following contents: from typing import NamedTuple class Result(NamedTuple): product: int desc: str def multiply(a: int, b: int) -> Result: return Result( product=a * b, desc=f"muliplied {a} and {b}", ) x=4 y=5 print(multiply(x, y)) If I run it just like that it of course yields the e... | Since you are passing two different dictionaries for locals and globals, from the docs: If exec gets two separate objects as globals and locals, the code will be executed as if it were embedded in a class definition Class bodies are not an enclosing scope, functions defined in the class body do not have access to var... | 7 | 5 |
76,222,274 | 2023-5-10 | https://stackoverflow.com/questions/76222274/how-to-add-private-methods-to-pyo3-pymethods | I'd like to add hidden methods to pyo3 class methods implementation which will be invisible for Python. Example: #[pyclass] pub struct SomeItem; #[pymethods] impl SomeItem { #[new] pub fn new() -> Self { // visible for python constructor SomeItem; } pub fn method(&self) -> u8 { // visible for python method self.hidden_... | What about using a separate impl block? #[pymethods] impl SomeItem { #[new] pub fn new() -> Self { // visible for python constructor SomeItem; } pub fn method(&self) -> u8 { // visible for python method self.hidden_method() } } impl SomeItem { fn hidden_method(&self) -> u8 { 0 } } | 3 | 3 |
76,222,022 | 2023-5-10 | https://stackoverflow.com/questions/76222022/how-to-use-categorical-data-type-with-pyarrow-dtypes | I'm working with the arrow dtypes with pandas, and my dataframe has a variable that should be categorical, but I can't figure out how to transform it into pyarrow data type for categorical data (dictionary) According to pandas (https://arrow.apache.org/docs/python/pandas.html#pandas-arrow-conversion), the arrow data ty... | I believe pd.ArrowDtype is required: dtype=pd.ArrowDtype(pa.dictionary(pa.int16(), pa.string())) | 6 | 6 |
76,220,790 | 2023-5-10 | https://stackoverflow.com/questions/76220790/in-network-programming-must-the-accepting-end-close-both-sockets | I raised a question earlier, and one of the answers involved another question. That is to say, in general, the accepting end should create two sockets to establish the accepting end. like this: Python from socket import * sockfd = socket(...) # ... client_sockfd, addr = sockfd.accept() # ... client_sockfd.close() sockf... | So can we skip the task of creating the client_sockfd variable? For connection-oriented protocols such as TCP, no. The two sockets involved on the receiving side of such a service are of different kinds and serve different purposes, both required. The socket that (in C) you create via the socket() function and use wi... | 3 | 2 |
76,219,628 | 2023-5-10 | https://stackoverflow.com/questions/76219628/how-to-find-the-no-of-nulls-in-every-column-in-a-polars-dataframe | In pandas, one can do: import pandas as pd d = {"foo":[1,2,3, None], "bar":[4,None, None, 6]} df_pandas = pd.DataFrame.from_dict(d) dict(df_pandas.isnull().sum()) [out]: {'foo': 1, 'bar': 2} In polars it's possible to do the same by looping through the columns: import polars as pl d = {"foo":[1,2,3, None], "bar":[4,N... | Assuming you're not married to the output format the idiomatic way to do it is... df.select(pl.all().is_null().sum()) However if you really like the dict output you can easily get it... df.select(pl.all().is_null().sum()).to_dicts()[0] The way this works is that inside the select we start with pl.all() which means al... | 7 | 8 |
76,218,118 | 2023-5-10 | https://stackoverflow.com/questions/76218118/convert-matlab-to-python-for-reading-a-binary-file | Im trying to convert a matlab script into python. The script read a binary file and reshape into a number of columns. The matlab script is: fid=fopen(binary_file,'rb'); [inpar,ic]=fread(fid,4,'int'); if (ic<4) ; idata=[];return;end nmagic=inpar(1); nh=inpar(2); nrpar=inpar(3); nipar=inpar(4); [rdata,ic]=fread(binary_fi... | Lets try to read the data with open in rb mod so it will be read in binary mode. Then we will use np.fromfile to read from the file. import numpy as np with open(binary_file, 'rb') as fid: inpar = np.fromfile(fid, dtype=np.int32, count=4) if inpar.size < 4: idata = [] else: nmagic, nh, nrpar, nipar = inpar rdata = np.f... | 3 | 4 |
76,159,708 | 2023-5-3 | https://stackoverflow.com/questions/76159708/how-to-disable-authentication-in-fastapi-based-on-environment | I have a FastAPI application for which I enable Authentication by injecting a dependency function. controller.py router = APIRouter( prefix="/v2/test", tags=["helloWorld"], dependencies=[Depends(api_key)], responses={404: {"description": "Not found"}}, ) Authorzation.py async def api_key(api_key_header: str = Security... | You could create a subclass of APIKeyHeader class and override the __call__() method to perform a check whether the request comes from a "safe" client, such as localhost or 127.0.0.1, using request.client.host, as explained here. If so, you could set the api_key to application's API_KEY value, which would be returned a... | 9 | 6 |
76,189,734 | 2023-5-6 | https://stackoverflow.com/questions/76189734/how-to-convert-struct-to-series-in-polars | I have Dataframe with stuct inside after used pl.cum_fold(). How struct convert to normal series based column? ┌───────────────────────────────────┐ │ price │ │ --- │ │ struct[2000] │ ╞═══════════════════════════════════╡ │ {null,null,null,null,30302.67187… │ └───────────────────────────────────┘ Is it possible with p... | There is transpose once the struct is unnested. This will be relatively slow but I don't think there is any other way: df = pl.DataFrame( {"price": {'test0' : None, 'test1' : 1, 'test2' : 2}}) df.unnest('price').transpose(column_names=['price']) shape: (3, 1) ┌───────┐ │ price │ │ --- │ │ f64 │ ╞═══════╡ │ null │ │ 1.... | 5 | 1 |
76,200,899 | 2023-5-8 | https://stackoverflow.com/questions/76200899/polars-equivalent-of-pandas-groupby-applydrop-duplicates | I am new to polars and I wonder what is the equivalent of pandas groupby.apply(drop_duplicates) in polars. Here is the code snippet I need to translate : import pandas as pd GROUP = list('123231232121212321') OPERATION = list('AAABBABAAAABBABBBA') BATCH = list('777898897889878987') df_input = pd.DataFrame({'GROUP':GROU... | It looks like you want the first instance of each OPERATION, BATCH "pairing" per GROUP You can use pl.struct to create the "pairing" and then use is_first_distinct() as a Window function. (df.with_row_index() .filter(pl.struct("OPERATION", "BATCH").is_first_distinct().over("GROUP")) ) shape: (9, 4) ┌───────┬───────┬──... | 3 | 2 |
76,205,305 | 2023-5-9 | https://stackoverflow.com/questions/76205305/updating-non-trivial-structures-in-polars-cells | Say I have this: >>> polars.DataFrame([[(1,2),(3,4)],[(5,6),(7,8)]], list('ab')) shape: (2, 2) ┌────────┬────────┐ │ a ┆ b │ │ --- ┆ --- │ │ object ┆ object │ ╞════════╪════════╡ │ (1, 2) ┆ (5, 6) │ │ (3, 4) ┆ (7, 8) │ └────────┴────────┘ How would I go with updating the 2nd element of the tuple only? E.g. what do I n... | If you choose dicts instead, Polars will turn them into Structs df = pl.DataFrame({ "a": [{"x": 1, "y": 2}, {"x": 3, "y": 4}], "b": [{"x": 5, "y": 6}, {"x": 7, "y": 8}] }) shape: (2, 2) ┌───────────┬───────────┐ │ a ┆ b │ │ --- ┆ --- │ │ struct[2] ┆ struct[2] │ ╞═══════════╪═══════════╡ │ {1,2} ┆ {5,6} │ │ {3,4} ┆ {7,... | 3 | 1 |
76,188,316 | 2023-5-6 | https://stackoverflow.com/questions/76188316/is-pythonpath-really-an-environment-variable | The docs for sys.path state the following: A list of strings that specifies the search path for modules. Initialized from the environment variable PYTHONPATH, plus an installation-dependent default. So my understanding here is that PYTHONPATH is an environment variable. Environment variables can be printed out in Pow... | The variable PYTHONPATH is an environment variable which you can set to add additional directories where python will look for modules and packages. This variable is not set by default and not needed for Python to work because it it already knows where to find its standard libraries (sys.path). But if for any reason you... | 6 | 12 |
76,189,891 | 2023-5-6 | https://stackoverflow.com/questions/76189891/imagedraw-object-has-no-attribute-textbbox | I am working on a simple text mining project. When I tried to create a word-cloud I got this error: AttributeError: 'ImageDraw' object has no attribute 'textbbox' I have a dataset of News and their categories; to create a word-cloud I tried to preprocessing the text: import pandas as pd import numpy as np import panda... | History The ImageDraw.textsize() method was deprecated in PIL version 9.2.0 and completely removed beginning with version 10.0.0 on 2023-07-01. The ImageDraw.textbbox() method was introduced in version 8.0.0 as a more robust solution. Example If you are looking to simply replace one line of code, and you previously had... | 6 | 8 |
76,187,256 | 2023-5-6 | https://stackoverflow.com/questions/76187256/importerror-urllib3-v2-0-only-supports-openssl-1-1-1-currently-the-ssl-modu | After pip install openai, when I try to import openai, it shows this error: the 'ssl' module of urllib3 is compile with LibreSSL not OpenSSL I just followed a tutorial on a project about using API of OpenAI. But when I get to the first step which is the install and import OpenAI, I got stuck. And I tried to find the ... | The reason why the error message mentioned OpenSSL 1.1.1+ and LibreSSL 2.8.3 is that urllib3 v2.0 (the version you've installed) requires OpenSSL 1.1.1+ to work properly, as it relies on some new features of OpenSSL 1.1.1. The issue is that the version of the 'ssl' module that is currently installed in your environment... | 172 | 259 |
76,212,816 | 2023-5-9 | https://stackoverflow.com/questions/76212816/403-forbidden-tweepy-authentication-error-when-attempting-to-access-tweet-user | import tweepy import os api_key = os.getenv('TWI_API_KEY') api_key_secret = os.getenv('TWI_API_KEY_SECRET') bearer_token = os.getenv('TWI_BEARER_TOKEN') access_token = os.getenv('TWI_ACCESS_TOKEN') access_token_secret = os.getenv('TWI_ACCESS_TOKEN_SECRET') client = tweepy.Client(bearer_token=bearer_token, consumer_key=... | The error is because of twitter policy change where in the free tier, there is no way for us to pull tweets, we can only do that if we have a basic subscription which is 100$ per month now. Details can be found here: https://developer.twitter.com/en/products/twitter-api | 3 | 2 |
76,182,655 | 2023-5-5 | https://stackoverflow.com/questions/76182655/trying-to-convert-a-date-to-another-format-gives-error | I have a program where the user selects a date from a datepicker, and I need to convert this date to another format. The original format is %d/%m/%Y and I need to convert it to %-d-%b-%Y. I made a small example of what happens: from datetime import datetime # Import tkinter library from tkinter import * from tkcalendar... | The reason why that gives an error is because %-d only works on Unix machines (Linux, MacOS). On Windows (or Cygwin), you have to use %#d. | 3 | 2 |
76,207,341 | 2023-5-9 | https://stackoverflow.com/questions/76207341/how-to-get-first-n-chars-from-a-str-column-in-python-polars | What's the alternative of pandas : data['ColumnA'].str[:2] in python polars? pl.col('ColumnA').str[:3] throws TypeError: 'ExprStringNameSpace' object is not subscriptable error. | You can use str.slice, It takes two arguments offset and length. offset specifies the start index and the length specifies the length of slice. If set to None (default), the slice is taken to the end of the string. >>> import polars as pl >>> >>> df = pl.DataFrame({"animal": ["Crab", "cat and dog", "rab$bit", None]}) >... | 6 | 10 |
76,200,452 | 2023-5-8 | https://stackoverflow.com/questions/76200452/error-while-iterating-over-dataframe-columns-entries-attributeerror-series | Using pandas version 2, I get an error when calling iteritems. for event_id, region in column.iteritems(): pass The following error message appears: Traceback (most recent call last): File "/home/analyst/anaconda3/envs/outrigger_env/lib/python3.10/site- packages/outrigger/io/gtf.py", line 185, in exon_bedfiles for eve... | iteritems was removed in 2.0.0 by GH45321. Removed deprecated Series.iteritems()... use obj.items instead. (from v2.0.0 release notes) You can use items wherever you used iteritems: for event_id, region in column.items(): pass | 23 | 44 |
76,195,972 | 2023-5-7 | https://stackoverflow.com/questions/76195972/aspect-sentiment-analysis-using-hugging-face | I am new to transformers models and trying to extract aspect and sentiment for a sentence but having issues from transformers import AutoTokenizer, AutoModelForSequenceClassification model_name = "yangheng/deberta-v3-base-absa-v1.1" tokenizer = AutoTokenizer.from_pretrained(model_name) model = AutoModelForSequenceClass... | The model you are trying to use predicts the sentiment for a given aspect based on a text. That means, it requires text and aspect to perform a prediction. It was not trained to extract aspects from a text. You could use a keyword extraction model to extract aspects (compare this SO answer). import torch import torch.n... | 3 | 1 |
76,208,101 | 2023-5-9 | https://stackoverflow.com/questions/76208101/is-there-a-way-to-change-the-html-textcontent-from-inside-the-pyodide-runpython | So for example I have a for loop inside my pyodide script that is inside my .html document. Is there a ways to change textContent of a div directly from pyodide for loop. In the example below, only the last value of the for loop (in my case 99) is then sent to "myDiv". Is it even possible to change the textContent dire... | The issue isn't that the textContent isn't being changed; the issue is that there's no opportunity for the screen to update to actually display the change. The solution is to use a coroutine. Confirming that Changes Do Happen To observe that the textContent is indeed changing, we can add a small Mutation Observer to th... | 3 | 3 |
76,213,454 | 2023-5-9 | https://stackoverflow.com/questions/76213454/hide-ultralytics-yolov8-model-predict-output-from-terminal | I have this output that was generated by model.predict() 0: 480x640 1 Hole, 234.1ms Speed: 3.0ms preprocess, 234.1ms inference, 4.0ms postprocess per image at shape (1, 3, 640, 640) 0: 480x640 1 Hole, 193.6ms Speed: 3.0ms preprocess, 193.6ms inference, 3.5ms postprocess per image at shape (1, 3, 640, 640) ... How do I... | The Ultralytics docs are sadly not up to date, as of today. The right way of doing this is: from ultralytics import YOLO model = YOLO('yolov8m-seg.pt') results = model.predict(source='0', verbose=False) for result in results: masks = result.masks.masks print(masks.shape) Notice the verbose=False argument. This won't p... | 9 | 17 |
76,193,660 | 2023-5-7 | https://stackoverflow.com/questions/76193660/in-python-can-i-return-a-child-instance-when-instantiating-its-parent | I have a zoo with animals, represented by objects. Historically, only the Animal class existed, with animal objects being created with e.g. x = Animal('Bello'), and typechecking done with isinstance(x, Animal). Recently, it has become important to distinguish between species. Animal has been made an ABC, and all animal... | In the end, I went with a class decorator: # defining the decorator def dont_init_twice(Class): """Decorator for child classes of Animal, to allow Animal to return a child instance.""" original_init = Class.__init__ Class._initialized = False def wrapped_init(self, *args, **kwargs): if not self._initialized: object.__s... | 4 | 0 |
76,199,653 | 2023-5-8 | https://stackoverflow.com/questions/76199653/valueerror-run-not-supported-when-there-is-not-exactly-one-input-key-got-q | Getting the error while trying to run a langchain code. ValueError: `run` not supported when there is not exactly one input key, got ['question', 'documents']. Traceback: File "c:\users\aviparna.biswas\appdata\local\programs\python\python37\lib\site-packages\streamlit\runtime\scriptrunner\script_runner.py", line 565, i... | For a prompt with multiple inputs, use predict() instead of run(), or just call the chain directly. (Note: Requires Python 3.8+) prompt_template = "Tell me a {adjective} joke and make it include a {profession}" llm_chain = LLMChain( llm=OpenAI(temperature=0.5), prompt=PromptTemplate.from_template(prompt_template) ) # O... | 4 | 4 |
76,208,544 | 2023-5-9 | https://stackoverflow.com/questions/76208544/networkx-digraph-nodes-set-the-border-and-inner-color-and-format-text | I'm using Django, and in my view I generate a diagram of relations between parties. The problem is with the following: nx.set_node_attributes(G, fill_coloring, name="background") But this unfortunately doesn't work. I'm unable to find in the documentation how I can set it properly. What I want to achieve is to direct ... | Thanks @Paul Brodersen; below posted as accepted answer: I found the answer, shortly after posting this. Graphviz needs the style to be set to "filled". Below solved this: nx.set_node_attributes(G, {e.customer_end.name: "filled"}, name="style") Additionally I changed the model to add colors based on the segmentation. ... | 3 | 0 |
76,174,677 | 2023-5-4 | https://stackoverflow.com/questions/76174677/correctly-displaying-tooltips-with-rounded-corners-with-pyqt5 | I need to properly display a tooltip with rounded corners using PyQt5. The default behavior whenever using the border-radius: 8px; in the stylesheet of a QToolTip keeps the tooltip rendered as a rectangle, and the border-radius property only impacts the shape of the border, which is rather ugly. This question is follow... | It seems that by default, Windows 11 creates a mask for tooltips ; therefore if super().styleHint(hint, opt, widget, returnData): is always True. If we want to run the logic generating the mask, we have to remove that block. In order to render the tooltip, to get a mask to clip it later, we also have to prevent infinit... | 3 | 3 |
76,180,798 | 2023-5-5 | https://stackoverflow.com/questions/76180798/jenkins-job-failing-for-urllib3-valueerror-timeout-value-connect-was-object-o | As of May 4, 2023, at 16:00, I started seeing one of our Jenkins job failing with the following error: Traceback (most recent call last): File "/home/jenkins/agent/workspace/my-jenkins-job/.tox/appdev-ci-staging/lib/python3.9/site-packages/jenkins/__init__.py", line 822, in get_info return json.loads(self.jenkins_open(... | A new version 2.0.2 of urllib3 was released on May 4, 2023, which can be seen here: urllib3 2.0.2 - Release history As my job installs the Python libraries in the beginning of the job using pip in a virtual Python environment, it started installing the latest version of urllib3 which had some issues. So, it is looks an... | 4 | 16 |
76,191,646 | 2023-5-6 | https://stackoverflow.com/questions/76191646/how-to-annotate-grouped-bars-with-percent-for-each-index | I have created a bar plot with the following code. I would like to label the percentages adding up to ~100% for each user, as I've done in MSpaint for user1 and user2 below: import matplotlib.pyplot as plt import numpy as np import pandas as pd users = ['user1', 'user2', 'user3', 'user4', 'user5', 'user6', 'user7',\ '... | Plot df, but create a dataframe of the percents, which can be used as custom labels for .bar_label. See How to add value labels on a bar chart for a thorough explanation, and additional examples, of .bar_label. # create a dataframe of percents percent = df.div(df.sum(axis=1), axis=0).mul(100).round(1) # plot ax = df.... | 3 | 4 |
76,213,501 | 2023-5-9 | https://stackoverflow.com/questions/76213501/python-packages-imported-in-editable-mode-cant-be-resolved-by-pylance-in-vscode | I have several Python packages developed locally, which I often use in VSCode projects. For these projects, I create a new virtualenv and install these packages with pip install -e ../path/to/package. This succeeds, and I can use these packages in the project. However, VSCode underlines the package's import line in yel... | Usually, when you choose the correct interpreter, Pylance should take effect immediately. You can try adding "python.analysis.extraPaths": ["path/to/your/package"] to your settings.json. You can also try clicking on the install prompt in vscode to see which environment it will install the package in. I still believe th... | 22 | 9 |
76,201,333 | 2023-5-8 | https://stackoverflow.com/questions/76201333/how-can-time-spent-in-asynchronous-generators-be-measured | I want to measure a time spent by generator (time blocking main loop). Lets say that I have two following generators: async def run(): for i in range(5): await asyncio.sleep(0.2) yield i return async def walk(): for i in range(5): time.sleep(0.3) yield i return I want to measure that run spent around 0.0s per iteratio... | So - one thing (a bit though) is to measure times in regular co-routines - I got it going with a decorator. However, when you go a step ahead into async-generators, it is another beast - I am still trying to figure it out - it is a mix of public-exposed async-iterator methods (__anext__, asend, etc...) with traditional... | 3 | 2 |
76,196,220 | 2023-5-7 | https://stackoverflow.com/questions/76196220/python-why-is-my-marginal-y-histogram-plot-changing-when-the-x-variable-is-chan | I am trying to use plotly to create a scatter plot where the x-variable can be selected from a drop-down menu. The scatter plot would also have marginal histogram plots. # Generate data and import libraries import pandas as pd import numpy as np import plotly.express as px import plotly.graph_objects as go # set the ra... | You can fix this by specifying which trace to update, passing an array of trace indices to the update method : args = [ {'x': [df_scatterplot[str(col)]]}, # update x variable {'xaxis.title.text': str(col)}, # update x-axis title [0, 1] # update only trace 0 and 1 (preserve marginal_y) ], The idea is to preserve the ma... | 3 | 2 |
76,209,122 | 2023-5-9 | https://stackoverflow.com/questions/76209122/how-to-detect-a-windows-network-path | I am writing a script which runs a Windows executable file in a directory supplied by a user. If this script is a network path, making it the current directory will look like it worked, but running any commands in this directory will fail: >>> import os >>> os.chdir(r'\\server\share\folder') # my actual name is differe... | I agree that the simplest check is yourpathstring.startswith(r'\\'). However, this will be a false-positive for any linux path which starts with \\ (unlikely but possible) and a false-negative when people use forward slashes: //server\share\folder. It appears that the library function splitdrive was designed with netwo... | 3 | 4 |
76,197,174 | 2023-5-8 | https://stackoverflow.com/questions/76197174/aws-elastic-beanstalk-cant-install-mysqlclient | I am going through the adding database to elastic beanstalk python documentation but following the steps leads to the following error 2023/05/07 14:06:36.847596 [ERROR] An error occurred during execution of command [app-deploy] - [InstallDependency]. Stop running the command. Error: fail to install dependencies with re... | After some trial and error I ended up modifying my config file to start with this, which solved my issue packages: yum: mariadb105-devel: [] I found the package completely by chance. If someone know how to discover these for the future please do tell me | 3 | 9 |
76,208,396 | 2023-5-9 | https://stackoverflow.com/questions/76208396/pyrebase4-error-cannot-import-name-gaecontrib | I have been trying to install pyrebase4 using pip install pyrebase4 but when ran it throws below error "C:\Users\ChodDungaTujheMadhadchod\anaconda3\envs\sam_upgraded\lib\site-packages\requests_toolbelt\adapters\appengine.py", line 42, in <module> from .._compat import gaecontrib ImportError: cannot import name 'gaecont... | Okay so what I found that the latest requests-toolbelt 1.0.1 is currently throwing this issue. So downgrading it to next previous version requests-toolbelt==0.10.1 fixes the issue. | 7 | 12 |
76,202,488 | 2023-5-8 | https://stackoverflow.com/questions/76202488/mockerfixture-has-no-attribute-assert-called-once-attr-defined | In module.py, I have: def func(x: int) -> str | None: if x > 9: return "OK" return None def main(x: int) -> str | None: return func(x) In test_module.py, I have: import pytest from pytest_mock import MockerFixture from module import main @pytest.fixture(name="func") def fixture_func(mocker: MockerFixture) -> MockerFix... | You have declared a wrong type for the func argument. The return type of mocker.patch is unittest.mock.MagicMock: import pytest from unittest.mock import MagicMock from pytest_mock import MockerFixture from module import main @pytest.fixture(name="func") def fixture_func(mocker: MockerFixture) -> MagicMock: return mock... | 3 | 4 |
76,180,770 | 2023-5-5 | https://stackoverflow.com/questions/76180770/writing-integers-as-sum-of-kth-power-distinct-integers | Given an n integer (n >= 1), and a number k, return all possible ways to write n as kth power different integers. For instance, if n = 100 and k = 2: 100 = 1**2 + 3**2 + 4**2 + 5**2 + 7**2 = 6**2 + 8**2 = 10**2 or if k = 3: 100 = 1**3 + 2**3 + 3**3 + 4**3 So program(100,2) returns something like [(2, [1, 3, 4, 5, 7])... | If you implement this as a recursive generator, you won't need to store a large number of values (not even the results): def powersum(n,k,b=1): bk = b**k while bk < n: for bases in powersum(n-bk,k,b+1): yield [b]+bases b += 1 bk = b**k if bk == n : yield [b] print(*powersum(100,2)) # [1, 3, 4, 5, 7] [6, 8] [10] print(*... | 3 | 5 |
76,197,265 | 2023-5-8 | https://stackoverflow.com/questions/76197265/why-is-squaring-a-number-slower-than-multiplying-itself-by-itself | I was curious and decided to run this code in python: import time def timeit(function): strt = time.time() for _ in range(100_000_000): function() end = time.time() print(end-strt) @timeit def function1(): return 1 * 1 @timeit def function2(): return 1_000_000_000_000_000_000_000_000_000_000 * 1_000_000_000_000_000_000... | Here's the implementation of int.__pow__, abridged to only show code that executes for this operation: /* pow(v, w, x) */ static PyObject * long_pow(PyObject *v, PyObject *w, PyObject *x) { PyLongObject *a, *b, *c; /* a,b,c = v,w,x */ int negativeOutput = 0; /* if x<0 return negative output */ PyLongObject *z = NULL; /... | 5 | 6 |
76,196,651 | 2023-5-7 | https://stackoverflow.com/questions/76196651/how-to-sort-dataframe-result-based-on-column-values | import requests import pandas as pd url = "https://coinmarketcap.com/new/" page = requests.get(url,headers={'User-Agent': 'Mozilla/5.0'}, timeout=1) pagedata = page.text usecols = ["Name", "Price", "1h", "24h", "MarketCap", "Volume"]#, "Blockchain"] df = pd.read_html(pagedata)[0] #Checking table df[["Name", "Symbol"]] ... | I would convert all the numeric columns in your df to numeric values; then you can sort them easily (you can always add back $ and % as required on display). numcols = df.columns[df.columns != 'Name'] df[numcols] = df[numcols].apply(lambda c:pd.to_numeric(c.str.replace(r'[^\d.]|(?<!\d)\.|\.(?!\d)', '', regex=True))) df... | 3 | 2 |
76,194,973 | 2023-5-7 | https://stackoverflow.com/questions/76194973/python-tkinter-cascaded-menu-command-not-executing | I have a problem, which I am trying to solve, and have reproduced it with the code below. The issue that I have, is that I can get the specified command to work from a main menu item, but when the same command is included in a cascade menu, it doesn't appear to execute. I'm not sure whether this is in anyway to do with... | The submenu in the code in the question is set up as an element of button: sub_menu = tk.Menu(button, tearoff=False) However, this causes the submenu to be displayed correctly but to not be clickable (reproduced on Ubuntu, Python 3.10.6, Tkinter 8.6). When you make the submenu an element of context_menu then it does w... | 5 | 1 |
76,195,685 | 2023-5-7 | https://stackoverflow.com/questions/76195685/how-to-replicate-value-based-on-distinct-column-values-from-a-different-df-pyspa | I have a df like: df1 = AA BB CC DD 1 X Y Z 2 M N O 3 P Q R I have another df like: df2 = BB CC DD G K O H L P I M Q I want to copy all the columns and rows of df2 for every distinct value of 'AA' column of df1 and get the resultant df as: df = AA BB CC DD 1 X Y Z 1 G K O 1 H L P 1 I M Q 2 M N O 2 G K O 2 H L P 2 I M... | This would work: resultDf= df.select("AA")\ .crossJoin(df2)\ .union(df) # No Need to order the actual result, this is just for displaying this example. resultDf.orderBy("AA").show() Although, this would still be a huge operation and can be expensive on the cluster. Input DF1: +---+---+---+---+ | AA| BB| CC| DD| +---+-... | 3 | 2 |
76,195,463 | 2023-5-7 | https://stackoverflow.com/questions/76195463/shorthand-index-to-get-a-cycle-of-a-numpy-array | I want to index all elements in a numpy array and also include the first index at the end. So if I have the array [2, 4, 6] , I want to index the array such that the result is [2, 4, 6, 2]. import numpy as np a = np.asarray([2,4,6]) # One solution is cycle = np.append(a, a[0]) # Another solution is cycle = a[[0, 1, 2, ... | Another possible solution: a = np.asarray([2,4,6]) cycle = np.take(a, np.arange(len(a)+1), mode='wrap') Output: [2 4 6 2] | 3 | 2 |
76,174,236 | 2023-5-4 | https://stackoverflow.com/questions/76174236/is-there-any-way-to-load-an-index-created-through-vectorstoreindexcreator-in-lan | I am experimenting with langchains and its applications, but as a newbie, I could not understand how the embeddings and indexing really work together here. I know what these two are, but I can't figure out a way to use the index that I created and saved using persist_directory. I succesfully saved the object created by... | By default VectorstoreIndexCreator use the vector database DuckDB which is transient a keeps data in memory. If you want to persist data you have to use Chromadb and you need explicitly persist the data and load it when needed (for example load data when the db exists otherwise persist it). for more details about chrom... | 5 | 3 |
76,187,515 | 2023-5-6 | https://stackoverflow.com/questions/76187515/how-to-parse-the-result-of-requests-get-to-produce-the-needed-data | I am trying to get some data from a url using the code below. I need help to produce the needed output. from bs4 import BeautifulSoup import requests page = requests.get("https://coinmarketcap.com/new/") pagedata = page.text print ("* ", pagedata) My output: (Truncated) <a href="/currencies/cheems-token/" class="cmc... | With pandas, you can use read_html with a bit of post-processing : #pip install pandas import pandas as pd usecols = ["Name", "Symbol", "Price", "1h", "24h", "MarketCap", "Volume", "Blockchain"] df = pd.read_html("https://coinmarketcap.com/new/")[0] df[["Name", "Symbol"]] = df["Name"].str.split(r"\d+", expand=True) df ... | 3 | 2 |
76,187,178 | 2023-5-6 | https://stackoverflow.com/questions/76187178/perform-a-python-split-on-a-pandas-dataframe | I have the following dataframe: import pandas as pd data = {'Test_Step_ID': ['9.1.1', '9.1.2', '9.1.3', '9.1.4'], 'Protocol_Name': ['A', 'B', 'C', 'D'], 'Req_ID': ['SRS_0081d', 'SRS_0079', 'SRS_0082SRS_0082a', 'SRS_0015SRS_0015cSRS_0015d'] } df = pd.DataFrame(data) I want to duplicate the rows based on the column "Req... | split on the zero width location between SRS and a preceding character using the '(?<=.)(?=SRS) regex, and explode: out = (df .assign(Req_ID=df['Req_ID'].str.split(r'(?<=.)(?=SRS)')) .explode('Req_ID') ) Output: Test_Step_ID Protocol_Name Req_ID 0 9.1.1 A SRS_0081d 1 9.1.2 B SRS_0079 2 9.1.3 C SRS_0082 2 9.1.3 C SRS_... | 4 | 3 |
76,167,901 | 2023-5-3 | https://stackoverflow.com/questions/76167901/tkinter-modify-fill-option-when-using-tksvg | Thanks to this question, I discovered tksvg. I already know how to display an svg file: import tkinter as tk import tksvg window = tk.Tk() svg_image = tksvg.SvgImage(file="tests/orb.svg") label = tk.Label(image=svg_image) label.pack() window.mainloop() and also how to do the same using svg data/string: import tkinter ... | In addition to the answer of "acw1668". Creating a new TkImage is costly and you should just update your old image with the new data. Therefore it makes sense to use image.configure(data=data_string), example below: def change_color(event): global svg_string fill_color = "blue" if "red" in svg_string else "red" svg_str... | 3 | 1 |
76,183,612 | 2023-5-5 | https://stackoverflow.com/questions/76183612/delete-string-if-there-is-a-longer-string-that-starts-with-same-pattern | I have a list of values: ['27', '27.1', '27.1.a', '27.1.b', '27.3.d.28', '27.3.d.28.1', '27.3.d.28.2', ] I want to keep only the longest values for each "parent" value. That is, delete 27 if there is a 27.something. Delete 27.1. if there is a 27.1.something, etc. In this case, output should be ['27.1.a', '27.1.b', '2... | Assuming the match is anchored on the left, a strategy might be to sort the strings, thus the strings will cluster by prefix, then only compare the successive pairs: def is_parent(p, target): return p.startswith(target) and len(p)>len(target) and p[len(target)] == '.' out = [] prev = '' for s in sorted(lis)+['']: if pr... | 4 | 3 |
76,180,900 | 2023-5-5 | https://stackoverflow.com/questions/76180900/how-to-make-a-custom-class-be-able-to-be-received-by-range | range() in Python seems to accept integer as parameter only. How to make range() accept a custom class as parameter? I've defined a class such as: class MyInteger: def __init__(self, a:int): self._a = a def __int__(self): return self._a And I tried: n = MyInteger(5) for i in range(n): print(i) It always causes 'objec... | Implement __index__ to allow your class instances to be interpreted as an int class MyInteger: def __init__(self, a:int): self._a = a def __index__(self): return self._a n = MyInteger(5) for i in range(n): print(i) | 4 | 6 |
76,177,406 | 2023-5-4 | https://stackoverflow.com/questions/76177406/compute-m-columns-from-2m-columns-without-a-for-loop | I have a dataframe where some columns are name-paired (for each column ending with _x there is a corresponding column ending with _y) and others are not. For example: import pandas as pd import numpy as np colnames = [ 'foo', 'bar', 'baz', 'a_x', 'b_x', 'c_x', 'a_y', 'b_y', 'c_y', ] rng = np.random.default_rng(0) data ... | You can use groupby_apply with a custom function: func = lambda sr: (sr.iloc[:, 0] - sr.iloc[:, 1]) / sr.iloc[:, 1] # r'' stands for raw strings like f'' for formatted strings # Keep columns that end ($) with '_x' or '_y' (_[xy]) # Groupby column prefix (a_x -> a, b_x -> b, ..., c_y -> c) # Apply your formula on each g... | 3 | 1 |
76,172,523 | 2023-5-4 | https://stackoverflow.com/questions/76172523/error-httpresponse-object-has-no-attribute-strict-when-verifying-id-token-wi | I have a Cloud Function in python 3.9 that calls this code : firebase_admin.initialize_app() def check_token(token, app_check_token): """ :param app_check_token: :param token: :return: """ try: app_token = app_check.verify_token(app_check_token) logging.info(f"App check token verified : {app_token}") except Exception a... | I had a similar issue and someone pointed me to this: https://github.com/psf/requests/issues/6437 and also for firebase specifically: https://github.com/firebase/firebase-admin-python/issues/699 Apparently there's been a breaking change to the library and one solution is to use urllib3 2.0.0 as a workaround which I am ... | 3 | 3 |
76,166,620 | 2023-5-3 | https://stackoverflow.com/questions/76166620/generate-hierarchical-data-from-pandas-df-to-list | I have data in this form data = [ [2019, "July", 8, '1.2.0', 7.0, None, None, None], [2019, "July", 10, '1.2.0', 52.0, "Breaking", 6.0, 'Path Removed w/o Deprecation'], [2019, "July", 15, "0.1.0", 210.0, "Breaking", 57.0, 'Request Parameter Removed'], [2019, 'August', 20, '2.0.0', 100.0, "Breaking", None, None], [2019,... | Assuming that headers are known and sorted in hierarchical with description of header that must be grouped order like so (see datetime doc for its usage): from datetime import datetime hierarchical_description = [ ([("name", "Year")], lambda d: int(d["name"])), ([("name", "Month")], lambda d: datetime.strptime(d["name"... | 4 | 4 |
76,175,067 | 2023-5-4 | https://stackoverflow.com/questions/76175067/find-second-occurence-from-the-right-of-a-character-without-iteration | I have a Python string: test = 'blablabla_foo_bar_baz' I want the negative index of the second occurence from the right of _: in this case, this would be -8, but even 13, the positive index, would be an acceptable answer, because it's not hard to compute the negative index from the positive index. How can I do that? A... | I am unsure the exact solution that is wanted but if the goal is just to split the string there is a much cleaner approach which can also give you the index it was cut at. test = 'blablabla_foo_bar_baz' result, *_ = test.rsplit('_', maxsplit=2) # split from the right two times print(result) # blablabla_foo print(len(re... | 4 | 1 |
76,163,832 | 2023-5-3 | https://stackoverflow.com/questions/76163832/pandas-on-spark-throwing-java-lang-stackoverflowerror | I am using pandas-on-spark in combination with regex to remove some abbreviations from a column in a dataframe. In pandas this all works fine, but I have the task to migrate this code to a production workload on our spark cluster, and therefore decided to use pandas-on-spark. However, I am running into a weird error. I... | Is it possible that your input data is deeply nested? This could contribute to the looping stack calls you can see in there. The first thing I would try is running with a larger stack size than you're doing now. I'm not sure what OS/java version you're running this on, so can't know what the default stack size is on yo... | 4 | 4 |
76,171,532 | 2023-5-4 | https://stackoverflow.com/questions/76171532/spark-cdm-connector-in-databricks-java-lang-noclassdeffounderror-org-apache-sp | we are having compatibility issue with spark-cdm-connector, to give a little context I have a cdm data in ADLS which I’m trying to read into Databricks Databricks Runtime Version 12.1 (includes Apache Spark 3.3.1, Scala 2.12) , I have installed com.microsoft.azure:spark-cdm-connector:0.19.1 I ran this code: AccountNam... | You're using incorrect version of the connector - 0.19.1 was for Spark 3.1, but you use Spark 3.3. You need to try Release spark3.3-1.19.5, but it may not be available on Maven Central. | 3 | 3 |
76,170,810 | 2023-5-4 | https://stackoverflow.com/questions/76170810/tweepy-twitter-api-v2-retrieve-tweets-on-free-access | I'm trying to authenticate to twitter's new API (v2) using tweepy and retrieve tweets but encounter a strange error related to the authentication process. I'm currently using the free access to the API. Code sample : import tweepy # Authentification OAuth 1.0a User Context to retrieve my own data dict_twitter_api = { "... | The returned exception is in fact not related to the authentication process. Twitter's free API access does not allow you to retrieve your own timeline or event tweets at all. This is stated in the about the twitter API documentation's page; it also explains why the page on rate limits only details the 'Basic' access'r... | 10 | 10 |
76,166,230 | 2023-5-3 | https://stackoverflow.com/questions/76166230/how-can-a-python-program-determine-which-core-it-is-running-on | I need to debug a Python 3 program that uses the multiprocessing module. I want to keep track of which cores (of a multi-core machine) are getting used and how. Q: I am looking for a way for the Python code to determine which core is running it. The closest I have found is to use the following: multiprocessing.current... | This is absolutely going to be an OS-specific problem, but here's how to do it in Windows (source). As mentioned in the comments, the processor number will likely be changing all the time unless you specifically pin the task to a given core (outside the scope of this answer). from ctypes import * from ctypes import win... | 4 | 2 |
76,168,695 | 2023-5-4 | https://stackoverflow.com/questions/76168695/a-memory-leak-in-a-simple-python-c-extension | I have some code similar to the one below. That code leaks, and I don't know why. The thing that leaks is a simple creation of a Python class' instance inside a C code. The function I use to check the leak is create_n_times that's defined below and just creates new Python instances and derefrences them in a loop. This ... | PyTuple_SetItem steals the reference to the supplied object, but Py_False is a single object. When the args tuple is destroyed, the reference count for Py_False isgetting mangled. Use PyBool_FromLong(0) to create a new reference to Py_False, like the other two calls to PyTuple_SetItem. (see docs.python.org/3/c-api/bool... | 3 | 5 |
76,168,260 | 2023-5-3 | https://stackoverflow.com/questions/76168260/regex-look-ahead-look-behind-when-the-look-behind-pattern-is-different | First off, my apologies for posting this ugly, long sample, but it's all I could muster. I'm trying to get the IPs for both the source of the malware and the host. My pattern works well with the host, but it breaks when I try to return the source IP because the pattern captured in the look behind portion of the log cha... | Use alternatives to match either dst= or cs5= before deviceProcessName=. (?:(?<=dst=).*?|(?<=cs5=).*?)(?=\s+deviceProcessName=) | 3 | 2 |
76,166,628 | 2023-5-3 | https://stackoverflow.com/questions/76166628/can-i-store-and-then-read-write-to-a-sqlite-database-using-azure-file-storage-fr | I have a Python flask app that I want to see if I can turn it into a product, and it just needs a simple storage like SQLite, but it needs to have read/write capabilities. I want to do this as cheap as possible for now because there's a lot of unknowns on if it would even be successful. Currently, I'm able to push it o... | Regarding the issue of data reset when restarting the App Service, it is because the SQLite database is stored in the temporary storage of the App Service. When you restart the App Service, all data in the temporary storage is deleted. If you go to the section Development Tools of your Azure App Service, you can SSH an... | 3 | 3 |
76,166,558 | 2023-5-3 | https://stackoverflow.com/questions/76166558/creating-a-list-comprehension-that-repeats-certain-values-in-a-list-for-x-times | I have a very specific use-case for creating a list comprehension and I am having a bit of trouble figuring out how to do it. I am sure there must be a method or function that can help me, but I guess I am not aware of it. Here is the scenario: Following code works as expected and generates all expected variations (8 i... | A concise way to do this combines itertools.product to give the combinations, with enumerate to give you a running counter. You can floor-divide that counter by 5 to give your "account number": import itertools List_A = ["apples", "oranges"] List_B = ["meat", "chicken"] flexibility = range(2) rate_limit = 5 res = [(n, ... | 5 | 5 |
76,164,992 | 2023-5-3 | https://stackoverflow.com/questions/76164992/creating-an-array-by-shifting-values | I have an interger d and boolean array, say M = array([[ True, False, False, True], [False, True, False, False], [False, False, False, False], [False, False, False, True]]) Now I want to create a new array from M with the following rule: Trues stay and the next d positions left of a True also become True. I came up wi... | You can use a 2D convolution with scipy.signal.convolve2d: from scipy.signal import convolve2d d = 2 kernel = np.repeat([1, 1, 0], [d, 1, d])[None] # array([[1, 1, 1, 0, 0]]) out = convolve2d(M, kernel, mode='same') > 0 Output for d = 1: array([[ True, False, True, True], [ True, True, False, False], [False, False, Fa... | 3 | 4 |
76,161,409 | 2023-5-3 | https://stackoverflow.com/questions/76161409/adding-security-to-opc-ua-python-server-client-asyncua | I'm new to OPC UA and Python, but with the asyncua examples, I created the example that I need for a real project. Now I need to add security to the server and client, and for now, using a username and password is fine. Here is my functional code without security. If someone knows what functions I need to use to create... | You have to create a class that implements get_user class CustomUserManager: def get_user(self, iserver, username=None, password=None, certificate=None): if username == "admin": if password == 'secret_admin_pw': return User(role=UserRole.Admin) elif username == "user": if password == 'secret_pw': return User(role=UserR... | 3 | 3 |
76,122,326 | 2023-4-27 | https://stackoverflow.com/questions/76122326/how-to-return-separate-json-responses-using-fastapi | I am not sure if this is part of OpenAPI standard. I am trying to develop an API server to replace an existing one, which is not open source and vendor is gone. One particular challenge I am facing is it returns multiple JSON objects without enclosing them either in a list or array. For example, it returns the followin... | Option 1 You could return a custom Response directly, as demonstrated in this answer, as well as in Option 2 of this answer. Example from fastapi import FastAPI, Response import json app = FastAPI() def to_json(d): return json.dumps(d, default=str) @app.get('/') async def main(): data_1 = {'items': 10} data_2 = {'order... | 4 | 3 |
76,129,550 | 2023-4-28 | https://stackoverflow.com/questions/76129550/how-to-make-case-insensitive-choices-using-pythons-enum-and-fastapi | I have this application: import enum from typing import Annotated, Literal import uvicorn from fastapi import FastAPI, Query, Depends from pydantic import BaseModel app = FastAPI() class MyEnum(enum.Enum): ab = "ab" cd = "cd" class MyInput(BaseModel): q: Annotated[MyEnum, Query(...)] @app.get("/") def test(inp: MyInput... | You could make case insensitive enum values by overriding the Enum's _missing_ method . As per the documentation, this classmethod—which by default does nothing—can be used to look up for values not found in cls; thus, allowing one to try and find the enum member by value. Note that one could extend from the str class ... | 11 | 20 |
76,130,370 | 2023-4-28 | https://stackoverflow.com/questions/76130370/why-is-python-slower-inside-a-docker-container | The following small code snippet times how long adding a bunch of numbers takes. import gc from time import process_time_ns gc.disable() # disable garbage collection for func in [ process_time_ns, ]: pre = func() s = 0 for a in range(100000): for b in range(100): s += b print(f"sum: {s}") post = func() delta_s = (post ... | The slowdown seems to be caused not by docker, but by differences in the python binary. I copied the python packaged within the docker image python:3 to my host machine (copying docker's /usr/local to my hosts docker-python folder). Then I ran the same benchmark again on using this binary with the following command: LD... | 5 | 6 |
76,107,909 | 2023-4-26 | https://stackoverflow.com/questions/76107909/when-should-i-use-asyncio-create-task | I am using Python 3.10 and I am a bit confused about asyncio.create_task. In the following example code, the functions are executed in coroutines whether or not I use asyncio.create_task. It seems that there is no difference. How can I determine when to use asyncio.create_task and what are the advantages of using async... | TL;DR It makes sense to use create_task, if you want to schedule the execution of that coroutine immediately, but not necessarily wait for it to finish, instead moving on to something else first. Explanation As has been pointed out in the comments already, asyncio.gather itself wraps the provided awaitables in tasks, w... | 14 | 16 |
76,145,761 | 2023-5-1 | https://stackoverflow.com/questions/76145761/use-poetry-to-create-binary-distributable-with-pyinstaller-on-package | I think I'm missing something simple I have a python poetry application: name = "my-first-api" version = "0.1.0" description = "" readme = "README.md" packages = [{include = "application"}] [tool.poetry.scripts] start = "main:start" [tool.poetry.dependencies] python = ">=3.10,<3.12" pip= "23.0.1" setuptools="65.5.0" fa... | I have found a solution using the pyinstaller API. As you may know already, Poetry will only let you run 'scripts' if they are functions inside your package. Just like in your pyproject.toml, you map the start command to main:start, which is the start() function of your main.py module. Similarly, you can create a funct... | 8 | 15 |
76,119,902 | 2023-4-27 | https://stackoverflow.com/questions/76119902/how-to-create-a-custom-json-mapping-for-nested-dataclasses-with-sqlalchemy-2 | I want to persist a python (data)class (i.e. Person) using imperative mapping in SQLAlchemy. One field of this class refers to another class (City). The second class is only a wrapper around two dicts and I want to store it in a denormalized way as a JSON column. My example classes look like this: @dataclass class Pers... | I found a solution. Whether this is an elegant way to solve this problem or not is for the reader to decide. My initial reasoning was not to pollute the models with I/O implementation details. Another approach would be to introduce a service layer and/or create additional dumb DTOs that can be translated to/from the mo... | 3 | 0 |
76,147,221 | 2023-5-1 | https://stackoverflow.com/questions/76147221/trying-to-fix-a-numpy-asscalar-deprecation-issue | While trying to update an old Python script I ran into the following error: module 'numpy' has no attribute 'asscalar'. Did you mean: 'isscalar'? Specifically: def calibrate(x, y, z): # H = numpy.array([x, y, z, -y**2, -z**2, numpy.ones([len(x), 1])]) H = numpy.array([x, y, z, -y**2, -z**2, numpy.ones([len(x)])]) H = ... | Just replace numpy.scalar using numpy.ndarray.item, that is, change offsets = map(numpy.asscalar, offsets) scale = map(numpy.asscalar, scale) to offsets = map(numpy.ndarray.item, offsets) scale = map(numpy.ndarray.item, scale) | 4 | 2 |
76,138,267 | 2023-4-29 | https://stackoverflow.com/questions/76138267/read-write-data-over-raspberry-pi-pico-usb-cable | How can I read/write data to Raspberry Pi Pico using Python/MicroPython over the USB connection? | Use Thonny to put MicroPython code on Raspberry Pi Pico. Save it as 'main.py'. Unplug Raspberry Pi Pico USB. Plug Raspberry Pi Pico USB back in. (don't hold do the boot button). Run the PC Python code to send and receive data between PC and Raspberry Pi Pico. Code for Raspberry Pi Pico: Read data from sys.stdin. Wri... | 6 | 8 |
76,116,626 | 2023-4-27 | https://stackoverflow.com/questions/76116626/error-jupyter-is-not-recognized-as-an-internal-or-external-command-operable | I am trying to install Jupyter Notebook without installing Anaconda on my Windows. I have followed the steps in https://jupyter.org/install but seems not to work. I have tried to close & reopen the command prompt and restart the Windows but didn't work too. What did I miss? C:\Users\xxxxxx>pip install notebook Requirem... | You should add <your_python_root>\Scripts to the PATH environment variables. (Go to Environmental Variables > system variable > Path > Edit). Then the system knows where to find jupyter command. | 3 | 1 |
76,137,512 | 2023-4-29 | https://stackoverflow.com/questions/76137512/langchain-huggingface-cant-evaluate-model-with-two-different-inputs | I'm evaluating a LLM on Huggingface using Langchain and Python using this code: # https://github.com/hwchase17/langchain/blob/0e763677e4c334af80f2b542cb269f3786d8403f/docs/modules/models/llms/integrations/huggingface_hub.ipynb from langchain import HuggingFaceHub, LLMChain import os hugging_face_write = "MY_KEY" os.env... | You need to upgrade your hugging face account to Pro version to host the large model for inference. "google/flan-t5-base" works for the free account. | 3 | 0 |
76,122,294 | 2023-4-27 | https://stackoverflow.com/questions/76122294/pyinstaller-adding-directory-inside-dist-as-data | I'm facing this issue while building a executable of my pyqt5 application. I've images folder which contain 6 images and I want to add this images directory in dist folder so structure will look like this dist > app > images but I'm not able to do that it copies all images instead of picking folder. I've tried adding l... | Strange! updating app.spec file and running pyinstaller app.spec did not worked for me I don't know why If anyone know please let me know. What I did I deleted dist, build and old app.spec file and ran this command and it worked pyinstaller ui.py -n myapp --add-data "images:images" --add-data "logo.png:." | 3 | 1 |
76,122,630 | 2023-4-27 | https://stackoverflow.com/questions/76122630/how-to-ignore-environment-directory-when-using-python-ruff-linter-in-console | I was trying ruff linter. I have a file structure like below project_folder ├── env # Python enviroment [python -m venv env] │ ├── Include │ ├── Lib │ ├── Scripts │ ├── ... ├── __init__.py └── numbers.py I am trying to use this code I activated the environment inside the project_folder and ran the script below ruff ch... | You can use the exclude option, ruff check --exclude=env . | 9 | 9 |
76,153,606 | 2023-5-2 | https://stackoverflow.com/questions/76153606/dialogflow-doesnt-return-training-phrases | I am trying to get an overview of the training phrases per intent from Dialogflow in python. I have followed this example to generate the following code: from google.cloud import dialogflow_v2 # get_credentials is a custom function that loads the credentials credentials, project_id = get_credentials() client = dialogfl... | After searching in the documentation some more, I found this page. Therefore I added the intent_view parameter to the request as in the snippet below: from google.cloud import dialogflow_v2 # get_credentials is a custom function that loads the credentials _credentials, project_id = self._get_credentials() client = dial... | 2 | 2 |
76,107,450 | 2023-4-26 | https://stackoverflow.com/questions/76107450/flask-attributeerror-module-flask-json-has-no-attribute-jsonencoder | My flask app was working prior to upgrades. I was having trouble with sending email when there was a forgot-reset-password. To try and fix this I recently upgraded some modules for my flask app. The modules that I upgraded with current versions are: email-validator==2.0.0.post2 Flask==2.3.1 itsdangerous==2.1.2 The Tr... | Python has had a builtin JSONEncoder since at least 3.2, making Flask's version redundant. So it's reasonable to remove it. If this was a module you controlled, you could just replace your line JSONEncoder = json.JSONEncoder with from json import JSONEncoder Since you don't control this library though, you should noti... | 20 | 17 |
76,110,267 | 2023-4-26 | https://stackoverflow.com/questions/76110267/firestore-warning-on-filtering-with-positional-arguments-how-to-use-filter-kw | Firestore started showing UserWarning: Detected filter using positional arguments. Prefer using the 'filter' keyword argument instead. when using query.where(field_path, op_string, value) while it's the the method from the official docs https://cloud.google.com/firestore/docs/query-data/queries So how shall we use the... | Based on @Robert G's excellent answer you can get rid of this warning with a semi-small tweak. Instead of: query = collection_ref query = query.where(field, op, value) Do this: from google.cloud.firestore_v1.base_query import FieldFilter query = collection_ref query = query.where(filter=FieldFilter(field, op, value)) ... | 28 | 35 |
76,125,621 | 2023-4-28 | https://stackoverflow.com/questions/76125621/how-to-annotate-slice-type-in-python | I want to use slice[int] like list[int], but my IDE tells me that this usage is invalid. So how to annotate slice type, if I want to constrain the type of its parameters? | Update (2023-05-12) I opened a PR to make slice generic. The change would introduce quite a few mypy errors in many existing projects. The good people at python/typeshed made it clear that until we have type variable defaults (proposed in PEP 696, but not yet accepted) and the slice type utilizes them, they will not ac... | 3 | 3 |
76,149,834 | 2023-5-1 | https://stackoverflow.com/questions/76149834/dicom-slice-thickness-in-python | I'm working on a project that requires slicing a 3D .stl file into a stack of DICOM slices, and I need to get the distance between the slices. I have figured out how to include the real .stl dimensions (in mm) in each DICOM file, using Autodesk Meshmixer; however, I can't seem to get the correct distance/thickness betw... | Considering what @blunova said, using the 'SliceThickness' attribute also worked for what I need, since (for this case) it's the same to consider thick slices with a null spacing between them, than infinitesimal-thickness slices with non-zero spacing between them. This way, the thickness is equal to the slice height, a... | 2 | 1 |
76,152,720 | 2023-5-2 | https://stackoverflow.com/questions/76152720/how-to-replace-certain-values-in-a-polars-series | I want to replace the inf values in a polars series with 0. I am using the polars Python library. This is my example code: import polars as pl example = pl.Series([1,2,float('inf'),4]) This is my desired output: output = pl.Series([1.0,2.0,0.0,4.0]) All similiar questions regarding replacements are regarding polars D... | You can use Series.set: s = s.set(s == float('inf'), 0) although there's a note there: Use of this function is frequently an anti-pattern, as it can block optimisation (predicate pushdown, etc). Consider using pl.when(predicate).then(value).otherwise(self) instead. which suggests using a way longer: s = s.to_frame()... | 4 | 4 |
76,130,589 | 2023-4-28 | https://stackoverflow.com/questions/76130589/what-is-the-function-of-the-text-target-parameter-in-huggingfaces-autotokeni | I'm following the guide here: https://huggingface.co/docs/transformers/v4.28.1/tasks/summarization There is one line in the guide like this: labels = tokenizer(text_target=examples["summary"], max_length=128, truncation=True) I don't understand the function of the text_target parameter. I tried the following code and ... | Sometimes it is necessary to look at the code: if text is None and text_target is None: raise ValueError("You need to specify either `text` or `text_target`.") if text is not None: # The context manager will send the inputs as normal texts and not text_target, but we shouldn't change the # input mode in this case. if n... | 4 | 6 |
76,134,340 | 2023-4-29 | https://stackoverflow.com/questions/76134340/including-additional-data-in-django-drf-serializer-response-that-doesnt-need-to | Our Django project sends GeoFeatureModelSerializer responses and we want to include an additional value in this response for JS to access. We figured out how to do this in serializers.py: from rest_framework_gis import serializers as gis_serializers from rest_framework import serializers as rest_serializers from core.m... | Figured it out. This answer is if you're using views, but for viewsets see list() and include this in your viewset: def list(self, request, *args, **kwargs): queryset = self.filter_queryset(self.get_queryset()) serializer = self.get_serializer(queryset, many=True) # idk what this code does but as we're overriding proba... | 3 | 1 |
76,158,147 | 2023-5-2 | https://stackoverflow.com/questions/76158147/pandas-groupby-valueerror-cannot-subset-columns-with-a-tuple-with-more-than-o | I was updated my Pandas from I think it was 1.5.1 to 2.0.1. Any how I started getting an error on some code that works just fine before. df = df.groupby(df['date'].dt.date)['Lake', 'Canyon'].mean().reset_index() Traceback (most recent call last): File "f:...\My_python_file.py", line 37, in df = df.groupby(df['date'].... | Versions before Pandas < 2.0.0 raises a FutureWarning if you don't use double brackets to select multiple columns FutureWarning: Indexing with multiple keys (implicitly converted to a tuple of keys) will be deprecated, use a list instead From Pandas >= 2.0.0, it raises a ValueError: ValueError: Cannot subset columns... | 8 | 20 |
76,158,045 | 2023-5-2 | https://stackoverflow.com/questions/76158045/split-column-list-into-rows-without-duplicating-data | I have a dataframe where the first column is a list, how can I iterate through the list and add a value to the relevant pre defined column: workflow cost cam gdp ott pdl ['cam', 'gdp', 'ott'] $2,346 ['pdl', 'ott'] $1,200 should convert to: workflow cost cam gdp ott pdl ['cam', 'gdp', 'ott'] $2,346 782 782 782 ['pdl', ... | Another alternative: df1 = ( df.assign(cost= df["cost"].str.replace(r"\$|,", "", regex=True).astype("float") / df["workflow"].str.len() ) .explode("workflow") .pivot(columns="workflow", values="cost") ) df = pd.concat([df[["workflow", "cost"]], df1], axis=1) Result for the sample: workflow cost cam gdp ott pdl 0 [cam... | 7 | 4 |
76,155,063 | 2023-5-2 | https://stackoverflow.com/questions/76155063/thread-joins-timeout-does-not-work-when-thread-is-computing-a-sum | In the following code: import threading def infinite_loop(): while True: pass def huge_sum(): return sum(range(2**100)) thread = threading.Thread(target=huge_sum) thread.start() thread.join(1) print("Done") I expect the script to print "Done" after one second since join() will timeout, but instead the script hangs. If... | Looking at builtin_sum_impl in bltinmodule.c, int and float are optimized to perform the sum without releasing the Global Interpreter Lock (GIL). Python only allows byte code to execute in a single thread at a time. Every so often the byte code executor will release the GIL so that other threads can run. C code can rel... | 2 | 3 |
76,119,400 | 2023-4-27 | https://stackoverflow.com/questions/76119400/pyspark-remove-duplicated-messages-within-a-24h-window-after-an-initial-new-valu | I have a dataframe with a status (integer) and a timestamp. Since I get a lot of "duplicated" status messages, I want to reduce the dataframe by removing any row which repeats a previous status within a 24h window after a "new" status, meaning: The first 24h window starts with the first message of a specific status. T... | That's a nice question, i spent some time trying to fiugre it out. I have something like this: At first i am calculating time diff in hours from prev element for each row within window Then i am aggregating above values together as a new column for each row (first row has null, next [4], third [4,19] etc Then i am usin... | 6 | 1 |
76,152,242 | 2023-5-2 | https://stackoverflow.com/questions/76152242/vs-code-skips-breakpoints-after-import | When debugging my code, my breakpoints are ignored by visual studio code, once I use these lines of code: from brainflow.board_shim import BoardShim, BrainFlowInputParams, BoardIds from brainflow.data_filter import DataFilter, FilterTypes, DetrendOperations, AggOperations No error Message is given. I edited my launch.... | It has something to do with your python version. Using the python 3.10 version you will get the desired effect. Report it on GitHub: https://github.com/microsoft/debugpy/issues/1284 | 3 | 1 |
76,151,211 | 2023-5-2 | https://stackoverflow.com/questions/76151211/unable-to-import-python-dependencies-that-come-with-miniconda-in-a-docker-run | I am trying to run a python script inside a dockerized miniconda environment. The issue I am facing is that when I docker run interactively(-it) and run the script manually inside, it works great. But when I docker run non-interactively, the modules that come with miniconda installation like cryptography, lxml, are not... | I struggled with the same issue. The key is when you perform conda init, it adds some lines in your shell rc, in your case .bashrc. source. Thus the solution is straightforward: source your .bashrc. Although, you have another solution that does not involve to edit your rc file. You can change your SHELL to be in your c... | 3 | 1 |
76,152,193 | 2023-5-2 | https://stackoverflow.com/questions/76152193/find-indices-of-nan-elements-in-nested-lists-and-remove-them | names=[['Pat','Sam', np.nan, 'Tom', ''], ["Angela", np.nan, "James", ".", "Jackie"]] values=[[1, 9, 1, 2, 1], [1, 3, 1, 5, 10]] I have 2 lists: names and values. Each value goes with a name, i.e., Pat corresponds to the value 1 and Sam corresponds to the value 9. I would like to remove the nan from names and the corre... | Simply this? import numpy as np import pandas as pd names=[['Pat','Sam', np.nan, 'Tom', ''], ["Angela", np.nan, "James", ".", "Jackie"]] values=[[1, 9, 1, 2, 1], [1, 3, 1, 5, 10]] new_names = [] new_values = [] for names_, values_ in zip(names, values): n = [] v = [] for name, value in zip(names_, values_): if not pd.i... | 6 | 2 |
76,151,960 | 2023-5-2 | https://stackoverflow.com/questions/76151960/how-do-you-get-regex-to-match-individual-words-only-when-the-line-starts-with-a | I'm trying to have RegEx match all the words in a dialogue that are said by a specific character. Every line is formatted as "[NAME]: [DIALOGUE]", so there's a consistent tag at the start of each line to check with, but I can't work out how to do that. For example, if I was looking Romeo's Dialogue in Romeo and Juliet,... | Simply iterate over the lines and match all words if the line starts with the given character name: import re def get_character_words(character_name, dialogue): result = [] for line in dialogue.splitlines(): if line.startswith(character_name): result += re.findall(fr'\w+', line[len(character_name) + 2:]) return result ... | 2 | 3 |
76,143,042 | 2023-4-30 | https://stackoverflow.com/questions/76143042/is-there-an-interface-to-access-pyproject-toml-from-python | Is there an interface to access the information in pyproject.toml from Python? In particular, I'd like to access the dependencies. It doesn't seem hard to do toml.load("pyproject.toml")['project']['dependencies'] and then parse that list. But that would be rewriting logic that must already be available somewhere. Appa... | In both cases, whether project metadata (such as dependency requirements) is obtained from pyproject.toml's standardized [project] section or via importlib.metadata the values should be the same. At least, as far as I know, the dependency requirements have the same format. Probably I would use the 3rd party packaging l... | 8 | 6 |
76,142,428 | 2023-4-30 | https://stackoverflow.com/questions/76142428/unexpected-uint64-behaviour-0xffffffffffffffff-1-0 | Consider the following brief numpy session showcasing uint64 data type import numpy as np a = np.zeros(1,np.uint64) a # array([0], dtype=uint64) a[0] -= 1 a # array([18446744073709551615], dtype=uint64) # this is 0xffff ffff ffff ffff, as expected a[0] -= 1 a # array([0], dtype=uint64) # what the heck? I'm utterly con... | By default, NumPy converts Python int objects to numpy.int_, a signed integer dtype corresponding to C long. (This decision was made back in the early days when Python int also corresponded to C long.) There is no integer dtype big enough to hold all values of numpy.uint64 dtype and numpy.int_ dtype, so operations betw... | 46 | 41 |
76,144,065 | 2023-4-30 | https://stackoverflow.com/questions/76144065/why-does-python-turtle-graphics-keep-crashing-stop-responding | Whenever I try and run my program, it draws the two turtles and then the window stops responding. What I was expecting is that, until one of the pieces touches the other one based on me dragging it close to the other one, I will be able to drag both of them by themselves. What's happening though is that whenever I run ... | The while loop does two things over and over: add drag handlers, and check distance. The loop doesn't call any turtle methods that cause turtle's rendering/event loop to run (for example, .forward() or .goto()), so the distance checks can't be true to break the loop. We want to get to mainloop() to enable user interact... | 5 | 1 |
76,143,613 | 2023-4-30 | https://stackoverflow.com/questions/76143613/trying-to-add-a-pydantic-model-to-a-set-gives-unhashable-error | I have the following code from pydantic import BaseModel class User(BaseModel): id: int name = "Jane Doe" def add_user(user: User): a = set() a.add(user) return a add_user(User(id=1)) When I run this, I get the following error: TypeError: unhashable type: 'User' Is there a way this issue can be solved? | You just need to implement an hash function for the class. You can easily do that by hashing the User's id or name and return it as the hash... like this: from pydantic import BaseModel class User(BaseModel): id: int name = "Jane Doe" def __hash__(self) -> int: return self.name.__hash__() # or self.id.__hash__() def ad... | 5 | 5 |
76,137,714 | 2023-4-29 | https://stackoverflow.com/questions/76137714/trying-to-fit-a-gaussian-with-scipy | I have a diffractogram, and I need to fit a given peak to a gaussian function, I'm trying to use curve_fit from scipy.optimize for that but I'm getting some errors. First at all, because of my data, I've added a straight line to the equation to fit, so I have When I try to fit this equation via import matplotlib.pyplo... | Yes, you need initial parameters; no, you're not calculating them correctly. The mean of Y is not the mean of your random variable, and the standard deviation of Y is not the standard deviation of your random variable. The better your constraints and guesses are, the faster and more reliably your fit will converge. Tha... | 3 | 4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.