eshangj/stackoverflow_q_and_a_sample huggingface dataset:
Question: I want to make a tkinter-based GUI in a RaspberryPi. I need it to be on a fullscreen mode. I have the following script: from tkinter import * win = Tk() win.geometry("650x250") label = Label(win, text="Hello World!", font=('Times New Roman bold', 20)) label.pack(padx=10, pady=10) # Utiliza wm_attributes para establecer el modo fullscreen win.wm_attributes('-fullscreen', 'true') win.mainloop()  I know it will sound stupid, but it only works sometimes (as seen in images). Is there any way to update the necessary libraries or similar? What options do I have?   I've been using tkinter for a year and never had such a problem, but I always worked with the 32-bit Raspi OS. Due to a library I need, I must stay with the 64-bit OS. Thanks!

Answer: As a workaround try to make the application fullscreen after some time, e.g.: Instead: win.wm_attributes('-fullscreen', 'true')  try: win.after(1000, lambda: win.wm_attributes('-fullscreen', 'true'))
Question: Here's a Python program which does the following:  Makes an API call to treasury.gov to retrieve data Stores the data in a Pandas dataframe Plots the data  import requests import pandas as pd import matplotlib.pyplot as plt page_size = 10000 url = 'https://api.fiscaldata.treasury.gov/services/api/fiscal_service/v2/accounting/od/debt_to_penny' url_params = f'?page[size]={page_size}' response = requests.get(url + url_params) result_json = response.json() df = pd.DataFrame(result_json['data']) df['record_date'] = pd.to_datetime(df['record_date']) rows = df[df['debt_held_public_amt'] != 'null'] rows['debt_held_public_amt'] = pd.to_numeric(rows['debt_held_public_amt']) plt.ion() rows.plot(x='record_date', y='debt_held_public_amt', kind='line', rot=90)  Here's the resulting chart that I get:  Question The debt_held_public_amt is in U.S. dollars:  What's a good way to format the y-axis as trillions of U.S. dollars?

Answer: I looked around for someone who did this in a nice looking way, and I found this graph on Wikipedia. I decided to do that. First, I converted the amount to a number. I found that your code for doing this conversion didn't work for me - it created a SettingWithCopy warning. rows = df[df['debt_held_public_amt'] != 'null'].copy() rows['debt_held_public_amt'] = pd.to_numeric(rows['debt_held_public_amt'])  Next, I did a unit conversion, and set the tick format to put '$ T' around each number. rows['debt_held_public_amt_tr'] = rows['debt_held_public_amt'] / 1e12 ax = rows.plot(x='record_date', y='debt_held_public_amt_tr', kind='line', rot=90) ax.yaxis.set_major_formatter('${x:.0f} T')  See also Dollar ticks from the matplotlib documentation.
Question: I want to change the fontsize of the label above an input widget in my streamlit app. What I have so far: import streamlit as st label = "Enter text here" st.text_input(label)  This renders the following:  I want to make the label "Enter text here" bigger. I know there are various ways to change fontsize in st.write(). So, I tried some of them:  the markdown headers syntax: st.write(f"# {label}") # <--- works st.text_input(f"# {label}") # <--- doesn't work   some CSS: s = f"<p style='font-size:20px;'>{label}</p>" st.markdown(s, unsafe_allow_html=True) # <--- works st.text_input(s) # <--- doesn't work    but as commented above, neither work. How do I make it work?

Answer: Option 1: Components API So did a little digging and it turns out that streamlit has a components API which can be used to render an html string. So we can basically use a little javascript to change the font size of a specific label. Since labels are unique for each widget, we can simply search for the paragraph element whose inner text that matches the label. A working example: label = "Enter text here" st.text_input(label) st.components.v1.html( f""" <script> var elems = window.parent.document.querySelectorAll('div[class*="stTextInput"] p'); var elem = Array.from(elems).find(x => x.innerText == '{label}'); elem.style.fontSize = '20px'; // the fontsize you want to set it to </script> """ )  It renders a field that looks like the following:  A convenience function that can be used to change font size, color and font family (you can actually add more as you wish): def change_label_style(label, font_size='12px', font_color='black', font_family='sans-serif'): html = f""" <script> var elems = window.parent.document.querySelectorAll('p'); var elem = Array.from(elems).find(x => x.innerText == '{label}'); elem.style.fontSize = '{font_size}'; elem.style.color = '{font_color}'; elem.style.fontFamily = '{font_family}'; </script> """ st.components.v1.html(html) label = "My text here" st.text_input(label) change_label_style(label, '20px')   Option 2: Latex text It turns out you can use LaTeX expressions, so I ended up using latex text in math mode because you can change font size using \Huge, \LARGE etc. in Latex. Since the default font in streamlit is sans-serif, I used \textsf{}. A working example: import streamlit as st st.text_input(r"$\textsf{\Large Enter text here}$")  which renders   The above uses \Large font size. The following is an example using all possible font size options: label = r''' $\textsf{ \Huge Text \huge Text \LARGE Text \Large Text \large Text \normalsize Text \small Text \footnotesize Text \scriptsize Text \tiny Text }$ ''' st.text_input(label)
Question: I was playing with Never type in mypy. If I have a function foo(x: int) I expected that when called with a value of type Never mypy would complain, but it silently typechecks the call: from typing import Never def foo(x: int): pass def bar(x: Never): foo(x) # ok, I exected a type error foo("foo") # err  --- edit --- Just for reference my solution to create a uninhabited type is this from abc import ABC, abstractmethod, final @final class Never(ABC): @abstractmethod def __init__(self) -> None: ... 

Answer: This is normal. Never is a subtype of every other type. After all, Never is the type with no values. All values of Never type are values of every other type, because there are no values of Never type.
Question: I am trying to work with time and timezones. I am in the US/Mountain time zone and my computer (Windows) is configured to that time zone. import datetime import zoneinfo utc = zoneinfo.ZoneInfo('UTC') mt = zoneinfo.ZoneInfo('US/Mountain') print(datetime.datetime.now()) print(datetime.datetime.now().astimezone(mt)) print(datetime.datetime.now().astimezone(utc)) # 2023-10-27 13:17:18.840857 # 2023-10-27 13:17:18.840857-06:00 # 2023-10-27 19:17:18.840857+00:00  The last line is the one that confuses me. I thought the code datetime.datetime.now() creates a timezone naive object, then astimezone(utc) converts it to a timezone aware object, but doesn't change the "value" of the time. But here you can see that astimezone(utc) causes 6 hours to be added to the value of the time, as if the time generated by datetime.datetime.now() was a mountain time object.

Answer: See the docs on astimezone:  Return a datetime object with new tzinfo attribute tz, adjusting the date and time data so the result is the same UTC time as self, but in tz’s local time. If provided, tz must be an instance of a tzinfo subclass, and its utcoffset() and dst() methods must not return None. If self is naive, it is presumed to represent time in the system timezone. ... If you merely want to attach a time zone object tz to a datetime dt without adjustment of date and time data, use dt.replace(tzinfo=tz). If you merely want to remove the time zone object from an aware datetime dt without conversion of date and time data, use dt.replace(tzinfo=None).  I get the expected behavior if I use replace: import datetime import zoneinfo utc = zoneinfo.ZoneInfo('UTC') mt = zoneinfo.ZoneInfo('US/Mountain') print(datetime.datetime.now()) print(datetime.datetime.now().replace(tzinfo=mt)) print(datetime.datetime.now().replace(tzinfo=utc)) # 2023-10-27 13:45:35.897159 # 2023-10-27 13:45:35.897159-06:00 # 2023-10-27 13:45:35.897159+00:00  What was happening in my code is that when I use astimezone() the datetime modules DOES infer a timezone from my system time and then uses that to convert the time to the SAME utc time. replace is the function to use to just "drop in" a timezone without making adjustments.
Question: I have a dataframe as follow:     armed signs_of_mental_illness count     gun False 628   gun True 155   knife False 142   vehicle False 104   knife True 84   metal pole True 1   metal rake True 1     I want to sort this dataframe as follow:     armed signs_of_mental_illness count     gun False 628   gun True 155   knife False 142   knife True 84     I tired armed_mental = focus_age_group.groupby(['armed', 'signs_of_mental_illness'])['id'].count().sort_values(ascending=False)  that had product above result. But I have difficulty getting what I want. The category (armed) with highest number(True + False) of should be on top of the dataframe. Then follow by True and False.

Answer: If you want to sort by the total per "armed", y first need to combine the counts with groupby.transform: import numpy as np order = np.lexsort([df['signs_of_mental_illness'], -df.groupby('armed')['count'].transform('sum')]) out = df.iloc[order]  Alternative: out = (df.assign(total=df.groupby('armed')['count'].transform('sum')) .sort_values(by=['total', 'signs_of_mental_illness'], ascending=[False, True]) .drop(columns='total') )  Output:  armed signs_of_mental_illness count 0 gun False 628 1 gun True 155 2 knife False 142 4 knife True 84 3 vehicle False 104 5 metal pole True 1 6 metal rake True 1
Question: I have a nested dataclasses that I would like to convert and save to the yaml format using the PyYaml library. The resultant YAML output contains YAML tags which I would like to remove. I have the following Python code: from dataclasses import dataclass import yaml @dataclass class Database: host: str username: str password: str @dataclass class Environment: name: str database: Database @dataclass class Config: environment: Environment database = Database(host="localhost", username="admin", password="secret") environment = Environment(name="local", database=database) config = Config(environment=environment) print(yaml.dump(config))  which produces the YAML output: !!python/object:__main__.Config environment: !!python/object:__main__.Environment database: !!python/object:__main__.Database host: localhost password: secret username: admin name: local  How can I produce a YAML output of nested dataclasses without the YAML tags included? The desired outcome should look something like: environment: database: host: localhost password: secret username: admin name: local 

Answer: When dumping instances of Python classes, PyYaml will serialize the contents and add a tag indicating the class in order to allow reading the yaml output back to the designated class. PyYaml does not tag native Python objects like lists and dicts, so by converting the dataclass instances to dictionaries with the asdict method the YAML dump will contain no tags: from dataclasses import dataclass, asdict import yaml @dataclass class Database: host: str username: str password: str @dataclass class Environment: name: str database: Database @dataclass class Config: environment: Environment database = Database(host="localhost", username="admin", password="secret") environment = Environment(name="local", database=database) config = Config(environment=environment) print(yaml.dump(asdict(config)))  The updated code above produces the following output: environment: database: host: localhost password: secret username: admin name: local
Question: I have a simple Python script that asks the user for an ID and returns a serial number: ... id = input("Enter ID (0-indexed):\n") ... print(serial_number)  I'm using this .py script inside of a larger bash script via command substitution: serial_number=$(./get_serial_no.py) echo "$serial_number"  The problem I'm facing is the following: since command substitution takes the entire output of the command as input, the input prompt inside the Python script is also stored in the serial_number variable and never gets displayed on screen (until the echo). Therefore, if I run the shell script, the console waits for input without giving me a prompt. Is there a way to separate the Python prompt from the value that I want returned via command substitution (i.e. the serial number)? The only things I can think of is either write the serial number to another file, or ask for input inside of the shell script and pass the ID as an option to the Python script.

Answer: I recommend against prompts if you are using a python script in a shell script. Use command-line options with a library such as argparse. It is so much easier, plus you get input validation as a bonus: import argparse parser.add_argument( '-s', '--serial_number', type = int, default = 12345, required = False, help = re.sub( r'\s+', r' ', '''Serial number (default: %(default)s)''')) options = parser.parse_args() print(optiions.serial_number)
Question: In VS Code, the latest Pylance extension (v2023.10.50) failed with this error:  TypeError: _0x2f33cc[(_0x1efd68(...) + _0x1efd68(...))] is not a function  (When I highlight on any line of code). I tried to delete some suspected libs but nothing happened.

Answer: The same error occurred when using Pylance v2023.10.50, and downgraded to v2023.10.40 and the problem was resolved.
Question: I'am using Pyinstaller package to build a python desktop app, however Pyinstaller seems to put the bundled exe file outside _internal folder is there a solution I can try ? Thanks in advance output by Pyinstaller _internal folder structure my goal is to package all the app in a folder (dist) that exe file must be inside _internal folder

Answer: From the update logs,on Pyinstaller's document:https://pyinstaller.org/en/stable/CHANGES.html#id2 it says:  Restructure onedir mode builds so that everything except the executable (and if you’re using external PYZ archive mode) are hidden inside a sub-directory. This sub-directory’s name defaults to but may be configured with a new --contents-directory option. Onefile applications and macOS bundles are unaffected. (#7713.pkg_internal.app)  It means: from the verison ,6.0.0, it will build with a dir named _interne,when you choose to build by onedir. So,a simple way to go back,is , make the version no bigger than 6.0.0.such as 5.13.2. It works well for me. Also ,from the github issue.Below: https://github.com/pyinstaller/pyinstaller/pull/7713 Pyinstall may give us a way to build exe file (use onedir),no create a dir named _interne.But,I can not find it. Sorry for that,English is not my mother tongue.I have tried my best to get the grammar correct.
Question: I'm using decimal module to avoid float rounding errors. In my case the values are money so I want two decimal places. To do that I do decimal.getcontext().prec = 2 but then I get some surprising results which make me think I'm missing something. In this code the first assertion works, but the second fails from decimal import getcontext, Decimal assert Decimal("3000") + Decimal("20") == 3020 getcontext().prec = 2 assert Decimal("3000") + Decimal("20") == 3020 # fails  Since 3000 and 20 are integers I was expecting this to hold, but I get 3000 instead. Any ideas on what is happening?

Answer: decimal does not implement fixed-point arithmetic directly. It implements base 10 floating-point arithmetic. The precision (prec) is the total number of significant digits retained and has nothing to do with the position of the radix point. Try displaying the computed value in your last example: >>> Decimal("3000") + Decimal("20") Decimal('3.0E+3')  The exact result (3020) is rounded back to the 2 (because you set prec to 2) most significant digits, so the trailing "20" is thrown away. If, e.g., you want 2 places after the decimal point, you'll have to arrange for that yourself. Search the docs for the question "Once I have valid two place inputs, how do I maintain that invariant throughout an application?".
Question: I've got a function that returns a tuple, and I need to check if a specific element is in the tuple. I don't know types of elements will be in the tuple, but I know that I want an exact match. For example, I want 1 in (1, [0, 6], 0) --> True 1 in ([1], 0, 6]) --> False  This should be really straightforward, right? I just check 1 in tuple_output_from_function. This breaks if there is a numpy array as an element in the tuple import numpy as np s = tuple((2, [0, 6], 1)) 4 in s --> False t = tuple((2, np.arrary([0, 6]), 1)) 4 in t --> ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()  I expect the second case to return False because 4 is not in the tuple. Even if it were in the array, I would still expect False. I can do 0 in t[1] without error. Why does this break, and how can I make my check robust to it without assuming that there will be a numpy array or having to check for it explicitly?

Answer: It breaks because if you in operator, Python under the hood is using the equality operator (==). Consider this: t = (2, np.array([0, 6]), 1) v = 1 print(v in t)  Python checks each value in the tuple t for equality. For numpy array the operation 1 == np.array([0, 6]) is another boolean array [False False]. Python then checks if this result is truthy, which throws the exception you see. You can use any() and check if the current value you check is the type of the value is int: t = (2, np.array([0, 6]), 1) v = 1 x = any(v == i for i in t if isinstance(i, int)) print(x)  Prints: True
Question: I have an existing python project and trying to debug in via Microsoft Visual Studio Code. Therefore I have the following launch.json: { "version": "0.2.0", "configurations": [ { "name": "Python: myproject", "type": "python", "request": "launch", "program": "E:\\<path>\\__main__.py", "cwd": "${workspaceFolder}", "env": {"PYTHONPATH": "${cwd}" }, "args": [ "publish", "--config=E:\\<path>\\config.yaml" ], } ] }  Unfortunately it runs up to one excpetion:  Exception has occurred: PackageNotFoundError No package metadata was found for myproject   importlib.metadata.PackageNotFoundError: No package metadata was found for myproject  I already tried  pip install importlib.metadata  But it doesn't help. The lines of code that are running the exception are in the return:  import atexit, copy, getopt, importlib.metadata, json, logging, os, re, signal, shutil, sys, textwrap, time, urllib . . . return importlib.metadata.version(package)  Using the interpreter:  Anyone could help how to fix this? Thanks in advance. Cheers

Answer: After additional research it was just an only the following command, that helped: pip install -e .  If someone has the same issue (the current project wasn't installed)
Question: I've some difficulty in matching what Numpy expects when performing the dot product and vector representation in linear algebra, in term of shapes. Let's say I've a matrix and two column vectors represented by Numpy arrays: import numpy as np A = np.array([[1,2], [3,1], [-5,2]]) x = np.array([[0], [2]]) y = np.array([[-2], [0], [3]])  and I want to compute Axꞏy, Ax being a matrix multiplication and ꞏ being the dot product. This doesn't work: # a = Axꞏy a = (A @ x).dot(y)   shapes (3,1) and (3,1) not aligned: 1 (dim 1) != 3 (dim 0)  Ax: [[4], [2], [4]]  is indeed a column vector and the dot product of the two column vectors is the scalar: -8+0+12=4, this is the result I'm expecting. What is the correct operation or reshaping required, using vectors as they are defined?

Answer: You can't compute a dot product between two (3, 1) arrays, a dot product A @ B is only valid if the shape of A and B are (n, k) and (k, m). It looks like you want: (A@x).T @ y  Output: [[4]] Or as scalar: ((A@x).T @ y).item()  Output: 4 NB. in the context of 2D arrays @ and dot are equivalent.  Other operations that would have been valid given the shapes: (A@x) @ y.T array([[-8, 0, 12], [-4, 0, 6], [-8, 0, 12]]) (A.T*x) @ y array([[0], [4]])
Question: I have a dataframe as below: Part Date Quantity A 2023-10-26 -1 A 2023-10-26 1 A 2023-11-03 1 A 2023-12-15 -1 B 2023-11-09 2 B 2023-11-14 -2 B 2023-11-14 2 B 2023-11-19 2  Each part is a cluster, and each date within a part is a sub-cluster. I want to order the Quantity values for each date for each part based on: positive values first. Result should be: Part Date Quantity A 2023-10-26 1 A 2023-10-26 -1 A 2023-11-03 1 A 2023-12-15 -1 B 2023-11-09 2 B 2023-11-14 2 B 2023-11-14 -2 B 2023-11-19 2  It is possible to use some sort of double groupby, or should I look for a different solution?

Answer: Use key parameter in DataFrame.sort_values with specify column Quantity for False for positive values by compare bySeries.lt or Series.le: out = df.sort_values(['Part', 'Date', 'Quantity'], key=lambda x: x.le(0) if x.name=='Quantity' else x) print (out) Part Date Quantity 1 A 2023-10-26 1 0 A 2023-10-26 -1 2 A 2023-11-03 1 3 A 2023-12-15 -1 4 B 2023-11-09 2 6 B 2023-11-14 2 5 B 2023-11-14 -2 7 B 2023-11-19 2
Question: Consider a FastAPI using the lifespan parameter like this: def lifespan(app): print('lifespan start') yield print('lifespan end') app = FastAPI(lifespan=lifespan)  Now I want to register a sub app with its own lifecycle functions: app.mount(mount_path, sub_app)  How can I register startup/shutdown handlers for the sub app? All solutions I could find either require control over the lifespan generator (which I don't have) or involve deprecated methods like add_event_handler (which doesn't work when lifespan is set).  Update Minimal reproducible example: from fastapi import FastAPI # --- main app --- def lifespan(_): print("startup") yield print("shutdown") app = FastAPI(lifespan=lifespan) @app.get("/") async def root(): return {"message": "Hello World"} # --- sub app --- sub_app = FastAPI() @sub_app.get("/") async def sub_root(): return {"message": "Hello Sub World"} app.mount("/sub", sub_app) app.on_event("startup")(lambda: print("sub startup")) # doesn't work app.on_event("shutdown")(lambda: print("sub shutdown")) # doesn't work  Run with: uvicorn my_app:app --port 8000

Answer: I found a solution, but I'm not sure if I like it... It accesses the existing lifespan generator via app.router.lifespan_context and wraps it with additional startup/shutdown commands: from contextlib import asynccontextmanager ... main_app_lifespan = app.router.lifespan_context @asynccontextmanager async def lifespan_wrapper(app): print("sub startup") async with main_app_lifespan(app) as maybe_state: yield maybe_state print("sub shutdown") app.router.lifespan_context = lifespan_wrapper  Output: INFO: Waiting for application startup. sub startup startup INFO: Application startup complete. ... INFO: Shutting down INFO: Waiting for application shutdown. shutdown sub shutdown INFO: Application shutdown complete.
Question: I have a list of lists and strings and would like to append the string elements into the list element directly before it. Below is a sample of the data. data = [['way','say','may','lay'], 'wake', ['hay','pay','yay'], 'lake', ['tay'], 'shake']  The desire output should be something like this: out = [['way','say','may','lay','wake'], ['hay','pay','yay','lake'], ['tay', 'shake']]  I have tried converting the list into a dataframe and use groupby and cumsum() however this seems to only partly solve my problem. Thanks!

Answer: You could zip together the odd and even parts of data and use list addition of those parts to build your desired output: out = [odd + [even] for odd, even in zip(data[0::2], data[1::2])]  Output: [ ['way', 'say', 'may', 'lay', 'wake'], ['hay', 'pay', 'yay', 'lake'], ['tay', 'shake'] ]