QuestionId
int64
74.8M
79.8M
UserId
int64
56
29.4M
QuestionTitle
stringlengths
15
150
QuestionBody
stringlengths
40
40.3k
Tags
stringlengths
8
101
CreationDate
stringdate
2022-12-10 09:42:47
2025-11-01 19:08:18
AnswerCount
int64
0
44
UserExpertiseLevel
int64
301
888k
UserDisplayName
stringlengths
3
30
79,011,972
1,938,026
How to solve a case of circular imports with referencing dataclasses and default_factory?
<p>I'm writing a Python package in which there are a lot of units (classes, functions...) that are referencing each other. I face problems with circular imports.</p> <p>How to solve something like that:</p> <p>a.py:</p> <pre><code>from dataclasses import dataclass, field from .b import B from .c import C @dataclass class A: b: B = field(default_factory=B) c: C = field(default_factory=C) </code></pre> <p>b.py:</p> <pre><code>from dataclasses import dataclass, field from .a import A from .c import C @dataclass class B: a: A = field(default_factory=A) c: C = field(default_factory=C) </code></pre> <p>c.py:</p> <pre><code>from dataclasses import dataclass, field from .a import A from .b import B @dataclass class C: a: A = field(default_factory=A) b: B = field(default_factory=B) </code></pre> <p>The above code will lead to circular imports. I know I can solve them by putting all classes into one file. But there is a lot of code, and if I put all classes into one file each time I have this problem, then I have would very big files, and I prefer to split it into many files, for better programming experience. What would be the best way to solve that?</p> <p>What I tried:</p> <ol> <li><p>I tried putting names of the classes in <code>'</code> (apostrophes). But that doesn't work for <code>deafult_factory</code>.</p> </li> <li><p>I tried using <code>import</code> instead, but I can't figure out how to do relative imports with <code>import</code> keyword. Something like that: <code>import .a</code> didn't work.</p> </li> </ol>
<python><import><python-import><circular-dependency><circular-reference>
2024-09-22 15:23:03
0
318
Damian
79,011,931
4,690,023
Is discord.py on_message listener a privacy issue?
<p>While writing a bot with <code>discord.py</code> I realised that it would be extremely easy for a developer to log all messages that would pass through the listener <code>on_message</code>.</p> <p>A simple <code>logging</code> call in the listen such as:</p> <pre><code>@commands.Cog.listener() async def on_message(self, message): logger.debug(f&quot;Message received from {message.author} in {message.guild.name}: {message.content}&quot;) # ... </code></pre> <p>As all messages sent in channels where this bot is present passes through this listener, the 3 lines above would allow a developer with access to the bot internal log to &quot;listen&quot; to anything that is written in any channel were the bot is present.</p> <p>This is even more severe if the bot is granted (because it's required or by mistake) admin rights in the guild/server, allowing all channels in the server to be transcribed in the log.</p> <p>Is this correct? Am I doing something wrong with my bot?</p> <p>I'm not writing my bot with the intention to spy on other guilds/servers, but I'm realising how easy it would be and I would like to understand if, by mistake, I'm basically coding a spy bot or if there is a way to be more fair with my users. I would also like to avoid accusations of doing so or (probably a bit far fetched) even legal consequenses</p>
<python><discord><discord.py>
2024-09-22 14:59:38
1
1,870
Luca
79,011,915
1,581,090
How to create smooth interpolations between two images with OpenCV?
<p>I have been trying to create smooth interpolated images between two images (they might be a bit rotated, translated and/or zoomed) and came up with this function</p> <pre><code>def interpolate_images(image1, image2, n_interpolations): # Convert to grayscale for feature detection gray1 = cv2.cvtColor(image1, cv2.COLOR_BGR2GRAY) gray2 = cv2.cvtColor(image2, cv2.COLOR_BGR2GRAY) # Detect ORB keypoints and descriptors orb = cv2.ORB_create() kp1, des1 = orb.detectAndCompute(gray1, None) kp2, des2 = orb.detectAndCompute(gray2, None) # Match features using brute-force matcher bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True) matches = bf.match(des1, des2) matches = sorted(matches, key=lambda x: x.distance) # Extract location of good matches src_pts = np.float32([kp1[m.queryIdx].pt for m in matches]).reshape(-1, 1, 2) dst_pts = np.float32([kp2[m.trainIdx].pt for m in matches]).reshape(-1, 1, 2) # Find homography matrix M, mask = cv2.findHomography(dst_pts, src_pts, cv2.RANSAC, 5.0) # Identity matrix for the first image identity_matrix = np.eye(3) h, w = image1.shape[:2] # Interpolation between identity matrix and homography interpolated_images = [] for i in range(n_interpolations + 1): alpha = i / n_interpolations # Interpolated transformation matrix interpolated_matrix = (1 - alpha) * identity_matrix + alpha * M # Warp the first image with the interpolated matrix warped_image1 = cv2.warpPerspective(image1, interpolated_matrix, (w, h)) interpolated_images.append(warped_image1) return interpolated_images </code></pre> <p>However, when I run it with two very similar images like</p> <p><a href="https://i.sstatic.net/jyaJ7C5F.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/jyaJ7C5F.jpg" alt="image1" /></a> <a href="https://i.sstatic.net/F0pTxKhV.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/F0pTxKhV.jpg" alt="image2" /></a></p> <p>and with the code</p> <pre><code>img1 = cv2.imread(&quot;image1.jpg&quot;) img2 = cv2.imread(&quot;image2.jpg&quot;) # Interpolate frames n = 4 interpolated_frames = interpolate_images(img1, img2, n) for index, image in enumerate(interpolated_frames): cv2.imwrite(f&quot;interp_{index}.jpg&quot;, image) cv2.imwrite(f&quot;interp_{n+1}.jpg&quot;, img2) </code></pre> <p>there is still a rough cut between the last interpolated image (<code>interp_4.jpg</code>) and the actual second image (<code>image2.jpg</code>=<code>interp_6.jpg</code>).</p> <p>How can this be fixed, so I get a smooth transition interpolation between the two images <code>image1</code> and <code>image2</code>?</p> <p>Ideally the interpolated images only show a combination of rotation, translation and zooming between the images <code>image1</code> and <code>image2</code> ...</p> <p>Does not have to be <code>OpenCV</code>, a different library can do as well ...</p>
<python><opencv><computer-vision><feature-matching>
2024-09-22 14:52:40
0
45,023
Alex
79,011,854
1,593,077
Failure trying to pip install in Cygwin: "UserWarning: unprocessed git archival found (no export subst applied)"
<p>I'm trying to install some Python packages on Cygwin, on an X86_64 machine running Windows 10.</p> <p>I've just updated my Cygwin distribution, and installed python. Now, using pip, some packages install fine, like <code>argparse</code>, but some just don't. The errors seem to be:</p> <ul> <li><code>UserWarning: git archive did not support describe output</code></li> <li><code>UserWarning: unprocessed git archival found (no export subst applied)</code></li> </ul> <p>see a full trace below.</p> <p>Why is this happening? And how can I fixed/circumvent this?</p> <pre><code>$ pip install ninja Collecting ninja Using cached ninja-1.11.1.1.tar.gz (132 kB) Installing build dependencies ... done Getting requirements to build wheel ... done Preparing metadata (pyproject.toml) ... done Building wheels for collected packages: ninja Building wheel for ninja (pyproject.toml) ... error error: subprocess-exited-with-error × Building wheel for ninja (pyproject.toml) did not run successfully. │ exit code: 1 ╰─&gt; [13 lines of output] /tmp/pip-build-env-8cad4e54/overlay/lib/python3.9/site-packages/setuptools_scm/git.py:312: UserWarning: git archive did not support describe output warnings.warn(&quot;git archive did not support describe output&quot;) /tmp/pip-build-env-8cad4e54/overlay/lib/python3.9/site-packages/setuptools_scm/git.py:331: UserWarning: unprocessed git archival found (no export subst applied) warnings.warn(&quot;unprocessed git archival found (no export subst applied)&quot;) Traceback (most recent call last): File &quot;/tmp/pip-build-env-8cad4e54/overlay/lib/python3.9/site-packages/skbuild/setuptools_wrap.py&quot;, line 639, in setup cmkr = cmaker.CMaker(cmake_executable) File &quot;/tmp/pip-build-env-8cad4e54/overlay/lib/python3.9/site-packages/skbuild/cmaker.py&quot;, line 145, in __init__ self.cmake_version = get_cmake_version(self.cmake_executable) File &quot;/tmp/pip-build-env-8cad4e54/overlay/lib/python3.9/site-packages/skbuild/cmaker.py&quot;, line 102, in get_cmake_version raise SKBuildError(msg) from err Problem with the CMake installation, aborting build. CMake executable is cmake [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. ERROR: Failed building wheel for ninja Failed to build ninja ERROR: ERROR: Failed to build installable wheels for some pyproject.toml based projects (ninja) </code></pre> <p>More info about my setup:</p> <ul> <li>pip 24.2</li> <li>Python 3.9.16</li> <li>additional info will be provided upon request...</li> </ul> <p>Related questions:</p> <ul> <li><p><a href="https://stackoverflow.com/q/77286013/1593077">I can&#39;t install any libraries, it gives me an error saying subprocess-exited-with-error</a></p> <p>where the solutio suggeted is</p> <blockquote> <p>setup the full python version</p> <p>$ sudo apt install python3-full</p> </blockquote> <p>... but there's no such Cgwin package. I have installed some more Python packages I could think might br related, but to no avail.</p> </li> </ul>
<python><pip><cygwin><package-management><git-archive>
2024-09-22 14:26:41
1
137,004
einpoklum
79,011,778
9,030,200
How to reply emails with original content preserved using smtplib and imaplib
<p>I want to use Python's smtplib and imaplib to implement reading emails (such as Gmail, Exchange) and replying to the original email. What I want to do is read an email, add a new message to the original email while preserving the original message, just like using Gmail's reply function. The new message might be in HTML format. I've searched through smtplib and imaplib documentation but haven't found any similar reply functionality. I can send or reply to emails, but I can only send new messages without being able to retain the original email's content.</p>
<python><html><smtplib><imaplib><reply>
2024-09-22 13:53:03
0
567
黃郁暉
79,011,631
11,165,214
How to change the resolution of a OpenStreetMaps figure?
<p>For a little design project, I want to use some geo data from OpenStreetMaps.</p> <p>Let's use the data from the little german coast village of Greetsiel for illustration of the issue.</p> <p>I use the following code snippet:</p> <pre><code>import osmnx as ox import matplotlib.pyplot as plt place_name = &quot;Greetsiel, Germany&quot; # List key-value pairs for tags tags_buildings = {'building': True} plt.rcParams[&quot;figure.dpi&quot;] = 100 buildings = ox.features_from_place(place_name, tags_buildings) buildings.plot(figsize=(120,180), markersize=0.01, linewidth=0.01) plt.savefig(r'C:\Users\Lepakk\Desktop\buildings.png', dpi=100) </code></pre> <p>The figure that is opened in Spyder looks like this:</p> <p><a href="https://i.sstatic.net/0kfmv6tC.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/0kfmv6tC.png" alt="Whole figure view in Spyder" /></a></p> <p>Where the village is in the lower right corner, let's focus on a uniquely shaped building in the center of the village.</p> <p><a href="https://i.sstatic.net/oT9ktDGA.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/oT9ktDGA.png" alt="View of detail in Spyder" /></a></p> <p>If i open the saved image and zoom into the respective position, it looks like this:</p> <p><a href="https://i.sstatic.net/51tPmTPH.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/51tPmTPH.png" alt="Saved figure at 100 dpi" /></a></p> <p>Now I was thinking, the bad resolution might be due to 100 dpi being just not enough. Let's change this value to</p> <pre><code>plt.rcParams[&quot;figure.dpi&quot;] = 1000 buildings = ox.features_from_place(place_name, tags_buildings) buildings.plot(figsize=(120,180), markersize=0.01, linewidth=0.01) plt.savefig(r'C:\Users\Lepakk\Desktop\buildings.png', dpi=1000) </code></pre> <p>The resolution should be ten times more now. However, the figure looks unchanged:</p> <p><a href="https://i.sstatic.net/AxBIIW8J.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/AxBIIW8J.png" alt="Saved figure at 1000 dpi" /></a></p> <p>So, how can I change the resolution of the saved image file? Thank you in advance!</p>
<python><matplotlib><openstreetmap><geopandas><osmnx>
2024-09-22 12:36:58
1
449
Lepakk
79,011,622
1,403,470
How to prevent Pelican from copying Markdown source files into output folder?
<p>I am converting my Jekyll blog to Pelican. The directory structure of the source <code>content</code> folder uses <code>YYYY/MM/DD/slug.md</code> to organize blog posts and stores static files in <code>files/YYYY/filename.ext</code>. Static pages are in <code>pages/filename.md</code>:</p> <pre><code>content |-- 2023 | |-- 01 | | |-- 01 | | | |-- plans-for-the-year.md | | | +-- sdxjs-introduction.md | | |-- 02 | | | +-- sdxjs-systems-programming.md | | |-- 03 | | | +-- sdxjs-async-programming.md | | |-- 04 | | | +-- sdxjs-unit-test.md |-- 2024 | |-- 01 | | |-- 03 | | | +-- the-other-examples.md |-- files | |-- 2023 | | |-- awesome-robot.png | | |-- blackberry-pie.jpg +-- pages +-- about.md </code></pre> <p>I have added the following to my <code>pelicanconf.py</code> settings file:</p> <pre><code>OUTPUT_SOURCES = False SLUGIFY_SOURCE = &quot;basename&quot; ARTICLE_URL = &quot;{date:%Y}/{date:%m}/{date:%d}/{slug}/&quot; ARTICLE_SAVE_AS = &quot;{date:%Y}/{date:%m}/{date:%d}/{slug}/index.html&quot; PAGE_URL = &quot;{slug}/&quot; PAGE_SAVE_AS = &quot;{slug}/index.html&quot; </code></pre> <p>The HTML files are generated as I want and where I want, but the source Markdown files are copied to the output directory as well, despite explicitly setting <code>OUTPUT_SOURCES</code> to <code>False</code> as suggested in <a href="https://docs.getpelican.com/en/stable/settings.html" rel="nofollow noreferrer">the docs</a>. I could add another line to <code>Makefile</code> to delete these unwanted files after the build, but how can I prevent them being copied in the first place?</p> <ul> <li>Pelican: 4.10.0</li> <li>Python: 3.12.6</li> </ul>
<python><pelican>
2024-09-22 12:32:55
1
1,403
Greg Wilson
79,011,621
184,379
Sqlite gives a value which I cannot recreate
<p>Using django: here is some values and the query:</p> <pre><code> max_played, avg_days_last_played = get_next_song_priority_values() # Calculate time since played using raw SQL time_since_played_expr = RawSQL(&quot;(julianday('now') - julianday(main_song.played_at))&quot;, []) query = Song.objects # Annotate priority songs_with_priority = query.annotate( time_since_played=ExpressionWrapper(time_since_played_expr, output_field=FloatField()), priority=( F('rating') - (F('count_played') / Value(max_played)) + (F('time_since_played') / Value(avg_days_last_played)) ), ).order_by('-priority') </code></pre> <p>my logging:</p> <pre><code> logger.info(f'Next Song: {next_song}') calculated_priority = ( next_song.rating - (next_song.count_played / max_played) + (next_song.time_since_played / avg_days_last_played) ) logger.info(f'Next Song: priority {next_song.priority:.2f} vs calc {calculated_priority:.2f}') logger.info(f'Next Song: rating {next_song.rating:.2f}') playd = next_song.count_played / max_played logger.info(f'Next Song: played {playd:.2f} ({next_song.count_played} / {max_played})') tspd = next_song.time_since_played / avg_days_last_played logger.info( f'Next Song: days {tspd:.2f} ({next_song.time_since_played} / {avg_days_last_played})' ) </code></pre> <p>and I get:</p> <pre><code>INFO Next Song: &lt;Song-1489 End of the World Cold&gt; INFO Next Song: priority 2.73 vs calc 2.56 INFO Next Song: rating 0.50 INFO Next Song: played 0.17 (1 / 6) INFO Next Song: days 2.23 (4.043296354357153 / 1.8125720233656466) </code></pre> <p>So my calculated value is lower. All the values are there: the rating of 0.5 is solid, the play counts if 1 vs 6 is solid, the time since is used from the result <code>next_song.time_since_played</code>.</p> <p>I'm using the same values sqlite should be using, but my calc is different.</p>
<python><django><sqlite>
2024-09-22 12:32:28
1
17,352
Tjorriemorrie
79,011,599
395,857
How to fix "Invalid value for purpose." error when using Azure OpenAI GPT 4o mini batch?
<p>I try to use Azure OpenAI GPT 4o mini batch. I first need to create the batch. I ran:</p> <pre><code>import os from openai import AzureOpenAI client = AzureOpenAI( api_key=&quot;[insert Azure OpenAI API key here]&quot;, api_version=&quot;2023-07-01-preview&quot;, azure_endpoint=&quot;https://[insert Azure OpenAI API enddpoint here].openai.azure.com/&quot;, ) file = client.files.create( file=open(&quot;./dummy.jsonl&quot;, &quot;rb&quot;), purpose=&quot;batch&quot; ) file_id = file.id </code></pre> <p>with <code>dummy.jsonl</code> containing:</p> <pre><code>{ &quot;custom_id&quot;: &quot;request-1&quot;, &quot;method&quot;: &quot;POST&quot;, &quot;url&quot;: &quot;/v1/chat/completions&quot;, &quot;body&quot;: { &quot;model&quot;: &quot;gpt-3.5-turbo-0125&quot;, &quot;messages&quot;: [ { &quot;role&quot;: &quot;system&quot;, &quot;content&quot;: &quot;You are a helpful assistant.&quot; }, { &quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;Hello world!&quot; } ], &quot;max_tokens&quot;: 1000 } } </code></pre> <p>I get the error:</p> <pre><code>BadRequestError: Error code: 400 - {'error': {'code': 'invalidPayload', 'message': 'Invalid value for purpose.'}} </code></pre> <p>How to fix that error?</p>
<python><azure><batch-processing><azure-openai><gpt-4>
2024-09-22 12:13:19
1
84,585
Franck Dernoncourt
79,011,417
4,412,929
Null values in log file from Python logging module when used with Dask
<p>I have been trying to setup logging using the <em>logging</em> module in a Python script, and I have got it working properly. It can now log to both the console and a log file. But if fails when I setup a Dask cluster. The first log message is now replaced with invalid/null values in the log file, while the console output is fine.</p> <p>A minimal working example is given below:</p> <pre><code>import logging from dask.distributed import LocalCluster as Cluster logfile_name='test.log' logger=logging.getLogger(__name__) logger.setLevel('DEBUG') log_format=logging.Formatter( '%(asctime)s %(levelname)s: %(message)s', datefmt='%Y-%m-%d %H:%M:%S', ) console_handler=logging.StreamHandler() console_handler.setLevel('DEBUG') console_handler.setFormatter( log_format) file_handler=logging.FileHandler( logfile_name, mode='w') file_handler.setLevel('DEBUG') file_handler.setFormatter(log_format) logger.addHandler(file_handler) logger.addHandler(console_handler) if __name__=='__main__': logger.info('First log message') cluster=Cluster( name='test', n_workers=1, threads_per_worker=1, memory_limit='1GiB', dashboard_address=':8000', ) logger.info('Second log message') logger.info('Third log message') logger.info('Fourth log message') logger.info('Fifth log message') cluster.close() logging.shutdown() </code></pre> <p>The console log:</p> <pre><code>2024-09-22 15:28:30 INFO: First log message 2024-09-22 15:28:31 INFO: Second log message 2024-09-22 15:28:31 INFO: Third log message 2024-09-22 15:28:31 INFO: Fourth log message 2024-09-22 15:28:31 INFO: Fifth log message </code></pre> <p>And the log file contents (copy-pasted from Gedit):</p> <pre><code>\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\002024-09-22 15:41:46 INFO: Second log message 2024-09-22 15:41:46 INFO: Third log message 2024-09-22 15:41:46 INFO: Fourth log message 2024-09-22 15:41:46 INFO: Fifth log message </code></pre> <p>Notice the invalid/null values in the first line, and the first log message is missing.</p> <p>After some digging around, I found out that if I remove the Dask cluster code, everything is fine. What is strange is that if I change the mode to <em>append</em> in <em>FileHandler</em>, the issue goes away without removing the Dask cluster initialisation.</p> <p>How do I fix this issue without removing the Dask code or changing the file open mode?</p>
<python><character-encoding><dask><dask-distributed><python-logging>
2024-09-22 10:28:02
0
363
RogUE
79,011,352
3,357,352
determine which system modules were loaded
<p>I'm trying to determine which python system modules are loaded:</p> <pre class="lang-py prettyprint-override"><code>In [1]: import sys In [2]: l = sorted(list(sys.modules.keys())) In [3]: 'json' in l Out[3]: True </code></pre> <p>According to <a href="https://docs.python.org/3/library/sys.html#sys.modules" rel="nofollow noreferrer">the docs</a>:</p> <blockquote> <p>This is a dictionary that maps module names to modules which have already been loaded.</p> </blockquote> <p>So I thought that <em>maybe</em> <code>sys</code> imports <code>json</code>, but this turns out wrong:</p> <pre class="lang-py prettyprint-override"><code>In [4]: json.dumps({'oren': 12}) --------------------------------------------------------------------------- NameError Traceback (most recent call last) Cell In[4], line 1 ----&gt; 1 json.dumps({'oren': 12}) NameError: name 'json' is not defined </code></pre> <p>What am I missing?</p>
<python><module>
2024-09-22 09:59:00
1
7,270
OrenIshShalom
79,011,203
3,203,158
PySpark: Throwing error 'Column' object is not callable while using .count()
<p>I'm working with a PySpark DataFrame and trying to count the number of null values in each column. I tried the following expression:</p> <pre><code>[col(c).isNull().count() for c in df.columns] </code></pre> <p>throws error:</p> <pre><code>----&gt; 2 [col(c).isNull().count() for c in df.columns] TypeError: 'Column' object is not callable </code></pre> <p>On the other hand, this expression works without any issue:</p> <pre><code>[df.filter(col(c).isNull()).count() for c in df.columns] </code></pre> <p>Output:</p> <pre><code>[0, 0, 0, 0, 0, 0, 109, 109, 0, 0, 0, 0, 0] </code></pre> <p>I’m confused about why the first expression fails while the second one works. Could someone explain the difference between the two and why the error occurs in the first case?</p>
<python><dataframe><pyspark><apache-spark-sql>
2024-09-22 08:23:31
1
922
aroyc
79,011,125
4,555,765
Assignin lists as elements of CUDF DataFrame
<p>While using Pandas, I can add lists as elements without issues, as in</p> <pre><code>import pandas as pd A = {&quot;cls&quot;: &quot;A&quot;} B = {&quot;cls&quot;: &quot;B&quot;} C = {&quot;cls&quot;: [&quot;A&quot;, &quot;B&quot;]} df = pd.DataFrame([A,B,C]) type(df.iloc[2][&quot;cls&quot;]) # Returns `list` </code></pre> <p>But <code>cudf.DataFrame</code> do not accept a List. As we can see here:</p> <pre><code>import cudf cu_df = cudf.DataFrame([A, B, C]) </code></pre> <p>Fails with <code>ArrowTypeError: Expected bytes, got a 'list' object</code></p> <p>We can see if we do not add <code>C</code>, it work.</p> <pre><code>import cudf cu_df = cudf.DataFrame([A, B]) </code></pre> <p>(no error)</p> <p>Trying to convert from a regular pandas dataframe, also do not works</p> <pre><code>cu_df = cudf.DataFrame(df) </code></pre> <p>(fails with the same <code>ArrowTypeError</code>)</p> <p>Any ideas in how to circumvent this?</p>
<python><pandas><dataframe><cudf>
2024-09-22 07:47:06
1
1,211
Lin
79,010,931
8,741,108
How to trigger a POST request API to add a record in a SQLite database table using FastAPI and HTML forms using Jinja2?
<p>I am trying to submit a HTML form from the browser to create a new user in a SQLite database table. Clicking on the Submit button triggers a POST request using FastAPI and Sqlalchemy 2.0. The API works perfectly when executed from the Swagger UI. But it does not work when triggered from an actual HTML form, returning a <code>422 Unprocessable Entity</code> error. Below is the code I have used for the same along with the error I am seeing on the browser.</p> <p>I can see that the error is pointing to an <code>id</code> which does not exist in my Pydantic model and also in my html form. Any help on how to handle this error would be greatly appreciated.</p> <p>I am using:</p> <ul> <li>Python 3.12.6 (x64) on Windows 11</li> <li>Sqlalchemy 2.0.34</li> <li>Pydantic 2.9.1</li> </ul> <p><em><strong>core/database.py</strong></em></p> <pre><code>from os import getenv from dotenv import load_dotenv from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker, DeclarativeBase load_dotenv() # Needed to load full path of the .env file engine = create_engine( getenv(&quot;DATABASE_URL&quot;), connect_args={&quot;check_same_thread&quot;: False} ) SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) # Database dependency async def get_db(): db = SessionLocal() try: yield db finally: db.close() # declarative base class class Base(DeclarativeBase): pass </code></pre> <p><em><strong>users/models.py</strong></em></p> <pre><code>from datetime import datetime, timezone from sqlalchemy import String, Enum from sqlalchemy.orm import Mapped, mapped_column from typing import Optional, List from enum import Enum as pyEnum from .database import Base class Gender(str, pyEnum): default = &quot;&quot; male = &quot;M&quot; female = &quot;F&quot; def time_now(): return datetime.now(timezone.utc).strftime(&quot;%b %d, %Y %I:%M:%S %p&quot;) class AbstractBase(Base): __abstract__ = True id: Mapped[Optional[int]] = mapped_column(primary_key=True, index=True) created_by: Mapped[Optional[str]] = mapped_column(String(50), nullable=True, default=&quot;&quot;) updated_by: Mapped[Optional[str]] = mapped_column(String(50), nullable=True, default=&quot;&quot;) created: Mapped[Optional[str]] = mapped_column(nullable=True, default=time_now) updated: Mapped[Optional[str]] = mapped_column(nullable=True, default=time_now, onupdate=time_now) class User(AbstractBase): __tablename__ = &quot;users&quot; first_name: Mapped[str] = mapped_column(String(25), nullable=False) last_name: Mapped[Optional[str]] = mapped_column(String(25), default=&quot;&quot;) gender: Mapped[Optional[Gender]] = mapped_column(Enum(Gender), nullable=False, default=Gender.default.value) email: Mapped[str] = mapped_column(String(50), unique=True, nullable=False, index=True) </code></pre> <p><em><strong>users/schemas.py</strong></em></p> <pre><code>from typing import Optional from pydantic import BaseModel, EmailStr, Field from .models import Gender class UserCreate(BaseModel): first_name: str = Field(min_length=1, max_length=25) last_name: Optional[str] = Field(min_length=0, max_length=25, default=&quot;&quot;) gender: Optional[Gender] = Gender.default.value email: EmailStr = Field(min_length=7, max_length=50) class UserUpdate(UserCreate): pass class UserResponse(UserUpdate): id: Optional[int] created_by: Optional[EmailStr] = Field(min_length=7, max_length=50) updated_by: Optional[EmailStr] = Field(min_length=7, max_length=50) created: Optional[str] updated: Optional[str] class Config: from_attributes = True </code></pre> <p><em><strong>users/routers.py</strong></em></p> <pre><code>from fastapi import APIRouter, Depends, HTTPException, Request, Form from fastapi.templating import Jinja2Templates from fastapi.responses import HTMLResponse from sqlalchemy.orm import Session from core.database import get_db from users.models import User from users.schemas import UserCreate, UserUpdate, UserResponse templates = Jinja2Templates(directory=&quot;templates&quot;) users_router = APIRouter() # API to redirect user to the Register page @users_router.get(&quot;/register&quot;, response_class=HTMLResponse, status_code=200) async def redirect_user(request: Request): return templates.TemplateResponse( name=&quot;create_user.html&quot;, context={ &quot;request&quot;: request, &quot;title&quot;: &quot;FastAPI - Create User&quot;, &quot;navbar&quot;: &quot;create_user&quot; } ) # API to create new user @users_router.post(&quot;/create&quot;, response_model=UserCreate, response_class=HTMLResponse, status_code=201) async def create_user(request: Request, user: UserCreate=Form(), db: Session = Depends(get_db)): if db.query(User).filter(User.email == user.email).first(): raise HTTPException( status_code=403, detail=f&quot;Email '{user.email}' already exists. Please try with another email.&quot; ) obj = User( first_name = user.first_name, last_name = user.last_name, gender = user.gender.value, email = user.email.lower(), created_by = user.email.lower(), updated_by = user.email.lower() ) db.add(obj) db.commit() db.refresh(obj) return ( templates.TemplateResponse( name=&quot;create_user.html&quot;, context={ &quot;request&quot;: request, &quot;item&quot;: obj, &quot;title&quot;: &quot;FastAPI - Create User&quot;, &quot;navbar&quot;: &quot;create_user&quot; } ) ) </code></pre> <p><em><strong>main.py</strong></em></p> <pre><code>from fastapi import FastAPI, Request from fastapi.middleware.cors import CORSMiddleware from fastapi.templating import Jinja2Templates from core.database import Base, engine from users.routers import users_router templates = Jinja2Templates(directory=&quot;templates&quot;) # Create FastAPI instance app = FastAPI() app.include_router(users_router, prefix='/users', tags = ['Users']) # Specify URLS that are allowed to connect to the APIs origins = [ &quot;http://localhost&quot;, &quot;http://127.0.0.1&quot;, &quot;http://localhost:8000&quot;, &quot;http://127.0.0.1:8000&quot; ] app.add_middleware( CORSMiddleware, allow_origins=origins, allow_credentials=True, allow_methods=[&quot;*&quot;], allow_headers=[&quot;*&quot;], ) # Create tables in database Base.metadata.create_all(bind=engine) </code></pre> <p><em><strong>templates/create_user.py</strong></em></p> <pre><code>{% extends 'base.html' %} {% block title %} {{ title }} {% endblock title %} {% block content %} &lt;form method=&quot;POST&quot; action=&quot;/create&quot;&gt; &lt;div class=&quot;mb-3&quot;&gt; &lt;label for=&quot;first_name&quot; class=&quot;form-label&quot;&gt;First Name&lt;/label&gt; &lt;input type=&quot;text&quot; class=&quot;form-control&quot; id=&quot;first_name&quot; name=&quot;first_name&quot;&gt; &lt;/div&gt; &lt;div class=&quot;mb-3&quot;&gt; &lt;label for=&quot;last_name&quot; class=&quot;form-label&quot;&gt;Last Name&lt;/label&gt; &lt;input type=&quot;text&quot; class=&quot;form-control&quot; id=&quot;last_name&quot; name=&quot;last_name&quot;&gt; &lt;/div&gt; &lt;div class=&quot;mb-3&quot;&gt; &lt;label for=&quot;email&quot; class=&quot;form-label&quot;&gt;Email&lt;/label&gt; &lt;input type=&quot;email&quot; class=&quot;form-control&quot; id=&quot;email&quot; name=&quot;email&quot; aria-describedby=&quot;emailHelp&quot;&gt; &lt;/div&gt; &lt;a href=&quot;{{ url_for('create_user') }}&quot; type=&quot;submit&quot; class=&quot;btn btn-outline-success float-end&quot;&gt;Submit&lt;/a&gt; &lt;/form&gt; {% endblock content %} </code></pre> <p><em><strong>Error Message on Browser:</strong></em></p> <pre><code>{ &quot;detail&quot;: [ { &quot;type&quot;: &quot;int_parsing&quot;, &quot;loc&quot;: [ &quot;path&quot;, &quot;id&quot; ], &quot;msg&quot;: &quot;Input should be a valid integer, unable to parse string as an integer&quot;, &quot;input&quot;: &quot;create&quot; } ] } </code></pre>
<python><sqlite><sqlalchemy><jinja2><fastapi>
2024-09-22 05:23:58
1
1,723
Code_Sipra
79,010,838
4,555,765
Neo4j results to JSON in Python
<p>While python Neo4j library, with bolt driver, when executing queries by <code>session.run(query)</code> I receive a result object that can be manipulated perfectly. In the other hand Neo4j browser interface, when executing a query, in table tab, it returns a string formatted as a JSON.</p> <p>Is there any function in neo4j python library that converts the results python object to a JSON string to the table in web interface?</p> <p>Using <code>.data()</code> method over the records returns me a simple json instead a more complete one from web interface.</p> <p>For example from Python <code>.data()</code> I receive the following dictionary (that can be later converted to json)</p> <pre><code>{'n': {'name': 'dog'}} </code></pre> <p>While the same result in web interface returns the following string</p> <pre><code>{ &quot;identity&quot;: 19, &quot;labels&quot;: [ &quot;NOUN&quot; ], &quot;properties&quot;: { &quot;name&quot;: &quot;dog&quot; }, &quot;elementId&quot;: &quot;4:a94a1b6d-fb11-4844-a6e9-31362e907dd0:19&quot; } </code></pre> <p>As we can see the <code>.data()</code> from python loses a lot of information as labels and IDs.</p>
<python><neo4j><bolt>
2024-09-22 03:43:47
1
1,211
Lin
79,010,712
13,634,560
advanced multi conditional list comprehension
<p>I am new to Python and would like to assign a value based on mathematical operations, eg &quot;right&quot; if &gt;, &quot;left&quot; if &lt;, &quot;equal&quot; if ==, within a list comprehension.</p> <p>I have tried the below, but it throws an error. Can multiple conditions be specified in a single list comprehension in this way, where each &quot;elif&quot; generates a different output, or will I need to use a loop?</p> <p>Fully reproduceable example:</p> <pre><code>from sklearn.datasets import load_iris bunch = load_iris(as_frame=True) df = bunch.data.reset_index().rename(columns={&quot;index&quot;: &quot;id&quot;}).merge(bunch.target.reset_index().rename(columns={&quot;index&quot;: &quot;id&quot;})).drop([&quot;id&quot;], axis=1) # question is in last row, &quot;skew&quot; datasummary_dct = { &quot;50%&quot;: [df[col].median().round(2) if any(t in str(df[col].dtype) for t in (&quot;float&quot;, &quot;int&quot;, &quot;time&quot;)) else &quot; &quot; for col in df.columns], &quot;mean&quot;: [df[col].mean().round(2) if any(t in str(df[col].dtype) for t in (&quot;float&quot;, &quot;int&quot;, &quot;time&quot;)) else &quot; &quot; for col in df.columns], &quot;skew&quot;: [&quot;left&quot; if df[col].median() &gt; df[col].mean() else &quot;right&quot; if df[col].median() &lt; df[col].mean() else &quot;equal&quot; if df[col].median()==df[col].mean() if any(t in str(df[col].dtype) for t in (&quot;float&quot;, &quot;int&quot;, &quot;time&quot;)) else &quot; &quot; for col in df.columns], } </code></pre> <p>again I am still fairly new to programming; apologies if I do not immediately understand the solution. any guidance is appreciated!</p>
<python><pandas>
2024-09-22 01:34:30
2
341
plotmaster473
79,010,633
1,332,263
How to Change Multiple Values in a json file
<p>I want to change the values in a json file. The json file contents are commented out. I want to change the values individually with having to write to the file separately for each value.</p> <pre><code>import json &quot;&quot;&quot; { &quot;keys&quot;: { &quot;developer&quot;: {}, &quot;personal&quot;: { &quot;api_key&quot;: &quot;1234567890&quot;, &quot;client_id&quot;: &quot;9876543210&quot;, &quot;client_secret&quot;: &quot;ncjegcbcncwkwdcowdch&quot; } } } &quot;&quot;&quot; json_file = &quot;/home/api_keys.json&quot; with open(json_file) as json_data: data = json.load(json_data) with open(json_file, &quot;w&quot;) as jsonFile: json.dump(data, jsonFile) data[&quot;keys&quot;][&quot;personal&quot;][&quot;api_key&quot;] = &quot;9999&quot; with open(json_file, &quot;w&quot;) as jsonFile: json.dump(data, jsonFile) data[&quot;keys&quot;][&quot;personal&quot;][&quot;client_id&quot;] = &quot;000000000000&quot; with open(json_file, &quot;w&quot;) as jsonFile: json.dump(data, jsonFile) data[&quot;keys&quot;][&quot;personal&quot;][&quot;client_secret&quot;] = &quot;hyfgdjocoduxbxlwowichcnckw&quot; with open(json_file) as json_data: data = json.load(json_data) api_key = data[&quot;keys&quot;][&quot;personal&quot;][&quot;api_key&quot;] client_id = data[&quot;keys&quot;][&quot;personal&quot;][&quot;client_id&quot;] client_secret = data[&quot;keys&quot;][&quot;personal&quot;][&quot;client_secret&quot;] </code></pre>
<python><json>
2024-09-21 23:53:40
1
417
bob_the_bob
79,010,629
22,407,544
Running `collecstatic` returns [Errno 13] Permission denied in docker compose
<p>I run my django app in Docker. I recently tried running <code>collecstatic</code> and instead was given this error code:</p> <pre><code>&gt;docker-compose exec web python manage.py collectstatic </code></pre> <pre><code>Traceback (most recent call last): File &quot;/code/manage.py&quot;, line 22, in &lt;module&gt; main() File &quot;/code/manage.py&quot;, line 18, in main execute_from_command_line(sys.argv) File &quot;/usr/local/lib/python3.11/site-packages/django/core/management/__init__.py&quot;, line 442, in execute_from_command_line utility.execute() ... PermissionError: [Errno 13] Permission denied: '/code/static/admin/img/tooltag-arrowright.bbfb788a849e.svg.gz' </code></pre> <p>I added a USER at the end of my Dockerfile so that the USER isn't root which I know is a security vulnerability. Here is my Dockerfile:</p> <pre><code># Pull base image FROM python:3.11.4-slim-bullseye # Set environment variables ENV PIP_NO_CACHE_DIR off ENV PIP_DISABLE_PIP_VERSION_CHECK 1 ENV PYTHONUNBUFFERED 1 ENV PYTHONDONTWRITEBYTECODE 1 ENV COLUMNS 80 #install Debian and other dependencies that are required to run python apps(eg. git, python-magic). RUN apt-get update \ &amp;&amp; apt-get install -y --force-yes python3-pip ffmpeg git libmagic-dev libpq-dev gcc \ &amp;&amp; rm -rf /var/lib/apt/lists/* # Set working directory for Docker image WORKDIR /code/ # Install dependencies COPY requirements.txt . RUN pip install -r requirements.txt # Copy project COPY . . # Create a custom non-root user RUN useradd -m example-user # Grant necessary permissions to write directories and to user 'example-user' RUN mkdir -p /code/media /code/static &amp;&amp; \ chown -R example-user:example-user 1. List item /code/media /code/static # Change permissions of /code directory RUN chmod -R 755 /code # Switch to the non-root user. All this avoids running Celery with root/superuser priviledges which is a security risk USER example-user </code></pre> <p>And my docker-compose-yml file:</p> <pre><code>#version: &quot;3.9&quot; services: web: build: . #command: python /code/manage.py runserver 0.0.0.0:8000 command: gunicorn mysite.wsgi -b 0.0.0.0:8000 --reload volumes: - .:/code ports: - 8000:8000 depends_on: - db - redis - celery environment: - &quot;DJANGO_SECRET_KEY=scret_key&quot; - &quot;DJANGO_DEBUG=True&quot; - &quot;DJANGO_SECURE_SSL_REDIRECT=False&quot; - &quot;DJANGO_SECURE_HSTS_SECONDS=0&quot; - &quot;DJANGO_SECURE_HSTS_INCLUDE_SUBDOMAINS=False&quot; - &quot;DJANGO_SECURE_HSTS_PRELOAD=False&quot; - &quot;DJANGO_SESSION_COOKIE_SECURE=False&quot; # new - &quot;ACCESS_KEY_ID=scret_id&quot; - &quot;SECRET_ACCESS_KEY=scret_key&quot; - &quot;STORAGE_BUCKET_NAME=bucket&quot; - &quot;S3_CUSTOM_DOMAIN=domain&quot; - CELERY_BROKER_URL=redis://redis:6379/0 - CELERY_RESULT_BACKEND=redis://redis:6379/0 user: example-user db: image: postgres:13 volumes: - postgres_data:/var/lib/postgresql/data/ environment: - &quot;POSTGRES_HOST_AUTH_METHOD=trust&quot; redis: image: redis:6 ports: - 6379:6379 celery: build: . command: celery -A mysite worker --loglevel=info volumes: - .:/code depends_on: - redis - db environment: - &quot;DJANGO_SECRET_KEY=scret_key&quot; - &quot;DJANGO_DEBUG=True&quot; - &quot;DJANGO_SECURE_SSL_REDIRECT=False&quot; - &quot;DJANGO_SECURE_HSTS_SECONDS=0&quot; - &quot;DJANGO_SECURE_HSTS_INCLUDE_SUBDOMAINS=False&quot; - &quot;DJANGO_SECURE_HSTS_PRELOAD=False&quot; - &quot;DJANGO_SESSION_COOKIE_SECURE=False&quot; # new - &quot;ACCESS_KEY_ID=scret_id&quot; - &quot;SECRET_ACCESS_KEY=scret_key&quot; - &quot;STORAGE_BUCKET_NAME=name&quot; - &quot;S3_CUSTOM_DOMAIN=domain&quot; - CELERY_BROKER_URL=redis://redis:6379/0 - CELERY_RESULT_BACKEND=redis://redis:6379/0 user: example-user volumes: postgres_data: </code></pre> <p>I also added <code>chmod -R 755 /code/media /code/static</code> however it still did not work and the results are the same. When I run <code> docker-compose exec web ls -l /code/static</code> the results indicate that all files/folders are being run as root execpt staticfiles.json:</p> <pre><code>total 16 drwxrwxrwx 1 root root 4096 Apr 5 05:42 admin drwxrwxrwx 1 root root 4096 Sep 21 22:36 css drwxrwxrwx 1 root root 4096 Sep 21 22:36 human drwxrwxrwx 1 root root 4096 Sep 18 18:42 img -rw-r--r-- 1 user-mani user-mani 13091 Sep 21 22:36 staticfiles.json drwxrwxrwx 1 root root 4096 Sep 21 22:36 transcribe </code></pre>
<python><django><docker><docker-compose>
2024-09-21 23:49:43
0
359
tthheemmaannii
79,010,413
6,136,013
Annotate a constructor that delegates to another function
<p>I have a Python library that encapsulates an external c++ library that exposes its objects via handles. I have a root class</p> <pre><code>class ABObj: def __init__(self, *args, **kwargs): if is_handle(args[0]): self.handle = args[0] else: self.handle = self._make_obj(*args, **kwargs) </code></pre> <p>The idea is the constructor can either capture an external handle or create a new object. The latter task is delegated to the subclasses of <code>ABObj</code>.</p> <p>The problem with this setup is the user gets no parameter hints when instantiating a subclass of <code>ABObj</code>. The autocompletion tool (like Pylance in VS Code) has no idea that the constructor signature is either a single handle or it matches the subclass's <code>_make_obj</code> method. Is there a way to accomplish that?</p>
<python><python-typing>
2024-09-21 20:29:14
0
681
BlindDriver
79,010,412
20,591,261
Efficiently Applying Multiple Operations to a Polars DataFrame Using a Custom Function
<p>I'm working with a Polars DataFrame and trying to clean up a column by applying multiple string operations. The first operation I need to do is a <code>str.replace()</code> to fix some inconsistencies in the string, and then I want to extract several values into new columns.</p> <p>My current approach:</p> <pre><code>df = pl.DataFrame( { &quot;engine&quot;: [&quot;172.0HP 1.6L 4 Cylinder Engine Gasoline Fuel&quot;, &quot;3.0 Liter Twin Turbo&quot;, &quot;429.0HP 5.0L 8 Cylinder Engine Gasoline Fuel&quot;], } ) ( df .with_columns( pl.col(&quot;engine&quot;).str.replace(r'\sLiter', &quot;L&quot;) ) .with_columns( pl.col(&quot;engine&quot;).str.extract(r'(\d+)\.\d+HP',1).alias(&quot;HP&quot;), pl.col(&quot;engine&quot;).str.extract(r'(\d+\.\d+)L',1).alias(&quot;Displacement&quot;), pl.col(&quot;engine&quot;).str.extract(r'(\d+)\sCylinder',1).alias(&quot;Cylinder&quot;), ) ) </code></pre> <p>Since I'm going to apply multiple operations over the main dataframe, I want to create a function to make this code more reusable and cleaner. This is the function-based approach I've come up with:</p> <p>Approach with function:</p> <pre><code>def get_engine() -&gt; pl.Expr: return ( pl.col(&quot;engine&quot;).str.extract(r'(\d+)\.\d+HP',1).alias(&quot;HP&quot;), pl.col(&quot;engine&quot;).str.extract(r'(\d+\.\d+)L',1).alias(&quot;Displacement&quot;), pl.col(&quot;engine&quot;).str.extract(r'(\d+)\sCylinder',1).alias(&quot;Cylinder&quot;), pl.col(&quot;engine&quot;).str.contains(&quot;Electric&quot;).alias(&quot;Electric&quot;) ) ( df .with_columns( pl.col(&quot;engine&quot;).str.replace(r'\sLiter', &quot;L&quot;) ) .with_columns( get_engine() ) ) </code></pre> <p>Is there a better or more efficient way to combine these operations while keeping the code clean?</p> <p>EDIT1: Just edited the approach with fuction as @DeanMacGregor suggeested</p>
<python><python-polars>
2024-09-21 20:27:52
1
1,195
Simon
79,010,316
344,669
How do I map a column to create an autoincrement primary key?
<p>My SQLAlchemy 2.0 mapped column with an SQLite database is creating a primary key column due to which I'm not able to insert.</p> <p>Mode class:</p> <pre><code>import datetime from typing import Optional from sqlalchemy import String, TIMESTAMP, Integer from sqlalchemy import func from sqlalchemy.dialects import postgresql, sqlite from sqlalchemy.orm import DeclarativeBase from sqlalchemy.orm import Mapped, mapped_column from sqlalchemy.schema import CreateTable from typing_extensions import Annotated timestamp = Annotated[datetime.datetime, mapped_column(nullable=False, server_default=func.CURRENT_TIMESTAMP()),] class Base(DeclarativeBase): type_annotation_map = {datetime.datetime: TIMESTAMP(timezone=True), } class UserClass(Base): __tablename__ = &quot;user&quot; id: Mapped[Integer] = mapped_column(Integer, primary_key=True, autoincrement=True) name: Mapped[str] = mapped_column(String(50)) fullname: Mapped[Optional[str]] = mapped_column(String(50), nullable=False) nickname: Mapped[Optional[str]] = mapped_column(String(30)) date: Mapped[datetime.datetime] status: Mapped[str] created_at: Mapped[timestamp] = mapped_column(server_default=func.UTC_TIMESTAMP()) updated_at: Mapped[timestamp] = mapped_column(server_default=func.UTC_TIMESTAMP()) </code></pre> <p>Table:</p> <pre><code>CREATE TABLE user ( id BIGINT NOT NULL, name VARCHAR(50) NOT NULL, fullname VARCHAR(50) NOT NULL, nickname VARCHAR(30), date TIMESTAMP NOT NULL, status VARCHAR NOT NULL, created_at TIMESTAMP DEFAULT (UTC_TIMESTAMP()) NOT NULL, updated_at TIMESTAMP DEFAULT (UTC_TIMESTAMP()) NOT NULL, PRIMARY KEY (id) ); </code></pre> <p>Insert command:</p> <pre><code>INSERT INTO user (name, fullname, nickname, date, status, created_at, updated_at) VALUES ('John', 'John Doe', 'Johnny', '2024-09-21 19:09:51.484769', 'active', '2024-09-21 19:09:51.490379', '2024-09-21 19:09:51.490400') </code></pre> <p>When I insert it's giving this error message:</p> <blockquote> <p>sqlite3.IntegrityError) NOT NULL constraint failed: user.id</p> </blockquote> <p>I think a primary key needs to be created like this in SQLite: <code>id integer primary key autoincrement</code>. How do I map a column to create the primary key like this?</p>
<python><sql><sqlite><sqlalchemy><flask-sqlalchemy>
2024-09-21 19:24:54
1
19,251
sfgroups
79,010,261
1,255,630
Finding the leftover rows in pandas dataframes
<p>If I'm detecting Ys in particular columns using this:</p> <pre><code>thing1 = df[df['column1'] == 'Y'] thing2 = df[df['column2'] == 'Y'] thing3 = df[df['column3'] == 'Y'] thing4 = df[df['column4'] == 'Y'] </code></pre> <p>How can I get all the rows that don't have Y in one of those columns? I have tried something like:</p> <pre><code>none_of_the_things = df[(df['column1'] != 'Y') &amp; (df['column2'] != 'Y') &amp; (df[df['column3'] != 'Y']) &amp; (df[df['column4'] != 'Y'])] </code></pre> <p>but this does not work. With this sort of error:</p> <pre><code>numpy.core._exceptions._ArrayMemoryError: Unable to allocate 23.3 TiB for an array with shape (1855862, 1724897) and data type float64 python ./deepseek-v2.5-chart.py 11.91s user 2.81s system 105% cpu 13.996 total </code></pre> <p>have I created some sort of monster with this method? 23.3 TiB sounds like a lot.</p> <p>example csv:</p> <pre><code>RECVDATE,column1,column2,column3,column4 01/01/2024,Y,N,N,N 01/04/2024,N,N,N,N 02/02/2024,N,Y,N,N 02/02/2024,N,Y,N,N 02/04/2024,N,N,N,N 03/03/2024,N,N,Y,N 03/03/2024,N,N,Y,N 03/03/2024,N,N,Y,N 03/04/2024,N,N,N,N 04/04/2024,N,N,N,Y 04/04/2024,N,N,N,Y 04/04/2024,N,N,N,Y 04/04/2024,N,N,N,Y 04/04/2024,N,N,N,Y 04/04/2024,N,N,N,Y 04/04/2024,N,N,N,N 04/04/2024,N,N,N,N </code></pre> <p>example python with the failing stuff commented out:</p> <pre><code>#!/usr/bin env python3 date_field = 'RECVDATE' import glob, os import pandas as pd import matplotlib.pyplot as plt from datetime import datetime dir_path = 'data' dfs = [pd.read_csv(f, encoding='latin-1', low_memory=False, quotechar='&quot;') for f in glob.glob(os.path.join(dir_path, 'example.csv'))] df = pd.concat(dfs, axis=0, ignore_index=True) df[date_field] = pd.to_datetime(df[date_field], errors='coerce') thing1 = df[df['column1'] == 'Y'] thing1['YearMonth'] = thing1[date_field].dt.to_period('M') monthly_counts1 = thing1.groupby('YearMonth').size() monthly_counts1.index = monthly_counts1.index.astype(str) thing2 = df[df['column2'] == 'Y'] thing2['YearMonth'] = thing2[date_field].dt.to_period('M') monthly_counts2 = thing2.groupby('YearMonth').size() monthly_counts2.index = monthly_counts2.index.astype(str) thing3 = df[df['column3'] == 'Y'] thing3['YearMonth'] = thing3[date_field].dt.to_period('M') monthly_counts3 = thing3.groupby('YearMonth').size() monthly_counts3.index = monthly_counts3.index.astype(str) thing4 = df[df['column4'] == 'Y'] thing4['YearMonth'] = thing4[date_field].dt.to_period('M') monthly_counts4 = thing4.groupby('YearMonth').size() monthly_counts4.index = monthly_counts4.index.astype(str) # none_of_the_things = df[(df['column1'] != 'Y') &amp; (df['column2'] != 'Y') &amp; (df[df['column3'] != 'Y']) &amp; (df[df['column4'] != 'Y'])] # none_of_the_things['YearMonth'] = none_of_the_things[date_field].dt.to_period('M') # non_monthly_counts = none_of_the_things.groupby('YearMonth').size() # non_monthly_counts.index = non_monthly_counts.index.astype(str) # Plotting plt.figure(figsize=(12, 6)) monthly_counts1.plot(kind='line', marker='o', label='count1', color='red') monthly_counts2.plot(kind='line', marker='o', label='count2', color='blue') monthly_counts3.plot(kind='line', marker='o', label='count3', color='green') monthly_counts4.plot(kind='line', marker='o', label='count4', color='purple') # non_monthly_counts.plot(kind='line', marker='o', label='none', color='black') plt.title('Number of Deaths/LifeThreating/Hospitalizations per Month') plt.xlabel('Month') plt.ylabel('Count') plt.grid(True) plt.xticks(rotation=45) plt.legend(title='Legend', loc='upper left') plt.show() </code></pre>
<python><pandas><dataframe>
2024-09-21 18:46:58
2
1,258
thoth
79,009,823
14,506,951
Is there a faster way to crawl a predefined list of URLs with scrapy when having to authenticate first?
<p>I have two scrapy Spiders:</p> <ul> <li>Spider 1 crawls a list of product links (~10000) and saves them to a <code>csv</code> file using a feed. It doesn't visit each of those links, only the categories (with multiple pages). This Spider rarely needs to run, so speed is not an issue here.</li> <li>Spider 2 visits each of those links and extracts some product information, also saving to a csv feed. This needs to run at least once a day, so speed is crucial.</li> </ul> <p>As both visit the same website (just different subpages), their structure is similar. Both need to authenticate first (multi-step authentication), which is why I can't just have all the links that they need to crawl in <code>start_urls</code>. I don't have a static authentication token, I need to simulate the actual user login. However, even though they're extremely similar, Spider 1 crawls about 500 pages per minute and Spider 2 only about 50 pages per minute, which is way to slow.</p> <p>The only key difference is how they &quot;discover&quot; the pages that they need to crawl:</p> <ul> <li>Spider 1 starts with a small list and then discovers the other pages one by one</li> <li>Spider 2 reads a large predefined list from a file and then just loops over the pages to crawl them</li> </ul> <p>Since both also don't really do any heavy processing of the crawled pages, my guess was that running the pages in a loop like in Spider 2 (method <code>after_2nd_step</code>) prevents scrapy from properly crawling them asynchronously, but I have no clue if that's really the case. I'm using <code>scrapy runspider file.py</code> if that's important.</p> <p>Another assumption I had, is that the website itself takes longer to load the product info pages for whatever reason. I didn't however find a way to see some data on that, like average page load times for an execution.</p> <p>So my question is the following: Why is spider 2 10x slower than Spider 1, even though it's running on the same machine, crawling the same website? Is there a faster way to crawl the long predefined list of URLs in Spider 2? If the issue isn't obvious from my code, is there a good way to analyze the time needed for the page to load?</p> <p>Here's my code for both of them, I did anonymize some sensitive parts, be assured that the original is valid python code. I tried to keep most of it, since there might be an issue in something that seems irrelevant to me:</p> <pre class="lang-py prettyprint-override"><code># Spider 1 import scrapy from scrapy.http import TextResponse from product_pages import PRODUKTSEITEN # a list of ~27 predefined URLs for all the categories class ProductLinkSpider(scrapy.Spider): name = 'my_name' start_urls = ['URL to login page'] custom_settings = { 'FEEDS': { 'path\\product_links.csv': { 'format': 'csv', 'encoding': 'utf8', 'overwrite': True, }, }, } def parse(self, response): # First, we handle the login form return scrapy.FormRequest.from_response( response, formid='loginForm', formdata={ #entering password and username }, callback=self.after_login ) def after_login(self, response): # Check for login success by verifying the response content if &quot;Your User ID or Password is incorrect. Please try again&quot; in response.text: self.logger.error(&quot;Login failed&quot;) # 2nd login step return scrapy.FormRequest.from_response( response, formxpath='//form[@action=&quot;/lorem ipsum&quot;]', formdata={ # Formdata is filled in }, callback=self.after_2nd_step ) def after_2nd_step(self, response): for page in PRODUKTSEITEN: yield scrapy.Request( page+&quot;?sort=asc&amp;q=%3Arelevance#&amp;page=0&quot;, callback=self.parse_products_list_page, cb_kwargs=dict(url_without_page=page+&quot;?sort=asc&amp;q=%3Arelevance&quot;, page=0) ) def parse_products_list_page(self, response: TextResponse, url_without_page: str, page: int): product_links = response.css('a css selector to get the links').getall() if There is another page: # Checks if there is another page, and requests it next yield scrapy.Request( url_without_page + f&quot;&amp;page={page+1}&quot;, callback=self.parse_products_list_page, cb_kwargs=dict(url_without_page=url_without_page, page=page+1) ) for link in product_links: yield {&quot;url&quot;: link} </code></pre> <p>And for the second Spider:</p> <pre class="lang-py prettyprint-override"><code># Spider 2 import scrapy from scrapy.http import TextResponse class ProductInfoSpider(scrapy.Spider): name = 'lorem ipsum' start_urls = ['login page'] custom_settings = { 'FEEDS': { 'path\\product_info_added_2.csv': { 'format': 'csv', 'encoding': 'utf8', 'overwrite': True, }, }, } def parse(self, response): # First, we handle the login form return scrapy.FormRequest.from_response( response, formid='loginForm', formdata={ # Enter username and password }, callback=self.after_login ) def after_login(self, response): # Check for login success by verifying the response content if &quot;Your User ID or Password is incorrect. Please try again&quot; in response.text: self.logger.error(&quot;Login failed&quot;) return scrapy.FormRequest.from_response( response, formxpath='//form[@action=&quot;/lorem ipsum&quot;]', formdata={ # Enter the same data as in the first Spider }, callback=self.after_2nd_step ) def after_2nd_step(self, response): with open(r&quot;path\product_links.csv&quot;, &quot;r&quot;) as file: # HERE is the only key difference lines = file.readlines() product_links = lines[1:] for link in product_links: yield scrapy.Request(&quot;domain&quot;+link, callback=self.parse_product_page) def parse_product_page(self, response): # extract some info about the product using 4 different css selectors to get the data yield {Some of the extracted info, 6 columns} </code></pre>
<python><web-scraping><scrapy><web-crawler>
2024-09-21 14:55:26
1
2,623
LoahL
79,009,679
2,989,330
PyCharm warning: Type of 'field' is incompatible with 'A' when implementing property from protocol
<p>I want to define an interface for a data class, but leave open the way the data is stored. To this end, I define a protocol <code>A</code> for the interface and an implementation <code>B</code>:</p> <pre><code>class A(Protocol): @property def field(self): ... @field.setter def field(self, value): ... class B(A): @property def field(self): return &quot;&quot; @field.setter def field(self, value): pass </code></pre> <p><code>mypy</code> has no issues with this implementation, but PyCharm warns me that</p> <pre><code>Type of 'field' is incompatible with 'A' </code></pre> <p>Above approach was already proposed in <a href="https://stackoverflow.com/a/68339603">this answer</a>, but PyCharm doesn't really like it.</p> <p>How would I better write this?</p>
<python><pycharm><python-typing>
2024-09-21 13:35:46
1
3,203
Green 绿色
79,009,651
3,572,505
python nested dict multikey method suggestion
<p>apparently, there is no built-in dict method (let's call it <code>.nestkey</code>) for dynamic key addressing in multi-nested dict structures. this can be demanding when dealing with complex dict structures,</p> <p>e.g., <code>dic_1.nestkey(list_of_keys_A) = value</code> instead of manually doing <code>dic_1[&quot;key_1&quot;][&quot;subkey_2&quot;][&quot;subsubkey_3&quot;].. = value</code>.</p> <p>this is not to be confused with level-1 assignment: <code>dic_1[&quot;key_1&quot;] = value_1, dic_2[&quot;key_2&quot;] = value_2, ..</code>.</p> <p>i know it's generally good practice to avoid nested structures, but when necessary, dynamic addressing is powerful:</p> <pre class="lang-py prettyprint-override"><code>list_values = [1, 2, 3]; ii = -1 for list_nestedkeys_i in [list_nestedkeys_A, list_nestedkeys_B, list_nestedkeys_C]: ii += 1; dic.nestkey(list_nestedkeys_i) = list_values[ii] # endfor </code></pre> <p>for this purpose, i suggest implementing <code>.nestkey</code> as a built-in <code>dict</code> method. here’s how it could be expressed in method format:</p> <pre class="lang-py prettyprint-override"><code>def nestkey(self, keys, value): d = self # the nested dict for key in keys[:-1]: # traverse to the second last key if key not in d: d[key] = {} # create a nested dict if key doesn't exist # endif d = d[key] # move deeper into the dict # endfor d[keys[-1]] = value # set the value for the final key # enddef </code></pre>
<python><dictionary><dynamic><nested><multikey>
2024-09-21 13:19:12
1
903
José Crespo Barrios
79,009,647
8,964,393
How to calculate the Exponential Moving Average (EMA) through record iterations in pandas dataframe
<p>I have created a pandas dataframe as follows:</p> <pre><code>import pandas as pd import numpy as np ds = { 'trend' : [1,1,1,1,2,2,3,3,3,3,3,3,4,4,4,4,4], 'price' : [23,43,56,21,43,55,54,32,9,12,11,12,23,3,2,1,1]} df = pd.DataFrame(data=ds) </code></pre> <p>The dataframe looks as follows:</p> <p>display(df)</p> <pre><code> trend price 0 1 23 1 1 43 2 1 56 3 1 21 4 2 43 5 2 55 6 3 54 7 3 32 8 3 9 9 3 12 10 3 11 11 3 12 12 4 23 13 4 3 14 4 2 15 4 1 16 4 1 </code></pre> <p>I have saved the dataframe to a .csv file called df.csv:</p> <pre><code>df.to_csv(&quot;df.csv&quot;, index = False) </code></pre> <p>I need to create a new field called <code>ema2</code> which:</p> <ol> <li><p>iterates through each and every record of the dataframe</p> </li> <li><p>calculates the Exponential Moving Average (EMA) by considering the price observed at each iteration and the prices (EMA length is 2 in this example) observed in the previous trends. For example:</p> </li> <li><p>I iterate at record 0 and the EMA is NaN (missing).</p> </li> <li><p>I iterate at record 1 and the EMA is still NaN (missing)</p> </li> <li><p>I Iterate at record 12 and the EMA is 24.20 (it considers price at record 3, price at record 5 and price at record 12</p> </li> <li><p>I Iterate at record 13 and the EMA is 13.53 (it considers price at record 3, price at record 5 and price at record 13</p> </li> <li><p>I Iterate at record 15 and the EMA is 12.46 (it considers price at record 3, price at record 5 and price at record 15 and so on .....</p> </li> </ol> <p>I have written the following code:</p> <pre><code>time_window = 2 ema= [] for i in range(len(df)): ds = pd.read_csv(&quot;df.csv&quot;, nrows=i+1) d = ds.groupby(['trend'], as_index=False).agg( {'price':'last'}) d['ema2'] = d['price'].ewm(com=time_window - 1, min_periods=time_window).mean() ema.append(d['ema2'].iloc[-1]) df['ema2'] = ema </code></pre> <p>Which produces the correct dataframe:</p> <pre><code>print(df) trend price ema2 0 1 23 NaN 1 1 43 NaN 2 1 56 NaN 3 1 21 NaN 4 2 43 35.666667 5 2 55 43.666667 6 3 54 49.571429 7 3 32 37.000000 8 3 9 23.857143 9 3 12 25.571429 10 3 11 25.000000 11 3 12 25.571429 12 4 23 24.200000 13 4 3 13.533333 14 4 2 13.000000 15 4 1 12.466667 16 4 1 12.466667 </code></pre> <p>The problem is that when the dataframe has millions of records: it takes a very long time to run.</p> <p>Does anyone know how to get the same results in a quick, efficient way, please?</p>
<python><pandas><dataframe><iterator><calculated-columns>
2024-09-21 13:16:15
1
1,762
Giampaolo Levorato
79,009,603
12,190,301
Process inside daemon immediately exits when using FIFO
<p>I have a setup that looks roughly like the following example:</p> <pre class="lang-py prettyprint-override"><code>from contextlib import contextmanager import subprocess import os from pathlib import Path import daemon @contextmanager def tmp_fifo(path: Path): try: os.mkfifo(path) file = os.open(path, os.O_RDWR | os.O_NONBLOCK) yield file finally: os.unlink(path) with tmp_fifo(Path.home() / &quot;sh.fifo&quot;) as fifo, open(&quot;dout.log&quot;, &quot;w+&quot;) as outfile: context = daemon.DaemonContext() with context: with subprocess.Popen([&quot;sh&quot;], stdin=fifo, stdout=outfile) as popen: popen.wait() </code></pre> <p>Essentially, what I am trying to do is to forward a shell to a FIFO. Without daemonizing, this works; i.e., I could write</p> <pre class="lang-py prettyprint-override"><code>from contextlib import contextmanager import subprocess import os from pathlib import Path @contextmanager def tmp_fifo(path: Path): try: os.mkfifo(path) file = os.open(path, os.O_RDWR | os.O_NONBLOCK) yield file finally: os.unlink(path) with tmp_fifo(Path.home() / &quot;sh.fifo&quot;) as fifo, open(&quot;dout.log&quot;, &quot;w+&quot;) as outfile: with subprocess.Popen([&quot;sh&quot;], stdin=fifo, stdout=outfile) as popen: popen.wait() </code></pre> <p>which allows me to input commands in the FIFO and see the results in the log file. How do I reproduce the desired behavior using a daemon? I tried moving the file redirects to the <code>DaemonContext</code> constructor, but that doesn't help. I also looked through the configuration options but none seem to be applicable.</p>
<python><mkfifo><python-daemon>
2024-09-21 12:49:49
1
2,109
Schottky
79,009,454
6,449,621
Convert a list of time string to unique string format
<p>I have a list of time string with different formats as shown</p> <pre><code>time = [&quot;1:5 am&quot;, &quot;1:35 am&quot;, &quot;8:1 am&quot;, &quot;9:14 am&quot;, &quot;14:23 pm&quot;, &quot;20:2 pm&quot;] dict = {'time': time} df = pd.DataFrame(dict) </code></pre> <p>and wanted to replace strings in list as shown below.</p> <pre><code>[&quot;01:05 am&quot;, &quot;01:35 am&quot;, &quot;08:01 am&quot;, &quot;09:14 am&quot;, &quot;14:23 pm&quot;, &quot;20:02 pm&quot;] </code></pre> <p>Not sure how to write a regex that format the string in DataFrame.</p>
<python><pandas><dataframe>
2024-09-21 11:36:14
4
465
anandyn02
79,009,352
15,260,108
how to configure nginx so that front end and backend works in AWS
<p>i am deploying my app on AWS instance. i have both frontend and backend as docker image. i want to use nginx. when i run this config, and go to AWS given public URL, then 502 is returned by nginx. /api /docs they are working but /admin / returning 502. here is my conf files:<br /> docker-compose.yml:</p> <pre><code> backend: container_name: backend image: ${BACKEND_IMAGE_NAME}:${IMAGE_TAG} command: python manage.py runserver 0.0.0.0:8000 env_file: - .env expose: - 8000 frontend: container_name: frontend image: ${FRONTEND_IMAGE_NAME}:${IMAGE_TAG} expose: - 3002 env_file: - .env nginx: build: ./nginx ports: - 80:80 depends_on: - backend - frontend </code></pre> <p>here is nginx conf:</p> <pre><code>upstream backend { server backend:8000; } upstream frontend { server frontend:3002; } server { listen 80; location /api/ { proxy_pass http://backend; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /docs/ { proxy_pass http://backend; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /admin/ { proxy_pass http://backend; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location / { proxy_pass http://frontend; # Proxy to frontend on port 3002 proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; # Ensure that Nginx handles large files and requests well client_max_body_size 100M; # Timeout settings to prevent 502 Bad Gateway proxy_connect_timeout 600; proxy_send_timeout 600; proxy_read_timeout 600; send_timeout 600; } }``` </code></pre> <p>nginx docker file:</p> <pre><code>FROM nginx:1.27 RUN rm /etc/nginx/conf.d/default.conf COPY nginx.conf /etc/nginx/conf.d``` </code></pre> <p>front end docker file:</p> <pre><code># Use a Node.js base image FROM node:18-alpine # Set working directory WORKDIR /app # Copy package.json and install dependencies COPY package*.json ./ RUN npm install # Copy the rest of the application code COPY . . # Build the app for production RUN npm run build # Expose the port your app runs on EXPOSE 3002 # Start the app CMD [&quot;npm&quot;, &quot;run&quot;, &quot;start&quot;] </code></pre> <p>backend docker file:</p> <pre><code>FROM python:3.12 ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 WORKDIR /app/src COPY requirements.txt ./ RUN pip install --no-cache-dir -r requirements.txt COPY . /app/ EXPOSE 8000 </code></pre>
<python><django><docker><nginx><nuxt.js>
2024-09-21 10:36:31
1
400
Diyorbek
79,009,315
19,556,055
Multiplying a 2D array with a 3D array of vectors in Numpy
<p>I have a dxd matrix that I would like to multiply with a dx1xn matrix. The idea is to get back another dx1xn matrix, so I would essentially like to multiply each dxd matrix with each dx1 matrix n times along that third axis. I have no idea how to go about this though. I have tried <code>np.apply_along_axis</code> and <code>np.apply_over_axes</code>, but the first only selects one axis rather than the dx1 matrices, and the second doesn't do what I want either.</p> <pre><code>k = 2 s = 36 d = k + s - 1 n = 1119 T = np.zeros(shape=(d, d) alpha_filt = np.zeros(shape=(d, 1, n)) # Doesn't work obviously np.matmul(T, alpha_filt) </code></pre>
<python><arrays><numpy>
2024-09-21 10:18:42
2
338
MKJ
79,009,151
769,677
What is the difference between python requests and cURL?
<p>I have the following situation. I send a request from 3 sources (postman, cURL and python requests library). For Postman and cURL I receive the same response but for <strong>python requests</strong> library I get a different response(other HTML source) and I don't understand the difference:</p> <p>In Postman I send the request without cookies and without follow redirects. All the requests use the same IP address from the same machine.</p> <p><strong>Versions:</strong></p> <p><strong>cURL</strong> curl 8.6.0 (x86_64-apple-darwin23.0) libcurl/8.6.0 (SecureTransport) LibreSSL/3.3.6 zlib/1.2.12 nghttp2/1.61.0 <strong>Python</strong> 3.7 requests 2.25.1 <strong>OS</strong> macOS 14.5 (x64)</p> <p><strong>cURL command</strong></p> <pre><code>curl --location '&lt;URL&gt;' \ --header 'host: &lt;HOST&gt;' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36' \ --header 'Accept-Encoding: gzip, deflate' \ --compressed &gt; test.html </code></pre> <p><strong>Python requests code</strong></p> <pre><code>import requests url = &quot;&lt;URL&gt;&quot; payload = {} headers = { 'host': '&lt;HOST&gt;', 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36', 'Accept-Encoding': 'gzip, deflate' } response = requests.request(&quot;GET&quot;, url, headers=headers, data=payload, allow_redirects=False) print(response.text) </code></pre> <p>I tried to check which http protocol is use by all these methods and I found that all use HTTP 1.1</p> <p><strong>I don't understand what is the difference between these methods(cURL and requests) so I receive different response.</strong></p>
<python><http><curl><python-requests>
2024-09-21 08:48:43
1
1,660
Adrian B
79,009,052
8,086,892
run docker command within python subprocess within GitHub runner
<p>I am running functional tests as CI in my GitHub runner. To properly execute my tests, I am building a docker image and running it (a slightly modified mysql container). Because I am building the container from a Dockerfile (not only pulling it from a registry), I dont use GitHub <code>service</code> or <code>container</code> capabilities (<a href="https://docs.github.com/en/actions/use-cases-and-examples/using-containerized-services/about-service-containers" rel="nofollow noreferrer">https://docs.github.com/en/actions/use-cases-and-examples/using-containerized-services/about-service-containers</a>).</p> <p>Instead I have some steps dedicated in my GH workflow to build the container and run it like this</p> <pre><code> - name: build docker container run: | cd tests/functional/olbp/mocked_data/ docker build --no-cache -f my_service.Dockerfile -t my_service_test:latest . - name: run container run: docker run --name my_service -d -p 127.0.0.1:3306:3306 my_service_test --sql_mode=&quot;NO_ENGINE_SUBSTITUTION&quot; - name: wait for MySQL to start run: | until mysqladmin ping -h 127.0.0.1 --silent; do echo 'Waiting for MySQL to start...' sleep 1 done </code></pre> <p>Finally I am calling my functional tests (pytest) with python</p> <pre><code> - name: run the functional tests run: python -m pytest tests/functional -vv -s --log-cli-level=DEBUG </code></pre> <p>This is working fine, my tests can obvisouly interract with the mysql container.</p> <p>However I am struggling to interract with Docker in this context. I would like to generate a mysqldump part of my tests. So I wrote this inside my tests:</p> <pre><code>dck_exc_output = subprocess.run( [ &quot;docker&quot;, &quot;exec&quot;, &quot;my_service&quot;, &quot;mysqldump&quot;, &quot;--skip-triggers&quot;, &quot;--skip-extended-insert&quot;, &quot;--compact&quot;, &quot;--no-create-info&quot;, &quot;-uroot&quot;, &quot;-psupersecret&quot;, &quot;my_db&quot;, &quot;my_table&quot;, &quot;&gt;&quot;, live_data_dump, ], capture_output=True, shell=True, ) logging.debug(dck_exc_output) </code></pre> <p>It is working fine when being executed from my computer but whenever I try to get this executed inside the GH Runner (this docker command or even a simple docker version). I end up on this output (output for subprocess of a simple <code>docker version</code> via subprocess):</p> <pre><code>DEBUG root:my_test.py:246 CompletedProcess(args=['docker', 'version'], returncode=0, stdout=b'', stderr=b' Usage: docker [OPTIONS] COMMAND ... ') </code></pre> <p>I already confirmed that I have same user, same permission and same env variable between the subprocess and the GH runner commands.<br /> I cannot understand why I am receiving this output. The docker executable seems to be found (because I am receiving the helppage as if I was executing a wrong command) but it will not execute as it is doing when I run the test locally.</p>
<python><docker><subprocess><github-actions><pytest>
2024-09-21 08:03:48
1
347
mouch
79,008,714
1,234,799
Django Filter __In Preserve Order
<p>This question is regarding Django filtering, with <code>__In</code> clause. Basically, I am trying to understand how to filter by providing <code>videos.filter(video__in = video_ids)</code> with string ids, so that each row that gets returned has the same order as the order of string ids in the list used for filtering.</p> <p>For more context, filtering is done using string ids for e.g. <code>['7C2z4GqqS5E','kTlv5_Bs8aw','OK3GJ0WIQ8s','p8npDG2ulKQ','6ZfuNTqbHE8']</code>. Model <code>video</code> field is video id described above. It is different from the integer id.</p> <p>The <code>video_id_order</code> used below was something I had tried that gave error <code>Field 'id' expected a number but got '7C2z4GqqS5E'</code>, I believe this is not being used correctly, and something is still missing to get the order of results preserved as it is in <code>video_ids</code>. What should be the correct order function in this case or is this approach even correct with Django models to preserve query-set result when <code>__In</code> clause is used?</p> <pre><code>def get_video_objects(video_ids,count): ''' video_ids are already in the correct order, filter should return rows in the same order ''' videos = Video.objects.all() // video_id_order = Case(*[When(id=id, then=pos) for pos,id in enumerate(video_ids)]) results = videos.filter(video__in = video_ids) // results = results.order_by(video_id_order) results = list(results[:int(count)]\ .values('video','title','comment_count','likes')) return results </code></pre> <p>Video model is as following</p> <pre><code>class Video(models.Model): id = models.PositiveBigIntegerField(primary_key=True,serialize=False,auto_created=False) video = models.SlugField(unique=True,null=False,primary_key=False) title = models.CharField(max_length=200) comment_count = models.PositiveIntegerField(default=0) likes = models.PositiveIntegerField(default=0) </code></pre>
<python><django><database><data-structures>
2024-09-21 03:32:22
3
4,214
Patt Mehta
79,008,560
238,671
Identify duplicated groups in pandas
<p>Assume I have the following data</p> <pre><code>df = pd.DataFrame({ 'task_id': [1, 1, 1, 1, 2, 2, 2, 2], 'job_id': [1, 1, 2, 2, 0, 0, 1, 1], 'filename': ['filename1', 'filename2', 'filename33', 'filename2342', 'filename1', 'filename2', 'filename33', 'filename5'] }) </code></pre> <pre><code> task_id jobs_id filename 0 1 1 filename1 1 1 1 filename2 2 1 2 filename33 3 1 2 filename2342 4 2 0 filename1 5 2 0 filename2 6 2 1 filename33 7 2 1 filename5 </code></pre> <p>I want to identify the pairs (<code>task_id</code> and <code>jobs_id</code>) that contain exactly the same filenames (no more, no fewer filenames). In my case the results should be <code>[((1, 1), (2, 0), )]</code> since they contain exactly (<code>filename1</code>, <code>filename2</code>).</p> <p>I guess I have to group and then use frozenset, as</p> <pre><code>df.groupby(['task_id', 'jobs_id'])['filename'].apply(lambda x: frozenset(x)) </code></pre> <pre><code>task_id jobs_id 1 1 (filename1, filename2) 2 (filename33, filename2342) 2 0 (filename1, filename2) 1 (filename33, filename5) Name: filename, dtype: object </code></pre>
<python><pandas>
2024-09-21 00:27:34
1
17,832
Ruggero Turra
79,008,480
1,658,617
Does Cython guarantee __dealloc__ order in __mro__?
<p>Does Cython respect the <code>__mro__</code> in case of <code>__dealloc__</code>?</p> <p>For example, in the case of inheritence:</p> <pre><code>cdef class A: def __dealloc__(self): # Deallocate cdef class B(A): def __dealloc__(self): # Deallocate some more </code></pre> <p>Is <code>B.__dealloc__</code> guaranteed to be called before <code>A.__dealloc__</code>?</p> <p>I wish to create a threadsafe child class that takes a lock during deallocation, and just calls the parent <code>__dealloc__</code> within that lock.</p>
<python><memory-management><cython>
2024-09-20 23:09:04
1
27,490
Bharel
79,008,391
1,713,850
Grabbing a specific url from a webpage with re and requests
<pre><code>import requests, re r = requests.get('example.com') p = re.compile('\d') print(p.match(str(r.text))) </code></pre> <p>This always prints None, even though r.text definitely contains numbers, but print(p.match('12345')) works. What do I need to do to r.text to make it readable by re.compile.match()? Casting to str is clearly insufficient.</p>
<python><regex><python-requests><python-re>
2024-09-20 22:15:34
1
728
Red Dwarf
79,008,369
1,921,352
Rumble RSS feed - gives 403 when called with a python urllib.request
<p>The iine of code failing is</p> <pre><code> req = urllib.request.Request(url) </code></pre> <p>A rumble RSS feed address that works fine typed into a browser address line returns a '403 - authorisation will not help'.</p> <p>A youtube RSS feed address works fine, other RSS feed addresses work fine.</p> <p>The sequence is that the address is hit, rumble give a temporary redirect to an api address then this gives the 403. Both the original address and teh API address work fine in from a browser address line.</p> <p>I have been through adding more and more headers etc... and am only hitting one url... so it is unlikely to be throttling - it makes no sense to have more clever anti-bot stuff on an RSS feed(!) but I have tried it all and it doesn't work. Any ideas welcome.</p> <p>FYI</p> <p>These are two sets of headers I have tried - they didn't work, but did break the you tube links(!).</p> <pre><code> headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', 'Accept-Language': 'en-US,en;q=0.5', 'Accept-Encoding': 'gzip, deflate, br', 'Connection': 'keep-alive', 'Upgrade-Insecure-Requests': '1', 'Sec-Fetch-Dest': 'document', 'Sec-Fetch-Mode': 'navigate', 'Sec-Fetch-Site': 'none', 'Sec-Fetch-User': '?1', 'Cache-Control': 'max-age=0', } headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:89.0) Gecko/20100101 Firefox/89.0', 'Accept': 'application/rss+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Language': 'en-US,en;q=0.5', 'Accept-Encoding': 'gzip, deflate, br', 'Connection': 'keep-alive', 'Referer': 'https://www.rumble.com/', 'Origin': f'https://{parsed_url.netloc}' } </code></pre> <p>Both used with</p> <pre><code> req = urllib.request.Request(url, headers=headers) </code></pre>
<python><rss><rumble-api>
2024-09-20 22:07:20
1
1,497
pperrin
79,008,316
1,422,096
Parameter encoded with encodeURIComponent, how to get it in a Python Bottle server?
<p>Let's say I send a request with JavaScript:</p> <pre class="lang-javascript prettyprint-override"><code>fetch(&quot;/query?q=&quot; + encodeURIComponent(&quot;c'est un château? Yes &amp; no!&quot;)); </code></pre> <p>to a Python Bottle server:</p> <pre class="lang-python prettyprint-override"><code>from bottle import Bottle, request app = Bottle(&quot;&quot;) @app.route(&quot;/query&quot;) def query(): q = request.query.get(&quot;q&quot;) # how to decode it? print(q) app.run() </code></pre> <p>How to decode <code>request.query.get(&quot;q&quot;)</code> so that it extracts the <code>encodeURIComponent</code> encoding? In this example, the <code>?</code> and <code>&amp;</code> are correctly decoded, but the <code>â</code> is not: <code>print(q)</code> gives <code>c'est un château? Yes &amp; no!</code></p>
<javascript><python><bottle><encodeuricomponent>
2024-09-20 21:32:31
1
47,388
Basj
79,008,301
2,278,511
FLET: Matematical operation on value in Slider controls
<p>I have specific problem and i don't understand how to solve it :/</p> <p>Source: <a href="https://flet.dev/docs/controls/slider" rel="nofollow noreferrer">FLET Slider Example</a></p> <pre class="lang-py prettyprint-override"><code>import flet as ft def main(page): def slider_changed(e): t.value = f&quot;Slider changed to {e.control.value}&quot; page.update() t = ft.Text() page.add( ft.Text(&quot;Slider with 'on_change' event:&quot;), ft.Slider(min=0, max=100, divisions=10, label=&quot;{value}%&quot;, on_change=slider_changed), t) ft.app(main) </code></pre> <p>Value <strong>label</strong> works fine, but in my project I need to apply mathematical operation (dividing) on this value.</p> <p>Value <code>label=&quot;{value}%&quot;</code> is probably string, but when I try to transform it to int, debugger show me error <code>ValueError: invalid literal for int() with base 10</code></p> <p>Please, how can I divide value and after that show is as label?</p>
<python><flutter><flet>
2024-09-20 21:23:03
1
408
lukassliacky
79,008,185
13,634,560
median() tries to change column to numeric
<p>I am using median() inside of an if-else list comprehension as such:</p> <pre><code>summary_frame = pd.DataFrame({ # ... &quot;50%&quot;: [df[col].median() if &quot;float&quot; or &quot;int&quot; or &quot;time&quot; in str(df[col].dtype) else df[col].mode() for col in df.columns] # ... }) </code></pre> <p>where if the datatype is not numerical, else it should default to mode(), which works when the datatype is not numerical.</p> <p>however, it tries to convert the series to numerical and throws a TypeError. Is there a way around this?</p>
<python><pandas><typeerror>
2024-09-20 20:32:28
1
341
plotmaster473
79,008,149
1,415,405
Implement a scipy Butterworth filter to operate on data contained in a sequence of numpy arrays
<p>I have seen code examples of how to use the scipy Butterworth filter to filter data stored in a numpy array.</p> <p>I need to do something slightly different. I want to process the data in blocks.</p> <p>As an example, if the total signal is 4096 samples long, I would like to process the first 1024 samples and output the result. Then the next 1024 samples, and so on.</p> <p>But when I concatenate the output arrays I would like the result to be exactly as if I had processed all 4096 samples in one operation.</p> <p>My guess is that I will need to carry the state of the filter from one block to the next, but any pointers on how to do this would be very helpful.</p> <p>I have used 1024 as an example. I could make the buffers larger or smaller if that helps. But I can't put all the data in a single buffer because that would limit the total data I could process to the available memory and the data might be bigger than that in some cases.</p>
<python><numpy><filter><scipy><butterworth>
2024-09-20 20:18:14
1
498
Martin McBride
79,008,105
4,129,091
Passing an Enum as a tool to a client: "TypeError: Object of type ModelMetaclass is not JSON serializable"
<p>I'm attempting to call a tool in langchain.</p> <p>The function takes an <code>IntEnum</code> input. It rolls a dice and returns a random integer.</p> <pre class="lang-py prettyprint-override"><code>import random from enum import IntEnum from dotenv import load_dotenv from langchain.tools import Tool, tool from langchain_openai import AzureChatOpenAI from pydantic import BaseModel, Field load_dotenv() class Dice(IntEnum): &quot;&quot;&quot; Roll a D&amp;D dice. A d4 dice has 4 sides and thus rolling a d4 dice will return a value from 1 through 4. &quot;&quot;&quot; d4 = 4 d6 = 6 d8 = 8 d10 = 10 d12 = 12 d20 = 20 d100 = 100 def roll_dice(dice: Dice) -&gt; int: &quot;&quot;&quot; Simulates rolling a dice with a specified number of sides. Parameters: dice (Dice): A dice to roll. Returns: int: The result of the dice roll. &quot;&quot;&quot; return random.randint(1, dice.value) class RollDiceInput(BaseModel): dice: Dice def get_function_description(func): &quot;&quot;&quot;Extract docstrings from the functions&quot;&quot;&quot; return func.__doc__.strip() # Define the tool with the input schema roll_dice_tool = Tool( name=&quot;roll_dice&quot;, description=get_function_description(roll_dice), args_schema=RollDiceInput, func=roll_dice, ) # Define the prompt prompt = &quot;&quot;&quot; Roll a dice in Dungeons and Dragons. &quot;&quot;&quot; client = AzureChatOpenAI() # Call the GPT-4 API with descriptions extracted from docstrings response = client.invoke( model=&quot;gpt-4o&quot;, input=prompt, tools=[roll_dice_tool], tool_choice={ &quot;type&quot;: &quot;function&quot;, &quot;function&quot;: {&quot;name&quot;: &quot;roll_dice&quot;}, }, # forces the model to call the `roll_dice` function ) </code></pre> <p>It yields the error:</p> <p><code>TypeError: Object of type ModelMetaclass is not JSON serializable</code>.</p> <p>It seems to fail on serializing the function.</p> <p>How do I correctly pass and define a tool for the <code>roll_dice</code> function?</p> <p>langchain 0.3.0 langchain-openai 0.2.0</p>
<python><pydantic><langchain><py-langchain>
2024-09-20 19:52:44
1
3,665
tsorn
79,008,061
4,298,208
Proper way to process larger-than-memory datasets in Polars
<p>I have begun to learn and implement Polars because of (1) the potential speed improvements and (2) for the promise of being able to process larger-than-memory datasets. However, I'm struggling to see how the second promise is actually delivered in specific scenarios that my use case requires.</p> <p>One specific example I'm struggling with is how to read a multi-GB JSONL file from S3, apply a few transformations, and send the modified records to <code>STDOUT</code>.</p> <h2>Gaps in the lazy &quot;sink&quot; methods...</h2> <p>As I just <a href="https://github.com/pola-rs/polars/issues/18834" rel="nofollow noreferrer">raised</a> in GitHub, the <code>sink_*()</code> methods do not support writing to a buffer or file-like - only to a named file path. Otherwise, it seems the simple solution would be something like <code>sink_ndjson(sys.stdout, ...)</code></p> <h2>No clear way to &quot;batch&quot; a <code>DataFrame</code> or <code>LazyFrame</code> into smaller data frames.</h2> <p>The next thing I tried was to get smaller batches or dataframes (for instance 100K rows at a time) which I could process in memory and write with <code>write_ndjson(sys.stdout, ...)</code> one at a time until I reach the end of the stream.</p> <p>The closest I could find is <code>LazyFrame.slice(offset, batch_size).collect()</code> - except in practice, this seems to hang/crash on the first invocation rather than reading just the first n records and then proceeding. Even when I set a low number of records in the LazyFrame's schema scan limit. Perhaps this is a bug - but even still, the <code>slice()</code> method does not seem specifically designed for getting incremental batches from the lazy frame.</p> <p>Any help is much appreciated!</p>
<python><python-polars>
2024-09-20 19:35:00
1
2,630
aaronsteers
79,008,055
4,635,580
Difference in validation result using `jsonschema` and `check-jsonschema` in regard to a field with value of date-time
<p>Given <code>model_schema.json</code></p> <pre class="lang-json prettyprint-override"><code>{ &quot;properties&quot;: { &quot;dt&quot;: { &quot;format&quot;: &quot;date-time&quot;, &quot;title&quot;: &quot;Dt&quot;, &quot;type&quot;: &quot;string&quot; } }, &quot;required&quot;: [ &quot;dt&quot; ], &quot;title&quot;: &quot;Model&quot;, &quot;type&quot;: &quot;object&quot;, &quot;$schema&quot;: &quot;https://json-schema.org/draft/2020-12/schema&quot; } </code></pre> <p>and <code>model_instance.json</code></p> <pre class="lang-json prettyprint-override"><code>{ &quot;dt&quot;: &quot;2032-04-23T10:20:30&quot; } </code></pre> <p>Running the following Python script produces no error.</p> <pre class="lang-py prettyprint-override"><code>import json from pprint import pprint import jsonschema with open(&quot;model_schema.json&quot;) as f: schema = json.load(f) with open(&quot;model_instance.json&quot;) as f: m1_as_dict = json.load(f) pprint(schema) print(&quot;\n=====================================\n&quot;) pprint(m1_as_dict) jsonschema.validate(m1_as_dict, schema) </code></pre> <p>However, running the the following command</p> <pre><code>check-jsonschema --schemafile model_schema.json model_instance.json </code></pre> <p>produces the following error</p> <pre><code>Schema validation errors were encountered. model_instance.json::$.dt: '2032-04-23T10:20:30' is not a 'date-time' </code></pre> <p>I think the command's behavior is correct. Why doesn't the given Python script produce a comparable error as the command?</p> <p>My environment is:</p> <pre><code>check-jsonschema 0.28.2 jsonschema 4.21.1 jsonschema-specifications 2023.12.1 types-jsonschema 4.21.0.20240331 </code></pre>
<python><jsonschema>
2024-09-20 19:32:48
2
739
Isaac To
79,007,935
307,149
PyQt QMessageBox is Blocking, or not?
<p>I have some operations that take place in the <strong>init</strong>() phase of my GUI. It looks for the presence of a file in a particular location and if it finds it, it will pop up a message box asking the user if they want to load the settings in that file. When I place that operation in the <strong>init</strong>() phase, the pop up comes up first and the GUI is not present at all. If I move that function to a button on demand, outside of <strong>init</strong>(), then it works fine. The GUI comes up, I click my button and the message box appears, etc. My understanding is that it's very difficult to interact with the GUI from threads outside the main thread, but because the message box comes up and the GUI does not load behind it, I'm assuming the message box is blocking. I have found in my online research folks saying that it's NOT blocking, but the behavior of having this message box coming up without the rest of the GUI loading behind it would say otherwise. This makes me think I need to make the message box non-blocking, but I don't know how to do that other than launching the message box in another thread, which again may not be possible since you need to be in the main thread to do so? I've read about differences regarding how the QMessageBox is constructed, .show() vs. ._exec(), etc. but not sure that will fix the issue? If you want to see my <strong>init</strong>() or a screenshot of the behavior I can upload that.</p> <p>Below is the code I'm using to launch the message box:</p> <pre class="lang-py prettyprint-override"><code>def popUpYN(self, message): if QMessageBox.StandardButton.Yes == QMessageBox.question( self, '', message, QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No ): return True else: return False # // END popUpYN() </code></pre>
<python><qt><pyqt><pyside><qmessagebox>
2024-09-20 18:42:49
0
645
spickles
79,007,795
10,319,707
Pymssql: "DBPROCESS is dead or not enabled" error every time I run my sixth query, no matter how many times I rerun in one day
<h2>The Problem</h2> <p>I have an AWS Glue job that uses the <a href="https://aws.amazon.com/blogs/big-data/aws-glue-python-shell-now-supports-python-3-9-with-a-flexible-pre-loaded-environment-and-support-to-install-additional-libraries/" rel="nofollow noreferrer">standard set of analytics libraries</a> with Python Shell. Of special note, it uses <code>SQLAlchemy</code> to connect to our Microsoft SQL Server. We also go out of our way to import <code>pymssql</code> 2.3.1 for this. In this Glue job, we run multiple copies of the same stored procedure six times in sequence. <strong>Seemingly at random</strong>, the sixth (and therefore final) stored procedure will run to completion from SQL Server's point of view but fail inside its <code>pandas.read_sql</code> call. The error message, which as best as I can tell comes from <a href="https://www.freetds.org/" rel="nofollow noreferrer">FreeTDS</a>, is</p> <blockquote> <p>Operational Error(&quot;pymssql.exceptions.OperationalError) (20047, b'DB-lib error message 20047, severity 9: DBPROCESS is dead or not enabled ')</p> </blockquote> <p>Its type is <code>sqlalchemy.exc.OperationalError</code>.</p> <p>The data on our SQL box only changes once per day, but here's the weird thing: <strong>When I get this error, I get it for the rest of the day</strong>. It does not matter how many times I rerun the Glue job.</p> <p>How can I debug this?</p> <h2>What I've Tried or Ruled Out</h2> <p>Sorry for the length, but I've tried a lot:</p> <ul> <li>I am certain that the SQL box has no issues. The final query runs to completion from its point of view. Neither Extended Events, <code>sp_WhoIsActive</code>, nor the SQL Server Error Log show anything of interest. They know when Python closes the connection, but that's normal.</li> <li>Changing <code>pymssql</code> version <a href="https://github.com/pymssql/pymssql/issues/908" rel="nofollow noreferrer">as suggested here</a> did nothing. I've tried everything below with both 2.3.0 and 2.3.1.</li> <li>There are no AWS permissions issues. This works just fine most days of the year.</li> <li>Adding <code>stream_results</code> to my connection options has no effect, whether <code>True</code> or <code>False</code>. The documentation isn't clear on if Microsoft SQL Server even supports it.</li> <li>I've added <code>echo=&quot;debug&quot;, echo_pool=&quot;debug&quot;</code> to my engine options. The additional logging that they add has been of no value. I won't even bother to share it here. It ticks along perfectly until we get the same error as I've put above.</li> <li><code>pool_pre_ping = True</code> is <a href="https://github.com/rails-sqlserver/activerecord-sqlserver-adapter/issues/402#issuecomment-1356793443" rel="nofollow noreferrer">by</a> far <a href="https://stackoverflow.com/a/74841789/10319707">the</a> most <a href="https://stackoverflow.com/questions/78623486/aws-fargate-api-keeps-dropping-out">suggested</a> solution. It does not solve the problem. I can see the pre ping in the additional logs discussed above, but the job still fails in the same way.</li> <li>Disabling connection pooling (<code>poolclass=NullPool</code>) did not fix the problem, nor did <code>pool_reset_on_return</code>.</li> <li>Given the above, I feel that pooling issue are ruled out. But I do find it interesting that the default number of pools is 5 and I'm failing on query 6.</li> <li>I have hunted <a href="https://xkcd.com/1334/" rel="nofollow noreferrer">very deeply on Google</a> for this error. I have read <strong>every single page of Google results</strong> for &quot;20047 db-lib error message dbprocess is dead&quot;. This includes items beyond Python (Ruby seems to share this issue). Nothing has worked.</li> <li>It's not a problem of having too much data. We have another Glue job that collects a superset of this data and it worked just fine today. In all aspects expect for a change in stored procedure name, the other job's code is totally identical.</li> <li>I see nothing to indicate that this is a timeout issue.</li> <li>Spark is not an option. It just isn't. I'd be open to trying <code>pyobdc</code>, but I've never got it to work with the Windows EC2 that we're hitting.</li> </ul> <p>Adding even more calls to the stored procedure fixes the problem (e.g. I can cover all of 2024 either in one run or by doing one half of 2024 and then the other half), but I don't want to do this due to performance costs. It also feels like cheating rather than finding the root cause.</p>
<python><sql-server><amazon-web-services><aws-glue><pymssql>
2024-09-20 17:47:23
1
1,746
J. Mini
79,007,782
2,287,458
Polars when().then(map_elements(function)) always calls function
<p>I have this code:</p> <pre class="lang-py prettyprint-override"><code>import polars as pl def get_year(entry_id: str) -&gt; str: arr = entry_id.split('.') print(f'&gt; Function is called for {entry_id} &lt;') if arr[0] != 'DEBT': return None else: return int(arr[1]) df = pl.DataFrame({ 'Type': ['CAT_YY', 'CAT5', 'CAT_YY', 'CATX'], 'ID': ['DEBT.24', 'CASH.EU', 'DEBT.26', 'CASH.US'], }).with_columns(year=pl.when(pl.col('Type') == 'CAT_YY') .then(pl.col('ID').map_elements(get_year, return_dtype=pl.Int64)) .otherwise(None)) print(df) </code></pre> <p>which gives the correct result (= strip out the <code>YY</code> part year from the ID, if the Type is <code>CAT_YY</code>).</p> <pre><code>shape: (4, 3) ┌────────┬─────────┬──────┐ │ Type ┆ ID ┆ year │ │ --- ┆ --- ┆ --- │ │ str ┆ str ┆ i64 │ ╞════════╪═════════╪══════╡ │ CAT_YY ┆ DEBT.24 ┆ 24 │ │ CAT5 ┆ CASH.EU ┆ null │ │ CAT_YY ┆ DEBT.26 ┆ 26 │ │ CATX ┆ CASH.US ┆ null │ └────────┴─────────┴──────┘ </code></pre> <p>However, my function <code>get_year</code> gets called <strong>for every entry</strong> in my dataframe, regardless of the <code>pl.when(...)</code> condition:</p> <pre><code>&gt; Function is called for DEBT.24 &lt; &gt; Function is called for CASH.EU &lt; &gt; Function is called for DEBT.26 &lt; &gt; Function is called for CASH.US &lt; </code></pre> <p>I am very surprised by this, because this seems counter-intuitive &amp; also very inefficient. Note, in practice, my data and my <strong>function</strong> are a lot <strong>more complex</strong>. So this is just a toy example to demonstrate the issue.</p> <p>Am I doing anything wrong? How can I change polars logic to only call <code>get_year</code> when the <code>pl.when()</code> condition is actually satisfied?</p>
<python><performance><vectorization><python-polars>
2024-09-20 17:42:03
4
3,591
Phil-ZXX
79,007,637
6,431,715
python: ssl.wrap_socket - cert.pem vs. cert & key
<p>I'm running SFTP server with the following code:</p> <pre><code>httpd= HTTPServer (('10.0.0.10',4443), MyHandler) httpd.socket = ssl.wrap_socket (httpd.socket, keyfile='private.key', certfile='cert.pem', server_side=True) httpd.serve_forever () </code></pre> <p>It's working fine.</p> <p>As you can see, keyfile is 'None'. Can you please tell what is the added value of using keyfile ? Currently I need cert.pem is both server and client sides. With keyfile I will need also keyfile at both sides.</p> <p>My cert.pem contains:</p> <pre><code>-----BEGIN CERTIFICATE----- MIID5zCCAs+gAwIBAgIURqxtwR4h5Byjj5139okUQhHdpL8wDQYJKoZIhvcNAQEL ... Lsgcc6ild9ME6cmFhCKiIsdSaVQoNhU+lFC2Xu/1bZyYOGs4LgdfOXDfog== -----END CERTIFICATE----- </code></pre>
<python><ssl>
2024-09-20 16:52:59
0
635
Zvi Vered
79,007,518
9,392,446
Find duplicates from pandas column of nested lists within previous rows with multiple conditions
<p>I'm a little confused on how to code this.</p> <p>I have a dataset like this:</p> <pre><code>rules user_list event_time row_number rule1 123,244,344 2024-09-20 1 rule1 125,346,421 2024-09-19 2 rule1 125,343,431 2024-09-18 3 rule2 125,344,423 2024-09-20 1 rule2 125,346,421 2024-09-19 2 rule3 125,348,331 2024-09-20 1 rule3 125,336,221 2024-09-19 2 </code></pre> <h5>reproducible df</h5> <pre><code>data = { 'rules': ['rule1', 'rule1', 'rule1', 'rule2', 'rule2', 'rule3', 'rule3'], 'user_list': ['123,244,344', '125,346,421', '125,343,431', '125,344,423', '125,346,421', '125,348,331', '125,336,221'], 'event_time': ['2024-09-20', '2024-09-19', '2024-09-18', '2024-09-20', '2024-09-19', '2024-09-20', '2024-09-19'], 'row_number': [1, 2, 3, 1, 2, 1, 2] } data = pd.DataFrame(data) data['event_time'] = pd.to_datetime(data['event_time']) </code></pre> <p>I am trying to build another column that counts/finds the number of user_ids from the latest rule rows (where row_number = 1) that are in other rows within the past day and where the rule is a different rule (so count duplicate users that fired on different rules within the past day).</p> <p>the final table should look like this:</p> <pre><code>rules user_list event_time row_number dupe_users rule1 123,244,344 2024-09-20 1 344 rule1 125,346,421 2024-09-19 2 125,125,346,421 rule1 125,343,431 2024-09-18 3 125 rule2 125,344,423 2024-09-20 1 125,344 rule2 125,346,421 2024-09-19 2 125,125,346,421 rule3 125,348,331 2024-09-20 1 125,125 rule3 125,336,221 2024-09-19 2 125,125 </code></pre> <p>ex: user 344 was seen on rule1 2024-09-20 and on rule2 on 2024-09-20.</p>
<python><pandas>
2024-09-20 16:13:54
1
693
max
79,007,387
3,258,380
Python 3 superclass instantiation via derived class's default constructor
<p>In this code:</p> <pre><code>class A(): def __init__(self, x): self.x = x def __str__(self): return self.x class B(A): def __str__(self): return super().__str__() b = B(&quot;Hi&quot;) print(b) </code></pre> <p>The output is: <code>Hi</code>.</p> <p>What is happening under the hood? How does the default constructor in the derived class invoke the super class constructor? How are the params passed to the derived class object get mapped to those of the super class?</p>
<python><python-3.x>
2024-09-20 15:23:32
2
698
Aroonalok
79,007,264
1,084,684
Upload large files (multipart) with md5 verification, using same code for both AWS S3 and Alibaba OSS?
<p>I'm hoping to upload (potentially) large files (up to 5 Gig) to both Amazon S3 and Alibaba OSS, with verification - preferably MD5 verification.</p> <p>My code currently looks like:</p> <pre><code>#!/usr/bin/env python3.10 &quot;&quot;&quot; This toy program is an exploration of how to do verified, multipart file uploads to AWS S3 and Alibaba OSS. It's a modified version of https://stackoverflow.com/questions/58921396/boto3-multipart-upload-and-md5-checking &quot;&quot;&quot; import os import sys import hashlib import boto3 from botocore.exceptions import ClientError from botocore.client import Config from boto3.s3.transfer import TransferConfig chunk_size = 2**23 # This function is a re-worked function taken from here: https://stackoverflow.com/questions/43794838/multipart-upload-to-s3-with-hash-verification # Credits to user: https://stackoverflow.com/users/518169/hyperknot def calculate_s3_etag(file_path, chunk_size=chunk_size): &quot;&quot;&quot;Calculate an S3/OSS etag for the file.&quot;&quot;&quot; chunk_md5s = [] with open(file_path, &quot;rb&quot;) as fp: while True: data = fp.read(chunk_size) if not data: break chunk_md5s.append(hashlib.md5(data)) num_hashes = len(chunk_md5s) if not num_hashes: # do whatever you want to do here raise ValueError if num_hashes == 1: return f&quot;{chunk_md5s[0].hexdigest()}&quot; digest_byte_string = b&quot;&quot;.join(m.digest() for m in chunk_md5s) digests_md5 = hashlib.md5(digest_byte_string) return f&quot;{digests_md5.hexdigest().lower()}-{num_hashes}&quot; def s3_md5sum(bucket_name, resource_name, client): &quot;&quot;&quot;Calculate an MD5 hash for the file.&quot;&quot;&quot; try: et = client.head_object(Bucket=bucket_name, Key=resource_name)[&quot;ETag&quot;] assert et[0] == '&quot;' and et[-1] == '&quot;' return et[1:-1].lower() except ClientError: # do whatever you want to do here raise ClientError def upload_one_file( *, filename, endpoint_url, aws_credentials, aws_region, bucket, addressing_style=None, ): &quot;&quot;&quot;Upload one file to S3. The file can be up to 5 gigabytes in size, and will be verified on upload.&quot;&quot;&quot; config = {} config[&quot;region_name&quot;] = aws_region if addressing_style: config[&quot;s3&quot;] = {&quot;addressing_style&quot;: addressing_style} kwargs = {&quot;config&quot;: Config(**config), **aws_credentials} if endpoint_url: kwargs[&quot;endpoint_url&quot;] = endpoint_url client = boto3.client(&quot;s3&quot;, **kwargs) transfer_config = TransferConfig(multipart_chunksize=chunk_size) client.upload_file(filename, bucket, filename, Config=transfer_config) tag = calculate_s3_etag(filename) result = s3_md5sum(bucket, filename, client) return (tag, result) class AuthorizationData: &quot;&quot;&quot;Hold things about what S3/OSS to use.&quot;&quot;&quot; def __init__( self, *, name, bucket, aws_region, aws_access_key_id, aws_secret_access_key, endpoint_url=None, addressing_style=None ): &quot;&quot;&quot;Initialize.&quot;&quot;&quot; self.name = name self.endpoint_url = endpoint_url self.bucket = bucket self.aws_region = aws_region # self.aws_credentials = aws_credentials self.aws_credentials = { &quot;aws_access_key_id&quot;: aws_access_key_id, &quot;aws_secret_access_key&quot;: aws_secret_access_key, } self.addressing_style = addressing_style def create_test_inputs(): &quot;&quot;&quot;Create test files.&quot;&quot;&quot; for filename, blocksize, total_size in ( (&quot;dastromberg-urandom-1k&quot;, 2**10, 2**10), (&quot;dastromberg-urandom-16M&quot;, 2**20, 2**24), (&quot;dastromberg-urandom-256M&quot;, 2**20, 2**28), (&quot;dastromberg-urandom-1G&quot;, 2**20, 2**30), (&quot;dastromberg-urandom-5G&quot;, 2**20, 5 * 2**30), ): if not os.path.isfile(filename): length_written = 0 print(&quot;Creating test input %s&quot; % filename) with ( open(&quot;/dev/urandom&quot;, &quot;rb&quot;) as infile, open(filename, &quot;wb&quot;) as outfile, ): while length_written &lt; total_size: block = infile.read(blocksize) outfile.write(block) len_block = len(block) assert blocksize == len_block length_written += len_block assert length_written == total_size assert os.path.getsize(filename) == total_size, &quot;Final length does not match. Perhaps remove %s and try again?&quot; % filename def main(): &quot;&quot;&quot;Test some AWS S3- and Alibaba OSS-use.&quot;&quot;&quot; # This works. aws = AuthorizationData( name=&quot;AWS&quot;, bucket=&quot;aaa&quot;, aws_region=&quot;us-west-2&quot;, aws_access_key_id=&quot;bbb&quot;, aws_secret_access_key=os.environ[&quot;aws_secret_key&quot;], ) alibaba = AuthorizationData( name=&quot;Alibaba&quot;, # endpoint_url=&quot;https://blz-p-cdn-gamepublishing.oss-cn-hangzhou.aliyuncs.com/&quot;, endpoint_url=&quot;https://oss-cn-hangzhou.aliyuncs.com&quot;, bucket=&quot;ccc&quot;, aws_region=&quot;cn-hangzhou&quot;, aws_access_key_id=&quot;ddd&quot;, aws_secret_access_key=os.environ[&quot;alibaba_secret_key&quot;], addressing_style=&quot;virtual&quot;, ) all_good = True create_test_inputs() for auth in ( aws, alibaba, ): for filename in ( &quot;dastromberg-urandom-1k&quot;, &quot;dastromberg-urandom-16M&quot;, &quot;dastromberg-urandom-256M&quot;, # &quot;dastromberg-urandom-1G&quot;, # &quot;dastromberg-urandom-5G&quot;, ): print(f&quot;Checking {auth.name}: {filename}&quot;) (tag, result) = upload_one_file( filename=filename, endpoint_url=auth.endpoint_url, aws_credentials=auth.aws_credentials, aws_region=auth.aws_region, bucket=auth.bucket, addressing_style=auth.addressing_style, ) if tag == result: print(&quot;Verification succeeded: %s, %s&quot; % (tag, result)) else: all_good = False print(&quot;Verification failed: %s, %s&quot; % (tag, result), file=sys.stderr) if all_good: print(&quot;All tests passed&quot;) else: print(&quot;One or more tests failed&quot;, file=sys.stderr) sys.exit(1) if __name__ == &quot;__main__&quot;: main() </code></pre> <p>Running it, AWS S3 verifies for all test inputs, but Alibaba only verifies for the 1 kilobyte test - the 16 megabyte test fails, as do the larger tests.</p> <p>In <a href="https://www.alibabacloud.com/help/en/oss/use-cases/can-i-use-etag-values-as-oss-md5-hashes-to-check-data-consistency" rel="nofollow noreferrer">https://www.alibabacloud.com/help/en/oss/use-cases/can-i-use-etag-values-as-oss-md5-hashes-to-check-data-consistency</a> Alibaba says that they don't recommend using MD5 for verification.</p> <p>In <a href="https://www.alibabacloud.com/help/en/oss/use-cases/check-data-transmission-integrity-by-using-crc-64" rel="nofollow noreferrer">https://www.alibabacloud.com/help/en/oss/use-cases/check-data-transmission-integrity-by-using-crc-64</a> they seem to relatively thoroughly explore using x-oss-hash-crc64ecma. I'd rather use MD5 (with boto3), but can use crc64ecma if necessary (hopefully with boto3 still).</p> <p>Has anyone explored this?</p> <p>Any suggestions?</p>
<python><amazon-web-services><amazon-s3><boto3><alibaba-cloud-oss>
2024-09-20 14:49:17
1
7,243
dstromberg
79,007,232
485,337
How to create a factory function that preserves generic type information in Python?
<p>I have the following function that returns a class with a generic type parameter:</p> <pre class="lang-py prettyprint-override"><code>T = TypeVar('T') def create_property(event_bus: EventBus): class Property(Generic[T]): def __init__(self, validator: Callable[[T], bool]): self._validator = validator def __set_name__(self, obj: Any, name: str): self.name = name def __get__(self, obj: Any, type: Any) -&gt; T: return obj.__dict__.get(self.name) def __set__(self, obj: Any, value: T): if not self._validator(value): raise ValueError(&quot;Invalid value&quot;) obj.__dict__[self.name] = value event_bus.publish() return Property </code></pre> <p>What I'm trying to do here is to create a class that has an <code>EventBus</code> bound to it so that I don't have to pass it as a constructor parameter.</p> <p>My problem with the above code is that this will resolve to <code>Property[Any]</code> instead of <code>Property[T]</code> so the generic is lost somewhere along the way. How can I fix this function to preserve the generic?</p>
<python><generics><python-typing>
2024-09-20 14:38:10
1
30,760
Adam Arold
79,007,161
457,290
can columns be kept in ruamel.yaml?
<p>I'm reading a YAML file, manipulating it and dumping it again with <a href="https://pypi.org/project/ruamel.yaml/" rel="nofollow noreferrer"><code>ruamel.yaml</code></a>. I'd like to get it as much human readable as it was before. That requires some tables to be kept in columns.</p> <p>This is a short example of what I need. I'd like the output to be in columns as in the input.</p> <pre class="lang-py prettyprint-override"><code>In [1]: import sys In [2]: from ruamel.yaml import YAML In [3]: yaml = YAML() In [4]: tabs = &quot;&quot;&quot; ...: vals: ...: 0: { 0: 1, 1: 2, 2: 3 } ...: 1: { 0: 12, 1: 2.3, 2: -1.4} ...: &quot;&quot;&quot; In [5]: yaml.dump(yaml.load(tabs), sys.stdout) vals: 0: {0: 1, 1: 2, 2: 3} 1: {0: 12, 1: 2.3, 2: -1.4} </code></pre> <p>Can that be done?</p> <hr /> <p>Python code for reference:</p> <pre class="lang-py prettyprint-override"><code>import sys from ruamel.yaml import YAML yaml = YAML() tabs = &quot;&quot;&quot; vals: 0: { 0: 1, 1: 2, 2: 3 } 1: { 0: 12, 1: 2.3, 2: -1.4} &quot;&quot;&quot; yaml.dump(yaml.load(tabs), sys.stdout) </code></pre>
<python><ruamel.yaml>
2024-09-20 14:19:56
1
2,019
matiasg
79,007,120
2,130,515
How tox create a fresh environments
<p>Here is my workflow:</p> <p>I have a requirements.txt file that includes tox and many other packages.</p> <p>Run:</p> <pre><code> python3 -m venv global_env source global_env/bin/activate pip install -r requirements </code></pre> <p>I create a tox.ini as following and I call all the different env in the jenkinsfile which is really very nice:</p> <pre><code>[tox] envlist = py3.10.12, linter, unit-tests, docs skipsdist = true [testenv] allowlist_externals = pytest, sphinx-build deps = -rrequirements.txt [testenv:linter] description = Run Black linter deps = black commands = black mtqe/ --check [testenv:unit-tests] description = Run unit tests deps = {[testenv]deps} commands = pytest ./tests/ --disable-warnings </code></pre> <p>My understading is that tox will create a completly fresh environments and run the tests. However, it is not the case. All environments inherits from the global_env and I test that my removing some packages from the requirements.txt and I expect that some unit tests should fail but it does not fail. What is wrong in my understanding. How tox create an isolated environments then ?</p>
<python><unit-testing><pytest><tox>
2024-09-20 14:10:14
1
1,790
LearnToGrow
79,007,107
4,352,047
Langchain FastEmbed with ChromaDB
<p>I'm trying to follow a simple example I found of using Langchain with FastEmbed and ChromaDB. I will eventually hook this up to an off-line model as well. I believe I have set up my python environment correctly and have the correct dependencies. Just am I doing something wrong with how I'm using the embeddings and then calling Chroma.from_documents?</p> <pre><code>from langchain_community.embeddings.fastembed import FastEmbedEmbeddings from langchain_community.document_loaders import PyPDFLoader from langchain_community.vectorstores.utils import filter_complex_metadata from langchain_community.vectorstores import Chroma from langchain.text_splitter import RecursiveCharacterTextSplitter import glob class ChatPDF: vector_store = None retriever = None chain = None def __init__(self): self.embeddings = FastEmbedEmbeddings() self.text_splitter = RecursiveCharacterTextSplitter(chunk_size=1024, chunk_overlap=100) def ingest(self, file_path: str): doc = PyPDFLoader(file_path=file_path).load() chunks = self.text_splitter.split_documents(doc) chunks = filter_complex_metadata(chunks) # generate vector store vector_store = Chroma.from_documents(documents=chunks, embedding=self.embeddings) new_chat = ChatPDF() docs_to_process = glob.glob(&quot;tmp/*.pdf&quot;) for pdf in docs_to_process: new_chat.ingest(file_path=pdf) </code></pre> <p>When I run it however, I get the following:</p> <pre><code>Traceback (most recent call last): File &quot;/Users/c/Documents/Code/embeddings-test.py&quot;, line 35, in &lt;module&gt; new_chat.ingest(file_path=pdf) File &quot;/Users/c/Documents/Code/embeddings-test.py&quot;, line 26, in ingest vector_store = Chroma.from_documents(documents=chunks, embedding=self.embeddings) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File &quot;/Users/c/Documents/Code/.venv/lib/python3.12/site-packages/langchain_community/vectorstores/chroma.py&quot;, line 878, in from_documents return cls.from_texts( ^^^^^^^^^^^^^^^ File &quot;/Users/c/Documents/Code/.venv/lib/python3.12/site-packages/langchain_community/vectorstores/chroma.py&quot;, line 842, in from_texts chroma_collection.add_texts(texts=texts, metadatas=metadatas, ids=ids) File &quot;/Users/c/Documents/Code/.venv/lib/python3.12/site-packages/langchain_community/vectorstores/chroma.py&quot;, line 277, in add_texts embeddings = self._embedding_function.embed_documents(texts) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File &quot;/Users/c/Documents/Code/.venv/lib/python3.12/site-packages/langchain_community/embeddings/fastembed.py&quot;, line 117, in embed_documents embeddings = self._model.embed( ^^^^^^^^^^^^^^^^^ AttributeError: 'NoneType' object has no attribute 'embed' </code></pre>
<python><py-langchain><chromadb>
2024-09-20 14:06:20
2
379
Deftness
79,006,887
1,117,028
Regular expression to match contents of double brackets containing other groups of double brackets
<p>I would like to clean-up raw data from a Wiktionary dump. Here are two usecases.</p> <p>Multilines:</p> <pre><code>[[Archivo:Diagrama bicicleta.svg|400px|miniaturadeimagen|'''Partes de una bicicleta:'''&lt;br&gt; [[asiento]] o [[sillín]], [[cuadro]]{{-sub|8}}, [[potencia]], [[puño]]{{-sub|4}}, [[cuerno]], [[manubrio]], [[telescopio]], [[horquilla]], [[amortiguador]], [[frenos]], [[tijera]], [[rueda]], [[rayos]], [[buje]], [[llanta]], [[cubierta]], [[válvula]], [[pedal]], [[viela]], [[cambio]], [[plato]]{{-sub|5}} o [[estrella]], [[piñón]], [[cadena]], [[tija]], [[tubo de asiento]], [[vaina]].]] + [[ something|of course]] </code></pre> <p>Single line:</p> <pre><code>[[File:Karwats.jpg|thumb|A scourge ''(noun {{senseno|en|whip}})'' [[exhibit#Verb|exhibited]] in a [[museum#Noun|museum]].]] + [[ something|of course]] </code></pre> <p>In both cases, I need to match only what is inside <code>[[Archivo:xxx]]</code> and <code>[[File:xxx]]</code> where both can be multilines statement, and include nested double-bracket code that need to go away too.</p> <p>It's not my <a href="https://github.com/BoboTiG/ebook-reader-dict/issues/1716" rel="nofollow noreferrer">first attempt</a> haha, I retry on a regular basis, but I can't make it work alone!</p> <p>Here is my current regexp, which will match the whole line (and in both examples, the regexp should leave alone the trailing <code> + [[ something|of course]]</code>).</p> <pre><code>\[\[(?:Archivo|File):(?:.|\n)+?(?=\]\])\]\]$ </code></pre> <hr /> <p>Note: I can produce some code without using a regexp, but meh, it would be shorter to find that magic pattern!</p>
<python><regex>
2024-09-20 13:07:49
1
7,220
Tiger-222
79,006,776
4,443,260
AssertionError when launching python via systemd
<p>I seem to be getting an AssertionError with my Python script, but only when I launch it through <code>systemd</code>. Otherwise, it works fine if launched manually from the command line. I thought perhaps it's a permissions thing, but it also runs fine being manually executed as root.</p> <p><a href="https://i.sstatic.net/B8OqEDzu.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/B8OqEDzu.png" alt="enter image description here" /></a></p> <p>This is the error. The python file this error is in can be found here: <a href="https://github.com/lericson/mavlink-tools/tree/master" rel="nofollow noreferrer">https://github.com/lericson/mavlink-tools/tree/master</a>, I'm using the <code>logdl.py</code>.</p> <p>I'm almost certain this is not an issue with the actual Python itself as it runs perfectly fine being ran manually from command line. Any ideas? A quick Google revealed a bug with old pipenv but I made sure mine is all up to date.</p> <p>The <code>systemd</code> service:</p> <pre><code>[Unit] Description=Logger Service After=network-online.target [Service] ExecStart=/home/logger/start_logger.sh [Install] WantedBy=multi-user.target </code></pre> <p><code>start_logger.sh</code>:</p> <pre><code>#!/bin/sh /home/logger/.venv/bin/python3 /home/logger/logger/main.py </code></pre> <p>From here, <code>main.py</code> waits until it detects the flight controller device. It then launches <code>logdl.py</code> as a subprocess and waits for it to finish. It also blinks an LED so the user knows when the download has finished, then waits until the flight controller is removed before looping back to detecting it again.</p> <p><strong>UPDATE:</strong></p> <p>I removed the shell script from the process, realised it was probably unnecessary. Now, the service file calls <code>/home/logger/.venv/python3 /home/logger/logger/main.py</code> itself. However, now it logs with a serial exception every single time a Flight Controller is connected.</p> <p>Error now:</p> <p><code>serial.serialutil.SerialException: device reports readiness to read but returned no data (device disconnected or multiple access on port?)</code></p> <p>Once again, error is not present running the service command manually in the terminal. It's only present running it as a service</p>
<python><service><systemd><mavlink>
2024-09-20 12:37:39
1
923
Kris Rice
79,006,736
22,466,650
How to make a function accessible from both the object and the class itself?
<p>I have a simple class called <code>Storage</code> that has many methods and properties.</p> <p>For this question, I'm only interested in making <code>uniques</code> a classmethod and a property in the same time. I don't know if this is possible. I wonder if there is a dynamic processing : based on if <code>uniques</code> is being called from the class or an object, then we should always have the same result for the same input used (here it's <code>data</code>).</p> <pre><code>class Storage: def __init__(self, data): self.data = data @classmethod def uniques(cls, data=None): if data is None: data = cls.data return [list(set(item)) for item in data] </code></pre> <p>Unfortunately, when I try doing both calls one is working but the second one gives error :</p> <pre><code>data = [[&quot;apple&quot;, &quot;banana&quot;, &quot;apple&quot;], [&quot;cat&quot;, &quot;dog&quot;, &quot;dog&quot;], [&quot;red&quot;, &quot;blue&quot;, &quot;red&quot;]] print(Storage.uniques(data)) # [[&quot;banana&quot;, &quot;apple&quot;], [&quot;cat&quot;, &quot;dog&quot;], [&quot;blue&quot;, &quot;red&quot;]] ######################################## print(Storage(data).uniques()) 5 @classmethod 6 def uniques(cls, data=None): 7 if data is None: ----&gt; 8 data = cls.data 9 return [list(set(item)) for item in data] AttributeError: type object 'Storage' has no attribute 'data' </code></pre> <p>Can you guys show me how to deal with that ? Is this even possible ?</p>
<python><class><oop>
2024-09-20 12:27:15
3
1,085
VERBOSE
79,006,642
6,930,340
Multiply elements of list column in polars dataframe with elements of regular python list
<p>I have a <code>pl.DataFrame</code> with a column comprising lists like this:</p> <pre><code>import polars as pl df = pl.DataFrame( { &quot;symbol&quot;: [&quot;A&quot;, &quot;A&quot;, &quot;B&quot;, &quot;B&quot;], &quot;roc&quot;: [[0.1, 0.2], [0.3, 0.4], [0.5, 0.6], [0.7, 0.8]], } ) shape: (4, 2) ┌────────┬────────────┐ │ symbol ┆ roc │ │ --- ┆ --- │ │ str ┆ list[f64] │ ╞════════╪════════════╡ │ A ┆ [0.1, 0.2] │ │ A ┆ [0.3, 0.4] │ │ B ┆ [0.5, 0.6] │ │ B ┆ [0.7, 0.8] │ └────────┴────────────┘ </code></pre> <p>Further, I have a regular python list <code>weights = [0.3, 0.7]</code></p> <p>What's an efficient way to multiply <code>pl.col(&quot;roc&quot;)</code> with <code>weights</code> in a way where the first and second element of the column will be multiplied with the first and second element of <code>weights</code>, respectively?</p> <p>The expected output is like this:</p> <pre><code>shape: (4, 3) ┌────────┬────────────┐──────────────┐ │ symbol ┆ roc │ roc_wgt │ │ --- ┆ --- │ --- │ │ str ┆ list[f64] │ list[f64] │ ╞════════╪════════════╡══════════════╡ │ A ┆ [0.1, 0.2] │ [0.03, 0.14] │ = [0.1 * 0.3, 0.2 * 0.7] │ A ┆ [0.3, 0.4] │ [0.09, 0.28] │ = [0.3 * 0.3, 0.4 * 0.7] │ B ┆ [0.5, 0.6] │ [0.15, 0.42] │ = [0.5 * 0.3, 0.6 * 0.7] │ B ┆ [0.7, 0.8] │ [0.21, 0.56] │ = [0.7 * 0.3, 0.8 * 0.7] └────────┴────────────┘──────────────┘ </code></pre>
<python><dataframe><list><python-polars>
2024-09-20 11:58:52
4
5,167
Andi
79,006,506
3,218,338
Google Cloud Speech-To-Text tagging requests for billing purposes
<p>I am looking to reduce the amount of hassle we get by managing multiple customers within the same app. Today we're using service account JSON files for authentication, one file for each customer. We do this to separate billing accordingly. This basically means that each customer is its own project within the Google Cloud Console.</p> <p>My wish is that we would have one account, and one JSON file for all customers. But in order to successfully to this and track the cost within the Google Console Billing I need each request to be tagged so that it can be filtered. This is a requirement from billing &amp; management to be able to track and see the cost of each project/customer.</p> <p>Here's an example of our authentication and Speech-2-Text request.</p> <pre><code>from google.oauth2 import service_account from google.cloud import speech auth = service_account.Credentials.from_service_account_file(&quot;project-A-Customer10050.json&quot;) client = speech.SpeechClient(credentials=auth) config = speech.RecognitionConfig( encoding=speech.RecognitionConfig.AudioEncoding.LINEAR16, enable_automatic_punctuation=False, audio_channel_count=1, language_code=&quot;en-US&quot;, model=&quot;default&quot;, speech_contexts=[{'phrases': [&quot;Hint X&quot;, &quot;Hint Y&quot;]}] ) client.recognize(request={&quot;config&quot;: config, &quot;audio&quot;: &quot;audio.wav&quot;}) </code></pre> <p>Does anyone know if this can be achieved? Or suggest an alternative solution to our problem?</p>
<python><google-cloud-platform><speech-recognition>
2024-09-20 11:15:55
0
682
user3218338
79,006,487
10,639,382
Plotly Chlorepath Map Subplot
<p>I have geopandas dataframe as show below. I want to create subplots where each subplot would have a map.</p> <p>I managed to do a Single plot using plotly express</p> <pre><code>p4 = px.choropleth(s_new_cp, geojson=s_new_cp.geometry, color = &quot;usage&quot;, locations = s_new_cp.index) p4.update_geos(fitbounds=&quot;locations&quot;, visible = False) </code></pre> <p>But can't get it to work using subplot. How can I plot maps within subplots ?</p> <pre><code>p5 = make_subplots(rows = 1, cols = 2, specs = [[{&quot;type&quot;:&quot;mapbox&quot;},{&quot;type&quot; :&quot;mapbox&quot;}]]) p5.add_trace(go.Choroplethmapbox( geojson=s_new_cp.geometry, locations = s_new_cp.index, z = s_new_cp.usage ), row = 1, col = 1) &gt;&gt;&gt; TypeError: Object of type Polygon is not JSON serializable </code></pre> <p>DataFrame : s_new_cp</p> <pre><code>print(s_new_cp) area new usage n_obs y estimate geometry 0 BARINGO 1 0.347646 0 0 0.000000 POLYGON ((35.7839 1.65557, 35.78496 1.65554, 3... 1 BOMET 1 0.816969 0 0 0.000000 POLYGON ((35.4736 -0.3992, 35.47845 -0.40663, ... 2 BUNGOMA 1 0.465844 29 29 0.227280 POLYGON ((34.62017 1.10228, 34.62133 1.1016, 3... 3 BUSIA 1 0.713608 40 39 0.445942 POLYGON ((34.36097 0.7773, 34.36172 0.77696, 3... 4 ELGEYO MARAKWET 1 0.168763 1 0 0.027333 POLYGON ((35.69818 1.28225, 35.69788 1.27905, ... </code></pre>
<python><plotly>
2024-09-20 11:10:08
0
3,878
imantha
79,006,427
3,976,229
SQLModel how to find foreign_key information while introspecting SQLModel classes?
<p>I am looping through my SQLModel classes, extracting the field info, and creating a .dbml format file from the details. This works great, except trying to find the foreign_key information in the fields. Here is an example of an SQLModel classes:</p> <pre><code> class Account(PostgresBase, table=True): __tablename__ = 'accounts' id: str = Field(default_factory=lambda: genb58_id(22, &quot;account&quot;), primary_key=True, index=True, nullable=False) first_name: str = Field(index=True) last_name: str = Field(index=True) username: str = Field(index=True, unique=True) # ----- Relationships ----- some_activity_records: list[&quot;SomeActivity&quot;] = Relationship( back_populates=&quot;account&quot;) class SomeActivity(PostgresBase, table=True): __tablename__ = 'some_activity_recs' id: str = Field(default_factory=lambda: genb58_id(22, &quot;activity&quot;), primary_key=True, index=True, nullable=False) name: str type: Union[dict, None] = Field(sa_type=JSON) fk_account_id: Union[str, None] = Field( default=None, foreign_key=&quot;accounts.id&quot;) things: list[str] = Field(sa_type=ARRAY(String), default=[]) # ----- Relationships ----- account: Union[&quot;Account&quot;, None] = Relationship( back_populates=&quot;some_activity_records&quot;) </code></pre> <p>How can I tease out the foreign_key info that the SomeActivity fk_account_id field is linked to the table+field <code>accounts.id</code>?</p> <p>Here is the script I am running to get the fields and the relationships:</p> <pre><code>import inspect from sqlmodel import SQLModel import sys import types import typing from typing import get_args from models import * # Get all classes from models.py that are subclasses of SQLModel. models = [obj for name, obj in inspect.getmembers(sys.modules[__name__]) if inspect.isclass(obj) and issubclass(obj, SQLModel) and obj != SQLModel] # Generate dbml for each model. dbml_content = &quot;&quot; for model in models: # Extract class docstring. doc = inspect.getdoc(model).replace('\n', ' ') if doc.startswith(&quot;Usage docs&quot;): doc = None # Build the table definition. dbml_content = f&quot;Table {model.__tablename__} {{\n&quot; dbml_content += f&quot; // {doc}\n&quot; if doc else &quot;&quot; # Build the field lines. for key in model.model_fields.keys(): fieldstr = f&quot; {key}&quot; field_info = model.model_fields[key] annotation = field_info.annotation match type(annotation): case t if t == type: type_name = annotation.__name__ if type_name == &quot;str&quot;: type_name = &quot;varchar&quot; opts = &quot;&quot; if key == &quot;id&quot;: opts = &quot;[pk, unique, not null]&quot; fieldstr += f&quot; {type_name} {opts}&quot; case t if t == typing._UnionGenericAlias: args = get_args(annotation) arg_name = args[0].__name__ match arg_name: case &quot;dict&quot;: arg_name = &quot;json&quot; case &quot;str&quot;: arg_name = &quot;varchar&quot; fieldstr += f&quot; {arg_name}&quot; case t if t == types.GenericAlias: fieldstr += f&quot; varchar[]&quot; case t if t == typing._LiteralGenericAlias: args = get_args(annotation) fieldstr += f&quot; varchar //{args}&quot; dbml_content += fieldstr + &quot;\n&quot; dbml_content += &quot;}\n\n&quot; # Add relationships. relationships = [] for model in models: for field in model.model_fields.values(): if 'foreign_key' in field.metadata: fk = field.metadata['foreign_key'] if fk: ref_table, ref_field = fk.split('.') relationships.append( f'Ref: &quot;{model.__tablename__}&quot;.&quot;{field.name}&quot; &lt; &quot;{ref_table}&quot;.&quot;{ref_field}&quot;\n') dbml_content += ''.join(relationships) print(dbml_content) </code></pre> <p>The &quot;Generate dbml for each model.&quot; loop works great and creates an appropriate dbml, eg:</p> <pre><code>Table accounts { id varchar [pk, unique, not null] first_name varchar last_name varchar username varchar } Table some_activity_recs { id varchar [pk, unique, not null] name varchar type json fk_account_id varchar things varchar[] } </code></pre> <p>However, when I run the section to &quot;Add relationships.&quot;, the <code>field.metadata</code> is always an empty list, even when inspecting the <code>fk_account_id</code> field.</p> <p>I have tried to use the <code>field.foreign_key</code> member, which should exist in SQLModel FieldInfo class, but it gives me the following traceback:</p> <pre><code>***** model.__name__: Account ***** type(model): &lt;class 'sqlmodel.main.SQLModelMetaclass'&gt; ***** field.foreign_key: PydanticUndefined Traceback (most recent call last): File &quot;/soc-api/./soc/dao/scripts/create_dbml.py&quot;, line 86, in &lt;module&gt; print(f&quot;***** field.foreign_key: {field.foreign_key}&quot;) ^^^^^^^^^^^^^^^^^ AttributeError: 'FieldInfo' object has no attribute 'foreign_key' </code></pre>
<python><sqlmodel>
2024-09-20 10:49:06
1
362
havoc1
79,006,254
7,499,018
FastHTML fail to load
<p>When loading the <a href="https://www.fastht.ml/" rel="nofollow noreferrer">fastHTML</a> demo example the browser page for <a href="http://0.0.0.0:5001" rel="nofollow noreferrer">http://0.0.0.0:5001</a> shows invalid address:</p> <p>This site can't be reached. ERR_ADDRESS_INVALID Site might be temporarily down...</p>
<python><fasthtml>
2024-09-20 09:53:33
2
487
Martin Cronje
79,006,122
8,790,507
Is there a way to test only a subset of unittests in a jupyter notebook?
<p>I followed the unittest example in this answere here: <a href="https://stackoverflow.com/a/48405555/8790507">https://stackoverflow.com/a/48405555/8790507</a></p> <p>I have two test classes in two cells, so something like:</p> <p>First cell:</p> <pre><code>class TestSuite1(unittest.TestCase): def test_in_suite1(self): pass: </code></pre> <p>Second cell:</p> <pre><code>class TestSuite2(unittest.TestCase): def test_in_suite2(self): pass: </code></pre> <p>Third cell:</p> <pre><code>unittest.main(argv=[''], verbosity=2, exit=False) </code></pre> <p>Now my problem is, that the last cell runs all tests in both test suites. I would like to split the third cell into two, one which tests suite 1, and another that tests suite 2.</p> <p>What do I need to put in <code>argv</code> to achieve this?</p> <p><strong>Edit</strong>: Following a suggestion, I tried <code>unittest.main(argv=['TestSuite2'], verbosity=2, exit=False)</code> to only run suite 2, but as the screenshot below shows, TestSuite2 only has a single test in it, but it's still running the 10 tests in TestSuite1.</p> <p><a href="https://i.sstatic.net/IYOnxJxW.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/IYOnxJxW.png" alt="enter image description here" /></a></p>
<python><unit-testing><jupyter-notebook><python-unittest>
2024-09-20 09:20:33
1
1,594
butterflyknife
79,006,060
9,973,879
Click a button to go to a URL in a Jupyter notebook
<p>I want to be able to open <code>http://example.com</code> when clicking on an <code>ipywidgets.Button</code> (ideally in the same tab).</p> <p>I tried</p> <pre class="lang-py prettyprint-override"><code>def on_click(btn): display(Javascript('window.open(&quot;http://example.com&quot;);')) </code></pre> <p>and</p> <pre class="lang-py prettyprint-override"><code>def on_click(btn): display(Javascript('window.location.href = &quot;http://example.com&quot;;')) </code></pre> <p>as <code>on_click</code> callbacks, but nothing happens when I click the button.</p>
<python><jupyter-notebook><jupyter-lab><ipywidgets>
2024-09-20 09:05:16
1
1,967
user209974
79,005,800
5,507,055
How to show enum keys in OpenAPI?
<p>I use <code>EnumInt</code> and want to show the enum keys at the OpenAPI docs.</p> <pre><code>from enum import IntFlag from pydantic import BaseModel class ResponseCode(IntFlag): request_failed: 1000 request_success: 1001 class Response(BaseModel): success: bool message: str code: ResponseCode </code></pre> <p>But the the OpenAPI shows only:</p> <p><a href="https://i.sstatic.net/26lX95GM.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/26lX95GM.png" alt="OpenAPI" /></a></p> <p>I would like to show the keys and the values together.</p>
<python><enums><fastapi><openapi>
2024-09-20 07:53:37
0
2,845
ikreb
79,005,484
2,192,824
How to dynamically create a protobuf object from string?
<p>I have a protobuf definition like below,</p> <pre><code>message MyProto { optional string ip = 1; optional int32 port = 2; optional Flags flags = 3; } message Flags { optional bool flag1 = 1; optional bool flag2 = 2; } </code></pre> <p>My goal is to create a MyProto object from the below string:</p> <pre><code>ip:127.0.0.1 port:8080 Flags: flag1: True flag2: False </code></pre> <p>I can generate an &quot;empty&quot; object with my_proto = MyProto(), and can set the attribute of it by using</p> <pre><code>setattr(my_proto, &quot;ip&quot;, &quot;127.0.0.1&quot;) setattr(my_proto, &quot;port&quot;, 8080) </code></pre> <p>but cannot figure out how to &quot;fill in&quot; the <code>Flags</code> message into my_proto. Is there any general way to do that? By general way, I mean assume we need to figure out the message name of <code>Flags</code> from the string</p> <pre><code>Flags: flag1: True flag2: False </code></pre> <p>(because there could be other message definitions used in <code>MyProto</code>)</p>
<python><protocol-buffers>
2024-09-20 06:26:10
0
417
Ames ISU
79,005,424
12,035,739
Why do I get a value error while creating a ragged array but only for a certain shape?
<pre class="lang-py prettyprint-override"><code>import numpy as np for h in range(10): try: array = np.array([np.zeros((h, 4)), np.zeros((3, h))], dtype=object) except ValueError: print(f'Value Error for h={h} only.') </code></pre> <p>In the above code, <code>ValueError</code> only happens for <code>h=3</code>. This seems arbitrary.</p> <p>The full error being,</p> <pre><code> File &quot;path/to/arr.py&quot;, line 4, in &lt;module&gt; array = np.array([np.zeros((h, 4)), np.zeros((3, h))], dtype=object) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ValueError: could not broadcast input array from shape (3,4) into shape (3,) </code></pre> <p>How may I avoid this and why does this happen?</p>
<python><numpy>
2024-09-20 06:07:16
1
886
scribe
79,005,356
3,404,377
Can I load docutils nodes directly as an XML file?
<p>A <a href="https://docutils.sourceforge.io/docs/ref/doctree.html" rel="nofollow noreferrer">docutils document</a> is based on a hierarchy of nodes. They say throughout that the nodes are XML (or at least XML-like) and there are ways to dump documents and document fragments in XML format. They even produce a <a href="https://docutils.sourceforge.io/docs/ref/docutils.dtd" rel="nofollow noreferrer">DTD</a> describing an XML document format for nodes.</p> <p>I want to generate docutils nodes using a non-Python tool, serialize them into a machine-readable format, then load them with docutils (as part of a Sphinx plugin).</p> <p>I tried to find a way to load either a full XML document or an XML fragment (in the DTD-specified format) and get back a node tree, but I can't find anything. Is there any way to read the docutils XML format back into nodes, that is, the reverse of <code>Node.asdom()</code>?</p> <p>More generally, is there any machine-readable format that I can load with docutils that describes a node tree? Either something based on XML or some other format?</p>
<python><xml><python-sphinx><docutils>
2024-09-20 05:36:18
1
1,131
ddulaney
79,005,148
1,530,967
What does `get_type_analyze_hook` return in a MyPy plugin that handles subtypes created by __class_getitem__ and recapitulate the __subclasshook__?
<p>(NB: repost of a question that was deemed not specific enough and then auto-deleted before I got a chance to revise it)</p> <p><strong>Background tl;dr</strong></p> <p>I contribute to a scientific worklow engine called <a href="https://pydra.readthedocs.io/en/latest/" rel="nofollow noreferrer">Pydra</a>, which utilises Python typing annotations to provide dynamic type-checking at workflow construction time. It also uses these annotations to know which inputs are are files/directories so their contents can be included in hashes used in the internal cache.</p> <p>Addressing some issues we were having dealing copying around file formats with separate headers led me to write a package for validating/handling different file formats, <a href="https://arcanaframework.github.io/fileformats/" rel="nofollow noreferrer">FileFormats</a>. This also enabled us to include format-validation as part of the dynamic type-checking and register standard converters between some format types.</p> <p>In this package I started using <code>__class_getitem__</code> to specify additional information about the contents of the files, e.g. <code>Gzip[Png]</code> a PNG file that has been gzipped, without reading the warnings about it not being recommended outside the stdlib. However, it has proved to work really well for dynamic typing and I have started using it fairly widely, e.g. <code>DicomSeries[Brain, T1Weighted]</code> a dicom series containing T1-weighted MRI images of a brain. A <code>__subclasshook__</code> is implemented in a mixin class that handles these cases where <code>DicomSeries[Brain, T1Weighted]</code> is considered a subclass of <code>DicomSeries[Brain]</code>, <code>DicomSeries[T1Weighted]</code> and <code>DicomSeries</code>.</p> <p>So I'm really quite happy with how the package works, but... then I tried to see if I could get it to work with static type-checking, specifically Mypy, and found out that I had drifted into the weeds of unrecommended/supported functionality in using <code>__class_getitem__</code> for this purpose.</p> <p><strong>My question</strong></p> <p>So, what I want to know is how to write a plugin with <code>get_type_analyze_hook</code> to quash the warnings about using <code>__class_getitem__</code> for non-generics and to recapitulate the rules in my subclass hook. I didn't get much out of reading the docs for <code>get_type_analyze_hook</code>, what is it meant to do? Do I just need to get it to return a valid type, can I use the logic in my code to do this?</p>
<python><mypy>
2024-09-20 03:59:04
0
594
Tom Close
79,005,098
10,829,044
Modifying range in Traffic light Iconset in Openpyxl
<p>I have a sample data in excel like as below</p> <pre><code>cust_id,avg_purchase 1,0.2 2,0.5 3,100 4,9 5,1 6,31 7,9.5 8, &quot;No purchase&quot; 9, &quot;No purchase&quot; </code></pre> <p>I would like to do the below using Openpyxl</p> <p>a) Insert traffic light symbol for column B that is 'avg_purchse' based on the below criteria</p> <pre><code> if avg_purchase &lt;= 8 then &quot;Yellow&quot; if avg_purchase &gt;8 and avg_purchase &lt;=10 then &quot;green&quot; else (avg_purchase) &gt; 10 then &quot;red&quot; </code></pre> <p>So, I tried the below</p> <pre><code>from openpyxl.formatting.rule import IconSet, FormatObject first = FormatObject(type='num', val=0) second = FormatObject(type='num', val=8) third = FormatObject(type='num', val=10) iconset = IconSet(iconSet='3TrafficLights1', cfvo=[third, second, first], showValue=None, percent=None, reverse=None) # assign the icon set to a rule from openpyxl.formatting.rule import Rule rule = Rule(type='iconSet', iconSet=iconset) sheet.conditional_formatting.add(&quot;B2:B11111&quot;, rule) workbook.save('wb2e.xlsx') </code></pre> <p>However, it doesn't work the way I expect it. May be I don't understand how to define the limits correctly</p> <p>I expect my output to be like as below</p> <p><a href="https://i.sstatic.net/0baEz6yC.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/0baEz6yC.png" alt="enter image description here" /></a></p>
<python><excel><dataframe><openpyxl><conditional-formatting>
2024-09-20 03:34:02
0
7,793
The Great
79,005,032
4,875,641
How to have a pool of Python tasks wait for a wake up event
<p>I have created a pool of Python processes with the multiproccessing.pool function, any of which performs similar work. This is to have more work done simultaneously.</p> <p>I would like all of the tasks to wait on one event/signal/semafore or other object that has the tasks sleeping until signaled. They will perform their work then go back to sleep waiting on that event to trigger again.</p> <p>Other tasks in the program will trigger the event when they have work that needs to be performed.</p> <p>I am not sure what I can use for event posting by other tasks when they need work to be performed. I am not sure how to have these tasks wait on that signal.</p> <p>Using Pool() the tasks are different processes, but they all need to wake up from a common signal of some sort.</p>
<python><events><multiprocessing><wait><wakeup>
2024-09-20 02:44:39
1
377
Jay Mosk
79,005,011
4,451,521
Loading yaml config files twice
<p>I am following and analyzing a code from a course on ML deployment and I found something puzzling. (This question is not related to the ML part of the code)</p> <p>The ML pipeline uses some values that are in a config file. This config file is a yaml file.</p> <p>This yaml file is provided to the scripts that need it through a script called <code>core.py</code>.</p> <p>The structure of this part of the code is like this</p> <pre><code> regression | -----config | \----core.py | |----config.yml | |---train.py |---predict.py </code></pre> <p>So for example <code>train.py</code> or <code>predict.py</code> calls the config values through</p> <p><code>from config.core import config</code> or sometimes <code>from regression.config.core import config</code></p> <p>The <code>core.py</code> file is something like this</p> <pre><code>from pydantic import BaseModel from strictyaml import YAML class Config(BaseModel): value1: str value2: str def ParseConfigFile()-&gt;YAML: # Here some code to parse the yaml file def get_config()-&gt; Config: parsed_config=ParseConfigFile() _config = Config(**parsed_config.data) return _config config = get_config() print(f&quot;Config: {config}&quot;) #-&gt; Originally it was not here </code></pre> <p>When I run the code, at first I did not notice, but after putting the print there, I notice that every time a script imports config, this makes the <code>get_config()</code> function gets called and the yaml read again.</p> <ul> <li>Is this common or usual? Is this not costly since it is reading a yaml file? Or is there a better way to do this and loads the yaml only once? Is that even worth the effort?</li> </ul> <p>And a minor question</p> <ul> <li>Are <code>from config.core import config</code> and <code>from regression.config.core import config</code> equivalent? (this project gets installed with setup.py and tox btw)</li> </ul>
<python><config>
2024-09-20 02:32:09
1
10,576
KansaiRobot
79,004,901
4,577,467
How to pass byte buffer from C++ to Python using SWIG?
<p>I am using SWIG version 4.0.2 in a Windows Subsystem for Linux (WSL) Ubuntu distribution. The C++ class I want to wrap contains an array of bytes (i.e., each item in the array is of type <code>uint8_t</code> or <code>unsigned char</code>). The C++ class has a method whose output parameter is a double pointer, so that the caller can obtain a pointer to that array of bytes.</p> <p>The simple C++ class to wrap is represented by the following header file.</p> <h5>example6.h</h5> <pre><code>#pragma once class Message { private: uint8_t * m_data; int m_size; public: Message( void ) : m_data( NULL ) , m_size( 0 ) { m_data = new uint8_t[3](); m_data[0] = 'A'; m_data[1] = 'B'; m_data[2] = 'C'; m_size = 3; } virtual ~Message( void ) { delete[] m_data; } int package( uint8_t** buf ) { *buf = NULL; int size = 0; if ( m_data ) { *buf = m_data; size = m_size; } return size; } }; </code></pre> <p>The SWIG interface file I use to wrap the C++ code is the following.</p> <h5>example6.swg</h5> <pre><code>%module example6 %{ #define SWIG_FILE_WITH_INIT #include &quot;example6.h&quot; %} %typemap( in, numinputs=0 ) ( uint8_t** buf ) { uint8_t** temp = 0x0; $1 = temp; } %typemap( argout ) ( uint8_t** buf ) { if ( *$1 ) { $result = PyBytes_FromString( (char *)( *$1 ) ); free( *$1 ); } } %include &quot;example6.h&quot; </code></pre> <p>In the SWIG interface file, I am attempting to use appropriate <code>%typemap(in)</code> and <code>%typemap(argout)</code> directives, based on breadcrumbs from several examples. I have several concerns about them and do not know yet if they will work. However, those are not the first obstacle.</p> <p>I am not certain what type of Python variable to provide as the argument for the <code>Message.package()</code> method when I call it. I think I want the variable to be of type <code>bytes</code>. Or, maybe I need additional <code>%typemap</code> directives to correctly convert the Python <code>bytes</code> variable to a C++ <code>uint8_t**</code> variable?</p> <p>The following is a demonstration of the problem.</p> <pre><code>finch@laptop:~/work/swig_example$ python3 Python 3.10.12 (main, Nov 20 2023, 15:14:05) [GCC 11.4.0] on linux Type &quot;help&quot;, &quot;copyright&quot;, &quot;credits&quot; or &quot;license&quot; for more information. &gt;&gt;&gt; import example6 &gt;&gt;&gt; m = example6.Message() &gt;&gt;&gt; b = bytes() &gt;&gt;&gt; b b'' &gt;&gt;&gt; m.package( b ) Traceback (most recent call last): File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt; File &quot;/home/finch/work/swig_example/example6.py&quot;, line 73, in package return _example6.Message_package(self, buf) TypeError: in method 'Message_package', argument 2 of type 'uint8_t **' </code></pre> <p>The <code>TypeError</code> exception is raised in the SWIG-generated <code>example6_wrap.cxx</code> code. The exception happens well before it gets a chance to execute the C++ snippet that the <code>%typemap(argout)</code> directive above injects into it.</p> <h5>example6_wrap.cxx</h5> <pre><code>SWIGINTERN PyObject *_wrap_Message_package(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; Message *arg1 = (Message *) 0 ; uint8_t **arg2 = (uint8_t **) 0 ; void *argp1 = 0 ; int res1 = 0 ; void *argp2 = 0 ; int res2 = 0 ; PyObject *swig_obj[2] ; int result; if (!SWIG_Python_UnpackTuple(args, &quot;Message_package&quot;, 2, 2, swig_obj)) SWIG_fail; res1 = SWIG_ConvertPtr(swig_obj[0], &amp;argp1,SWIGTYPE_p_Message, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), &quot;in method '&quot; &quot;Message_package&quot; &quot;', argument &quot; &quot;1&quot;&quot; of type '&quot; &quot;Message *&quot;&quot;'&quot;); } arg1 = reinterpret_cast&lt; Message * &gt;(argp1); res2 = SWIG_ConvertPtr(swig_obj[1], &amp;argp2,SWIGTYPE_p_p_uint8_t, 0 | 0 ); if (!SWIG_IsOK(res2)) { //*** Finch temp: This is where the TypeError exception will be raised. SWIG_exception_fail(SWIG_ArgError(res2), &quot;in method '&quot; &quot;Message_package&quot; &quot;', argument &quot; &quot;2&quot;&quot; of type '&quot; &quot;uint8_t **&quot;&quot;'&quot;); } arg2 = reinterpret_cast&lt; uint8_t ** &gt;(argp2); result = (int)(arg1)-&gt;package(arg2); resultobj = SWIG_From_int(static_cast&lt; int &gt;(result)); //*** Finch temp: This is the snippet that the %typemap(argout) directive injects. { if ( *arg2 ) { resultobj = PyBytes_FromString( (char *)( *arg2 ) ); free( *arg2 ); } } //*** return resultobj; fail: return NULL; } </code></pre> <h1>Problem 1</h1> <p>What typemap will help me convert a Python <code>bytes</code> variable to a C++ <code>uint8_t**</code> variable.</p> <h1>Problem 2</h1> <p><code>PyBytes_FromString()</code> expects to be given a <code>char const *</code> variable. But the underlying message data in the real C++ library I am wrapping is <code>uint8_t</code>; I am stuck with that. I worry that blindly recasting will cause some byte values to be wrong. Is there another <code>PyBytes_something()</code> function I have not seen?</p> <p>If not, is it appropriate for the <code>%typemap(argout)</code> directive to have a <em>lot</em> more involved code in it, such as iterating the byte buffer and manually copying it to ... something else?</p> <p>I have been searching for and piecing together examples from several places, including:</p> <ul> <li><a href="https://stackoverflow.com/questions/36184402/how-to-apply-a-swig-typemap-for-a-double-pointer-struct-argument">How to apply a SWIG typemap for a double pointer struct argument</a></li> <li><a href="https://stackoverflow.com/questions/13380982/swig-python-wrapping-a-function-that-expects-a-double-pointer-to-a-struct">SWIG Python - wrapping a function that expects a double pointer to a struct</a></li> <li><a href="https://stackoverflow.com/questions/66805415/swig-return-bytes-instead-of-string-with-typemap">SWIG return bytes instead of string with typemap</a></li> <li><a href="https://stackoverflow.com/questions/3660270/swig-typemap-for-python-input-and-output-arrays">swig typemap for python: input and output arrays</a></li> <li><a href="https://stackoverflow.com/questions/69905004/how-do-i-apply-a-swig-typemap-to-only-a-specific-function">How do I apply a SWIG typemap to _only_ a specific function?</a></li> <li><a href="https://stackoverflow.com/questions/38880899/swig-cstring-i-python-return-byte-type-instead-of-string-type">SWIG &#39;cstring.i&#39; Python return byte type instead of string type</a></li> <li><a href="https://docs.python.org/3.10/c-api/bytearray.html" rel="nofollow noreferrer">https://docs.python.org/3.10/c-api/bytearray.html</a></li> <li><a href="https://docs.python.org/3.10/c-api/bytes.html" rel="nofollow noreferrer">https://docs.python.org/3.10/c-api/bytes.html</a></li> </ul>
<python><c++><swig>
2024-09-20 01:13:37
1
927
Mike Finch
79,004,858
1,079,110
How can I wait for a threading event and socket pollin at the same time?
<p>I have a <code>select.poll()</code> object for incoming messages of a socket, and a <code>queue.Queue()</code> object that contains potential outgoing messages.</p> <p>While both objects separately support waiting for a timeout without spending CPU cycles, I need to wait on both at the same time and resume the thread once either of them triggers. Is there a mechanism for that?</p> <p>I have tried waiting on both after another in a loop with very short timeout, but this is basically busy-waiting and ended up costing too much CPU. I have also tried increasing the timeout, which frees up CPU as expected but increases latency too much.</p> <p>It looks like <code>select.poll()</code> can wait on any UNIX file descriptor, so perhaps another way of asking my question is whether there is a <code>queue.Queue()</code> or <code>threading.Event()</code> alternative that exposes a file descriptor that can be polled?</p> <p><strong>Current</strong></p> <pre class="lang-py prettyprint-override"><code>import socket import select import queue import threading socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) socket.connect(('localhost', 4200)) incoming = select.poll() incoming.register(socket, select.POLLIN) outgoing = queue.Queue() while True: if incoming.poll(timeout=0.001): read(socket) try: msg = outgoing.get(block=False, timeout=0.001) send(socket, msg) except queue.Empty: pass </code></pre> <p><strong>Desired</strong></p> <pre class="lang-py prettyprint-override"><code>import socket import queue import threading socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) socket.connect(('localhost', 4200)) outgoing = queue.Queue() poller = HYBRID_POLLER() # TODO poller.register(socket) poller.register(outgoing) while True: available = poller.poll(timeout=1) if socket in available: read(socket) if outgoing in available: msg = outgoing.get(block=False, timeout=0.001) send(socket, msg) </code></pre>
<python><multithreading><sockets><unix>
2024-09-20 00:32:18
1
34,449
danijar
79,004,806
5,937,757
Streamlit (python) App button issue: Showing Previous Number After Button Click Instead of New Random Number
<p>I'm building a simple Streamlit app as a demonstration of a larger project I'm working on. The goal is to display a random number between 0-100 and let the user select whether they &quot;like&quot; the number or not. After the user clicks either &quot;Yes&quot; or &quot;No,&quot; the app should store the number and their response in JSON format and then show a new random number immediately.</p> <p>However, after the user clicks a button, the old number still shows up for another round of selection instead of displaying the next random number. It's only after clicking a button again that a new number appears, but it ends up associating the response with the new number instead of the old one. Below is the simplified example code I'm using:</p> <pre class="lang-py prettyprint-override"><code>import streamlit as st import random import json # Initialize session state to store numbers and user responses in JSON format if &quot;data&quot; not in st.session_state: st.session_state.data = [] # Function to generate the next random number def get_next_number(): return random.randint(0, 100) # Initialize the first number when the app starts if &quot;current_number&quot; not in st.session_state: st.session_state.current_number = get_next_number() # Function to handle the user response def store_response(response): current_number = st.session_state.current_number st.session_state.data.append({&quot;Number&quot;: current_number, &quot;Response&quot;: response}) # Generate the next random number immediately after response st.session_state.current_number = get_next_number() st.title(&quot;Random Number Preference App&quot;) # Display the current number st.write(f&quot;Do you like the number **{st.session_state.current_number}**?&quot;) # Layout for the response buttons col1, col2 = st.columns(2) # Handling &quot;Yes&quot; button click with col1: if st.button(&quot;Yes&quot;): store_response(&quot;Yes&quot;) # Handling &quot;No&quot; button click with col2: if st.button(&quot;No&quot;): store_response(&quot;No&quot;) # Display the stored responses in JSON format if len(st.session_state.data) &gt; 0: st.subheader(&quot;User Responses (JSON Format)&quot;) st.json(st.session_state.data) # Allow the user to download the results as a JSON file json_data = json.dumps(st.session_state.data) st.download_button(label=&quot;Download as JSON&quot;, data=json_data, file_name=&quot;responses.json&quot;, mime=&quot;application/json&quot;) </code></pre> <p><strong>Problem:</strong></p> <ul> <li>After the first number is shown, if the user selects either &quot;Yes&quot; or &quot;No,&quot; the same number is displayed again. <ul> <li>When the next random number is eventually displayed, the previously recorded response (e.g., &quot;Yes&quot; or &quot;No&quot;) is applied to the newly generated number, not the number the user saw when they made the selection.</li> </ul> </li> </ul> <p><strong>Steps to Reproduce the Issue (with Screenshots):</strong></p> <ol> <li><p><strong>Initial Screen:</strong><br /> When the app starts, it immediately shows a random number (e.g., 65). The user is presented with two buttons, &quot;Yes&quot; and &quot;No,&quot; to select if they like the number. <a href="https://i.sstatic.net/9QeQ3ziK.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/9QeQ3ziK.png" alt="enter image description here" /></a></p> </li> <li><p><strong>After Selecting &quot;Yes&quot;:</strong><br /> After pressing the &quot;Yes&quot; button, the app still shows the same number (65). The user can click &quot;Yes&quot; or &quot;No&quot; again, but it seems that the new random number hasn’t appeared yet. <a href="https://i.sstatic.net/KPyknyZG.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/KPyknyZG.png" alt="![Same Number After Click](attachment link)" /></a></p> </li> <li><p><strong>Next Random Number Appears with the Wrong Response:</strong><br /> After pressing &quot;Yes&quot; again, a new random number is finally shown (in this case, 44), but the response (Yes) from the previous selection is now associated with the new number, which is not the expected behavior. <a href="https://i.sstatic.net/6l3uT8BM.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/6l3uT8BM.png" alt="![New Number with Wrong Response](attachment link)" /></a></p> </li> </ol> <p><strong>What I expect:</strong> - When the user clicks a button (either &quot;Yes&quot; or &quot;No&quot;), the next number should immediately appear, and the response should be recorded for the current number, not the next one.</p> <p>I've tried managing state with <code>st.session_state</code> and experimented with <code>st.experimental_rerun()</code> (though my version of Streamlit doesn't support it), but I can't seem to get the app to display a new number right after the button click.</p> <p><strong>Question:</strong> - How can I make the app show the next random number immediately after the user selects their response, while correctly associating the recorded response with the displayed number?</p> <p>Any insights on what I'm missing or alternative approaches would be greatly appreciated!</p>
<python><button><streamlit>
2024-09-19 23:53:29
1
423
mas
79,004,785
7,366,596
Merge intervals based on condition
<p>This is the classical approach to merge intervals:</p> <pre><code>def merge(intervals: List[List[int]]) -&gt; List[List[int]]: result = [] intervals.sort() prev_interval = intervals[0] for curr_interval in intervals[1:]: if prev_interval[1] &gt;= curr_interval[0]: # Check if they overlap prev_interval = [prev_interval[0], max(curr_interval[1], prev_interval[1])] else: result.append(prev_interval) prev_interval = curr_interval result.append(prev_interval) return result </code></pre> <p>I'd like to modify this solution to merge the intervals if 'end' of any interval + 1 is equal to 'start' of any interval in the list.</p> <ul> <li>Ex.1: intervals = [[1,2], [3,4]] ==&gt; [[1,4]]</li> <li>Ex.2: intervals = [[1,5], [6,9]] ==&gt; [[1,9]]</li> <li>Ex.3: intervals = [[1,5], [14, 17], [6,9], [10,13]] ==&gt; [[1,17]]</li> <li>Ex.4: intervals = [[1,5], [14, 17], [6,9], [10,13], [4,7], [8,12]] ==&gt; [[1,17], [4,12]]</li> </ul> <p>I cannot build on top of my current solution, because I'm not assured that intervals that have potential to overlap will be adjacent in the sorted form of given intervals list. An inefficient solution would be iterating over each pair combination in the list, and if they overlap, removing them from the list and pushing their merge into the result.</p> <p>Can you help me to create this function in the most optimal way possible?</p>
<python><algorithm><data-structures><intervals>
2024-09-19 23:32:56
1
402
bbasaran
79,004,666
12,299,000
Why does `ismethod` return False for a method when accessed via the class?
<p>Define a simple method:</p> <pre class="lang-py prettyprint-override"><code>class Foo: def bar(self): print('bar!') </code></pre> <p>Now use <code>inspect.ismethod</code>:</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; from inspect import ismethod &gt;&gt;&gt; ismethod(Foo.bar) False </code></pre> <p>Why is this? Isn't <code>bar</code> a method?</p>
<python><python-inspect>
2024-09-19 22:29:11
1
51,583
kaya3
79,004,528
3,906,713
Does numpy implement indexed choice function
<p>Here is an indexed choice function</p> <pre><code>def np_ifelse( x: np.ndarray[float] | float, ind: bool | np.ndarray[bool], v1: float, v2: float ) -&gt; float | np.ndarray[float]: if isinstance(x, np.ndarray): y = np.full_like(x, v2) y[ind] = v1 return y else: return v1 if ind else v2 </code></pre> <p>In case the input is a scalar, it is a simple if-else statement between two possible outcomes, resulting in a scalar output</p> <p>In case the input is an array, the if-else statement is applied individually to each array element, with the result being an array.</p> <p><strong>Question</strong>: This code looks somewhat ugly to me. Is there already a numpy function that does this more elegantly, without explicit type checking?</p>
<python><numpy>
2024-09-19 21:33:41
1
908
Aleksejs Fomins
79,004,499
6,618,225
Get certain value from column with varying row index in Pandas
<p>I am using Pandas to process numerous Excel files and I need to extract certain values from columns. The position within the column (the row) may vary but the name of the column remains the same throughout the files as does the start of the desired value which always starts with 'K_'.</p> <p>The only way I can come up with is iterating over the files, creating dataframes, getting the unique values of each column and then with an if-statement get the value that starts with 'K_'.</p> <p>That solution works fine but I am certain there is an easier and more elegant way to achieve the same result.</p> <p>Here is a brief working example of my problem:</p> <pre><code>import pandas as pd file1 = {'Col1' : ['', '', 'K_ABC', '', '', '']} file2 = {'Col1' : ['', 'K_DEF', '', '', '', '']} file3 = {'Col1' : ['', '', '', 'K_GHI', '', '']} files = [file1, file2, file3] for foo in files: df = pd.DataFrame(foo) values = df['Col1'].unique() for val in values: if val.startswith('K_'): print(val) </code></pre> <p><strong>The other rows can be anything like empty strings, NaN, other strings, etc. so just filtering out the empty strings is not going to cut it.</strong></p>
<python><pandas>
2024-09-19 21:20:02
1
357
Kai
79,004,263
5,867,094
Write pandas dataframe to excel consume too much memory
<p>I am using this code to write a dataframe into Excel file:</p> <pre class="lang-py prettyprint-override"><code>with pd.ExcelWriter(file_data, engine='xlsxwriter',engine_kwargs={&quot;options&quot;: {&quot;strings_to_formulas&quot;: False}}) as writer: df.to_excel(excel_writer=writer,sheet_name=&quot;data&quot;,index=False,) </code></pre> <p>where <code>file_data = io.BytesIO()</code>. It takes a lot of memory to finish this line. There are around 13k rows, and the result file is only around 43 MB, but the memory usage goes up to 1.1 GB. I also tried to chunk the dataframe into smaller pieces, but it consumes the same amount of memory as a whole. Is it designed to use so much memory, or am I using it wrong?</p>
<python><excel><pandas><memory>
2024-09-19 20:04:13
1
891
Tiancheng Liu
79,004,136
2,962,555
Got "PydanticUserError" when import ChatGroq
<p>I have following packages installed</p> <pre><code>langchain_core==0.2.39 langchain==0.2.16 langchain-community==0.2.16 langchain_groq==0.1.10 langchain_openai==0.1.24 fastapi==0.114.2 redis pyyaml </code></pre> <p>However, when I try to</p> <pre><code>from langchain_groq import ChatGroq </code></pre> <p>I got error</p> <pre><code>PydanticUserError Traceback (most recent call last) Cell In[20], line 70 64 #print(pm) 65 66 68 import os ---&gt; 70 from langchain_groq import ChatGroq File /opt/anaconda3/envs/my_env/lib/python3.12/site-packages/langchain_groq/__init__.py:1 ----&gt; 1 from langchain_groq.chat_models import ChatGroq 3 __all__ = [&quot;ChatGroq&quot;] File /opt/anaconda3/envs/my_env/lib/python3.12/site-packages/langchain_groq/chat_models.py:87 80 from langchain_core.utils.function_calling import ( 81 convert_to_openai_function, 82 convert_to_openai_tool, 83 ) 84 from langchain_core.utils.pydantic import is_basemodel_subclass ---&gt; 87 class ChatGroq(BaseChatModel): 88 &quot;&quot;&quot;`Groq` Chat large language models API. 89 90 To use, you should have the (...) 296 'logprobs': None} ... 2454 if hasattr(tp, '__origin__') and not is_annotated(tp): PydanticUserError: The `__modify_schema__` method is not supported in Pydantic v2. Use `__get_pydantic_json_schema__` instead in class `SecretStr`. For further information visit https://errors.pydantic.dev/2.9/u/custom-json-schema </code></pre> <p>Please advise.</p>
<python><langchain><groq><langchain-agents>
2024-09-19 19:22:22
3
1,729
Laodao
79,004,026
674,039
Why doesn't the future barry_as_FLUFL work in a .py file?
<p>There is a future statement which enables using the diamond operator <code>&lt;&gt;</code> instead of <code>!=</code> for equality comparisons.</p> <p>Here is a demonstration in a REPL:</p> <pre><code>&gt;&gt;&gt; from __future__ import barry_as_FLUFL &gt;&gt;&gt; print(1 &lt;&gt; 2) True &gt;&gt;&gt; 1 != 2 File &quot;&lt;stdin&gt;&quot;, line 1 1 != 2 ^^ SyntaxError: with Barry as BDFL, use '&lt;&gt;' instead of '!=' </code></pre> <p>It also works as expected with <code>eval</code>, <code>exec</code>, and <code>compile</code>, e.g.:</p> <pre><code>&gt;&gt;&gt; import __future__ &gt;&gt;&gt; exec(compile('print(1 &lt;&gt; 2)', 'foo', 'single', __future__.CO_FUTURE_BARRY_AS_BDFL)) True </code></pre> <p>However, it doesn't work when used in a script.</p> <pre><code># script.py from __future__ import barry_as_FLUFL print(1 &lt;&gt; 2) </code></pre> <p>Whether you import or run the file, that syntax change doesn't take effect:</p> <pre><code>$ python3 script.py File &quot;.../script.py&quot;, line 3 print(1 &lt;&gt; 2) ^^ SyntaxError: invalid syntax </code></pre> <p>I'm aware that the feature is a joke, and its functionality may have only been checked in an interactive interpreter. Nevertheless, I'm interested in the technical reason why, unlike other future statements, it doesn't work in a .py file.</p> <p>Why doesn't the future <code>barry_as_FLUFL</code> work in a script?</p>
<python>
2024-09-19 18:47:05
0
367,866
wim
79,003,971
9,973,879
How can I plot an interactive matplotlib figure without the figure number in a Jupyter notebook?
<p>I am using matplotlib with the <code>%matplotlib widget</code> in a Jupyter lab notebook. When I display a figure, there is &quot;Figure 1&quot; displayed just above it. How can I get rid of it?</p> <p>I have found that <code>plt.figure(num='', frameon=False)</code> does show a figure without this prefix, however it is not interactive and I cannot update its content later on (which is the reason why I am using the above magic in the first place).</p>
<python><matplotlib><jupyter-notebook><jupyter-lab><matplotlib-widget>
2024-09-19 18:30:11
1
1,967
user209974
79,003,823
1,491,895
Is there any use for a top-level global variable declaration?
<p>In Python, the <code>global</code> declaration is used inside function definitions to specify that assigning the variable will create/update a global variable, rather than the default local variable.</p> <p>Python also allows the <code>global</code> statement outside of function definitions. This doesn't cause an error, which leads many beginners to misuse it by writing the top-level declaration once instead of putting it in each function that needs it.</p> <p>It seems like this should be a syntax error, like using <code>return</code> outside a function or <code>break</code> outside a loop. Do these declarations serve any purpose, which would explain why it's allowed?</p>
<python><global-variables>
2024-09-19 17:44:47
1
788,391
Barmar
79,003,679
22,407,544
How to change Root User to Custom User in Dockerfile
<p>I've been attempting to make all users in my Dockerfile to custom user as when running <code>collectstatic</code> in my Django app, I get a error message:</p> <pre><code> [Errno 13] Permission denied: /code/static/admin/js/vendor/select2/i18n/pl.6031b4f16452.js.gz' </code></pre> <p>I also want to do so for security reasons.</p> <p>Currently when I run <code>&gt;docker-compose exec web ls -l /code/static</code> I get:</p> <pre><code>total 16 drwxrwxrwx 1 root root 4096 Apr 5 05:42 admin drwxrwxrwx 1 root root 4096 Sep 18 21:21 css drwxrwxrwx 1 root root 4096 Sep 18 21:21 human drwxrwxrwx 1 root root 4096 Sep 18 18:42 img -rw-r--r-- 1 1234 1234 13091 Sep 18 21:21 staticfiles.json drwxrwxrwx 1 root root 4096 Sep 18 21:21 transcribe </code></pre> <p>Here is my Dockerfile:</p> <pre><code># Pull base image FROM python:3.11.4-slim-bullseye # Set environment variables ENV PIP_NO_CACHE_DIR off ENV PIP_DISABLE_PIP_VERSION_CHECK 1 ENV PYTHONUNBUFFERED 1 ENV PYTHONDONTWRITEBYTECODE 1 ENV COLUMNS 80 #install Debian and other dependencies that are required to run python apps(eg. git, python-magic). RUN apt-get update \ &amp;&amp; apt-get install -y --force-yes python3-pip ffmpeg git libmagic-dev libpq-dev gcc \ &amp;&amp; rm -rf /var/lib/apt/lists/* # Set working directory for Docker image WORKDIR /code/ # Install dependencies COPY requirements.txt . RUN pip install -r requirements.txt # Copy project COPY . . # Create a custom non-root user RUN useradd -m example-user # Grant necessary permissions to write directories and to user 'celery-user' RUN mkdir -p /code/media /code/static &amp;&amp; \ chown -R example-user:uexample-user /code/media /code/static # Switch to the non-root user. All this avoids running Celery with root/superuser priviledges which is a security risk USER example-user </code></pre> <p>Whenever I rearrange my Dockerfile according to Docker best practice examples and build my image I get a successful build but also several error messages.</p> <p>Build Error 1:</p> <pre><code>=&gt; CACHED [celery 5/8] WORKDIR /code/ =&gt; CACHED [celery 6/8] COPY requirements.txt . =&gt; [celery 7/8] RUN pip install -r requirements.txt =&gt; =&gt; # WARNING: The script gunicorn is installed in '/home/example-user/.local/bin' which is not on PATH. =&gt; =&gt; # Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location. =&gt; =&gt; # WARNING: The script django-admin is installed in '/home/example-user/.local/bin' which is not on PATH. =&gt; =&gt; # Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location. =&gt; =&gt; # WARNING: The script celery is installed in '/home/example-user/.local/bin' which is not on PATH. =&gt; =&gt; # Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location. </code></pre> <p>Build error 2:</p> <pre><code>=&gt; =&gt; transferring context: 49.55kB =&gt; CACHED [celery 2/8] RUN apt-get update &amp;&amp; apt-get install -y --force-yes python3-pip ffmpeg git libmagic-dev libpq-dev gcc &amp;&amp; r =&gt; CACHED [celery 3/8] RUN groupadd -g 1234 customgroupexample &amp;&amp; useradd -m -u 1234 -g customgroupexample example-user =&gt; [celery 4/8] WORKDIR /code/ =&gt; [celery 5/8] COPY requirements.txt . =&gt; [celery 6/8] RUN pip install -r requirements.txt =&gt; =&gt; # WARNING: The scripts cpack, ctest and cmake are installed in '/home/example-user/.local/bin' which is not on PATH. =&gt; =&gt; # Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location. =&gt; =&gt; # WARNING: The script normalizer is installed in '/home/example-user/.local/bin' which is not on PATH. =&gt; =&gt; # Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location. =&gt; =&gt; # WARNING: The script chardetect is installed in '/home/example-user/.local/bin' which is not on PATH. =&gt; =&gt; # Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location. </code></pre>
<python><django><docker>
2024-09-19 17:01:07
1
359
tthheemmaannii
79,003,623
11,770,390
Get icons from X apps that don't have _NET_WM_ICON property set
<p>I'm trying to extract the icon from an xwindow, namely the one from <code>Obsidian</code> which doesn't seem to have the <code>_NET_WM_ICON</code> property set. How can I still extract this icon information? Is there another way? I'm using python-xlib right now.</p>
<python><ubuntu><x11><xorg><window-managers>
2024-09-19 16:44:11
1
5,344
glades
79,003,530
1,872,357
Parse Base64 Email Attachment in Python
<p>I created an Agent to review emails I forward to it. Emails are sent by AWS SES, stored in S3, and pushed to an SQS queue, which I read in my Python server.</p> <p>**Unfortunately, I could not extract the base64 attachment from the email. While I manage to read the Sender, Recipient, and other metadata. In the end, attachments is empty array, I cannot find it via <code>Content-Disposition</code> **</p> <p>Example of the email, this is the last part with the attachment:</p> <pre><code> Return-Path: &lt;john@gmail.com&gt; Received: from mail-ua1-f43.google.com (mail-ua1-f43.google.com [209.85.222.43]) by inbound-smtp.us-east-1.amazonaws.com with SMTP id pukag4ih1cmn9kkv80mbgq76ihqtmn1iegpq37o1 for review@gmail.app; Thu, 19 Sep 2024 04:58:26 +0000 (UTC) X-SES-Spam-Verdict: PASS X-SES-Virus-Verdict: PASS Received-SPF: pass (spfCheck: domain of _spf.google.com designates 209.85.222.43 as permitted sender) client-ip=209.85.222.43; envelope-from=john@gmail.com; helo=mail-ua1-f43.google.com; Authentication-Results: amazonses.com; spf=pass (spfCheck: domain of _spf.google.com designates 209.85.222.43 as permitted sender) client-ip=209.85.222.43; envelope-from=john@gmail.com; helo=mail-ua1-f43.google.com; dkim=pass header.i=@gmail.com; dmarc=pass header.from=gmail.com; X-SES-RECEIPT: AEFBQUFBQUFBQUFFZ2JHc0crQjlHelF5VUNDVUU2TUQ3Q2JTTUNxTGJjSm4wc0FHZjhYNc9PQ== X-SES-DKIM-SIGNATURE: a=rsa-sha256; q=dns/txt; b=PaW0ekScZFtkYj70ZltKs6/F2wVz5u5tbdecPA1MLE2VA9GJs0amXqM7LSCIvElqBkqncHCnv8ihFm+63UNrSfs4udIs0J8487tramL5PFsHweTEjk5m1e26mk6S62jwiH0/jn/yYiubrFxfk38vtXE24eQxGRp+ZM4ADy5ad08=; c=relaxed/simple; s=ug7nbtf4gccmlpwj322ax3p6ow6yfsug; d=amazonses.com; t=1726721906; v=1; bh=bScrS43KllskxOQzi+HJjcjEx0KiD5SVYtuSxG3pO4k=; h=From:To:Cc:Bcc:Subject:Date:Message-ID:MIME-Version:Content-Type:X-SES-RECEIPT; Received: by mail-ua1-f43.google.com with SMTP id a1e0cc1a2514c-846c5995a6fso123828241.0 for &lt;review@gmail.app&gt;; Wed, 18 Sep 2024 21:58:26 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1726721905; x=1727326705; darn=gmail.app; h=to:subject:message-id:date:from:in-reply-to:references:mime-version :from:to:cc:subject:date:message-id:reply-to; bh=1EFj7V5N3rGWogN7xvdVR45Df5dw8I9iVhoHHLKwXb8=; b=WnqqDF/pk/2qGINGjGq0/2Y6iqc64UX314BpyVYBzAm061fCYECa/rID0/g5k7ubY4 zHFtxGTqui7LbFfmWyW30uHsdHEB8jVXdHEL3ye2QmRyo75r4GlK2QePkyLnzK3UTkVA 9xSA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1726721905; x=1727326705; h=to:subject:message-id:date:from:in-reply-to:references:mime-version :x-gm-message-state:from:to:cc:subject:date:message-id:reply-to; bh=1EFj7V5N3rGWogN7xvdVR45Df5dw8I9iVhoHHLKwXb8=; b=AIbwVZhgae73QWUp 4dzA== X-Gm-Message-State: AOJu0YxvoiAVUcscxADiEKxQhMXaYG7qGSFEJSobz85CPD9HulH36T0v VjxeMRSDH9LgyY4639urxmSFD96n/r6HU X-Google-Smtp-Source: AGHT+IF94l6O4wxdwbAWB8bUqEzsTjkImbi70jIQzUXeqwL8sM9naZDEQuZ8T/RSuGZzD4PJQXCUSmWFF7nrdWYsxaw= X-Received: by 2002:a05:6102:e10:b0:498:ef8d:8368 with SMTP id ada2fe7eead31-49d4f60e8f6mr15076922137.13.1726721904892; Wed, 18 Sep 2024 21:58:24 -0700 (PDT) MIME-Version: 1.0 References: &lt;SEZPR03MB766.apcprd03.prod.outlook.com&gt; &lt;E5084324-CDFB-4236-BCB2@gmail.com&gt; In-Reply-To: &lt;E5084324-CDFB-4236-BCB2@gmail.com&gt; From: John Doe&lt;john@gmail.com&gt; Date: Thu, 19 Sep 2024 12:58:13 +0800 Message-ID: &lt;CAFUY-ktg8M8DB=iyRMpcgU5Ktv41Tpcm+A0RPpzZPHfjNfTqWw@mail.gmail.com&gt; Subject: Fwd: From: 61 2 9300 9218, you have received a 3 page fax on: 291693497 from Remote ID 13055037548 - sample To: review@gmail.app Content-Type: multipart/mixed; boundary=&quot;000000000000c4fbc8062271c50c&quot; --000000000000c4fbc8062271c50c Content-Type: multipart/alternative; boundary=&quot;000000000000c4fbc7062271c50a&quot; --000000000000c4fbc7062271c50a Content-Type: text/plain; charset=&quot;UTF-8&quot; Content-Transfer-Encoding: quoted-printable Forwarderd ---------- Forwarded message --------- =D0=92=D1=96=D0=B4: Email AI &lt;tech@gmail.com&gt; Date: =D0=BF=D0=BD, 16 =D0=B2=D0=B5=D1=80. 2024=E2=80=AF=D1=80. =D0=BE 21:4= 2 Subject: Fwd: From: 61 2 9300 9218, you have received a 3 page fax on: 291693497 from Remote ID 13055037548 - sample To: john@gmail.com &lt;john@gmail.com&gt; Example A Begin forwarded message: *From: *Bondi Go &lt;Go.bon@bgmail.com&gt; *Subject: **FW: From: 61 2 9300 9218, you have received a 3 page fax on: 291693497 from Remote ID 13055037548 - sample* *Date: *9 September 2024 at 16:55:57 GMT+10 *To: *&quot;tech@gmail.com&quot; &lt;tech@gmail.com&gt; *From:* Go Receive &lt;receive@Go.com.au&gt; *Sent:* Wednesday, 31 July 2024 9:36 AM *To:* Bondi Go &lt;Go.bon@bgmail.com&gt; *Subject:* From: 61 2 9300 9218, you have received a 3 page fax on: 291693497 from Remote ID 13055037548 Inbound Fax Received Received at: 31-07-2024-09:35:48 From: 61 2 9300 9218 Remote Fax ID: 13055037548 FaxID: 64235128 On Fax Number: 291693497 Pages: 3 Transmission Result: COMPLETE Speed: 9600 Connection Time: 113 --=20 *Igor Steblii* igorsteblii.com --000000000000c4fbc7062271c50a Content-Type: text/html; charset=&quot;UTF-8&quot; Content-Transfer-Encoding: quoted-printable &lt;div dir=3D&quot;ltr&quot;&gt;Forwarderd&lt;br&gt;&lt;br&gt;&lt;div class=3D&quot;gmail_quote&quot;&gt;&lt;div dir=3D&quot;l= tr&quot; class=3D&quot;gmail_attr&quot;&gt;---------- Forwarded message ---------&lt;br&gt;=D0=92= =D1=96=D0=B4: &lt;strong class=3D&quot;gmail_sendername&quot; dir=3D&quot;auto&quot;&gt;Email AI&lt;= /strong&gt; &lt;span dir=3D&quot;auto&quot;&gt;&amp;lt;&lt;a href=3D&quot;mailto:tech@gmail.com&quot;&gt;tech@c= areaihq.com&lt;/a&gt;&amp;gt;&lt;/span&gt;&lt;br&gt;Date: =D0=BF=D0=BD, 16 =D0=B2=D0=B5=D1=80. 20= 24=E2=80=AF=D1=80. =D0=BE 21:42&lt;br&gt;Subject: Fwd: From: 61 2 9300 9218, you = have received a 3 page fax on: 291693497 from Remote ID 13055037548 - sampl= e&lt;br&gt;To: &lt;a href=3D&quot;mailto:john@gmail.com&quot;&gt;john@gmail.com&lt;/= a&gt; &amp;lt;&lt;a href=3D&quot;mailto:john@gmail.com&quot;&gt;john@gmail.com&lt;/a&gt;= &amp;gt;&lt;br&gt;&lt;/div&gt;&lt;br&gt;&lt;br&gt; &lt;div&gt; &lt;div style=3D&quot;line-break:after-white-space&quot;&gt;Example A&lt;br id=3D&quot;m_-798919805= 8068842788x_lineBreakAtBeginningOfMessage&quot;&gt; &lt;div&gt;&lt;br&gt; &lt;blockquote type=3D&quot;cite&quot;&gt; &lt;div&gt;Begin forwarded message:&lt;/div&gt; &lt;br&gt; &lt;div style=3D&quot;margin-top:0px;margin-right:0px;margin-bottom:0px;margin-left= :0px&quot;&gt; &lt;span style=3D&quot;font-family:-webkit-system-font,Helvetica Neue,Helvetica,san= s-serif;color:rgba(0,0,0,1.0)&quot;&gt;&lt;b&gt;From: &lt;/b&gt;&lt;/span&gt;&lt;span style=3D&quot;font-family:-webkit-system-font,Helvetica Neue,He= lvetica,sans-serif&quot;&gt;Bondi Go &amp;lt;&lt;a href=3D&quot;mailto:Go.bon@bjchealth.c= om.au&quot; target=3D&quot;_blank&quot;&gt;Go.bon@bgmail.com&lt;/a&gt;&amp;gt;&lt;br&gt; &lt;/span&gt;&lt;/div&gt; &lt;div style=3D&quot;margin-top:0px;margin-right:0px;margin-bottom:0px;margin-left= :0px&quot;&gt; &lt;span style=3D&quot;font-family:-webkit-system-font,Helvetica Neue,Helvetica,san= s-serif;color:rgba(0,0,0,1.0)&quot;&gt;&lt;b&gt;Subject: &lt;/b&gt;&lt;/span&gt;&lt;span style=3D&quot;font-family:-webkit-system-font,Helvetica Neue,He= lvetica,sans-serif&quot;&gt;&lt;b&gt;FW: From: 61 2 9300 9218, you have received a 3 page= fax on: 291693497 from Remote ID 13055037548 - sample&lt;/b&gt;&lt;br&gt; &lt;/span&gt;&lt;/div&gt; &lt;div style=3D&quot;margin-top:0px;margin-right:0px;margin-bottom:0px;margin-left= :0px&quot;&gt; &lt;span style=3D&quot;font-family:-webkit-system-font,Helvetica Neue,Helvetica,san= s-serif;color:rgba(0,0,0,1.0)&quot;&gt;&lt;b&gt;Date: &lt;/b&gt;&lt;/span&gt;&lt;span style=3D&quot;font-family:-webkit-system-font,Helvetica Neue,He= lvetica,sans-serif&quot;&gt;9 September 2024 at 16:55:57 GMT+10&lt;br&gt; &lt;/span&gt;&lt;/div&gt; &lt;div style=3D&quot;margin-top:0px;margin-right:0px;margin-bottom:0px;margin-left= :0px&quot;&gt; &lt;span style=3D&quot;font-family:-webkit-system-font,Helvetica Neue,Helvetica,san= s-serif;color:rgba(0,0,0,1.0)&quot;&gt;&lt;b&gt;To: &lt;/b&gt;&lt;/span&gt;&lt;span style=3D&quot;font-family:-webkit-system-font,Helvetica Neue,He= lvetica,sans-serif&quot;&gt;&amp;quot;&lt;a href=3D&quot;mailto:tech@gmail.com&quot; target=3D&quot;_b= lank&quot;&gt;tech@gmail.com&lt;/a&gt;&amp;quot; &amp;lt;&lt;a href=3D&quot;mailto:tech@gmail.com&quot; = target=3D&quot;_blank&quot;&gt;tech@gmail.com&lt;/a&gt;&amp;gt;&lt;br&gt; &lt;/span&gt;&lt;/div&gt; &lt;br&gt; &lt;div&gt; &lt;div style=3D&quot;font-family:Helvetica;font-size:14px;font-style:normal;font-v= ariant-caps:normal;font-weight:400;letter-spacing:normal;text-align:start;t= ext-indent:0px;text-transform:none;white-space:normal;word-spacing:0px;text= -decoration:none&quot;&gt; &lt;div style=3D&quot;margin:0cm;font-size:11pt;font-family:Calibri,sans-serif&quot;&gt;&lt;sp= an&gt;=C2=A0&lt;/span&gt;&lt;/div&gt; &lt;div style=3D&quot;margin:0cm;font-size:11pt;font-family:Calibri,sans-serif&quot;&gt;&lt;sp= an&gt;=C2=A0&lt;/span&gt;&lt;/div&gt; &lt;div style=3D&quot;border-width:1pt medium medium;border-style:solid none none;b= order-color:rgb(225,225,225) currentcolor currentcolor;padding:3pt 0cm 0cm&quot;= &gt; &lt;div style=3D&quot;margin:0cm;font-size:11pt;font-family:Calibri,sans-serif&quot;&gt;&lt;b&gt;= &lt;span lang=3D&quot;EN-US&quot;&gt;From:&lt;/span&gt;&lt;/b&gt;&lt;span lang=3D&quot;EN-US&quot;&gt;&lt;span&gt;=C2=A0&lt;/spa= n&gt;Go Receive &amp;lt;&lt;a href=3D&quot;mailto:receive@Go.com.au&quot; target=3D&quot;_blan= k&quot;&gt;receive@Go.com.au&lt;/a&gt;&amp;gt;&lt;br&gt; &lt;b&gt;Sent:&lt;/b&gt;&lt;span&gt;=C2=A0&lt;/span&gt;Wednesday, 31 July 2024 9:36 AM&lt;br&gt; &lt;b&gt;To:&lt;/b&gt;&lt;span&gt;=C2=A0&lt;/span&gt;Bondi Go &amp;lt;&lt;a href=3D&quot;mailto:Go.bon@bj= chealth.com.au&quot; target=3D&quot;_blank&quot;&gt;Go.bon@bgmail.com&lt;/a&gt;&amp;gt;&lt;br&gt; &lt;b&gt;Subject:&lt;/b&gt;&lt;span&gt;=C2=A0&lt;/span&gt;From: 61 2 9300 9218, you have received a= 3 page fax on: 291693497 from Remote ID 13055037548&lt;/span&gt;&lt;/div&gt; &lt;/div&gt; &lt;div style=3D&quot;margin:0cm;font-size:11pt;font-family:Calibri,sans-serif&quot;&gt;=C2= =A0&lt;/div&gt; &lt;p&gt;&lt;br&gt; Inbound Fax Received&lt;br&gt; Received at: 31-07-2024-09:35:48&lt;br&gt; From: 61 2 9300 9218&lt;br&gt; Remote Fax ID: 13055037548&lt;br&gt; FaxID: 64235128&lt;br&gt; On Fax Number: 291693497&lt;br&gt; Pages: 3&lt;br&gt; Transmission Result: COMPLETE&lt;br&gt; Speed: 9600&lt;br&gt; Connection Time: 113&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/blockquote&gt; &lt;/div&gt; &lt;/div&gt; &lt;div style=3D&quot;line-break:after-white-space&quot;&gt; &lt;div&gt; &lt;blockquote type=3D&quot;cite&quot;&gt; &lt;div&gt;&lt;/div&gt; &lt;/blockquote&gt; &lt;/div&gt; &lt;br&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt;&lt;br clear=3D&quot;all&quot;&gt;&lt;div&gt;&lt;br&gt;&lt;/div&gt;&lt;span class=3D&quot;gmail_signature_prefi= x&quot;&gt;-- &lt;/span&gt;&lt;br&gt;&lt;div dir=3D&quot;ltr&quot; class=3D&quot;gmail_signature&quot; data-smartmail= =3D&quot;gmail_signature&quot;&gt;&lt;div dir=3D&quot;ltr&quot;&gt;&lt;font size=3D&quot;-1&quot; style=3D&quot;color:rgb(= 136,136,136)&quot;&gt;&lt;span style=3D&quot;vertical-align:baseline;font-size:12px;font-fa= mily:Arial;background-color:transparent&quot;&gt;&lt;b&gt;Igor Steblii&lt;/b&gt;&lt;/span&gt;&lt;/font&gt;&lt;= font size=3D&quot;-1&quot; style=3D&quot;color:rgb(136,136,136)&quot;&gt;&lt;br&gt;&lt;/font&gt;&lt;br&gt;&lt;div&gt;&lt;a hr= ef=3D&quot;http://igorsteblii.com&quot; target=3D&quot;_blank&quot;&gt;igorsteblii.com&lt;/a&gt;&lt;br&gt;&lt;/di= v&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt; --000000000000c4fbc7062271c50a-- --000000000000c4fbc8062271c50c Content-Type: application/pdf; name=&quot;291693497-2024-07-31-093548-64235128.pdf&quot; Content-Disposition: attachment; filename=&quot;291693497-2024-07-31-093548-64235128.pdf&quot; Content-Transfer-Encoding: base64 Content-ID: &lt;19208a4c905d7a58eae1&gt; X-Attachment-Id: 19208a4c905d7a58eae1 JVBERi0xLjMgCjEgMCBvYmoKPDwKL1BhZ2VzIDIgMCBSCi9UeXBlIC9DYXRhbG9nCj4+CmVuZG9i agoyIDAgb2JqCjw8Ci9UeXBlIC9QYWdlcwovS2lkcyBbIDMgMCBSIDE3IDAgUiAzMSAwIFIgXQov Q291bnQgMwo+PgplbmRvYmoKMyAwIG9iago8PAovVHlwZSAvUGFnZQovUGFyZW50IDIgMCBSCi9S ZXNvdXJjZXMgPDwKL1hPYmplY3QgPDwgL0ltMCA4IDAgUiA+PgovUHJvY1NldCA2IDAgUiA+Pgov TWVkaWFCb3ggWzAgMCA2MDkuODgyIDc4OS40MjldCi9Dcm9wQm94IFswIDAgNjA5Ljg4MiA3ODku Zm8gNDUgMCBSCi9Sb290IDEgMCBSCi9JRCBbPGI2ZGFmYTllY2Q5NWI4NDg4YjkwY2U3NjA0ZmIw MDQ3MTg3NWI4OTNhYmZiMDkwY2YyYTRjMjA2MmE4YjU4OTA+IDxiNmRhZmE5ZWNkOTViODQ4OGI5 MGNlNzYwNGZiMDA0NzE4NzViODkzYWJmYjA5MGNmMmE0YzIwNjJhOGI1ODkwPl0KPj4Kc3RhcnR4 cmVmCjg4NzA4CiUlRU9GCg== --000000000000c4fbc8062271c50c-- </code></pre> <p>I parse it with a code, like:</p> <pre><code>import os import base64 import email msg = email.message_from_string(raw_string) def extract_email_info(msg): # Extract basic email details email_data = { 'sender': msg.get('From', 'Unknown Sender'), 'recipient': msg.get('To', 'Unknown Recipient'), 'subject': msg.get('Subject', 'No Subject'), 'date': extract_date(msg), 'body_plain': None, 'attachments': [], } for part in msg.walk(): process_part(part, email_data) # Ensure plain text body has a fallback message if not email_data['body_plain']: email_data['body_plain'] = &quot;No plain text content found&quot; return email_data def process_part(part, email_data): content_type = part.get_content_type() disposition = str(part.get(&quot;Content-Disposition&quot;, &quot;&quot;)) if content_type == &quot;message/rfc822&quot;: forwarded_msg = email.message_from_bytes(part.get_payload(decode=True)) extract_email_info(forwarded_msg) # Process forwarded message elif content_type == &quot;text/plain&quot; and &quot;attachment&quot; not in disposition: if not email_data['body_plain']: email_data['body_plain'] = part.get_payload(decode=True).decode(part.get_content_charset() or 'utf-8') elif part.get_filename() or &quot;attachment&quot; in disposition or content_type.startswith('application/'): attachment = { 'file_name': part.get_filename() or &quot;unnamed_attachment&quot;, 'content_type': content_type, 'data': part.get_payload(decode=True), 'content_id': part.get('Content-ID'), } email_data['attachments'].append(attachment) </code></pre> <p>I also want to parse the email from where it was forwarded, as I automatically set forwarding on my email client. Forwarded emails might also have attachments I want to process.</p>
<python><email><base64><amazon-ses>
2024-09-19 16:15:40
0
768
ilbets
79,003,448
1,658,617
Py_INCREF in Cython accepts Python object but not pointer
<p>I have a small implementation of a linked list in Cython, and I wish to add a value to the list.</p> <p>For some reason, when I try to <code>Py_INCREF</code> (to make sure I keep a strong reference in each node), Cython does not accept a pointer to the Python object, but only the object itself:</p> <pre><code>ctypedef struct Node: PyObject* group PyObject* value # (group, value) Node* next cdef bint _put(object group, object value) except 1: cdef: Node* node = &lt;Node*&gt;PyMem_Malloc(sizeof(Node)) PyObject* _group = &lt;PyObject*&gt; group PyObject* _value = &lt;PyObject*&gt; value if not node: raise MemoryError(&quot;Failed to allocate memory for new node&quot;) node.group = _group Py_INCREF(node.group) # Cannot convert 'PyObject *' to Python object Py_INCREF(_group) # Cannot convert 'PyObject *' to Python object Py_INCREF(&lt;PyObject*&gt; group) # Cannot convert 'PyObject *' to Python object Py_INCREF(group) # Works </code></pre> <p>Supposedly, <code>Py_INCREF</code> is meant to work with <code>PyObject*</code>.</p> <p>Both looking up around the web and chatgpt directly suggested that:</p> <blockquote> <p><code>Py_INCREF</code> in Cython works with a <code>PyObject*</code>, which is a pointer to a Python object, not a Python-level object. Therefore, you should pass a <code>PyObject*</code> (a pointer) to <code>Py_INCREF</code>.</p> </blockquote> <p>The code seems so simple, I'm unsure why it doesn't work.</p>
<python><cython>
2024-09-19 15:54:07
1
27,490
Bharel
79,003,432
5,454
Why is mypy issuing import-not-found errors on every single import?
<p>I am writing a simple Python application using FastAPI. I am using pdm as my package manager which means I have a pyproject.toml file and a pdm.lock file. I also using pyenv to manage both versions of Python installed on my system as well as virtual environments. So in this case, I started off creating my project by running commands like this:</p> <ul> <li>pyenv virtualenv 3.12.5 myproject</li> <li>pyenv local myproject</li> <li>pdm init minimal</li> </ul> <p>I then followed the prompts that pdm gives to give my project a name, and install various dependencies (e.g. FastAPI, uvicorn, etc.). Now I'm trying to run <code>mypy .</code> but it's complaining about basically every single import statement I have. Here's the full error text:</p> <pre><code>myproject/routers/transactions.py:1: error: Cannot find implementation or library stub for module named &quot;asapi&quot; [import-not-found] myproject/routers/transactions.py:2: error: Cannot find implementation or library stub for module named &quot;fastapi&quot; [import-not-found] myproject/routers/transactions.py:3: error: Cannot find implementation or library stub for module named &quot;psycopg_pool&quot; [import-not-found] myproject/routers/system.py:1: error: Cannot find implementation or library stub for module named &quot;fastapi&quot; [import-not-found] myproject/config/app.py:4: error: Cannot find implementation or library stub for module named &quot;pydantic&quot; [import-not-found] myproject/config/app.py:5: error: Cannot find implementation or library stub for module named &quot;pydantic_settings&quot; [import-not-found] tests/test_settings.py:3: error: Cannot find implementation or library stub for module named &quot;pytest&quot; [import-not-found] tests/test_settings.py:3: note: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports myproject/config/loggers.py:7: error: Cannot find implementation or library stub for module named &quot;orjson&quot; [import-not-found] myproject/config/loggers.py:8: error: Cannot find implementation or library stub for module named &quot;opentelemetry.sdk.resources&quot; [import-not-found] myproject/config/loggers.py:9: error: Cannot find implementation or library stub for module named &quot;opentelemetry.trace&quot; [import-not-found] myproject/main.py:5: error: Cannot find implementation or library stub for module named &quot;anyio&quot; [import-not-found] myproject/main.py:6: error: Cannot find implementation or library stub for module named &quot;asapi&quot; [import-not-found] myproject/main.py:7: error: Cannot find implementation or library stub for module named &quot;fastapi&quot; [import-not-found] myproject/main.py:8: error: Cannot find implementation or library stub for module named &quot;psycopg_pool&quot; [import-not-found] Found 14 errors in 6 files (checked 7 source files) </code></pre> <p>I am not sure how to overcome these errors. I know that I could simply create a mypy.ini file with this as its contents to effectively ignore these types of errors:</p> <pre><code>[mypy] ignore_missing_imports = True </code></pre> <p>However, that seems like bad practice as I would much rather understand why mypy is showing these errors and how I can go about fixing the situation. My code is able to run successfully (thus demonstrating that the imports work), and if I run <code>pip list</code> I can clearly see all of the dependencies installed within the virtual environment (which pyenv is managing). So why is mypy having so much trouble with these same imports?</p>
<python><mypy><pyenv><pyenv-virtualenv>
2024-09-19 15:50:01
1
10,170
soapergem
79,003,375
10,962,766
API changes when using app_store_scraper in Python?
<p>Last summer, I created code for scraping Apple podcast reviews based on the official documentation provided for app-store-scraper:</p> <p><a href="https://pypi.org/project/app-store-scraper/" rel="nofollow noreferrer">https://pypi.org/project/app-store-scraper/</a></p> <p>Here is the relevant section from my longer Jupyter notebook:</p> <pre><code># import packages import pandas as pd import numpy as np import csv from app_store_scraper import AppStore # app_name = podcast name from URL # app_id = podcast id from URL podcast = AppStore(country='us', app_name='black-girl-gone-a-true-crime-podcast', app_id = '1556267741') podcast.review(how_many=7000) # change number if necessary reviews=podcast.reviews print(&quot;This podcast has &quot;, len(reviews), &quot;reviews.&quot;) df = pd.DataFrame() # columns in each review = date, review, rating, isEdited, userName, title podcastdf = pd.DataFrame(np.array(podcast.reviews),columns=['review']) display(podcastdf) </code></pre> <p>Unfortunately, I now get a 401 error when running the code again and I wonder if there are any changes in the Apple API that prevent me from collecting the data.</p> <p>Or maybe there's some kind of dependency issue because packages have been updated.</p>
<python><pandas><app-store>
2024-09-19 15:38:14
0
498
OnceUponATime
79,003,290
3,259,222
How to align xarray dimensions without performing calculation?
<p>I have 2 DataArrays with partially overlapping dimensions. If I perform any calculation the dimensions of the result are auto aligned according to the exact matches between the overlapping dimensions.</p> <p>How can I achieve the same result without performing the redundant calculation below:<code>y_da.y * x_da.x/x_da.x</code>?</p> <p>I tried: align, broadcast, merge methods without any success...</p> <pre><code>import xarray as xr import pandas as pd x_da = pd.DataFrame({ 'reporting_date': pd.to_datetime([ '2024-01-01','2024-02-01','2024-03-01', '2024-01-01','2024-02-01','2024-03-01', '2024-01-01','2024-02-01','2024-03-01', ]), 'user': [ 'A','A','A', 'B','B','B', 'C','C','C', ], 'rating': [ 1,1,1, 1,2,3, 3,2,1 ], 'x': [ 10,20,30, 20,30,40, 30,40,50 ] }) y_da = pd.DataFrame({ 'rating': [ 1,1,1,1,1,1, 2,2,2,2,2,2, 3,3,3,3,3,3 ], 'horizon': [ 1,2,3,4,5,6, 1,2,3,4,5,6, 1,2,3,4,5,6 ], 'y': [ 0.1,0.2,0.3,0.4,0.5,0.6, 0.2,0.3,0.4,0.5,0.6,0.7, 0.3,0.4,0.5,0.6,0.7,0.8, ] }) x_da = x_da.set_index(['user','reporting_date','rating']).to_xarray() y_da = y_da.set_index(['rating','horizon']).to_xarray() ds = x_da.assign(y=y_da.y * x_da.x/x_da.x) display(ds.sel({'user':'A'}).y) </code></pre> <p><a href="https://i.sstatic.net/ZQ6WPFmS.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/ZQ6WPFmS.png" alt="enter image description here" /></a></p>
<python><python-xarray>
2024-09-19 15:16:59
1
431
Konstantin
79,003,259
11,370,582
Return an Error Message in Plotly Dash and place at the top of the page
<p>I have a fairly complex visualization tool I created in Plotly Dash, so I won't share the entire code, though what I am trying to do is return an error message using a try/except block.</p> <pre><code>except Exception as e: print(e) return html.Div([ html.B('THERE WAS AN ERROR PROCESSING THIS FILE - PLEASE REVIEW FORMATTING.') ]) </code></pre> <p>This works, technically, but I can't find a method to return the message as the first <code>html.Div</code> and therefore at the top of the page. Currently it returns right at the bottom. Anybody tried to address this before?</p>
<python><pandas><plotly><plotly-dash><dashboard>
2024-09-19 15:08:58
1
904
John Conor
79,003,145
12,730,406
Python - Parent and Child Class inheritance - attribute inheritance
<p>If I have this parent class to define a profile:</p> <pre><code>class Profile: # this is the class constructor def __init__(self, account_holder, account_type, value): self.account_holder = account_holder self.account_type = account_type self.value = value # some methods for the user account: def info(self): print(self.account_holder) print(self.account_type) print(self.value) # create object: personal_acc = Profile(account_holder='Me', account_type='main account', value= 100) personal_acc.info() </code></pre> <p>Now if I make a child class which is simply a business user profile - this inherits all the attributes of the parent class:</p> <pre><code>class Business(Profile): # this is a child class: def __init__(self, business_name, business_value = 100): self.business_name = business_name self.business_value = business_value # new_method def increase_value(self, increase = 400): self.business_value += increase meta = Business(business_name='whatsapp', business_value = 1000) meta.increase_value() print(meta.business_value) # print a method of the parent class using child class Business: meta.info() </code></pre> <p>when i run the last line of <code>meta.info()</code> I get this error message:</p> <blockquote> <p>Traceback (most recent call last): File &quot;c:\Users\beans\test.py&quot;, line 558, in meta.info() File &quot;c:\Users\beans\test.py&quot;, line 523, in info print(self.account_holder) AttributeError: 'Business' object has no attribute &gt;'account_holder'</p> </blockquote> <p>How do i pass in the attribute <code>account_holder</code>, <code>account_type</code> and <code>value</code> when I create my user sub class?</p> <p>Or should I set default values for these?</p>
<python><oop>
2024-09-19 14:49:31
1
1,121
Beans On Toast
79,003,089
926,459
azure function .python_packages missing
<p>I have an azure function app to which I am trying to deploy some python code to via zip upload through the CLI. I can get a hello world application to run but I cannot add external libraries. I added a requirements.txt in my root folder but this is not being picked up.</p> <p>Many solutions and suggestions I found on the web revolve around pointing the python path to /home/site/wwwroot/.python_packages but when I ssh into the machine this path doesn't even exist. I tried to put a venv in that path manually and installing the required packages but the function code still fails during import.</p> <p>I used the portal to create a function app with python 3.11 on linux. Is this .python_packages folder still supposed to be there or did something change?</p>
<python><azure><pip><azure-functions>
2024-09-19 14:36:58
2
2,209
matteok
79,003,081
8,037,521
Faster voxelization with inverse indices
<p>I am using the following piece of code to get a <code>voxelized</code> point cloud <strong>with inverse indices</strong> so that I can compute the e.g. mask on the downsampled point cloud and then apply it on the original point cloud by getting the original points through inverse indices.</p> <pre><code>def voxelize(points, voxel_size): voxel_indices = np.floor(points / voxel_size).astype(np.int32) unique_voxel_indices, inverse_indices = np.unique( voxel_indices, axis=0, return_inverse=True ) voxel_centers = (unique_voxel_indices + 0.5) * voxel_size return voxel_indices, unique_voxel_indices, voxel_centers, inverse_indices </code></pre> <p>However, this code is becoming a bottleneck for me as it is executed thousands of times.</p> <p>I find similar questions to speed up this <strong>but without the inverse indices</strong>. Numba also does not have this version of <code>np.unique</code> implemented. Is there any method I am missing that is significantly faster but also provides the indices calculation?</p>
<python>
2024-09-19 14:35:08
1
1,277
Valeria
79,003,055
13,469,674
Langgraph tools_condition prebuilt method routing to other nodes instead of END node
<p>I was building quite a simple graph using Langgraph. I decided the pre-built tools_condition function from langgraph. So I imported it and used it as follows:</p> <pre><code>graph_builder = StateGraph(State) graph_builder.add_node(&quot;chatbot&quot;, assistant) graph_builder.add_node(&quot;tools&quot;, lambda state: run_tool(state, tools={&quot;athena_query&quot;:athena_query})) graph_builder.add_node(&quot;report_checker&quot;, report_check) graph_builder.add_edge(START, &quot;chatbot&quot;) graph_builder.add_conditional_edges( &quot;chatbot&quot;, tools_condition ) # graph_builder.add_edge(&quot;chatbot&quot;, &quot;tools&quot;) graph_builder.add_edge(&quot;tools&quot;, &quot;chatbot&quot;) graph_builder.add_edge(&quot;chatbot&quot;, &quot;report_checker&quot;) graph = graph_builder.compile(checkpointer=memory) </code></pre> <p>The resulting graph is the following:</p> <p><a href="https://i.sstatic.net/82PcHv1T.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/82PcHv1T.png" alt="enter image description here" /></a></p> <p>It does not make sense that there is a conditional edge pointing from assistant to <code>report_checker</code> when I specify that it is a regular edge. Why is the default behaviour of <code>tools_condition</code> to make conditional edges to everything else if its not a tool call and not just go to <code>END</code>?</p> <p>I know this because if I pass the routing arguments of where it is supposed to go, the extra conditional edges disappear:</p> <pre><code>graph_builder = StateGraph(State) graph_builder.add_node(&quot;chatbot&quot;, assistant) graph_builder.add_node(&quot;tools&quot;, lambda state: run_tool(state, tools={&quot;athena_query&quot;:athena_query})) graph_builder.add_node(&quot;report_checker&quot;, report_check) graph_builder.add_edge(START, &quot;chatbot&quot;) graph_builder.add_conditional_edges( &quot;chatbot&quot;, tools_condition, { &quot;END&quot;: END, &quot;tools&quot;: &quot;tools&quot;, } ) graph_builder.add_edge(&quot;tools&quot;, &quot;chatbot&quot;) graph_builder.add_edge(&quot;chatbot&quot;, &quot;report_checker&quot;) graph = graph_builder.compile(checkpointer=memory) </code></pre> <p>The unwanted conditional edge is now gone:</p> <p><a href="https://i.sstatic.net/261ANI2M.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/261ANI2M.png" alt="enter image description here" /></a></p> <p>Why is default <code>tools_condition</code> routing the main node somewhere other than the <code>END</code> node?</p>
<python><langchain><langgraph>
2024-09-19 14:31:08
2
955
DPM
79,003,021
17,721,722
How to Read Multiple CSV Files with Skipping Rows and Footer in PySpark Efficiently?
<p>I have several CSV files with an inconsistent number of data rows without a header row and I want to read these files into a single PySpark DataFrame. The structure of the CSV files is as follows:</p> <pre><code>data1,data2 data1,data2,data3 data1,data2,data3,data4,data5,data6 data1,data2,data3,data4,data5,data6 data1,data2,data3,data4,data5,data6 data1,data2,data3,data4,data5,data6 data1,data2,data3,data4,data5,data6 data1,data2,data3,data4,data5,data6 data1,data2,data3,data4,data5,data6 data1,data2,data3,data4,data5,data6 data1,data2,data3,data4,data5,data6 data1,data2,data3,data4,data5,data6 data1,data2,data3,data4,data5,data6 =&gt; data1,data2,data3,data4,data5,data6 data1,data2,data3,data4,data5,data6 data1,data2,data3,data4,data5,data6 data1,data2,data3,data4,data5,data6 data1,data2,data3,data4,data5,data6 data1,data2,data3,data4,data5,data6 data1,data2,data3,data4,data5,data6 data1,data2,data3,data4,data5,data6 data1,data2,data3,data4,data5,data6 data1,data2,data3,data4,data5,data6 data1,data2,data3,data4,data5,data6 data1,data2,data3,data4,data5,data6 data1,data2,data3,data4,data5,data6 data1,data2 data1,data2 data1,data2,data3 </code></pre> <p>I want to skip the first two rows and the last three rows from each file before combining them into one DataFrame. I am using the following approach, which works but I am looking for a more optimized solution because the datasets is quite large.</p> <pre class="lang-py prettyprint-override"><code>def concat(df_list: list): df = df_list[0] for i in df_list[1:]: df = df.unionByName(i, allowMissingColumns=True) return df def __read_with_separators(self, spark: SparkSession, field_details: List[Dict[str, Any]], file_path_list: List[str], kwargs: dict) -&gt; DataFrame: df_list = [] for file_path in file_path_list: rdd = spark.sparkContext.textFile(file_path) total_rows = rdd.count() start_index = kwargs.get(&quot;skiprows&quot;, 0) end_index = total_rows - kwargs.get(&quot;skipfooter&quot;, 0) rdd_filtered = rdd.zipWithIndex().filter(lambda x: start_index &lt;= x[1] &lt; end_index).map(lambda x: x[0]).map(lambda line: line.split(delimiter)) temp_df = rdd_filtered.toDF(schema) df_list.append(temp_df) return concat(df_list) </code></pre> <p><strong>Questions:</strong></p> <ol> <li>Is there a way to read multiple CSV files at once while skipping rows and footer rows more efficiently?</li> <li>Are there any optimizations or improvements to the current approach to handle large datasets more effectively?</li> </ol>
<python><python-3.x><apache-spark><pyspark><apache-spark-sql>
2024-09-19 14:23:24
2
501
Purushottam Nawale
79,002,987
12,647,231
Vault does not return token renewed by script
<p>I write a script for renewing Hashicorp Vault tokens. But I faced an issue. When the token renewed automatically by the script Vault retuns n/a instead of token value so I cannot save it anywhere, to kubernetes secret, for example.</p> <p>Output looks like this:</p> <pre><code>--- ----- token n/a token_accessor ------------- token_duration 10h token_renewable true token_policies [&quot;default&quot;] identity_policies [] policies [&quot;default&quot;] </code></pre> <p>My script:</p> <pre><code>import subprocess import json from kubernetes import client, config def renew_vault_token(vault_pod, token_id): try: result = subprocess.run( ['kubectl', 'exec', '-ti', vault_pod, '-n', 'vault', '--', 'vault', 'token', 'renew', '-accessor', token_id], capture_output=True, text=True, check=True ) output = result.stdout print(&quot;Vault renew output:&quot;, output) # Debugging output token_line = next(line for line in output.splitlines() if line.startswith('token')) new_token = token_line.split(None, 1)[1] print(new_token) return new_token except subprocess.CalledProcessError as e: print(f&quot;Error renewing token: {e}&quot;) return None if __name__ == &quot;__main__&quot;: VAULT_POD = 'vault-0' TOKEN_ID = '----------------' new_token = renew_vault_token(VAULT_POD, TOKEN_ID) </code></pre>
<python><python-3.x><kubernetes><hashicorp-vault><vault>
2024-09-19 14:14:37
1
1,677
poisoned_monkey
79,002,984
10,722,752
How to save all Plotly express graphs created using a for loop in a PDF?
<p>I am trying to save all the charts generated through a for loop in a SINGLE PDF file.</p> <p>My sample data:</p> <pre><code>import pandas as pd import numpy as np import plotly.io as pio import plotly.express as px import plotly.graph_objects as go np.random.seed(0) df = pd.DataFrame({'State' : np.repeat(['NY', 'TX', 'FL', 'PA'], 12), 'Month' : np.tile(pd.date_range('2023-09-01', '2024-08-01', freq = 'MS'), 4), 'Actual' : np.random.randint(1000, 1500, size = 48), 'Forecast' : np.random.randint(1000, 1500, size = 48)}) df['Month'] = pd.to_datetime(df['Month']) df.set_index('Month', inplace = True) </code></pre> <p>I am able to generate the charts in jupyter notebook using:</p> <pre><code>for s in df['State'].unique(): d = df.loc[df['State'] == s, ['Actual', 'Forecast']] fig = px.line(d, x = d.index, y = d.columns) fig.update_layout(title = 'Actuals vs Forecast for ' + s, template = 'plotly_dark', xaxis_title = 'Month') fig.update_xaxes(tickformat = '%Y-%B', dtick = 'M1') fig.show() </code></pre> <p>Can someone please let me know how to get all the charts in a single PDF file?</p> <p>I tried using<code>fig_trace</code> and <code>make_subplots</code> approach that uses Graph Object <code>go.Scatter</code> inplace of <code>px.line</code>, but it's not working.</p>
<python><pandas><plotly><pypdf>
2024-09-19 14:14:29
1
11,560
Karthik S