eshangj/stackoverflow_q_and_a_sample huggingface dataset:
Question: I can able to see the .pkl which is downloaded using actions/download-artifact@v3 action in work directory along with Dockerfile as shown below,  When I try to COPY file inside Dockefile, I get a file not found error.  How to copy the files inside docker image that are downloaded(through github actions) before building docker image? Here is doc from github on docker support, but I didn't get exactly how to solve my issue. Any help would be really appreciated!! Dockerfile: name: Docker - GitHub workflow env: CONTAINER_NAME: xxx-xxx on: workflow_dispatch: push: branches: ["main"] pull_request: branches: ["main"] permissions: id-token: write contents: read jobs: load-artifacts: runs-on: ubuntu-latest environment: dev env: output_path: ./xxx/xxx_model.pkl steps: - uses: actions/checkout@v3 - name: Download PPE model file run: | az storage blob download --container-name ppe-container --name xxx_model.pkl -f "${{ env.output_path }}" - name: View output - after run: | ls -lhR - name: 'Upload Artifact' uses: actions/upload-artifact@v3 with: name: ppe_model path: ${{ env.output_path }} build: needs: load-artifacts runs-on: ubuntu-latest env: ACR: xxxx steps: - uses: actions/checkout@v3 - uses: actions/download-artifact@v3 id: download with: name: ppe_model # path: ${{ env.model_path }} - name: Echo download path run: echo ${{steps.download.outputs.download-path}} - name: View directory files run: | ls -lhR -a - name: Build container image uses: docker/build-push-action@v2 with: push: false tags: ${{ env.ACR }}.azurecr.io/${{ env.CONTAINER_NAME }}:${{ github.run_number }} file: ./Dockerfile 

Answer: In your workflow file, you're not specifying the context:  - name: Build container image uses: docker/build-push-action@v2 with: push: false tags: ${{ env.ACR }}.azurecr.io/${{ env.CONTAINER_NAME }}:${{ github.run_number }} file: ./Dockerfile  By default, that means that docker/build-push-action uses a git context. That will re-clone your repository... without your model. The fix, then, is to specify a path context, like this:  - name: Build container image uses: docker/build-push-action@v2 with: context: . push: false tags: ${{ env.ACR }}.azurecr.io/${{ env.CONTAINER_NAME }}:${{ github.run_number }} file: ./Dockerfile
Question: I am using seaborn object interface and I want to go a little further in graph customization. Here is a case with facet plot on 2 observations: df = pd.DataFrame( np.array([['A','B','A','B'],['odd','odd','even','even'], [1,2,1,2], [2,4,1.5,3],]).T , columns= ['kind','face','Xs','Ys'] ) ( so.Plot(df,x='Xs' , y='Ys') .facet("kind","face") .add(so.Dot()) .label(title= 'kind :{}'.format) )   As you can see, subplots title display "kind: | kind: ". I want to display "kind: | face: ". Obviously I tried title= 'kind :{}, face :{}'.format but it threw an error... I discovered .label(title= 'kind :{}'.format) iterates over facet observation inputs and made a quick and dirty workaround. df = pd.DataFrame( np.array([['A','B','A','B'],['odd','odd','even','even'], [1,2,1,2], [2,4,1.5,3],]).T , columns= ['kind','face','Xs','Ys'] ) def multiObs_facet_title(t:tuple) -> str: if t in ['A','B']: return 'kind: {}'.format(t) else: return 'face: {}'.format(t) ( so.Plot(df,x='Xs' , y='Ys') .facet("kind","face") .add(so.Dot()) .label(title= multiObs_facet_title) )   I wonder if there is a better way to do this without to have checking the value of observations?

Answer: It's probably not what you are looking for. But with a 2-D Seaborn facet (columns and rows), it doesn't seem too bad to do it in pandas if you want to avoid defining a custom function. df = pd.DataFrame( np.array([['A','B','A','B'],['odd','odd','even','even'], [1,2,1,2], [2,4,1.5,3],]).T , columns= ['kind','face','Xs','Ys'] ) df["kind_1"] = "kind: "+ df["kind"] df["face_1"] = "face: "+ df["face"] ( so.Plot(df,x='Xs' , y='Ys') .facet("kind_1","face_1") .add(so.Dot()) )
Question: I've been working with the python flet package for a while and I'd like to know how to get my window's position. Does anyone know anything? I googled but found nothing.

Answer: I haven't used this package before, but looking at the docs it seems that window_top and window_left on the root Page instance are what you're after (assuming this is a desktop app). See relevant docs here: https://flet.dev/docs/controls/page#window_top.
Question: I'm getting an error of Module not found when trying to create a test function to mock the get method of sqlalchemy query (with pytest) example: from mock import patch @patch('flask_sqlalchemy._QueryProperty.__get__') def test_get_all(queryMock): assert True  When running pytest i get an error: ModuleNotFoundError: No module named 'flask_sqlalchemy._QueryProperty'  I'm using the 3.0.2 version of Flask-SQLAlchemy. So i just changed to version 2.5.1 and it worked. However i think would be good to use the latest version. Is there any other way to mock the sql-alchemy query that works with the latest versions?

Answer: Use flask_sqlalchemy.model._QueryProperty.__get__ instead of flask_sqlalchemy._QueryProperty.__get__. This will resolve your issue as _QueryProperty class has been moved into model. from mock import patch @patch('flask_sqlalchemy.model._QueryProperty.__get__') def test_get_all(queryMock): assert True
Question: I'm trying to compile a Tkinter app as an executable for MacOs. I tried to use py2app and pyinstaller. I almost succeed using py2app, but it returns the following error: Traceback The Info.plist file must have a PyRuntimeLocations array containing string values for preferred Python runtime locations. These strings should be "otool -L" style mach ids; "@executable_stub" and "~" prefixes will be translated accordingly.  This is how the setup.py looks like: from setuptools import setup APP = ['main.py'] DATA_FILES = ['config.json'] OPTIONS = { 'argv_emulation': True } setup( app=APP, data_files=DATA_FILES, options={'py2app': OPTIONS}, setup_requires=['py2app'], )  And this is the directory structure: -modules/---__init.py__ | | | -- gui_module.py | | | -- scraper_module.py | | | -- app.ico | -config.json | -countries_list.txt | -main.py | -requirements.txt | -setup.py  I'm happy to share more details and the files if you need them.

Answer: The problem was that you need to give an executable path for the python framework you have on your MacOs. So I modify the setup.py setup.py from setuptools import setup class CONFIG: VERSION = 'v1.0.1' platform = 'darwin-x86_64' executable_stub = '/opt/homebrew/Frameworks/Python.framework/Versions/3.10/lib/libpython3.10.dylib' # this is important, check where is your Python framework and get the `dylib` APP_NAME = f'your_app_{VERSION}_{platform}' APP = ['main.py'] DATA_FILES = [ 'config.json', 'countries_list.txt', ('modules', ['modules/app.ico']), # this modules are automatically added if you use __init__.py in your folder # ('modules', ['modules/scraper_module.py']), # ('modules', ['modules/gui_module.py']), ] OPTIONS = { 'argv_emulation': False, 'iconfile': 'modules/app.ico', 'plist': { 'CFBundleName': APP_NAME, 'CFBundleDisplayName': APP_NAME, 'CFBundleGetInfoString': APP_NAME, 'CFBundleVersion': VERSION, 'CFBundleShortVersionString': VERSION, 'PyRuntimeLocations': [ executable_stub, # also the executable can look like this: #'@executable_path/../Frameworks/libpython3.4m.dylib', ] } } def main(): setup( name=CONFIG.APP_NAME, app=CONFIG.APP, data_files=CONFIG.DATA_FILES, options={'py2app': CONFIG.OPTIONS}, setup_requires=['py2app'], maintainer='foo bar', author_email='foo@domain.com', ) if __name__ == '__main__': main()  Then you need to run python3 setup.py py2app and now you can go and just double click on your_app_{VERSION}_{platform}.app. Recomendations by the py2app docs:  Make sure not to use the -A flag Do not use --argv-emulation when the program uses a GUI toolkit (as Tkinter) py2app options docs
Question: I'm trying to understand what actually happens when you declare a new class which inherits from a parent class in python. Here's a very simple code snippet: # inheritance.py class Foo(): def __init__(self, *args, **kwargs): print("Inside foo.__init__") print(args) print(kwargs) class Bar(Foo): pass print("complete")  If I run this there are no errors and the output is as I would expect. ❯ python inheritance.py complete  Here's a script with an obvious bug in it, I inherit from an instance of Foo() rather than the class Foo # inheritance.py class Foo(): def __init__(self, *args, **kwargs): print("Inside foo.__init__") print(f"{args=}") print(f"{kwargs=}\n") foo = Foo() class Bar(foo): <---- This is wrong pass print("complete")  This code runs without crashing however I don't understand why Foo.__init__() is called twice. Here's the output: ❯ python inheritance.py Inside foo.__init__ <--- this one I expected args=() kwargs={} Inside foo.__init__ <--- What is going on here...? args=('Bar', (<__main__.Foo object at 0x10f190b10>,), {'__module__': '__main__', '__qualname__': 'Bar'}) kwargs={} complete  On line 8 I instantiate Foo() with no arguments which is what I expected. However on line 9 Foo.__init__ is called with the arguments that would normally be passed to type() to generate a new class. I can see vaguely what's happening: class Bar(...) is code that generates a new class so at some point type("Bar", ...) needs to be called but:  How does this actually happen? Why does inheriting from an instance of Foo() cause Foo.__init__("Bar", <tuple>, <dict>) to be called? Why isn't type("Bar", <tuple>, <dict>) called instead? 

Answer: Python is using foo to determine the metaclass to use for Bar. No explicit metaclass is given, so the "most derived metaclass" must be determined. The metaclass of a base class is its type; usually, that's type itself. But in this case, the type of the only base "class", foo, is Foo, so that becomes the most derived metaclass. And so, class Bar(foo): pass  is being treated as class Bar(metaclass=Foo): pass  which means that Bar is created by calling Foo: Bar = Foo('Bar', (foo,), {})  Note that Bar is now an instance of Foo, not a type. Yes, a class statement does not necessarily create a class.
Question: Is there a way to reference a parameter in a Quarto figure or table caption? In the example below, I am able to reference my input parameter txt in a regular text block, but not in a figure caption. In the figure caption, only the raw text is displayed: --- title: "example" format: html params: txt: "example" --- ## I can reference it in text Here I can reference an input parameter: `r params$txt` ```{r} #| label: fig-example #| fig-cap: "Example: I cannot reference a parameter using `r params$txt` or params$txt." plot(1:10, 1:10) ``` 

Answer: Try with !expr  ```{r} #| label: fig-example #| fig-cap: !expr params$txt plot(1:10, 1:10) ```  -output   If we need to add some text, either paste or use glue #| fig-cap: !expr glue::glue("This should be {params$txt}")
Question: One can do that with dataclasses like so: from dataclasses import dataclass import pandas as pd @dataclass class MyDataClass: i: int s: str df = pd.DataFrame([MyDataClass("a", 1), MyDataClass("b", 2)])  that makes the DataFrame df with columns i and s as one would expect. Is there an easy way to do that with an attrs class? I can do it by iterating over the the object's properties and constructing an object of a type like dict[str, list] ({"i": [1, 2], "s": ["a", "b"]} in this case) and constructing the DataFrame from that but it would be nice to have support for attrs objects directly.

Answer: You can access the dictionary at the heart of a dataclass like so a = MyDataClass("a", 1) a.__dict__  this outputs: {'i': 'a', 's': 1}  Knowing this, if you have an iterable arr of type MyDataClass, you can access the __dict__ attribute and construct a dataframe arr = [MyDataClass("a", 1), MyDataClass("b", 2)] df = pd.DataFrame([x.__dict__ for x in arr])  df outputs:  i s 0 a 1 1 b 2  The limitation with this approach that if the slots option is used, then this will not work. Alternatively, it is possible to convert the data from a dataclass to a tuple or dictionary using dataclasses.astuple and dataclasses.asdict respectively. The data frame can be also constructed using either of the following: # using astuple df = pd.DataFrame( [dataclasses.astuple(x) for x in arr], columns=[f.name for f in dataclasses.fields(MyDataClass)] ) # using asdict df = pd.DataFrame([dataclasses.asdict(x) for x in arr])
Question: Cursor repeating and remaining in the Integrated Terminal in VS Code  I encountered this bug in my terminal while doing Python tutorial so downloaded and reinstalled the same version (latest version of VS Code) but the problem persists. I looked about for some answers but only found this tutorial which is not related. Anyway, I reinstalled the software only to find the bug was still present. The code runs but the cursor is an obstruction. From time to time I may type in the wrong execution so it's a bit of a bother.

Answer: Turned off GPU acceleration in the Terminal of VS Code. That has seemed to resolve the matter; No longer cursor trails. Settings > Type 'Render' > Go to Terminal › Integrated: Gpu Acceleration. Setting controls whether the terminal will leverage the GPU to do its rendering. Switch 'off' in dropdown menu
Question: Is there a way to unpack a tuple type alias? For example, ResultTypeA = tuple[float, float, dict[str, float]] ResultTypeB = tuple[*ResultTypeA, str, str]  So that ResultTypeB evaluates to  tuple[float, float, dict[str, float], str, str]  instead of  tuple[tuple[float, float, dict[str, float]], str, str]  If not possible, what would be a workaround for this?

Answer: What you are looking for may be the new typing.TypeVarTuple as proposed by PEP 646. Due to how new it is (Python 3.11+) and how big of a change this produces, many static type checkers still do not fully support it (see this mypy issue for example). Maybe typing.Unpack is actually more applicable in this case, but again hardly useful so long as type checkers don't support it. But at a certain point, you should probably ask yourself, if your design is all that good, if your type annotations become this complex.
Question: I am trying to analyze an earnings call using python regular expression. I want to delete unnecessary lines which only contain the name and position of the person, who is speaking next. This is an excerpt of the text I want to analyze: "Questions and Answers\nOperator [1]\n\n Shannon Siemsen Cross, Cross Research LLC - Co-Founder, Principal & Analyst [2]\n I hope everyone is well. Tim, you talked about seeing some improvement in the second half of April. So I was wondering if you could just talk maybe a bit more on the segment and geographic basis what you're seeing in the various regions that you're selling in and what you're hearing from your customers. And then I have a follow-up.\n Timothy D. Cook, Apple Inc. - CEO & Director [3]\n ..." At the end of each line that I want to delete, you have [some number]. So I used the following line of code to get these lines: name_lines = re.findall('.*[\d]]', text) This works and gives me the following list: ['Operator [1]', ' Shannon Siemsen Cross, Cross Research LLC - Co-Founder, Principal & Analyst [2]', ' Timothy D. Cook, Apple Inc. - CEO & Director [3]'] So, now in the next step I want to replace this strings in the text using the following line of code: for i in range(0,len(name_lines)): text = re.sub(name_lines[i], '', text)  But this does not work. Also if I just try to replace 1 instead of using the loop it does not work, but I have no clue why. Also if I try now to use re.findall and search for the lines I obtained from the first line of code I don`t get a match.

Answer: The first argument to re.sub is treated as a regular expression, so the square brackets get a special meaning and don't match literally. You don't need a regular expression for this replacement at all though (and you also don't need the loop counter i): for name_line in name_lines: text = text.replace(name_line, '')
Question: It see that depending on system and configuration, packages are installed in different places. Example: Machine 1: pip3 install fb-idb pip3 show fb-idb > ... > /opt/homebrew/lib/python3.9/site-packages  Machine 2: pip3 install fb-idb pip3 show fb-idb > ... > /us/local/lib/python3.10/site-packages  Now the problem I have is that on machine 1, I got the path to the binary by executing which idb (> /opt/homebrew/bin/idb), but on machine 2, it seems the bin dir wasn't added to the path, so which doesn't work. Is there a way to figure out where the binaries are installed, if I only have the site-packages path?

Answer: pip3 show --files fb-idb shows where pip has installed all the files of the package. Run pip3 show --files fb-idb | grep -F /bin/  to extract the directory where pip installed scripts and entry points (On Windows it's \Scripts\). The directories are related to the header Location: so either do grep -F Location: separately or do it combined: pip3 show --files fb-idb | grep 'Location:\|/bin/'
Question: I just installed pyenv and virtualenv following: https://realpython.com/intro-to-pyenv/ After completing installation I was prompted with: pyenv-virtualenv: prompt changing will be removed from future release. configure `export PYENV_VIRTUALENV_DISABLE_PROMPT=1' to simulate the behavior  I added export PYENV_VIRTUALENV_DISABLE_PROMPT=1 to my .bash_aliases just to see what the behavior would be, and sure enough it removed the prompt that used to exist at the beginning of the command prompt indicating the pyenv-virtualenv version. Used to be like: (myenv) user@foo:~/my_project [main] $ where (myenv) is the active environment, and [main] is the git branch. I would love to have the environment indicator back! It is very useful. I guess at some possibilities such as: export PYENV_VIRTUALENV_DISABLE_PROMPT=0 export PYENV_VIRTUALENV_ENABLE_PROMPT=1 But these do not return the previous behavior. I have googled all over and can't figure out how to get this back. This answer is not useful, as it seems like a hack around the original functionality, and displays the environment always, not just when I enter (or manually activate) an environment.

Answer: Borrowing a solution from here, the following works (added to .bashrc or .bash_aliases): export PYENV_VIRTUALENV_DISABLE_PROMPT=1 export BASE_PROMPT=$PS1 function updatePrompt { if [[ "$(pyenv virtualenvs)" == *"* $(pyenv version-name) "* ]]; then export PS1='($(pyenv version-name)) '$BASE_PROMPT else export PS1=$BASE_PROMPT fi } export PROMPT_COMMAND='updatePrompt'
Question: I want to make my legend size bigger in Pyplot. I used this answer to do that. Here is my code. import matplotlib.pyplot as plt import seaborn as sns sns.set_style("whitegrid") plt.rcParams['figure.figsize'] = [15, 7] lst = [1,2,3,4,5,6,7,8,9,8,7,6,5,4,3,4,5,6] plt.plot(lst) plt.legend(fontsize="x-large") # Here I make it bigger but doesn't work plt.legend(["This is my legend"]) plt.ylabel('some numbers') plt.show()  I get this warning and I don't know what is wrong. I don't understand what "Artist" means here.  No artists with labels found to put in legend. Note that artists whose label start with an underscore are ignored when legend() is called with no argument. 

Answer: "Artist" is a term from matplotlib: https://matplotlib.org/stable/tutorials/intermediate/artists.html Presumably the error message means that there are no items in the legend whose font size can be changed. Maybe pass the fontsize argument to the same plt.legend call in which you create the legend, or call plt.legend(fontsize=...) after you have created the legend.
Question: I've started using python Snowpark and no doubt missing obvious answers based on being unfamiliar to the syntax and documentation. I would like to do a very simple operation: append a new column to an existing Snowpark DataFrame and assign with a simple string. Any pointers to the documentation to what I presume is readily achievable would be appreciated.

Answer: You can do this by using the function with_column in combination with the lit function. The with_column function needs a Column expression and for a literal value this can be made with the lit function. see documentation here: https://docs.snowflake.com/en/developer-guide/snowpark/reference/python/api/snowflake.snowpark.functions.lit.html from snowflake.snowpark.functions import lit snowpark_df = snowpark_df.with_column('NEW_COL', lit('your_string'))
Question: This is easy to do in R and I am wondering if it is straight forward in Python and I am just missing something, but how do you create a vector of NaN values and Null values in Python? I am trying to do this using the np.full function. R Code: vec <- vector("character", 15) vec[1:15] <- NA vec  Python Code unknowns = np.full(shape = 5, fill_value = ???, dtype = 'str') '''test if fill value worked or not''' random.seed(1177) categories = np.random.choice(['web', 'software', 'hardware', 'biotech'], size = 15, replace = True) categories = np.concatenate([categories, unknowns]) example = pd.DataFrame(data = {'categories': categories}) example['transformed'] = [ x if pd.isna(x) == False else 'unknown' for x in example['categories']] print(example['transformed'].value_counts())  This should lead to 5 counts of unknown in the value counts total. Ideally I would like to know how to write this fill_value for NaN and Null and know whether it differs for variable types. I have tried np.nan with and without the string data type. I have tried None and Null with and without quotes. I cannot think of anything else to try and I am starting to wonder if it is possible. Thank you in advance and I apologize if this question is already addressed and for my lack of knowledge in this area.

Answer: you could use either None or np.nan to create an array of just missing values in Python like so: np.full(shape=5, fill_value=None) np.full(shape=5, fill_value=np.nan)  back to your example, this works just fine: import numpy as np import pandas as pd unknowns = np.full(shape=5, fill_value=None) categories = np.random.choice(['web', 'software', 'hardware', 'biotech'], size = 15, replace = True) categories = np.concatenate([categories, unknowns]) example = pd.DataFrame(data = {'categories': categories}) example['transformed'] = [ x if pd.isna(x) == False else 'unknown' for x in example['categories']] print(example['transformed'].value_counts())  Lastly, this line is inefficient. example['transformed'] = [ x if pd.isna(x) == False else 'unknown' for x in example['categories']] You do want to avoid loops & list comprehensions when using pandas on large data, this is going to run much faster: example['transformed'] = example.categories.apply(lambda s: s if s else 'unknown')
Question: I want to test whether a certain method can handle different dates in a pandas dataframe, which it takes as an argument. The following example should clarify what kind of setup I want. In the example column('Date', dtype=pd.datetime) does not work for creating a date column in the test dataframe: from hypothesis import given from hypothesis.extra.pandas import column, data_frames import pandas as pd from unittest import TestCase class TestExampleClass(TestCase): @given(data_frames([column('A', dtype=str), column('B', dtype=int),column('Date', dtype=pd.datetime)])) def test_example_test_method(self, dataframe): self.assertTrue(True)  Any ideas? I am aware of How to create a datetime indexed pandas DataFrame with hypothesis library?, but it did not help for my specific case.

Answer: Use dtype="datetime64[ns]" instead of dtype=pd.datetime.  I've opened an issue to look into this in more detail and give helpful error messages when passed pd.datetime, datetime, or a unitless datetime dtype; this kind of confusion isn't the user experience we want to offer!