eshangj/stackoverflow_q_and_a_sample huggingface dataset:
Question: I'm trying to make a Python bubble sort with a 5 variable list. The user will input the 5 values and the bubble_sort is going to arrange them in ascending order, but when I try to run it it gives the error: lista = list(n1, n2, n3, n4, n5) ^^^^^^^^^^^^^^^^^^^^^^^^ TypeError: list expected at most 1 argument, got 5  This is the code I wrote: print('Olá!') msg = 'Olá!' n1 = float(input('Digite um número qualquer:')) n2 = float(input('Digite outro número qualquer:')) n3 = float(input('Digite outro número qualquer:')) n4 = float(input('Digite outro número qualquer:')) n5 = float(input('Digite outro número qualquer:')) lista = list(n1, n2, n3, n4, n5) def bubble_sort(arr): n = len(arr) for i in range(n): for j in range(0, n - i - 1): if arr[j] > arr[j + 1]: arr[j], arr[j + 1] = arr[j + 1], arr[j] return arr print(bubble_sort(lista)) print('Fim') 

Answer: you are trying to create the list lista using the list() function but it expects an iterable as its argument, not multiple individual elements! create a list containing all the elements like this: lista = [n1, n2, n3, n4, n5]
Question: How can I connect a callback when using QMessageBox.open() ? In the documentation it says:  QMessageBox.open(receiver, member) Opens the dialog and connects its finished() or buttonClicked() signal to the slot specified by receiver and member . If the slot in member has a pointer for its first parameter the connection is to buttonClicked() , otherwise the connection is to finished() .  What should I use for receiver and member in the below example: import sys from PyQt6.QtWidgets import ( QApplication, QMainWindow, QPushButton, QMessageBox ) def show_dialog(app, window): mbox = QMessageBox(window) mbox.setIcon(QMessageBox.Icon.Information) mbox.setText("Message box pop up window") mbox.setWindowTitle("QMessageBox Example") mbox.setStandardButtons(QMessageBox.StandardButton.Ok | QMessageBox.StandardButton.Cancel) def button_clicked(): print("message box button clicked") mbox.done(0) app.quit() # How to connect button_clicked() to the standard buttons of the message box? mbox.open(receiver, member) # What to use for receiver and member? def main(): app = QApplication(sys.argv) window = QMainWindow() window.resize(330, 200) window.setWindowTitle("Testing") button = QPushButton(window) button.setText("Button1") button.setGeometry(100,100,100,30) def button_clicked(): print("button clicked") show_dialog(app, window) button.clicked.connect(button_clicked) window.show() app.exec() if __name__ == '__main__': main() 

Answer: After some trial and error I found that I could simply use mbox.open(button_clicked) but I am still not sure how I can determine from within the callback which of the two buttons was clicked. Also one should not call QMessageBox.done() from within the callback since that would lead to infinite recursion. Here is how I call QMessageBox.open() which works, but I am still missing the last piece of the puzzle: How to determine which button was clicked? def show_dialog(app, window): mbox = QMessageBox(window) mbox.setIcon(QMessageBox.Icon.Information) mbox.setText("Message box pop up window") mbox.setWindowTitle("QMessageBox Example") mbox.setStandardButtons(QMessageBox.StandardButton.Ok | QMessageBox.StandardButton.Cancel) #@pyqtSlot() # It is not necessary to use this decorator? def button_clicked(): print("message box button clicked") # But which button? #mbox.done(0) # Do not call this method as it will lead to infinite recursion app.quit() mbox.open(button_clicked) print("Dialog opened")  Update:  How to determine which button was clicked?  You can use mbox.clickedButton().text(), for example like this: def button_clicked(): if mbox.clickedButton().text() == "&OK": print("OK clicked") else: print("Cancel clicked") app.quit()
Question: I recently updated my Google Chrome browser to version 115.0.5790.99 and I'm using Python webdrivermanager library (version 3.8.6) for Chrome driver management. However, since this update, when I call the ChromeDriverManager().install() function, I encounter the following error:  There is no such driver by URL https://chromedriver.storage.googleapis.com/LATEST_RELEASE_115.0.5790  Steps to reproduce the issue:  Update Google Chrome to version 115.0.5790.99.  Execute the following Python code: from webdriver_manager.chrome import ChromeDriverManager driver_path = ChromeDriverManager().install()  capture: 

Answer: Selenium Manager With the availability of Selenium v4.6 and above you don't need to explicitly download ChromeDriver, GeckoDriver or any browser drivers as such using webdriver_manager. You just need to ensure that the desired browser client i.e. google-chrome, firefox or microsoft-edge is installed. Selenium Manager is the new tool integrated with selenium4 that would help to get a working environment to run Selenium out of the box. Beta 1 of Selenium Manager will configure the browser drivers for Chrome, Firefox, and Edge if they are not present on the PATH.  Solution As a solution you can simply do: from selenium import webdriver from selenium.webdriver.chrome.options import Options options = Options() options.add_argument("start-maximized") driver = webdriver.Chrome(options=options) driver.get("https://www.google.com/")
Question: I've got a set of 25 integers, ranging from 0 to 24 and my application involves selecting 5 of them (there are no repeated values, no value can be selected more than once) obtaining a combination like this one [15, 7, 12, 3, 22]. It's important to consider the the previous combination is considered equal to [7, 22, 12, 15, 3], the order doesn't matter, only the values do. By applying the binomial coefficient (25 choose 5) we can find out that there are 53.130 possible combinations. I want to encode all the possible combinations into an integer so that all values from 0 to 53129 are linked to a combination.

Answer: Use more_itertools.nth_combination that can compute the nth combination without computing all previous ones: # pip install more-itertools from more_itertools import nth_combination nth_combination(range(25), 5, 0) # (0, 1, 2, 3, 4) nth_combination(range(25), 5, 42) # (0, 1, 2, 5, 7) nth_combination(range(25), 5, 53129) # (20, 21, 22, 23, 24)  You can make things more interesting by combining the above with functools.partial/cache: from functools import partial, cache encode = partial(nth_combination, range(25), 5) # or with a cache # encode = cache(partial(nth_combination, range(25), 5)) encode(0) # (0, 1, 2, 3, 4) encode(42) # (0, 1, 2, 5, 7) encode(53129) # (20, 21, 22, 23, 24)  efficiency The advantage of nth_combination is that for large ranges, it is not needed to compute all n-1 combinations to access the nth one. Also, it is not needed to store all combinations, making it both CPU and memory efficient. Combined with cache this makes a compromise between memory and CPU by avoiding to recompute the same value twice if the same code is requested several times. However, if you must access all values eventually, then pre-computing all combinations as show by @ti7 will be more straightforward and efficient, but will require to compute and store all values from the beginning: from itertools import combinations encode = list(combinations(range(25), 5)) encode[0] # (0, 1, 2, 3, 4) encode[42] # (0, 1, 2, 5, 7) encode[53129] # (20, 21, 22, 23, 24)
Question: Please help me when I tried to use it in my Google Colab for transformers error:  ImportError: Using the Trainer with PyTorch requires accelerate=0.20.1: Please run pip install transformers[torch] or pip install accelerate -U`  NOTE: If your import is failing due to a missing package, you can manually install dependencies using either !pip or !apt. To view examples of installing some common dependencies, click the "Open Examples" button below. transformers - GPT - pytorch

Answer: Steps: pip install accelerate -U then Restart the notebook run all and you'll see it'll solve
Question: I have been struggling for days to deploy a Python web app with flask on Azure. But all I ever get is the default page. This is the address: https://el-priser.azurewebsites.net/ This is my Github repo: https://github.com/Michaelgimm/energinet-elpris I also tried with the azure guide for a test app, but it does the same. The deployment is a success and I can see all the files when accessing through SSH via this link: https://el-priser.scm.azurewebsites.net/ Any ideas? I haave tried everything I can think of. What I did expect to see was my app. In the structure of my app I have a main.py but placed the index.html in a folder called templates.

Answer: I have tried to deploy your application to Azure web app through VScode. I could deploy the application, but I was able to see only default page and few times it also led me to Application Error.   After many trials, I could figure out the resolution for this issue.  To run the deployed Flask application, we have to add few settings in the web app.  Go to your App service=> Settings =>Configuration =>Application Settings=> Click on Add new application settings and add the settings:   1. SCM_DO_BUILD_DURING_DEPLOYMENT=1 2. WEBSITES_CONTAINER_START_TIME_LIMIT=1800 3. WEBSITES_PORT=<port_number_of_your_application>    Go to General Settings in Configuration of your web app and add the startup command gunicorn --bind=0.0.0.0 main:app.  As your Flask app main module is main.py and the Flask app object in that file is named as app, use the above given Startup command.     Restart the web app after adding all these settings. Now, you will be able to access your application (index and prices pages):  Response: I could access both the index and prices pages as shown below:
Question: How can I find all matches that don't necessarily consume all characters with * and + modifiers? import regex as re matches = re.findall("^\d+", "123") print(matches) # actual output: ['123'] # desired output: ['1', '12', '123']  I need the matches to be anchored to the start of the string (hence the ^), but the + doesn't even seem to be considering shorter-length matches. I tried adding overlapped=True to the findall call, but that does not change the output. Making the regex non-greedy (^\d+?) makes the output ['1'], overlapped=True or not. Why does it not want to keep searching further? I could always make shorter substrings myself and check those with the regex, but that seems rather inefficient, and surely there must be a way for the regex to do this by itself. s = "123" matches = [] for length in range(len(s)+1): matches.extend(re.findall("^\d+", s[:length])) print(matches) # output: ['1', '12', '123'] # but clunky :(  Edit: the ^\d+ regex is just an example, but I need it to work for any possible regex. I should have stated this up front, my apologies.

Answer: You could use overlapped=True with the PyPi regex module and reverse searching (?r) Then reverse the resulting list from re.findall import regex as re res = re.findall(r"(?r)^\d+", "123", overlapped=True) res.reverse() print(res)  Output ['1', '12', '123']  See a Python demo.
Question: SOLVED: I'm having an issue using sqlalchemy and snowflake.connector to push my df to a new table in Snowflake but I am prompted with this error: raise errors.MissingDependencyError(self._dep_name) snowflake.connector.errors.MissingDependencyError: Missing optional dependency: pandas Edit: Accidentally posted without adding in more detail! I am importing pandas, and all necessary packages. I do not understand why the error is suggesting pandas is missing as it is used elsewhere many times in my scripts. Versions are: snowflake-connector-python 3.0.2 snowflake-sqlalchemy 1.4.7 SQLAlchemy 1.4.49 Below is a stripped out example of my code: import pandas as pd from snowflake.connector.pandas_tools import pd_writer from sqlalchemy.types import String from snowflake.sqlalchemy import URL from sqlalchemy import create_engine engine = create_engine(URL( user='service account', password='password', account='account', database='database', schema='schema', warehouse='warehouse', role="role" )) df.columns = map(lambda x: str(x).upper(), df.columns) df.to_sql(name=table_name.lower(), con=engine, schema="schema", index=False, if_exists='append', method=pd_writer, dtype={'field': String}) engine.dispose()  Solution: Run the following in terminal/powershell: pip install snowflake-connector-python[pandas]

Answer: Moving the answer from the question to the answer section, so it doesn't look as unanswered: pip install snowflake-connector-python[pandas]
Question: I'm migrating from v1 to v2 of Pydantic and I'm attempting to replace all uses of the deprecated @validator with @field_validator. However, I was previously using the pre validator argument and after moving to @field_validator, I'm receiving the following error: TypeError: field_validator() got an unexpected keyword argument 'pre'  Has the use of pre also been deprecated in V2? It seems it's still referenced in the V2 validator documentation though with the top-of-page warning:  This page still needs to be updated for v2.0.  Hoping somebody else has already worked through this and can suggest the best route forward. Thanks!

Answer:  It seems it's still referenced in the V2 validator documentation [...]  Not really. At least nowhere in the field validators section. (There is just an outdated mention of it in the "model validators" section as of today.) However, there is also a link to the detailed API reference for the field_validator decorator showing exactly what arguments you can pass to it. The closest thing to the v1 pre=True argument would now be the mode="before" argument. Say you have the following code in Pydantic v1: from pydantic import BaseModel, validator class Foo(BaseModel): x: int @validator("x", pre=True) def do_stuff(cls, v: object) -> object: if v is None: return 0 return v print(Foo(x=None)) # x=0  You would have to rewrite it like this in v2: from pydantic import BaseModel, field_validator class Foo(BaseModel): x: int @field_validator("x", mode="before") def do_stuff(cls, v: object) -> object: if v is None: return 0 return v print(Foo(x=None)) # x=0  I expect the maintainers will gradually rewrite and expand the docs to cover more details.
Question: My goal is to chain or link several different discord modals after one-another in order to create a continuous form since Discord does not allow to add more than 5 items or "questions" per modal. The goal is to have modal_1 and modal_2 with 5 questions in each. Every time a command is ran by a user, modal_1 would be displayed. After completion, the user would submit modal_1, after which modal_2 would appear. Sadly, all my tries were unsuccessful, with Discord not closing the first modal after submitting it and instead returning the error: "Something went wrong, try again". This error is not a code error, but inside of the Discord modal. Here is a code snippet to illustrate what I am doing: class Modal_2(discord.ui.Modal,title="Modal_2"): question_1 = discord.ui.TextInput(label="That's the second question") asnyc def on_sumbit(self,interaction:discord.Interaction): await interaction.response.send_message(content="Thanks for your input") class Modal_1(discord.ui.Modal,title="Modal_1"): question_1 = discord.ui.TextInput(label="That's the first question") asnyc def on_sumbit(self,interaction:discord.Interaction): await interaction.response.send_modal(Modal_2()) class main(commands.Cog): def __init__(self,bot): self.bot = bot @app_commands.command(name="survey") async def main(self,interaction:discord.Interaction) await interaction.response.send_modal(Modal_1())  After the command is run, shows the first modal. Though when submitted, the second modal never shows up nor is the first modal dismissed. It only returns the error: "Something went wrong, try again" within the first modal after submitting it, but now actual "code" error or exception is shown in the console.

Answer: No, you can't. Looking in this section of Discord's Developers' Portal, you can read that MODAL can't be the callback of a MODAL_SUBMIT interaction. Depending on what the data is, I would either use a form webpage or try to do something with the View Widgets, especially TextInputs, since you can send as many messages with these as you want.
Question: I'm trying to copy large bytes objects into a shareable list that's been initialized with bytes objects of large enough size. When the bytes object I'm copying over has trailing zeros (i.e. final values are 0x00), the new entry in the shared memory list is missing these zeros. Zeros in the middle of the data do not cause early truncation. A minimal example is below with the output. Code: from multiprocessing import shared_memory as shm shmList = shm.ShareableList([bytes(50)]) testBytes = bytes.fromhex("00112233445566778899aabbccddeeff0000") shmList[0] = testBytes print(testBytes) print(shmList[0]) shmList.shm.close() shmList.shm.unlink()  Output: b'\x00\x11"3DUfw\x88\x99\xaa\xbb\xcc\xdd\xee\xff\x00\x00' b'\x00\x11"3DUfw\x88\x99\xaa\xbb\xcc\xdd\xee\xff'  I would expect the bytes object would get copied over in full, including the trailing zeros. This seems like a "feature": sourcecode, but why? Are there any straightforward workarounds?

Answer: CPython seems to explicitly .rstrip(b'\x00'), but there doesn't seem to be any mention of this in the documentation. There is nothing documented at all about the storage neither in terms of semantics nor implementation (except that it should use (or be compatible with) the struct module). Personally, I'd say the way it is handled currently deserves to be considered a bug. Valid bytes objects are allowed to have trailing zero bytes, so the current implementation does not preserve specific valid values where it should do. You could file an issue to CPython about this.
Question: I am working with a large dataset (1 million + rows) and am tasked with counting up each truthy value for each ID and generating a new dict. The solution I came up with works, but does very poor in regards to performance. I have a dictionary as follow:  "data": { "employees": [ { "id": 274, "report": true }, { "id": 274, "report": false }, { "id": 276, "report": true }, { "id": 276, "report": true }, { "id": 278, "report": true }, { "id": 278, "report": false } ] }  I am looking to create a new dictionary with each individual employee ID with a count of each true value. Something like this: {274: {'id': 274, 'count': 1}, 276: {'id': 276, 'count': 2}, 278: {'id': 278, 'count': 1}}  My current code:  final_dict = {} for employee in result["data"]["employees"]: if employee["id"] not in final_dict.keys(): final_dict[employee["id"]] = {"id": employee["id"]} grouped_results = [res for res in result["data"]["employees"] if employee["id"] == res['id']] final_dict[employee["id"]]["count"] = len( [res for res in grouped_results if res["report"]] ) return final_dict  This does what it needs to do, but with the amount of data that is being processed it does very poorly. I am looking for some advice on how to avoid the multiple loops, in order to improve performance. Any advice helps!

Answer: There is no need to make multiple passes, just accumulate as you go so it is linear time not quadratic result = {} for employee in input_dict["data"]["employees"]: _id = employee["id"] if _id not in result: # note id is being added redundantly maybe rethink this result[_id] = dict(id=_id, count=0) result[_id]["count"] += employee["report"]
Question: I have the following dataframe / numpy array: a = np.array([ 55, 55, 69, 151, 151, 151, 103, 151, 151, 103]) df = pd.DataFrame([ 55, 55, 69, 151, 151, 151, 103, 151, 151, 103], columns = ["AOI"])   The values in this array can range from 1 to 151. I need to calculate the average consecutive repetition of the values. This involves the following logic:   55 occurs 2 time then 69 occurs 1 time then 151 occurs 3 times then 103 occurs 1 time then 151 occurs 2 times then 103 occurs 1 time.   So I have the following occurences for each value:   55: 2 69: 1 151: 3, 2 103: 1, 1   Now I need to calculate the mean of the occurences:   55: 2 69: 1 151: 2.5 ((3+2)/2) 103: 1 ((1+1)/2)  Ideally, in the end I have a numpy array with 151 entries. Each entry is zero and at index 55 I have the value 2, at index 69 the value 1, at index 151 the value 2.5 and at index 103 the value 1: [0,0,0,0,...,2,0,0,...,1,0,0,0,...,1,0,0,0,....,2.5]  How can this be achieved? Unfortunately, I am not even able to perform step 1. A simple groupby and count the rows does not work, as I need the count of consecutive occurences.

Answer: Here is one possible solution using pandas: df['group'] = (df.AOI != df.AOI.shift()).cumsum() x = df.groupby('group').agg({'AOI':('first', 'count')}).droplevel(0, axis=1) x = x.groupby('first')['count'].mean() x = x.reindex(range(0, x.index[-1] + 1), fill_value=0) # print(x) <- if you want pd.Series print(x.values) # print as numpy arrray  Prints: [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 2. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 2.5]
Question: How do I sum large (100, 1024, 1024) .npz files most efficiently? Is there a better file format to store python data of the given dimensions? I currently use this to sum the matrices: summed_matrix = np.sum([np.load(file) for file in files_list])  This exceeds my available memory.

Answer: Currently, you're loading all files at once and only then begin summing. If memory is a concern, a better approach would be to read and add one at a time: summed_matrix = np.zeros((100, 1024, 1024)) for file in files_list: summed_matrix += np.load(file)
Question: I have two Pydantic model classes where two fields have the same name as can be seen below: class SnowflakeTable(BaseModel): database: str schema: str table: str table_schema: List[SnowflakeColumn] class DataContract(BaseModel): schema: List[OpenmetadataColumn]  These model classes have been integrated with other modules to run via FastAPI and Mangum. Now, when I try hitting the APIs it gives me the below error: NameError: Field name "schema" shadows an attribute in parent "BaseModel"; you might want to use a different field name with "alias='schema'".  So, to resolve this I tried using Field of Pydantic as below but it didn't work either. class SnowflakeTable(BaseModel): database: str schema: str = Field(..., alias='schema') table: str table_schema: List[SnowflakeColumn] class DataContract(BaseModel): schema: List[OpenmetadataColumn] = Field(..., alias='schema')  The error remains the same. I tried multiple things w.r.t Fields. Also, tried using Route API but nothing worked. What am I missing here? TIA P.S. I can't rename the attributes. Thats against the API rules here.

Answer: You have to change the variable names because those names are already in use by pydantic. Try: class SnowflakeTable(BaseModel): database: str my_var_schema: str = Field(..., alias='schema') table: str table_schema: List[SnowflakeColumn] class DataContract(BaseModel): my_var_schema: List[OpenmetadataColumn] = Field(..., alias='schema')  Don't worry about API fields, if your field has an alias, then fastapi uses the field name in the alias in requests and responses. More about it: https://docs.pydantic.dev/latest/usage/model_config/#alias-precedence