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,423,192 | 2023-6-7 | https://stackoverflow.com/questions/76423192/output-of-typeobject-not-returned-in-assert-message-databricks-python | When applying the Python function type() to a single object, the type of the object is returned. num = 5 type(num) Out[1]: int When embedding this output into a string and printing the result, this seems to behave as expected. num = 5 print(f"type of {num} is {type(num)}") type of 5 is <class 'int'> However, when usi... | The character < in the output is being interpreted as the beginning of an HTML tag. By applying replace("<","<") to the f-string, this can be avoided. The full code then becomes: num = 5 assert isinstance(num,str), f"type of {num} is {type(num)}".replace("<", "<") | 2 | 4 |
76,426,902 | 2023-6-7 | https://stackoverflow.com/questions/76426902/how-to-add-rows-on-a-dataset-based-on-a-date-condition | I'm having problems with a dataset I want to use to display on a PowerBI report but in some registers it has a start time and an end time with a different date, which makes me hard to display on a daily basis. I want to divide the register automatically for each day. I have the following register, for example: Date... | Powerquery method let Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content], #"Added Custom" = Table.AddColumn(Source, "Custom", each List.Transform({Number.IntegerDivide(Number.From([Date_Start]), 1)..Number.IntegerDivide(Number.From([Date_End]), 1)}, each Text.From(Date.From(_)))), #"Expanded Custom" = Table.Exp... | 2 | 1 |
76,421,664 | 2023-6-7 | https://stackoverflow.com/questions/76421664/automatically-merging-multiple-pydantic-models-with-overlapping-fields | It is kind of difficult to accurately phrase my question in one sentence. I have the following models: from pydantic import BaseModel class Detail1(BaseModel): round: bool volume: float class AppleData1(BaseModel): origin: str detail: Detail1 class Detail2(BaseModel): round: bool weight: float class AppleData2(BaseMode... | Simplified solution Implementing a custom recursive version of the create_model function to dynamically construct a "combined" model class should work: from typing import TypeGuard, TypeVar from pydantic import BaseModel, create_model from pydantic.fields import SHAPE_SINGLETON M = TypeVar("M", bound=BaseModel) def is_... | 4 | 4 |
76,426,124 | 2023-6-7 | https://stackoverflow.com/questions/76426124/is-vars-same-as-dict | I read that vars() is a built-in that returns the __dict__ attribute of class, module or object. But when I checked for vars(Person) is Person.__dict__, it returned False(Person is the name of class). class Person: def __init__(self, name, age): self.name = name self.age = age vars(Person) is Person.__dict__ # False | Classes create a new mappingproxy on every __dict__ access. You would see the exact same results from Person.__dict__ is Person.__dict__. | 4 | 4 |
76,380,172 | 2023-6-1 | https://stackoverflow.com/questions/76380172/polars-group-by-value-counts | I need some help with polars: I have a dataframe with a categorical values column ┌───────────────────┬──────────────┬────────┐ │ session_id ┆ elapsed_time ┆ fqid │ │ --- ┆ --- ┆ --- │ │ i64 ┆ i32 ┆ cat │ ╞═══════════════════╪══════════════╪════════╡ │ 20090312431273200 ┆ 0 ┆ intro │ │ 20090312431273200 ┆ 1323 ┆ gramps... | Starting from train=pl.from_repr( """┌───────────────────┬──────────────┬────────┐ │ session_id ┆ elapsed_time ┆ fqid │ │ --- ┆ --- ┆ --- │ │ i64 ┆ i32 ┆ cat │ ╞═══════════════════╪══════════════╪════════╡ │ 20090312431273200 ┆ 0 ┆ intro │ │ 20090312431273200 ┆ 1323 ┆ gramps │ │ 20090312431273200 ┆ 831 ┆ gramps │ │ 200... | 4 | 6 |
76,404,811 | 2023-6-5 | https://stackoverflow.com/questions/76404811/attributeerror-dataframe-object-has-no-attribute-iteritems | I am using pandas to read csv on my machine then I create a pyspark dataframe from pandas dataframe. df = spark.createDataFrame(pandas_df) I updated my pandas from version 1.3.0 to 2.0 Now, I am getting this error: AttributeError: 'DataFrame' object has no attribute 'iteritems' | Found an answer on github: https://github.com/YosefLab/Compass/issues/92 It is an issue going on. iteritems is removed from pandas 2.0 For now I need to downgrade pandas back to version 1.5.3 Edit: Other workarounds may be Use the latest Spark (3.4.1) https://spark.apache.org/downloads.html For pandas >=2.0 You can a... | 10 | 28 |
76,380,381 | 2023-6-1 | https://stackoverflow.com/questions/76380381/create-virtualenv-for-python-2-7-with-python-3-10 | I am trying to create a virtual environment for python 2.7 on Ubuntu 22.04. I always receive an error as follows: RuntimeError: failed to query /usr/bin/python2.7 with code 1 err: ' File "/usr/local/lib/python3.10/dist-packages/virtualenv/discovery/py_info.py", line 152\n os.path.join(base_dir, exe) for exe in (f"pytho... | virtualenv versions >= 20.22.0 dropped support for creating Python environments for Python versions <= 3.6, so you'll need to downgrade virtualenv, e.g.: pip install virtualenv==20.21.1 | 6 | 16 |
76,391,344 | 2023-6-2 | https://stackoverflow.com/questions/76391344/implementing-name-synchronization-and-money-transfers-in-transactions-model-with | I have the following models in my Django application: class Transaction (models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) account_number = models.IntegerField() name = models.CharField(max_length=50) amount = models.DecimalField(max_digits=5, decimal_places=2) created_on = models.DateTimeField() ... | Even though I failed to implement an account name based on a given account number, I'm happy to share the way we can send money from one account to another. The technical way to do so is by creating only two models, Account and Transaction models, and adding what is in the Wallet model to an Account model like this: cl... | 4 | 0 |
76,379,924 | 2023-6-1 | https://stackoverflow.com/questions/76379924/create-dataclass-instance-from-union-type-based-on-string-literal | I'm trying to strongly type our code base. A big part of the code is handling events that come from external devices and forwarding them to different handlers. These events all have a value attribute, but this value can have different types. This value type is mapped per event name. So a temperature event always has an... | UPDATE: Using Pydantic v2 If you are willing to switch to Pydantic instead of dataclasses, you can define a discriminated union via typing.Annotated and use the TypeAdapter as a "universal" constructor that is able to discriminate between distinct Event subtypes based on the provided name string. Here is what I would s... | 3 | 4 |
76,407,803 | 2023-6-5 | https://stackoverflow.com/questions/76407803/define-an-output-schema-for-a-nested-json-in-langchain | Whats the recommended way to define an output schema for a nested json, the method I use doesn't feel ideal. # adding to planner -> from langchain.experimental.plan_and_execute import load_chat_planner refinement_response_schemas = [ ResponseSchema(name="plan", description="""{'1': {'step': '','tools': [],'data_sources... | From what I can see the recommended approach is to use the pydantic output parser as opposed to the structured output parser... python.langchain.com/docs/modules/model_io/output_parsers/… (and dealing with nesting explained here... youtube.com/watch?v=yD_oDTeObJY). e.g. from langchain.output_parsers import PydanticOutp... | 6 | 8 |
76,379,440 | 2023-6-1 | https://stackoverflow.com/questions/76379440/how-to-see-the-embedding-of-the-documents-with-chroma-or-any-other-db-saved-in | I can see everything but the Embedding of the documents when I used Chroma with Langchain and OpenAI embeddings. It always show me None for that Here is the code: for db_collection_name in tqdm(["class1-sub2-chap3", "class2-sub3-chap4"]): documents = [] doc_ids = [] for doc_index in range(3): cl, sub, chap = db_collect... | You just need to specify that you want the embeddings as well when using .get # Get all embeddings db._collection.get(include=['embeddings']) # Get embeddings by document_id db._collection.get(ids=['doc0', ..., 'docN'], include=['embeddings']) | 9 | 20 |
76,406,637 | 2023-6-5 | https://stackoverflow.com/questions/76406637/how-to-add-custom-html-content-to-fastapi-swagger-ui-docs | I need to add a custom button in Swagger UI of my FastAPI application. I found this answer which suggest a good solution to add custom javascript to Swagger UI along with this documentations from FastAPI. But this solution only works for adding custom javascript code. I tried to add some HTML code for adding a new butt... | You could modify FastAPI's get_swagger_ui_html() function, in order to inject some custom JavaScript code, as described by @lunaa here, and create the custom HTML button programmatically through the custom_script.js. However, since the Authorize button element is created after the DOM/Window is loaded—and there doesn't... | 5 | 2 |
76,413,746 | 2023-6-6 | https://stackoverflow.com/questions/76413746/saving-a-model-i-get-module-tensorflow-python-saved-model-registration-has-no | When I try to save my ternsorflow model I get this error message. What is the problem here and how do I fix it? model = tf.keras.models.Sequential() # define the neural network architecture model.add( tf.keras.layers.Dense(50, input_dim=hidden_dim, activation="relu") ) model.add(tf.keras.layers.Dense(n_classes)) k += ... | Check if your tensorflow version is older or up-to-date. This seems to be a newer module https://www.tensorflow.org/api_docs/python/tf/keras/saving/get_registered_name Make sure you have this version of tensorflow installed in your environment pip install tensorflow==2.12.0 I don't know about the dataset so I assumed ... | 4 | 1 |
76,418,777 | 2023-6-6 | https://stackoverflow.com/questions/76418777/kivy-is-there-a-list-of-all-color-names | In Kivy, the widgets' color property allows enter its value as a string of a color name, too, e.g. in .kv file: Label: color: "red" Is there a list of all possible color names? | TL;DR from kivy.utils import colormap # import dict with all CSS 3 Colors # like {'aliceblue':[0.9411764705882353, 0.9725490196078431, 1.0, 1.0]} 'aliceblue' in colormap # True For the plot, see the end of this answer. Dictionary of colors The kivy docs mention that colors referenced by name are retrieved from an obj... | 3 | 2 |
76,394,246 | 2023-6-3 | https://stackoverflow.com/questions/76394246/streaming-openai-results-from-a-lambda-function-using-python | I'm trying to stream results from Open AI using a Lambda function on AWS using the OpenAI Python library. For the invoke mode I have: RESPONSE_STREAM. And, using the example provided for streaming, I can see the streamed results in the Function Logs (abbreviated below): Response null Function Logs START RequestId: 3e01... | You are having trouble because python runtimes do not currently support streaming responses. From 4/7/2023 AWS announcement of streaming responses: Response streaming currently supports the Node.js 14.x and subsequent managed runtimes. As of 6/8/2023 this is still true. | 2 | 1 |
76,404,464 | 2023-6-5 | https://stackoverflow.com/questions/76404464/vector-stores-storage-in-langchain | I am working with LangChain for the first time. Due to data security, I want to be sure about the storage of langchain's vector store storage. I am using HNSWLib vector store, which mentions it is an in-memory store. What does it mean? Does Langchain/vector stores store any data in its servers? https://js.langchain.com... | HNSWLib store data in the server where the project is host. So if you host your server into vercel then your vector store is running in memory in vercel server. You can test this logic if true when you execute await vectorStore.save(directory); which will generate vector files inside your project directory. | 2 | 4 |
76,413,508 | 2023-6-6 | https://stackoverflow.com/questions/76413508/why-keyword-argument-are-not-passed-into-init-subclass | Code: class ExternalMeta(type): def __new__(cls, name, base, dct, **kwargs): dct['district'] = 'Jiading' x = super().__new__(cls, name, base, dct) x.city = 'Shanghai' return x class MyMeta(ExternalMeta): def __new__(cls, name, base, dct, age=0, **kwargs): x = super().__new__(cls, name, base, dct) x.name = 'Jerry' x.age... | Python exposes the mechanisms classes are created in the form of customizable meta-classes - and does not perform any magic beyond that. Which means: there is no "hidden channel" through which the keyword arguments of a class are passed to __init_subclass__ - that is done inside Python's type.__new__ call. When using _... | 3 | 8 |
76,413,729 | 2023-6-6 | https://stackoverflow.com/questions/76413729/define-partial-views-on-a-sqlalchemy-model | We are dealing with a very large legacy SQLAlchemy model (and underlying table schema) aggregating many logically-separate models, that cannot, for practical reasons, be refactored. We would want to be able to design authorizations/permissions on sub-models that restrict read/write to a subset of attributes (and perhap... | After a lot of experimenting, I finally found a solution that, while not extremely satisfying (it relies on a fairly ugly __table__ definition) seems to fit my bill exactly. Sharing for any future searches: from redatabase.database import db from redatabase.models import ValuationRequest from sqlalchemy.orm.relationshi... | 3 | 0 |
76,414,514 | 2023-6-6 | https://stackoverflow.com/questions/76414514/cannot-import-name-default-ciphers-from-urllib3-util-ssl-on-aws-lambda-us | What I want to achieve To scrape an website using AWS Lambda and save the data on S3. The issues I'm having When I execute Lambda, the following error message appears. { "errorMessage": "Unable to import module 'lambda_function': cannot import name 'DEFAULT_CIPHERS' from 'urllib3.util.ssl_' (/opt/python/urllib3/util/s... | Execute the following commands. pip install requests==2.25.0 -t ./python --no-user pip install beautifulsoup4 -t ./python --no-user pip install pytz -t ./python --no-user On PyPI, download the following whl files from the pages of numpy and pandas numpy-1.24.3-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.w... | 69 | 4 |
76,414,998 | 2023-6-6 | https://stackoverflow.com/questions/76414998/what-does-a-solution-like-r5-or-c15415-mean-when-i-use-solve-from-sagemath-py | i implemented a system of complex valued functions and i solved it with sagemath's "solve" method. In my solutions array i find entries like: x1 == r5 or for different cases x1 == c15403. (and so on with diffent numbers) Does the r5 stand for an arbitary rational number and c15403 for arbitary complex number? Maybe som... | Yes, 'c' stands for complex. I think that 'r' stands for real, 'z' stands for integer. I don't know if there is a symbol for rationals. I don't know where it's documented, but I believe this comes from Maxima, which Sage uses as a solver. See the documentation for new_variable at https://maxima.sourceforge.io/docs/manu... | 3 | 2 |
76,417,916 | 2023-6-6 | https://stackoverflow.com/questions/76417916/filtering-return-data-from-beautiful-soup | I'm trying to search for specific data on a page. I'm able to gather all the data from the page with: page = requests.get(url) soup = BeautifulSoup(page.content, 'html.parser') #html.parser') results = soup.find_all('tr', {'class':"parent"}) It provides a number of lines that look like the following: <tr class="parent... | You can select <tr> that contains the symbol in data-row= attribute. Then select the correct cells: # html_doc contains the HTML snippet from the question soup = BeautifulSoup(html_doc, 'html.parser') row = soup.select_one('tr[data-row*="BTCC 250117C5.00"]') bid_price = row.select_one('.bid_price').text ask_price = row... | 3 | 1 |
76,415,360 | 2023-6-6 | https://stackoverflow.com/questions/76415360/opencv-moments-returns-zero-causing-zerodivisionerror-in-calculation-of-objec | I am trying to compute the area and the center coordinates of objects in a binary mask using opencv. However, I noticed that in some cases I get the wrong result. For example, if I get the contours like this: import numpy as np import cv2 binary_mask = np.array([ [0, 0, 1, 1, 0, 0], [0, 0, 1, 1, 0, 0], [0, 0, 0, 0, 0, ... | Looks like a bug in the implementation of moments(). It appears to not consider how contours are defined in OpenCV. The issue isn't with your 2x2 connected component, but with the 6x1 one. That one is returned first. Its contour consists of two points. For the contour of a 1-pixel line, moments() should have still give... | 2 | 3 |
76,416,898 | 2023-6-6 | https://stackoverflow.com/questions/76416898/pandas-doesnt-assign-values-to-dataframe | I wrote a function that creates a table of periods given the comparison of a value from a series as well as a specific minimum duration. Now I recently cleaned up my environment and somehow the same function doesn't assign values anymore as it did before. However, it still creates a dataframe of the right shape, it jus... | In pandas the loc/iloc operations, when they are not setting anything, just return a copy of the data. When you do something along the lines of df.loc[row][col] = value, it may look like the loc operation setting something, but this "assignment" happen in two stages: First, df.loc[row] retrieves a copy of the relevant... | 3 | 2 |
76,415,555 | 2023-6-6 | https://stackoverflow.com/questions/76415555/write-test-for-dagster-asset-job | I am trying to write a simple test for a dagster job and I can't get it through... I am using dagster 1.3.6 So I have defined this job using the function dagster.define_asset_job from dagster import define_asset_job my_job: UnresolvedAssetJobDefinition = define_asset_job( name='name_for_my_job', selection=AssetSelectio... | The object that's produced by define_asset_job does not include object references to the asset definitions selected in the job. This means that, to execute an asset job in-process, you need to somehow pass those asset definition object references. One way to do this is through a Definitions object: from dagster import ... | 2 | 7 |
76,410,949 | 2023-6-6 | https://stackoverflow.com/questions/76410949/how-to-count-failure-occurrences-in-a-column-using-pandas | I need to use python's pandas to tabulate the test result in a csv format. The result could be "passsed" or sometime "failed". After I import python as pd,my code is: df = pd.read_csv('myfile.csv') pass_res =df['Status'].value_counts()['passed'] fail_res =df['Status'].value_counts()['failed'] this code will work if t... | You can also add a CategoricalDType as value_counts returns all observed: # sample df = pd.DataFrame({'Status': ['passed']*5 + ['other']*3}) status = pd.CategoricalDtype(['passed', 'failed'], ordered=True) passed, failed = df['Status'].astype(status).value_counts().sort_index() Output: >>> passed 5 >>> failed 0 >>> df... | 2 | 2 |
76,398,598 | 2023-6-4 | https://stackoverflow.com/questions/76398598/streamlit-why-does-updating-the-session-state-with-form-data-require-submitting | I appear to fundamentally misunderstand how Streamlit's forms and session_state variable work. Form data is not inserted into the session_state upon submit. However, submitting a second time inserts the data. Updating session_state values always requires submitting the form 2 times. I'd like to know if this is expecte... | The critical part to think about is: where are you writing session state values relative to where the widget is? In particular, you are accessing/displaying session state values before the widget. Try this to see what's happening a bit clearer: import streamlit as st st.write(st.session_state) with st.form('my_form'): ... | 4 | 7 |
76,411,055 | 2023-6-6 | https://stackoverflow.com/questions/76411055/typeerror-dataframe-drop-takes-from-1-to-2-positional-arguments-but-3-were-gi | I have a large file that I'm trying to reduce using dataframe.drop Here's my code: probe_df = pd.read_csv(csv_file,header = 9233, nrows = 4608) # Get rid of stuff c_to_drop = 'Unnamed: ' + str(count_tp+1) probe_df = probe_df.set_index("Chamber ID").drop(c_to_drop,1) When I ran this, I got this error message: probe_df ... | According to the pandas documentation, the source for drop would be DataFrame.drop(labels=None, *, axis=0, index=None, columns=None, level=None, inplace=False, errors='raise') The * represents the end of allowed positional arguments. This indicates that the positional arguments would be labels, and for python's error... | 10 | 16 |
76,409,916 | 2023-6-5 | https://stackoverflow.com/questions/76409916/python-xarray-valueerror-unrecognized-chunk-manager-dask-must-be-one-of | I am using xarray for combining multiple netcdf files using xarray.open_mfdataset. But I get the error while running the command, below are the commands and error. nc_all = xarray.open_mfdataset(files,combine = 'nested', concat_dim="time") files = glob.glob("/filepath/*") I get the following error- Traceback (most rec... | The issue was resolved when I downgraded the xarray version to 0.21.1 from 2023.5.0 | 6 | 4 |
76,409,390 | 2023-6-5 | https://stackoverflow.com/questions/76409390/prevent-premature-wrapping-in-2-column-html-report-using-css | I'm building a two-column "report" in HTML and CSS (I'm new to both) and printing it to a PDF via Weasyprint in Python. My problem is that content in the first column is wrapping into the second column prematurely, ultimately resulting in a broken table that should remain in one column: The HTML file calls the CSS fil... | Why not use a div with two divs inside it for each column. Something like this: <article id="satgeom"> <h2 id="satgeom-title">Satellite geometry</h2> <h3>Satellite geometry, depiction, and description</h3> <div style="display: flex;"> <div style="width: 50%; padding-right: 2em;"> <img style="width: 100%;" src="./satell... | 2 | 3 |
76,397,149 | 2023-6-3 | https://stackoverflow.com/questions/76397149/how-can-i-wrap-subplot-columns | I've been struggling with visualizing subplots column wrapping in Seaborn histogram plots (kdeplot, histplot). Tried various things including fig, ax & enumerate(zip(df.columns, ax.flatten()). Here's the dataset for col in df.columns: plt.figure(figsize = (3,3)) sns.histplot(df, x = col, kde = True, bins = 40, hue = '... | seaborn.displot with kind='hist' can be used to create subplots / facets, where col_wrap specifies the number of columns. See How to plot in multiple subplots for specifying nrows and ncols when using axes-level plots. See Figure-level vs. axes-level functions The data for 'Female' and 'Male' should be shown separa... | 2 | 3 |
76,403,216 | 2023-6-5 | https://stackoverflow.com/questions/76403216/how-can-i-generate-a-sine-wave-with-consistent-vibrato | I am trying to create a .wav file which contains a 440Hz sine wave tone, with 10Hz vibrato that varies the pitch between 430Hz and 450Hz. Something must be wrong with my approach, because when I listen to the generated .wav file, it sounds like the "amplitude" of the vibrato (e.g. the highest/lowest pitch reached by th... | A more straight forward approach that will accomplish what you want is to use a phasor (linear ramp that goes from 0 to 1 then shoots back down to 0) to look up the sin of that value. Then, you can control the amount the phasor increments (the frequency of vibrato). Here is the code. I lowered the sampling rate to make... | 2 | 2 |
76,402,412 | 2023-6-4 | https://stackoverflow.com/questions/76402412/how-do-i-calculate-the-total-number-of-likes-for-all-of-a-users-posts-in-django | I'm working on a Django project and I'm trying to calculate the total number of likes for a user based on their posts (i.e if a user has post with 10 likes and another with 5, the total likes must display 15) . I've tried various approaches, but I haven't been able to get it working. Here is my models.py: class User(Ab... | You can determine the total number of likes for an author with: from django.db.models import Count @login_required def show_user(request, user_id): user = get_object_or_404( User.objects.annotate(total_likes=Count('post__likes')), pk=user_id ) posts = Post.objects.filter(author=user) return render( request, 'show_user.... | 2 | 3 |
76,399,078 | 2023-6-4 | https://stackoverflow.com/questions/76399078/creating-a-typeddict-with-enum-keys | I am trying to create a TypedDict for better code completion and am running into an issue. I want to have a fixed set of keys (an Enum) and the values to match a specific list of objects depending on the key. For example: from enum import Enum class OneObject: pass class TwoObject: pass class MyEnum(Enum): ONE: 1 TWO: ... | This is not compatible with the TypedDict specification as laid out in PEP 589. Let me quote: (emphasis mine) A TypedDict type represents dictionary objects with a specific set of string keys, and with specific value types for each valid key. So using arbitrary enum members for defining TypedDict keys is invalid. Whi... | 8 | 3 |
76,398,117 | 2023-6-3 | https://stackoverflow.com/questions/76398117/how-to-override-the-default-200-response-in-fastapi-docs | I have this small fastapi application import uvicorn from fastapi import FastAPI, APIRouter from fastapi import Path from pydantic import BaseModel from starlette import status app = FastAPI() def test(): print("creating the resource") return "Hello world" router = APIRouter() class MessageResponse(BaseModel): detail: ... | The default response can be set with the status_code parameter, and the default response model can also be directly controlled by the return type. This example shows you how to do it with the decorator paradigm which is recommended over manually adding API routes. class MessageResponse(BaseModel): detail: str @router.p... | 2 | 6 |
76,397,098 | 2023-6-3 | https://stackoverflow.com/questions/76397098/how-to-make-a-variable-in-global-scope-in-robot-framework | I have create a small robot framework test suit which will communicate with trace32 Lauterbach. My idea is to run different functions name using a loop. Every loop, it will make a breakpoint in the Trace32 later batch. I have written a simple python script as library in the robot framework. test.robot file import os **... | Just initialize it in the constructor of the Trace32 class, so it will persist as long as Trace32 object exist, we can then also remove start_Debugger() class Trace32: def __init__(self): self.t32api = ctypes.cdll.LoadLibrary('D:/test/api/python/t32api64.dll') def start_Debugger(self): self.t32api.T32_Config(b"NODE=",b... | 3 | 2 |
76,395,953 | 2023-6-3 | https://stackoverflow.com/questions/76395953/regex-to-catch-email-addresses-in-email-header | I'm trying to parse a To email header with a regex. If there are no <> characters then I want the whole string otherwise I want what is inside the <> pair. import re re_destinatario = re.compile(r'^.*?<?(?P<to>.*)>?') addresses = [ 'XKYDF/ABC (Caixa Corporativa)', 'Fulano de Tal | Atlantica Beans <fulano.tal@atlanticab... | You may use this regex: <?(?P<to>[^<>]+)>?$ RegEx Demo RegEx Demo: <?: Match an optional < (?P<to>[^<>]+): Named capture group to to match 1+ of any characters that are not < and > >?: Match an optional > $: End Code Demo Code: import re re_destinatario = re.compile(r'<?(?P<to>[^<>]+)>?$') addresses = [ 'XKYDF/ABC (... | 2 | 4 |
76,371,195 | 2023-5-31 | https://stackoverflow.com/questions/76371195/how-to-make-a-json-post-request-from-java-client-to-python-fastapi-server | I send a post request from a java springboot application like this: String requestBody = gson.toJson(sbert); System.out.println(requestBody); // If I print this, and use this in postman it works! HttpRequest add_request = HttpRequest.newBuilder() .uri(URI.create("http://localhost:4557/sbert_similarity")) .POST(HttpRequ... | The example below deomonstrates how to make a JSON POST request using HttpURLConnection. The issue in your code might or might not be with Apache's HttpClient (you would need to test this on your own), but might be originated from the requestBody you send to the server; hence, I would suggest you manually specify a JSO... | 2 | 2 |
76,392,744 | 2023-6-2 | https://stackoverflow.com/questions/76392744/can-you-use-the-programs-you-pip-install-in-the-command-line | As a Python beginner, I was downloading the OpenAI's Whisper with the following command: pip install -U openai-whisper, and noticed that you can use Whisper in both Python and the Command-line. To my knowledge, pip install installs Python packages, so should only be available within Python, but it seems like you can us... | When you install something with pip, if the package defines an entry point, it creates a command-line wrapper, and adds it to your Python installation's bin. Your PATH environment variable should include the folder Python's bin, so you can run the package from the command-line. https://packaging.python.org/en/latest/sp... | 2 | 5 |
76,389,832 | 2023-6-2 | https://stackoverflow.com/questions/76389832/polars-how-to-add-two-series-that-contain-lists-as-elements | Trying to add, subtract, two Series that contains datatype List[i64]. The operation seems to be not supported. a = pl.Series("a",[[1,2],[2,3]]) b = pl.Series("b",[[4,5],[6,7]]) c = a+b this gives the error: PanicException: `add` operation not supported for dtype `list[i64]` I would expect a element-wise sum, like wou... | you can do the following: c = (a.explode() + b.explode()).reshape((2,-1)).alias('c') shape: (2,) Series: 'a' [list[i64]] [ [5, 7] [8, 10] ] Final thoughts: if your list has a fixed size, then you might consider using the new Polars Array datatype. | 3 | 4 |
76,385,931 | 2023-6-1 | https://stackoverflow.com/questions/76385931/validate-csv-by-checking-if-enumeration-columns-contains-any-invalid-coded-value | We recieve many different csv files from external labs and centers. When recieving such a file, we first need to do some QA checks before further processing. So make sure the data is correct, at least on a technical level. We have some Python scripts to check the number of columns, check date values, min/max range etc.... | You could try ... dfs = { column_name: df[~df[column_name].isin(allowed_values)] .value_counts(subset=column_name) .to_frame().reset_index(names="Invalid") for column_name, allowed_values in allowed_enum.items() } out = pd.concat(dfs, names=("Column_name", None)).droplevel(1) to get Invalid count Column_name sex Y 1 ... | 3 | 2 |
76,389,849 | 2023-6-2 | https://stackoverflow.com/questions/76389849/pandas-drop-duplicates-with-a-tolerance-value-for-duplicates | What I have is two Pandas dataframes of coordinates in xyz-format. One of these contains points that should be masked in the other one, but the values are slightly offset from each other, meaning a direct match with drop_duplicates is not possible. My idea was to round the values to the nearest significant number, but ... | You can numpy broadcasting: # Convert to numpy vals1 = df_test_1.values vals2 = df_test_2.values # Remove from df_test_1 arr1 = np.abs(vals1 - vals2[:, None]) msk1 = ~np.any(np.all(arr1 < [100, 100, 0.1], axis=2), axis=1) # Remove from df_test_2 arr2 = np.abs(vals2 - vals1[:, None]) msk2 = ~np.any(np.all(arr1 < [100, 1... | 2 | 5 |
76,389,663 | 2023-6-2 | https://stackoverflow.com/questions/76389663/algorithm-to-list-all-combinations-from-a-table-where-data-is-present-or-null | I have an Excel file (which can optionally be loaded into a database, and into an array of arrays of course) with values such as: A B C NULL NULL zxy xyz xzy NULL xyz xzy xyy yzy yyx yxy NULL NULL xyx xyz NULL yxx and so on. There are thousands of values. Is there any known algorithm to come up wi... | If you are tempted to use pandas : #pip install pandas import pandas as pd df = pd.read_excel("file.xlsx") out = ( df.replace(".+", "*", regex=True).fillna("NULL") .groupby(list(df), group_keys=False, sort=False) .size().reset_index(name="Number of occurrences") ) Output : print(out) A B C Number of occurrences 0 NULL... | 2 | 2 |
76,389,309 | 2023-6-2 | https://stackoverflow.com/questions/76389309/how-to-capture-words-with-letters-separated-by-a-consistent-symbol-in-python-reg | I am trying to write a Python regex pattern that will allow me to capture words in a given text that have letters separated by the same symbol or space. For example, in the text "This is s u p e r and s.u.p.e.r and s👌u👌p👌e👌r and s!u.p!e.r", my goal is to extract the words "s u p e r", "s.u.p.e.r", and s👌u👌p👌e👌r... | You may consider using pattern = r"(?<!\S)\w(?=(\W))(?:\1\w)+(?!\S)" results = [m.group() for m in re.finditer(pattern, x)] See the Python demo and the regex demo. import re x="This is s u p e r and s.u.p.e.r and s👌u👌p👌e👌r and s!u.p!e.r" pattern = r"(?<!\S)\w(?=(\W))(?:\1\w)+(?!\S)" print([m.group() for m in re.fi... | 3 | 3 |
76,389,395 | 2023-6-2 | https://stackoverflow.com/questions/76389395/attributeerror-module-numpy-has-no-attribute-long | I am trying to find 9 raise to power 19 using numpy. I am using numpy 1.24.3 This is the code I am trying: import numpy as np np.long(9**19) This is the error I am getting: AttributeError: module 'numpy' has no attribute 'long' | Sadly, numpy.long was deprecated in numpy 1.20 and it is removed in numpy 1.24 If you wan the result you have to try numpy.longlong import numpy as np np.longlong(9**19) #output 1350851717672992089 https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations | 8 | 14 |
76,388,105 | 2023-6-2 | https://stackoverflow.com/questions/76388105/efficient-algorithm-to-calculate-the-most-right-non-zero-digit-of-a-numbers-fac | Calculate the most right non-zero digit of n factorial efficiently I want to calculate the right most digit of a given number's factorial and print it. What I've done so far is: import math n = int(input()) fact = math.factorial(n) print(str(fact).rstrip('0')[-1]) but I still get time limits and I look for faster solu... | There is a neat recursive formula you can use: let D(n) be the last non-zero digit in n! If n<10, use a lookup table If the second last digit of n is odd, D(n) = 4 * D(n//5) * D(unit digit of n) If the second last digit of n is even, D(n) = 6 * D(n//5) * D(Unit digit of n) See this math stackexchange post for a proof... | 5 | 5 |
76,385,999 | 2023-6-1 | https://stackoverflow.com/questions/76385999/how-to-export-a-pydantic-model-instance-as-yaml-with-url-type-as-string | I have a Pydantic model with a field of type AnyUrl. When exporting the model to YAML, the AnyUrl is serialized as individual field slots, instead of a single string URL (perhaps due to how the AnyUrl.__repr__ method is implemented). For example: from pydantic import BaseModel, AnyUrl import yaml class MyModel(BaseMode... | Unfortunately, the pyyaml documentation is just horrendous, so seemingly elemental things like customizing (de-)serialization are a pain to figure out properly. But there are essentially two ways you could solve this. Option A: Subclass YAMLObject You had the right right idea of subclassing AnyUrl, but the __repr__ met... | 2 | 3 |
76,383,877 | 2023-6-1 | https://stackoverflow.com/questions/76383877/how-to-find-out-which-package-depends-on-futures-in-requirements-txt | I have defined many pip packages in a requirements.txt, but I have not define the "futures" package: ... future == 0.18.3 six == 1.16.0 joblib == 1.2.0 ... And then download all packages with the following command on Ubuntu 22.04: pip3.9 download -r "/home/requirements.txt" The above command exited with the following... | Create a fresh Python 3.9 venv and install your requirements without dependencies: python3.9 -m pip install --no-deps requirements.txt Then run the pip check CLI: python3.9 -m pip check It will complain that some package(s) have unmet dependencies, and you should find futures somewhere in there. Not to be confused wi... | 3 | 1 |
76,376,575 | 2023-5-31 | https://stackoverflow.com/questions/76376575/python-setuptools-exclude-dependencies-when-installing | Python setuptools allows you to specify optional dependencies, but does it allow you to do something in the inverse? For example, let's say I have a list of dependencies in my_package like below: numpy pandas So if I installed the package with pip install my_package, it would also install these two dependencies. Howe... | It is not currently supported - extras are strictly additive. It has been proposed several times, but the discussions never seem to get anywhere. The latest discussion is here: Proposal - expanding optional dependencies to support opt-out of recommended/default installables. As a workaround, you can use: pip install --... | 4 | 3 |
76,371,334 | 2023-5-31 | https://stackoverflow.com/questions/76371334/zlib-difference-in-size-for-level-0-between-python-3-9-and-3-10 | In this code that uses zlib to encode some data, but with level=0 so it's not actually compressed: import zlib print('zlib.ZLIB_VERSION', zlib.ZLIB_VERSION) total = 0 print('Total 1', total) compress_obj = zlib.compressobj(level=0, memLevel=9, wbits=-zlib.MAX_WBITS) total += len(compress_obj.compress(b'-' * 1000000)) p... | zlib 1.2.12 and 1.2.13 behave identically in this regard. The Python library must be making different deflate() calls with different amounts of data, and possibly introducing a flush in the later version. You can look in the Python source code to find out. You should be able to force identical output if you feed smalle... | 3 | 4 |
76,375,307 | 2023-5-31 | https://stackoverflow.com/questions/76375307/how-to-make-typer-traceback-look-normal | When using typer to parse CLI arguments, I get very verbose and colorful error messages. How can I get a normal Python traceback? See screenshot for an example traceback (just the first few lines) for illustration of the verbose style: ❯ python scripts/add_priors.py ╭─────────────────────────────── Traceback (most rece... | You can disable it on a one-off basis by setting the environment variable _TYPER_STANDARD_TRACEBACK=1. Disabling rich exceptions is possible by passing the kwarg pretty_exceptions_enable=False when initializing typer: import typer app = typer.Typer(pretty_exceptions_enable=False) @app.command() def main(): raise Except... | 13 | 10 |
76,369,970 | 2023-5-31 | https://stackoverflow.com/questions/76369970/how-can-i-resolve-circular-references-between-two-instances-of-a-class-in-python | I have two instances of a class that compete in a simulation where they try to shoot at each other. The class contains a position variable and a target variable. The second instance's target variable references the first instance's position object, and vice-versa. I have a chicken-and-egg problem when creating the two ... | I think there are two parts to your question: How to I get my references to another object's position to stay synced up, and how do you initialize objects that reference each other in a cycle. For the first part, I'd suggest a slightly simpler approach that the other answers: Don't reference the target position directl... | 3 | 2 |
76,330,421 | 2023-5-25 | https://stackoverflow.com/questions/76330421/specifying-a-different-input-type-for-a-pydantic-model-field-comma-separated-st | Using Pydantic, how can I specify an attribute that has an input type different from its actual type? For example I have a systems field that contains a list of systems (so a list of strings) and the user can provide this systems list as a comma separated string (e.g. "system1,system2"); then I use a validator to split... | Always annotate model fields with the types you actually want in your schema! If you want the field systems to be a list of strings, then annotate it accordingly. A comma-separated string is the exception after all. To allow it, use a mode='before' validator to intercept that string before the default field validators ... | 4 | 5 |
76,322,463 | 2023-5-24 | https://stackoverflow.com/questions/76322463/how-to-initialize-a-global-object-or-variable-and-reuse-it-in-every-fastapi-endp | I am having a class to send notifications. When being initialized, it involves making a connection to a notification server, which is time-consuming. I use a background task in FastAPI to send notifications, as I don't want to delay the response due to notification. Below is the sample code. file1.py: noticlient = Noti... | Option 1 You could store the custom class object to the app instance, which allows you to store arbitrary extra state using the generic the app.state attribute, as demonstrated here, as well as here and here. To access the app.state attribute, and subsequently the object, outside the main file (for instance, from a rou... | 20 | 36 |
76,338,261 | 2023-5-26 | https://stackoverflow.com/questions/76338261/polars-and-the-lazy-api-how-to-drop-columns-that-contain-only-null-values | I am working with Polars and need to drop columns that contain only null values during my data preprocessing. However, I am having trouble using the Lazy API to accomplish this. For instance, given the table below, how can I drop column "a" using Polars' Lazy API? df = pl.DataFrame( { "a": [None, None, None, None], "b"... | You can't, at least not in the way you want. polars doesn't know enough about the lazyframe to tell which columns are only nulls until you collect. That means you need a collect in order to get the columns you want and then another one to materialize the columns you wanted. Let's turn your df=df.lazy() Step 1: (df.sele... | 4 | 5 |
76,351,947 | 2023-5-28 | https://stackoverflow.com/questions/76351947/polars-convert-string-of-digits-to-list | So i have a polars column/series that is strings of digits. s = pl.Series("a", ["111","123","101"]) s shape: (3,) Series: 'a' [str] [ "111" "123" "101" ] I would like to convert each string into a list of integers. I have found a working solution but i am not sure if it is optimal. s.str.split("").list.eval(pl.element... | Update: .str.split("") no longers inserts leading/trailing empty strings in the result. https://github.com/pola-rs/polars/pull/15922 So you can just .cast() the resulting list directly. s.str.split("").cast(pl.List(pl.Int64)) shape: (3,) Series: 'a' [list[i64]] [ [1, 1, 1] [1, 2, 3] [1, 0, 1] ] | 3 | 5 |
76,322,342 | 2023-5-24 | https://stackoverflow.com/questions/76322342/fastapi-sqlalchemy-cannot-convert-dictionary-update-sequence-element-0-to-a-seq | I'm trying to return list of operations and getting error @router.get("/") async def get_specific_operations(operation_type: str, session: AsyncSession = Depends(get_async_session)): query = select(operation).where(operation.c.type == operation_type) result = await session.execute(query) return result.all() Error: Val... | For some simple cases, if you want to return a list of Pydantic models, just use response_model: response_model receives the same type you would declare for a Pydantic model field, so, it can be a Pydantic model, but it can also be, e.g. a list of Pydantic models, like List[Item]. Just like @sergei klinov mentioned. ... | 4 | 3 |
76,340,960 | 2023-5-26 | https://stackoverflow.com/questions/76340960/cuda-to-docker-container | I need to make docker of my server, but it works only with cuda, how can i add it in my Dockerfile? FROM python:3.10 ENV FLASK_RUN_PORT=5000 RUN sudo nvidia-ctk runtime configure # Here COPY . /app WORKDIR /app RUN pip install --no-cache-dir -r requirements.txt EXPOSE 5000 CMD ["python", "server.py"] I try to do it be... | You can start with a CUDA Docker image and then install Python, for example: FROM nvidia/cuda:12.1.1-runtime-ubuntu20.04 # Install Python RUN apt-get update && \ apt-get install -y python3-pip python3-dev && \ rm -rf /var/lib/apt/lists/* Note: User @chronoclast has suggested additionally installing python-is-python3 t... | 6 | 11 |
76,324,677 | 2023-5-24 | https://stackoverflow.com/questions/76324677/django-4-1-9-requires-system-checks-issue-with-manage-py-is-this-a-bug-or-not | Django 4.1.9 requires_system_checks issue with manage.py - is this a bug or not we are upgrading our wagtail 4.2.2 app to from django 3.1.9 to django 4.1.9 getting the error TypeError: requires_system_checks must be a list or tuple. when running python manage.py runserver_plus 0.0.0.0:8020 --keep-meta-shutdown Is this... | In 4.1, support for setting a boolean to requires_system_checks on a management command was dropped (release notes). You'll need to check your django "app" dependencies to see which define management commands, and which could be affected. Here's some examples, but the list is not exhaustive: graphene-django fixed in 3... | 2 | 1 |
76,363,168 | 2023-5-30 | https://stackoverflow.com/questions/76363168/openai-api-how-do-i-handle-errors-in-python | I tried using the below code, but the OpenAI API doesn't have the AuthenticationError method in the library. How can I effectively handle such error. import openai # Set up your OpenAI credentials openai.api_key = 'YOUR_API_KEY' try: # Perform OpenAI API request response = openai.some_function() # Replace with the appr... | Error handling with the OpenAI Python SDK v1.0.0 or newer • If you don't want to handle error types individually: import os from openai import OpenAI, OpenAIError client = OpenAI() OpenAI.api_key = os.getenv('OPENAI_API_KEY') try: # Make your OpenAI API request here response = client.completions.create( model="gpt-3.5-... | 5 | 11 |
76,367,218 | 2023-5-30 | https://stackoverflow.com/questions/76367218/how-do-i-make-a-time-delta-column-in-polars-from-two-datetime-columns | How would I make a column with the delta (in days) of two date columns. I thought I could just subtract the date objects, but I'm obviously missing something (pl.from_records([{'start': '2021-01-01', 'end': '2022-01-01'}]) .with_columns(pl.col(['start', 'end']).str.to_date('%Y-%m-%d')) .with_columns(delta = pl.col('end... | You can try using the Expr.sub() function instead of the - operator: (pl.from_records([{'start': '2021-01-01', 'end': '2022-01-01'}]) .with_columns(pl.col(['start', 'end']).str.to_date('%Y-%m-%d')) .with_columns(delta = pl.col('end').sub(pl.col('start')))) | 4 | 2 |
76,358,689 | 2023-5-29 | https://stackoverflow.com/questions/76358689/uncrop-3d-plots-in-jupyter-notebook | I'm doing some 3d scatter plots with jupyter notebooks in VSCode, and they aren't showing properly. I went to the documentation in matlab and downloaded the jupyter notebook for the 3d scatter plot and tried running that in vscode, getting the same results, the z label gets cut off. I've seen a lot of questions about ... | So, after a pair of issues in github, I've finally found an answer. I'll leave here the answer in github for reference It appears the problem is caused by the default inline backend saving the figure with bbox_inches= 'tight' which causes the code to crop the image. this can be solved using the inline magic %config Inl... | 3 | 3 |
76,365,636 | 2023-5-30 | https://stackoverflow.com/questions/76365636/warning-news-is-an-entry-point-defined-in-pyproject-toml-but-its-not-instal | I am trying to run my poetry based python project inside docker using docker compose When I run the application, it works but it gives me this warning ch_news_dev_python | Warning: 'news' is an entry point defined in pyproject.toml, but it's not installed as a script. You may get improper `sys.argv[0]`. ch_news_dev_p... | the error is related to the fact that the entry point is declared in poetry in your file pyproject.toml : [tool.poetry.scripts] news = "news.__main__:app" after declaring the entry point, you must execute the command poetry install in your terminal | 13 | 2 |
76,365,797 | 2023-5-30 | https://stackoverflow.com/questions/76365797/how-do-i-get-airflow-to-work-with-sqlalchemy-2-0-2-when-it-has-a-1-4-48-version | I have some problems in my project: I use SQLalchemy 2.0.2 in modules for working with the database however i try to use Apache Airflow 2.6.1 which has sqlalchemy 1.4.48 dependencies. After I run the code, the interpreter either does not work correctly with the database functions (if sqlalchemy 1.4.48 is installed), or... | Have you tried using the PythonVirtualEnvOperator ? It will allow you to install the library at runtime so you don't need to make changes on the server just for one job. To run a function called my_callable, simply use the following: my_task = PythonVirtualenvOperator( task_id="my_task ", requirements="sqlalchemy==2.0"... | 3 | 3 |
76,344,856 | 2023-5-27 | https://stackoverflow.com/questions/76344856/retaining-changes-for-streamlit-data-editor-when-hiding-or-switching-between-wid | I created this simple python example below. I used streamlit together with pandas. This example has an editable dataframe in each selectbox "A" and "B". When I hit the selectbox "A", and edit the table: for example, add a new row as "a4" and "4" as value, then hit the selectbox "B" and come back to selectbox "A", the d... | Comments in the code below. Something to keep in mind The data editor is a little different than other widgets; you can't "store" its state directly. However, widgets lose their information when they disappear from the screen. This creates a problem. For other widgets, you can save their value in session state (assigne... | 5 | 6 |
76,368,961 | 2023-5-30 | https://stackoverflow.com/questions/76368961/how-do-you-detect-when-an-asyncio-tcp-connection-is-gone | I apologize if this is a repeat question: I have looked and haven't found any that would satisfy my question. I have a python script that allows my computer to connect to a piece of hardware using a static IP address and port. This piece of hardware only allows one connection at a time on this port. My first issue is t... | My first issue is that asyncio.open_connection() returns a successful connection status even if there is already another "user" connected to the device. Establishing a connection is done inside the OS kernel and the kernel can do this for many connections in parallel, even if the user space application handles only o... | 2 | 3 |
76,368,086 | 2023-5-30 | https://stackoverflow.com/questions/76368086/search-for-imports-which-could-be-type-checking | I make heavy use of mypy static type checking. I have a large lib where I know I have many imports which are being done just for typehints that could be protected with an if TYPE_CHECKING to speed things up. But searching for them all is proving difficult. Is there a way to identify these "unused" imports automatically... | You can use the flake8-type-checking library for this. Installed using pip install flake8-type-checking | 3 | 3 |
76,362,805 | 2023-5-30 | https://stackoverflow.com/questions/76362805/why-is-np-zeros-faster-than-re-initializing-an-existing-array-in-numba-with-py | Why isnumpy.zeros() faster than re-initializing an existing array? I work with computer modeling and use numba for my work. Sometimes it is necessary to have a zeroed array to accumulate the results of some operation. In general, I suppose that zeroing an already allocated array cannot be slower than creating a new arr... | TL;DR: the observed behaviour is due to a combination of several low-level effects related to CPU caches and virtual memory. For large arrays, np.zeros does not actually fill anything in physical memory on mainstream platforms. In this case, the calloc system call is used internally to reserve a zeroized memory space ... | 5 | 5 |
76,368,145 | 2023-5-30 | https://stackoverflow.com/questions/76368145/filling-in-for-missing-values-by-name-pandas | I have a dataset that I need to fill in the blanks of the ID. ID Name Adam 101 Adam Adam 101 Adam 102 Ben 102 Ben Cathy Cathy 103 Cathy What I need: ID Name 101 Adam 101 Adam 101 Adam 101 Adam 102 Ben 102 Ben 103 Cathy 103 Cathy 103 Cathy I tried using df['Name'].ffill() but does not work when trying on multiple name... | Try with first df['ID'] = df.groupby('Name')['ID'].transform('first') | 3 | 3 |
76,366,233 | 2023-5-30 | https://stackoverflow.com/questions/76366233/context-based-regex-search | I need RegEx to find string based on it's first letters Hello. I have string ABDADBADBADBABDABDA I want program to find string with mask А*А*А*A..... where "*" is group of any symbols except "A", but every "*" is the same group I've tried /((A[^A]+)+A)/g but it matches the whole line Example Input: AxxAxxAbxAx Outp... | Yon need to use backreferences for this. For supplied example A(.*?)A(?:\1A)* should do the trick. Here: A matches A, (.*?) matches everything till the next A and puts it into group #1, (?:\1A)* matches content of group #1 followed by A any number of times. Demo here. | 2 | 2 |
76,365,558 | 2023-5-30 | https://stackoverflow.com/questions/76365558/match-at-whitespace-with-at-most-one-newline-in-regex | I would like to match a b if between a and b is only whitespace with at most one newline. Python example: import re r = "a\s*b" # ? # should match: print(re.match(r, "ab")) print(re.match(r, "a b")) print(re.match(r, "a \n b")) # shouldn't match: print(re.match(r, "a\n\nb")) print(re.match(r, "a \n\n b")) | You need to exclude a newline from \s and then optional match a newline with any zero or more whitespace chars other than a newline: a[^\S\n]*(?:\n[^\S\n]*)?b See the regex demo. Details: a - an a letter [^\S\n]* - zero or more whitespace chars other than newline (?:\n[^\S\n]*)? - one or zero occurrences of \n - a n... | 4 | 2 |
76,364,144 | 2023-5-30 | https://stackoverflow.com/questions/76364144/typeerror-histogram-got-an-unexpected-keyword-argument-normed | I am using numpy.histogram and I am getting this error: import numpy as np np.histogram(np.arange(4), bins=np.arange(5), normed=True) TypeError: histogram() got an unexpected keyword argument 'normed' I was expecting: (array([0.2,0.25,0.25]),array([0,1,2,3,4])) I am using numpy 1.24.3 | The normed parameter in the numpy.histogram function was deprecated in NumPy version 1.21.0 and removed in version 1.24.0. Example import numpy as np result = np.histogram(a=np.arange(4), bins=np.arange(5), density=True) print(result) # (array([0.25, 0.25, 0.25, 0.25]), array([0, 1, 2, 3, 4])) | 2 | 3 |
76,363,921 | 2023-5-30 | https://stackoverflow.com/questions/76363921/how-to-fix-pandas-v2-valueerror-cannot-convert-from-timedelta64ns-to-timedel | When upgrading from pandas version 1 to 2.0.0, I suddenly get a ValueError in a script that worked fine before upgrading pandas to version 2: ValueError: Cannot convert from timedelta64[ns] to timedelta64[D]. Supported resolutions are 's', 'ms', 'us', 'ns' This is a minimally reproducible example: import pandas as pd ... | Use the .dt.days accessor instead of astype('timedelta64[D]): df['recency'] = df['recency'].dt.days The change in behaviour from v1 to v2 is documented here in the Pandas changelog. | 3 | 6 |
76,326,219 | 2023-5-24 | https://stackoverflow.com/questions/76326219/how-to-make-changes-in-a-built-in-library-file-in-chaquopy | I am facing a problem where I have to change a line in a built-in file in a particular library (installed using pip). I have located the file in app\build\pip\debug\common\<library folder> But every time I run the Gradle (for installing or creating APK), the entire folder is recreated, and hence, the file is again th... | As mentioned in the comment by David K Hess, monkey patching may be the easiest solution. If monkey patching isn't suitable for your issue, then assuming the library is pure-Python, you can download it from PyPI, edit your local copy, and then install from that: For example, you could download a .whl file, edit the fi... | 3 | 2 |
76,357,846 | 2023-5-29 | https://stackoverflow.com/questions/76357846/numbers-of-combinations-modulo-m-efficiently | First of all I'm solving a programming problem rather than a math problem now. The question is Anish got an unbiased coin and he tossed it n times and he asked Gourabh to count all the number of possible outcomes with j heads, for all j from 0 to n. Since the number of possible outcome can be huge, he will tell the va... | Using the usual multiplicative formula to compute the next number from the previous, but with keeping the numbers small. Let's first look at a naive version for clarity. Naive def naive(n, m): c = 1 yield c for k in range(n): c = c * (n-k) // (k+1) yield c % m n, m = map(int, input().split()) print(*naive(n, m)) Takes... | 12 | 10 |
76,358,367 | 2023-5-29 | https://stackoverflow.com/questions/76358367/figure-out-return-of-a-method-that-returns-empty-hash-on-some-condition | I'm trying to understand how to make this work: def someMethod() -> dict[any, any]: if not os.path.exists('some path'): return {} config = {'a': 1, 'b': 2} return config I don't think that's correct. Seeing this error - Declared return type, "dict[Unknown, Unknown]", is partially unknownPylance The idea is to return e... | Lowercase any is a Python built-in function and not a type. Instead, you have to import capital Any from the typing module. from typing import Any import os def someMethod() -> dict[Any, Any]: if not os.path.exists('some path'): return {} config = {'a': 1, 'b': 2} return config | 2 | 5 |
76,352,280 | 2023-5-28 | https://stackoverflow.com/questions/76352280/can-a-python-function-be-both-a-generator-and-a-non-generator | I have a function which I want to yield bytes from (generator behaviour) and also write to a file (non-generator behaviour) depending on whether the save boolean is set. Is that possible? def encode_file(source, save=False, destination=None): # encode the contents of an input file 3 bytes at a time print('hello') with ... | A function can’t be a generator and also not be one, but of course you can decide whether to return a generator object or not by defining a helper function. To avoid duplicating the (read) with between the two (and reduce redundancy in general), make one branch a client of the other: def encode_file(source, save=False,... | 2 | 3 |
76,341,290 | 2023-5-26 | https://stackoverflow.com/questions/76341290/unable-to-import-requests-in-web2py-even-though-requests-is-accessible-directl | I'm attempting to integrate MSAL, which requires the requests module. I'm running Python 3.7 on Linux and using pipenv to manage the environment. I'm also using web2py 2.24.1 from source (as in I download the web2py framework via the source button on the web2py website). When I am in the pipenv shell and go into the py... | This is due to a buggy interaction between web2py's custom importer and the urllib3 module (which is imported by requests). web2py's custom importer raises an ImportError if a module is not found (code). (Arguably, it should instead raise ModuleNotFoundError, which is the subclass of ImportError specifically for this ... | 2 | 4 |
76,348,393 | 2023-5-27 | https://stackoverflow.com/questions/76348393/count-number-of-zeros-after-last-non-zero-value-per-row | I have the following df: index jan feb marc april One 1 7 0 0 two 0 8 7 0 three 0 0 0 1 I'd like to get the number of zeros after the last non-zero value per row. So the output should look like index num One 2 two 1 three 0 | Similar logic to that of @BrJ but more straightforward in my opinion. Using a reversed cummin to set to False all True preceding a False, then sum: out = (df.loc[:,::-1].eq(0) .cummin(axis=1).sum(axis=1) .to_frame('num') ) Output: num One 2 two 1 three 0 Intermediates: # boolean mask (0s are True) jan feb marc april... | 4 | 3 |
76,328,152 | 2023-5-25 | https://stackoverflow.com/questions/76328152/ebpf-kprobe-argument-not-matching-the-syscall | I'm learning eBPF and I'm playing with it in order to understand it better while following the docs but there's something I don't understand why it's not working... I have this very simple code that stops the code and returns 5. int main() { exit(5); return 0; } The exit function from the code above calls the exit_gro... | Fix You need to rename your function from my_exit to syscall__exit_group. Why does this matter? BPF programs named in this way get special handling from BCC. Here's what the documentation says: 8. system call tracepoints Syntax: syscall__SYSCALLNAME syscall__ is a special prefix that creates a kprobe for the system ca... | 3 | 1 |
76,346,099 | 2023-5-27 | https://stackoverflow.com/questions/76346099/type-annotations-typevar-bound-problem | In the Python Documentation, we find: T = TypeVar('T') # Can be anything S = TypeVar('S', bound=str) # Can be any subtype of str A = TypeVar('A', str, bytes) # Must be exactly str or bytes We find also this code: def repeat(x: T, n: int) -> Sequence[T]: """Return a list containing n references to x.""" return [x]*n de... | "exactly" is misleading here. In general, the type system assumes Liskov substitutability. So a subtype S of a type T is always acceptable in the place of T. The "exactly" is referring to a specific behavior. When you use a constrained instead of bound type variable*, the result is always either str or bytes, so even i... | 2 | 5 |
76,342,355 | 2023-5-26 | https://stackoverflow.com/questions/76342355/python-classes-difference-between-setting-an-attribute-and-using-setattr | I'm trying to set attributes to a class of which I don't know the name a-priori. I also want to avoid users to write to that attribute, so I use a property factory with getters and setters which returns a property object. However, when calling the property object, I get the reference to that object, instead of whatever... | Why do you want to do this? I've always gone back to this answer whenever I have an idea that uses the notion of dynamically-named attributes -- which is essentially what you're trying to do here if I'm not mistaken (with added read-only "protection" applied only to the keys in list1). Do you need to use a property fac... | 3 | 1 |
76,343,110 | 2023-5-26 | https://stackoverflow.com/questions/76343110/select-cell-from-pandas-dataframe-and-convert-to-int | When selecting cell from Dataframe, it returns me Series value and append it to list as series. How to convert cell into single int value? df = pd.DataFrame({"name": ['John', 'George', 'Ray'], "score": [123, 321, 112]}) x = df.loc[df['name']=='John', 'score'].reset_index(drop=True) x.astype(int) x list=[] list.append(x... | This happens because in general df["name"] == "John" could be true for several rows. A simple way to to work around this is to temporarily turn the "name" column into the DataFrame's index with set_index: import pandas as pd df = pd.DataFrame({"name": ['John', 'George', 'Ray'], "score": [123, 321, 112]}) x = df.set_ind... | 2 | 2 |
76,343,201 | 2023-5-26 | https://stackoverflow.com/questions/76343201/create-a-set-from-a-list-using-set-vs-unpacking-into-curly-brackets | In Python, a set can be created from a list using either the set constructor or by unpacking the list into curly brackets. For example: my_list = [1, 2, 3] my_set = set(my_list) or my_list = [1, 2, 3] my_set = {*my_list} Are there any specific reasons or use cases where one approach is preferred over the other? What ... | There is a subtle difference. set(my_list) produces whatever the callable bound to set returns. set is a built-in name for the set type, but it's possible to shadow the name with a global or local variable. {*my_list}, on the other hand, always creates a new set instance. It's not possible to change what the brace synt... | 2 | 4 |
76,340,851 | 2023-5-26 | https://stackoverflow.com/questions/76340851/xgboost-raising-valueerror-with-sklearn-metric | Im trying to use an XGBClassifier with a validation set and a metric taken from sklearn.metrics as eval_metric, as suggested by the XGBoost documentation. The MWE looks like this: import numpy as np from xgboost import XGBClassifier from sklearn.metrics import accuracy_score x_train, y_train = np.random.rand(10,3), np.... | The reason is that xgboost will feed probability outputs to the evaluation function (your accuracy here), but sklearn's accuracy score is expecting hard decisions (1s or 0s) not probabilities. It is unaware of your decision threshold, so it cannot map them to hard decisions. You can use model = xgb.XGBClassifier( n_est... | 3 | 3 |
76,337,589 | 2023-5-26 | https://stackoverflow.com/questions/76337589/repeat-rows-in-dataframe-with-respect-to-column | I have a Pandas DataFrame that looks like this: df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6], 'col3': [7, 8, 9]}) df col1 col2 col3 0 1 4 7 1 2 5 8 2 3 6 9 I would like to create a Pandas DataFrame like this: df_new col1 col2 col3 0 1 4 7 1 1 5 8 2 1 6 9 3 2 4 7 4 2 5 8 5 2 6 9 6 3 4 7 7 3 5 8 8 3 6 9 Is t... | I would also have gone for a cross merge as suggested by @Henry in comments: out = df[['col1']].merge(df[['col2', 'col3']], how='cross').reset_index(drop=True) Output: col1 col2 col3 0 1 4 7 1 1 5 8 2 1 6 9 3 2 4 7 4 2 5 8 5 2 6 9 6 3 4 7 7 3 5 8 8 3 6 9 Comparison of the different approaches: Note that @sammywemmy... | 9 | 7 |
76,331,894 | 2023-5-25 | https://stackoverflow.com/questions/76331894/custom-fastapi-middleware-causes-localprotocolerrortoo-much-data-for-declared | I have a middleware implemented for FastAPI. For responses that includes some content, it works perfectly. But if a response has no body, it is causing LocalProtocolError("Too much data for declared Content-Length") exception. To isolate the problem, I've reduced the middleware class to this: from starlette.middleware.... | I've solved it. I've just changed the order of which middlewares are added. When I moved my middleware after the GZIP middleware, problem disappeared. Thanks to MatsLindh for pointing out that it is a gzip header. | 4 | 1 |
76,334,787 | 2023-5-25 | https://stackoverflow.com/questions/76334787/python-given-dict-of-old-index-new-index-move-multiple-elements-in-a-list | In Python 3 what would be the best way to move multiple potentially non-contiguous elements to new potentially non-contiguous indexes given a dict of {old index: new index, old index: new index, old index: new index} Important Note: the dict may not contain all the new positions of elements, this is why the examples be... | A linear time one. I start with a result list full of dummy objects. Then move elements from the input sequence into the result list as requested. Then replace the remaining dummies in the result with the remaining non-dummy elements from the input sequence. from typing import Any def move_elements( seq: list[Any], new... | 3 | 1 |
76,331,049 | 2023-5-25 | https://stackoverflow.com/questions/76331049/ruamel-yaml-anchors-with-roundtriploader-roundtripdumper | I am trying to load below example yaml file using the ruamel.yaml python package. - database: dev_db <<: &defaults adapter: postgres host: localhost username: postgres password: password - database: test_db <<: *defaults - database: prod_db <<: *defaults from pydantic import BaseModel from ruamel.yaml import YAML yaml... | Although you should be able to specify a mapping as value for a merge key (instead of an alias to some previously anchored mapping, or a list of such aliases), this doesn't work properly in ruamel.yaml's round-trip mode for ruamel.yaml<0.17.27: import sys import ruamel.yaml yaml_str = """\ a: 42 <<: {b: 96} """ yaml = ... | 3 | 1 |
76,330,754 | 2023-5-25 | https://stackoverflow.com/questions/76330754/how-to-define-a-pydantic-model-nested-under-a-class | I have two Pydantic models: from typing import List, Union from pydantic import BaseModel class Students: class Student(BaseModel): StudentName: str StudentAge: int class StudentRequest(BaseModel): Class: int UUID: str Students: Union[List[Student], None] For the above class at Students: Union[List[Student], None], I ... | You need to understand that as long as the outer class is not fully constructed (when you are still setting up things inside its namespace), you will inevitably have to deal with forward references. So there are two mandatory things (and one optional) you need to remember, when doing this. 1) Use the qualified class na... | 4 | 9 |
76,330,655 | 2023-5-25 | https://stackoverflow.com/questions/76330655/attributeerror-module-numpy-has-no-attribute-complex | I am trying to make a real number complex using numpy. I am using numpy version 1.24.3 Here is the code: import numpy as np c=np.complex(1) However, I get this error: AttributeError: module 'numpy' has no attribute 'complex'. | np.complex was a deprecated alias for the builtin complex. Instead of np.complex you can use: complex(1) #output (1+0j) #or np.complex128(1) #output (1+0j) #or np.complex_(1) #output (1+0j) #or np.cdouble(1) #output (1+0j) Link to doc: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations | 3 | 7 |
76,328,904 | 2023-5-25 | https://stackoverflow.com/questions/76328904/is-there-a-difference-between-starlette-fastapi-background-tasks-and-simply-usin | I am looking for different ways to queue up functions that will do things like copy files, scrape websites, and manipulate files (tasks that will take considerable time). I am using FastAPI as a backend API, and I came across FastAPI's background task documentation as well as Starlette's background task documentation a... | TL;DR Those background tasks will always execute in the same process as your main application. They will either just run asynchronously on the event loop or in a separate thread. For operations that are not primarily I/O, you should probably avoid using them and use multiprocessing instead. Details Use multiprocessing... | 6 | 9 |
76,328,441 | 2023-5-25 | https://stackoverflow.com/questions/76328441/regex-to-remove-captions-with-condition-not-to-overlap-second-match | I have the following string, which I extract from a pdf: This is Fig. 13: John holding his present and the flowers Source: official photographer a beautiful Table: a table of some kind and fully complete Table: John holding his present and Source: official photographer sentence The text includes figs and tables, most ... | What you need to match is a Fig or Table followed by either Characters up to and including a line starting with Source, with no Fig or Table in between the original one and Source; or Characters up to the end of line You can achieve #1 above by using a tempered greedy token, which ensures that each character processe... | 2 | 4 |
76,328,354 | 2023-5-25 | https://stackoverflow.com/questions/76328354/subset-first-and-last-consecutive-value-from-pandas-df-col-python | I want to subset a df by returning the first and last consecutive value from a pandas col. Drop_duplciates won't work because it doesn't account for consecutive groupings. I'm using .shift() (below) but this only returns the last consecutive value, where I want the first and last. import pandas as pd df = pd.DataFrame(... | You need to compare against both the forward and backward shifted values so that you can find the start and finish of each group: df1 = df[(df['Item'].ne(df['Item'].shift())) | (df['Item'].ne(df['Item'].shift(-1)))] Output: Item Val1 Val2 0 A -20 150 2 A -20 150 3 B -20 148 6 B -20 151 7 A -23 150 8 A -22 148 | 2 | 3 |
76,325,603 | 2023-5-24 | https://stackoverflow.com/questions/76325603/evaluating-forward-references-with-typing-get-type-hints-in-python-for-a-class-d | I'm having trouble calling typing.get_type_hints() for classes that have forward references as strings. My code works with not defined inside of a function. I've reproduced a minimal example below in Python 3.10: import typing class B: pass class A: some_b: "B" print(typing.get_type_hints(A)) # prints {'some_b': <class... | typing.get_type_hints allows you to explicitly pass the local namespace to use for resolving references via the localns parameter. from typing import get_type_hints def func(): class A: some_b: "B" class B: pass print(get_type_hints(A, localns=locals())) func() Output: {'some_b': <class '__main__.func.<locals>.B'>} Se... | 6 | 3 |
76,322,524 | 2023-5-24 | https://stackoverflow.com/questions/76322524/how-to-use-asyncsession-from-sqlalchemy-in-celery-tasks | Use AsyncSession in celery tasks I use fastapi and sqlalchemy, I must create celery task, that will go to the database and check does any objects of my Event (table) has end_time < datetime.now() There is my code: @asynccontextmanager async def scoped_session(): scoped_factory = async_scoped_session( async_session, sco... | I just do like this async def update_event() -> None: async with async_session() as session: stmt = update(event.models.Event).where( event.models.Event.end_time <= datetime.now(), event.models.Event.is_active is True ).values(is_done=True) await session.execute(stmt) @celery.task(name='is_event_done', bind=True, ignor... | 4 | 3 |
76,322,128 | 2023-5-24 | https://stackoverflow.com/questions/76322128/pyo3-how-to-return-enums-to-python-module | I'm trying to build a Python package from Rust using PyO3. Right now I'm stuck trying to return enums Rust type to Python. I have a simple enum like so: pub enum Lang { Deu, Eng, Fra } And in lib.rs #[pyfunction] fn detect_language(text: &str) -> PyResult<????> { // Do some stuff .... res:Lang = Do_some_stuff(text) Ok... | One approach would to use #[pyclass] attribute to make the Python class from Rust Enum. Also make sure to export this class from Rust code, so that you can do the comparison on python layer. ie, use pyo3::prelude::*; #[pyclass] pub enum Lang { Deu, Eng, Fra } #[pyfunction] fn detect_language(text: &str) -> PyResult<Lan... | 2 | 3 |
76,319,917 | 2023-5-24 | https://stackoverflow.com/questions/76319917/python-unable-to-import-spacy-and-download-en-core-web-sm | What I want to achieve: Import spacy and use it. What I've tried: When I try to import spacy on python I get ImportError: cannot import name util error (detail on error1) Spacy is sucessfully installed to my device. https://github.com/explosion/spaCy/issues/2370 Following article I operated pip uninstall en_core_web_sm... | This has been reported. See the suggested workaround: https://github.com/explosion/spaCy/issues/12659. | 4 | 4 |
76,321,221 | 2023-5-24 | https://stackoverflow.com/questions/76321221/error-importerror-cannot-import-name-get-object-size-from-bson | when running the below file , I am getting error "ImportError: cannot import name 'get_object_size' from 'bson' (C:\Users\Dell\AppData\Local\Programs\Python\Python310\lib\site-packages\bson_init.py)" code: `from flask import Flask, request, jsonify from flask_pymongo import PyMongo # from bson.objectid import ObjectId ... | uninstall both pymongo and bson and install just pymongo, pymongo automatically installs bson pip uninstall pymongo pip uninstall bson pip install pymongo | 8 | 41 |
76,296,961 | 2023-5-20 | https://stackoverflow.com/questions/76296961/microservices-architecture-with-django | I have some questions about creating microservices with Django. Let's say we have an online shop or a larger system with many database requests and users. I want to practice and simulate a simple microservice to learn something new. We want to create a microservices-based system with the following components: A Django... | First a quick summary of Microservices vs Monolithic apps pros and cons (this is important). Microservices: [ PROS ] scalability (they scale independently) flexibility (each microservice can use its own stack & hardware setup) isolation (the failure of one microservice does not affect another, only its service fails.)... | 12 | 22 |
76,301,087 | 2023-5-21 | https://stackoverflow.com/questions/76301087/polars-list-to-columns-without-get | Say I have: In [1]: df = pl.DataFrame({'a': [[1,2], [3,4]]}) In [2]: df Out[2]: shape: (2, 1) ┌───────────┐ │ a │ │ --- │ │ list[i64] │ ╞═══════════╡ │ [1, 2] │ │ [3, 4] │ └───────────┘ I know that all elements of 'a' are lists of the same length. I can do: In [10]: df.select(pl.col('a').list.get(i).alias(f'a_{i}') fo... | You can convert the list to a struct and .unnest() df.with_columns(pl.col("a").list.to_struct()).unnest("a") shape: (2, 2) ┌─────────┬─────────┐ │ field_0 ┆ field_1 │ │ --- ┆ --- │ │ i64 ┆ i64 │ ╞═════════╪═════════╡ │ 1 ┆ 2 │ │ 3 ┆ 4 │ └─────────┴─────────┘ Warning: If your lists are not the same length, you must se... | 7 | 14 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.