eshangj/stackoverflow_q_and_a_sample huggingface dataset:
Question: I tried to add multiple functions to a messagebox in my program: from Tkinter import * from Tkinter import messagebox as msgbox *some code...* input1 = msgbox.askyesno.showwarning('title', 'blahblahblah') if input1 == 1: input2 = msgbox.askyesno.showwarning('title', 'blahblahblah') if input2 == 1: function()  But it shows me this error:  input1 = msgbox.askyesno.showwarning('title', 'blahblahblah') ^^^^^^^^^^^^^^^^^^^^^^^^^^^ AttributeError: 'function' object has no attribute 'showwarning'  I tried changing the order of the functions but it didn't help. Can anyone help??? EDIT: I got a comment saying it can't have multiple functions, so I guess i'll use VBS instead. Thanks for the help though! ANOTHER EDIT: I got it! I can just use this: title = "title" description = "blahblahblah" if MessageBox(description, title, MB_ICONWARNING | MB_YESNO) == IDNO: sys.exit(0) 

Answer: I think, you're getting the error because askyesno is already a function inside tkinter.messagebox, not a module or object. So when you write msgbox.askyesno.showwarning(...), you're trying to access .showwarning on a function, which doesn't make sense—hence the AttributeError. You need to call either askyesno or showwarning, depending on what you want the messagebox to do.
Question: I am trying to write code that produces a deck of cards. The deck is a 2D array that contains each card as an array. Each card array contains its card value as well as its suit, represented by the values 0 to 3. However, the code outputs this: [[ 1. 1.] ... [13. 1.] [ 1. 1.] ... [13. 1.] [ 1. 2.] ... [13. 2.] [ 1. 3.] ... [13. 3.]]  The first 13 indecies are my issue here, as the code I have written I believe should output [1. 0.] up until [13. 0.] My code is designed to have 13 of each suit, increasing from 1 to 13 (inclusive). Index 0 of each card represents the card value, Ace to King. Index 1 represents its suit (0=S,1=H,2=C,3=D). suits = 4 suitsize = np.empty(shape=(13,2)) suitsize[:,0] = np.arange(1,suitsize.shape[0]+1) a = suitsize print(suitsize) for i in range(1,suits): a[:,1] = i suitsize = np.concatenate([suitsize,a]) print(suitsize)  Whether I use np.empty, or np.zeros, the first 13 indecies all still have their index 1 value (suit) replaced with 1. This means that I end up producing a deck of cards with 0 spades, 26 hearts, 13 clubs, and 13 diamonds. If anyone could explain to me what is happening here or a fix, please let me know. Thank you!

Answer: You have a classic NumPy issue — mutable arrays. The problem is that when you write a = suitsize, you're not creating a new copy of the array. You're just making a new reference to the same array in the computer's memory. So when you do a[:,1] = i, you're also modifying suitsize at the same time. You need to create an actual copy of the array, not just a reference. Just change this line a = suitsize to a = suitsize.copy() .
Question: Problem Suppose we have a python Enum where values are of type functools.partial. How to pickle and unpickle a member of that enum ? import pickle from enum import Enum from functools import partial def function_a(): pass class EnumOfPartials(Enum): FUNCTION_A = partial(function_a) if __name__ == "__main__": with open("test.pkl", "wb") as f: pickle.dump(EnumOfPartials.FUNCTION_A, f) with open("test.pkl", "rb") as f: pickle.load(f)  The code above tries to pickle and unpickle such an object. The pickle.load operations results in error: ValueError: functools.partial(<function function_a at 0x7f5973e804a0>) is not a valid EnumOfPartials  Motivation The object in itself is useful for configurations purposes: using hydra, I can have a parameter in a YAML that corresponds to the choice of a function in the enum. The reason for using partial is so that FUNCTION_A does not get interpreted as a method (see this question). Being able to pickle a member of this enum is desirable to be able to send it to another process. Given my use case, an obvious workaround would be to have a dictionary of functions indexed by an enum, but I would prefer directly having the relevant value (the function) in the enum. Note I am using python 3.11.11.

Answer: The first answer is to pickle by name: from enum import Enum, pickle_by_enum_name class EnumDefs(Enum): __reduce_ex__ = pickle_by_enum_name  The second answer is to use the new member class/decorator to avoid using partial, and to add __call__ so you can actually invoke the members: import pickle from enum import Enum, member, pickle_by_enum_name def function_a(): print('function a()!') class EnumOfFunctions(Enum): # __reduce_ex__ = pickle_by_enum_name # def __call__(self, *args, **kwds): return self._value_(*args, **kwds) # FUNCTION_A = member(function_a) if __name__ == "__main__": with open("test.pkl", "wb") as f: pickle.dump(EnumOfFunctions.FUNCTION_A, f) with open("test.pkl", "rb") as f: func = pickle.load(f) print(func) func()  Note that you could also just have the functions themselves be in the enum: class EnumOfFunctions(Enum): . . . # @member def function_a(): print('function a()!')   1 Disclosure: I am the author of the Python stdlib Enum, the enum34 backport, and the Advanced Enumeration (aenum) library.
Question: I am making a python hangman game using tkinter. However, after guessing a correct letter, it continues to accept that letter but marking it as wrong. This is my guess function: def guess_letter(self, event=None): guess = self.entry.get().lower() self.entry.delete(0, tk.END) if not guess or len(guess) != 1 or not guess.isalpha() return self.guessed_letters.add(guess) self.guessed_label.config(text="Guessed Letters: " + ", ".join(sorted(self.guessed_letters))) if guess in self.word: for i, letter in enumerate(self.word): if letter == guess: self.display_word[i] = guess self.word_label.config(text=" ".join(self.display_word)) else: self.tries_left -= 1 self.draw_hangman() if "_" not in self.display_word: messagebox.showinfo("Hangman", "You won!") self.master.quit() elif self.tries_left == 0: messagebox.showinfo("Hangman", f"You lost! The word was: {''.join(self.word)}") self.master.quit()  I want it only to register guesses as wrong if they have not been guessed before. What is a method I could use to make it not accept an already guessed letter without any repercussions?

Answer: I have a fix. I have replaced:  if not guess or len(guess) != 1 or not guess.isalpha(): return  With:  if not guess or len(guess) != 1 or not guess.isalpha() or guess in self.guessed_letters: return  This checks if a letter has already been guessed, and doesn't take away lives if it has.
Question: I'm using tqdm to track the progress of a task. For the fun of it, I want to change the color of the progress bar dynamically during each iteration. I know you can update the description of the bar using set_description(), but I haven’t found anything similar for changing the color of the progress bar. Is there a way to do that with tqdm? Something along the lines of this (pseudo-code): from tqdm import tqdm import time colors = ["red", "yellow", "green", "cyan", "blue"] pbar = tqdm(range(5)) for i in pbar: pbar.set_color(colors[i]) time.sleep(0.5) 

Answer: You can manually set the tqdm object's colour attribute: from tqdm import tqdm import time colors = iter(["red", "yellow", "green", "cyan", "blue"]) pbar = tqdm(range(5)) for i in pbar: pbar.colour = next(colors) time.sleep(0.5)
Question: I've a simple FastAPI project. It is running correctly in pycharm and in the docker container. When running via nginx, the StaticFiles are not delivered. Structure is like this: ├── app │ ├── main.py │ ├── static_stuff │ │ └── styles.css │ └── templates │ └── item.html ├── Dockerfile ├── requirements.txt  main.py from fastapi import Request, FastAPI from fastapi.responses import HTMLResponse from fastapi.staticfiles import StaticFiles from fastapi.templating import Jinja2Templates import os.path as path ROOT_PATH = path.abspath(path.join(__file__ ,"../")) app = FastAPI(title="my_app", root_path='/my_app') app.mount("/static_stuff", StaticFiles(directory=f"/{ROOT_PATH}/static_stuff"), name="static") templates = Jinja2Templates(directory=f"/{ROOT_PATH}/templates") @app.get("/items/{id}", response_class=HTMLResponse, include_in_schema=False) async def read_item(request: Request, id: str): return templates.TemplateResponse( request=request, name="item.html", context={"id": id} )  The application is running in a docker container: Dockerfile: FROM python:3.13-slim WORKDIR /my_app COPY requirements.txt ./ RUN pip install --no-cache-dir -r requirements.txt COPY app ./app CMD ["gunicorn", "-k", "uvicorn.workers.UvicornWorker", "app.main:app", "--bind", "0.0.0.0:6543"] EXPOSE 6543  The nginx configuration looks like this: location /my_app { proxy_pass http://my_host:6543; include proxy_params; }  When calling the nginx -> http://my_host/my_app/items/5 Everything works except the staticfiles. The styles.css is not found. What am I doing wrong? I tried something like this, but I had no success location ~ /static_stuff/(.+) { proxy_pass http://my_host:6543; include proxy_params; } 

Answer: It seems like there is a bug in FastAPI with root_path parameter for mounted paths. If you specify root_path as a parameter of __init__ it expects additional my_app/ in path. So, your files are available on /my_app/my_app/static_stuff/ instead of /my_app/static_stuff/. Try specifying root_path as an argument of server (e.g. uvicorn main:app --root-path my_app for uvicorn) instead of passing it as a parameter of __init__.
Question: I'm trying to build a CAD model of a bolt, but I can't figure out how to cut off the tops of the corners at the top of the head at a 45-degree angle. I want to get this result  What did I do for this? At first I tried this: import cadquery as cq from math import sqrt, tan, radians head_diameter = 10.0 head_height = 5.0 shaft_diameter = 5.0 shaft_length = 20.0 R = head_diameter / 2 r = R * sqrt(3)/2 chamfer_size = (R - r) / tan(45) bolt_head = ( cq.Workplane("XY") .polygon(6, 2*R) .extrude(head_height) .translate((0, 0, -1 * (head_height/2))) ) bolt_head = bolt_head.edges("Z").chamfer(1) bolt_shaft = ( cq.Workplane("XY") .circle(shaft_diameter/2) .extrude(-shaft_length) ) bolt = bolt_head.union(bolt_shaft)  This code generates the following CAD:  Then so: import cadquery as cq from math import sqrt, tan, radians HEAD_DIAMETER = 20.0 HEAD_HEIGHT = 10.0 CUT_ANGLE = 45.0 SHAFT_DIAMETER = 8.0 SHAFT_LENGTH = 30.0 R = HEAD_DIAMETER / 2 r = R * sqrt(3)/2 cut_depth = (R - r) / tan(radians(CUT_ANGLE)) hexagon = ( cq.Workplane("XY") .polygon(6, HEAD_DIAMETER) .extrude(HEAD_HEIGHT + cut_depth) ) cutter = ( cq.Workplane("XY") .workplane(offset=HEAD_HEIGHT) .circle(r) .workplane(offset=cut_depth) .circle(R * 1.1) .loft(combine=True) ) result = hexagon.cut(cutter) result = ( result.faces(">Z") .workplane(centerOption="CenterOfMass") .circle(r) .cutBlind(-cut_depth) ) show_object(result)  But it outputs an error: ValueError: If multiple objects selected, they all must be planar faces.  This code generates the following CAD:  Does anyone know how to cut off the upper parts of the corners of the bolt head at a 45 degree angle?

Answer: You can cut the upper edge by using a solid of revolution: create a triangle with the required angle and revolve it around the bolt axis to create the cutter. cutter = ( cq.Workplane("XZ") .workplane(offset=HEAD_HEIGHT) .move(r, 0) .lineTo(R*1.1, 0).lineTo(R*1.1, -cut_depth).lineTo(r, 0) .wire() .revolve() )
Question: I have a script for my USB that i need to use on multiple devices, and i want it to auto-eject, and using this method, as long as it has elevated privileges it runs, no issues, no errors, but i check the file explorer and the USB is still in there:  p = Popen(["diskpart"], stdin=PIPE) p.stdin.write(b"select disk " + drive_letter.encode() + b"\n") p.stdin.write(b"remove all dismount\n") p.stdin.write(b"exit\n") print(f"Successfully ejected drive {successful_drive_path}.")  this is all using sub-process module for python, I know I don't need to do this, but I still want to. I suspect it's due to the code being ran in the usb, so maybe i could, with the bat file i use to run and handle everything, run the ejection code using a self-deleting script in the main disk. Idk just ideas.

Answer: I believe the issue is that you are call it as a disk, not a volume. This code will fix your issue, but only works with elevated privileges:  def eject_drive(drive_letter=input(): try: p = subprocess.Popen(["diskpart"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) # Prepare the diskpart script commands = f""" select volume {drive_letter} remove all dismount exit """ # Send the commands stdout, stderr = p.communicate(commands) if p.returncode == 0: print(f"Successfully ejected drive {drive_letter}.") else: print(f"Failed to eject drive {drive_letter}. Error: {stderr}") except Exception as e: print(f"Exception occurred: {e}")
Question: I have this example Polars DataFrame: import polars as pl df = pl.DataFrame({ "id": [1, 2, 3, 4, 5], "variable1": [15, None, 5, 10, 20], "variable2": [40, 30, 50, 10, None], })  I'm trying to filter all columns of my dataframe using the method pl.all(), and I also tried using pl.any_horizontal() == Condition. However I'm getting the following error: ComputeError: The predicate passed to 'LazyFrame.filter' expanded to multiple expressions: col("id").is_not_null(), col("variable1").is_not_null(), col("variable2").is_not_null(), This is ambiguous. Try to combine the predicates with the 'all' or `any' expression.  Here are my attemps to try to face this. # Attempt 1: ( df .filter( pl.all().is_not_null() ) ) # Attempt 2: ( df .filter( pl.any_horizontal().is_not_null() ) )  Desired output, but it's not scalable for bigger DataFrames: ( df .filter( pl.col("variable1").is_not_null(), pl.col("variable2").is_not_null() ) )  How can I filter all columns in a scalable way without specifying each column individually?

Answer: You need to collapse the multiple-generated-expressions (imagine three matrices come out of that first pl.all(), one for each column) into a single column. You can do that with pl.all_horizontal(your, columns, here): >>> df.filter(pl.all_horizontal(pl.col('*').is_not_null())) shape: (3, 3) ┌─────┬───────────┬───────────┐ │ id ┆ variable1 ┆ variable2 │ │ --- ┆ --- ┆ --- │ │ i64 ┆ i64 ┆ i64 │ ╞═════╪═══════════╪═══════════╡ │ 1 ┆ 15 ┆ 40 │ │ 3 ┆ 5 ┆ 50 │ │ 4 ┆ 10 ┆ 10 │ └─────┴───────────┴───────────┘
Question: I have this simple script: import os import gradio as gr from fastapi import FastAPI, Request import uvicorn import threading from typing import List from datetime import datetime api = FastAPI() # Shared logs class Log(): def __init__(self): self._logs: List[str] = [] self.logstr="" def log_message(self,msg: str): timestamp = datetime.now().strftime("%H:%M:%S") self._logs.append(f"[{timestamp}] {msg}") self.logstr="\n".join(self._logs) log = Log() log_state=gr.State(log) # === FastAPI Setup === @api.post("/log") async def receive_log(request: Request): data = await request.body() msg = f"API received: {data}" log.log_message(msg) gr.update(value=log.logstr) return {"status": "logged", "message": msg} def run_api(): api_port = int(os.environ.get("API_PORT", 8000)) uvicorn.run(api, host="0.0.0.0", port=api_port) # === Gradio UI === with gr.Blocks() as ui: gr.Markdown("## 📝 Incoming HTTP Requests") log_box = gr.Textbox(label="Logs", inputs=log_state, lines=20) # Trigger the refresh when the log state is updated def run_gradio(): gradio_port = int(os.environ.get("GRADIO_PORT", 7860)) ui.launch(server_port=gradio_port) # === Start Both === if __name__ == "__main__": threading.Thread(target=run_api, daemon=True).start() run_gradio()  What I try to achieve is to have FastAPI listening to one port and a admin panel into another one, that displays in realtime the incomming requests: POST /log -> FastAPI ->common_log -> Gradio  But I am unable to change the contents of Textbox when I receive Incomming requests in FastAPI. How I can do this?

Answer: Only method which works for me is def function(): return log.logstr Textbox(value=function, ..., every=1)  It runs function every 1 second, and this function returns current content in log. Doc: Gradio Textbox  Full code: import os import gradio as gr from fastapi import FastAPI, Request import uvicorn import threading from typing import List from datetime import datetime api = FastAPI() # Shared logs class Log(): def __init__(self): self._logs: List[str] = [] self.logstr="" def log_message(self,msg: str): timestamp = datetime.now().strftime("%H:%M:%S") self._logs.append(f"[{timestamp}] {msg}") self.logstr="\n".join(self._logs) log = Log() log_state = gr.State(log) # === FastAPI Setup === @api.post("/log") async def receive_log(request: Request): data = await request.body() msg = f"API received: {data}" log.log_message(msg) gr.update(value=log.logstr) #print('data:', data) return {"status": "logged", "message": msg} def run_api(): #print('run FastAPI') api_port = int(os.environ.get("API_PORT", 8000)) uvicorn.run(api, host="0.0.0.0", port=api_port) # === Gradio UI === def get_logs(): #print('run: get_logs') return log.logstr with gr.Blocks() as ui: gr.Markdown("## 📝 Incoming HTTP Requests") log_box = gr.Textbox(label="Logs", value=get_logs, lines=20, every=1) # Trigger the refresh when the log state is updated def run_gradio(): gradio_port = int(os.environ.get("GRADIO_PORT", 7860)) ui.launch(server_port=gradio_port) # === Start Both === if __name__ == "__main__": threading.Thread(target=run_api, daemon=True).start() run_gradio()
Question: I created a table ("DataGrid") using: ui.output_data_frame("grid")  which I filled using @render.data_frame def grid(): df = ... return render.DataGrid(df, selection_mode="row")  Now, I want to change the selection using codfe. Is this possible in Python's version of Shiny?

Answer: You can use update_cell_selection(): from shiny import ui, render, App, reactive import pandas as pd df = pd.DataFrame({"Row": ["Row Number 0", "Row Number 1", "Row Number 2"]}) app_ui = ui.page_fluid( ui.input_select( "rowSelection", "Which row shall be selected?", choices=["Choose", 0, 1, 2] ), ui.output_data_frame("my_df") ) def server(input, output, session): @render.data_frame def my_df(): return render.DataGrid(df, selection_mode="row") @reactive.Effect @reactive.event(input.rowSelection) async def setSelection(): if (input.rowSelection() == "Choose"): return x={'type': 'row', 'rows': int(input.rowSelection())} await my_df.update_cell_selection(x) app = App(app_ui, server)
Question: I have this pydantic model with a field, and this field could be either an int or a non numeric value like a str or list. from pydantic import BaseModel, Field class Foo(BaseModel): bar: str | list | int = Field('some string', ge=2)  I want it to be that the constraint ge=2 is applied only if the value given to bar happens to be an int. foo_instance = Foo(bar='asdf') # constraint should not be applied foo_instance = Foo(bar=4) # constraint should be applied  Trying the above throws an error: TypeError: Unable to apply constraint 'ge' to supplied value asdf How do I ensure pydantic only tries to apply this constraint if the value is numerical (or if the operation can be performed on this value)?

Answer: You can apply the validator to just the int value like so: from pydantic import BaseModel, Field from typing import Annotated class Foo(BaseModel): bar: str | list | Annotated[int, Field(ge=2)] foo_instance = Foo(bar="asdf") foo_instance = Foo(bar=4)
Question: I'm trying to create a double bar stacked bar chart using plotly. I found this code: from plotly import graph_objects as go data = { "original":[15, 23, 32, 10, 23], "model_1": [4, 8, 18, 6, 0], "model_2": [11, 18, 18, 0, 20], "labels": [ "feature", "question", "bug", "documentation", "maintenance" ] } fig = go.Figure( data=[ go.Bar( name="Original", x=data["labels"], y=data["original"], offsetgroup=0, ), go.Bar( name="Model 1", x=data["labels"], y=data["model_1"], offsetgroup=1, ), go.Bar( name="Model 2", x=data["labels"], y=data["model_2"], offsetgroup=1, base=data["model_1"], ) ], layout=go.Layout( title="Issue Types - Original and Models", yaxis_title="Number of Issues" ) )   Source: https://dev.to/fronkan/stacked-and-grouped-bar-charts-using-plotly-python-a4p This works, but I need to take it one step further if possible. I need the various models to able to appear on either side of each set of bars as I'm adding another parameter (yes on the left and no on the right). In the example, blue is always on the left bar and orange and/or green are always on the right. I'm looking for a way so that any of those colors could appear on both the left and right of a set of bars, but with different values. i.e. in the example feature has a blue bar count of 15, but maybe on the right side of feature blue has a value of 5.

Answer: you can use dynamic stacking with calculated base values and consistent color coding, maintaining exactly 10 bars -5 categories × 2 sides- while supporting variable component combinations per bar. also chekc this out stacked + grouped bar chart from plotly import graph_objects as go data = { "left": [ {"original": 15, "model_1": 4, "model_2": 11}, {"original": 23, "model_1": 8, "model_2": 18}, {"original": 32, "model_1": 18, "model_2": 18}, {"original": 10, "model_1": 6, "model_2": 0}, {"original": 23, "model_1": 0, "model_2": 20} ], "right": [ {"original": 7, "model_1": 3, "model_2": 5}, {"original": 12, "model_1": 6, "model_2": 8}, {"original": 15, "model_1": 8, "model_2": 10}, {"original": 5, "model_1": 4, "model_2": 0}, {"original": 10, "model_1": 2, "model_2": 12} ], "labels": [ "feature", "question", "bug", "documentation", "maintenance" ] } fig = go.Figure() colors = { "original": "#636EFA", "model_1": "#EF553B", "model_2": "#00CC96" } def add_stacked_bar(side, offset_group): side_data = data[side] for i, category in enumerate(data["labels"]): current_base = 0 for model_type in ["original", "model_1", "model_2"]: value = side_data[i].get(model_type, 0) if value > 0: fig.add_trace(go.Bar( name=f"{model_type.replace('_', ' ').title()} ({side.title()})", x=[category], y=[value], offsetgroup=offset_group, base=current_base, marker_color=colors[model_type], legendgroup=model_type, showlegend=(i == 0) )) current_base += value add_stacked_bar("left", 0) add_stacked_bar("right", 1) fig.update_layout( title="Issue Types - Original and Models", yaxis_title="Number of Issues", barmode='group', legend_title="Model Types", legend=dict( orientation="h", yanchor="bottom", y=1.02, xanchor="right", x=1 ) ) fig.show()