eshangj/stackoverflow_q_and_a_sample huggingface dataset:
Question: I am trying to make a method that gets called every time a function is called, for every single function in the class. The class is a subclass of another class (in my specific case, it is a subclass of list). class Foo(another_class): def __init__(self, bar): self.bar = bar super().__init__(self.bar) def function_to_be_called(self): self.bar += 1 def function(self): # do stuff foo = Foo(0) foo.function() foo.inherited_function() print(foo.bar) # should be 2, since function and inherited_function were called  I found an answer that suggests overwriting the __getattribute__ magic method, but doing so results in infinite recursion (since the function that is called needs to be found using __getattribute__ first), or creates very weird behaviour. My first attempt (causes RecursionError): class Foo(another_class): def __init__(self, bar): self.bar = bar super().__init__(self.bar) def function_to_be_called(self): self.bar += 1 def function(self): # do stuff def __getattribute__(self, attr): method = another_class.__getattribute__(self, attr) self.function_to_be_called() # this required __getattribute__ to be called to find function_to_be_called, causing an infinite loop # even if self.function_to_be_called() is replaced with the self.bar += 1, it still causes an infinite loop as __getattribute__ is called to find bar return method  My second attempt also includes the if callable(method) that was in the answer, and moving the contents of function_to_be_called into the if statement instead of calling the function (p.s. I am changing bar to be a list as that was my original intention, and is how I found the weird behaviour): # Assume that another_class has an append method class Foo(another_class): def __init__(self, bar): self.bar = bar super().__init__(self.bar) def function(self): print(self.bar) def __getattribute__(self, attr): method = another_class.__getattribute__(self, attr) if callable(method): self.bar.sort() # doing something to bar, for example sorting it return method foo = Foo([3, 1, 2]) print(foo) # [3, 1, 2], although the expected result is [1, 2, 3]. it does not actually seem to be sorting it foo.append(1) print(foo) # [3, 1, 2, 1], although the expected result is [1, 1, 2, 3] foo.function() # [1, 2, 3], the other 1 that was appended dissappears randomly (edit: I tried this again, with the actual class that I am using this in, and it seems to work for some reason), and it is sorted for some reason this time 

Answer: You can call the super().__getattribute__ method (which in this case resolves to the object.__getattribute__ method) instead to avoid recursion: class Foo(list): def __init__(self, seq): super().__init__(seq) self.bar = 0 def function_to_be_called(self): self.bar += 1 def function(self): pass def __getattribute__(self, name): attr = super().__getattribute__(name) if callable(attr): super().__getattribute__('function_to_be_called')() return attr foo = Foo([3, 1, 2]) foo.append(1) foo.function() print(foo.bar)  This outputs: 2  Demo: Try it online!
Question: I have the following example of Rich Live from the official examples of Rich. (layout.py) Code from datetime import datetime from time import sleep from rich.align import Align from rich.console import Console from rich.layout import Layout from rich.live import Live from rich.text import Text console = Console() layout = Layout() layout.split( Layout(name="header", size=1), Layout(ratio=1, name="main"), Layout(size=10, name="footer"), ) layout["main"].split_row(Layout(name="side"), Layout(name="body", ratio=2)) layout["side"].split(Layout(), Layout()) layout["body"].update( Align.center( Text( """This is a demonstration of rich.Layout\n\nHit Ctrl+C to exit""", justify="center", ), vertical="middle", ) ) class Clock: """Renders the time in the center of the screen.""" def __rich__(self) -> Text: return Text(datetime.now().ctime(), style="bold magenta", justify="center") layout["header"].update(Clock()) with Live(layout, screen=True, redirect_stderr=False) as live: try: while True: sleep(1) except KeyboardInterrupt: pass  Problem This works as expected when I do python layout.py in Powershell. But if I click on run via the IntelliJ IDE it is not working. The following is my configuration 

Answer: Toggling the "Emulate terminal in output console" option in the Run configuration should fix the problem. If this option is unavailable in the run configuration, remove it from Run | Edit Configuration and create a new one by right-clicking the file in the editor, More Run/Debug | Modify Configuration. Also, the version of IDEA is a bit outdated; please consider updating to the latest.
Question: I'm getting an error when I run a Python Selenium script to open a webpage. I have tried uninstalling and reinstalling selenium, chromeautoinstaller, and undetected chromedriver. I also tried adding option.add_argument('--headless'). None of these were successful and the error remained the same. Here is my code:  def driverInit(): option = uc.ChromeOptions() option.add_argument("--log-level=3") prefs = {"credentials_enable_service": False, "profile.password_manager_enabled": False, "profile.default_content_setting_values.notifications": 2 } option.add_experimental_option("prefs", prefs) driverr = uc.Chrome(options=option) return driverr def driverInitBuffMarket(): option = uc.ChromeOptions() option.add_argument( rf'--user-data-dir=C:\Users\{os.getlogin()}\AppData\Local\Google\ChromeBuff\User Data') # e.g. C:\Users\You\AppData\Local\Google\Chrome\User Data option.add_argument(r'--profile-directory=Default') driverr = uc.Chrome(options=option) return driver  The error occurs in the second-to-last line, driverr = uc.Chrome(options=option) Here is the error: Traceback (most recent call last): File "C:\Users\kumpd\OneDrive\Desktop\All Market Bots\BuffMarket Purchase Bot Testing\main.py", line 266, in <module> start_buy_monitoring() File "C:\Users\kumpd\OneDrive\Desktop\All Market Bots\BuffMarket Purchase Bot Testing\main.py", line 207, in start_buy_monitoring driverBuffMarket = driverInitBuffMarket() ^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\kumpd\OneDrive\Desktop\All Market Bots\BuffMarket Purchase Bot Testing\main.py", line 42, in driverInitBuffMarket driverr = uc.Chrome(options=option) ^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\kumpd\AppData\Local\Programs\Python\Python311\Lib\site-packages\undetected_chromedriver\__init__.py", line 398, in __init__ if headless or options.headless: ^^^^^^^^^^^^^^^^ AttributeError: 'ChromeOptions' object has no attribute 'headless'  Any help is greatly appreciated!

Answer: As of today, undetected-chromedriver is still using options.headless in their code. That's a problem due to this change in selenium 4.13.0 that was just released: * remove deprecated headless methods  Here are some alternatives:  Downgrade to an earlier selenium version until fixed. Use SeleniumBase's UC Mode (a modified fork of undetected-chromedriver):  from seleniumbase import Driver import time driver = Driver(uc=True) driver.get("https://nowsecure.nl/#relax") time.sleep(6) driver.quit()  Here's another, more advanced example with retries and clicks (using the SB() manager): from seleniumbase import SB with SB(uc=True) as sb: sb.driver.get("https://nowsecure.nl/#relax") sb.sleep(2) if not sb.is_text_visible("OH YEAH, you passed!", "h1"): sb.get_new_driver(undetectable=True) sb.driver.get("https://nowsecure.nl/#relax") sb.sleep(2) if not sb.is_text_visible("OH YEAH, you passed!", "h1"): if sb.is_element_visible('iframe[src*="challenge"]'): with sb.frame_switch('iframe[src*="challenge"]'): sb.click("span.mark") sb.sleep(4) sb.activate_demo_mode() sb.assert_text("OH YEAH, you passed!", "h1", timeout=3)  (This is mainly what I wrote here: https://github.com/ultrafunkamsterdam/undetected-chromedriver/issues/1584#issuecomment-1737963363)
Question: I'm trying to run a Flask app in a docker container and connect to it using my browser. I am not able to see the app and get an error This site can’t be reached when trying to go to http://127.0.0.1:5000. I've already followed the advice in these two questions (1) (2). This is my Dockerfile: FROM python:3.11.5-bookworm WORKDIR /app COPY requirements.txt . RUN pip install --upgrade pip RUN pip install -r requirements.txt COPY . . EXPOSE 5000 CMD ["flask", "run", "--host", "0.0.0.0"]  and this is my app: from flask import Flask app = Flask(__name__) @app.route("/") def home(): return 'hello' if __name__ == "__main__": app.run(host="0.0.0.0")  When I use docker desktop, I can see that the app is running correctly inside the docker container: 2023-09-27 14:14:44 * Debug mode: off 2023-09-27 14:14:44 WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead. 2023-09-27 14:14:44 * Running on all addresses (0.0.0.0) 2023-09-27 14:14:44 * Running on http://127.0.0.1:5000 2023-09-27 14:14:44 * Running on http://172.17.0.5:5000 2023-09-27 14:14:44 Press CTRL+C to quit 2023-09-27 14:15:14 127.0.0.1 - - [27/Sep/2023 19:15:14] "GET / HTTP/1.1" 200 -  from the command line in the docker terminal, the output is also as expected: # curl http://127.0.0.1:5000 hello#  However, when I use my browser to go to localhost (http://127.0.0.1:5000), I get an error: This site can’t be reached In the tutorial I was watching, it worked, so I'm not sure what I'm doing wrong here...

Answer: Make sure to run the container specifying the mapping port: docker run -p 5000:5000 <docker_image_id> The first port stands for the port on the host machine, and the second one is for which port you want to map it in the container. Make sure there aren't any background processes running. Check for any ( linux ): netstat -tuln | grep 5000 If any found, kill: kill -9 <PID>
Question: I have the following df:  col1 col2 col3 0 a 1.0 1.0 1 b NaN NaN 2 c 5.0 3.0 3 d 5.0 NaN  I want to do forward fill the rows only where col2 = NaN so the result would be like this  col1 col2 col3 0 a 1.0 1.0 1 b 1.0 1.0 2 c 5.0 3.0 3 d 5.0 NaN  I was able to get to here but this isn't a smart solution because it ffills row 3 even though it doesn't meet the requirements of col2 = NaN df['col2'] = df['col2'].fillna(method="ffill") df['col3'] = df['col3'].fillna(method="ffill") 

Answer: Code df.fillna(df.ffill().where(df['col2'].isna()))  output:  col1 col2 col3 0 a 1.0 1.0 1 b 1.0 1.0 2 c 5.0 3.0 3 d 5.0 NaN   Example import pandas as pd data = {'col1': ['a', 'b', 'c', 'd'], 'col2': [1, None, 5, 5], 'col3': [1, None, 3, None]} df = pd.DataFrame(data)
Question: I am trying to connect to a db instance, but my password has the following special characters: backslash, plus, dot, asterisk/star and at symbol. For example, 12@34\56.78*90 (regex nightmare lol) How do I safe pass it to the connection string? My code looks like that: connection_string = f'user={user} password={pass} host={host} dbname={dbname} port={port}' connection = psg2.connect(connection_string)  It gives me wrong pass/username error. However, I tried this combination directly on the db and it works, and I tried another combination on the python code and it worked as well. So looks like the problem is the password being passed weirdly to the connection. I tried urllib scape, I tried double quotes on the password, nothing works so far :(

Answer: Based on a reddit thread, I found out that passing variable by variable directly instead of a connection string did the trick: con = psycopg2.connect( dbname=dn, user=du, password=dp, host=dh, port=dbp, )
Question: Please consider the following DataFrame: mi = pd.MultiIndex( levels = [[1, 2, 3], ['red', 'green', 'blue'], ['a', 'b', 'c']], codes = [[1,0,1,0], [0,1,1,2], [1,0,0,1]], names = ["Key1", "Key2", "Key3"]) df = pd.DataFrame({ "values": [1, 2, 3, 4] }, index = mi)  ... which looks like this:  Now I know how to filter this by values of the index levels, eg: df[ df.index.get_level_values("Key1").isin([1]) & df.index.get_level_values("Key2").isin(["green"]) ]  I'm trying to write a function which makes this operation less verbose, so I'd like to pass in a dict like: {"Key1":1, "Key2":"green"} to do the same thing. The solution shouldn't hardcode the number of levels we are filtering on, so that later, I might want to only filter by one of the conditions, and would pass in {"Key1":1} or ``{"Key2":"green"}`. I don't know the syntax for constructing the predicate inside the df[ ... ] on-the-fly from a dict. Is this possible?

Answer: You can convert the MultiIndex to_frame, then slice the columns with dictionary keys and check if all are equal within a row to perform boolean indexing: d = {"Key1":1, "Key2":"green"} out = df[df.index.to_frame()[list(d)].eq(d).all(axis=1)]  Alternatively, using np.logical_and.reduce and your original approach: out = df[np.logical_and.reduce([df.index.get_level_values(k)==v for k,v in d.items()])]  Output:  values Key1 Key2 Key3 1 green a 2  Intermediates: # df.index.to_frame()[list(d)] Key1 Key2 Key1 Key2 Key3 2 red b 2 red 1 green a 1 green 2 green a 2 green 1 blue b 1 blue # df.index.to_frame()[list(d)].eq(d) Key1 Key2 Key1 Key2 Key3 2 red b False False 1 green a True True 2 green a False True 1 blue b True False # df.index.to_frame()[list(d)].eq(d).all(axis=1) Key1 Key2 Key3 2 red b False 1 green a True 2 green a False 1 blue b False dtype: bool
Question: I have the below code which for instance work as excepted but won't work in the Future :  total.name = 'New_Row' total_df = total.to_frame().T total_df.at['New_Row', 'CURRENCY'] = '' total_df.at['New_Row', 'MANDATE'] = Portfolio total_df.at['New_Row', 'COMPOSITE'] = 'GRAND TOTAL' total_df.set_index('COMPOSITE',inplace=True)  since an error is thrown in FutureWarning: Setting an item of incompatible dtype is deprecated and will raise in a future error of pandas. Value 'GRAND TOTAL' has dtype incompatible with float64, please explicitly cast to a compatible dtype first. total_df.at['New_Row', 'COMPOSITE'] = 'GRAND TOTAL'  How to fix this ? variable total is : CURRENCY MANDATE Mandate_Test USD AMOUNT 123 LOCAL AMOUNT 12 Beg. Mkt 123 End. Mkt 456 Name: New_Row, dtype: object 

Answer: I think it is bug -  BUG: incompatible dtype when creating string column with loc #55025 . In next version of pandas should be solved.
Question: I want to save a Pandas dataframe to a CSV file in such a way that no additional double quotes or any other characters are added to these formulas. Here is my attempt: import pandas as pd data = { "Column1": [1, 2, 3], "Column2": ["A", "B", "C"], "Formula": ['"=HYPERLINK(""https://www.yahoo.com"",""See Yahoo"")"', '"=HYPERLINK(""https://www.google.com"",""See Google"")"', '"=HYPERLINK(""https://www.bing.com"",""See Bing"")"'] } df = pd.DataFrame(data) # Save the DataFrame to a CSV file without adding extra double quotes df.to_csv("output.csv", index=False, doublequote=False)  But this throws this error:  File "pandas/_libs/writers.pyx", line 75, in pandas._libs.writers.write_csv_rows _csv.Error: need to escape, but no escapechar set How can I bypass this? I need it so that the hyperlink shows in Excel as a clickable link.

Answer: Remove the double quotes "" from the hyperlinks: import pandas as pd data = { "Column1": [1, 2, 3], "Column2": ["A", "B", "C"], "Formula": [ '=HYPERLINK("https://www.yahoo.com", "See Yahoo")', '=HYPERLINK("https://www.google.com", "See Google")', '=HYPERLINK("https://www.bing.com", "See Bing")', ], } df = pd.DataFrame(data) df.to_csv("out.csv", index=False, quotechar='"')  Creates out.csv: Column1,Column2,Formula 1,A,"=HYPERLINK(""https://www.yahoo.com"", ""See Yahoo"")" 2,B,"=HYPERLINK(""https://www.google.com"", ""See Google"")" 3,C,"=HYPERLINK(""https://www.bing.com"", ""See Bing"")"   Opening the CSV in LibreOffice (Ctrl+Click on the formula opens a webpage):
Question: As shown in LangChain Quickstart, I am trying the following Python code: from langchain.prompts.chat import ChatPromptTemplate template = "You are a helpful assistant that translates {input_language} to {output_language}." human_template = "{text}" chat_prompt = ChatPromptTemplate.from_messages([ ("system", template), ("human", human_template), ]) chat_prompt.format_messages(input_language="English", output_language="French", text="I love programming.")  But when I run the above code, I get the following error: Traceback (most recent call last): File "/home/yser364/Projets/SinappsIrdOpenaiQA/promptWorkout.py", line 6, in <module> chat_prompt = ChatPromptTemplate.from_messages([ File "/home/yser364/.local/lib/python3.10/site-packages/langchain/prompts/chat.py", line 220, in from_messages return cls(input_variables=list(input_vars), messages=messages) File "/home/yser364/.local/lib/python3.10/site-packages/langchain/load/serializable.py", line 64, in __init__ super().__init__(**kwargs) File "pydantic/main.py", line 341, in pydantic.main.BaseModel.__init__ pydantic.error_wrappers.ValidationError: 4 validation errors for ChatPromptTemplate messages -> 0 value is not a valid dict (type=type_error.dict) messages -> 0 value is not a valid dict (type=type_error.dict) messages -> 1 value is not a valid dict (type=type_error.dict) messages -> 1 value is not a valid dict (type=type_error.dict)  I use Python 3.10.12.

Answer: Your example is from the Prompt templates section of the LangChain Quickstart tutorial. I did not spot any differences, so it should work as given. I tried out the example myself, with an additional loop to output the messages created by chat_prompt.format_messages: from langchain.prompts.chat import ChatPromptTemplate template = "You are a helpful assistant that translates {input_language} to {output_language}." human_template = "{text}" chat_prompt = ChatPromptTemplate.from_messages([ ("system", template), ("human", human_template), ]) messages = chat_prompt.format_messages(input_language="English", output_language="French", text="I love programming.") for message in messages: print(message.__repr__())  The example works without any errors. The result is very similar to what is shown in the tutorial, although not identical: SystemMessage(content='You are a helpful assistant that translates English to French.', additional_kwargs={}) HumanMessage(content='I love programming.', additional_kwargs={}, example=False)  I ran the test with Python 3.9.5 and LangChain 0.0.300, which is the lastest version on PyPI. According to PyPI, it supports Python >=3.8.1 and <4.0. Maybe your version of LangChain or one of its dependencies is outdated? Try to run it in a new venv with a fresh install of LangChain.
Question: I want to add a column result to a polars DataFrame that contains a list of the column names with a value greater than zero at that position. So given this: import polars as pl df = pl.DataFrame({"apple": [1, 0, 2, 0], "banana": [1, 0, 0, 1]}) cols = ["apple", "banana"]  How do I get: shape: (4, 3) ┌───────┬────────┬─────────────────────┐ │ apple ┆ banana ┆ result │ │ --- ┆ --- ┆ --- │ │ i64 ┆ i64 ┆ list[str] │ ╞═══════╪════════╪═════════════════════╡ │ 1 ┆ 1 ┆ ["apple", "banana"] │ │ 0 ┆ 0 ┆ [] │ │ 2 ┆ 0 ┆ ["apple"] │ │ 0 ┆ 1 ┆ ["banana"] │ └───────┴────────┴─────────────────────┘  All I have so far is the truth values: df.with_columns(pl.concat_list(pl.col(cols).gt(0)).alias("result")) shape: (4, 3) ┌───────┬────────┬────────────────┐ │ apple ┆ banana ┆ result │ │ --- ┆ --- ┆ --- │ │ i64 ┆ i64 ┆ list[bool] │ ╞═══════╪════════╪════════════════╡ │ 1 ┆ 1 ┆ [true, true] │ │ 0 ┆ 0 ┆ [false, false] │ │ 2 ┆ 0 ┆ [true, false] │ │ 0 ┆ 1 ┆ [false, true] │ └───────┴────────┴────────────────┘ 

Answer: Here's one way: you can use pl.when with pl.lit in the concat_list to get either the literal column names or nulls, then do a list.drop_nulls: df.with_columns( result=pl.concat_list( pl.when(pl.col(col) > 0).then(pl.lit(col)) for col in df.columns ).list.drop_nulls() )  shape: (4, 3) ┌───────┬────────┬─────────────────────┐ │ apple ┆ banana ┆ result │ │ --- ┆ --- ┆ --- │ │ i64 ┆ i64 ┆ list[str] │ ╞═══════╪════════╪═════════════════════╡ │ 1 ┆ 1 ┆ ["apple", "banana"] │ │ 0 ┆ 0 ┆ [] │ │ 2 ┆ 0 ┆ ["apple"] │ │ 0 ┆ 1 ┆ ["banana"] │ └───────┴────────┴─────────────────────┘
Question: I'm currently using prefect to orchestrate some simple task in python. It's working fine until I get this error : Traceback (most recent call last): File "test.py", line 2, in <module> from prefect import flow File "/Users/.../.venv/lib/python3.8/site-packages/prefect/__init__.py", line 25, in <module> from prefect.states import State ... ImportError: cannot import name 'SecretField' from 'pydantic' (/Users/.../.venv/lib/python3.8/site-packages/pydantic/__init__.py)  It's seems I have the module install in my venv : (.venv) User@user % pip show pydantic Name: pydantic Version: 2.3.0 Summary: Data validation using Python type hints Home-page: None Author: None Author-email: Samuel Colvin <s@muelcolvin.com>, Eric Jolibois <em.jolibois@gmail.com>, Hasan Ramezani <hasan.r67@gmail.com>, Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com>, Terrence Dorsey <terry@pydantic.dev>, David Montague <david@pydantic.dev> License: None Location: /Users.../.venv/lib/python3.8/site-packages Requires: annotated-types, pydantic-core, typing-extensions Required-by: prefect, fastapi  Where this could come from ?

Answer: That's because Prefect isn't compatible with pydantic>2 yet. So, they've pinned the reqs to the versions less than 2 (check PR10144 for more details). Try to install the latest version of Perfect or downgrade your pydantic's to 1.10.11 : pip install -U prefect # or pip install pydantic==1.10.11
Question: I now use micromamba instead of conda or mamba. I would like to rename/move an environment. Using conda, I can rename via: conda rename -n CURRENT_ENV_NAME NEW_ENV_NAME  But this doesn't work with neither mamba nor micromamba: $ /opt/homebrew/Caskroom/miniforge/base/condabin/mamba rename -n flu_frequencies_test flu_frequencies Currently, only install, create, list, search, run, info, clean, remove, update, repoquery, activate and deactivate are supported through mamba. $ micromamba rename -n flu_frequencies_test flu_frequencies The following arguments were not expected: flu_frequencies rename Run with --help for more information. 

Answer: Micromamba As stated in the answer to Cloning environment with micromamba, --clone is not an option in micromamba. Instead, export the environment yaml and create a new environment using the --file flag. Then remove the old environment.  export the env dependencies: micromamba env export oldenv > oldenv.yaml create a new env with a new name: micromamba create -n newenv --file oldenv.yaml remove the old env: micromamba env remove -n oldenv delete the yaml file: rm oldenv.yaml