eshangj/stackoverflow_q_and_a_sample huggingface dataset:
Question: Let's say I have the following chunk of code: import matplotlib.pyplot as plt manager = plt.get_current_fig_manager() manager.full_screen_toggle() plt.show()  The screen is set to be in fullscreen mode. My issue is that the taskbar is being hidden. How do I adjust the fullscreen mode so that it doesn't hide my taskbar?

Answer: I usually use mng = plt.get_current_fig_manager() mng.frame.Maximize(True)  before the call to plt.show(), and I get a maximized window. This works for the 'wx' backend only. Or try this, wm = plt.get_current_fig_manager() wm.window.state('zoomed')
Question: In my book it says  Use class attributes to define properties that should have the same value for every class instance. Use instance attributes for properties that vary from one instance to another.  But then, in an example, the species class attribute is modified for miles as shown below: class Dog: species = "Canis familiaris" miles = Dog() snoopy = Dog() miles.species = "Felis silvestris"  That means that the species class attribute is not for the entire Dog class. Have I misunderstood something or is it simply normal to customise class attributes?

Answer:  Why is the class attribute being modified?  It isn't. miles is an instance of the Dog class, so assigning to miles.species creates an instance attribute.  That means that the species class attribute is not for the entire Dog class.  In the code you have shown, there are two things called species.  An attribute of the class Dog ("Canis familiaris"), which is unchanged for the whole program. An attribute of the instance miles ("Felis silvestris"), which only applies to miles, but not to the whole Dog class, nor to the snoopy instance.  Since snoopy doesn't have its own species instance attribute, accessing snoopy.species will fall back to Dog.species.
Question: Tkinter doesn't work, it throws an error. Installation: % pip3 install tk  My code: #!/usr/bin/env python3 import tkinter as tk  The error: Traceback (most recent call last): File "/Users/arghadip/Library/Application Support/CodeRunner/Unsaved/Untitled.py", line 4, in <module> import tkinter as tk File "/usr/local/Cellar/python@3.9/3.9.5/Frameworks/Python.framework/Versions/3.9/lib/python3.9/tkinter/__init__.py", line 37, in <module> import _tkinter # If this fails your Python may not be configured for Tk ModuleNotFoundError: No module named '_tkinter' 

Answer: For Python3 tkinter can be simply installed by, brew install python-tk  pip sometimes wont work successfully on my Mac, especially with the High Sierra OS version. Brew can be used to install all kinds of software packages in mac.
Question: I'm doing string formatting with tuples: a = (1,2,3) s = f"something in {a}" print(s)  'something in (1, 2, 3)'  Everything is fine until I encounter a single-element tuple, which gives: a = (1,) s = f"something in {a}"  'something in (1,)'  what I actually want is: 'something in (1)'  How do I make tuple string formatting behaves consistently and remove the trailing comma?

Answer: You could use your own formatting logic, e.g. a = (1,2,3) s = ','.join([str(x) for x in a]) print(s) # 1,2,3 a = (1,) s = ','.join([str(x) for x in a]) print(s) # 1
Question: I currently have code for a command that takes in a channel ID followed by some text message as input. The code then finds the channel and sends the message on it. However, Discord has just released a new thread feature, and currently, no update has been made to the official Discord API docs regarding how bots can interact with threads. So, how can a bot send messages to threads? Please leave down answers as new information is released by Discord. Here's the code I was talking about before: @bot.command() async def text(ctx, channel_id, *, msg): channel = bot.get_channel(int(channel_id)) try: await channel.send(ctx.message.attachments[0].url) except IndexError: pass await channel.trigger_typing() await channel.send(msg) 

Answer: Since discord.py 2.0, threads are supported with discord.Thread. get_thread method 1. Using the guild @bot.command() async def test(ctx): thread = ctx.guild.get_thread(thread_id)  There is also the method get_channel_or_thread which returns either a channel or a thread.  channel_or_thread = ctx.guild.get_channel_or_thread(channel_id)  2. Using the text channel @bot.command() async def test(ctx): thread = ctx.channel.get_thread(thread_id)   threads list 1. Using the guild @bot.command() async def test(ctx): threads = ctx.guild.threads  There is also the coroutine active_threads which returns all active threads which the bot can see  active_threads = await ctx.guild.active_threads()  2. Using the text channel @bot.command() async def test(ctx): threads = ctx.channel.threads  There is also the async iterator archived_threads that iterates over all archived threads in this text channel  async for thread in ctx.channel.archived_threads(): # ...
Question: I was expecting the Python match/case to have equal time access to each case, but seems like I was wrong. Any good explanation why? Lets use the following example: def match_case(decimal): match decimal: case '0': return "000" case '1': return "001" case '2': return "010" case '3': return "011" case '4': return "100" case '5': return "101" case '6': return "110" case '7': return "111" case _: return "NA"  And define a quick tool to measure the time: import time def measure_time(funcion): def measured_function(*args, **kwargs): init = time.time() c = funcion(*args, **kwargs) print(f"Input: {args[1]} Time: {time.time() - init}") return c return measured_function @measure_time def repeat(function, input): return [function(input) for i in range(10000000)]  If we run each 10000000 times each case, the times are the following: for i in range(8): repeat(match_case, str(i)) # Input: 0 Time: 2.458001136779785 # Input: 1 Time: 2.36093807220459 # Input: 2 Time: 2.6832823753356934 # Input: 3 Time: 2.9995620250701904 # Input: 4 Time: 3.5054492950439453 # Input: 5 Time: 3.815168857574463 # Input: 6 Time: 4.164452791213989 # Input: 7 Time: 4.857251167297363  Just wondering why the access times are different. Isn't this optimised with perhaps a lookup table?. Note that I'm not interested in other ways of having equals access times (i.e. with dictionaries).

Answer: The match/case statement introduced in PEP 622 offers a more elegant and readable approach to pattern matching compared to traditional if-elif-else chains. Its primary advantage lies in its ability to streamline complex conditional logic. Traditional approach def is_tuple(node): if isinstance(node, Node) and node.children == [LParen(), RParen()]: return True return (isinstance(node, Node) and len(node.children) == 3 and isinstance(node.children[0], Leaf) and isinstance(node.children[1], Node) and isinstance(node.children[2], Leaf) and node.children[0].value == "(" and node.children[2].value == ")")  Using match/case def is_tuple(node: Node) -> bool: match node: case Node(children=[LParen(), RParen()]): return True case Node(children=[Leaf(value="("), Node(), Leaf(value=")")]): return True case _: return False  While it may be equivalent to a dict lookup in the most primitive cases, in general it is not so. Case patterns are designed to look like normal python code but actually they conceal isinstance and len calls and don't execute what you'd expect to be executed when you see code like Node().  Essentially this is equivalent to a chain of if ... elif ... else statements. Note that unlike for the previously proposed switch statement, the pre-computed dispatch dictionary semantics does not apply here.
Question: I have two questions:  Why can't I mount two cloud secrets in the same directory? I have attempted to mount two secrets, FIREBASE_AUTH_SERVICE_ACCOUNT and PURCHASE_VALIDATION_SERVICE_ACCOUNT in the directory: flask_app/src/services/firebase/service_accounts/ However I get this error, when attempting to do this: spec.template.spec.containers[0].volume_mounts[1].mount_path, Duplicate volume mount paths are forbidden Why is this?  How do I access a mounted secret using python? I'm really not sure how to do this as I couldn't find any documentation on how to actually access the secret itself. This is the only thing I found. I am using python just for context. Would the secret be mounted as a .txt and is that mount path the folder that it is stored in or does it also specify the file name?  

Answer: With Cloud Run and Secret manager you can load a secret in 2 manners:  Load a secret in a environment variable, use --set-secrets=ENV_VAR_NAME=secretName:version Load a secret in a file, use --set-secrets=/path/to/file=secretName:version  Therefore, you can read a secret as you read  An environment variable (something like os.getenv()) A file (something like fs.open('/path/to/file','r'))  So, your first question about directory is not clear. If you mount 2 secrets in 2 files in the same directory, no problem! If it doesn't solve your question, please, clarify.
Question: I'm learning about Python packaging, and according to this guide, the command to build a python distribution package seems to be python3 -m build. But I aslo found that there is a command line interface for setup.py file from setuptools: $ python setup.py --help-commands Standard commands: build build everything needed to install sdist create a source distribution (tarball, zip file, etc.) bdist create a built (binary) distribution bdist_dumb create a "dumb" built distribution bdist_rpm create an RPM distribution ...  It seems that python setup.py build, sdist or bdist can aslo build distribution, but I didn't find detailed intructions for these commands, the setuptools command reference lacks explanation for build sdist bdist. So I'm a bit confused, what is the difference between python setup.py build and python -m build, or between python setup.py sdist and python -m build --sdist? Is the python setup.py command deprecated hence the lack of full documentation? When should I use python -m build or python setup.py build? Any help would be appreciated.  Update: The doc of build module says “build is roughly the equivalent of setup.py sdist bdist_wheel but with PEP 517 support, allowing use with projects that don’t use setuptools”. So should I always prefer build module rather than running python setup.py manually?. Is there still a use-case for setup.py build?

Answer: Citing Why you shouldn't invoke setup.py directly by Paul Ganssle.  The setuptools project has stopped maintaining all direct invocations of setup.py years ago, and distutils is deprecated. There are undoubtedly many ways that your setup.py-based system is broken today, even if it's not failing loudly or obviously. Direct invocations of setup.py cannot bootstrap their own dependencies, and so some CLI is necessary for dependency management. The setuptools project no longer wants to provide any public CLI, and will be actively removing the existing interface (though the time scale for this is long). PEP 517, 518 and other standards-based packaging are the future of the Python ecosystem and a lot of progress has been made on making this upgrade seamless.  Here's a summary table of the setup.py way and the newer recommended method:     setup.py New command     setup.py sdist python -m build (with build)   setup.py bdist_wheel python -m build (with build)   setup.py test pytest (usually via tox or nox)   setup.py install pip install   setup.py develop pip install -e   setup.py upload twine upload (with twine)   setup.py check twine check (this doesn't do all the same checks but it's a start)   Custom commands tox and nox environments.
Question: Based on everything that I have seen bisect.bisect and bisect.bisect_right in Python seem to do the same thing. Is there any difference that accounts for the difference in name, or do they have identical behavior and merely a different name? Obviously bisect.bisect_left is different from both of them, but both bisect and bisect_right seem to always return the rightmost position where insertion of the element would maintain a sorted order.

Answer: They are identical: >>> import bisect >>> bisect.bisect is bisect.bisect_right True  In case you were curious, bisect_right is the original function and bisect is the alias: >>> bisect.bisect.__name__ 'bisect_right'
Question: I am learning fastapi and created the sample following application: from fastapi import FastAPI import uvicorn app = FastAPI() @app.get("/hello") async def hello_world(): return {"message": "hello_world"} if __name__== "__main__": uvicorn.run(app, host="127.0.0.1", port=8080)  The server starts fine but when I test the url in browser I am getting the following error:  {"detail": "Not Found"}  and this error in the log:  "GET / HTTP /" 404 Not Found  I noticed another weird problem, when I make some error its not detecting the error and still starting the server. For example if I change the function like the following: @app.get("/hello") async def hello_world(): print (sample) return {"message": "hello_world"}  It should have thrown the error:  NameError: "sample" not defined  but it still is starting the server. Any suggestions will be helpful.

Answer: always add the trailing slash after the path, had the same issue, took me hours to debug
Question: I have a Dockerfile that does a pip install of a package from an AWS code artifact. The install requires an auth token, so my current approach is to generate the dynamic/secret repo url in a build script and pass it into Docker as a build arg, which leads to lines like this in my Dockerfile: ARG CORE_REPO_URL ARG CORE_VERSION RUN pip install -i $CORE_REPO_URL mylib_core==$CORE_VERSION  The use of ARGs in a RUN command cause that layer to never be cached, and therefore this part gets rebuilt every time even if the library version did not change. Is there a better way to do this such that the layer cache would be used unless the CORE_VERSION changed? Maybe I should be installing the aws tool chain in the image so the dynamic repo url can be generated in there in an earlier step (using the same command every time so it wouldn't require an ARG and would hopefully cache the layer)? One downside of this is having to put AWS credentials in the image. I could maybe involve docker secrets to avoid that if that's the only solution though.

Answer: Figured out for my use case of :  Package in CA Multi account setup where you assume a role to get where you need.  Hopefully this will help someone else who finds this. Docker Build using an Assumed Role Profile Remember to build with the buildkit # syntax = docker/dockerfile:experimental # This needs to go at the top of the file or it will break ^ # installing requirements NB, You can probably just take this image it's real small and depending on latest isn't the best, but idc only working on a poc. FROM amazon/aws-cli:latest AS dependencies ARG PYTHONLIBS ARG PROFILE ENV AWS_DEFAULT_PROFILE=$PROFILE COPY ./requirements.txt . # NB I had this here as I was assuming a role you may not need it. COPY ./config /root/.aws/config RUN yum install -y pip RUN --mount=type=secret,id=aws,target=/root/.aws/credentials aws codeartifact login --tool pip --repository //rest of command RUN pip install -r requirements.txt --target ${PYTHONLIBS}
Question: From python's asyncio examples: import asyncio import time def blocking_io(): print(f"start blocking_io at {time.strftime('%X')}") # Note that time.sleep() can be replaced with any blocking # IO-bound operation, such as file operations. time.sleep(1) print(f"blocking_io complete at {time.strftime('%X')}") async def main(): print(f"started main at {time.strftime('%X')}") await asyncio.gather( asyncio.to_thread(blocking_io), asyncio.sleep(1)) print(f"finished main at {time.strftime('%X')}") asyncio.run(main()) # Expected output: # # started main at 19:50:53 # start blocking_io at 19:50:53 # blocking_io complete at 19:50:54 # finished main at 19:50:54  It is outputting the next error:  asyncio.to_thread(blocking_io), AttributeError: module 'asyncio' has no attribute 'to_thread'  Has this feature been deprecated? What would be an alternative for threading with asyncio?

Answer: to_thread is only available in python 3.9+, if you are working with python 3.8 or an older version, you can copy the source code of it: async def to_thread(func, /, *args, **kwargs): loop = asyncio.get_running_loop() ctx = contextvars.copy_context() func_call = functools.partial(ctx.run, func, *args, **kwargs) return await loop.run_in_executor(None, func_call)  This method copies the context to the thread(to use the current value of your set ContextVars) If you don't need that and just want a one liner: await asyncio.get_running_loop().run_in_executor(None, blocking_io, arg1, arg2)  More info about run_in_executor
Question: When I try to import pandas, it throws an error. I cannot import pandas. I re-install pandas but it keeps ont throwing the same error. I tried running it in a local prompt and in a jupyter notebook. I think it may conflict with the pip version so I removed the package from pip. Currently I just have the conda version but still same error. What can I do?  Traceback (most recent call last): File "havatahmin.py", line 1, in <module> import pandas as pd File "C:\Anaconda\envs\ED\lib\site-packages\pandas\__init__.py", line 144, in <module> from pandas.io.api import ( File "C:\Anaconda\envs\ED\lib\site-packages\pandas\io\api.py", line 8, in <module> from pandas.io.excel import ExcelFile, ExcelWriter, read_excel File "C:\Anaconda\envs\ED\lib\site-packages\pandas\io\excel\__init__.py", line 1, in <module> from pandas.io.excel._base import ExcelFile, ExcelWriter, read_excel File "C:\Anaconda\envs\ED\lib\site-packages\pandas\io\excel\_base.py", line 33, in <module> from pandas.io.parsers import TextParser File "C:\Anaconda\envs\ED\lib\site-packages\pandas\io\parsers\__init__.py", line 1, in <module> from pandas.io.parsers.readers import ( File "C:\Anaconda\envs\ED\lib\site-packages\pandas\io\parsers\readers.py", line 17, in <module> from pandas._typing import ( ImportError: cannot import name 'DtypeArg' from 'pandas._typing' (C:\Anaconda\envs\ED\lib\site-packages\pandas\_typing.py)  

Answer: I confirm, it is a reproducible bug in pandas==1.3.1. A workaround is to downgrade it to some earlier version, e.g. pip install pandas==1.3.0. The woarkaround can be tested in build 20210717 of our python (3.8) CUDA-enabled containers: docker run -d --rm --name ml-gpu-py38-cuda112-cust -p 8888:8888 -v /home/mir:/home/jovyan mirekphd/ml-gpu-py38-cuda112-cust:20210717 && docker logs -f ml-gpu-py38-cuda112-cust  Has it been already reported to pandas devs on Github? Update: The issue still persists, so I've provided a reproducible example to Pandas devs in #42506.
Question: The default size of picture or video rendered by manim is 1920*1080. But I want to resize it to for example 2000 * 2000, and I don't know how to modify it. I browsed the doc of manim, but I haven't find any useful ways. Can you help me with it?   I tried to modify frame_height,frame_width,frame_size,but nothing happend. https://docs.manim.community/en/stable/reference/manim._config.utils.ManimConfig.html#manim._config.utils.ManimConfig.frame_height

Answer: you can use the -r, and set e.g. -r 2000,2000. Here I wrote a whole tutorial how to change the pixel size: https://flyingframes.readthedocs.io/en/latest/ch5.html
Question: I am able to run MediaPipe's Pose Landmark detection on my Windows 10 computer by following this tutorial here: https://google.github.io/mediapipe/solutions/pose.html#python-solution-api, but I'm not sure how I can run this example using a GPU. I know that it is quite fast to run on CPU, but I want to use the model with model_complexity=2 since its most accurate, but this makes it slow on my CPU (around 5 FPS). I have GPU, so if I can run on a GPU it will speed things up a lot. I found these following resources.  https://github.com/google/mediapipe/tree/master/mediapipe/modules/pose_landmark https://github.com/google/mediapipe/tree/master/mediapipe/modules/pose_detection  It mentions GPU in these links but I'm not sure how I can utilize these modules. If someone could provide a link or a quick explanation on how to run MediaPipe's Pose Landmark detection on a GPU, I would greatly appreciate it.

Answer: TensorFlow Lite GPU delegate is majorly designed for mobile phone accelerations. See also https://www.tensorflow.org/lite/performance/gpu. Experimentally, the OpenCL backend in TFLite GPU delegate can be supported through Linux platforms. However, we have not verified it on Windows yet. See also https://github.com/tensorflow/tensorflow/issues/40325#issuecomment-642143623.
Question: Question first, context below. How can I perform some server-side action (eg, cleanup) based on a cancellation of an RPC from the client with an async gRPC python server? In my microservice, I have an asyncio gRPC server whose main RPCs are bidirectional streams. On the client side (which is also using asyncio), when I cancel something, it raises an asyncio.CancelledError which is caught and not reraised by the grpc core: https://github.com/grpc/grpc/blob/master/src/python/grpcio/grpc/_cython/_cygrpc/aio/server.pyx.pxi#L679  except asyncio.CancelledError: _LOGGER.debug('RPC cancelled for servicer method [%s]', _decode(rpc_state.method()))  So I cannot rely on catching the asyncio.CancelledError in my own code, because it's caught beforehand and not reraised. The shared context is supposed to contain information as to whether the RPC was canceled on the client side, by calling .cancel() from the RPC call and being able to see if it was canceled by calling .cancelled(): https://grpc.github.io/grpc/python/grpc_asyncio.html#shared-context  abstract cancel() Cancels the RPC. Idempotent and has no effect if the RPC has already terminated. Returns A bool indicates if the cancellation is performed or not. Return type bool  abstract cancelled() Return True if the RPC is cancelled. The RPC is cancelled when the cancellation was requested with cancel(). Returns A bool indicates whether the RPC is cancelled or not. Return type bool   However, this shared context is not attached to the context variable given to the RPC on the server side by the gRPC generated code. (I cannot run context.cancelled() or context.add_done_callback; they're not present) So, again, the question: How can I perform some server-side action (eg, cleanup) based on a cancellation of an RPC from the client with an async gRPC python server?

Answer: thanks for the post. We are aware of this issue, and adding support for those two methods is on our roadmap. For a short term solution, you can use try-catch and decorators. The client-side-cancellation is observed as an asyncio.CancelledError in method handler. Here is a modified helloworld example: Server code: class Greeter(helloworld_pb2_grpc.GreeterServicer): async def SayHello( self, request: helloworld_pb2.HelloRequest, context: grpc.aio.ServicerContext) -> helloworld_pb2.HelloReply: try: await asyncio.sleep(4) except asyncio.CancelledError: print('RPC cancelled') raise return helloworld_pb2.HelloReply(message='Hello, %s!' % request.name)  Client code: async def run() -> None: async with grpc.aio.insecure_channel('localhost:50051') as channel: stub = helloworld_pb2_grpc.GreeterStub(channel) call = stub.SayHello(helloworld_pb2.HelloRequest(name='you')) await asyncio.sleep(2) call.cancel() print(await call.code())