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,301,828
2023-5-21
https://stackoverflow.com/questions/76301828/how-to-set-a-pydantic-field-value-depending-on-other-fields
from pydantic import BaseModel class Grafana(BaseModel): user: str password: str host: str port: str api_key: str | None = None GRAFANA_URL = f"http://{user}:{password}@{host}:{port}" API_DATASOURCES = "/api/datasources" API_KEYS = "/api/auth/keys" With Pydantic I get two unbound variables error messages for user, pas...
Pydantic v2 In Pydantic version 2 you can define a computed field for this exact purpose. from pydantic import BaseModel, computed_field class Model(BaseModel): foo: str bar: str @computed_field @property def foobar(self) -> str: return self.foo + self.bar obj = Model(foo="a", bar="b") print(obj) # foo='a' bar='b' foob...
12
17
76,273,150
2023-5-17
https://stackoverflow.com/questions/76273150/how-can-i-highlight-python-function-calls-with-in-vs-code
I would like to know how to enable the highlighting of function call in VS Code with python. See the following example where function call is blank, as other part of the code:
See the theming docs and the Developer: Inspect Editor Tokens and Scopes command in the command palette. Ex. Semantic highlighting customization route (requires a language extension that provides semantic highlighting support for Python) (highlights both function definitions and calls): "editor.semanticTokenColorCustom...
3
4
76,305,207
2023-5-22
https://stackoverflow.com/questions/76305207/openai-api-asynchronous-api-calls
I work with the OpenAI API. I have extracted slides text from a PowerPoint presentation, and written a prompt for each slide. Now, I want to make asynchronous API calls, so that all the slides are processed at the same time. this is the code from the async main function: for prompt in prompted_slides_text: task = async...
For those landing here, the error here was probably the instantiation of the object. It has to be: client = AsyncOpenAI(api_key=api_key) Then you can use: response = await client.chat.completions.create( model="gpt-4", messages=custom_prompt, temperature=0.9 )
12
18
76,314,792
2023-5-23
https://stackoverflow.com/questions/76314792/python-catching-and-then-re-throw-warnings-from-my-code
I want to catch and then re-throw warnings from my Python code, similarly to try/except clause. My purpose is to catch the warning and then re-throw it using my logger. The warnings are issued from whatever packages I'm using, I would like something that is totally generic, exactly like the try/except clause. How can I...
There are at least two ways to tackle this: Record the warnings and replay them Make warnings to behave like exceptions and break the control flow Option 1: Record warnings and replay them You could use warnings.catch_warnings with record=True to record the Warning objects. This way all your application code will get...
3
3
76,269,633
2023-5-17
https://stackoverflow.com/questions/76269633/how-to-accept-only-the-next-word-in-pycharm-github-copilot-suggestion
I would like to be able to accept only the next word of a github Copilot suggestion instead of the full suggestion. This is possible with VS Code as documented here. Is there a way to do this in PyCharm too?
This feature has been added with a recent update for the GitHub Copilot extension. One may now hit Ctrl + Right to accept the next word only, and in a multiline suggestion also Ctrl + Alt + Right to accept the next line only.
10
0
76,275,641
2023-5-17
https://stackoverflow.com/questions/76275641/mkdocs-how-to-attach-a-downloadable-file
I have a mkdocs project that resembles the following: project ├─mkdocs.yml ├─docs │ ├─home.md │ ├─chapter1.md │ ├─static ├─file.ext ├─image.png I am trying to find a way to "attach" file1.ext to the build, for instance as a link in chapter1.md. Any suggestions how to achieve that? Detail: I want the file to be downloa...
In mkdocs, to get the file to be downloadable on click using markdown, first you need to add this to your mkdocs.yml file : markdown_extensions: - attr_list and then in your chapter1.md you can add download attribute to your link ... like so : [file.ext](../static/file.ext){:download} Heck you can even name the downl...
3
8
76,313,592
2023-5-23
https://stackoverflow.com/questions/76313592/import-langchain-error-typeerror-issubclass-arg-1-must-be-a-class
I want to use langchain for my project. so I installed it using following command : pip install langchain but While importing "langchain" I am facing following Error: File /usr/lib/python3.8/typing.py:774, in _GenericAlias.__subclasscheck__(self, cls) 772 if self._special: 773 if not isinstance(cls, _GenericAlias): -->...
typing-inspect==0.8.0 typing_extensions==4.5.0
37
22
76,268,348
2023-5-17
https://stackoverflow.com/questions/76268348/how-to-update-modify-request-headers-and-query-parameters-in-a-fastapi-middlewar
I'm trying to write a middleware for a FastAPI project that manipulates the request headers and / or query parameters in some special cases. I've managed to capture and modify the request object in the middleware, but it seems that even if I modify the request object that is passed to the middleware, the function that ...
To update or modify the request headers within a middleware, you would have to update request.scope['headers'], as described in this answer. In that way, you could add new custom headers, as well as modify existing ones. In a similar way, by updating request.scope['query_string'], you could modify existing, as well as ...
4
4
76,318,098
2023-5-23
https://stackoverflow.com/questions/76318098/could-not-build-wheels-for-pycrypto-which-is-required-to-install-pyproject-toml
I'm facing an error while deploying to Heroku. ERROR: Could not build wheels for pycrypto, which is required to install pyproject.toml-based projects. However, my project does not specify use for pycrypto. What is causing this issue? My requirements.txt looks like: python==3.10.9 firebase_admin pyrebase pyrebase4 dash...
The problem occurred because I had both pyrebase and pyrebase4 inside the requirements.txt I removed pyrebase and kept pyrebase4. It solved the problem
10
0
76,279,266
2023-5-18
https://stackoverflow.com/questions/76279266/webdriverexception-unknown-error-runtime-callfunctionon-threw-exception-typee
I'm using Selenium with Python to generate inputs to credit card fields on a website. When you try send_keys to the field it always returns this error. I used different webdrivers (Chrome, Edge, Firefox) with the same effect. The error pops up before any input shows up in the field. from selenium import webdriver brows...
json.stringify() The json.stringify() static method is a built-in function in JavaScript that converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified. The json.stringify() method ...
2
4
76,309,946
2023-5-22
https://stackoverflow.com/questions/76309946/conda-attributeerror-module-brotli-has-no-attribute-error-after-update
I just run the command conda update conda. After that, all of my commands gives AttributeError: module 'brotli' has no attribute 'error'. I searched for solutions but none works. Anaconda Error - module 'brotli' has no attribute 'error' seems a reasonable answer but my anaconda3/lib directory does not contain a site-pa...
Lib\site-packages\urllib3\response.py tries to import brotlicffi as brotli and then tries import brotli, which yields brotli.error AttributeError: module 'brotli' has no attribute 'error'. pip install brotlicffi fixes the error in conda. Here are the versions I ended up with. Upgrading conda removed brotlipy-0.7.0-py31...
6
3
76,273,001
2023-5-17
https://stackoverflow.com/questions/76273001/how-to-solve-typeerror-type-object-does-not-support-context-manager-protocol
I was creating a voice assistant project but I am having problem with the line with with command in it. The code I've written is this import speech_recognition as sr import win32com.client speaker = win32com.client.Dispatch("SAPI.SpVoice") def say(text): speaker.Speak(f"{text}") def takeCommand(): r = sr.Recognizer() w...
try changing with sr.Microphone as source: to with sr.Microphone() as source:
5
17
76,297,649
2023-5-20
https://stackoverflow.com/questions/76297649/auto-arima-in-python-results-in-poor-fitting-prediction-of-trend
New to ARIMA and attempting to model a dataset in Python using auto ARIMA. I'm using auto-ARIMA as I believe it will be better at defining the values of p, d and q however the results are poor and I need some guidance. Please see my reproducible attempts below Attempt as follows: # DEPENDENCIES import pandas as pd imp...
Is auto_arima a method done by you? It depends how you differentiate and what you do there. Did you check the autocorrelation and partial autocorrelation to know which repeating time lags you have there? Also, it seems you have some seasonality patterns every year, you could try a SARIMA model if you are not doing it a...
7
2
76,290,771
2023-5-19
https://stackoverflow.com/questions/76290771/results-not-reproducible-between-runs-despite-seeds-being-set
How is it possible, that running the same Python program twice with the exact same seeds and static data input produces different results? Calling the below function in a Jupyter Notebook yields the same results, however, when I restart the kernel, the results are different. The same applies when I run the code from th...
This has now been fixed in probatus (the issue was a bug, apparently connected to the pandas implementation they were using, see here). For me, everything works as expecting when using the probatus' latest code version (not the package).
7
1
76,289,322
2023-5-19
https://stackoverflow.com/questions/76289322/selecting-python-interpreter-in-vscode
I am using VSCode with ArcGIS Pro 3.0 in a virtual environment. Until yesterday, everything worked just fine. After updating to Pro 3.0, I was still able to use open a script and then have it run in the terminal window. Previously, I was able to select a line from the script, run it, and then it would open the correct ...
I was typing python instead of Python. python was engaging python that was in PYTHONPATH.
10
0
76,284,412
2023-5-18
https://stackoverflow.com/questions/76284412/how-can-i-stream-a-response-from-langchains-openai-using-flask-api
I am using Python Flask app for chat over data. In the console I am getting streamable response directly from the OpenAI since I can enable streming with a flag streaming=True. The problem is, that I can't "forward" the stream or "show" the strem than in my API call. Code for the processing OpenAI and chain is: def ask...
With the usage of threading and callback we can have a streaming response from flask API. In flask API, you may create a queue to register tokens through langchain's callback. class StreamingHandler(BaseCallbackHandler): ... def on_llm_new_token(self, token: str, **kwargs) -> None: self.queue.put(token) You may get to...
7
3
76,268,799
2023-5-17
https://stackoverflow.com/questions/76268799/how-should-i-declare-enums-in-sqlalchemy-using-mapped-column-to-enable-type-hin
I am trying to use Enums in SQLAlchemy 2.0 with mapped_column. So far I have the following code (taken from another question): from sqlalchemy.dialects.postgresql import ENUM as pgEnum import enum class CampaignStatus(str, enum.Enum): activated = "activated" deactivated = "deactivated" CampaignStatusType: pgEnum = pgEn...
The crux of the issue relating to __mro__ causing the AttributeError is that CampaignStatusType is not a class, but rather an instance variable of type sqlalchemy.dialects.postgresql.ENUM (using pyright may verify this - given that it complains about Mapped[CampaignStatusType] being an "Illegal type annotation: variabl...
12
16
76,315,436
2023-5-23
https://stackoverflow.com/questions/76315436/html-iframe-with-dash-output
I have 2 pretty simple dashboards and I would like to run this two dashboards with flask using main.py for routing. app1.py import dash from dash import html, dcc app = dash.Dash(__name__) app.layout = html.Div( children=[ html.H1('App 1'), dcc.Graph( id='graph1', figure={ 'data': [{'x': [1, 2, 3], 'y': [4, 1, 2], 'typ...
I can't access the templates with your code, I think dask uses flask so this may be causing problems. What I have done is calling two dash apps and one flask app; this for main.py: from flask import Flask, render_template from app1 import create_app as create_app1 from app2 import create_app as create_app2 server = Fla...
5
3
76,316,261
2023-5-23
https://stackoverflow.com/questions/76316261/how-to-edit-an-already-created-python-script-in-powerbi
In my Power BI dashboard, I created a Python Script that accesses an API and generates a Pandas data frame. It works fine, but how can I edit the Python code? I thought it would be something simple, but I can't really find how to find it in the interface. If I send the .pbix file to someone, they will receive an alert ...
In Power Query you should be able to click on the ribbon to insert Python code as below. If the script is existing, then click the little cog icon to the right of the step in APPLIED STEPS as below:
5
2
76,319,199
2023-5-23
https://stackoverflow.com/questions/76319199/getting-the-price-of-the-game-from-egs
I'm trying to get the price of the game from the epic games store, but I get a 403 error import requests from bs4 import BeautifulSoup url = "https://store.epicgames.com/ru/p/cities-skylines" response = requests.get(url) if response.status_code == 200: soup = BeautifulSoup(response.text, 'html.parser') price_element = ...
You get to the cloudflare page dedicated to fighting robots. To get around this limitation, you need to imitate a real person. To do this, you can use the following library or similar. Here is an example of working code. Don't forget to pip install cloudscraper. from bs4 import BeautifulSoup import cloudscraper url = "...
3
0
76,282,003
2023-5-18
https://stackoverflow.com/questions/76282003/binary-image-classifier-in-pytorch-progress-bar-and-way-to-check-if-the-training
I would like to build and train a binary classifier in PyTorch that reads images from the path process them and trains a classifier using their labels. My images can be found in the following folder: -data - class_1_folder - class_2_folder Hence, to read them in tensors I am doing the following: PATH = "data/" transfo...
Synopsis There are few issues with the attached code: the torch API is underused (because the code is too long) the dataset is not fed properly (the training part iterates over one chunk of data returned once by iter), the last layer and loss don't look correct (because of one neuron in nn.Linear(num_features, 1) and ...
5
2
76,283,892
2023-5-18
https://stackoverflow.com/questions/76283892/how-to-add-an-information-display-button-to-the-interactive-plot-toolbar
The matplotlib plot toolbar has some support for customization. This example is provided on the official documentation: import matplotlib.pyplot as plt from matplotlib.backend_tools import ToolBase, ToolToggleBase plt.rcParams['toolbar'] = 'toolmanager' class ListTools(ToolBase): """List all the tools controlled by the...
You could modify the example you provided from the matplotlib documentation to add a button that create a figure in a new window with only text in it. And, once you click on the same button again it closes the window. See code below, I called the implemented tool/button 'Info': import matplotlib.pyplot as plt from matp...
4
0
76,311,807
2023-5-23
https://stackoverflow.com/questions/76311807/attributeerror-adam-object-has-no-attribute-build-during-unpickling
I'm training a Keras model and saving it for later use using pickle. When I unpickle I get this error: AttributeError: 'Adam' object has no attribute 'build' Here's the code: from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense import pickle model = Sequential() model.add(Dense(32, a...
Instead of pickling, you should save the model using h5. This solves the issue: from keras.models import load_model model.save('m.h5') loadedModel = load_model('m.h5')
4
3
76,314,229
2023-5-23
https://stackoverflow.com/questions/76314229/how-to-download-spacy-models-in-a-poetry-managed-environment
I am writing a Python Jupyter notebook that does some NLP processing on Italian texts. I have installed spaCy 3.5.3 via Poetry and then attempt to run the following code: import spacy load_model = spacy.load('it_core_news_sm') The import line works as expected, but running spacy.load produces the following error: OSE...
You can add a URL dependency. First edit your pyproject.toml file to add the following (note: the name used here should match the name of the package (i.e. it_core_news_sm): [tool.poetry.dependencies] it_core_news_sm = {url = "https://github.com/explosion/spacy-models/releases/download/it_core_news_sm-3.5.0/it_core_new...
10
19
76,313,231
2023-5-23
https://stackoverflow.com/questions/76313231/detect-the-foreground-rocks-stockpile-from-the-background-wall-to-find-mater
I am trying to find angles of a stockpile (on the left and right sides) by using Otsu threshold to segment the image. The image I have is like this: In the code, I segment it and find the first black pixel in the image The segmented photo doesn't seem to have any black pixels in the white background, but then it dete...
Your issue is that the image has noise. You need to deal with the noise. That is usually done with some kind of lowpassing, i.e. blurring. I'd recommend a median blur. Here's the result of a median filter, kernel size 9: And the per-pixel absolute differences to the source, magnified in amplitude by 20x: (this sugges...
5
4
76,315,624
2023-5-23
https://stackoverflow.com/questions/76315624/registering-discriminated-union-automatically
Using pydantic 1.10.7 and python 3.11.2 I have a recursive Pydantic model and I would like to deserialize each types properly using discriminated union. from pydantic import BaseModel, Field class Base(BaseModel): kind: str sub_models: Annotated[ List[Union[A,B]], Field( default_factory=list, discriminator="kind" ) ] c...
The challenge here is that a lot of the heavy lifting of Pydantic model creation is done by the metaclass, specifically its __new__ method. Simply re-defining sub_models and kind in the __annotations__ dictionary will not be enough for those changes to affect the actual fields because those are created and configured b...
3
2
76,308,514
2023-5-22
https://stackoverflow.com/questions/76308514/how-to-implement-mase-mean-absolute-scaled-error-in-python
I have Predicted values and Actual values, and I can calculate Mean Absolute Percentage Error by doing: abs(Predicted-Actual)/ Predicted *100 How do I calculate MASE with respect to my Predicted and Actual values?
The Mean Absolute Scaled Error (MASE) is calculated by subtracting the forecasted or predicted value from the actual value divided by the average forecast error where the actual value from the prior step is used as the prediction or forecast. Here is the equation as a list-comprehension: mase = numpy.mean([abs(Actual[i...
4
0
76,313,534
2023-5-23
https://stackoverflow.com/questions/76313534/shuffle-with-a-constraint
I have a problem analog to: We have 20 balls each ball is unique and identified by a number from 1 to 20. The balls numbered from 1 to 5 are yellow, from 6 to 10 green, from 10 to 15 red and from 16 to 20 blue. Find a method to randomly shuffle the balls while respecting the constraint: "2 successive balls cannot have ...
It boils down to calculate the number of permutations which obey your constrains. See https://math.stackexchange.com/questions/1208392/ways-to-arrange-4-different-colour-balls-with-no-two-of-the-same-colour-next-to for an answer how to calculate the number of ways to arrange your balls with the first one being one part...
6
1
76,315,335
2023-5-23
https://stackoverflow.com/questions/76315335/can-a-python-package-and-its-corresponding-pypi-project-have-different-names
For example, I'm wondering how is it possible that scikit-learn is the name of a PyPi package while the actual Python module is named sklearn. The reason I'm asking is that I have a local Python package packageA that I can't upload to PyPi since that name happens to already be taken. I therefore wonder if I can upload ...
The names on PyPi or the names you are useing when doing pip install NAME are Distribution Packages. The names you use when doing import NAME are Import Packages. One Distribution Package can have multiple Import Packages in it. Example As an example see this demo project bit-demo: The name of the repositories (you fi...
3
7
76,313,907
2023-5-23
https://stackoverflow.com/questions/76313907/remove-element-in-array-i-dont-understand-how-work-output-in-my-case-python
I don't understand how work output in my case. Could you explain to me what I'm doing wrong? task:(27. Remove Element) Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The order of the elements may be changed. Then return the number of elements in nums which are not equal...
The problem is that you are not removing the elements in-place, so nums outside the function is not affected. One option is to iterate over the list and remove items with pop. To avoid index out of range exception iterate over the list from end to start for i in range(len(nums) - 1, 0, -1): if nums[i] == val: nums.pop(...
3
3
76,313,897
2023-5-23
https://stackoverflow.com/questions/76313897/to-delete-a-transparent-area-of-an-image-in-python
I want to use Python to cut the transparent area of the image file. Please look at the picture below. image 1 (original image) image 2 (result image) The original image has alternating opaque and transparent areas. I want to transform the image consisting of 1-spaces-2-spaces-3-spaces-4 like the original image into 1...
You were very close - I would use Numpy indexing to gather the rows you want: from PIL import Image import numpy as np # Open image and ensure not palettised, make into Numpy array and select alpha channel im = Image.open('e0rRU.png').convert('RGBA') na = np.array(im) alpha = na[:, :, 3] # Find opaque rows non_empty_ro...
3
2
76,301,807
2023-5-21
https://stackoverflow.com/questions/76301807/comparison-of-bfs-and-dfs-algorithm-for-the-knapsack-problem
I am fairly new to python and I have a task which tells me to compare both algorithm time expended and space used in memory. I have coded both algorithms and ran them both. I was able to measure the time used, but wasnt able to look for ways to know how much space was used. I am also not sure if the question is asking ...
You can try doing what another answer suggested: https://stackoverflow.com/a/45679009/670693 While I couldn't run your code to try things out, missing the Node definition, you can try something like: import tracemalloc tracemalloc.start() knapsack_dfs(...) dfs_snapshot = tracemalloc.take_snapshot() knapsack_bfs(...) bf...
3
1
76,302,654
2023-5-22
https://stackoverflow.com/questions/76302654/why-does-property-override-object-getattribute
I noticed that contrary to the classmethod and staticmethod decorators, the property decorator overrides the object.__getattribute__ method: >>> list(vars(classmethod)) ['__new__', '__repr__', '__get__', '__init__', '__func__', '__wrapped__', '__isabstractmethod__', '__dict__', '__doc__'] >>> list(vars(staticmethod)) [...
To refresh yourself on what __getattribute__ is and how this is implemented in CPython, please refer to this very excellent answer first, as that answers contains all the detailed background information on what to look for in the CPython source, and the paragraphs below will reference those details without further expl...
3
3
76,309,963
2023-5-22
https://stackoverflow.com/questions/76309963/checking-a-column-in-a-pandas-df-does-not-contain-certain-text
I am attempting to write a specific value to a column in a pandas df depending on if another column does or does not contain certain text. I have 3 outputs in the destination columns: Distributor, OEM and End User. import pandas as pd df = pd.read_excel("Customer Records.xlsx") #Checking for distributor pricing tag df....
You can use np.select: conds = [ df['CustomerRoles'].str.contains('Discount-Distributor-STD'), df['CustomerRoles'].str.contains('Discount-OEM-STD') ] choices = ['Distributor', 'OEM'] df['Customer Type'] = np.select(condlist=conds, choicelist=choices, default='End User')
2
3
76,286,028
2023-5-19
https://stackoverflow.com/questions/76286028/how-to-cancel-all-tasks-in-a-taskgroup
import asyncio import random task_group: asyncio.TaskGroup | None = None async def coro1(): while True: await asyncio.sleep(1) print("coro1") async def coro2(): while True: await asyncio.sleep(1) if random.random() < 0.1: print("dead") assert task_group is not None task_group.cancel() # This function does not exist. el...
I end up use another task to wrap the function that contains the TaskGroup and cancel that task instead. It works as desired. # Only show functions that has been changed main_task: asyncio.Task[None] | None = None async def coro2(): while True: await asyncio.sleep(1) if random.random() < 0.1: print("dead") assert main_...
5
1
76,304,374
2023-5-22
https://stackoverflow.com/questions/76304374/how-can-we-add-a-list-of-documents-to-an-existing-index-in-llama-index
I have an existing index that is created using GPTVectorStoreIndex. However, when I am trying to add a new document to the existing index using the insert method, I am getting the following error : AttributeError: 'list' object has no attribute 'get_text' my code for updating the index is as follows : max_input_size = ...
I got it right, the mistake I was doing it was passing documents as a whole, which is a List object. The right way to update is as follows max_input_size = 4096 num_outputs = 5000 max_chunk_overlap = 256 chunk_size_limit = 3900 prompt_helper = PromptHelper(max_input_size, num_outputs, max_chunk_overlap, chunk_size_limi...
4
8
76,297,879
2023-5-21
https://stackoverflow.com/questions/76297879/benchmarks-of-fastapi-vs-async-flask
I'm a developer without an interest in benchmarking and I'm trying to decide whether I should use Flask or FastAPI to build some Python/Vue projects. I'm seeing stuff online about how FastAPI was faster than Flask because Flask was single-threaded or something like that, whereas FastAPI was async, but apparently more-r...
According to a benchmark study by Miguel Grinberg, FastAPI can be faster or slower than async Flask, depending on the web server and the Flask async type. Generally Flask on a Greenlet powered WSGI server (Meinheld / Gevent) can offer comparable throughput as an async-first ASGI framework like FastAPI. Note that Grinbe...
9
15
76,297,052
2023-5-20
https://stackoverflow.com/questions/76297052/how-to-write-a-python-regex-that-matches-strings-with-both-words-and-digits-exc
I want to write a regex that matches a string that may contain both words and digits and not digits only. I used this regex [A-z+\d*], but it does not work. Some matched samples: expression123 123expression exp123ression Not matched sample: 1235234567544 Can you help me with this one? Thank you in advance
Lookarounds to the rescue! ^(?!\d+$)\w+$ This uses a negative lookahead construct and anchors, see a demo on regex101.com Note that you could have the same result with pure Python code alone: samples = ["expression123", "123expression", "exp123ression", "1235234567544"] filtered = [item for item in samples if not ite...
3
7
76,276,568
2023-5-17
https://stackoverflow.com/questions/76276568/how-can-i-reuse-logic-to-handle-a-keypress-and-a-button-click-in-pythons-tkinte
I have this code: from tkinter import * import tkinter as tk class App(tk.Frame): def __init__(self, master): def print_test(self): print('test') def button_click(): print_test() super().__init__(master) master.geometry("250x100") entry = Entry() test = DoubleVar() entry["textvariable"] = test entry.bind('<Key-Return>'...
Commands callbacks for button clicks are called without arguments, because there is no more information that is relevant: the point of a button is that there's only one "way" to click it. However, key presses are events, and as such, callbacks for key-binds are passed an argument that represents the event (not anything...
2
3
76,296,055
2023-5-20
https://stackoverflow.com/questions/76296055/how-to-avoid-tkinter-slowing-down-as-number-of-shapes-increases
I have a python project with tkinter. On this project I draw small squares over time. I noticed tkinter is slowing down as the number of square increases. Here is a simple example that draws 200 red squares on each iteration: import tkinter as tk import random import time WIDTH = 900 CELL_SIZE = 2 GRID_WIDTH = int(WIDT...
When adding shapes, you are not just colorize pixels. You create graphics with contexts and store them into memory. Instead of abusing the Canvas paint a picture and show this picture in the Canvas this will be a lot faster and will give you more options to colorize your image that you rather want to draw.
5
2
76,292,501
2023-5-19
https://stackoverflow.com/questions/76292501/query-existing-pinecone-index-without-re-loading-the-context-data
I'm learning Langchain and vector databases. Following the original documentation I can read some docs, update the database and then make a query. https://python.langchain.com/en/harrison-docs-refactor-3-24/modules/indexes/vectorstores/examples/pinecone.html I want to access the same index and query it again, but witho...
You need to access the existing index. In order to do this, you must know the name of the index, and what embeddings were used to create it. index_name = "mlqai" embeddings = OpenAIEmbeddings(openai_api_key=os.environ['OPENAI_API_KEY']) docsearch = Pinecone.from_existing_index(index_name, embeddings) Documentation.
6
12
76,279,731
2023-5-18
https://stackoverflow.com/questions/76279731/why-snakemake-prefers-calling-script-using-script-directive-instead-of-calling-f
Snakemake rules in standardized workflows run Python scripts using the script directive, such as this template rule: rule XXXXX: input: ..., output: ...., params: ..., conda: "../envs/python.yaml" script: "../scripts/XXXX.py" Then in the script, it is possible to use snakemake object. However, the script is then tight...
The script approach is a bit more flexible in terms of the objects that the script can access via the params and other directives. If you follow the shell approach you might find it cumbersome to (re) define the argparse or other approaches to properly take account of the arguments passed via shell. It's going to be mo...
2
5
76,288,658
2023-5-19
https://stackoverflow.com/questions/76288658/python-dataframe-subtract-value-from-one-column-from-each-list-element-of-anothe
I have a dataframe. Column one has a list of numbers. Second column has average of list of numbers in column one. I need to create third column such that I subtract mean value from each of the elements of column one. df = pd.DataFrame({'A':[[4.2,2.3,6.5,2.3],[4.1,5.3,6.5,3.8]]}) df['avg'] = df['A'].apply(lambda p: np.a...
Use list comprehension with convert lists to numpy for improve performance: df['a_avg'] = [(np.round(np.array(p) - np.average(p), 3)).tolist() for p in df['A']] Or: df['a_avg'] = df.A.apply(lambda p: (np.round(np.array(p) - np.average(p), 3)).tolist()) print (df) A a_avg 0 [4.2, 2.3, 6.5, 2.3] [0.375, -1.525, 2.675, -...
2
1
76,287,668
2023-5-19
https://stackoverflow.com/questions/76287668/reading-extracting-data-from-databricks-database-hive-metastore-with-pyspar
I am trying to read in data from Databricks Hive_Metastore with PySpark. In screenshot below, I am trying to read in the table called 'trips' which is located in the database nyctaxi. Typically if this table was located on a AzureSQL server I was use code like the following: df = spark.read.format("jdbc")\ .option("url...
The samples catalog can be accessed in using spark.table("catalog.schema.table"). So you should be able to access the table using: df = spark.table("samples.nyctaxi.trips") Note also if you are working direct in databricks notebooks, the spark session is already available as spark - no need to get or create.
2
9
76,287,980
2023-5-19
https://stackoverflow.com/questions/76287980/how-can-i-convert-a-dictionary-into-a-pandas-dataframe-with-specific-keys-as-col
I have a dictionary as follows: D = {'mark': [['height', 7], ['weight', 70]], 'david': [['height', 8], ['weight', 80]], 'john': [['height', 9], ['weight', 90]]} print (D) I wanted to get the pandas dataframe into this form: names height weight 0 mark 7 70 1 david 8 80 2 john 9 90 I tried as follows. df = pd.DataFram...
You can use : df = pd.DataFrame({k: dict(v) for (k,v) in D.items()}).T.reset_index(names="names") Output : print(df) names height weight 0 mark 7 70 1 david 8 80 2 john 9 90
2
3
76,286,148
2023-5-19
https://stackoverflow.com/questions/76286148/how-do-custom-init-functions-work-in-pydantic-with-inheritance
I'm trying to use inheritance in pydantic with custom __init__ functions. I have parent (fish) and child (shark) classes that both require more in initialization than just setting fields (which in the MWE is represented by an additional print statement). So I need to override their inits. I tried: class fish(BaseModel)...
This has nothing to do with Fish needing to know anything about the fields defined on Shark. It has everything to do with BaseModel.__init__ knowing, which fields any given model has, and validating all keyword-arguments against those. You need to keep in mind that a lot is happening "behind the scenes" with any model ...
9
13
76,279,304
2023-5-18
https://stackoverflow.com/questions/76279304/configure-pylance-to-stop-prefixing-project-directory-on-import-auto-complete
When working in a Git repository where my Python/Django source is in a subfolder {$workspace}/app, as seen below. project/ .vscode/ .git/ app/ -- the app source code (not a Python module) docs/ .gitignore LICENSE The problem is that VSCode adds an incorrect app. prefix when auto-generating import statements. For e...
If it's the file structure in your question, open the project as a workspace. settings.json should be like this { "python.analysis.extraPaths": [ "./app", ], "python.autoComplete.extraPaths": [ "./app", ], }
3
4
76,284,920
2023-5-18
https://stackoverflow.com/questions/76284920/how-would-i-pad-a-string-with-random-symbols-in-python
I'm trying to make my 'hacking' portion of a Fallout terminal simulator more akin to what is actually in the game. I'm in the process of setting it up so that it uses a word list, picks some words from it, and then puts them into the list of address-like display. However, because the length of the words ranges from 4 l...
Create a random 15-character string. Then extract a slice of it long enough to pad out what you want. random_string = 'weopi94nf0683d0' word = 'FISH' left = (len(random_string) - len(word)) // 2 right = left + len(word) padded_word = random_string[:left] + word + random_string[right:]
3
2
76,284,570
2023-5-18
https://stackoverflow.com/questions/76284570/converting-real-time-audio-to-phonemes
Using a microphone as an input for real-time audio. How do I extract the currently said phoneme from the audio? I need it for lipsyncing 2d characters. Basically, my approach would be to: Fetch the real-time audio using a microphone Detect the current phoneme that is being pronounced from the audio. I have tried look...
The way I would approach this is to get the word from the audio using Whisper or a similar STT service (the Python Speech Recognition Library is the go-to at the moment), then I would use the CMU Dict Library to provide phonemes for each word. The phonemes are given using the CMU dictionary - for example DH for the θ p...
3
4
76,282,454
2023-5-18
https://stackoverflow.com/questions/76282454/pandas-dataframe-groupby-and-aggregate-counting-on-condition
I have started playing with Data Analysis and all the related tools: Pandas, Numpy, Jupyter etc... The task I am working on is simple, and I could do easily with regular python. However I am more interested in exploring Pandas, and I am looking therefore for a Pandas solution. I have this simple Pandas DataFrame. The t...
import pandas as pd # The DataFrame a = { 'id': [1, 2, 3, 4, 5, 6], 'timestamp': [9999, 1111, 9999, 1111, 9999, 1111], 'success': [True, True, False, True, True, True] } df = pd.DataFrame(a) # Group by timestamp and calculate the sum of success result = df.groupby('timestamp')['success'].sum().reset_index() # Result pr...
3
3
76,274,802
2023-5-17
https://stackoverflow.com/questions/76274802/plt-imshow-of-a-single-color-image-showing-as-black
I am trying to show a light-gray image using plt.imshow(), but the image turns out black. I tried: import matplotlib.pyplot as plt import numpy as np test_image = np.zeros((3871, 2484)) test_image.fill(200) plt.imshow(test_image, cmap="gray") plt.show() But ended up getting: Matplotlib version: 3.7.1 Numpy version: ...
You have to include the vmin,vmax parameters when you plot a single color image with plt.imshow(...). Set vmin=0 and vmax=500 to get a gray image. If vmin,vmax are not specified, then they will be set to the min and max values of the image data. This means that all of your input data is equal to vmin, which is the dark...
3
3
76,275,425
2023-5-17
https://stackoverflow.com/questions/76275425/how-to-add-custom-annotations-with-uncertainty-to-a-heatmap
I am attempting to visualize some data as a table, where the boxes of each table element are colored according to their value, the numerical value is also displayed, and the uncertainty on each element is shown. I can achieve 2 out of these 3 things using pandas.pivot_table and sns.heatmap, but cannot seem to include t...
You can pass a DataFrame with the formatted strings to sns.heatmap: table = pd.pivot_table(df, values=['D', 'E'], index=['A', 'B'], columns=['C'], aggfunc=np.sum, fill_value=0) sns.heatmap(table['D'], annot=table['D'].astype(str)+'±'+table['E'].astype(str), fmt='')
3
4
76,270,706
2023-5-17
https://stackoverflow.com/questions/76270706/mypy-errors-when-using-arraylike
I don't understand how I should be using ArrayLike in my code. If check mypy, I keep getting errors when I try to use the variables for anything without calling cast. I am trying to define function signatures that work with ndarray as well as regular lists. For example, the code below import numpy.typing as npt import ...
The purpose of numpy.typing.ArrayLike is to be able to annotate objects that can be coerced into an ndarray. With that purpose in mind, they defined the type to be the following union: Union[ _SupportsArray[dtype[Any]], _NestedSequence[_SupportsArray[dtype[Any]]], bool, int, float, complex, str, bytes, _NestedSequenc...
6
8
76,268,855
2023-5-17
https://stackoverflow.com/questions/76268855/remove-element-by-value-in-list-python-fastest
what is the fastest way to remove an element from a list by its value? I believe list.remove("element_to_be_removed") is the naive way. How can we optimize it?
Finding an element in a list by value is O(n), as is removing it once you have found it. There is no way to reduce this; it's inherent in how lists are built. Finding and/or removing an element in a set is O(1). Converting a list into a set is O(n). If you have a list and you need to remove one item, converting it to a...
2
4
76,268,656
2023-5-17
https://stackoverflow.com/questions/76268656/how-to-extract-dict-values-of-pandas-dataframe-in-new-columns
I would like to extract the values of a dictionary inside a Pandas DataFrame df into new columns of that DataFrame. All keys in the referring dict are the same across all rows. import pandas as pd df = pd.DataFrame({'a': [1, 2, 3], 'b': [{'x':[101], 'y': [102], 'z': [103]}, {'x':[201], 'y': [202], 'z': [203]}, {'x':[30...
If there are always one element lists is possible use nested list with dictionary comprehension and pass to DataFrame constructor: df = df.join(pd.DataFrame([{k: v[0] for k, v in x.items()} for x in df.pop('b')], index=df.index)) print (df) a x y z 0 1 101 102 103 1 2 201 202 203 2 3 301 302 303 Another idea is create...
3
3
76,223,362
2023-5-11
https://stackoverflow.com/questions/76223362/in-a-polars-group-by-aggregation-how-do-you-concatenate-string-values-in-each-g
When grouping a Polars dataframe in Python, how do you concatenate string values from a single column across rows within each group? For example, given the following DataFrame: import polars as pl df = pl.DataFrame( { "col1": ["a", "b", "a", "b", "c"], "col2": ["val1", "val2", "val1", "val3", "val3"] } ) Original df: ...
If you want to concatenate them, I assume you want the result as a string with your specified delimiter: out = df.group_by("col1").agg( pl.col("col2").str.join(",") ) Result: shape: (3, 2) ┌──────┬───────────┐ │ col1 ┆ col2 │ │ --- ┆ --- │ │ str ┆ str │ ╞══════╪═══════════╡ │ a ┆ val1,val1 │ │ b ┆ val2,val3 │ │ c ┆ va...
6
8
76,231,965
2023-5-11
https://stackoverflow.com/questions/76231965/add-hint-of-duration-for-each-iteration-in-tqdm
I have a list of tasks that each take a different amount of time. Let's say, I have 3 tasks, with durations close to 1x, 5x, 10*x. My tqdm code is something like: from tqdm import tqdm def create_task(n): def fib(x): if x == 1 or x == 0: return 1 return fib(x - 1) + fib(x - 2) return lambda: fib(n) n = 1 tasks = [creat...
There are two standard usages for tqdm progress bars: iterable-based, and manual. Manually updating a progress bar allows you to specify progress bar weights. Consider the following code: def my_func(x): """ Sleep for x / 5 seconds. """ duration = x / 5 time.sleep(duration) in_vals = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # Ex...
3
1
76,247,812
2023-5-14
https://stackoverflow.com/questions/76247812/how-to-create-pagination-embed-menu-in-discord-py
I need a 'SLASH COMMAND' that can displays an embed with 10 elements per page and buttons below for navigation (not reactions, those clickable buttons recently introduced). I am using Discord.py version 2.2.3 Here is the code snippet of my bot: import os import discord from discord import app_commands import asyncio TO...
I have a pagination view already prepared that I use in my bots: import discord from typing import Callable, Optional class Pagination(discord.ui.View): def __init__(self, interaction: discord.Interaction, get_page: Callable): self.interaction = interaction self.get_page = get_page self.total_pages: Optional[int] = Non...
3
4
76,218,303
2023-5-10
https://stackoverflow.com/questions/76218303/in-python-polars-filter-and-aggregate-dict-of-lists
I have got a dataframe with string representation of json: df = pl.DataFrame({ "json": [ '{"x":[0,1,2,3], "y":[10,20,30,40]}', '{"x":[0,1,2,3], "y":[10,20,30,40]}', '{"x":[0,1,2,3], "y":[10,20,30,40]}' ] }) shape: (3, 1) ┌───────────────────────────────────┐ │ json │ │ --- │ │ str │ ╞══════════════════════════════════...
json.loads() To parse JSON strings in Polars you can use .str.json_decode() (i.e. the equivalent of json.loads) df.with_columns(pl.col("json").str.json_decode()) shape: (3, 1) ┌──────────────────────────────┐ │ json │ │ --- │ │ struct[2] │ ╞══════════════════════════════╡ │ {[0, 1, … 3],[10, 20, … 40]} │ │ {[0, 1, … 3...
3
1
76,265,735
2023-5-16
https://stackoverflow.com/questions/76265735/does-pygbag-directly-interprets-python-in-the-browser-or-compiles-it-to-wasm-and
I was wandering through the docs of pygbag, and I couldn't find how the python scripts are actually executed from the browser. I made a test project to look how the files created by pygbag looked like, but I couldn't really figure out what role the index.html exactly plays. It seemed to me like I couldn't find any scri...
When running in the webpage pygbag is in fact a C runtime linked to libpython ( cpython-wasm from python.org) compiled to WebAssembly with emscripten compiler and hosted on a CDN (pygame-web.github.io). It is downloaded once per game and per version update for fast local use. There's some javascript glue to connect the...
4
2
76,249,186
2023-5-14
https://stackoverflow.com/questions/76249186/probability-of-moving-on-a-cartesian-plane
I am working on the below coding problem which looks more like a probability question rather than a coding problem platform consisting of 5 vertices. The coordinates of the vertices are: (-1,0), (0.-1). (0,0), (0.1). (1.0). You start at vertex (xs,ys) and keep moving randomly either left (i.e., x coordinate decreases b...
If we handle the edge cases where you start at your destination, or you start at an edge and the destination is the center, we're left with a simple scenario: find you way to the center, and then to the destination. Getting to the origin is a flat 0.25 probability, and then its just a matter of getting to the right edg...
4
9
76,225,595
2023-5-11
https://stackoverflow.com/questions/76225595/nameerror-name-partialstate-is-not-defined-error-while-training-hugging-face
Here is the code block which caused the error training_args = TrainingArguments( output_dir="my_awesome_mind_model", evaluation_strategy="epoch", save_strategy="epoch", learning_rate=3e-5, per_device_train_batch_size=32, gradient_accumulation_steps=4, per_device_eval_batch_size=32, num_train_epochs=10, warmup_ratio=0.1...
As of 2023-05-11: The error seems to be caused by an issue in the huggingface/accelerate library. You can try following solutions: Reinstall transformers & accelerate pip uninstall -y transformers accelerate pip install transformers accelerate If you are using colab/Jupyter, make sure to restart the notebook's Runtime...
11
21
76,220,715
2023-5-10
https://stackoverflow.com/questions/76220715/type-vector-does-not-exist-on-postgresql-langchain
I was trying to embed some documents on postgresql with the help of pgvector extension and langchain. Unfortunately I'm having trouble with the following error: (psycopg2.errors.UndefinedObject) type "vector" does not exist LINE 4: embedding VECTOR(1536), ^ [SQL: CREATE TABLE langchain_pg_embedding ( collection_id UUID...
Update 17th July 2023 As previously I mentioned my issue was somewhere else in my configuration, here is the other reason that may be responsible for the error, The pgvector extension isn't enabled in the database you are using. Make sure you run CREATE EXTENSION vector; in each database you are using for storing vect...
18
17
76,265,631
2023-5-16
https://stackoverflow.com/questions/76265631/chromadb-add-single-document-only-if-it-doesnt-exist
I'm working with langchain and ChromaDb using python. Now, I know how to use document loaders. For instance, the below loads a bunch of documents into ChromaDb: from langchain.embeddings.openai import OpenAIEmbeddings embeddings = OpenAIEmbeddings() from langchain.vectorstores import Chroma db = Chroma.from_documents(d...
Filter based solely on the Document's Content Here is an alternative filtering mechanism that uses a nice list comprehension trick that exploits the truthy evaluation associated with the or operator in Python: # Create a list of unique ids for each document based on the content ids = [str(uuid.uuid5(uuid.NAMESPACE_DNS,...
15
8
76,233,163
2023-5-12
https://stackoverflow.com/questions/76233163/valueerror-run-not-supported-when-there-is-not-exactly-one-output-key-got
I got an error says ValueError: `run` not supported when there is not exactly one output key. Got ['answer', 'sources', 'source_documents']. Here's the traceback error File "C:\Users\Science-01\anaconda3\envs\gpt-dev\lib\site-packages\streamlit\runtime\scriptrunner\script_runner.py", line 565, in _run_script exec(code...
I found the solution, change this code if prompt: response = chain.run(prompt, return_only_outputs=True) st.write(response) to this if st.button('Generate'): if prompt: with st.spinner('Generating response...'): response = chain({"question": prompt}, return_only_outputs=True) answer = response['answer'] st.write(answe...
5
3
76,222,409
2023-5-10
https://stackoverflow.com/questions/76222409/how-to-create-python-c-extension-with-submodule-that-can-be-imported
I'm creating a C++ extension for python. It creates a module parent that contains a sub-module child. The child has one method hello(). It works fine if I call it as import parent parent.child.hello() > 'Hi, World!' If I try to import my function it fails import parent from parent.child import hello > Traceback (most ...
Doing this from within the extension is a "simple" matter of emulating the behavior for modules that the import system recognizes as packages. (Depending on context, it might be nicer to provide an import hook that did the same thing from the outside.) Just a few changes are needed: Make the name of the child "parent....
5
1
76,249,589
2023-5-14
https://stackoverflow.com/questions/76249589/building-python-c-module-on-windows
I am trying to build a 'C' python extension on Windows, the core C code compiles absolutely fine, but I am unable to build the python module using setuptool as I am getting mandlebrot.c(36): fatal error C1083: Cannot open include file: 'stdio.h': No such file or directory error: command 'e:\Program Files\Microsoft Vis...
1. The error By default, Python is built on Win with VStudio ([Python.Wiki]: WindowsCompilers), and it also uses that to build C / C++ code (unless otherwise instructed). It seems like you don't have VStudio's cross build tools (for 032bit) installed. A quick search revealed: [SO]: Cannot open include file: 'stdio.h' ...
3
1
76,266,695
2023-5-16
https://stackoverflow.com/questions/76266695/cant-install-pyqt5-using-pip-on-alpine-docker
Here is my Dockerfile: FROM python:3.11-alpine AS app RUN apk update && apk add make automake gcc g++ subversion python3-dev gfortran openblas-dev RUN pip install --upgrade pip WORKDIR /srv When I connect to my container and I launch: pip install pyqt5 I got error: $ pip install pyqt5 Collecting pyqt5 Using cached PyQ...
The PyQt5 Pypi project requires that qmake can be found (emphasis mine): pip will also build and install the bindings from the sdist package but Qt’s qmake tool must be on PATH. This can be done by installing e.g. qt5-qtbase-dev, potentially together with other packages. Then the qmake command can be found in the pat...
3
2
76,217,754
2023-5-10
https://stackoverflow.com/questions/76217754/how-to-process-multiple-input-yaml-json-from-s3-using-nextflow-dsl2
I need to process over 1k samples with the nextflow (dsl2) pipeline in aws batch. current version of the workflow process single input per run. I'm looking workflow syntax (map tuple to iterate) to process multiple inputs to run in parralel. The inputs should be in json or yaml format, path to the input files are uniqu...
With channels it is possible to process any number of samples, including just one. Here's one way that use modules to handle both BAM and CRAM inputs. Note that each process below expects an input tuple where the first element is a sample name or key. To greatly assist with being able to merge channels downstream, we s...
3
2
76,266,682
2023-5-16
https://stackoverflow.com/questions/76266682/how-to-raise-custom-exceptions-in-a-fastapi-middleware
I have a simple FastAPI setup with a custom middleware class inherited from BaseHTTPMiddleware. Inside this middleware class, I need to terminate the execution flow under certain conditions. So, I created a custom exception class named CustomError and raised the exception. from fastapi import FastAPI, Request from star...
The obvious way would be to raise an HTTPException; however, in a FastAPI/Starlette middleware, this wouldn't work, leading to Exception in ASGI application error on server side, and hence, an Internal Server Error would be returned to the client. Option 1 - Using middleware and try/except block You could use a try/exc...
3
3
76,263,712
2023-5-16
https://stackoverflow.com/questions/76263712/streamlit-change-button-size-in-python
I have a program with an expander next to a button, but the button is smaller than the expander, and it bothers me a little. Is it possible to make the button bigger/make the expander's height smaller in only python. I have found solutions online using css, but I am just using python for my code. Here is my code if any...
You can use st.markdown(css, unsafe_allow_html=True) directly inside the Python code: import streamlit as st st.markdown( """ <style> button { height: auto; padding-top: 10px !important; padding-bottom: 10px !important; } </style> """, unsafe_allow_html=True, ) instructionCol, buttonCol = st.columns([4,1]) with instruc...
3
4
76,249,666
2023-5-14
https://stackoverflow.com/questions/76249666/streamlit-with-poetry-is-not-found-when-run-my-docker-container
Solved According to this: https://stackoverflow.com/a/57886655/15537469 and to this: https://stackoverflow.com/a/74918400/15537469 I make a Multi-stage Docker build with Poetry and venv FROM python:3.10-buster as py-build RUN apt-get update && apt-get install -y \ build-essential \ curl \ software-properties-common \ &...
With poetry config virtualenvs.in-project true poetry will create a virtual environment in the .venv directory and install all it's dependencies in it. The typical approach is to activate a virtual environment before using it. Typically this is done with the .venv/bin/activate (or with poetry run / poetry shell). E.g. ...
3
3
76,262,205
2023-5-16
https://stackoverflow.com/questions/76262205/error-upgrading-pip-errno2-no-such-file-or-directory
I am trying to upgrade pip by doing: pip install --upgrade pip And I got: Defaulting to user installation because normal site-packages is not writeable Requirement already satisfied: pip in /home/VICOMTECH/bdacosta/.local/lib/python3.8/site-packages (22.0.4) Collecting pip Using cached pip-23.1.2-py3-none-any.whl (2.1...
The problem was due because there were two versions of pip in the site-packages. In the folder /home/mypersonal/path/.local/lib/python3.8/site-packages/ weirdly there were: pip-23.1.2.dist-info (correct and up-to-date) pip-22.0.4.dist-info (root of the problem). I just removed the second one and everything started to...
3
2
76,257,827
2023-5-15
https://stackoverflow.com/questions/76257827/sqlalchemy-isnt-batching-rows-using-server-side-cursor-via-yield-per
Following documentation, and the code snippet provided from https://docs.sqlalchemy.org/en/14/core/connections.html#streaming-with-a-fixed-buffer-via-yield-per (posted directly below), my query is not being batched into 50_000 rows. with engine.connect() as conn: result = conn.execution_options(yield_per=100).execute(t...
The yield_per argument was having no effect in execute_options. In the example query snippets I posted in my question, fetchone() gets called N times, where N is the query result's row count. I discovered these fetchone() calls by getting the traceback from doing ctrl-C during an execution. That's a lot of server calls...
3
2
76,240,311
2023-5-12
https://stackoverflow.com/questions/76240311/visualization-of-descending-count
I have a dataframe that looks like this: components non_breaking_count breaking_count 0 paths-modified 22956 8640 1 endpoints-modified 22155 8149 2 endpoints-added 8109 5354 3 paths-added 7375 4787 4 info-version 5680 857 5 components-schemas-added 2555 1597 6 info-description 1940 762 7 tags-added 1031 564 8 info-tit...
I think there are several challenges here: amount of categories extreme value difference Bar plots (either horizontal or polar) handle numerous categories well but it's not always easy to deal with the extreme value difference. Additionally using a log axis with the bar plot could provide a useful visualization. A do...
3
3
76,241,352
2023-5-13
https://stackoverflow.com/questions/76241352/how-to-resolve-no-qt-platform-plugin-could-be-initialized-for-a-qt5-applicatio
I am working on a python application based on PyQt5. Everything was running good until I redo my PC and reinstall windows again because of some issue. I had copied my environment and after reinstalling Anaconda, I copied that environment again in env folder. Now the problem is that, when I run my code in PyCharm IDE, i...
Updated Answer to this question Answer Reference To add PyQt5's library path to your PATH environment variable: 1. Open the Edit Environment Variables dialog. 2. Select the appropriate Path variable (either User or System variables). (Note: I have changed in system variables) 3. Edit the variable and add the PyQt5 libr...
6
1
76,260,479
2023-5-16
https://stackoverflow.com/questions/76260479/hex-to-decimal-conversion-with-nan-values
I am trying to convert a Pandas dataframe column data['hexValues'] consisting of hex values to decimal. data["decValues"] = data.apply(lambda row: int(str(row["hexValues"]), 16), axis=1) This works but the column hexValues look like this 0 FF 1 F 2 nan 3 nan 4 FFFF 5 FFFF 6 F 7 F 8 F 9 F 10 FF 11 nan 12 nan I want to...
If nans are missing values use: data["decValues"] = [int(x, 16) if pd.notna(x) else np.nan for x in data["hexValues"]] More general solution with try-except: def test(x): try: return int(x, 16) except ValueError: return np.nan data["decValues"] = data["hexValues"].apply(test)
3
1
76,250,688
2023-5-15
https://stackoverflow.com/questions/76250688/webdriverexception-unhandled-inspector-error-no-node-with-given-id-found-at-a
I have written a Python script using Selenium and ChromeDriver to scrape data. The script navigates through several pages and clicks on various buttons to retrieve the data. However, I am encountering the following error: WebDriverException: Message: unknown error: unhandled inspector error: {"code":-32000,"message":"N...
This appears to be a defect with the recent ChromeDriver v113: https://bugs.chromium.org/p/chromedriver/issues/detail?id=4440 It appears currently this is the most likely suspect: it happens when the element being interacted with has been determined as stale by Chromedriver It looks like due to a defect, WebDriver is...
5
10
76,217,781
2023-5-10
https://stackoverflow.com/questions/76217781/how-to-continue-training-with-huggingface-trainer
When training a model with Huggingface Trainer object, e.g. from https://www.kaggle.com/code/alvations/neural-plasticity-bert2bert-on-wmt14 from transformers import Seq2SeqTrainer, Seq2SeqTrainingArguments import os os.environ["WANDB_DISABLED"] = "true" batch_size = 2 # set training arguments - these params are not rea...
If your use-case is about adjusting a somewhat-trained model then it can be solved just the same way as fine-tuning. To this end, you pass the current model state along with a new parameter config to the Trainer object in PyTorch API. I would say, this is canonical :-) The code you proposed matches the general fine-tun...
5
5
76,240,871
2023-5-13
https://stackoverflow.com/questions/76240871/how-do-i-add-memory-to-retrievalqa-from-chain-type-or-how-do-i-add-a-custom-pr
How do i add memory to RetrievalQA.from_chain_type? or, how do I add a custom prompt to ConversationalRetrievalChain? For the past 2 weeks ive been trying to make a chatbot that can chat over documents (so not in just a semantic search/qa so with memory) but also with a custom prompt. I've tried every combination of al...
Here's a solution with ConversationalRetrievalChain, with memory and custom prompts, using the default 'stuff' chain type. There are two prompts that can be customized here. First, the prompt that condenses conversation history plus current user input (condense_question_prompt), and second, the prompt that instructs th...
17
5
76,228,791
2023-5-11
https://stackoverflow.com/questions/76228791/conda-23-3-1-what-shall-be-the-content-of-build-sh
I found grayskull for creating meta.yml files and I found this github action for publishing on conda. However, said github action require a build.sh file and according to the official guide such a file must contain "...the text exactly as shown:" $PYTHON setup.py install # Python command to install the script. Neverth...
I found a sort of answer triggered by the comment I received that pushed me in searching towards the right direction. I decided to share my learnings (that may not be 100% accurate) that I hope will give some insights on how the conda package machinery work. The way to go today (2023) is grayskull, that I mentioned als...
4
2
76,255,967
2023-5-15
https://stackoverflow.com/questions/76255967/is-there-a-way-to-inherit-a-class-only-if-a-runtime-flag-is-true-in-python
I would like to have an existing class A inherit B only if a runtime flag is turned on. Is this possible? Usually for these cases, I either Just have A inherit B by default, and not use B if that flag is False Create another class A_mod, that inherits from A and B, and use this class when that flag is true.
You can use a conditional expression when specifying the parent class class A(B if flag else object):
3
7
76,248,162
2023-5-14
https://stackoverflow.com/questions/76248162/weird-time-series-plots-when-adding-the-dates-on-the-x-axis
I'm trying to plot a time series on python using plotly, here is the result without the dates on the x-axis : And when I add the date : Here is a view of my table : {'sasdate': {4: Timestamp('1959-01-09 00:00:00'), 5: Timestamp('1959-01-12 00:00:00'), 6: Timestamp('1960-01-03 00:00:00'), 7: Timestamp('1960-01-06 00:0...
You dates are in the wrong format. They need to be YYYY-MM-DD rather than YYYY-DD-MM, e.g., swap '1959-01-09 00:00:00' to be '1959-09-01 00:00:00' as so on, and the plot will look as expected. If you don't want to do the conversion manually, you could use the datetime package and tell it the format of the date/time tha...
3
2
76,251,837
2023-5-15
https://stackoverflow.com/questions/76251837/default-values-for-typeddict
Let's consider I have the following TypedDict: class A(TypedDict): a: int b: int What is the best practice for setting default values for this class? I tried to add a constructor but it doesn't seem to work. class A(TypedDict): a: int b: int def __init__(self): TypedDict.__init__(self) a = 0 b = 1 EDIT: I don't want ...
TypedDict is only for specifying that a dict follows a certain layout, not an actual class. You can of course use a TypedDict to create an instance of that specific layout but it doesn't come with defaults. One possible solution is to add a factory method to the class. You could use this factory method instead to set d...
8
12
76,235,292
2023-5-12
https://stackoverflow.com/questions/76235292/setting-tags-during-model-logging-mlflow
I am logging the model using mlflow.sklearn.log_model(model, "my-model") and I want to set tags to the model during logging, I checked that this method does not allow to set tags, there is a mlflow.set_tags() method but it is tagging the run not the model. Does anyone know how to tag the model during logging? Thank y...
When using mlflow.sklearn.log_model you work with the experiment registry which is run-focused so only experiments and runs can be described and tagged. If you want to set tags on models, you need to work with the model registry. The solution I would recommend is to register the model when logging using registered_mode...
3
3
76,246,578
2023-5-14
https://stackoverflow.com/questions/76246578/module-numpy-has-no-attribute-warnings
I'm trying to reproduce this tutorial with my own data. I've a simple square grid of polygons: from shapely import wkt import pandas as pd import geopandas as gpd data_list = [ [0,51, wkt.loads("POLYGON ((-74816.7238 5017078.8988, -74716.7238 5017078.8988, -74716.7238 5016978.8988, -74816.7238 5016978.8988, -74816.7238...
It turns out that numpy.warnings is just a reference to the warnings built-in Python module, as I can see on my NumPy version: >>> import numpy as np >>> np.__version__ '1.21.5' >>> np.warnings <module 'warnings' from 'D:\\Anaconda3\\lib\\warnings.py'> So, one possible workaround for your problem, may be adding that r...
5
8
76,249,640
2023-5-14
https://stackoverflow.com/questions/76249640/python-import-error-undefined-symbol-for-custom-c-module
I've been experimenting with C modules in python and I've had no problems with compilation. However, when it comes to importing the module I receive this error message: >>> import _strrev Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: /path/to/my/module.so: undefined symbol: strrev ...
I can see that strrev is here, so I don't understand why it says that the symbol in undefined. Au contraire: you can see that strrev is not there -- U in nm output means undefined. The strrev appears to be a Windows thing, and you are not on Windows. There is no such symbol in GLIBC: $ nm -D /lib/x86_64-linux-gnu/lib...
3
1
76,246,837
2023-5-14
https://stackoverflow.com/questions/76246837/how-do-i-drop-and-change-dtype-in-a-pipeline-with-sklearn
I have some scraped data that needs some cleaning. After the cleaning, I want to create a "numerical and categorical pipelines" inside a ColumnTransformer such as: categorical_cols = df.select_dtypes(include='object').columns numerical_cols = df.select_dtypes(exclude='object').columns num_pipeline = Pipeline( steps=[ (...
Instead of making a list of columns beforehand you can use scikit-learn's make_column_selector to dynamically specify the columns that each transformer will be applied to. In your example: from sklearn.compose import make_column_selector as selector preprocessor = ColumnTransformer([ ('num_pipeline', num_pipeline, sele...
3
3
76,244,436
2023-5-13
https://stackoverflow.com/questions/76244436/regular-expression-matching-either-an-empty-string-or-a-string-in-a-given-set
I would like to match either "direction" (">" or "<") from a string like "->", "<==", "...". When the string contains no direction, I want to match "". More precisely, the equivalent Python expression would be: ">" if ">" in s else ("<" if "<" in s else "") I first came up with this simple regular expression: re.searc...
A simpler version of Andrej Kesely's solution: re.search('<|>|$', s)[0]
3
4
76,215,725
2023-5-10
https://stackoverflow.com/questions/76215725/python-script-file-missing-in-singularity-image
In AWS, created a docker image with a python script to print a string(basicprint.py) docker file: FROM python COPY ./basicprint.py ./ CMD ["python", "basicprint.py"] It works fine then saved docker image as .tgz file. copy that .tgz file in to my local. I converted docker image(.tgz) into singularity image by using si...
Note that you put your file under the very root. singularity removed your file during conversion and cleaning. Similar issues have been reported and are, in general, expected when working with containers. This slightly modified image FROM python:3.11-slim COPY ./basicprint.py ./ CMD ["ls"] demonstrates that the file l...
3
2
76,237,951
2023-5-12
https://stackoverflow.com/questions/76237951/i-made-a-model-using-jupyter-notebook-and-then-i-am-trying-to-deploy-the-model-u
I created a model and deployed using streamlit. I am running in a virtual environement and inspite of running pip install streamlit it is still not working. The following error is shown enter image description here The error that is shown is this Traceback (most recent call last): File "C:\Python39\lib\runpy.py", line ...
Did you try pip install altair
3
1
76,233,164
2023-5-12
https://stackoverflow.com/questions/76233164/how-to-add-hatches-to-histplot-bars-and-legend
I created a bar plot with hatches using seaborn. I was also able to add a legend that included the hatch styles, as shown in the MWE below: import matplotlib.pyplot as plt import seaborn as sns tips = sns.load_dataset("tips") hatches = ['\\\\', '//'] fig, ax = plt.subplots(figsize=(6,3)) sns.barplot(data=tips, x="day",...
The issue is ax1.get_legend_handles_labels() returns empty lists for seaborn.histplot. Refer to this answer. Use the explicit interface by adding ax=ax to seaborn.histplot(...). Use ax.get_legend().legend_handles (.legendHandles is deprecate) to get the handles for the legend, and add hatches with set_hatch(). ax.get_l...
3
3
76,222,239
2023-5-10
https://stackoverflow.com/questions/76222239/pip-install-gymnasiumbox2d-not-working-on-google-colab
I have been working with the gymnasium environment for some weeks now and I had no problems with it in Google Colab by using this command in the notebook: pip3 install gymnasium[box2d] However, without changing anything I try to run the command once again and it suddenly stopped installing Box2d properly. I get the fol...
I was running into the same problem. After some digging and quite a lot of trial and error, I was able to get it to work by first running pip install swig. I hope that helps.
9
36
76,238,080
2023-5-12
https://stackoverflow.com/questions/76238080/in-python-merge-two-dataframes-with-the-merge-key-of-one-dataframe-contained-in
I would like to merge two dataframes df1 and df2 in order to compare two values info 1 and info 2. The key to merge them is hidden in the name columns. Df1 is 'clean' as it has a first name column and a last name column. Df2, however, is tricky. There is only a name column and the names can be given in different ways. ...
You can use a double substring merge: import re pattern1 = '|'.join(map(re.escape, df1['FirstName'])) pattern2 = '|'.join(map(re.escape, df1['LastName'])) match1 = df2['Name'].str.extractall(f'(?P<FirstName>{pattern1})').droplevel(1) match2 = df2['Name'].str.extractall(f'(?P<LastName>{pattern2})').droplevel(1) out = df...
4
4
76,235,874
2023-5-12
https://stackoverflow.com/questions/76235874/downgrade-python-from-3-11-2-to-3-10-in-specifc-environment
I am using Python's virtual environment 'venv'. My current version is 3.11.2 I need to downgrade it. I have already tried the following steps: pip3 install python==3.10.10 and got the following error: ERROR: Could not find a version that satisfies the requirement python==3.10.10 (from versions: none) ERROR: No matchin...
To answer your question directly Try python.org. Head straight to https://www.python.org/downloads/ to download the distribution you want. If I am to guess what problem you are facing, here are some details When you are running your command prompt, make sure you know which python you are executing. Example: PS C:\Users...
8
2
76,234,354
2023-5-12
https://stackoverflow.com/questions/76234354/how-does-poetry-associate-a-project-to-its-virtual-environment
How does Poetry associate a project to its virtual environment in ~/.cache/pypoetry/virtualenvs? I can't find any link inside the project, e.g. grep -ie NKJBdMnE . returns nothing. poetry env info: Virtualenv Python: 3.10.11 Implementation: CPython Path: /home/lddpro/.cache/pypoetry/virtualenvs/lxxo-NKJBdMnE-py3.10 Exe...
The path to the virtual environment is generated on the fly. It is not stored anywhere. The 8 letters NKJBdMnE are a part of the SHA256 of the working directory of you project. If you move your project into a different directory, poetry will use a different virtual environment as the SHA256 will be different. You can s...
3
6
76,234,312
2023-5-12
https://stackoverflow.com/questions/76234312/importerror-cannot-import-name-is-categorical-from-pandas-api-types
I want to convert file1.hic file into .cool format using hic2cool, which is written in Python. I converted the files using command line: hic2cool convert file1.hic file1.cool -r 10000 Traceback: Traceback (most recent call last): File "/home/melchua/.local/bin/hic2cool", line 5, in <module> from hic2cool.__main__ impo...
The latest version of pandas 2.0.1 seems to not have is_categorical but instead it has is_categorical_dtype. Seems that in hic2cool, pandas version is not pinned to the one that has that. I suggest installing a previous version of pandas before the changes took place. Or install a newer version of cooler as they update...
5
4
76,233,950
2023-5-12
https://stackoverflow.com/questions/76233950/new-discord-username-system
so currently i have this python bot that when a user tries to store something the author name along with the discriminator('#') is stored as well return "**Hello** **" + message.author.name + "#" + message.author.discriminator + "** ** :wave: " so my question is when they remove the discriminator and apply the new user...
The Discord.py package will be updated sometime after discord applies the username system. For now, you can't use the new system as the developers of Discord.py need to see how the new system works before they implement changes. As for your question: You will have to update the Discord.py package when an update eventua...
4
4
76,231,723
2023-5-11
https://stackoverflow.com/questions/76231723/pyspark-pandas-vectorized-udfs
I am trying to convert this udf into this pandas udf, in order to avoid creating two pandas udfs. Convert this: @udf("string") def splitEmailUDF(email: str, position: int) -> str: return email.split("@")[position] into this in one pandas udf --- position ??? Datatype or something else! from pyspark.sql.functions impor...
Setup df.show() +------------+ | email| +------------+ | foo@bar.com| |baz@spam.com| +------------+ Define a wrapper function which takes email and pos as arguments and returns the underlying pandas udf function def split(email, pos): @F.pandas_udf('string') def _split(email: pd.Series) -> pd.Series: return email.str....
3
2
76,231,351
2023-5-11
https://stackoverflow.com/questions/76231351/how-to-apply-enum-nonmember
I was trying to come up with a use case for the new @enum.nonmember decorator in Python 3.11. The docs clearly mention it is a decorator meant to be applied to members. However, when I tried literally decorating a member directly: import enum class MyClass(enum.Enum): A = 1 B = 2 @enum.nonmember C = 3 this results in ...
You would use it like so: import enum class MyClass(enum.Enum): A = 1 B = 2 C = enum.nonmember(3) As far as I can tell, the only reason why it is called a decorator, is because of nested classes. Currently, class MyClass(enum.Enum): A = 1 B = 2 class MyNestedClass: pass makes MyClass.MyNestedClass into one of the mem...
7
9