eshangj/stackoverflow_q_and_a_sample huggingface dataset:
Question: I'm working on my project for a course and I'm totally stuck right now. I'm creating a website to manage workouts by user and the create workout do not redirect to the user's workouts page when I create the new workout instance. views.py # View to return all user's workouts def user_workouts(request, user_id): user = User.objects.get(id=user_id) print(user) workouts = get_list_or_404(Workout, user=user.id) return render(request, "users/workouts.html", {"user": user, "workouts": workouts}) # Create workout view def add_workout(request, user_id): user = get_object_or_404(User, id=user_id) print(user) print(request._post) if request.method == "POST": workout_title = request.POST.get("workout") reps = request.POST.get("reps") load = request.POST.get("load") last_update = request.POST.get("last_update") workout = Workout(workout=workout_title, reps=reps, load=load, last_update=last_update, user=user) workout.save() print(user.id) return redirect('user_workouts') context = {"workout": workout} return render(request, "users/add_workout.html", context=context)  urls.py from django.urls import path from . import views app_name = "myapp" urlpatterns = [ path("", views.index, name="index"), path("user/<int:user_id>", views.user_detail, name="user_detail"), path("user/<int:user_id>/workouts", views.user_workouts, name="user_workouts"), path("user/<int:user_id>/workouts/<int:workout_id>", views.workout_detail, name="workout_detail"), path("user/<int:user_id>/workouts/Add Workout", views.open_workout_form, name="open_workout_form"), path("user/<int:user_id>/workouts/create/", views.add_workout, name="add_workout") ] 

Answer: You specified an app_name = … [Django-doc], so it is: return redirect('myapp:user_workouts')
Question: I want to run some code when my Django server starts-up in order to clean up from the previous end of the server. How can I run some code once and only once at startup before the server processes any requests. I need to access the database during this time. I've read a couple of things online that seem a bit outdated and are also not guaranteed to run only once. Update I've looked at the suggested answer by looking into the ready function. That appears to work, but it is documented that you should not access the database there (https://docs.djangoproject.com/en/dev/ref/applications/#django.apps.AppConfig.ready) There are many suggestions at Execute code when Django starts ONCE only?, but since that post is a few years old, I thought there might be some additional solutions. This looks promising from django.dispatch import receiver from django.db.backends.signals import connection_created @receiver(connection_created) def my_receiver(connection, **kwargs): with connection.cursor() as cursor: # do something to the database connection_created.disconnect(my_receiver)  Any other thoughts?

Answer: This is often done with the .ready() method [Django-doc] of any of the AppConfig classes [Django-doc] of an installed app. So if you have an app named app_name, you can work with: # app_name/apps.py from django.apps import AppConfig class MyAppConfig(AppConfig): # … def ready(self): # my management command # … This will run after the models of all INSTALLED_APPS are loaded, so you can do management commands. This is also often used to hook signals to models.
Question: I would like to install Python packages in the CI/CD pipeline using the uv package manager. I did not create a virtual environment because I would like to use the virtual machine's global Python interpreter. When I run the uv pip install <package> script, I get the following error: Requirement already satisfied: pip in /opt/hostedtoolcache/Python/3.12.4/x64/lib/python3.12/site-packages (24.1.1) Collecting pip Downloading pip-24.1.2-py3-none-any.whl.metadata (3.6 kB) Downloading pip-24.1.2-py3-none-any.whl (1.8 MB) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 1.8/1.8 MB 32.0 MB/s eta 0:00:00 Installing collected packages: pip Attempting uninstall: pip Found existing installation: pip 24.1.1 Uninstalling pip-24.1.1: Successfully uninstalled pip-24.1.1 Successfully installed pip-24.1.2 Collecting uv Downloading uv-0.2.23-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.metadata (35 kB) Downloading uv-0.2.23-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (13.4 MB) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 13.4/13.4 MB 104.1 MB/s eta 0:00:00 Installing collected packages: uv Successfully installed uv-0.2.23 error: No virtual environment found  Is it possible to install it into the global Python environment?

Answer: It is possible to install packages into the system Python using the --system option: uv pip install --system <packages>  The --system option instructs uv to instead use the first Python found in the system PATH.  WARNING: --system is intended for use in continuous integration (CI) environments and should be used with caution, as it can modify the system Python installation.  Reference to Installing into arbitrary Python environments.
Question: Consider this script: print("before loop") for i in range(100): breakpoint() print("after loop") breakpoint() print("exit")  Short of pressing "c" one hundred times, how can you get past the breakpoint within the loop at L3 and proceed to L5? I've tried the ignore command but couldn't work it out: $ python3 example.py before loop > /tmp/example.py(2)<module>() -> for i in range(100): (Pdb) ignore 0 *** Breakpoint 0 already deleted (Pdb) c > /tmp/example.py(2)<module>() -> for i in range(100): (Pdb) ignore 0 *** Breakpoint 0 already deleted (Pdb) c > /tmp/example.py(2)<module>() -> for i in range(100):  I want to execute the remainder of the loop, without tripping again the breakpoint on L3, then print "after loop" and break before printing "exit", remaining in the debugger. The answer must not require exiting the debugger and re-entering the runtime, or modifying the source code.

Answer: You can use the PYTHONBREAKPOINT environment variable to call a custom breakpoint handler that you define in a separate file. For example: $ export PYTHONBREAKPOINT=mybreak.mybreak  # mybreak/__init__.py import pdb _counter = 0 def mybreak(*args, **kwargs): global _counter if _counter >= 100: # default behavior pdb.set_trace(*args, **kwargs) else: # skip dropping into pdb while inside the range(100) loop pass _counter += 1  You might have to get a little tricky if there are other invocations of breakpoint() in the file but it would just be a matter of tracking what the counter value would be when you want to skip over the breakpoint. An alternate implementation of the custom handler, as suggested in nneonneo's answer: # mybreak/__init__.py import inspect import pdb def mybreak(): caller = inspect.stack()[1] if caller.filename.endswith("/foo.py") and caller.lineno == 2: # skip this breakpoint return pdb.set_trace(*args, **kwargs)
Question: I am trying to make a point object in 3D in python, and I have the following code import numpy as np class Point3D: def __init__(self, x, y, z): self.vector = np.matrix([x, y, z]) self.vector.reshape(3, 1) def x(self): return self.vector.item((0, 0)) def y(self): return self.vector.item((0, 1)) def z(self): return self.vector.item((0, 2))  I am using numpy to create vertical matrices to eventually use this for a rendering engine. I want to be able to reference the x,y and z of this vector without having to type self.vector.item((0, 0)) for example. I want to be able to do point.x and get the x value from the vector automatically. I also want to be able to set the values as such: point.x = 5. Is there any way this possible? I tried setting them at the start in the init function but then I would have to update it every time. I then made functions to there would only have to be an extra 2 chars, but setting is still not implemented.

Answer: What you are wanting to do is property getter and setters. The @property decorator returns a value without having to call the method. I.e. use p.x instead of p.x(). To assign a value to the property, you use the @<propertyname>.setter decorator which implements assigning to the property via p.x = 3. I added a __repr__ so the object looks nice if you are in interactive mode in Python. import numpy as np class Point3D: def __init__(self, x, y, z): self.vector = np.matrix([x, y, z]).reshape(3,1) def __repr__(self): n = self.__class__.__name__ return f'{n}({self.x}, {self.y}, {self.z})' @property def x(self): return self.vector[0,0] @property def y(self): return self.vector[1,0] @property def z(self): return self.vector[2,0] @x.setter def x(self, x_val): self.vector[0,0] = x_val @y.setter def y(self, y_val): self.vector[1,0] = y_val @z.setter def z(self, z_val): self.vector[2,0] = z_val
Question: I've recently started using pytest for testing in Python and created a fixture to manage a collection of items using gRPC. Below is the code snippet for my fixture: import pytest @pytest.fixture(scope="session") def collection(): grpc_page = GrpcPages().collections def create_collection(collection_id=None, **kwargs): default_params = { "id": collection_id, "is_active": True, # some other params } try: return grpc_page.create_collection(**{**default_params, **kwargs}) except Exception as err: print(err) raise err yield create_collection def delete_created_collection(): # Some code to hard and soft delete created data  This is my first attempt at creating a fixture, and I realized that I need a mechanism to delete data created during the fixture's lifecycle. While exploring options for implementing teardown procedures, I came across yield and addfinalizer. From what I understand, both can be used to define teardown actions in pytest fixtures. However, I'm having trouble finding clear documentation and examples that explain the key differences between these two approaches and when to choose one over the other. Here are the questions (for fast-forwarding :) ):  What are the primary differences between using yield and addfinalizer in pytest fixtures for handling teardown? Are there specific scenarios where one is preferred over the other? 

Answer: The main difference is not the number of addfinalizer or fixtures, there is no difference at all. You can add as many as you want (or just have more than one operation in on of them) @pytest.fixture(scope='session', autouse=True) def fixture_one(): print('fixture_one setup') yield print('fixture_one teardown') @pytest.fixture(scope='session', autouse=True) def fixture_two(): print('fixture_two setup') yield print('fixture_two teardown') def test_one(): print('test_one')  Output example.py::test_one fixture_one setup fixture_two setup PASSED [100%]test_one fixture_two teardown fixture_one teardown  The main difference is if the teardown will run in case of a failure in the setup stage. This is useful if there is need for cleanup even if the setup failed. Without finalizer the teardown won't run if there was an exception in the setup @pytest.fixture(scope='session', autouse=True) def fixture_one(): print('fixture_one setup') raise Exception('Error') yield print('fixture_one teardown') def test_one(): print('test_one')  Output ERROR [100%] fixture_one setup test setup failed ... E Exception: Error example.py:8: Exception  But with finalizer it will @pytest.fixture(scope='session', autouse=True) def fixture_one(request): def finalizer(): print('fixture_one teardown') request.addfinalizer(finalizer) print('fixture_one setup') raise Exception('Error') yield  Output ERROR [100%] fixture_one setup test setup failed ... E Exception: Error example.py:13: Exception fixture_one teardown
Question: The prototype for numpy.histogram contains an input argument density of type bool and default value None. If the caller does not supply density, what value does it take on? The closest Q&A that I can find is this. The first answer says "Don't use False as a value for a non-bool field", which doesn't apply here. It also says that bool(x) returns False, but that doesn't assure the caller that the function will set density to False if it isn't provided. Is this a mistake in the documentation of the prototype for numpy.histogram, or am I missing something about the documentation convention? The other answers to the above Q&A do not seem relevant to my question.

Answer: This is at best poorly documented. The documentation seems to imply that False and the default None will be treated equivalently, but it should either document that explicitly, or use the more sensible False as the default value. (The third option would be if the function makes a distinction between False and None, but that also should be explicitly documented.)
Question: I have a list like this: list1 = [ '000c.29e6.8fa5', 'fa16.3e9f.0c8c', 'fa16.3e70.323b' ]  I'm going to convert them to mac addresses in format 00:0C:29:E5:8F:A5 in uppercase. How can I do that? I googled but found nothing. I also thought how to do, but still don't have any clues. I just know this: for x in list1: x = x.replace('.', '').upper()[::1]  I know [::1] splits, but not sure if it's correct and if I can continue with this or not.

Answer: Another way, using bytes.fromhex() and bytes.hex(): >>> [":".join(bytes([b]).hex() for b in bytes.fromhex(l.replace(".", ""))) for l in list1] ['00:0c:29:e6:8f:a5', 'fa:16:3e:9f:0c:8c', 'fa:16:3e:70:32:3b']  Naturally, if you need upper-case, slap that on at the end. >>> [":".join(bytes([b]).hex() for b in bytes.fromhex(l.replace(".", ""))).upper() for l in list1] ['00:0C:29:E6:8F:A5', 'FA:16:3E:9F:0C:8C', 'FA:16:3E:70:32:3B']
Question: Consider some Polars code like so: df.with_columns( pl.date_ranges( pl.col("current_start"), pl.col("current_end"), "1mo", closed="left" ).alias("current_tpoints") ).drop("current_start", "current_end").with_columns( pl.date_ranges( pl.col("history_start"), pl.col("history_end"), "1mo", closed="left" ).alias("history_tpoints") ).drop( "history_start", "history_end" )  The key issue to note here is the repetitiveness of history_* and current_*. I could reduce duplication by doing this: for x in ["history", "current"]: fstring = f"{x}" + "_{other}" start = fstring.format(other="start") end = fstring.format(other="end") df = df.with_columns( pl.date_ranges( pl.col(start), pl.col(end), "1mo", closed="left", ).alias(fstring.format(other="tpoints")) ).drop(start, end)  But are there any other ways to reduce duplication I ought to consider?

Answer: As it seems like you might not need any original columns, you could use select() instead of with_columns(), so you don't need to drop() columns. And you can loop over column names within select() / with_columns(): df.select( pl.date_ranges( pl.col(f"{c}_start"), pl.col(f"{c}_end"), "1mo", closed="left" ).alias(f"{c}_tpoints") for c in ["current", "history"] )  To explain why this works: According to documentation, both select() and with_columns() methods can *exprs: IntoExpr | Iterable[IntoExpr] which means variable amount of arguments. You see it can be either multiple expressions or multiple lists of expressions. This is exactly what we can do with list comprehension, we just create list of expressions. [ pl.date_ranges( pl.col(f"{c}_start"), pl.col(f"{c}_end"), "1mo", closed="left" ).alias(f"{c}_tpoints") for c in ["current", "history"] ] [<Expr ['col("current_start").date_rang…'] at 0x206D93030E0>, <Expr ['col("history_start").date_rang…'] at 0x206D8F85520>]  Which we can then pass into the polars method. Notice that I didn't have square brackets in the final answer. This is cause we don't really need a list of expressions, we just need an iterable (in this case - generator).
Question: My DataFrame: import pandas as pd df = pd.DataFrame( { 'a': ['a', 'a', 'a', 'b', 'c', 'x', 'j', 'w'], 'b': [1, 1, 1, 2, 2, 3, 3, 3], } )  Expected output is changing column a:  a b 0 a 1 1 a 1 2 a 1 3 NaN 2 4 NaN 2 5 NaN 3 6 NaN 3 7 NaN 3  Logic: The groups are based on b. If for a group df.a.nunique() > 1 then df.a == np.nan. This is my attempt. It works but I wonder if there is a one-liner/more efficient way to do it: df['x'] = df.groupby('b')['a'].transform('nunique') df.loc[df.x > 1, 'a'] = np.nan 

Answer: More efficient than groupby, use duplicated with keep=False, and boolean indexing: df.loc[~df[['a', 'b']].duplicated(keep=False), 'a'] = float('nan')  If you really want to use groupby.transform: df.loc[df.groupby('b')['a'].transform('nunique')>1, 'a'] = float('nan')  Output:  a b 0 a 1 1 a 1 2 a 1 3 NaN 2 4 NaN 2 5 NaN 3 6 NaN 3 7 NaN 3
Question: I'm trying to have an image rotate and translate in matplotlib according to a predefined pattern. I'm trying to use FuncAnimation and Affine2D to achieve this. My code looks something like this : from matplotlib.animation import FumcAnimation from matplotlib.transforms import Affine2D from matplotlib import pyplot as plt fig, ax = plt.subplots() img = ax.imgshow(plt.imread("demo.png"),aspect="equal") def update(i): if i>0: img.set_transform(Affine2D().translate(1,0)) return img anim=FuncAnimation(fig,update,frames=(0,1)) plt.show()  Instead of the image moving right, it disappears.

Answer: You're not using the value of the frames (0 or 1) to make the movement and that's not the only issue. So, assuming you want to simultaneously translate the image (to the right) and rotate_deg (relative to the center), you can do something like below : import matplotlib.pyplot as plt import matplotlib.transforms as mtransforms from matplotlib.animation import FuncAnimation img = plt.imread("mpl_log.png") W, H, *_ = img.shape fig, ax = plt.subplots(figsize=(10, 5)) # feel free to readapt.. ax.grid() ax.patch.set_facecolor("whitesmoke") aximg = ax.imshow(img, aspect="equal") ax.set(xlim=(-W // 2, W * 7), ylim=(-H, H * 2)) def move(frame): transfo = mtransforms.Affine2D() ( transfo # centered rotation .translate(-W / 2, -H / 2) .rotate_deg(frame % 190) .translate(W / 2, H / 2) # translation to the right .translate(frame, 0) ) aximg.set_transform(transfo + ax.transData) return (aximg,) anim = FuncAnimation(fig, move, frames=range(0, W * 6, 100))  Output (fps=10) :
Question: I've the following dataframe  df = pl.DataFrame({ "col1": [1, 2, 3], "col2": [4, 5, 6], "col3": [7, 8, 9], "col4": ["a", "v", "b"], })  I'd like to add a column containing the variance for all columns except col4. So far I've found this that could be a workaround the lack of horizontal computations in polars. df = ( (_df := df.with_row_index('i')) .join( _df.melt('i').group_by('i').agg(pl.col('value').var()), on='i' ) .sort('i') .drop('i') )  However this only found when all columns are numerical. Is there a way to exclude col4 but to have it in the final dataframe?

Answer:  selectors to filter out non-numeric columns. concat_list() to get chosen columns into list. list.var() to calculate variance.  import polars.selectors as cs df.with_columns(var = pl.concat_list(cs.numeric()).list.var()) ┌──────┬──────┬──────┬──────┬─────┐ │ col1 ┆ col2 ┆ col3 ┆ col4 ┆ var │ │ --- ┆ --- ┆ --- ┆ --- ┆ --- │ │ i64 ┆ i64 ┆ i64 ┆ str ┆ f64 │ ╞══════╪══════╪══════╪══════╪═════╡ │ 1 ┆ 4 ┆ 7 ┆ a ┆ 9.0 │ │ 2 ┆ 5 ┆ 8 ┆ v ┆ 9.0 │ │ 3 ┆ 6 ┆ 9 ┆ b ┆ 9.0 │ └──────┴──────┴──────┴──────┴─────┘
Question: For comparison purposes, I want to create an object which would have the same shape and indexing properties in matlab and python (numpy). Let's say that on the matlab side the object would be : arr_matlab = cat(4, ... cat(3, ... [ 1, 2; 3, 4; 5, 6], ... [ 7, 8; 9, 10; 11, 12], ... [ 13, 14; 15, 16; 17, 18], ... [ 20, 21; 22, 23; 24, 25]), ... cat(3, ... [ 26, 27; 28, 29; 30, 31], ... [ 32, 33; 34, 35; 36, 37], ... [ 38, 39; 40, 41; 42, 43], ... [ 44, 45; 46, 47; 48, 49]), ... cat(3, ... [ 50, 51; 52, 53; 54, 55], ... [ 56, 57; 58, 59; 60, 61], ... [ 62, 63; 64, 65; 66, 67], ... [ 68, 69; 70, 71; 72, 73]), ... cat(3, ... [ 74, 75; 76, 77; 78, 79], ... [ 80, 81; 82, 83; 84, 85], ... [ 86, 87; 88, 89; 90, 91], ... [ 92, 93; 94, 95; 96, 97]), ... cat(3, ... [ 98, 99; 100, 101; 102, 103], ... [104, 105; 106, 107; 108, 109], ... [110, 111; 112, 113; 114, 115], ... [116, 117; 118, 119; 120, 121])); K>> size(arr_matlab) ans = 3 2 4 5 K>> arr_matlab(1, 2, 1 ,1) ans = 2  size(arr_matlab) should be identical to arr_python.shape and indexing should give the same result (same result for arr_python[0,1,0,0] and arr_matlab(1,2,1,1) for example). For the moment I can't do it. data = np.array([ ...: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 20, 21, 22, 23, 24, 25, ...: 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, ...: 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, ...: 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, ...: 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121 ...: ]) ...: ...: # Reshape to 3x2x4x5 ...: arr_python = data.reshape((3, 2, 4, 5), order='F') In [138]: arr_python.shape Out[138]: (3, 2, 4, 5) arr_python[0,1,0,0] Out[143]: 4 

Answer: This is what you're trying to achieve in Python and MatLab: MatLab arr_matlab = reshape(1:120, [3, 2, 4, 5]); L = size(arr_matlab); disp(L); disp(arr_matlab(1, 2, 1, 1));  Prints 3 2 4 5 4  Python import numpy as np data = np.arange(1, 120 + 1) arr_python = data.reshape((3, 2, 4, 5), order='F') print(arr_python.shape) print(arr_python[0, 1, 0, 0])  Prints (3, 2, 4, 5) 4   Comments:  Note that Python's end range is not inclusive.  You could simplify data = np.array(list(range(1, 120 + 1))) to data = np.arange(1, 120 + 1) in the Python version.  Python’s F ordering is reversed from its C ordering. But this doesn’t match MATLAB’s ordering. If Python’s C ordering is indexed as a,b,c,d, then MATLAB’s ordering is c,d,b,a. It’s weird, I know. Test your code with more than that one indexing operation, you might find discrepancies. – Cris Luengo  OK, my comment above relates to the interpretation of axes in MATLAB and Python, but not about the storage order, which is what this question is about. I did test the indexing for this solution, and it does match. – Cris Luengo
Question: Here's my query: def create_entity_nodes(tx, report_id, entities): query = ( "UNWIND $entities AS entity " "MATCH (report:Report {id: $report_id}) " "CREATE (entity.name:entity.type entity), " "(report)-[:OWNS]->(entity.name) " "(entity.name)-[:BELONGS_TO]->(report)" "RETURN report" )  I previously only did it with one entity in my code below and it worked. So, I wanted to try it with a list but I'm not sure if it's possible.  entity_type = entity["type"] if not entity_type: raise ValueError("Entity type is required.") entity_type = entity_type[0].upper() + entity_type[1:].lower() entity.pop("type") query = ( f"MATCH (report:Report {{id: $report_id}}) " f"CREATE ({entity['name']}:{entity_type} $props), " f"({entity['name']})-[:BELONGS_TO]->(report), " f"(report)-[:OWNS]->({entity['name']})" f"RETURN report" ) result = tx.run(query, report_id=report_id, props=entity) 

Answer: No, your first query won't work. At the moment, the only way to create labels dynamically is to build the query string as you did with your second query, or by using an apoc function like apoc.create.node.
Question: I have a list of substrings: ls = ['BLAH a b c A B C D 12 34 56', 'BLAH d A B 12 45 78', 'BLAH a/b A B C 12 45 78', 'BLAH a/ b A 12 45 78', 'BLAH a b c A B C D 12 34 99']  I want to replace the lower case substrings with an identifier: dict2 = {'a b c':'1','d':'2','a/b':'3','a/ b':'4'}  I am looping over all the items in the list and trying to perform a replace using: [[ls[i].replace(k,v) for k,v in dict2.items()][0] for i in range(len(ls))]  but this does not perform the correct replacement from the dictionary for each element(d, a/b, and a/ b were not replaced), and results in: ['BLAH 1 A B C D 12 34 56', 'BLAH d A B 12 45 78', 'BLAH a/b A B C 12 45 78', 'BLAH a/ b A 12 45 78', 'BLAH 1 A B C D 12 34 99']  I would like to end up with: ['BLAH 1 A B C D 12 34 56', 'BLAH 2 A B 12 45 78', 'BLAH 3 A B C 12 45 78', 'BLAH 4 A 12 45 78', 'BLAH 1 A B C D 12 34 99'] 

Answer: This way seems to work for me. Here is an online test: https://www.pythonmorsels.com/p/2qmeh/ result = [] for s in ls: for k, v in dict2.items(): s = s.replace(k, v) result.append(s) print(result)