eshangj/stackoverflow_q_and_a_sample huggingface dataset:
Question: python 3.8 with VScode. I have two sibling directories, and I want to import the first sibling (support_tools) to the second one. this is my project hierarchy: ├── support_tools │ ├── __init__.py │ └── file_utils.py └── optimizations ├──.vscode │ ├── launch.json │ └── settings.json ├── __init__.py └── test1.py  I added the parent path to the launch.json: { // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "name": "Python: Current File", "type": "python", "request": "launch", "env": { "PYTHONPATH": "${workspaceFolder}${pathSeparator}..${pathSeparator}", }, } ] }  and to the settings.json: { "python.analysis.extraPaths": [ "${workspaceFolder}/../" ] }  The pylance recognize the module support_tools.py, but I cannot import the support_tools module without appending the parent path to the os.paths: sys.path.append("../") In this tutorial: https://k0nze.dev/posts/python-relative-imports-vscode/ they clearly mention that after adding the paths to both file, I should be able to remove the os.path.append line In addition I tried to find an answer in the following pages: VSCode settings for Pylance Import Sibling Packages with __init__.py doesn't work Importing modules from parent folder Thanks for the helpers

Answer:  A simple way is to use the optimizations parent folder as the workspace. VsCode searches files using the workspace as the root directory. If the file you want to import is not in the workspace, it will not find the content. Tips: You can use the absolute path in "python. analytics. extraPaths". Because in the workspace, the workspace is already the root directory. If you use the relative path, there does not exist the parent directory.
Question: Im using unittest.mock for building tests for my python code. I have a method that I am trying to test that contains a async call to another function. I want to patch that async call so that I can just have Mock return a testing value for the asset id, and not actually call the async method. I have tried many things I've found online, but none have worked thus far. Simplified example below: test.py import pytest from app.create.creations import generate_new_asset from app.fakeapi.utils import create_asset from unittest.mock import Mock, patch @patch("app.fakeapi.utils.create_asset") @pytest.mark.anyio async def test_generate_new_asset(mock_create): mock_create.return_value = 12345678 await generate_new_asset() ...  creations.py from app.fakeapi.utils import create_asset ... async def generate_new_asset() ... # When I run tests this does not return the 12345678 value, but actually calls the `create_asset` method. return await create_asset(...) 

Answer: Testing async code is bit tricky. If you are using python3.8 or higher AsyncMock is available. Note: it will work only for Python > 3.8 I think in your case event loop is missing. Here is the code which should work, you may need to do few tweaks. You may also need to install pytest-mock. Having it as fixture will allow you to have mock different values for testing for different scenarios. import asyncio from unittest.mock import AsyncMock, Mock @pytest.fixture(scope="module") def mock_create_asset(mocker): async_mock = AsyncMock() mocker.patch('app.fakeapi.utils.create_asset', side_effect=async_mock) return async_mock @pytest.fixture(scope="module") def event_loop(): return asyncio.get_event_loop() @pytest.mark.asyncio async def test_generate_new_asset(mock_create_asset): mock_create_asset.return_value = 12345678 await generate_new_asset()
Question: what's up? I am having a little problem, where I need to use the pandas dropna function to remove rows from my dataframe. However, I need it to not delete the unique values from my dataframe. Let me explain better. I have the following dataframe:     id birthday     0102-2 09/03/2020   0103-2 14/03/2020   0104-2 NaN   0105-2 NaN   0105-2 25/03/2020   0108-2 07/04/2020     In the case above, I need to delete the row from my dataframe based on the NaN values in the birthday column. However, as you can see the id "0104-2" is unique unlike the id "0105-2" where it has a NaN value and another with a date. So I would like to keep track of all the lines that have NaN that are unique. Is it feasible to do this with dropna, or would I have to pre-process the information beforehand?

Answer: You could sort by the birthday column and then drop duplicates keeping the first out of the two, by doing the following: The complete code would look like this: import pandas as pd import numpy as np data = { "id": ['102-2','103-2','104-2', '105-2', '105-2', '108-2'], "birthday":['09/03/2020', '14/03/2020', np.nan, np.nan, '25/03/2020', '07/04/2020'] } df = pd.DataFrame(data) df.sort_values(['birthday'], inplace=True) df.drop_duplicates(subset="id", keep='first', inplace=True) df.sort_values(['id'], inplace=True)   CODE EXPLANATION: Here is the original dataframe: import pandas as pd import numpy as np data = { "id": ['102-2','103-2','104-2', '105-2', '105-2', '108-2'], "birthday":['09/03/2020', '14/03/2020', np.nan, np.nan, '25/03/2020', '07/04/2020'] } df = pd.DataFrame(data)   Now sort the dataframe: df.sort_values(['birthday'], inplace=True)   Then drop the duplicates based on the id column. Keeping only the first value. df.drop_duplicates(subset="id", keep='first', inplace=True)
Question: I was just writing a python code and after switching folder, it threw an error stating:- Error loading webview: Error: Could not register service workers: InvalidStateError: Failed to register a ServiceWorker: The document is in an invalid state.

Answer: Read this issue which can help. Emptying the cache is an effective solution. The simplest step is killall code or restart vscode.
Question: I have an app that tracks truck appointments. In this app I have a list of carriers in a db table. When the user wants to update an appointment, they can choose a new carrier from the list of carriers in the db using a dropdown menu. How can I set the dropdown default value to be the current carrier selection? Here's what I tried so far (without any luck): app.py: class carriers_db(db.Model): carrier_id = db.Column(db.Integer, primary_key=True) carrier_name = db.Column(db.String(100), nullable=False) class appts_db(db.Model): id = db.Column(db.Integer, primary_key=True) carrier = db.Column(db.String(100), nullable=False) @app.route('/update/<int:id>', methods=['GET', 'POST']) def update(id): appt = appts_db.query.get_or_404(id) carriers = carriers_db.query.order_by(carriers_db.carrier_name).all()  update.html: <h4>Current carrier: {{ appt.carrier }}</h4> <label>Option to select a new carrier:</label><br> <select name="carrier"> {% for carrier in carriers %} <option value = "{{ carrier.carrier_name }}" selected = "{{ carrier.carrier_name }}"> {{ carrier.carrier_name }}</option> {% endfor %} </select> 

Answer: You can add a check if the value is equal to the selected value in the for loop in update.html: update.html: <h4>Current carrier: {{ appt.carrier }}</h4> <label>Option to select a new carrier:</label><br> <select name="carrier"> {% for carrier in carriers %} <option value = "{{ carrier.carrier_name }}" {% if carrier.carrier_name == appt.carrier %} selected {% endif %}> {{ carrier.carrier_name }}</option> {% endfor %} </select>  A full example to show selected option value in Jinja template: app.py: from flask import Flask, render_template, flash, url_for, request, redirect app = Flask(__name__) app.secret_key = b'a secret key' @app.route('/update', methods=['GET', 'POST']) def show_update(): current_carrier = "tello" carriers = [{"carrier_name": "mint"}, {"carrier_name": "tmobile"}, {"carrier_name": "tello"}] return render_template('update.html', current_carrier=current_carrier, carriers=carriers)  update.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Update page</title> </head> <body> <h4>Current carrier: {{ current_carrier }}</h4> <label>Option to select a new carrier:</label><br> <select name="carrier"> {% for carrier in carriers %} <option value="{{ carrier.carrier_name }}" {% if carrier.carrier_name== current_carrier %} selected {% endif %}> {{ carrier.carrier_name }} </option> {% endfor %} </select> </body> </html>  Output:
Question: I am using the RangeSlider in Python Dash. This slider is supposed to allow users to select a range of dates to display, somewhere between the minimum and maximum years in the dataset. The issue that I am having is that each mark shows as 2k due to it being automatically rounded. The years range between 1784 and 2020, with a step of 10 each time. How do I get the marks to show as the actual dates and not just 2k? This is what I have below. dcc.RangeSlider(sun['Year'].min(), sun['Year'].max(), 10, value=[sun['Year'].min(), sun['Year'].max()], id='years') 

Answer: You can use attribute marks to style the ticks of the sliders as follows: marks={i: '{}'.format(i) for i in range(1784,2021,10)}  The full code: from dash import Dash, dcc, html app = Dash(__name__) app.layout = html.Div([ dcc.RangeSlider(1784, 2020, id='non-linear-range-slider', marks={i: '{}'.format(i) for i in range(1784,2021,10)}, value=list(range(1784,2021,10)), dots=False, step=10, updatemode='drag' ), html.Div(id='output-container-range-slider-non-linear', style={'margin-top': 20}) ]) if __name__ == '__main__': app.run_server(debug=True, use_reloader=False)  Output
Question: I want to find a list of all possible combinations of 0's and 1's. The only condition is that the number of 1's must be more than or equal to the number of 0's. For example for n = 4 the output should be something like this: [(0, 0, 1, 1), (0, 1, 0, 1), (0, 1, 1, 0), (0, 1, 1, 1), (1, 0, 0, 1), (1, 0, 1, 0), (1, 0, 1, 1), (1, 1, 0, 0), (1, 1, 0, 1), (1, 1, 1, 0), (1, 1, 1, 1)]  Is there an elegant way to do this?

Answer: You can use distinct_permutations: from more_itertools import distinct_permutations def get_combos(n): for i in range((n+1)//2, n + 1): for permutation in distinct_permutations([1] * i + [0] * (n - i), n): yield permutation print(list(get_combos(4))) # [(0, 0, 1, 1), (0, 1, 0, 1), (0, 1, 1, 0), (1, 0, 0, 1), (1, 0, 1, 0), (1, 1, 0, 0), (0, 1, 1, 1), (1, 0, 1, 1), (1, 1, 0, 1), (1, 1, 1, 0)]  Here, we simply consider the permutations of each sublist: [0, 0, 1, 1] [0, 1, 1, 1] [1, 1, 1, 1]  Notice that for large n, the yield statement is very useful because you do not generate all permutations at once. We need to use distinct_permutations because you use just 1's and 0's , so regular permutations will give you repeated elements.  If you don't want to install another library, you can use: from itertools import permutations def get_combos(n): for i in range(n // 2 if n%2 == 0 else n//2 + 1, n): for permutation in permutations([1] * i + [0] * (n - i), n): yield permutation print(set(get_combos(4))) # {(0, 1, 0, 1), (0, 1, 1, 1), (1, 0, 1, 1), (1, 1, 0, 0), (1, 1, 1, 0), (0, 1, 1, 0), (1, 0, 1, 0), (1, 0, 0, 1), (1, 1, 0, 1), (0, 0, 1, 1)}  as set will eliminate the repeated elements, at the cost of needing to process the entire set of permutations at once (ie., by calling set, you will consume the entire generator immediately, rather than drawing elements from it as you need them). More details on distinct_permutations It might not be clear why these are needed. Consider this list: [1, 2]  permutations, by default, will tell you that all the permutations of this list are (1, 2)  and (2, 1)  However, permutations doesn't bother checking what the elements are or if they are repeated, so it simply performs the swap as above and if the list is [1, 1]  you'll get back [(1, 1), (1, 1)]
Question: Receiving a string that has 2 or more words and a certain length, I need to insert spaces uniformly between words, adding additional spaces between words from left to right. Let's say I receive "Hello I'm John" and a length of 17, it should return:'Hello I'm John I have tried many different ways and I couldn't do the left-to-right requirement. This is what I have now:  if ' ' in string: final_string='' string=string.split() for i in range(len(string)): if string[i]==string[-1]: final_string+=string[i] else: final_string+=string[i]+' ' print(final_string)  Output: Hello I'm John which gives me a length greater than what I want...

Answer: Probably something like this? words = cad_carateres.split() total_nb_of_spaces_to_add = total_string_length - len(cad_carateres) nb_of_spaces_to_add_list = [total_nb_of_spaces_to_add // (len(words) - 1) + int(i < (total_nb_of_spaces_to_add % (len(words) - 1))) for i in range(len(words) - 1)] + [0] result = ' '.join([w + ' ' * (nb_of_spaces_to_add) for w, nb_of_spaces_to_add in zip(words, nb_of_spaces_to_add_list)])  First line - you split your line into words Second line - how many spaces, in total, we need to add. Third line - suppose that we need to add 20 spaces, and we have 7 words in total (thus, 6 gaps where we add additional spaces). Let's add [3, 3, 2, 2, 2, 2] spaces in these gaps, and, obviously 0 spaces after the last word. nb_of_spaces_to_add_list will contain the list like [3, 3, 2, 2, 2, 2, 0] The last line line - join the padded (with spaces, their number comes from nb_of_spaces_to_add_list) words into the string - this is your result! I also use zip function to convert 2 one-dimensional lists (words and number of spaces to add) into a two-dimensional list, this allows me to use list comprehension.
Question: @dataclass(frozen=True, eq=True, order=True) class C: x: int l = [C(1), C(2), C(1)] print(sorted(l))  The above code works but gives a warning: Expected type 'Iterable' (matched generic type 'Iterable[SupportsLessThanT]'), got 'list[C]' instead. I think the order=True param passed to @dataclass should result in generation of __lt__ etc and thus confirm to SupportsLessThanT? An explicit implementation of __lt__ silences the warning, but how do I silence it without?

Answer: Apparently a known bug in PyCharm, tracked here
Question: I have this dataframe: a = [0,0,5,0,0,0,0,0,0,7,0,0,0,0,0,0,0,0] b = [0,0,0,0,250,350,500,0,0,0,0,0,0,125,70,95,0,0] df = pd.DataFrame(columns=['a', 'b']) df = pd.DataFrame.assign(df, a=a, b=b) df a b 0 0 0 1 0 0 2 5 0 3 0 0 4 0 250 5 0 350 6 0 500 7 0 0 8 0 0 9 7 0 10 0 0 11 0 0 12 0 0 13 0 125 14 0 70 15 0 95 16 0 0 17 0 0  I wanted to record the first value from column B, following each iteration through column A. I was looking for this result: 5 250 7 125  My first attempt is this Loop below. I tried to extract the row index, so I could pass it to the next for loop, to start the loop at n index, but it's not quite what I expected. for item in df.a: if item > 0: print(item) index = df.iterrows() print(index) for i in df.b: if i > 0: print(i) break which yields: 5 <generator object DataFrame.iterrows at 0x000002C654B0EF20> 250 7 <generator object DataFrame.iterrows at 0x000002C654B01C80> 250  Advice on how to approach this is much appreciated!

Answer: Another possible solution: df1 = df.mask(df.eq(0)).dropna(how='all') df1.assign(b = df1['b'].shift(-1)).dropna()  Output:  a b 2 5.0 250.0 9 7.0 125.0
Question: I'm trying to create a custom constructor for my python dataclass that will ideally take in a dict (from request json data) and fill in the attributes of the dataclass. Eg @dataclass class SoldItem: title: str purchase_price: float shipping_price: float order_data: datetime def main(): json = requests.get(URL).json() sold_item = SoldItem(json)  So I want SoldItem to have a method that saves the json data in the appropriate attributes of the dataclass instead of having to do SoldItem(title=json['title']... I would also preferably have the class be able to recognise that the data being passed in is a dict and execute the from dict constructor. I have done my best to look up possible solutions but have come up mostly empty. Any help would be greatly appreciated.

Answer: For the simplest approach - with no additional libraries - I would personally go with a de-structuring approach via **kwargs. For example: >>> json = {'title': 'test', 'purchase_price': 1.2, 'shipping_price': 42, 'order_data': datetime.min} >>> SoldItem(**json) SoldItem(title='test', purchase_price=1.2, shipping_price=42, order_data=datetime.datetime(1, 1, 1, 0, 0))   In case of a more involved use case, such as:  a nested dataclass structure the input dict is the result of an API call keys in the dict are not in snake_case value for a key does not match annotated type for a dataclass field  In such cases, I would suggest third-party tools that will automagically handle this data transform for you. For instance, the dataclass-wizard is a (de)serialization library I have come up with, for exactly this use case, i.e. when the input data might be coming from another source, such as the result of an API call or response. It can be installed with pip: pip install dataclass-wizard  Usage: from dataclasses import dataclass from datetime import datetime from dataclass_wizard import JSONWizard @dataclass class SoldItem(JSONWizard): title: str purchase_price: float shipping_price: float order_data: datetime def main(): from pprint import pprint # json = requests.get(URL).json() json = {'title': 'test', 'purchasePrice': '1.23', 'shipping-price': 42, 'Order_Data': '2021-01-02T12:34:56Z'} # create a `SoldItem` instance from an input `dict`, # such as from an API response. sold_item = SoldItem.from_dict(json) pprint(sold_item) if __name__ == '__main__': main()  Prints: SoldItem(title='test', purchase_price=1.23, shipping_price=42.0, order_data=datetime.datetime(2021, 1, 2, 12, 34, 56, tzinfo=datetime.timezone.utc))
Question: I'm trying to change the background colour for the title in plotly to something like the below:  Plotly Code: from plotly.subplots import make_subplots import plotly.graph_objects as go fig = make_subplots( rows=2, cols=2, subplot_titles=("Plot 1", "Plot 2", "Plot 3", "Plot 4")) fig.add_trace(go.Scatter(x=[1, 2, 3], y=[4, 5, 6]), row=1, col=1) fig.add_trace(go.Scatter(x=[20, 30, 40], y=[50, 60, 70]), row=1, col=2) fig.add_trace(go.Scatter(x=[300, 400, 500], y=[600, 700, 800]), row=2, col=1) fig.add_trace(go.Scatter(x=[4000, 5000, 6000], y=[7000, 8000, 9000]), row=2, col=2) fig.update_layout(height=500, width=700, title_text="Multiple Subplots with Titles") fig.show()   Is there a way to change the background colour of the title text using plotly?

Answer: From what I can see, there does not seem to be a direct way to set the subplot title backgrounds, however, the closest I could get to what you were looking for was to create an annotation at the top of each chart, and set it's background accordingly.  Now you could perhaps generate some form of formula to calculate the best position of each annotation, however, I just did it by eye - as a proof of concept. In general, the x-coord is the middle x-point of each chart, and the y-coord is just above the maximum y-value of each chart. Please let me know what you think: from plotly.subplots import make_subplots import plotly.graph_objects as go fig = make_subplots( rows=2, cols=2) fig.add_trace(go.Scatter(x=[1, 2, 3], y=[4, 5, 6]),row=1, col=1) fig.add_trace(go.Scatter(x=[20, 30, 40], y=[50, 60, 70]), row=1, col=2) fig.add_trace(go.Scatter(x=[300, 400, 500], y=[600, 700, 800]), row=2, col=1) fig.add_trace(go.Scatter(x=[4000, 5000, 6000], y=[7000, 8000, 9000]), row=2, col=2) fig.update_layout(height=500, width=700, title_text="Multiple Subplots with Annotated Titles", annotations=[dict( x=2, y=6.3, # Coordinates of the title (plot 1) xref='x1', yref='y1', text='* Plot 1 Title *', bgcolor = "#2b3e50", # dark background font_color = "#FFFFFF", # white font showarrow=False), dict( x=30, y=73, # Coordinates of the title (plot 2) xref='x2', yref='y2', text='* Plot 2 Title *', bgcolor = "#2b3e50", # dark background font_color = "#FFFFFF", # white font showarrow=False), dict( x=400, y=830, # Coordinates of the title (plot 3) xref='x3', yref='y3', text='* Plot 3 Title *', bgcolor = "#2b3e50", # dark background font_color = "#FFFFFF", # white font showarrow=False), dict( x=5000, y=9290, # Coordinates of the title (plot 4) xref='x4', yref='y4', text='* Plot 4 Title *', bgcolor = "#2b3e50", # dark background font_color = "#FFFFFF", # white font showarrow=False)]) fig.show()  OUTPUT:
Question: I have a dataframe, and I would like to group by a column and take the head of each group, but I want the depth of the head to be defined by a function of the group label. If it weren't for the variable group sizes, I could easily do df.groupby('label').head(n). I can imagine a solution that involves iterating through df['label'].unique(), slicing the dataframe and building a new one, but I'm in a context where I'm pretty sensitive to performance so I'd like to avoid that kind of iteration if possible. Here's an exmaple dataframe:  label values 0 apple 7 1 apple 5 2 apple 4 3 car 9 4 car 6 5 dog 5 6 dog 3 7 dog 2 8 dog 1  and code for my example setup: import pandas as pd df = pd.DataFrame({'label': ['apple', 'apple', 'apple', 'car', 'car', 'dog', 'dog', 'dog', 'dog'], 'values': [7, 5, 4, 9, 6, 5, 3, 2 ,1]}) def depth(label): if label == 'apple': return 1 elif label == 'car': return 2 elif label == 'dog': return 3  my desired output is a dataframe with the number of rows from each group defined by that function:  label values 0 apple 7 3 car 9 4 car 6 5 dog 5 6 dog 3 7 dog 2 

Answer: I would use a dictionary here and using <group>.name in groupby.apply: depth = {'apple': 1, 'car': 2, 'dog': 3} out = (df.groupby('label', group_keys=False) .apply(lambda g: g.head(depth.get(g.name, 0))) )  NB. if you really need a function, you can do the same with a function call. Make sure to return a value in every case. Alternative option with groupby.cumcount and boolean indexing: out = df[df['label'].map(depth).gt(df.groupby('label').cumcount())]  output:  label values 0 apple 7 3 car 9 4 car 6 5 dog 5 6 dog 3 7 dog 2
Question: I want to make c++ code callable from python. https://docs.python.org/3/extending/ explains how to do this, but does not mention how to specify c++ version. By default distutils calls g++ with a bunch of arguments, however does not provide the version argument. Example of setup.py: from distutils.core import setup, Extension MOD = "ext" module = Extension("Hello", sources = ["hello.cpp"]) setup( name="PackageName", version="0.01", description="desc", ext_modules = [module] )  I'm using linux, if that matters.

Answer: You can pass compiler arguments as extra_compile_args so for example module = Extension( "Hello", sources = ["hello.cpp"], extra_compile_args = ["-std=c++20"] )