eshangj/stackoverflow_q_and_a_sample huggingface dataset:
Question: Is there a way to specify the output cell where a function should print its output? In my specific case, I have some threads running, each with a logger. The logger output is printed on any running cell, interfering with that cell's intended output. Is there a way I can force the logger to print only on cell #1, for example?

Answer: You could use the following approach:  Redirect all log messages in the root logger (which you will get by calling getLogger()) to a QueueHandler to accumulate the log messages in a queue.Queue. In the intended output cell, start a QueueListener that wraps a StreamHandler. The QueueListener, as its name implies, will listen to new items on the logging queue. It will pass new items to the StreamHandler, which will actually print them.  Assuming we want to print below cell 1, this could look as follows: # Cell 1 import logging, queue, threading, time from logging.handlers import QueueHandler, QueueListener log_queue = queue.Queue(-1) logging.getLogger().addHandler(QueueHandler(log_queue)) listener = QueueListener(log_queue, logging.StreamHandler()) listener.start()  In cell 2, we will simulate some activity: # Cell 2 def log_activity_1(): while True: logging.getLogger().warning("Activity 1") time.sleep(1) threading.Thread(target=log_activity_1, daemon=True).start()  And likewise, in cell 3: # Cell 3 def log_activity_2(): while True: logging.getLogger().warning("Activity 2") time.sleep(2) threading.Thread(target=log_activity_2, daemon=True).start()  The output will happen, basically in real time, under the cell that contains the listener.start() call, thus under cell 1 (and only there) in our case. It will look as expected: For each logged "Activity 2", we will see "Activity 1" logged in alternation and approximately twice as often, as we sleep 2 seconds in the former, and 1 second in the latter:  Once processing has finished, we can stop the QueueListener (either programmatically or manually) via listener.stop() – or rather, we should stop the listener this way, following its documentation: if you don’t call [stop()] before your application exits, there may be some records still left on the queue, which won’t be processed.
Question: I can make inference from my trained Roboflow model using Google Colab and the AWS cloud9 test environment. To do this, I used the following code: from roboflow import Roboflow rf = Roboflow(api_key="xxxxxxxxxxxxxxxxx") path = "/context/image.jpeg" project = rf.workspace().project("xxxxxx") model = project.version(x).model # infer on a local image currency_result= model.predict(path, confidence=40).json()```  However, when I put it into production I got the following error:  [ERROR] TypeError: expected str, bytes or os.PathLike object, not NoneType Traceback (most recent call last): File "/var/lang/lib/python3.8/imp.py", line 234, in load_module return load_source(name, filename, file) File "/var/lang/lib/python3.8/imp.py", line 171, in load_source module = _load(spec) File "<frozen importlib._bootstrap>", line 702, in _load File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 843, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/var/task/app.py", line 1, in <module> from roboflow import Roboflow File "/var/lang/lib/python3.8/site-packages/roboflow/__init__.py", line 10, in <module> from roboflow.adapters import rfapi File "/var/lang/lib/python3.8/site-packages/roboflow/adapters/rfapi.py", line 8, in <module> from roboflow.config import API_URL, DEFAULT_BATCH_NAME, DEFAULT_JOB_NAME File "/var/lang/lib/python3.8/site-packages/roboflow/config.py", line 51, in <module> API_URL = get_conditional_configuration_variable("API_URL", "https://api.roboflow.com") File "/var/lang/lib/python3.8/site-packages/roboflow/config.py", line 22, in get_conditional_configuration_variable default_path = os.path.join(os.getenv("HOME"), ".config/roboflow/config.json") File "/var/lang/lib/python3.8/posixpath.py", line 76, in join a = os.fspath(a)  What I found interesting was that I was able to run the code in cloud9 using sam local invoke, but in the production environment I got the above error.

Answer: As @iurisilvio pointed out, try adding HOME environmental variable into your lambda configuration. The stack trace hints you where the error is, os.getenv("HOME") is None, and hence os.path.join(os.getenv("HOME"), ".config/roboflow/config.json") results in error. Below is from python3.8 >>> import os >>> os.path.join(None, "foo") Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python3.8/posixpath.py", line 76, in join a = os.fspath(a) TypeError: expected str, bytes or os.PathLike object, not NoneType
Question: I have been using Snowflake to do ML works. I have built a Multiple linear regression. I am writing an output df as a table using session.write_pandas. I get this error 'SQL compilation error: Object 'SNOWPARK_TEMP_STAGE_XXXXX' already exists.'  in snowflake streamlit app. This goes if I refresh the page. But why it occurs? I could not find issues related to this in web. I get this error only if i write dataframe as pandas. Below is the code where i get this error.  from snowflake.snowpark.context import get_active_session session = get_active_session() session.write_pandas(df_final, "TEMPTABLE",database="db",schema="schema", auto_create_table=True, overwrite=True)  I have tried to clear or drop the stage every time before write_pandas code. import uuid # Drop the stage if it already exists session.sql(f"DROP STAGE IF EXISTS {stage_name}").collect() # Create a new temporary stage session.sql(f"CREATE TEMPORARY STAGE {stage_name}").collect()  This does not work and what is the real reason I get this error? Please help I have no idea why this happens.

Answer: Trying to patch away two types of errors when writing from pandas Dataframe() to tables in Snowflake.  SNOWPARK_TEMP_FILE_FORMAT_XXXX already exists SNOWPARK_TEMP_STAGE_XXXX already exists  There is also a race condition which ever may occur first, so we have to write try-except within a try-except to resolve this issue. This issue seen in all SNOWPARK related tools like Streamlit in Snowflake, Python-workbook and Python Stored procedures etc. # EXAMPLE: # Modify this fix to your own use accordingly ✅ # Snowflake may patch this BUG in the future. # This BUG is really annoying. import re from snowflake.snowpark.context import get_active_session session = get_active_session() def try_to_write_pd_to_table(my_session, my_df, my_tablename, my_db, my_sch): try: my_session.write_pandas(my_df, my_tablename, database=f"{my_db}", schema="{my_sch}", auto_create_table=True, overwrite=True) except Exception as e1: try: tmp_file_format=re.findall('SNOWPARK_TEMP_FILE_FORMAT_[A-Z]{10}', str(e1)) if(len(tmp_file_format)>0): my_session.sql(f'DROP FILE FORMAT IF EXISTS {my_db}.{my_sch}.{tmp_file_format[0]};').collect(); tmp_stage=re.findall('SNOWPARK_TEMP_STAGE_[A-Z]{10}', str(e1)) if(len(tmp_stage)>0): my_session.sql(f'DROP STAGE IF EXISTS {my_db}.{my_sch}.{tmp_stage[0]};').collect(); my_session.write_pandas(my_df, my_tablename, database=f"{my_db}", schema="{my_sch}", auto_create_table=True, overwrite=True) except Exception as e2: tmp_file_format=re.findall('SNOWPARK_TEMP_FILE_FORMAT_[A-Z]{10}', str(e2)) if(len(tmp_file_format)>0): my_session.sql(f'DROP FILE FORMAT IF EXISTS {my_db}.{my_sch}.{tmp_file_format[0]};').collect(); tmp_stage=re.findall('SNOWPARK_TEMP_STAGE_[A-Z]{10}', str(e2)) if(len(tmp_stage)>0): my_session.sql(f'DROP STAGE IF EXISTS {my_db}.{my_sch}.{tmp_stage[0]};').collect(); my_session.write_pandas(my_df, my_tablename, database=f"{my_db}", schema="{my_sch}", auto_create_table=True, overwrite=True) try_to_write_pd_to_table(session, df_final, "TEMPTABLE", 'LLM_DATABASE', 'ML_SCHEMA');
Question: Kivy app icon is not filling the entire space designed for It. I am not English fluent, but I will describe my problem as best as I can. I am using an icon with 480 x 320 of size and It works fine on the smartphone, but instead of occupying the entire space, the icon is being reduced to approximatelly 50% of the size. The rest is being occupied by a white background. How do I do to put the icon for occupying the entire space? The only change I made in spec file related to the icon was: icon.filename = directory_name/icon_name.png

Answer: There are in fact two ways to add icons for kivy apps. The quick one that you used which is simple but does not allow resize of the icon and an adaptative one which works as follows. You have to edit the following lines of the buildozer.spec file instead : # (str) Adaptive icon of the application (used if Android API level is 26+ at runtime) icon.adaptive_foreground.filename = ./resources/ic_launcher.png icon.adaptive_background.filename = ./resources/ic_launcher_background.png  The two images must be defined as explained on this page : https://developer.android.com/develop/ui/views/launch/icon_design_adaptive Both images should have the same size, I recommend using 512x512. The foreground should have content only in the center square of dimension 312x312 (with recommended dimension).
Question: I've been trying to create a custom PK based on fields in the model. https://redis.io/learn/develop/python/redis-om "The default ID generation function creates ULIDs, though you can change the function that generates the primary key for models if you'd like to use a different kind of primary key." I would like to customise the generation of primary keys based on some of the fields of the model (instance). I noticed that if I create a field called "pk," redis-om does take this value as the primary key. But is there a way. I can just declaratively assign fields as primary keys?

Answer: You can add Field(primary_key=True) to any of the attributes in your model. Here is the code provided in their example with the default pk: import datetime from typing import Optional from redis_om import HashModel class Customer(HashModel): first_name: str last_name: str email: str join_date: datetime.date age: int bio: Optional[str] = "Super dope" andrew = Customer( first_name="Andrew", last_name="Brookins", email="andrew.brookins@example.com", join_date=datetime.date.today(), age=38) print(andrew.pk) # > '01FJM6PH661HCNNRC884H6K30C' andrew.save() assert Customer.get(andrew.custom_pk) == andrew  To assign your own primary key, you would update the code as follows: import datetime from typing import Optional from redis_om import HashModel, Field class Customer(HashModel): custom_pk:str = Field(primary_key=True) first_name: str last_name: str email: str join_date: datetime.date age: int bio: Optional[str] = "Super dope" andrew = Customer( custom_pk = "customPkValue", first_name="Andrew", last_name="Brookins", email="andrew.brookins@example.com", join_date=datetime.date.today(), age=38) andrew.save() assert Customer.get(andrew.custom_pk) == andrew
Question: In Odoo 16, I'm trying to make all fields from a form view readonly depending on the value of other field of the same form. First I've tried the following: <xpath expr="//field" position="attributes"> <attribute name="attrs">{'readonly': [('my_field', '=', True)]}</attribute> </xpath>  With no result. I can't use <form edit="false"> neither since I have to check the field value. A rule with <field name="perm_write">1</field> works, but it doesn't behave as I need, since it allows you to modify the whole form until you click on Save and get the permission error. And overwriting get_view is not a valid option, since cannot depend on my_field value. The only solution I can find is to modify each field of the form with xpath, which is pretty disturbing, and is not consistent if in the future more fields are added to the form view via other apps. Does anyone have a better solution for this?

Answer: Extending get_view actually is a good idea. There is a module in server-ux repo of the OCA where something similar is done: when something is saved in a one2many field, every field in the form view will be set to readonly. To do this, the readonly modifier is rewritten for each field. The module: base_tier_validation The interesting part of code: get_view Code for your case: @api.model def get_view(self, view_id=None, view_type="form", **options): res = super().get_view( view_id=view_id, view_type=view_type, **options, ) if view_type == "form": doc = etree.XML(res["arch"]) for field in doc.xpath("//field[@name][not(ancestor::field)]"): modifiers = json.loads( field.attrib.get("modifiers", '{"readonly": false}') ) if modifiers.get("readonly") is not True: modifiers["readonly"] = OR( [ modifiers.get( "readonly", [] ) or [], [("my_field", "=", True)], ] ) field.attrib["modifiers"] = json.dumps(modifiers) res["arch"] = etree.tostring(doc, pretty_print=True) return res
Question: Consider the following toy example: import polars as pl xs = pl.DataFrame( [ pl.Series( "date", ["2024 Jan", "2024 Feb", "2024 Jan", "2024 Jan"], dtype=pl.String, ) ] ) ys = ( xs.with_columns( pl.col("date").str.split(" ").list.to_struct(fields=["year", "month"]), ) .with_columns( pl.col("date").struct.with_fields(pl.field("year").cast(pl.Int16())) ) .unnest("date") ) ys  shape: (4, 2) ┌──────┬───────┐ │ year ┆ month │ │ --- ┆ --- │ │ i16 ┆ str │ ╞══════╪═══════╡ │ 2024 ┆ Jan │ │ 2024 ┆ Feb │ │ 2024 ┆ Jan │ │ 2024 ┆ Jan │ └──────┴───────┘  I think it would be more efficient to do the operations on a unique series of date data (I could use replace, but I have opted for join for no good reason): unique_dates = ( pl.DataFrame([xs["date"].unique()]) .with_columns( pl.col("date") .str.split(" ") .list.to_struct(fields=["year", "month"]) .alias("struct_date") ) .with_columns( pl.col("struct_date").struct.with_fields( pl.field("year").cast(pl.Int16()) ) ) ) unique_dates  shape: (2, 2) ┌──────────┬──────────────┐ │ date ┆ struct_date │ │ --- ┆ --- │ │ str ┆ struct[2] │ ╞══════════╪══════════════╡ │ 2024 Jan ┆ {2024,"Jan"} │ │ 2024 Feb ┆ {2024,"Feb"} │ └──────────┴──────────────┘  zs = ( xs.join(unique_dates, on="date", left_on="date", right_on="struct_date") .drop("date") .rename({"struct_date": "date"}) .unnest("date") ) zs  shape: (4, 2) ┌──────┬───────┐ │ year ┆ month │ │ --- ┆ --- │ │ i16 ┆ str │ ╞══════╪═══════╡ │ 2024 ┆ Jan │ │ 2024 ┆ Feb │ │ 2024 ┆ Jan │ │ 2024 ┆ Jan │ └──────┴───────┘  What can I do to improve the efficiency of this operation even further? Am I using polars idiomatically enough?

Answer: .str.splitn() should be more efficient as it avoids the List creation + .list.to_struct() .struct.field() can also be used to "unnest" the fields directly. xs.select( pl.col.date.str.splitn(" ", 2) .struct.rename_fields(["year", "month"]) .struct.with_fields(pl.field("year").cast(pl.Int16)) .struct.field("year", "month") )  shape: (4, 2) ┌──────┬───────┐ │ year ┆ month │ │ --- ┆ --- │ │ i16 ┆ str │ ╞══════╪═══════╡ │ 2024 ┆ Jan │ │ 2024 ┆ Feb │ │ 2024 ┆ Jan │ │ 2024 ┆ Jan │ └──────┴───────┘
Question: At least in Spyder, the PyPlot plots can be low resolution, e.g., from: import numpy as np import matplotlib.pyplot as plt # import seaborn as sns rng = np.random.default_rng(1) scat = plt.scatter( *rng.integers( 10, size=(2,10) ) )  My web surfing has brought me to a suggested solution: Increase the dots-per-inch. plt.rcParams['figure.dpi']=300  Surfing indicates that the default is 100. After much experimentation, is there a way to "get" the DPI from the plotted object, e.g., scat above? There doesn't seem to be a scat.dpi, scat.getdpi, or scat.get_dpi. Afternote: Thanks to BigBen for pointing out the object-oriented interface. It requires the definition of a figure and axes therein before actually plotting the data. His code patterns seem to return a DPI, but in Spyder, the displayed figure isn't updated with the plotted data.  Web surfing yields indications that "inline" plots in Spyder are static. I'm wasn't entirely sure if this was the cause, since the plots in the "Plots" window aren't inline (top half of above image), but they also fail to show the plotted data. Eventually, I found that setting the following did allow BigBen's solution to work: Tools -> Preferences -> IPython console -> Graphics -> Graphics backend -> Automatic. A separate window opens for the figure and axes when it is defined by the source code, and it is updated with plot of the data when scatter is invoked.

Answer:  There doesn't seem to be a scat.dpi, scat.getdpi, or scat.get_dpi.  This makes sense, because scatter returns a PathCollection. The relevant property and method are Figure.dpi or Figure.get_dpi. Highly suggest you use the object-oriented interface: fig, ax = plt.subplots() ax.scatter(*rng.integers(10, size=(2,10))) print(fig.dpi) # returns 100.0  Using the pyplot interface: plt.gcf().dpi  or plt.gcf().get_dpi()
Question: I'm building a map with Folium. I used plugins.FeatureGroupSubGroup in order to create four subgroup so that one can filter the markers. As you can see in the picture below, at the top of the white box there is the name of the tiles I'm using (Cartodb dark_matter). Is there any chance to have the box without that writing? If so, how can I remove it?  I tried to search for a solution on StackOverflow and in Folium documentation but couldn't find an answer.

Answer: One option would be to add the TileLayer manually and turn-off its control : import folium m = folium.Map(location=[0, 0], zoom_start=6, tiles=None) t = folium.TileLayer(tiles="cartodbdark_matter", control=False).add_to(m)   # irrelevant / just for reproducibility from folium.plugins import FeatureGroupSubGroup, MarkerCluster mcg = MarkerCluster(control=False).add_to(m) coordinates = [[-1, -1], [-1, 1], [1, 1], [1, -1]] groups = ["A", "B", "C", "D"] for coo, grp in zip(coordinates, groups): sg = FeatureGroupSubGroup(mcg, grp).add_to(m) _ = folium.Marker(coo).add_to(sg) folium.LayerControl(collapsed=False).add_to(m)  Output (m) :
Question: I am trying to install Pyrebase to my NewLoginApp Project using PyCharm IDE and Python. I checked and upgraded the version of the software and I selected the project as my interpreter, but I still get this error: ERROR: ERROR: Failed to build installable wheels for some pyproject.toml based projects (pycryptodome)  Below is the screenshot of the error that I am getting:  Below is the whole code I wrote to the terminal to fix the problem:  

Answer: I think you should install Pyrebase4 pip install Pyrebase4  or pip3 install Pyrebase4  https://pypi.org/project/Pyrebase4/  A simple python wrapper for the Firebase API with current deps  This is a more recent one with last released on Apr 30, 2024    The old one was : pip install Pyrebase  it was last released on Jan 7, 2017 so it will not be supported by new python versions. https://pypi.org/project/Pyrebase/
Question: I made a CPU based raytracer in PyGame which uses a tile per thread to render each section of the screen. Currently I divide the screen vertically between lines, this doesn't give me the best distribution: I want to divide threads in even boxes covering both the X and Y directions. For example: If my resolution is x = 640, y = 320 and I have 4 threads, I want a list of 4 boxes representing tile boundaries in the form (x_min, y_min, x_max, y_max), in this case the result being [(0, 0, 320, 160), (320, 0, 640, 160), (0, 160, 320, 320), (320, 160, 640, 320)]. Problem is I don't see how to automatically divide the number of threads into a 2D grid: I want to extract the closest two whole numbers that multiply to match the thread setting. If this number can't be divided evenly, jump to the closest one that can... for instance no two integers can multiply to create 7, use 6 or 8 instead. I tried math.sqrt but it only works for perfectly divisible numbers like 16, even when rounding that it won't give accurate results for values like 32. What is the simplest solution? Examples: 4 = 2 * 2, 6 = 2 * 3, 8 = 2 * 4, 9 = 3 * 3, 16 = 4 * 4, 24 = 4 * 6, 32 = 4 * 8, 64 = 8 * 8.

Answer: If I understand you correctly, you are looking for the following: Given a number x > 0, find the pair of factors (z, h) where the absolute difference of (z, h) is the at a minimum. x is the number of available threads and (z, h) will then be the number of tilings you will have (vertically, horizontally). If the number of pixels doesn't divide perfectly in your number of tilings, you can add the remainder to the last tiling. The most efficient algorithm that I can think of is as follows:  start with x, the number we want to factor. calculate sqrt(x) and round it down to the nearest integer. Call this s. the smaller factor we're looking for will be the largest divisor of x that's less than or equal to s.  In python code it'll look something like this: import math def closest_factors(x): s = int(math.sqrt(x)) for z in range(s, 0, -1): if x % z == 0: return z, x // z x = 60 factor1, factor2 = closest_factors(x) print(f"The factors of {x} with the least difference are: {factor1} and {factor2}") print(f"Their difference is: {abs(factor1 - factor2)}")  There may be a mathematical formula for this that speeds it up, but I'm not familiar with it. Updated according to @MirceaKitsune 's suggestion in the comments.
Question: I have the following script import gradio as gr # Define the function for the first tab def greet(text): return f"Hello {text}" # Define the function for the second tab def farewell(text): return f"Goodbye {text}" # Create the interface for the first tab with gr.Blocks() as greet_interface: input_text = gr.Textbox(label="Input Text") output_text = gr.Textbox(label="Output Text") button = gr.Button("Submit") button.click(greet, inputs=input_text, outputs=output_text) # Create the interface for the second tab with gr.Blocks() as farewell_interface: input_text = gr.Textbox(label="Input Text") output_text = gr.Textbox(label="Output Text") button = gr.Button("Submit") button.click(farewell, inputs=input_text, outputs=output_text) # Combine the interfaces into tabs with gr.Blocks() as demo: with gr.Tabs(): with gr.TabItem("Greet"): greet_interface.render() with gr.TabItem("Farewell"): farewell_interface.render() # Launch the interface # demo.launch() demo.launch(server_name="0.0.0.0", server_port=7861)  I am scratching my head because this works in one environment I have, and yet in the other it fails terribly. How it fails: In the second tab (farewell) when the button is pressed, it actually calls the greet function. farewell is never called. I can see that some processing is being done in the output_text of the second tab but it never is completed. Instead the output text of the first tab is filled I can not comprehend why this is happening. The only difference I have is that of the environments  The environment where it works:   Python 3.11.1 use venv gradio 4.37.2   The environment where it fails   Python 3.9.16 use poetry gradio 4.32.2  Can someone help me with this strange occurrence? Is tabbed gradio buggy? Btw, I already tried using completely different variables per tab but that does not work

Answer: Yes, tabbed gradio was buggy. It was fixed in version 4.36.1 See the changelog:  Fixes TabbedInterface bug where only first interface events get triggered.  This explains the differences you see between both versions (4.32.2 < 4.36.1 < 4.37.2)