eshangj/stackoverflow_q_and_a_sample huggingface dataset:
Question: i have an api entrypoint: @app.get('/dealers_get_users/', response_model = schemas.SellSideUserId, status_code=200) def getdata(db: database.SessionLocal = _Depends(database.get_db)): result = {} i = db.query(models.sellSideUser).all() for dealer_users in i: result[str(dealer_users.user_id)] = { 'user_name' : dealer_users.user_name, 'user_pass' : dealer_users.user_pass, } m = schemas.SellSideUserId(user_id=result) return m  the data coming in from the db is just 3 fields: user_id,user_name,user_pass when i call the api, i get this: { "user_id": { "1": { "user_name": "testname", "user_pass": "testpass" } } }  ok, cool - i got my data. but i'm still trying to understand how these models work, and am not really grasping how to move in or out of a nested dictionary. for example, i would like it to look like this, instead: { "1": { "user_name": "testname", "user_pass": "testpass" } }  but i'm not sure how to pass the 'result' variable into this class - any way i do it, i'm met with an error. my model: class SellSideUserId(_BaseModel): user_id : dict class Config: orm_mode = True  am i supposed to build two pydantic models - one being based on another? could use some help with this thanks!

Answer: You can easily make a model with dynamic keys using a dict as custom root type: class User(BaseModel): name: str password: str class ProductModel(BaseModel): __root__: Dict[str, User]  Moreover, you can constrain dictionary keys using constr сapabilities, such as regex pattern: UserId = constr(regex=r'^\d+$') class ProductModel(BaseModel): __root__: Dict[UserId, User]  This will work well for validating returned responses against your model. But generated OpenAPI schema will be rather scanty, since at the moment FastAPI 0.68 and swagger UI does not support yet OpenAPI 3.1, which contains such keyword as patternProperties or propertyNames.
Question: I am referring to 33 body points and connector lines between them. I'd like to change the colors of those, especially of the white default color of the connector lines. Here's my code, I have created a class module for mediapipe which I can import and use in my other programs import cv2 import mediapipe as mp class poseDetector(): def __init__(self, mode=False, complex=1, smooth_landmarks=True, segmentation=True, smooth_segmentation=True, detectionCon=0.5, trackCon=0.5): self.mode = mode self.complex = complex self.smooth_landmarks = smooth_landmarks self.segmentation = segmentation self.smooth_segmentation = smooth_segmentation self.detectionCon = detectionCon self.trackCon = trackCon self.mpDraw = mp.solutions.drawing_utils self.mpDrawStyle = mp.solutions.drawing_styles self.mpPose = mp.solutions.pose self.pose = self.mpPose.Pose(self.mode, self.complex, self.smooth_landmarks, self.segmentation, self.smooth_segmentation, self.detectionCon, self.trackCon) def findPose(self, img, draw=True): imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) self.results = self.pose.process(imgRGB) if self.results.pose_landmarks: if draw: self.mpDraw.draw_landmarks(img, self.results.pose_landmarks, self.mpPose.POSE_CONNECTIONS) return img def main(): cap = cv2.VideoCapture("..//assets//videos//v4.mp4") detector = poseDetector() while True: success, img = cap.read() img = detector.findPose(img) cv2.imshow("Image", img) cv2.waitKey(1) if __name__ == "__main__": main() 

Answer: So as per the documentation, this is the code for draw_landmarks mp_drawing.draw_landmarks( image: numpy.ndarray, landmark_list: mediapipe.framework.formats.landmark_pb2.NormalizedLandmarkList, connections: Optional[List[Tuple[int, int]]] = None, landmark_drawing_spec: mediapipe.python.solutions.drawing_utils.DrawingSpec = DrawingSpec(color=(0, 0, 255), thickness=2, circle_radius=2), connection_drawing_spec: mediapipe.python.solutions.drawing_utils.DrawingSpec = DrawingSpec(color=(0, 255, 0), thickness=2, circle_radius=2), )  So in your findPose function you need to update only one line of code def findPose(self, img, draw=True): imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) self.results = self.pose.process(imgRGB) if self.results.pose_landmarks: if draw: self.mpDraw.draw_landmarks(img, self.results.pose_landmarks, self.mpPose.POSE_CONNECTIONS, self.mpDraw.DrawingSpec(color=(245,117,66), thickness=2, circle_radius=2), self.mpDraw.DrawingSpec(color=(245,66,230), thickness=2, circle_radius=2)) return img  The first self.mpDraw.DrawingSpec argument corresponds to the points of the landmark. The second self.mpDraw.DrawingSpec argument corresponds to the COnnection between those landmarks points. The color is in (B, G, R) format
Question: I've started to learn about the pickle module used for object serialization and deserialization. I know that pickle.dump is used to store the code as a stream of bytes (serialization), and pickle.load is essentially the opposite, turning a stream of bytes back into a python object. (deserialization). But what are pickle.dumps and pickle.loads, and what are the differences between them and pickle.dump and pickle.load? I've looked at the documentation, but I am having trouble differentiating between the two. From the documentation:  pickle.dumps(obj, protocol=None, *, fix_imports=True, buffer_callback=None) ; Return the pickled representation of the object obj as a bytes object, instead of writing it to a file.   pickle.loads(data, /, *, fix_imports=True, encoding="ASCII", errors="strict", buffers=None) Return the reconstituted object hierarchy of the pickled representation data of an object. data must be a bytes-like object. 

Answer: The difference between dump and dumps is that dump writes the pickled object to an open file, and dumps returns the pickled object as bytes. The file must be opened for writing in binary mode. The pickled version of the object is exactly the same with both dump and dumps. So, if you did the following for object obj: with open("pickle1", "wb") as f: pickle.dump(obj, f) with open("pickle2", "wb") as f: f.write(pickle.dumps(obj))  you'd end up with two files with exactly the same contents. The same applies to loading - load "unpickles" from an open (readable) file object, and loads uses a bytes object.
Question: Given the following code snippet: import argparse import sys parser = argparse.ArgumentParser() subparsers = parser.add_subparsers(help="subcommand help") command1 = subparsers.add_parser("foo", description="Run foo subcommand") command2 = subparsers.add_parser("bar", description="Run bar subcommand") opts = parser.parse_args(sys.argv[1:])  When I print help for this I get this: usage: test.py [-h] {foo,bar} ... positional arguments: {foo,bar} subcommand help optional arguments: -h, --help show this help message and exit  Is there a way to make it print something like this instead: usage: test.py [-h] {foo,bar} ... subcommands: foo Run foo subcommand bar Run bar subcommand optional arguments: -h, --help show this help message and exit  without supplying a custom formatter? If I change the formatter then it also changes everything else about how the help is printed, but in my case I just want to change the way that subcommand help is printed from the parent (sub)command.

Answer: You need to set the help parameter, not the description parameter, to get the output you desire: import argparse import sys parser = argparse.ArgumentParser() subparsers = parser.add_subparsers(help="subcommand help") command1 = subparsers.add_parser("foo", help="Run foo subcommand") command2 = subparsers.add_parser("bar", help="Run bar subcommand") opts = parser.parse_args(sys.argv[1:])  Output: usage: test.py [-h] {foo,bar} ... positional arguments: {foo,bar} subcommand help foo Run foo subcommand bar Run bar subcommand optional arguments: -h, --help show this help message and exit  The argparse docs have this to say about the help value:  The help value is a string containing a brief description of the argument. When a user requests help (usually by using -h or --help at the command line), these help descriptions will be displayed with each argument.  And this to say to about the description value:  This argument gives a brief description of what the program does and how it works. In help messages, the description is displayed between the command-line usage string and the help messages for the various arguments.
Question: I'm trying to build a certain repository using meson on Cygwin. This is what happens: $ meson build_dir The Meson build system Version: 0.58.2 Source dir: /home/joeuser/src/meld-3.21.0 Build dir: /home/joeuser/src/meld-3.21.0/build_dir Build type: native build Project name: meld Project version: 3.21.0 Host machine cpu family: x86_64 Host machine cpu: x86_64 Program python3 found: YES (/usr/bin/python3) Found pkg-config: /usr/bin/pkg-config (1.6.3) Run-time dependency python3 found: NO (tried pkgconfig and sysconfig) meson.build:18:0: ERROR: Dependency "python3" not found, tried pkgconfig and sysconfig  Why is this happening? And how can I get meson to find the python3 dependency? Note: I've installed python38-pkgconfig in case that matters.

Answer: meson will find python3 if you also install the python3-devel package using the Cygwin installer.
Question: I want to be notified when there is a new entry in a specific table "FileInfos" in PostgreSQL 12, so I wrote the following trigger: create trigger trigger1 after insert or update on public."FileInfos" for each row execute procedure notify_id_trigger();  and the following function: create or replace function notify_id_trigger() returns trigger as $$ begin perform pg_notify('new_Id'::text, NEW."Id"::text); return new; end; $$ language plpgsql;  to get the notifications I use the python library psycopg2: import psycopg2 from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT import select def dblistener(): connection = psycopg2.connect( host="127.0.0.1", database="DBNAME", user="postgres", password="....") connection.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT) cur = connection.cursor() cur.execute("LISTEN new_Id;") while True: select.select([connection], [], []) connection.poll() while connection.notifies: notify = connection.notifies.pop() print("Got NOTIFY:", notify.pid, notify.channel, notify.payload) if __name__ == '__main__': dblistener()  But unfortunately my python code does not work, what did I do wrong? BTW: The database and the table were created with the Entity Framework (C#).

Answer: According to NOTIFY syntax, channel is an identifier. That means that new_Id in LISTEN new_Id  is automaticaly converted to new_id. Unfortunately, pg_notify('new_Id'::text, new."Id"::text) notifies on channel new_Id. You have two options. Change the channel in the trigger: perform pg_notify('new_id'::text, new."Id"::text);  or enclose the channel in double-quotes in LISTEN: LISTEN "new_Id"  The use of capital letters in Postgres can cause surprises.
Question: Could someone explain what is going on under the hood and why this program does not finish? class A: def __getitem__(self, key): return 1 print(*A()) 

Answer: This program doesn't finish because the class you defined is iterable, using the old sequence iteration protocol. Basically, __getitem__ is called with integers increasing from 0, ..., n until an IndexError is raised. >>> class A: ... def __getitem__(self, key): ... return 1 ... >>> it = iter(A()) >>> next(it) 1 >>> next(it) 1 >>> next(it) 1 >>> next(it) 1  You are unpacking an infinite iterator, so eventually you'll run out of memory. From the iter docs:  Without a second argument, object must be a collection object which supports the iteration protocol (the __iter__() method), or it must support the sequence protocol (the __getitem__() method with integer arguments starting at 0). If it does not support either of those protocols, TypeError is raised.
Question: I'm doing some exercises in Python and I came across a doubt. I have to set a list containing the first three elements of list, with the .append method. The thing is, I get an assertion error, lists don't match. If I print list_first_3 I get "[['cat', 3.14, 'dog']]", so the double square brackets are the problem. But how can I define the list so the output matches? list = ["cat", 3.14, "dog", 81, 6, 41] list_first_3 = [] list_first_3.append(list[:3]) assert list_first_3 == ["cat", 3.14, "dog"] 

Answer: append can only add a single value. I think what you may be thinking of is the extend method (or the += operator) list1 = ["cat", 3.14, "dog", 81, 6, 41] list_first_3 = [] list_first_3.extend(list1[:3]) assert list_first_3 == ["cat", 3.14, "dog"]  or list1 = ["cat", 3.14, "dog", 81, 6, 41] list_first_3 = [] list_first_3 += list1[:3] assert list_first_3 == ["cat", 3.14, "dog"]  otherwise you'll need a loop: list1 = ["cat", 3.14, "dog", 81, 6, 41] list_first_3 = [] for value in list1[:3]: list_first_3.append(value) assert list_first_3 == ["cat", 3.14, "dog"]  with append but without a loop would be possible using a little map() trickery: list1 = ["cat", 3.14, "dog", 81, 6, 41] list_first_3 = [] any(map(list_first_3.append,list1[:3])) assert list_first_3 == ["cat", 3.14, "dog"]
Question: When trying to produce a figure with the following code @app.callback( [ Output("selected-plot", "figure") ], [ Input("submit-selected-plotting", "n_clicks"), State("table", "data") ], ) def plot(button_clicked, data) fig = go.Scatter(x=data["index"], y=data["result"], mode='lines', name='result') return fig  and  dbc.Col( [ dcc.Graph(id='selected-plot') ], width=6, )  I get a strange error with the app expecting a different object:  dash._grouping.SchemaTypeValidationError: Schema: [<Output selected-plots.figure>] Path: () Expected type: (<class 'tuple'>, <class 'list'>) Received value of type <class 'plotly.graph_objs._scatter.Scatter'>: Scatter({...})  I have tried everything but I can't seem to go around this error. Thanks for any suggestions in advance!

Answer: The error is due to the fact that the app expects a figure object, you can fix it by updating the callback as follows: @app.callback( [ Output("selected-plot", "figure") ], [ Input("submit-selected-plotting", "n_clicks"), State("table", "data") ], ) def plot(button_clicked, data) trace = go.Scatter( x=data["index"], y=data["result"], mode='lines', name='result' ) return [go.Figure(data=trace)]
Question: What I have, are multi similar and simple dockerfiles But what I want is to have a single base dockerfile and my dockerfiles pass their variables into it. In my case the only difference between dockerfiles are simply their EXPOSE, so I think it's better to keep a base dockerfile and other dockerfiles only inject that variables into base dockerfile like a template engine A sample dockerfile: FROM golang:1.17 AS builder WORKDIR /app COPY . . RUN go mod download RUN go build -o /bin/app ./cmd/root.go FROM alpine:latest WORKDIR /bin/ COPY --from=builder /bin/app . EXPOSE 8080 LABEL org.opencontainers.image.source="https://github.com/mohammadne/bookman-auth" ENTRYPOINT ["/bin/app"] CMD ["server", "--env=dev"] 

Answer: as yasen said, it's impossible to have import directive. finally what I have did is as follow: link to github repository  create a template text file with EXPOSE ${{ EXPOSED_PORT }}:  FROM golang:1.17 AS builder WORKDIR /app COPY . . RUN go mod download && make ent-generate RUN go build -o /bin/app ./cmd/root.go FROM alpine:latest WORKDIR /bin/ COPY --from=builder /bin/app . EXPOSE ${{ EXPOSED_PORT }} LABEL org.opencontainers.image.source="https://github.com/mohammadne/bookman-library" ENTRYPOINT ["/bin/app"] CMD ["server", "--env=dev"]   and then create a python script  #!/usr/bin/python from shutil import copyfile import os class Config: def __init__(self, service, port): self.service = service self.port = port configs = [ Config("auth", "8080"), Config("user", "8081"), Config("library", "8082"), ] pathToDir = "../build" template = f"{pathToDir}/template.txt" for config in configs: outputDir = f"{pathToDir}/{config.service}" os.mkdir(outputDir) fileName = copyfile(template, f"{outputDir}/Dockerfile") with open(fileName, "rt") as file: replacedText = file.read().replace('${{ EXPOSED_PORT }}', config.port) with open(fileName, "wt") as file: file.write(replacedText)  then in the python script you can replace your patterns !!!
Question: I have an image represented as a 2D array. I would like to get the coordinates of pixels over a line from point 1 to point 2. For example, let's say I have an image with size 5x4 like in the image below. And I have a line from point 1 at coordinates (0, 2) to point 2 at (4, 1). Like the red line on the image below:  So here I would like to get the coordinates of the blue pixels as a list like this: [(0, 2), (1, 2), (2, 2), (2, 1), (3, 1), (4, 1)] How can I achieve this? I am using Python and numpy, but actually a solution in any language including pseudo code would be helpful. I can then try to convert it into a numpy solution.

Answer: You can do this with scikit-image: from skimage.draw import line # Get coordinates, r=rows, c=cols of your line rr, cc = line(0,2,4,1) print(list(zip(rr,cc))) [(0, 2), (1, 2), (2, 1), (3, 1), (4, 1)]  The source code to see the implemented algorithm: https://github.com/scikit-image/scikit-image/blob/main/skimage/draw/_draw.pyx#L44 It is an implementation of the Bresenham's line algorithm
Question: I want to use poetry to build and distribute Python source packages, but after poetry init I get an error running poetry build.  ModuleOrPackageNotFound No file/folder found for package mdspliter.tree 

Answer: Reason The reason it can't be found is most likely because the directory hierarchy is incorrect. The released package is not directly the source code folder, there are many things in it that are not needed in the final package such as version control, testing and dependency management. You should put this folder with the same name as the package as a package in that folder. Solution  Change the directory hierarchy so that there are packages with the corresponding names in the folder.for example:  D:\GitRepository\python_distribution\temp\tree ├──_init__.py ├──tree.py ├──pyproject.toml └──README.rst  ↓ D:\GitRepository\python_distribution\temp\tree ├──tree │ ├──__init__.py │ └──tree.py ├──pyproject.toml └──README.rst   Specify the folder in pyproject.toml  packages = [ { include = "your_folder_as_pack" } ]  Variants If the name of the project is mdspliter.tree, then it is not useful at all to include the folder mdspliter.tree, because this naming scheme does not conform to the specification, if you use poetry new mdspliter.tree, you will find that the name of the folder actually should be mdspliter_tree. (in version 1.2, this behavior has been changed to generate multi-layer folders, mdsplitter/tree)
Question: I have a pandas Dataframe and a pandas Series that looks like below. df0 = pd.DataFrame({'col1':['a','b','c','d'],'col2':['b','c','e','f'],'col3':['d','f','g','a']}) col1 col2 col3 0 a b d 1 b c f 2 c e g 3 d f a df1 = pd.Series(['b','g','g'], index=['col1','col2','col3']) col1 b col2 g col3 g dtype: object  As you can see, the columns of df0 and the indices of df1 are the same. For each index of df1, I want to know if the value at that index exists in the corresponding column of df0. So, df1.col1 is b and we need to look for b only in df0.col1 and check if it exists. Desired output: array([True, False, True])  Is there a way to do this without using a loop? Maybe a method native to numpy or pandas?

Answer: You can make use of broadcasting: (df0 == df1).any().values  It also works with NumPy ndarrays: assert (df0.columns == df1.columns).all() (df0.values == df1.values).any(axis=0)  Output: array([ True, False, True])
Question: For a subclass of QObject I'd like to define a property. On change, a signal should be emitted. According to the documentation, something like this: p = Property(int, _get_p, _set_p, notify=p_changed) should work, but the signal is not emitted by the change. Full example here: from PySide2.QtCore import QObject, Property, Slot, Signal class A(QObject): p_changed = Signal() def __init__(self): super(A, self).__init__() self._p = 0 def _get_p(self): print(f"Getting p (val: {self._p})") return self._p def _set_p(self, v): print(f"Setting new p: {v}") self._p = v p = Property(int, _get_p, _set_p, notify=p_changed) if __name__ == "__main__": import sys from PySide2.QtWidgets import QApplication, QWidget app = QApplication([]) class W(QWidget): def __init__(self, *args): super().__init__(*args) self.a = A() self.a.p_changed.connect(self.test_slot) print(self.a.p) self.a.p = 42 # Expecting "Got notified"! print(self.a.p) # This would print "Got notified": # self.a.p_changed.emit() @Slot() def test_slot(self): print("Got notified") w = W() w.show() sys.exit(app.exec_()) 

Answer: That you associate a signal to a QProperty does not imply that it will be emitted automatically but that you have to emit it explicitly. def _set_p(self, v): if self._p != v: print(f"Setting new p: {v}") self._p = v self.p_changed.emit()  For more information read The Property System.
Question: Here is my trivial fastapi app: from datetime import datetime import asyncio import uvicorn from fastapi import FastAPI app = FastAPI() @app.get("/delayed") async def get_delayed(): started = datetime.now() print(f"Starting at: {started}") await asyncio.sleep(10) ended = datetime.now() print(f"Ending at: {ended}") return {"started": f"{started}", "ended": f"{ended}"} if __name__ == "__main__": uvicorn.run("fastapitest.main:app", host="0.0.0.0", port=8000, reload=True, workers=2)  When I make 2 consecutive calls to it, the code in the function for the second one doesn't start executing until the first request finishes, producing an output like: Starting at: 2021-09-17 14:52:40.317915 Ending at: 2021-09-17 14:52:50.321557 INFO: 127.0.0.1:58539 - "GET /delayed HTTP/1.1" 200 OK Starting at: 2021-09-17 14:52:50.328359 Ending at: 2021-09-17 14:53:00.333032 INFO: 127.0.0.1:58539 - "GET /delayed HTTP/1.1" 200 OK  Given that the function is marked async and I am awaiting the sleep, I would expect a different output, like: Starting at: ... Starting at: ... Ending at: ... INFO: 127.0.0.1:58539 - "GET /delayed HTTP/1.1" 200 OK Ending at: ... INFO: 127.0.0.1:58539 - "GET /delayed HTTP/1.1" 200 OK  [for the calls I just opened up 2 browser tabs at localhost:8000/delayed ] What am I missing?

Answer: It works in parallel as expected - it is just a browser thing: chrome on detecting the same endpoint being requested in different tabs, will wait for the first to be completly resolved to check if the result can be cached. If instead you place 3 http requests from different processes in the shell, the results are as expected: content-length: 77 content-type: application/json date: Fri, 17 Sep 2021 19:51:39 GMT server: uvicorn { "ended": "2021-09-17 16:51:49.956629", "started": "2021-09-17 16:51:39.955487" } HTTP/1.1 200 OK content-length: 77 content-type: application/json date: Fri, 17 Sep 2021 19:51:39 GMT server: uvicorn { "ended": "2021-09-17 16:51:49.961173", "started": "2021-09-17 16:51:39.960850" } HTTP/1.1 200 OK content-length: 77 content-type: application/json date: Fri, 17 Sep 2021 19:51:39 GMT server: uvicorn { "ended": "2021-09-17 16:51:49.964156", "started": "2021-09-17 16:51:39.963510" }  Adding a random, even if unused, query parameter on the URL for each browser tab will all cancel the trying-to-cache behavior. related question: Chrome stalls when making multiple requests to same resource?