eshangj/stackoverflow_q_and_a_sample huggingface dataset:
Question: I'm learning Python and Qt, and as an exercise I designed a simple window in QT Designer with a QGraphicsView which would represent a stack data structure. It should hold the items on the stack as a rectangle with a label representing the item, but my problem is that I can't position the rectangle at(x,y). Google and the documentation didn't help. Maybe it's a simple oversight or it's just me being dumb. This code draws a rectangle in the center of the QGraphicsView, and it should(if I understand correctly)place a 10x10 rectangle at 10,10: class Ui(QMainWindow): def __init__(self): super().__init__() uic.loadUi('Stack.ui', self) self.scene = QGraphicsScene() self.graphicsView.setScene(self.scene) self.scene.addRect(QRectF(10,10,10,10)) app=QApplication([]) window=Ui() window.show() app.exec()  Stack.ui: <?xml version="1.0" encoding="UTF-8"?> <ui version="4.0"> <class>MainWindow</class> <widget class="QMainWindow" name="MainWindow"> <property name="geometry"> <rect> <x>0</x> <y>0</y> <width>800</width> <height>600</height> </rect> </property> <property name="windowTitle"> <string>MainWindow</string> </property> <widget class="QWidget" name="centralwidget"> <layout class="QGridLayout" name="gridLayout"> <item row="0" column="1"> <widget class="QLineEdit" name="lineEdit"> <property name="sizePolicy"> <sizepolicy hsizetype="Minimum" vsizetype="Fixed"> <horstretch>0</horstretch> <verstretch>0</verstretch> </sizepolicy> </property> </widget> </item> <item row="0" column="0" rowspan="3"> <widget class="QGraphicsView" name="graphicsView"/> </item> <item row="0" column="3"> <widget class="QPushButton" name="pushButton"> <property name="text"> <string>Push</string> </property> </widget> </item> <item row="1" column="3"> <widget class="QPushButton" name="pushButton_2"> <property name="text"> <string>Pop</string> </property> </widget> </item> </layout> </widget> <widget class="QMenuBar" name="menubar"> <property name="geometry"> <rect> <x>0</x> <y>0</y> <width>800</width> <height>24</height> </rect> </property> </widget> <widget class="QStatusBar" name="statusbar"/> </widget> <resources/> <connections/> </ui> 

Answer: from PyQt5 import uic from PyQt5.QtCore import * from PyQt5.QtWidgets import * from PyQt5.QtCore import Qt class Ui(QMainWindow): def __init__(self): super().__init__() uic.loadUi('Stack.ui', self) self.scene = QGraphicsScene() self.graphicsView.setScene(self.scene) self.graphicsView.setSceneRect(0, 0, 250, 250) # adjust as needed self.graphicsView.setAlignment(Qt.AlignTop | Qt.AlignLeft) self.scene.addRect(QRectF(10, 10, 10, 10)) app = QApplication([]) window = Ui() window.show() app.exec()
Question: My directory structure is C:\Users\...\[MATH] foldername So to change directories, as per some SE post I saw, I have to use: cd 'C:\Users\...\`[MATH`] foldername' which indeed changes to the required directory. Once here, I use py -m venv Project, and it creates the Project folder with the venv stuff correctly. When I try to run Scripts\activate, I get the following error: Line | 185 | $VenvDir = $VenvExecDir.Parent.FullName.TrimEnd("\\/") | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | You cannot call a method on a null-valued expression. Line | 138 | $pyvenvConfigPath = Join-Path -Resolve -Path $ConfigDir -ChildPat … | ~~~~~~~~~~ | Cannot bind argument to parameter 'Path' because it is an empty string. Line | 206 | … ose " Got leaf-name of $VenvDir='$(Split-Path -Path $venvDir -Leaf)' … | ~~~~~~~~ | Cannot bind argument to parameter 'Path' because it is an empty string.Line | 207 | $Prompt = Split-Path -Path $venvDir -Leaf | ~~~~~~~~ | Cannot bind argument to parameter 'Path' because it is an empty string.  I don't really know how to proceed. Thanks in advance for help. If it helps I'm on a windows system. Basically, I was able to narrow down the problem to the fact that my directory has a special character in it. Using the same procedure for other paths that don't have this causes no issues.

Answer: Python's bundled venv module (v3.4+), as of v3.12.3, has a bug that prevents it from working properly in directories whose names contain [ / ] in PowerShell. These characters are metacharacters (characters with special meaning) in PowerShell wildcard expressions, and arguments passed to the -Path parameter (which is also the first positional parameter) of file system-related cmdlets such as Get-Item and Get-ChildItem are interpreted as wildcard expressions. To ensure verbatim interpretation of a path, use the -LiteralPath parameter instead. You have two workaround options:  Bypass the problem by avoiding [ / ] in your project directory names.  Manually fix ./Scripts/bin/Activate.ps1 once your project has been initialized with python -m venv ./Scripts.  To do so, replace the line $VenvExecDir = Get-Item -Path $VenvExecPath with $VenvExecDir = Get-Item -LiteralPath $VenvExecPath
Question: I want to plot a sequence of three colormaps in a 3D space, with a line crossing all the planes of the colormaps, as shown in the figure below. https://i.sstatic.net/65yOib6B.png To do that, I am using mpl.plot_surface to generate the planes and LinearSegmentedColormap to create a colormap that transitions from transparent to a specific color. However, when I plot the figure, a gray grid appears on my plot. How can I remove it? Ideally, the blue shade would appear on a completely transparent plane, but a lighter color could also work. Here is the code I used to generate the plot: import matplotlib.pyplot as plt import numpy as np from matplotlib.colors import LinearSegmentedColormap # Testing Data sigma = 1.0 mu = np.linspace(0,2, 10) x = np.linspace(-5, 5, 100) y = np.linspace(-5, 5, 100) X, Y = np.meshgrid(x, y) Z = [] for m in mu: Z.append(np.exp(-((X - m)**2 + (Y - m)**2) / (2 * sigma**2))) fig = plt.figure() ax = fig.add_subplot(111, projection='3d') for i in [0, 5, -1]: cmap = LinearSegmentedColormap.from_list('custom_blue', [(1, 1, 1, 0), (0, 0, 1, 1)]) wmap = cmap(Z[i]/Z[i].max()) ax.plot_surface(mu[i] * np.ones(X.shape), X, Y,facecolors=wmap, alpha=1, antialiased=True, edgecolor='none') loc_max_x = [] loc_max_y = [] for i in range(len(mu)): loc_x = np.where(Z[i] == Z[i].max())[0][0] loc_y = np.where(Z[i] == Z[i].max())[1][0] loc_max_x.append(loc_x) loc_max_y.append(loc_y) ax.plot(mu, x[loc_max_x], y[loc_max_y], color='r') ax.set_box_aspect((3.4, 1, 1)) plt.savefig('3dplot.png', dpi=300) plt.show() 

Answer: I think there's nothing you could have done better in matplotlib, great job! I think to solve your problem, it is better to change the library and approach your problem using plotly. Please see my code: import plotly.graph_objects as go import numpy as np # Testing Data sigma = 1.0 mu = np.linspace(0, 2, 10) x = np.linspace(-5, 5, 100) y = np.linspace(-5, 5, 100) X, Y = np.meshgrid(x, y) Z = [] for m in mu: Z.append(np.exp(-((X - m)**2 + (Y - m)**2) / (2 * sigma**2))) fig = go.Figure() colorscale = [[0, 'rgba(255, 255, 255, 0)'], [1, 'rgba(0, 0, 255, 1)']] # colorscale = transparent to blue #plot the surfaces for i in [0, 5, -1]: fig.add_trace(go.Surface( x=mu[i] * np.ones(X.shape), y=X, z=Y, surfacecolor=Z[i], colorscale=colorscale, cmin=0, cmax=Z[i].max(), showscale=False, opacity=1)) #plot the line crossing the surfaces loc_max_x = [] loc_max_y = [] for i in range(len(mu)): loc_x = np.where(Z[i] == Z[i].max())[0][0] loc_y = np.where(Z[i] == Z[i].max())[1][0] loc_max_x.append(loc_x) loc_max_y.append(loc_y) #add the line trace fig.add_trace(go.Scatter3d( x=mu, y=x[loc_max_x], z=y[loc_max_y], mode='lines', line=dict(color='red', width=5))) fig.update_layout(scene_aspectmode='manual', scene_aspectratio=dict(x=3.4, y=1, z=1), scene=dict(xaxis_title='mu', yaxis_title='X', zaxis_title='Y')) fig.show()  which results this plot:
Question: I'm trying to use re.findall(pattern, string) to match all numbers and however many duplicates follow in a string. Eg. "1222344" matches "1", "222", "3", "44". I can't seem to find a pattern to do so though. I tried using the pattern "(\d)\1+" to match a digit 1 or more times but it doesn't seem to be working. But when I print the result, it shows up as an empty array [].

Answer: You're on the right track but your pattern (\d)\1+ actually matches two or more contiguous digits (the first digit is matched by \d and then the + quantifier says match one or more of that digit. So what you want is (\d)\1* where the * says match zero or more of that previous digit The other thing that is perhaps confusing is that re.findall() only returns a list of the matched subexpressions (in this case the individual digit) to see the entire string matched you can use re.search() or re.finditer() to get a match object then access the entire matched string using mo.group(0) import re text = "122333444455555666666" patt = re.compile(r"(\d)\1*") print() print(patt.findall(text)) # print list of JUST first digit in each run print() for mo in patt.finditer(text): # iterate over all the Match Objects print(mo.group(0)) # group(0) is the entire matched string  Output is: ['1', '2', '3', '4', '5', '6'] 1 22 333 4444 55555 666666
Question: I'm curious about how Python handles "if" statements with multiple conditions. Does it evaluate the total boolean expression, or will it "break" from the expression with the first False evaluation? So, for example, if I have: if (A and B and C): Do_Something()  Will it evaluate "A and B and C" to be True/False (obviously), and then apply the "if" to either enter or not enter Do_Something()?, or will it evaluate each sequentially, and if any turn out to be false it will break. So, say A is True, B is False. Will it go: A is true --> keep going, B is false - now break out and not do Do_Something()? The reason I ask is that in the function I'm working on, I've organised A, B, and C to be functions of increasing computational load, and it (of course) would be a complete waste to run B and C if A is False; and equally C is A is True and B is False). Now, of course, I could simple restructure the code to the following, but I was hoping to use the former if possible: if (A): if (B): if (C): Do_Something()  Of course, this equally applies to while statements as well. Any input would be greatly appreciated.

Answer: It's the latter. if A and B and C: Do_Something()  is equivalent to if A: if B: if C: Do_Something()  This behavior is called short-circuit evaluation.
Question: I'm trying to format a datetime object in Python using either the strftime method or an f-string. I would like to include the time zone offset from UTC with a colon between the hour and minute. According to the documentation, a format code, %:z, may be available to do exactly what I want. The documentation does warn, however, that this may not be available on all platforms. I am running Python 3.10 on Windows, and it doesn't seem to work for me. I guess I'm wondering if I just have the syntax mixed up or if indeed this format code isn't available to me. Anyone else have experience with this? The following statement raises a ValueError: Invalid format string: print(f"{datetime.now().astimezone():%Y-%m-%d %H:%M:%S%:z}")  Using the %z format code instead of the %:z code does work, however, giving me something close to what I want, namely 2024-10-09 13:17:21-0700 at the time I ran it: print(f"{datetime.now().astimezone():%Y-%m-%d %H:%M:%S%z}") 

Answer: Per documentation:  Added in version 3.12: %:z was added.  Example on Windows 10: Python 3.12.6 (tags/v3.12.6:a4a2d2b, Sep 6 2024, 20:11:23) [MSC v.1940 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import datetime as dt >>> print(f"{dt.datetime.now().astimezone():%Y-%m-%d %H:%M:%S%:z}") 2024-10-09 15:46:13-07:00  Pre 3.12, you could make a helper function: import datetime as dt def now(): s = f'{dt.datetime.now().astimezone():%Y-%m-%d %H:%M:%S%z}' return s[:-2] + ':' + s[-2:] print(now())  Output: 2024-10-09 15:52:51-07:00
Question: I have the following dataframe: data = [['123456ABCD234567', 'A'], ['8502', 'A'], ['74523654894WRZI3', 'B'], ['85CGNK6987541236', 'B'], ['WF85Z4HJ95R4CF2V', 'C'], ['VB52FG85RT74DF96', 'C'], ['WERTZ852146', 'D'], ['APUNGF', 'D'] ] df = pd.DataFrame(data, columns=['CODE', 'STOCK']) df CODE STOCK 0 123456ABCD234567 A 1 8502 A 2 74523654894WRZI3 B 3 85CGNK6987541236 B 4 WF85Z4HJ95R4CF2V C 5 VB52FG85RT74DF96 C 6 WERTZ852146 D 7 APUNGF D  Each stock is part of various codes. The code should have a length of 16 characters. My objective is to filter out any stocks that have no codes attached which are not composed of 16 characters. In this example, stock A has at least one code with a length of 16 characters, so it should be kept. However, stock D has no codes with a length of 16 characters. I believe this can be accomplished using the groupby-function in Pandas. Ultimately, I aim at obtaining below output:  CODE STOCK 6 WERTZ852146 D 7 APUNGF D  Many thanks for any suggestions in advance!

Answer: You could create a boolean column for values not matching the condition and groupby.transform with all to identify the STOCK with all non matching rows: out = df[df['CODE'].str.len().ne(16).groupby(df['STOCK']).transform('all')]  Output:  CODE STOCK 6 WERTZ852146 D 7 APUNGF D  Intermediates:  CODE STOCK str.len ne(16) transform('all') 0 123456ABCD234567 A 16 False False 1 8502 A 4 True False 2 74523654894WRZI3 B 16 False False 3 85CGNK6987541236 B 16 False False 4 WF85Z4HJ95R4CF2V C 16 False False 5 VB52FG85RT74DF96 C 16 False False 6 WERTZ852146 D 11 True True 7 APUNGF D 6 True True  Using DeMorgan's law you could also run: out = df[~df['CODE'].str.len().eq(16).groupby(df['STOCK']).transform('any')]  Intermediates:  CODE STOCK str.len eq(16) transform('any') ~ 0 123456ABCD234567 A 16 True True False 1 8502 A 4 False True False 2 74523654894WRZI3 B 16 True True False 3 85CGNK6987541236 B 16 True True False 4 WF85Z4HJ95R4CF2V C 16 True True False 5 VB52FG85RT74DF96 C 16 True True False 6 WERTZ852146 D 11 False False True 7 APUNGF D 6 False False True  And without groupby you could identify all the STOCK that have at least one match, and reverse select the others with isin: out = df[~df['STOCK'].isin(df.loc[df['CODE'].str.len().eq(16), 'STOCK'].unique())]  Intermediates: df.loc[df['CODE'].str.len().eq(16), 'STOCK'].unique() # array(['A', 'B', 'C'], dtype=object) ~df['STOCK'].isin(df.loc[df['CODE'].str.len().eq(16), 'STOCK'].unique()) # 0 False # 1 False # 2 False # 3 False # 4 False # 5 False # 6 True # 7 True # Name: STOCK, dtype: bool
Question: I created a function and want to run it automatically on start. The function creates several objects I have an error AppRegistryNotReady("Apps aren't loaded yet.") Reason is clear - the function imports objects from another application (parser_app) I am starting app like this  gunicorn --bind 0.0.0.0:8000 core_app.wsgi # project/core_app/wsgi.py import os from django.core.wsgi import get_wsgi_application from django.core.management import call_command from scripts.create_schedules import create_cron_templates os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core_app.settings') application = get_wsgi_application() call_command("migrate") call_command("collectstatic", interactive=False) create_cron_templates()  Full error: django_1 | File "/project/core_app/wsgi.py", line 14, in <module> django_1 | from scripts.create_schedules import create_cron_templates django_1 | File "/project/scripts/create_schedules.py", line 1, in <module> django_1 | from parser_app.models import Schedule django_1 | File "/project/parser_app/models.py", line 7, in <module> django_1 | class TimeBase(models.Model): django_1 | File "/usr/local/lib/python3.9/site-packages/django/db/models/base.py", line 127, in __new__ django_1 | app_config = apps.get_containing_app_config(module) django_1 | File "/usr/local/lib/python3.9/site-packages/django/apps/registry.py", line 260, in get_containing_app_config django_1 | self.check_apps_ready() django_1 | File "/usr/local/lib/python3.9/site-packages/django/apps/registry.py", line 138, in check_apps_ready django_1 | raise AppRegistryNotReady("Apps aren't loaded yet.") django_1 | django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.  Code of the function # project/scripts/create_schedules.py from parser_app.models import Schedule def create_cron_templates(): Schedule.objects.get_or_create( name="1", cron="0 9-18/3 * * 1-5#0 19-23/2,0-8/2 * * 1-5#0 */5 * * 6-7" ) 

Answer: Solved with help of ready() function in apps.py My solution class ParserAppConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'parser_app' def ready(self): from scripts.create_schedules import create_cron_templates create_cron_templates()
Question: I'm trying to create a uv project that uses an --extra-index-url with Google Cloud Artifact Registry. According to the uv documentation, this should be possible. I am using uv 0.4.18. Here's what I've tried so far: gcloud auth application-default login --project ${PROJECT_ID} uv venv source .venv/bin/activate uv pip install keyring keyrings.google-artifactregistry-auth uv pip install --keyring-provider subprocess ${MY_PACKAGE} --extra-index-url https://${REGION}-python.pkg.dev/${PROJECT_ID}/${REPOSITORY_ID}/simple  However, it returns an error indicating that my package can't be found. Interestingly, when I use standard Python, I can install my private package without any issues. Here's the code that works: gcloud auth application-default login --project ${PROJECT_ID} python -m venv .venv source .venv/bin/activate pip install keyring keyrings.google-artifactregistry-auth pip install ${MY_PACKAGE} --extra-index-url https://${REGION}-python.pkg.dev/${PROJECT_ID}/${REPOSITORY_ID}/simple  It seems like others have faced this issue before, as mentioned in this closed GitHub issue. Has anyone else encountered this problem or found a workaround? Any help would be appreciated!

Answer: Pointing to the solution of the issue here: The code that works is: gcloud auth application-default login --project ${PROJECT_ID} uv venv source .venv/bin/activate uv pip install keyring keyrings.google-artifactregistry-auth uv pip install ${MY_PACKAGE} --keyring-provider subprocess --extra-index-url https://oauth2accesstoken@${REGION}-python.pkg.dev/${PROJECT_ID}/${REPOSITORY_ID}/simple  The addition of the oauth2accesstoken string in the URL is necessary for the keyring CLI to retrieve a password, as pointed out in uv's GitHub issue 1520.
Question: I generated a bunch of violin plots, here is an example of one and the code that generates it: plt.figure(figsize=(8, 4)) ax = sns.violinplot( x=data, # `data` is a few thousand float values between 0 and 1 orient='h', color=get_color(ff), # `get_color` returns a color based on the dataset, #FFBE0B in this case cut=0 )   I want to make the black box in the middle quite a bit bigger. According to the documentation from Seaborn at https://seaborn.pydata.org/generated/seaborn.violinplot.html, I should be able to do this with the inner_kws parameter. I added this argument to the above code: plt.figure(figsize=(8, 4)) ax = sns.violinplot( x=data, # `data` is a few thousand float values between 0 and 1 orient='h', color=get_color(ff), # `get_color` returns a color based on the dataset, #FFBE0B in this case inner_kws=dict(box_width=150, whis_width=20), cut=0 )  Above, the box and whisker width are 150 and 20 respectively. I've also tried 15 and 2, and 1500 and 200. No matter what values I enter here, the figure does not change at all. What am I doing wrong?

Answer: The inner_kws argument was introduced in version 0.13.0; if you have an older version of seaborn installed it has no effect. I had seaborn v0.12.2 (installed via conda) and your example printed with normal boxplot dimensions until I upgraded seaborn to v0.13.2, E.g. #!/usr/bin/env python import random import seaborn as sns import matplotlib.pyplot as plt data = [] for i in range(0, 1000): x = round(random.uniform(0, 1), 4) data.append(x) ax = sns.violinplot( x=data, # `data` is a few thousand float values between 0 and 1 orient='h', color='#FFBE0B', inner_kws=dict(box_width=100, whis_width=20), cut=0 ) plt.savefig("example.png")   Does that solve your problem? Or is there something else causing an issue?
Question: I have a CT scan of an object: images with pixels in an x-y grid, one image per z value. I want to make x-z images, to view the object from a different angle. The most obvious way to do this: load all the images into a 3D array like bigImageArray[x,y,z] and save the slices bigImageArray[:,y,:] for each value of y. The problem: bigImageArray would be too large to store in memory. What's the best way to handle this? Attempted solution: for each y value, make an empty x-z array, open each x-y image and fill in one line. This works but is quite slow (lots of file opening/closing). Adding a python tag since that's what I've been using, but I'm open to using anything

Answer: let's say you can fit n x-y or n x-z images into memory. Load up n x-y images and use them to write out n width x n x n "blocks". Repeat until you've covered z. Then, load up all the blocks that have y=0, and use them to write out n x-z images. Repeat until you've covered y.
Question: I'm trying to parallelize the task of finding minimum cost paths through a raster cost surface, but I keep bumping into the same PicklingError: Could not pickle the task to send it to the workers. This is a code example of what's going on: import numpy as np from skimage.graph import MCP_Geometric import timeit from joblib import Parallel, delayed np.random.seed(123) cost_surface = np.random.rand(1000, 1000) mcp = MCP_Geometric(cost_surface) pois = [(np.random.randint(0, 1000), np.random.randint(0, 1000)) for _ in range(20)] def task(poi): costs_array, traceback = mcp.find_costs(starts=[poi], ends=pois) ends_idx = tuple(np.asarray(pois).T.tolist()) costs = costs_array[ends_idx] tracebacks = [mcp.traceback(end) for end in pois] Parallel(n_jobs=6)(delayed(task)(poi) for poi in pois)  I'm fairly new to parallelizing tasks, but the code I'm running might take weeks if done sequentially and want to leverage parallel. I understand that pickling is not possible for some complex objects, so I'm also looking for alternatives.

Answer: This is because MCP_Geometric is unpickable. You need to move initialization of this class into task function:  import numpy as np from skimage.graph import MCP_Geometric import timeit from joblib import Parallel, delayed np.random.seed(123) cost_surface = np.random.rand(1000, 1000) pois = [(np.random.randint(0, 1000), np.random.randint(0, 1000)) for _ in range(20)] def task(poi): # --- each process will have it's own version of the `mcp` class mcp = MCP_Geometric(cost_surface) costs_array, traceback = mcp.find_costs(starts=[poi], ends=pois) ends_idx = tuple(np.asarray(pois).T.tolist()) costs = costs_array[ends_idx] tracebacks = [mcp.traceback(end) for end in pois] Parallel(n_jobs=6)(delayed(task)(poi) for poi in pois)