eshangj/stackoverflow_q_and_a_sample huggingface dataset:
Question: I have this code to check whether or not a variable is a number or a Vector2: def __mul__(self, other): match type(other): case int | float: pass case Vector2: pass  If I run this, I get SyntaxError: name capture 'int' makes remaining patterns unreachable  And when I hover in vscode, it gives me: "int" is not accessed Irrefutable pattern allowed only as the last subpattern in an "or" pattern All subpatterns within an "or" pattern must target the same names Missing names: "float" Irrefutable pattern is allowed only for the last case statement  If I remove  | float it still won't work, so I can't make them separate cases.

Answer: Case with a variable (ex: case _: or case other:) needs to be the last case in the list. It matches any value, where the value was not matched by a previous case, and captures that value in the variable. A type can be used in a case, but implies isinstance(), testing to determine if the value being matched is an instance of that type. Therefore, the value used for the match should be the actual variable other rather than the type type(other), since type(other) is a type whose type would match type(). def __mul__(self, other): match other: case int() | float(): pass case Vector2(): pass
Question: I have the below code that defines an enum and uses enum.auto() to give entries generated values starting from 1: from enum import Enum, auto class Colors(Enum): RED = auto() BLUE = auto() YELLOW = auto() def main(): print(Colors.RED.value) print(Colors.BLUE.value) print(Colors.YELLOW.value) if __name__ == '__main__': main()  Output: 1 2 3  The code works fine and used to not have any warnings, but after updating PyCharm today, I am now getting the following warning for auto(): Parameter(s) unfilled Possible callees: EnumMeta.__call__(cls: Type[_T], value, names: None = ...) EnumMeta.__call__(cls: EnumMeta, value: str, names: Union[str, Iterable[str], Iterable[Iterable[str]], Mapping[str, Any]], *, module: Optional[str] = ..., qualname: Optional[str] = ..., type: Optional[type] = ..., start: int = ..., boundary: Optional[FlagBoundary] = ...) EnumMeta.__call__(cls: Type[_T], value, names: None = ...) EnumMeta.__call__(cls: EnumMeta, value: str, names: Union[str, Iterable[str], Iterable[Iterable[str]], Mapping[str, Any]], *, module: Optional[str] = ..., qualname: Optional[str] = ..., type: Optional[type] = ..., start: int = ...)  I checked the Python documentation but couldn't find anything relevant, as all the examples still use auto() without any parameters. I assume the new warning is because PyCharm is using updated Python linting rules. How do I resolve this warning? UPDATE 1: It seems that PyCharm is detecting enum.auto() as enum.auto(IntFlag), thus the warning that the parameter is unfilled:  I will also report this issue to the PyCharm devs. Perhaps it's a bug. UPDATE 2: Nevermind, everyone. I just found out this was a bug and was reported a month ago here. UPDATE 3: The bug has finally been fixed! 🎉

Answer: Nevermind, everyone. I just found out this was a bug and was reported a month ago here. UPDATE: The bug has finally been fixed! 🎉
Question: I'm trying to run Django from a Docker container on Heroku, but to make that work, I need to run python manage.py collectstatic during my build phase. To achieve that, I wrote the following Dockerfile: # Set up image FROM python:3.10 WORKDIR /usr/src/app ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 # Install poetry and identify Python dependencies RUN pip install poetry COPY pyproject.toml /usr/src/app/ # Install Python dependencies RUN set -x \ && apt update -y \ && apt install -y \ libpq-dev \ gcc \ && poetry config virtualenvs.create false \ && poetry install --no-ansi # Copy source into image COPY . /usr/src/app/ # Collect static files RUN python -m manage collectstatic -v 3 --no-input  And here's the docker-compose.yml file I used to run the image: services: db: image: postgres env_file: - .env.docker.db volumes: - db:/var/lib/postgresql/data networks: - backend ports: - "5433:5432" web: build: . restart: always env_file: - .env.docker.web ports: - "8001:$PORT" volumes: - .:/usr/src/app depends_on: - db networks: - backend command: gunicorn --bind 0.0.0.0:$PORT myapp.wsgi volumes: db: networks: backend: driver: bridge  The Dockerfile builds just fine, and I can even see that collectstatic is running and collecting the appropriate files during the build. However, when the build is finished, the only evidence that collectstatic ran is an empty directory called staticfiles. If I run collectstatic again inside of my container, collectstatic works just fine, but since Heroku doesn't persist files created after the build stage, they disappear when my app restarts. I found a few SO answers discussing how to get collectstatic to run inside a Dockerfile, but that's not my problem; my problem is that it does run, but the collected files don't show up in the container. Anyone have a clue what's going on? UPDATE: This answer did the trick. My docker-compose.yml was overriding the changes made by collectstatic with this line:  volumes: - .:/usr/src/app  If, like me, you want to keep the bind mount for ease of local development (so that you don't need to re-build each time), you can edit the command for the web service as follows:  command: bash -c "python -m manage collectstatic && gunicorn --bind 0.0.0.0:$PORT myapp.wsgi"  Note that the image would have run just fine as-is had I pushed it to Heroku (since Heroku doesn't use the docker-compose.yml file), so this was just a problem affecting containers I created on my local machine.

Answer: You are overriding the content of /usr/src/app in your container when you added the volumes: - .:/usr/src/app  to your docker compose file. Remove it since you already copied everything during the build.
Question: I am currently working on showing some visuals about how my NER model has performed. The data I currently have looks like this: counter_list = [ ('Name', {'p':0.56,'r':0.56,'f':0.56}), ('Designation', {'p':0.10,'r':0.20,'f':0.14}), ('Location', {'p':0.56,'r':0.56,'f':0.56}), ('Name', {'p':0.14,'r':0.14,'f':0.14}), ('Designation', {'p':0.10,'r':0.20,'f':0.14}), ('Location', {'p':0.56,'r':0.56,'f':0.56}) ]  I would like to eliminate the duplicates and add their respective values to only one of each kind. So the output to look like this: [ ('Name', {'p':0.7,'r':0.7,'f':0.7}), ('Designation', {'p':0.2,'r':0.4,'f':0.28}), ('Location', {'p':1.12,'r':1.12,'f':1.12}) ]  I have tried to use the reduce function but it gives me only the output for 'Name' entry only. result = functools.reduce(lambda x, y: (x[0], Counter(x[1])+Counter(y[1])) if x[0]==y[0] else (x[0],x[1]), counter_list)  What would be the right approach? I am trying to create some visuals with the final results, to determine which item has the higher 'f','p' or 'r' component.

Answer: Why not use pandas and its ~.groupby method? >>> import pandas as pd >>> keys, data = zip(*counter_list) >>> df = pd.DataFrame(data=data, index=keys).groupby(level=0).sum() >>> df p r f Designation 0.20 0.40 0.28 Location 1.12 1.12 1.12 Name 0.70 0.70 0.70  and then do >>> list(df.T.to_dict().items()) [ ('Designation', {'p': 0.2, 'r': 0.4, 'f': 0.28}), ('Location', {'p': 1.12, 'r': 1.12, 'f': 1.12}), ('Name', {'p': 0.7, 'r': 0.7, 'f': 0.7}) ]
Question: This is the project directory structure . ├── meow.py └── pyproject.toml 0 directories, 2 files  This is the meow.py: def main(): print("meow world")  This is the pyproject.toml: [build-system] requires = ["setuptools"] build-backend = "setuptools.build_meta" [project] name = "meowpkg" version = "0.1" description = "a package that meows" [project.scripts] meow_world = "meow:main"  When building this package, no matter whether with python3 -m pip wheel . or using python3 -m build, it creates a file named like meowpkg-0.1-py3-none-any.whl which can not be installed on Python 2. $ python2.7 -m pip install meowpkg-0.1-py3-none-any.whl ERROR: meowpkg-0.1-py3-none-any.whl is not a supported wheel on this platform.  But "meowpkg" actually works on Python 2 as well. How to instruct setuptools and/or wheel to create a universal wheel tagged like meowpkg-0.1-py2.py3-none-any.whl, without using the old setup.cfg/setup.py ways? Current workaround: echo "[bdist_wheel]\nuniversal=1" > setup.cfg && python3 -m build && rm setup.cfg 

Answer: Add this section into the pyproject.toml: [tool.distutils.bdist_wheel] universal = true
Question: I have designed a program that compares two images and gives you the coordinates of the pixels that are different in both images and plots the using pygame. I do not mind having to use another library or to remake my whole code but it should ideally take less that 0.6s to process and it should not reduce file size, all I need it to do is to return the coordinates relative to the image My code: import cv2 import pygame from pygame.locals import * import time lib = 'Map1.png' lib2 = 'Map2.png' lib3 = () coordenatesx = () coordenatesy = () Read = list(cv2.imread(lib).astype("int")) Read2 = list(cv2.imread(lib2).astype("int")) counter = 0 pygame.init() flags = DOUBLEBUF screen = pygame.display.set_mode((500,500), flags, 4) start = time.process_time()#To tell me how long it takes for y in range(len(Read)):#y coords for x in range(len(Read[y])):#x coords all = list(Read[y][x])[0] all2 = list(Read2[y][x])[0] difference = (all)-(all2) if difference > 10 or difference < -10: #To see if the pixel's difference is in the boundary if not it is different and it gets plotted counter+=1 pygame.draw.rect(screen, (255, 0, 0), pygame.Rect(x, y, 1, 1)) pygame.display.update() print(time. process_time() - start) if counter >= (y * x) * 0.75: print('They are similar images') print('They are different by only :', str((counter / (y * x)) * 100), '%') else: print('They are different') print('They are different by:', str((counter / (y * x)) * 100), '%') pygame.display.update()      image1 image2          

Answer: You do not need to use for loop to do the same. Numpy makes things simple:  it's easy to understand speed up operations  Reading both your images in grayscale: img1 = cv2.imread(r'C:\Users\524316\Desktop\Stack\m1.png', 0) 1mg2 = cv2.imread(r'C:\Users\524316\Desktop\Stack\m2.png', 0)  Subtracting them. cv2.subtract() takes care of normalization such that it doesn't return negative values. Coordinates having no change remain black (pixel intensity = 0) sub = cv2.subtract(img1, img2)  Using numpy find the coordinates where changes are more than 0 coords = np.argwhere(sub > 0) # return first 10 elements of the array coords coords[:10] array([[ 0, 23], [ 0, 24], [ 0, 25], [ 0, 26], [ 0, 27], [ 0, 28], [ 0, 29], [ 0, 30], [ 0, 31], [ 0, 32]], dtype=int64)  coords returns an array, which can be converted to a list: coords_list = coords.tolist() # return first 10 elements of the list: >>> coords_list[:10] [[0, 23], [0, 24], [0, 25], [0, 26], [0, 27], [0, 28], [0, 29], [0, 30], [0, 31], [0, 32]]  Update: Based on the comment made by fmw42, if you are only looking for coordinates where difference between pixel intensities is less than or greater than a certain value (say 10); you could do the following: sub = cv2.absDiff(img1, img2) np.argwhere(sub > 10)
Question: I have a view inheriting from LoginRequiredMixin, TemplateView, which renders some data using the admin/base_site.html template as the base. I treat it as a part of the admin interface, so it requires an administrator login. I'd like to make this view a little bit more a part of the Django admin interface by enabling the standard sidebar navigation on the left-hand side. Note that I don't have a custom ModelAdmin definition anywhere, I simply render the template at some predefined URL. There are no models used in the interface either, it parses and displays data from database-unrelated sources. Currently, I just build the required context data manually, e.g.: data = super().get_context_data(**kwargs) data.update(**{ "is_popup": False, "site_header": None, "is_nav_sidebar_enabled": True, "has_permission": True, "title": "My title", "subtitle": None, "site_url": None, "available_apps": [] })  The sidebar is visible, but displays an error message:  Adding an app to available_apps ("available_apps": ["my_app"]) doesn't help either:  So my question is - how do I do that? Is there a class I can inherit from to achieve this behaviour? Or a method I can call to get all required context data for base_site.html? Or perhaps I should insert some information in my template? Perhaps I need an AdminSite object, or can somehow call methods of the default one?

Answer: By accident I noticed there is a DefaultAdminSite object in django.contrib.admin.sites, and it's instantiated as site. Therefore, in my case, simply using site is sufficient. from django.contrib.admin import AdminSite from django.contrib.admin.sites import site admin_site: AdminSite = site data.update(**admin_site.each_context(self.request))  Furthermore, turns out I can just use the apps in case importing site would be an issue, just like DefaultAdminSite does it: AdminSiteClass = import_string(apps.get_app_config("admin").default_site) self._wrapped = AdminSiteClass()
Question: I am looking to get the closest match between two columns of string data type in two separate tables. I don't think the content matters too much. There are words that I can match by pre-processing the data (lower all letters, replace spaces and stop words, etc...) and doing a join. However I get around 80 matches out of over 350. It is important to know that the length of each table is different. I did try to use some code I found online but it isn't working: def Races_chien(df1,df2): myList = [] total = len(df1) possibilities = list(df2['Rasse']) s = SequenceMatcher(isjunk=None, autojunk=False) for idx1, df1_str in enumerate(df1['Race']): my_str = ('Progress : ' + str(round((idx1 / total) * 100, 3)) + '%') sys.stdout.write('\r' + str(my_str)) sys.stdout.flush() # get 1 best match that has a ratio of at least 0.7 best_match = get_close_matches(df1_str, possibilities, 1, 0.7) s.set_seq2(df1_str, best_match) myList.append([df1_str, best_match, s.ratio()]) return myList  It says: TypeError: set_seq2() takes 2 positional arguments but 3 were given How can I make this work?

Answer: Here is an answer I finally got: from fuzzywuzzy import process, fuzz value = [] similarity = [] for i in df1.col: ratio = process.extract(i, df2.col, limit= 1) value.append(ratio[0][0]) similarity.append(ratio[0][1]) df1['value'] = pd.Series(value) df1['similarity'] = pd.Series(similarity)  This will add the value with the closest match from df2 in df1 together with the similarity %
Question: The python subprocess docs only mention the errors parameter in passing:  If encoding or errors are specified, or universal_newlines is true, file objects for stdin, stdout and stderr are opened in text mode using the specified encoding and errors or the io.TextIOWrapper default.  I understand the usage of text and universal_newlines, which are synonyms. I also understand the usage of encoding. What is the function of the errors parameter? It appears to have been added in Python 3.6. Is errors just a synonym of encoding? If it is just a synonym, are there any published reasoning for this addition?

Answer: The errors parameter is described in the linked documentation for io.TextIOWrapper:  errors is an optional string that specifies how encoding and decoding errors are to be handled. Pass 'strict' to raise a ValueError exception if there is an encoding error (the default of None has the same effect), or pass 'ignore' to ignore errors. (Note that ignoring encoding errors can lead to data loss.) 'replace' causes a replacement marker (such as '?') to be inserted where there is malformed data. 'backslashreplace' causes malformed data to be replaced by a backslashed escape sequence. When writing, 'xmlcharrefreplace' (replace with the appropriate XML character reference) or 'namereplace' (replace with \N{...} escape sequences) can be used. Any other error handling name that has been registered with codecs.register_error() is also valid.
Question: Assume a 2*X(always 2 rows) pytorch tensor: A = tensor([[ 1., 2., 2., 3., 3., 3., 4., 4., 4.], [43., 33., 43., 76., 33., 76., 55., 55., 55.]])  torch.unique(A, dim=1) will return: tensor([[ 1., 2., 2., 3., 3., 4.], [43., 33., 43., 33., 76., 55.]])  But I also need the indices of every unique elements where they firstly appear in original input. In this case, indices should be like: tensor([0, 1, 2, 3, 4, 6]) # Explanation # A = tensor([[ 1., 2., 2., 3., 3., 3., 4., 4., 4.], # [43., 33., 43., 76., 33., 76., 55., 55., 55.]]) # (0) (1) (2) (3) (4) (6)  It's complex for me because the second row of tensor A may not be nicely sorted: A = tensor([[ 1., 2., 2., 3., 3., 3., 4., 4., 4.], [43., 33., 43., 76., 33., 76., 55., 55., 55.]]) ^ ^  Is there a simple and efficient method to get the desired indices? P.S. It may be useful that the first row of the tensor is always in ascending order.

Answer: One possible way to gain such indicies: unique, idx, counts = torch.unique(A, dim=1, sorted=True, return_inverse=True, return_counts=True) _, ind_sorted = torch.sort(idx, stable=True) cum_sum = counts.cumsum(0) cum_sum = torch.cat((torch.tensor([0]), cum_sum[:-1])) first_indicies = ind_sorted[cum_sum]  For tensor A in snippet above: print(first_indicies) # tensor([0, 1, 2, 4, 3, 6])  Note that unique in this case is equal to:  tensor([[ 1., 2., 2., 3., 3., 4.], [43., 33., 43., 33., 76., 55.]])
Question: I was wondering if there is an easy way to essentially have multiple keys in a dictionary for one value. An example of what I would like to achieve is as following: class test: key="test_key" def __str__(self): return self.key tester = test() dictionary = {} dictionary[tester] = 1 print(dictionary[tester]) print(dictionary["test_key"])  where the output would be: >>> 1 >>> 1  What I'm looking for is a way to automatically convert the object to a string before its used as a key. Is this possible?

Answer: Personally, I think it's better to explicitly cast the object to a string, e.g. dictionary[str(tester)] = 1  That being said, if you're really really REALLY sure you want to do this, define the __hash__ and __eq__ dunder methods. No need to create a new data structure or change the existing code outside of the class definition: class test: key="test_key" def __hash__(self): return hash(self.key) def __eq__(self, other): if isinstance(other, str): return self.key == other return self.key == other.key def __str__(self): return self.key  This will output: 1 1
Question: I'm working with RL agents, and was trying to replicate the finding of the this paper, wherein they make a custom parkour environment based on Gym open AI, however when trying to render this environment I run into. import numpy as np import time import gym import TeachMyAgent.environments env = gym.make('parametric-continuous-parkour-v0', agent_body_type='fish', movable_creepers=True) env.set_environment(input_vector=np.zeros(3), water_level = 0.1) env.reset() while True: _, _, d, _ = env.step(env.action_space.sample()) env.render(mode='human') time.sleep(0.1) c:\users\manu dwivedi\teachmyagent\TeachMyAgent\environments\envs\parametric_continuous_parkour.py in render(self, mode, draw_lidars) 462 463 def render(self, mode='human', draw_lidars=True): --> 464 from gym.envs.classic_control import rendering 465 if self.viewer is None: 466 self.viewer = rendering.Viewer(RENDERING_VIEWER_W, RENDERING_VIEWER_H) ImportError: cannot import name 'rendering' from 'gym.envs.classic_control' (C:\ProgramData\Anaconda3\envs\teachagent\lib\site-packages\gym\envs\classic_control\__init__.py) [1]: https://github.com/flowersteam/TeachMyAgent  I thought this might be a problem with this custom environments and how the authors decided to render it, however, when I try just from gym.envs.classic_control import rendering  I run into the same error, github users here suggested this can be solved by adding rendor_mode='human' when calling gym.make() rendering, but this seems to only goes for their specific case.

Answer: I got (with help from a fellow student) it to work by downgrading the gym package to 0.21.0. Performed the command pip install gym==0.21.0 for this. Update, from Github issue: Based on https://github.com/openai/gym/issues/2779 This should be a problem of gymgrid, there is an open PR: wsgdrfz/gymgrid#1 If you want to use the last version of gym, you can try using the branch of that PR (https://github.com/CedricHermansBIT/gymgrid2); you can install it with pip install gymgrid2
Question: What's the difference between tuple[str, ...] vs tuple[str]? (python typing)

Answer: giving a tuple type with ellipsis means that number of elements in this tuple is not known, but type is known: x: tuple[str, ...] = ("hi",) #VALID x: tuple[str, ...] = ("hi", "world") #ALSO VALID  not using ellipsis means a tuple with specific number of elements, e.g.: y: tuple[str] = ("hi", "world") # Type Warning: Expected type 'Tuple[str]', got 'Tuple[str, str]' instead  This goes in contrast to notation of other collections, e.g. list[str] means list of any length with elements of type str.
Question: I'm developing a simple FastAPI app and I'm using Pydantic for storing app settings. Some settings are populated from the environment variables set by Ansible deployment tools but some other settings are needed to be set explicitly from a separate env file. So I have this in config.py class Settings(BaseSettings): # Project wide settings PROJECT_MODE: str = getenv("PROJECT_MODE", "sandbox") VERSION: str class Config: env_file = "config.txt"  And I have this config.txt VERSION="0.0.1"  So project_mode env var is being set by deployment script and version is being set from the env file. The reason for that is that we'd like to keep deployment script similar across all projects, so any custom vars are populated from the project specific env files. But the problem is that when I run the app, it fails with: pydantic.error_wrappers.ValidationError: 1 validation error for Settings VERSION field required (type=value_error.missing)  So how can I populate Pydantic settings model from the local ENV file?

Answer: If the environment file isn't being picked up, most of the time it's because it isn't placed in the current working directory. In your application in needs to be in the directory where the application is run from (or if the application manages the CWD itself, to where it expects to find it). In particular when running tests this can be a bit confusing, and you might have to configure your IDE to run tests with the CWD set to the project root if you run the tests from your IDE.
Question: In Flask, it is possible to assign an arbitrary function to a route functionally like: from flask import Flask app = Flask() def say_hello(): return "Hello" app.add_url_rule('/hello', 'say_hello', say_hello)  which is equal to (with decorators): @app.route("/hello") def say_hello(): return "Hello"  Is there such a simple and functional way (add_url_rule) in FastAPI?

Answer: You can use the add_api_route method to add a route to a router or an app programmtically: from fastapi import FastAPI, APIRouter def foo_it(): return {'Fooed': True} app = FastAPI() router = APIRouter() router.add_api_route('/foo', endpoint=foo_it) app.include_router(router) app.add_api_route('/foo-app', endpoint=foo_it)  Both expose the same endpoint in two different locations: λ curl http://localhost:8000/foo {"Fooed":true} λ curl http://localhost:8000/foo-app {"Fooed":true}