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
βŒ€
78,981,007
6,394,722
How to add namespace when add node to XML with xml.etree.ElementTree?
<p>I have next code to parse one XML string, and then add a new node to the XML. But you can see my code can only add <code>&lt;category term=&quot;Platform Version&quot; value=&quot;Linux_6.6&quot; /&gt;</code> without namespace. I need the <code>ns0</code> before <code>category</code>.</p> <p><code>test_xml.py</code>:</p> <pre class="lang-python prettyprint-override"><code>import xml.etree.ElementTree as ET source_str = &quot;&quot;&quot;&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt; &lt;ns0:testcase xmlns:ns0=&quot;http://jazz.net/xmlns/alm/qm/v0.1/&quot;&gt; &lt;ns0:category term=&quot;Platform Version&quot; value=&quot;Linux_5.4&quot;/&gt; &lt;/ns0:testcase&gt; &quot;&quot;&quot; xml_root = ET.fromstring(source_str) new_str = '&lt;category term=&quot;Platform Version&quot; value=&quot;Linux_6.6&quot;/&gt;' new_node = ET.fromstring(new_str) xml_root.append(new_node) final_str = ET.tostring(xml_root, encoding='utf-8').decode('utf-8') print(final_str) </code></pre> <p>Execution:</p> <pre class="lang-bash prettyprint-override"><code>$ python3 test_xml.py &lt;ns0:testcase xmlns:ns0=&quot;http://jazz.net/xmlns/alm/qm/v0.1/&quot;&gt; &lt;ns0:category term=&quot;Platform Version&quot; value=&quot;Linux_5.4&quot; /&gt; &lt;category term=&quot;Platform Version&quot; value=&quot;Linux_6.6&quot; /&gt;&lt;/ns0:testcase&gt; </code></pre> <p>My expectation:</p> <pre class="lang-xml prettyprint-override"><code>&lt;ns0:testcase xmlns:ns0=&quot;http://jazz.net/xmlns/alm/qm/v0.1/&quot;&gt; &lt;ns0:category term=&quot;Platform Version&quot; value=&quot;Linux_5.4&quot; /&gt; &lt;ns0:category term=&quot;Platform Version&quot; value=&quot;Linux_6.6&quot; /&gt;&lt;/ns0:testcase&gt; </code></pre> <p>If I change the code like this:</p> <pre class="lang-python prettyprint-override"><code>new_str = '&lt;ns0:category term=&quot;Platform Version&quot; value=&quot;Linux_6.6&quot;/&gt;' new_node = ET.fromstring(new_str) </code></pre> <p>It will just give me error:</p> <pre class="lang-python prettyprint-override"><code>Traceback (most recent call last): File &quot;/home/nxa13855/test_xml.py&quot;, line 11, in &lt;module&gt; new_node = ET.fromstring(new_str) File &quot;/usr/lib/python3.9/xml/etree/ElementTree.py&quot;, line 1347, in XML parser.feed(text) xml.etree.ElementTree.ParseError: unbound prefix: line 1, column 0 </code></pre> <p>How can I manage my aim?</p>
<python><xml><elementtree>
2024-09-13 06:55:16
2
32,101
atline
78,980,993
13,494,917
When comparing two dataframes in an azure function app, I receive this error- valueerror: the truth value of a series is ambiguous
<p>I have some logic here that I'm using to iterate through dataframes. My goal is to iterate through all of the rows in one dataframe and compare that row against every row found in another dataframe. So, where &quot;code&quot; matches in the two dataframes I want to</p> <ol> <li>Transform df2's code to equal df's&quot;code2&quot; value instead.</li> <li>Also transform df2's &quot;IsForm&quot;'s value to equal df's &quot;IsForm&quot;'s value.</li> </ol> <p><strong>If there is no match between code values on the two dataframes, transformation on df2 should not take place</strong></p> <p>Here is a small example of what I'm doing (this example works as expected):</p> <pre class="lang-py prettyprint-override"><code>df_dict = {'code':[388,289,200], 'code2':[1,2,3], 'IsForm':[1, 0, 0]} df = pd.DataFrame(df_dict) df2_dict = {'code':[388,289,200], 'IsForm':[0, 0, 0]} df2 = pd.DataFrame(df2_dict) for ind in df.index: for ind2 in df2.index: if df2['code'][ind2] == df['code'][ind]: df2['code'][ind2] = df['code2'][ind] if df['IsForm'][ind] == 1: df2['IsForm'][ind2] = 1 </code></pre> <p>The above example behaves as expected and transforms df2, but when working with actual data that I'm pulling from a couple tables and stuffing them into the dataframes, I receive this error, triggered by <code>if df['IsForm'][ind] == 1:</code>:</p> <blockquote> <p>exception: valueerror: the truth value of a series is ambiguous. use a.empty, a.bool(), a.item(), a.any() or a.all().</p> </blockquote> <p>I can run this code locally, even extract the actual data I'm using from an azure sql database and it performs just fine, but I receive this error when the code is run in the cloud. Regardless, how do I solve this issue and is there any better way to achieve my goal here? I'm sure this solution is quite slow so I'm looking to improve that if possible.</p>
<python><sql><pandas><dataframe><azure-functions>
2024-09-13 06:52:33
1
687
BlakeB9
78,980,960
12,466,687
How to get consistent results in tabular PDF parsing with llama-parse?
<p>I was parsing some PDF files using llama in Python with below code:</p> <pre><code>import os import pandas as pd import nest_asyncio nest_asyncio.apply() os.environ[&quot;LLMA_CLOUD_API_KEY&quot;] = &quot;some_key_id&quot; key_input = &quot;some_key_id&quot; from llama_parse import LlamaParse # running llama parsing doc_parsed = LlamaParse(result_type=&quot;markdown&quot;,api_key=key_input ).load_data(r&quot;Path\myfile.pdf&quot;) </code></pre> <p>The results of parsing the same document is <em>different</em> when I run this same code now from then. Difference is of <code>|</code> and line separation for the separations in tabular text.</p> <p>Is there a way to get the same old results in llama or to fix some parameters so that it works on same model or same way to always get same consistent results again &amp; again so that I can build Analytics on this based on same code logic?</p> <p>Last month's llama results:</p> <pre><code>print(doc_parsed[5].text[:1000]) </code></pre> <pre><code># Information |Name|: Mr. XXX| |---|---| |Age/Sex|: XX YRS/M| |Lab Id.|: 0124080X| |Refered By|: Self| |Sample Collection On|: 03/Aug/2024 08:30AM| |Collected By|: XXX| |Sample Lab Rec. On|: 03/Aug/2024 11:50 AM| |Collection Mode|: HOME COLLECTION| |Reporting On|: 03/Aug/2024 02:48 PM| |BarCode|: XXX| # Test Results |Test Name|Result|Biological Ref. Int.|Unit| |---|---|---|---| </code></pre> <p>Llama results on same PDF now:</p> <pre><code>print(doc_parsed[5].text[:1000]) </code></pre> <pre><code># Report Name: Mr. XXX Age/Sex: XXX YRS/M Lab Id: 0124080X Referred By: Self Sample Collection On: 03/Aug/2024 08:30 AM Collected By: XXX Sample Lab Rec. On: 03/Aug/2024 11:50 AM Collection Mode: HOME COLLECTION Reporting On: 03/Aug/2024 02:48 PM BarCode: XXX # Test Results Test Name Result Biological Ref. Int. Unit </code></pre> <p>Desired Results:</p> <pre><code># Above part doesn't matter but Test Results should be separated by | # Test Results |Test Name|Result|Biological Ref. Int.|Unit| </code></pre> <p>Is there a change of model at the back causing difference? Can I fix the model to get the consistent results?</p>
<python><pdf><pdf-parsing><llama-parse>
2024-09-13 06:44:26
2
2,357
ViSa
78,980,819
311,786
Using specific Django LTS version with cookiecutter-django
<p>Currently, the Cookiecutter Django template uses Django 5.0, which is not a long-term support (LTS) release.</p> <p>I couldn't find clear instructions in their documentation on how to specify a different Django version during installation.</p> <p>I'd like to use Django 4.2 with <a href="https://github.com/cookiecutter/cookiecutter-django" rel="nofollow noreferrer">cookiecutter-django</a> since it has LTS support until 2026. How can I do this?</p>
<python><django><cookiecutter-django>
2024-09-13 06:02:06
1
1,846
Manish
78,980,609
520,558
Weirdest behaviour (pycharm, python, virtual environment, loading error)
<p>Long story short: python &quot;sees&quot; some files but not others. <a href="https://i.sstatic.net/A2YbqY98.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/A2YbqY98.png" alt="the console inside pycharm" /></a></p> <p><a href="https://i.sstatic.net/4D0b6aLj.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/4D0b6aLj.png" alt="the files are there" /></a></p> <p>And this is what I'm trying to do:</p> <p>I want to use &quot;enchant&quot; spellchecking lib in python. I've written some code that works perfectly in external terminal (= linux terminal = system shell), but fails when I run under pycharm. The error message is &quot;<code>ImportError: The 'enchant' C library was not found and maybe needs to be installed.</code>&quot; These are other infos somehow related to the problem:</p> <ul> <li>I'm on Linux Pop OS</li> <li>the project has a virtual environment set up (python 3.11, and system is 3.10.12)</li> <li>the installed pyenchant in the venv is 3.2.2, I've also forced to 3.0.0 as seen somewhere, nothing improves</li> <li>I've tried &quot;<code>sudo systemctl stop apparmor</code>&quot; but it doesn't change anything. When apparmor is active it doesn't show any new entry when the code fails</li> <li>The code was giving that error on the system terminal, then I installed &quot;python3-enchant&quot; from deb package manager and it started working, but only in the terminal, not in pycharm</li> <li>pycharm is installed via flatpak</li> <li>I've overwritten the files in the venv pip package (pyenchant) with the contents from the deb package, with no luck. then I've restored the original ones</li> <li>I've tried adding global variables to pycharm runtime configuration. If I run the script without global variables I get the &quot;ImportError&quot;, but if I add &quot;<code>PYENCHANT_LIBRARY_PATH=/usr/lib/x86_64-linux-gnu/libenchant-2.so.2</code>&quot; to runtime configuration, I get &quot;<code>OSError: cannot open shared object file: No such file or directory</code>&quot;, that means, thinks the file doesn't exist, as shown in the screenshots.</li> </ul> <p>In short, I don't think it's a problem specific from the pyenchant library. I just find VERY weird that the simplest <code>os.path.exists</code> fails to detect the presence of some files, but detects others. They all are in the same folder and have similar attributes (readable permissions). I can't understand what is happening.</p>
<python><pycharm><python-venv>
2024-09-13 04:19:27
1
2,171
Attilio
78,980,496
2,985,331
Moving a class into a module and loading an instance from joblib
<p>I have a class called DiseaseTree defined in a file called diseaseTree.py. I have been using this class for a while. In a different workflow I have generated an instance of this class, and written to file using joblib.</p> <p>I am now attempting to construct a module, with this code in it. My directory structure looks like this:</p> <pre><code>/ /models __init__.py models.py diseaseTree.py /plots __init__.py plots.py __init__.py main.py </code></pre> <p>In models/<strong>init</strong>.py I have:</p> <pre><code>from .models import DatabaseConnector from .diseaseTree import DiseaseTree </code></pre> <p>In plots/plots.py, I have:</p> <pre><code>from models import DatabaseConnector from models import DiseaseTree import joblib with open(&quot;/data/projects/classifiers/data/diseaseTree.joblib&quot;, &quot;rb&quot;) as file: mainTree = joblib.load(file) </code></pre> <p>The imports work. When I attempt to load the joblib file, I get:</p> <pre><code>ModuleNotFoundError: No module named 'diseaseTree' </code></pre> <p>As best I can tell, it has something to do with the pickling process when the initial instance of DiseaseTree is dumped to file, but I have no idea how to rectify this. If I specifically add the class to sys.modules, I can fool it, i.e do this:</p> <pre><code>from models import DiseaseTree temp_module = types.ModuleType('diseaseTree') temp_module.DiseaseTree = DiseaseTree sys.modules['diseaseTree'] = temp_module </code></pre> <p>and then load the joblib file works. If I have to resort to this every time I want to load that instance of diseaseTree, I don't see the point in putting everything into modules in the first place.</p> <p>How do I either convert/update the instance stored in the joblib file, or handle this elegantly?</p>
<python><joblib>
2024-09-13 03:21:21
1
451
Ben
78,980,254
3,311,276
Why adding custom_openapi scema to FastAPI is causing the authorisation not to work?
<p>I have this FastAPI app working in the <code>main.py</code>:</p> <pre><code>app = FastAPI() app.add_middleware( CORSMiddleware, allow_origins=[&quot;*&quot;], allow_credentials=True, allow_methods=[&quot;*&quot;], allow_headers=[&quot;*&quot;], ) sub_app1 = FastAPI() sub_app1.include_router(auth.router) </code></pre> <p>and in the <code>routers/auth.py</code> I have:</p> <pre><code>@router.post(&quot;/complete&quot;, status_code=status.HTTP_201_CREATED) async def complete_registration_create_user(db: db_dependency, create_user_request: CreateUserRequest): &quot;&quot;&quot;Compeletes the registration when user submits password.&quot;&quot;&quot; hashed_password = bcrypt_context.hash(create_user_request.password) create_user_model = Users( email=create_user_request.email, hashed_password=hashed_password, phone=create_user_request.phone, ) # Note: In a organisation all staff members should be approved by Owner. try: db.add(create_user_model) await db.commit() except IntegrityError as er: raise HTTPException( status_code=status.HTTP_409_CONFLICT, detail=f&quot;User {create_user_request.email} already exists. Choose a different email or try resetting the password.&quot; ) await db.refresh(create_user_model) return {&quot;user&quot;: create_user_request.email} @router.post(&quot;/token&quot;, response_model=Token) async def user_login_for_access_token(form_data: Annotated[OAuth2EmailRequestForm, Depends()], db: db_dependency): &quot;&quot;&quot;Login user for an access token&quot;&quot;&quot; user = await authenticate_user(form_data.email, form_data.password, db) if not user: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail=&quot;Could not validate user.&quot; ) tenant_identifier = form_data.identifier token = create_access_token( user.email, user.id, tenant_identifier, timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES) ) return {'access_token': token, 'token_type': 'bearer'} </code></pre> <p>all above works but as soon as I add the below udpate to specify openschema to <code>main.py</code>:</p> <pre><code>def custom_openapi(): if sub_app1.openapi_schema: return sub_app1.openapi_schema openapi_schema = get_openapi( title=&quot; Authorisation API&quot;, version=&quot;0.0.1&quot;, description=&quot;API on this docs deals with all user and company registration.&quot;, routes=sub_app1.routes, ) sub_app1.openapi_schema = openapi_schema return sub_app1.openapi_schema sub_app1.openapi = custom_openapi </code></pre> <p>the auth endpoints starts resulting in Not found error i.e.</p> <pre><code>INFO: 127.0.0.1:43756 - &quot;POST /register/token?email=user2%40example.com&amp;identifier=sada&amp;password=string HTTP/1.1&quot; 404 Not Found INFO: 127.0.0.1:44748 - &quot;POST /register/complete HTTP/1.1&quot; 404 Not Found </code></pre> <p>What can I try next?</p>
<python><fastapi>
2024-09-13 00:28:15
1
8,357
Ciasto piekarz
78,980,144
17,275,378
Select Multiple Columns Efficiently in SQLModel
<p>I'm using <a href="https://github.com/fastapi/sqlmodel" rel="nofollow noreferrer">SQLModel</a>, which is a wrapper around SQLAlchemy.</p> <p>The data model includes:</p> <pre><code>class Line(SQLModel, table = True): id: int | None = Field(default = None, primary_key = True) name: str class Product(SQLModel, table = True): id: int | None = Field(default = None, primary_key = True) line_id: int | None = Field(default = None, foreign_key = 'line.id') myob_uid: str myob_name: str weight: float </code></pre> <p>An example query that selects a subset of columns from both tables:</p> <pre><code>query = select(Product.id, Product.weight, Line.name)\ .join(Line) </code></pre> <p>Notice the repetition of table name in the select statement. In SQLAlchemy we can do this:</p> <pre><code>select(Product.c['id','weight'], Line.c['name']) </code></pre> <p>However the c attribute is not available in SQLModel.</p> <p>Is there a way to subset a table by multiple columns without repeating the name?</p> <p>This is a pedantic request. However writing DRY queries is important as they become large and complex.</p> <p>I've tried both the following however they aren't as elegant for readability:</p> <ul> <li>Aliasing the tables to a letter (p or l for example).</li> <li><code>select(*[getattr(Product, x) for x in ['id','weight']], Line.name)</code>.</li> </ul>
<python><sqlmodel>
2024-09-12 22:59:12
1
326
eldrly
78,980,136
44,375
Face recognition test failing with correct image
<p>I'm beginning to explore face recognition but even my simple &quot;hello world&quot; is blowing up on my face.</p> <p>Here's the code:</p> <pre class="lang-python prettyprint-override"><code>import face_recognition from PIL import Image import numpy as np import base64 from io import BytesIO def test_face_recognition(image_path): # Open the image and ensure it's in RGB format img = Image.open(image_path).convert('RGB') # Convert image to numpy array img_np = np.array(img) # Check face detection face_locations = face_recognition.face_locations(img_np) print(f&quot;Faces detected: {len(face_locations)}&quot;) if len(face_locations) &gt; 0: face_encodings = face_recognition.face_encodings(img_np, known_face_locations=face_locations) print(f&quot;Encodings found: {len(face_encodings)}&quot;) else: print(&quot;No faces detected.&quot;) # Replace with the path to a local image file test_face_recognition(&quot;test_image.jpg&quot;) </code></pre> <p>The <code>test_image.jpg</code> can be any JPEG file with a face on it.</p> <p>When run, the code above explodes with the following error message:</p> <pre><code>Traceback (most recent call last): File &quot;C:\Users\User\source\repos\ballot-box\flask\test_face_recognition.py&quot;, line 25, in &lt;module&gt; test_face_recognition(&quot;test_image.jpg&quot;) File &quot;C:\Users\User\source\repos\ballot-box\flask\test_face_recognition.py&quot;, line 15, in test_face_recognition face_locations = face_recognition.face_locations(img_np) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File &quot;C:\Users\User\source\repos\ballot-box\flask\venv\Lib\site-packages\face_recognition\api.py&quot;, line 121, in face_locations return [_trim_css_to_bounds(_rect_to_css(face), img.shape) for face in _raw_face_locations(img, number_of_times_to_upsample, model)] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File &quot;C:\Users\User\source\repos\ballot-box\flask\venv\Lib\site-packages\face_recognition\api.py&quot;, line 105, in _raw_face_locations return face_detector(img, number_of_times_to_upsample) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ RuntimeError: Unsupported image type, must be 8bit gray or RGB image. </code></pre> <p>According to the error message, the image is in an invalid format but, before passing the face recognition function, I do convert to the appropriated format: <code>img = Image.open(image_path).convert('RGB')</code></p> <p><strong>Edited:</strong></p> <p>I changed from <em>img_np</em> to <em>img</em> to no avail. Now it explodes with the following error:</p> <pre><code>Traceback (most recent call last): File &quot;C:\Users\PauloSantos\source\repos\ballot-box\flask\test_face.py&quot;, line 25, in &lt;module&gt; test_face_recognition(&quot;test_image.jpg&quot;) File &quot;C:\Users\PauloSantos\source\repos\ballot-box\flask\test_face.py&quot;, line 15, in test_face_recognition face_locations = face_recognition.face_locations(img) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File &quot;C:\Users\PauloSantos\source\repos\ballot-box\flask\venv\Lib\site-packages\face_recognition\api.py&quot;, line 121, in face_locations return [_trim_css_to_bounds(_rect_to_css(face), img.shape) for face in _raw_face_locations(img, number_of_times_to_upsample, model)] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File &quot;C:\Users\PauloSantos\source\repos\ballot-box\flask\venv\Lib\site-packages\face_recognition\api.py&quot;, line 105, in _raw_face_locations return face_detector(img, number_of_times_to_upsample) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ TypeError: __call__(): incompatible function arguments. The following argument types are supported: 1. (self: _dlib_pybind11.fhog_object_detector, image: numpy.ndarray, upsample_num_times: int = 0) -&gt; _dlib_pybind11.rectangles Invoked with: &lt;_dlib_pybind11.fhog_object_detector object at 0x000001A8DB8E0370&gt;, &lt;PIL.Image.Image image mode=RGB size=1280x720 at 0x1A8FBD47110&gt;, 1 </code></pre> <hr/> <p><strong>Solved</strong></p> <p>The problem is the <code>numpy</code> version 2.0. According to <a href="https://stackoverflow.com/a/78638053/44375">this answer</a> the problem occurs due to a breaking change on <code>numpy</code>. Reverting to <code>numpy</code> 1.26.4 solved the problem.</p>
<python><face-recognition>
2024-09-12 22:54:08
1
11,730
Paulo Santos
78,980,100
1,444,564
Python/Oct2Py/Octave Setup Woes
<p>In Windows 10 or 11, I am trying to set up a Python/Oct2Py/Octave environment so that I can write Python scripts that can invoke Octave functionality. I set this up on my own machine, and got it working about a year ago. Now I am trying to replicate this setup, but my notes must be somewhat deficient, as I run into errors doing the simplest tasks. For example, in the Octave CLI, I can run this command:</p> <pre><code>octave:1&gt; pwd() ans = C:\Users\bob </code></pre> <p>In my working Anaconda Powershell, I can run this equivalent:</p> <pre><code>(base) PS C:\Users\bob&gt; python Python 3.9.12 (main, Apr 4 2022, 05:23:19) [MSC v.1916 32 bit (Intel)] :: Anaconda, Inc. on win32 Type &quot;help&quot;, &quot;copyright&quot;, &quot;credits&quot; or &quot;license&quot; for more information. &gt;&gt;&gt; from oct2py import Oct2Py &gt;&gt;&gt; o = Oct2Py() &gt;&gt;&gt; o.pwd() 'C:\\Users\\bob' &gt;&gt;&gt; </code></pre> <p>However, in my new setup, I run into problems:</p> <pre><code>(base) PS C:\Users\rsg&gt; python Python 3.9.12 (main, Apr 4 2022, 05:23:19) [MSC v.1916 32 bit (Intel)] :: Anaconda, Inc. on win32 Type &quot;help&quot;, &quot;copyright&quot;, &quot;credits&quot; or &quot;license&quot; for more information. &gt;&gt;&gt; from oct2py import Oct2Py &gt;&gt;&gt; o = Oct2Py() &gt;&gt;&gt; o.pwd() Traceback (most recent call last): File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt; File &quot;C:\ProgramData\Anaconda3\lib\site-packages\oct2py\dynamic.py&quot;, line 111, in __call__ return self._ref().feval(self.name, *inputs, **kwargs) File &quot;C:\ProgramData\Anaconda3\lib\site-packages\oct2py\core.py&quot;, line 403, in feval return self._feval( File &quot;C:\ProgramData\Anaconda3\lib\site-packages\oct2py\core.py&quot;, line 620, in _feval write_file(req, out_file, oned_as=self._oned_as, convert_to_float=self.convert_to_float) File &quot;C:\ProgramData\Anaconda3\lib\site-packages\oct2py\io.py&quot;, line 58, in write_file data = _encode(obj, convert_to_float) File &quot;C:\ProgramData\Anaconda3\lib\site-packages\oct2py\io.py&quot;, line 351, in _encode out[key] = _encode(value, ctf) File &quot;C:\ProgramData\Anaconda3\lib\site-packages\oct2py\io.py&quot;, line 376, in _encode if isinstance(data, spmatrix): NameError: name 'spmatrix' is not defined &gt;&gt;&gt; </code></pre> <p>In both cases, all the software is the same:</p> <ol> <li>Windows 11 Home</li> <li>Anaconda (2022.05 - Python 3.9.12)</li> <li>Oct2Py (installed via &quot;conda install -c conda-forge oct2py&quot;)</li> <li>Octave 8.2.0</li> </ol> <p>I cannot figure out what is going on with the new install (I've tried it on three separate machines, and they all fail).</p>
<python><octave><oct2py>
2024-09-12 22:28:08
1
723
Bob
78,979,833
8,086,892
Monkeypatch Extract step in ETL data pipeline for functional testing
<p>Consider an ETL pipelines repo build like that:</p> <pre><code>etl_repo β”œβ”€β”€ app β”œβ”€β”€ extract β”œβ”€β”€ extr_a.py β”œβ”€β”€ extr_b.py β”œβ”€β”€ transform β”œβ”€β”€ trans_a.py β”œβ”€β”€ trans_b.py β”œβ”€β”€ load β”œβ”€β”€ load_a.py β”œβ”€β”€ load_b.py β”œβ”€β”€ config.py β”œβ”€β”€ my_job1.py β”œβ”€β”€ tests β”œβ”€β”€ test_my_job1.py </code></pre> <p>I am running in a production server <code>python app/my_job1.py</code> on a periodic basis. The job(s) are importing functions from the different ETL models stored in the repo (extract, transform and load). I have unit tests coverage for the ETL models but I would like functional (end to end) testing for the actual job(s).</p> <p>I learned about monkeypatch with pytest to load static data instead of relying on my extract network ressources. It is working as expected.</p> <p>However I cannot figure out what would be the best way to monkeypatch my extract models and make the test execute the <code>python app/my_job1.py</code> command, as if it was in production.</p> <p>I would like to avoid having to copy the full job into another test function with monkeypatch fixture. Although technically working, it would be painful to modify both the job and its test each and every time.</p> <p>The functional test has to be as close as possible to what the production system is doing.<br /> I tried to use subprocess to create a child process from inside the test method but the child process itself is not inheriting from the monkeypatched imports.<br /> I would like to avoid having to inject test code/import in <code>my_job1.py</code>, within conditions like <code>if Config.ETL_ENV == &quot;TEST&quot;</code>, just to keep my code clean between code and tests.</p> <p>UPDATE:</p> <p>I finally encapsulated <code>my_job1.py</code> execution into a function and calling it within <code>if __name__ == &quot;__main__&quot;:</code>.<br /> Execution is still called when using the production command <code>python app/my_job1.py</code> but now I can import the my_job1.py inside the pytest file and exec the function later on (after applying my monkeypatch)</p> <p>My issue remains though: when executing the my_job1 main function, the extract is not patched!</p> <p>Here is an example pytest file following my previous repo structure:</p> <pre><code>from app.extract import extr_a from app import my_job1 @pytest.fixture def mock_getdata_extra_a(monkeypatch): def mock_func(aref): with open(&quot;staticpickle.pkl&quot;, &quot;rb&quot;) as file: data = pickle.load(file) return data[aref] monkeypatch.setattr(extr_a, &quot;getdata&quot;, mock_func) def test_my_job1( mock_getdata, ): # attempt with the run method now from the script; # monkeypatch should be fine now since the import has been done, # we applied the monkeypatch afterward, # and we call the job run from within the same python process/env # this is monkeypatched extra_a.getdata(&quot;thisisaref&quot;) # this is not!!! the my_job1 is importing app.extract.extr_a on its own and using the extra_a.getdata... but this time the monkeypatch is not applied my_job1.main() </code></pre>
<python><pytest><monkeypatching>
2024-09-12 20:22:59
2
347
mouch
78,979,548
6,930,340
Create list column out of column names
<p>I have a simple <code>pl.DataFrame</code> with a number of columns that only contain boolean values.</p> <pre><code>import polars as pl df = pl.DataFrame( {&quot;s1&quot;: [True, True, False], &quot;s2&quot;: [False, True, True], &quot;s3&quot;: [False, False, False]} ) shape: (3, 3) β”Œβ”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β” β”‚ s1 ┆ s2 ┆ s3 β”‚ β”‚ --- ┆ --- ┆ --- β”‚ β”‚ bool ┆ bool ┆ bool β”‚ β•žβ•β•β•β•β•β•β•β•ͺ═══════β•ͺ═══════║ β”‚ true ┆ false ┆ false β”‚ β”‚ true ┆ true ┆ false β”‚ β”‚ false ┆ true ┆ false β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”˜ </code></pre> <p>I need to add another column that contains lists of varying length. A list in any individual row should contain the column name where the values of the columns <code>S1</code>, <code>s2</code>, and <code>s3</code> have a <code>True</code> value.</p> <p>Here's what I am actually looking for:</p> <pre><code>shape: (3, 4) β”Œβ”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ s1 ┆ s2 ┆ s3 β”‚ list β”‚ β”‚ --- ┆ --- ┆ --- β”‚ --- β”‚ β”‚ bool ┆ bool ┆ bool β”‚ list[str] β”‚ β•žβ•β•β•β•β•β•β•β•ͺ═══════β•ͺ═══════║══════════════║ β”‚ true ┆ false ┆ false β”‚ [&quot;s1&quot;] β”‚ β”‚ true ┆ true ┆ false β”‚ [&quot;s1&quot;, &quot;s2&quot;] β”‚ β”‚ false ┆ true ┆ false β”‚ [&quot;s2&quot;] β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ </code></pre>
<python><python-polars>
2024-09-12 18:45:17
3
5,167
Andi
78,979,442
7,700,802
Get subset of dataframe following a condition from a dictionary
<p>I am trying to find instances of where three columns may exceed some number that is stored in a dictionary. I know this code works, but I think there is a better more pythonic way of doing this.</p> <pre><code>l = [] for index, row in df_usage.iterrows(): item_id = row['item_id'] try: if ( row['start_count'] &gt; historical_orders_dict[item_id] or row['end_count'] &gt; historical_orders_dict[item_id] or row['received_total'] &gt; historical_orders_dict[item_id] ): l.append(df_usage.loc[[index], :]) except: pass df_too_many_consuables = pd.concat(l).reset_index(drop=True) df_too_many_consuables.shape </code></pre> <p>Here is an example</p> <pre><code>historical_orders_dict = { '10346': 28644.99, '10877': 28979.99, '10695': 6200.0, '70020': 1960.0, '40265': 57300.0, '91524': 9750.0, '60022': 200.0, '10210': 156.0, '11040': 49350.0} data = { 'item_id': ['10346', '10877', '10695', '70020', '40265', '91524', '60022', '10210','11040'], 'start_count': [100000000, 2, 3, 4, 5, 6, 7, 8, 9], 'end_count': [10, 11, 12, 13, 14, 15, 16, 17, 18], 'received_total': [19, 20, 21, 22, 23, 24, 46, 45, 34]} df_usage = pd.DataFrame(data=data) </code></pre>
<python><pandas>
2024-09-12 18:01:00
1
480
Wolfy
78,979,400
9,064,615
How to set width/height of widgets within a Paned Window widget in Tkinter after initialization?
<p>I'm trying to create a save/restore functionality in my Tkinter GUI, but I'm having trouble restoring the width/height of Widgets within a Paned Window. I've tried .place() and .config, but the resizable window around each of the widgets disappears and I can no longer resize each widget.</p> <p>Example code:</p> <pre class="lang-py prettyprint-override"><code>from tkinter import * root = Tk() pw = PanedWindow(root) text1 = Text(pw) pw.add(text1) text2 = Text(pw) pw.add(text2) entry1 = Entry(pw) pw.add(entry1) </code></pre> <p>EDIT: No longer using TTK</p> <p>EDIT2: No longer using Tkinter. Switched to PyQt5 and everything just works.</p>
<python><python-3.x><tkinter>
2024-09-12 17:50:53
3
608
explodingfilms101
78,979,258
163,679
Configure python argparse to accept an optional argument multiple times, like `grep --exclude`
<p>How do I configure a python <code>argparse</code> object to accept an optional argument multiple times, similar to how I can pass <code>--exclude</code> to <code>grep</code> mutliple times?</p> <pre><code># Command line example python main.py --exclude=foo.js --exclude=bar.java # args.exclude should be ['foo.js', 'bar.java'] python main.py --exclude=foo.js # args.exclude should be ['foo.js'] python main.py # args.exclude should be [] python main.py --exclude foo.js bar.java # Reject this, or don't put bar.java in list python main.py --exclude # Reject this </code></pre> <p>I tried this code, but it only accepts the last <code>--exclude</code> argument. The previous ones are discarded.</p> <pre class="lang-py prettyprint-override"><code>import argparse parser = argparse.ArgumentParser() parser.add_argument( '--exclude', type=str, nargs='*', default=[], help='Something to exclude') args = parser.parse_args('--exclude=foo.js --exclude=bar.java'.split(' ')) print(args.exclude) </code></pre> <pre class="lang-bash prettyprint-override"><code># output ['bar.java'] # actual output ['foo.js', 'bar.java'] # desired output </code></pre> <p>Additional requirements</p> <ol> <li><code>--exclude</code> should be optional. <code>args.exclude</code> should be an empty list if exclude isn't supplied</li> <li>If <code>--exclude</code> is supplied, it should have 1 and only 1 argument.</li> </ol>
<python><argparse>
2024-09-12 17:07:27
1
2,673
bigh_29
78,979,081
2,928,970
Python exception stack trace not full when function is wrapped
<p>I have two files <code>t.py</code>:</p> <pre><code>import functools import traceback def wrapper(func): @functools.wraps(func) def wrapped(*args, **kwargs): try: return func(*args, **kwargs) except Exception as e: traceback.print_exception(e) return wrapped @wrapper def problematic_function(): raise ValueError(&quot;Something went wrong&quot;) </code></pre> <p>and t2.py:</p> <pre><code>from t import problematic_function problematic_function() </code></pre> <p>when I call from command line <code>python t2.py</code>, the stack trace information that has info from <code>t2.py</code> is lost when printing <code>traceback.print_exception(e)</code> in the <code>t.py</code>. What I get is</p> <pre><code>Traceback (most recent call last): File &quot;/home/c/t.py&quot;, line 9, in wrapped return func(*args, **kwargs) File &quot;/home/c/t.py&quot;, line 18, in problematic_function raise ValueError(&quot;Something went wrong&quot;) ValueError: Something went wrong </code></pre> <p>where as if I remove the decorator I get:</p> <pre><code>Traceback (most recent call last): File &quot;/home/c/t2.py&quot;, line 3, in &lt;module&gt; problematic_function() File &quot;/home/cu/t.py&quot;, line 17, in problematic_function raise ValueError(&quot;Something went wrong&quot;) ValueError: Something went wrong </code></pre> <p>How do I get the full stack trace in the wrapped function as without the wrapper? Thanks!</p>
<python><exception><wrapper><python-decorators>
2024-09-12 16:15:06
2
1,395
hovnatan
78,978,944
4,817,370
TimescaleDB not accepting intervales less than one day
<p>I have a timescaleDB but I cannot seem to be able to use the time_bucket method with less than one day intervals.</p> <p>The code attempting to access it is running inside of a fast API and is as follows :</p> <pre class="lang-py prettyprint-override"><code> async def get_candlestick_data(self, db: AsyncSession, market_name: str, resource_name: str, interval: str): sql = f&quot;&quot;&quot; SELECT time_bucket('{interval}', timestamp) as period, FIRST(price, timestamp) as open, MAX(price) as high, MIN(price) as low, LAST(price, timestamp) as close, SUM(quantity) as volume FROM resource_market_value WHERE market_name = :market_name AND resource_name = :resource_name GROUP BY period ORDER BY period; &quot;&quot;&quot; result = await db.execute(text(sql), {'market_name': market_name, 'resource_name': resource_name}) return result.fetchall() </code></pre> <p>Here is the model I am using :</p> <pre class="lang-py prettyprint-override"><code>from sqlalchemy import DateTime from sqlalchemy import Column, Integer, String, BigInteger from common_modules.database.base import Base class ResourceMarketValue(Base): __tablename__ = 'resource_market_value' id = Column(BigInteger, primary_key=True, autoincrement=True) market_name = Column(String, nullable=False) resource_name = Column(String, nullable=False) timestamp = Column(DateTime, nullable=False) price = Column(Integer, nullable=False) quantity = Column(Integer, nullable=False) </code></pre> <p>And here is the only configuration / edit I am doing to the table :</p> <pre><code>SELECT create_hypertable('resource_market_value', 'timestamp'); </code></pre> <p>The issue is that the TimescaleDB is not accepting intervals of less than one day. Here are the logs I am getting :</p> <pre><code>2024-09-12 14:59:54.455 UTC [50740] ERROR: interval must not have sub-day precision 2024-09-12 14:59:54.455 UTC [50740] STATEMENT: SELECT time_bucket('15 minutes', timestamp) as period, FIRST(price, timestamp) as open, MAX(price) as high, MIN(price) as low, LAST(price, timestamp) as close, SUM(quantity) as volume FROM resource_market_value WHERE market_name = $1 AND resource_name = $2 GROUP BY period ORDER BY period; 2024-09-12 14:59:54.456 UTC [50741] ERROR: could not map dynamic shared memory segment 2024-09-12 14:59:54.456 UTC [50742] ERROR: could not map dynamic shared memory segment 2024-09-12 14:59:54.458 UTC [1] LOG: background worker &quot;parallel worker&quot; (PID 50741) exited with exit code 1 2024-09-12 14:59:54.459 UTC [1] LOG: background worker &quot;parallel worker&quot; (PID 50742) exited with exit code 1 </code></pre> <p>What makes me very confused is that I am not seeing any for of configuration being mentioned in the documentation of the <code>time_bucket</code> as seen here : <a href="https://docs.timescale.com/use-timescale/latest/time-buckets/use-time-buckets/" rel="nofollow noreferrer">https://docs.timescale.com/use-timescale/latest/time-buckets/use-time-buckets/</a> <br/> If anything, it seems like I should be able to do so.</p> <p>The intent with my code on the long run is to be able to have market values being displayed in a candlestick chart and I'll need to be able to have up to 15 minutes per candle as minimum and 1 day as maximum.<br/> Currently the only data in the database is test data that I inserted. There is one entry per minute, no more.<br/> Ideally, if possible, I would like to automate the configuration and not navigate to a web page if changing configuration is needed.</p> <p>Edit : the version of timescaleDB I am using is the 2.16.1 as seen here :</p> <pre><code>psql (14.12) Type &quot;help&quot; for help. timescaledb=# SELECT default_version, installed_version FROM pg_available_extensions WHERE name = 'timescaledb'; default_version | installed_version -----------------+------------------- 2.16.1 | 2.16.1 (1 row) timescaledb=# SELECT version(); version --------------------------------------------------------------------------------------------------------------- PostgreSQL 14.12 on x86_64-pc-linux-musl, compiled by gcc (Alpine 13.2.1_git20240309) 13.2.1 20240309, 64-bit (1 row) </code></pre> <p>I will also add that it is as unconfigured as it can get. It has the password and username through environ values and that is it.</p>
<python><sqlalchemy><fastapi><timescaledb>
2024-09-12 15:38:49
2
2,559
Matthieu Raynaud de Fitte
78,978,937
1,818,713
In a python stubs file, how to have a type without importing an external package?
<p>Suppose I want to annotate pyarrow's <code>pq.ParquetFile</code> which takes a filesystem parameter. A valid input to that parameter is pyarrow's own FileSystem implementation. That is easy enough to just have <code>filesystem: FileSystem | None</code> but what I really want is <code>filesystem: FileSystem | fsspec.AbstractFileSystem | None</code> but the stubs shouldn't impose a dependency and since it's a <code>pyi</code> file it can't have <code>try</code> import (I don't think). While this is specifically what I'm actually trying to do I'm hoping it's a general solution not specific to pyarrow or fsspec.</p> <p>Is there a way to do this?</p> <p>I found <a href="https://stackoverflow.com/q/60259717/1818713">this</a> but it's a few years old so hoping there's a way to do it now.</p>
<python><python-typing>
2024-09-12 15:36:59
0
19,938
Dean MacGregor
78,978,810
12,466,687
How to use st.file_uploader() returned object to parse pdf through LlamaParse() in python streamlit?
<p>I am trying to upload a PDF using <code>st.file_uploader()</code> from <code>streamlit</code> and then parse it using <code>LlamaParse()</code> currently running on <code>localhost</code>.</p> <p>Issue is I am getting <code>[]</code> in output which is probably happening because of directly using returned <code>uploaded_file</code> from the below code.</p> <p>I am not sure if a returned <code>uploaded object</code> can directly be used to feed <code>llama_parse</code> as this PDF works when I directly upload the PDF from my local machine directory into <code>LlamaParse()</code> instead of <code>uploaded_file = st.file_uploader()</code></p> <p>Is there something that I need to do for using <code>uploaded_file</code> before feeding it into <code>LlamaParse()</code>?</p> <ol> <li><p>Setting up <code>streamlit</code>:</p> <pre><code>import streamlit as st import pandas as pd import os import nest_asyncio nest_asyncio.apply() os.environ[&quot;LLMA_CLOUD_API_KEY&quot;] = &quot;my_key&quot; key_input = &quot;my_key&quot; from llama_parse import LlamaParse ############### Setting Configuration ############### st.set_page_config(page_title=&quot;Pdf Parsing&quot;, layout='wide', initial_sidebar_state=&quot;expanded&quot;) # title st.markdown(&quot;&lt;h1 style='text-align: center; font-size: 70px;color: black;letter-spacing: 4px;'&gt;PDF Parsing&lt;/h1&gt;&quot;, unsafe_allow_html=True) </code></pre> </li> <li><p>Uploading file &amp; parsing through Llama:</p> <pre><code>st.write(&quot;checkpoint1&quot;) with st.container(border=True): st.write(&quot;checkpoint2&quot;) uploaded_file = st.file_uploader('Choose your .pdf file to upload', type=&quot;pdf&quot;) if uploaded_file is not None: st.write(uploaded_file.name) st.success(&quot;File is uploaded&quot;) if uploaded_file: if st.button('Parse Uploaded pdf file (Powered by AI)'): doc_parsed = LlamaParse(result_type=&quot;markdown&quot;,api_key=key_input ).load_data(uploaded_file) st.write('checkpoint3') st.write(doc_parsed) </code></pre> </li> </ol> <p><a href="https://i.sstatic.net/cWq2MI7g.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/cWq2MI7g.png" alt="Streamlit Output" /></a></p> <p><strong>UPDATE:</strong></p> <p>Is this happening <strong>Due to Not Using</strong> <code>st.session_state</code> ?</p> <p>Could it be a possibility that when I click the <strong>button</strong> then the whole <strong>app refreshes/runs</strong> again and the file gets lost and nothing goes into llama ?</p>
<python><pdf><file-upload><streamlit><llama>
2024-09-12 15:02:57
1
2,357
ViSa
78,978,783
607,846
Iterate over batch size for each batch
<p>Its there a more pythonic way, or built in function in python to do the following:</p> <pre><code>def batch(number, batch_size): number_left = number while number_left: if number_left &gt;= batch_size: yield batch_size number_left -= batch_size else: yield number_left number_left = 0 </code></pre> <p><code>batch(21,10)</code> outputs: <code>[10,10,1]</code></p>
<python>
2024-09-12 14:58:30
3
13,283
Baz
78,978,757
13,158,157
How to prevent Calamine from auto-guessing data types when reading Excel files
<p>I’m working with an Excel file and need to read its contents into a DataFrame. When I use pandas (with default engine), I can specify the data type of the columns to be strings, which works perfectly:</p> <pre><code>import pandas as pd df = pd.read_excel(fp, dtype=str, nrows=10) print(df[col]) </code></pre> <p>This gives me a column with values like:</p> <p><code>4200000000</code></p> <p>However, when I use Calamine to read the same file, the values in the same column end up with a .0 suffix:</p> <pre><code>from calamine import CalamineWorkbook wb = CalamineWorkbook.from_path(fp) row_list = wb.get_sheet_by_name(wb.sheet_names[0]).to_python() print(row_list) </code></pre> <p>This results in: <code>4200000000.0</code></p> <p>How can I stop Calamine from auto-guessing the data types? In pandas, I would use dtype=str, but my version of pandas does not support Calamine as an engine, and I cannot update it.</p>
<python><excel><pandas><calamine>
2024-09-12 14:54:40
1
525
euh
78,978,753
8,297,745
How to manage concurrent API token updates in a Python script using a ini file for multiple clients?
<p>I’m working on a Low-Level Discovery (LLD) script for Zabbix, which is set up as an &quot;External&quot; item. The script interacts with Aruba’s API to generate hosts for different clients based on their specific sites and devices.</p> <p>The Aruba API requires authentication via access tokens, which expire after a set period. When the token expires, I need to refresh it using a refresh token.</p> <p>The challenge here is that I need to manage API credentials for multiple clients... Each client that is monitored in my LLD needs a client ID, client secret, access token, and a refresh token.</p> <p>The script is executed simultaneously for different clients.. It access those informations in a <code>.ini</code> file I created.</p> <p>The <code>ini</code> file has something like this:</p> <pre class="lang-ini prettyprint-override"><code>[client1] client_id client_secret access_token refresh_token [client2] client_id client_secret access_token refresh_token </code></pre> <p>However, whenever the script runs concurrently (for example, for 5 clients at once), which happens whenever my discovery rule is executed, the tokens in the <code>.ini</code> file sometimes get lost or overwritten, leading to issues in API authentication. So, i do not know how can I do this using the same INI file.</p> <p>Here’s what I’ve tried:</p> <ol> <li>I implemented <strong>file locking</strong> using <code>fcntl</code> to prevent multiple processes from writing to the file at the same time. So kind of a queue should be created...</li> <li>Each client’s tokens are stored in a separate section of the <code>.ini</code> file, and each script execution is responsible for updating its own client’s section.</li> <li>I expected file locking to prevent issues with tokens being overwritten, but despite using this approach, the tokens still sometimes get lost or corrupted when the script runs concurrently for multiple clients.</li> </ol> <p>None of my implementations worked. Since I don't have a database I can use with a table to manage my tokens, how could I manage those tokens using my python script to manage multiple tokens using local files? I also cannot create a local sqlite since the script is pretty simple and my client needs a simple structure (Like INI file...) to manage their clients.</p> <p>I expected the tokens to be safely updated and written to the <code>.ini</code> file without any loss or corruption but they keep getting overwritten on each interaction wronglly. Anyone has an idea on what I could do in this scenario?</p> <hr /> <h3>Additional Information:</h3> <p>For anyone interested in reviewing the code, it’s available on my GitHub repository:<br /> <a href="https://github.com/HorselessName/monitoramento-aruba" rel="nofollow noreferrer">https://github.com/HorselessName/monitoramento-aruba</a></p> <hr />
<python><zabbix>
2024-09-12 14:54:12
0
849
Raul Chiarella
78,978,581
247,542
Playwright test failing in headless mode due to Paypal button
<p>I have a Playwright test that confirms an e-commerce site's checkout process works, which terminates in clicking a Paypal button, logging into Paypal, and clicking submit payment.</p> <p>In headed mode, it can interact with the Paypal popup just fine, but in headless mode, the Paypal widget doesn't render at all, and therefore there's no button to click. I've confirmed this using Playwright's <code>page.screenshot()</code> method.</p> <p>From what I've read, this is a common problem because Paypal doesn't know their customers write integration tests, and therefore they treat any headless usage as evil bots trying to hack their sandbox site.</p> <p>Is there any known workaround?</p> <p>I'm running my test as part of a Django test case and the relevant Playwright startup code looks like:</p> <pre><code>SHOW = bool(int(os.environ.get('SHOW', 0))) class Tests(StaticLiveServerTestCase): @classmethod def setUpClass(cls): os.environ[&quot;DJANGO_ALLOW_ASYNC_UNSAFE&quot;] = &quot;true&quot; super().setUpClass() cls.playwright = sync_playwright().start() cls.browser = cls.playwright.chromium.launch(headless=not SHOW) </code></pre> <p>I've tried passing in &quot;--disable-web-security&quot;, &quot;--use-gl=desktop&quot;, &quot;--disable-features=IsolateOrigins&quot;, and &quot;--disable-site-isolation-trials&quot;, to <code>launch(args=[...])</code> but those either have no effect or break the Paypal widget even in headed mode.</p>
<python><paypal><playwright><playwright-python>
2024-09-12 14:15:34
0
65,489
Cerin
78,978,563
24,191,255
Colouring a surface using go.Surface in plotly
<p>I aim to colour a surface in a 3d plot, created using <code>plotly.graph_objects</code>.</p> <p>I've been working on an approach incorporating <code>Mesh3d</code>, the code runs, but the wanted surface is not coloured. How can this be solved in <code>plotly</code>?</p> <p>The final outcome should look similar to this example plot: <a href="https://i.sstatic.net/VVevNBth.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/VVevNBth.png" alt="enter image description here" /></a></p> <p>And this is where I am at now: <a href="https://i.sstatic.net/OlxwtWq1.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/OlxwtWq1.png" alt="enter image description here" /></a></p> <p>So, the aim is to colour the surface where the vertical lines are connecting the two curves (i.e., a 3-dimensional curve and its projection onto the x-y plane).</p> <p>Example data can be obtained <a href="https://docs.google.com/spreadsheets/d/1NaTLLoo4cr38W5UzFLgiscqfU6YiN0a4HjIoc_tI9gg/edit?usp=sharing" rel="nofollow noreferrer">here</a>.</p> <p>Here is my code:</p> <pre><code>import pandas as pd import plotly.graph_objects as go import numpy as np data = pd.read_excel(r&quot;&quot;) x = data['x'].values y = data['y'].values z = data['alt'].values z_min_adjusted = np.maximum(z, 350) def plot_3d_course_profile(x, y, z, color_attribute, colorbar_label): fig = go.Figure() # Projection at z = 350 fig.add_trace(go.Scatter3d( x=x, y=y, z=[350] * len(x), mode='lines', line=dict( color='black', width=5, ) )) # Profile curve fig.add_trace(go.Scatter3d( x=x, y=y, z=z, mode='lines', line=dict( color=color_attribute, width=13, colorscale='Jet', colorbar=dict( title=dict( text=colorbar_label, font=dict(size=14, color='black') ), thickness=20, len=0.6, tickfont=dict(size=12, color='black'), tickmode='linear', tickformat='.2f', outlinewidth=1, outlinecolor='black' ) ) )) # Vertical lines for i in range(0, len(x), 20): xi, yi, zi = x[i], y[i], z[i] fig.add_trace(go.Scatter3d( x=[xi, xi], y=[yi, yi], z=[350, zi], mode='lines', line=dict(color='dimgray', width=4), opacity=0.6, showlegend=False )) #Layout fig.update_layout( template='plotly_white', scene=dict( xaxis=dict(title='Meters north from start position', showgrid=True, gridcolor='lightblue', zeroline=False), yaxis=dict(title='Meters east from start position', showgrid=True, gridcolor='lightblue', zeroline=False), zaxis=dict(title='Altitude [m]', showgrid=True, gridcolor='lightblue', zeroline=False), aspectmode='manual', aspectratio=dict(x=1.25, y=1, z=0.7) ), title=f'{colorbar_label}', margin=dict(l=0, r=0, b=0, t=50) ) fig.show() plot_3d_course_profile(x, y, z_min_adjusted, z_min_adjusted, 'Altitude [m]') </code></pre>
<python><arrays><plot><plotly><surface>
2024-09-12 14:10:56
1
606
MΓ‘rton HorvΓ‘th
78,978,557
1,424,395
Plotting each row in a pandas DataFrame as a bar with seaborn
<p>Given such a dataframe,</p> <pre><code>data = pd.DataFrame({'a':[1,2],'b':[2,3],'c':[3,4],'d':[1,2],'code':[1,2]}) a b c d code 0 1 2 3 1 1 1 2 3 4 2 2 </code></pre> <p>I want to have a barplot with a 2 bars for each column (one for each row...)</p> <p>this one</p> <pre><code>sns.barplot(data.iloc[0]) </code></pre> <p>works just fine,</p> <p><a href="https://i.sstatic.net/FhjK14Vo.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/FhjK14Vo.png" alt="barplot 1 column" /></a></p> <p>but when i try to doit for 2 columns,</p> <pre><code>sns.barplot(data,hue='code') </code></pre> <p>claims:</p> <blockquote> <p>ValueError: The following variable cannot be assigned with wide-form data: <code>hue</code></p> </blockquote>
<python><pandas><seaborn>
2024-09-12 14:09:33
1
1,827
myradio
78,978,475
17,082,611
Unable to import module 'main': No module named 'pydantic_core._pydantic_core when deploying a FastAPI app to AWS Lambda
<p>I am working on my MacOS machine following <a href="https://www.youtube.com/watch?v=7-CvGFJNE_o" rel="nofollow noreferrer">this tutorial</a>.</p> <p>I am trying to deploy my FastAPI app to AWS Lambda.</p> <p>I launched <code>pip install fastapi uvicorn mangum</code></p> <p>and these are the dependencies I get:</p> <pre><code>Package Version ----------------- ------- annotated-types 0.7.0 anyio 4.4.0 click 8.1.7 fastapi 0.114.1 h11 0.14.0 idna 3.8 mangum 0.17.0 pip 24.2 pydantic 2.9.1 pydantic_core 2.23.3 sniffio 1.3.1 starlette 0.38.5 typing_extensions 4.12.2 uvicorn 0.30.6 </code></pre> <p>Then leaving only <code>fastapi</code> and <code>mangum</code>, as the guy in the tutorial says:</p> <pre><code>fastapi==0.114.1 mangum==0.17.0 </code></pre> <p>Then I created my app:</p> <pre><code>from fastapi import FastAPI from mangum import Mangum app = FastAPI() handler = Mangum(app) @app.get(&quot;/&quot;) async def hello(): return {&quot;message&quot;: &quot;Hello World&quot;} </code></pre> <p>and ran:</p> <pre><code> pip3 install -t dependencies -r requirements.txt </code></pre> <p>and then:</p> <pre><code>(cd dependencies; zip ../aws_lambda_artifact.zip -r .) </code></pre> <p>and finally:</p> <pre><code>zip aws_lambda_artifact.zip -u main.py </code></pre> <p>Then I uploaded the <code>zip</code> file into AWS Lambda but I am getting:</p> <pre><code>{ &quot;errorMessage&quot;: &quot;Unable to import module 'main': No module named 'pydantic_core._pydantic_core'&quot;, &quot;errorType&quot;: &quot;Runtime.ImportModuleError&quot;, &quot;requestId&quot;: &quot;&quot;, &quot;stackTrace&quot;: [] } </code></pre> <p>This is the runtime environment:</p> <p><a href="https://i.sstatic.net/yKTG7h0w.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/yKTG7h0w.png" alt="env" /></a></p> <p>Can you help me? Both Lambda and my Mac are running ARM64.</p>
<python><amazon-web-services><aws-lambda><fastapi><python-3.12>
2024-09-12 13:47:45
1
481
tail
78,978,265
2,171,348
python 3.9 multiprocessing.RLock on windows 10
<p>Here is my code:</p> <pre><code>from multiprocessing import Process, RLock import os LOCK = RLock() def acquire_lock(): r = LOCK.acquire() print(os.getpid(), &quot;lock acquired:&quot;, r) if __name__ == &quot;__main__&quot;: acquire_lock() process1 = Process(target=acquire_lock) process1.start() process2 = Process(target=acquire_lock) process2.start() process1.join() process2.join() </code></pre> <p>With the above code, I'd expect one line printed to the stdout and the execution should not exit; but I get three lines, and the execution exited:</p> <pre><code>C:\workspace\nap\nap_test\validator&gt;\apps\Python39\python.exe .\rlock.py 36660 lock acquired: True 20624 lock acquired: True 36792 lock acquired: True C:\workspace\nap\nap_test\validator&gt; </code></pre> <p>Same result swicthing from RLock to Lock. Is the use of multiprocessing.RLock in the above code snippet correct?</p>
<python><multiprocessing><locking>
2024-09-12 12:55:39
0
481
H.Sheng
78,978,045
562,769
Is it possible to switch to a through model in one release?
<p>Assume I have those Django models:</p> <pre><code>class Book(models.Model): title = models.CharField(max_length=100) class Author(models.Model): name = models.CharField(max_length=100) books = models.ManyToManyField(Book) </code></pre> <p>I already have a production system with several objects and several Author &lt;-&gt; Book connections.</p> <p>Now I want to switch to:</p> <pre><code>class Book(models.Model): title = models.CharField(max_length=100) class BookAuthor(models.Model): book = models.ForeignKey(Book, on_delete=models.CASCADE) author = models.ForeignKey(&quot;Author&quot;, on_delete=models.CASCADE) impact = models.IntegerField(default=1) class Meta: unique_together = (&quot;book&quot;, &quot;author&quot;) class Author(models.Model): name = models.CharField(max_length=100) books = models.ManyToManyField(Book, through=BookAuthor) </code></pre> <p>If I do this Migration:</p> <pre><code>from django.db import migrations def migrate_author_books(apps, schema_editor): Author = apps.get_model('yourappname', 'Author') BookAuthor = apps.get_model('yourappname', 'BookAuthor') for author in Author.objects.all(): for book in author.books.all(): # Create a BookAuthor entry with default impact=1 BookAuthor.objects.create(author=author, book=book, impact=1) class Migration(migrations.Migration): dependencies = [ ('yourappname', 'previous_migration_file'), ] operations = [ migrations.CreateModel(name=&quot;BookAuthor&quot;, ...), migrations.RunPython(migrate_author_books), migrations.RemoveField(model_name=&quot;author&quot;, name=&quot;books&quot;), migrations.AddField(model_name=&quot;author&quot;, name=&quot;books&quot;, field=models.ManyToManyField(...), ] </code></pre> <p>then the loop <code>for book in author.books.all()</code> will access the new (and empty) <code>BookAuthor</code> table instead of iterating over the existing default table Django created.</p> <p>How can I make the data migration?</p> <p>The only way I see is to have two releases:</p> <ol> <li>Just add the new <code>BookAuthor</code> model and fill it with data, but keep the existing one. So introducing a new field and keeping the old one. Also change every single place where author.books is used to <code>author.books_new</code></li> <li>Release + migrate on prod</li> <li>Remove author.books and rename books_new to books. Another migration, another release.</li> </ol> <p>Isn't there a simpler way?</p>
<python><django><django-orm>
2024-09-12 11:59:52
1
138,373
Martin Thoma
78,978,016
1,606,657
Add default text to curses Textbox object
<p>I'm using the curses python library in an application and have implemented a <code>Textbox</code> as well <a href="https://docs.python.org/3/library/curses.html#textbox-objects" rel="nofollow noreferrer">https://docs.python.org/3/library/curses.html#textbox-objects</a>.</p> <p>Is there a way to add a default text when displaying the text box that can then be either edited or replaced by the user?</p> <p>Example of textbox usage:</p> <pre><code>import curses import curses.textpad def main(stdscr): stdscr.addstr(1, 0, &quot;Text: &quot;) stdscr.refresh() win = curses.newwin(1, 20, 1, 6) textbox = curses.textpad.Textbox(win) # add a default text here to be displayed # which can be modified, deleted or replaced text = textbox.edit() stdscr.addstr(3, 0, &quot;Input: &quot;) stdscr.addstr(3, 7, text) stdscr.refresh() stdscr.getch() if __name__ == &quot;__main__&quot;: curses.wrapper(main) </code></pre>
<python><textbox><python-curses>
2024-09-12 11:53:35
1
6,352
wasp256
78,977,945
1,473,517
What is the fastest way to read in a large yaml file containing lists of lists?
<p>I have a number of yaml files I need to read in which contain lists of list. Here is a way to make some example data:</p> <pre><code>from time import time import random import yaml # First make a list of lists N = 2**17 lol = [] for _ in range(N): lol.append([random.uniform(0, 2) for _ in range(10)]) # Write the list of lists to a yaml file with open('data.yml', 'w') as outfile: yaml.dump(lol, outfile, default_flow_style=True) </code></pre> <p>I want to read them in as quickly as possible. Pyyaml is unfortunately slow.</p> <pre><code># Now time how long it takes to read it back in t = time() with open(&quot;data.yml&quot;, &quot;r&quot;) as f: lol = yaml.safe_load(f) print(f&quot;Reading took {round(time()-t, 2)} seconds&quot;) </code></pre> <p>This give over 60 seconds for me. The file is 27MB in size.</p> <p>Is there a faster way to read in a yaml fie of exactly this format?</p>
<python><performance>
2024-09-12 11:32:12
1
21,513
Simd
78,977,827
1,469,980
Cannot close a dialog PyQt5
<p>I have the following 2 classes. From <code>UI_mainwindow</code> I open a dialog as seen below. I want that dialog to close when I click on one of those 2 buttons (<code>createProject_btn</code>, <code>openProject_btn</code>). Though nothing seems to be working.</p> <p>I know this kind of questions have been asked million times, and I'm sure there are duplicates, but my eyes are so new to the python, I cannot follow the patterns. Hence, any help is appreciated.</p> <p>Note: the ui files are pretty simple, one button on UI_mainwindow to open the dialog, 2 buttons on the dialog to set a property inside and close the dialog.</p> <p><strong>Ui_mainWindow</strong></p> <pre><code>import os from .createOrOpenProjectDialog import CreateOrOpenProjectDialog from qgis.PyQt import uic from PyQt5 import QtWidgets from PyQt5.QtWidgets import (QDialog) FORM_CLASS, _ = uic.loadUiType(os.path.join(os.path.dirname(__file__), 'ui', 'window.ui')) class Ui_mainWindow(QtWidgets.QDialog, FORM_CLASS): def __init__(self, parent=None): &quot;&quot;&quot;Constructor.&quot;&quot;&quot; super(Ui_mainWindow, self).__init__(parent) # Set up the user interface from Designer through FORM_CLASS. self.setupUi(self) self.connectSignalsSlots() def connectSignalsSlots(self): print(&quot;main.connectSignalsSlots 1&quot;) self.pushButton1.clicked.connect(self.createProject) print(&quot;main.connectSignalsSlots 2&quot;) def createProject(self): dialog = MyDialog(self) print(dialog.exec()) dialog.showOutput() class MyDialog(QDialog): def __init__(self, parent=None): super().__init__(parent) # .dialog is just a handle - class property that we created here self.dialog = CreateOrOpenProjectDialog(self) def showOutput(self): print(&quot;showOutput:&quot;) print(self.dialog.clickedButton) </code></pre> <p><strong>CreateOrOpenProjectDialog</strong></p> <pre><code>import os from qgis.PyQt import uic from PyQt5.QtWidgets import (QDialog) # This loads your .ui file so that PyQt can populate your plugin with the elements from Qt Designer FORM_CLASS, _ = uic.loadUiType(os.path.join(os.path.dirname(__file__), 'ui', 'dialog.ui')) class CreateOrOpenProjectDialog(QDialog, FORM_CLASS): def __init__(self, parent=None): &quot;&quot;&quot;Constructor.&quot;&quot;&quot; super(CreateOrOpenProjectDialog, self).__init__(parent) self.setupUi(parent) self.connectSignalsSlots() def connectSignalsSlots(self): # todo: figure out if actions are better to use then direct events # self.action_create_project.triggered.connect(self.createProject) self.createProject_btn.clicked.connect(self.createProject) self.openProject_btn.clicked.connect(self.openProject) def createProject(self): print(&quot;dialog.createProject&quot;) self.clickedButton = &quot;createProj&quot; self.accept() def openProject(self): print(&quot;dialog.openProject&quot;) self.clickedButton = &quot;openProj&quot; self.accept() </code></pre>
<python><pyqt5><qdialog>
2024-09-12 11:03:02
0
7,390
Tolga Evcimen
78,977,494
9,525,238
Combine 2 numpy 1d arrays taking elements from each consecutively
<p>I have 2 arrays</p> <pre><code>xs1 = [ x0, x1, x2, x3, x4, x5, x6, x7, x8] xs2 = [x00, x01, x02, x03, x04, x05, x06, x07, x08] </code></pre> <p>I want to combine them taking an element from each at a time.</p> <pre><code>xs = [x0, x00, x1, x01, x2, x02, x3, x03, x4, x04, x5, x05, x6, x06, x7, x07, x8, x08] </code></pre> <p>How can i achieve this with numpy without a for loop?</p>
<python><numpy>
2024-09-12 09:39:31
2
413
Andrei M.
78,977,364
188,331
Simple import codes in transformers cause errors
<p>Here are my simple import codes:</p> <pre><code>from transformers import trainer_seq2seq </code></pre> <p>It shows:</p> <pre><code>2024-09-12 16:47:25.651645: E external/local_xla/xla/stream_executor/cuda/cuda_fft.cc:485] Unable to register cuFFT factory: Attempting to register factory for plugin cuFFT when one has already been registered 2024-09-12 16:47:25.672144: E external/local_xla/xla/stream_executor/cuda/cuda_dnn.cc:8454] Unable to register cuDNN factory: Attempting to register factory for plugin cuDNN when one has already been registered 2024-09-12 16:47:25.678423: E external/local_xla/xla/stream_executor/cuda/cuda_blas.cc:1452] Unable to register cuBLAS factory: Attempting to register factory for plugin cuBLAS when one has already been registered 2024-09-12 16:47:25.693224: I tensorflow/core/platform/cpu_feature_guard.cc:210] This TensorFlow binary is optimized to use available CPU instructions in performance-critical operations. To enable the following instructions: AVX2 FMA, in other operations, rebuild TensorFlow with the appropriate compiler flags. 2024-09-12 16:47:26.503496: W tensorflow/compiler/tf2tensorrt/utils/py_utils.cc:38] TF-TRT Warning: Could not find TensorRT Traceback (most recent call last): File &quot;/home/jupyter-raptor/.local/lib/python3.10/site-packages/transformers/utils/import_utils.py&quot;, line 1603, in _get_module return importlib.import_module(&quot;.&quot; + module_name, self.__name__) File &quot;/opt/tljh/user/lib/python3.10/importlib/__init__.py&quot;, line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File &quot;&lt;frozen importlib._bootstrap&gt;&quot;, line 1050, in _gcd_import File &quot;&lt;frozen importlib._bootstrap&gt;&quot;, line 1027, in _find_and_load File &quot;&lt;frozen importlib._bootstrap&gt;&quot;, line 1006, in _find_and_load_unlocked File &quot;&lt;frozen importlib._bootstrap&gt;&quot;, line 688, in _load_unlocked File &quot;&lt;frozen importlib._bootstrap_external&gt;&quot;, line 883, in exec_module File &quot;&lt;frozen importlib._bootstrap&gt;&quot;, line 241, in _call_with_frames_removed File &quot;/home/jupyter-raptor/.local/lib/python3.10/site-packages/transformers/modeling_tf_utils.py&quot;, line 38, in &lt;module&gt; from .activations_tf import get_tf_activation File &quot;/home/jupyter-raptor/.local/lib/python3.10/site-packages/transformers/activations_tf.py&quot;, line 22, in &lt;module&gt; import tf_keras as keras File &quot;/home/jupyter-raptor/.local/lib/python3.10/site-packages/tf_keras/__init__.py&quot;, line 3, in &lt;module&gt; from tf_keras import __internal__ File &quot;/home/jupyter-raptor/.local/lib/python3.10/site-packages/tf_keras/__internal__/__init__.py&quot;, line 3, in &lt;module&gt; from tf_keras.__internal__ import backend File &quot;/home/jupyter-raptor/.local/lib/python3.10/site-packages/tf_keras/__internal__/backend/__init__.py&quot;, line 3, in &lt;module&gt; from tf_keras.src.backend import _initialize_variables as initialize_variables File &quot;/home/jupyter-raptor/.local/lib/python3.10/site-packages/tf_keras/src/__init__.py&quot;, line 21, in &lt;module&gt; from tf_keras.src import applications File &quot;/home/jupyter-raptor/.local/lib/python3.10/site-packages/tf_keras/src/applications/__init__.py&quot;, line 18, in &lt;module&gt; from tf_keras.src.applications.convnext import ConvNeXtBase File &quot;/home/jupyter-raptor/.local/lib/python3.10/site-packages/tf_keras/src/applications/convnext.py&quot;, line 33, in &lt;module&gt; from tf_keras.src.engine import sequential File &quot;/home/jupyter-raptor/.local/lib/python3.10/site-packages/tf_keras/src/engine/sequential.py&quot;, line 24, in &lt;module&gt; from tf_keras.src.engine import functional File &quot;/home/jupyter-raptor/.local/lib/python3.10/site-packages/tf_keras/src/engine/functional.py&quot;, line 33, in &lt;module&gt; from tf_keras.src.engine import training as training_lib File &quot;/home/jupyter-raptor/.local/lib/python3.10/site-packages/tf_keras/src/engine/training.py&quot;, line 48, in &lt;module&gt; from tf_keras.src.saving import saving_api File &quot;/home/jupyter-raptor/.local/lib/python3.10/site-packages/tf_keras/src/saving/saving_api.py&quot;, line 25, in &lt;module&gt; from tf_keras.src.saving.legacy import save as legacy_sm_saving_lib File &quot;/home/jupyter-raptor/.local/lib/python3.10/site-packages/tf_keras/src/saving/legacy/save.py&quot;, line 27, in &lt;module&gt; from tf_keras.src.saving.legacy.saved_model import load_context File &quot;/home/jupyter-raptor/.local/lib/python3.10/site-packages/tf_keras/src/saving/legacy/saved_model/load_context.py&quot;, line 68, in &lt;module&gt; tf.__internal__.register_load_context_function(in_load_context) AttributeError: module 'tensorflow._api.v2.compat.v2.__internal__' has no attribute 'register_load_context_function'. Did you mean: 'register_call_context_function'? The above exception was the direct cause of the following exception: Traceback (most recent call last): File &quot;/home/jupyter-raptor/.local/lib/python3.10/site-packages/transformers/utils/import_utils.py&quot;, line 1603, in _get_module return importlib.import_module(&quot;.&quot; + module_name, self.__name__) File &quot;/opt/tljh/user/lib/python3.10/importlib/__init__.py&quot;, line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File &quot;&lt;frozen importlib._bootstrap&gt;&quot;, line 1050, in _gcd_import File &quot;&lt;frozen importlib._bootstrap&gt;&quot;, line 1027, in _find_and_load File &quot;&lt;frozen importlib._bootstrap&gt;&quot;, line 1006, in _find_and_load_unlocked File &quot;&lt;frozen importlib._bootstrap&gt;&quot;, line 688, in _load_unlocked File &quot;&lt;frozen importlib._bootstrap_external&gt;&quot;, line 883, in exec_module File &quot;&lt;frozen importlib._bootstrap&gt;&quot;, line 241, in _call_with_frames_removed File &quot;/home/jupyter-raptor/.local/lib/python3.10/site-packages/transformers/integrations/integration_utils.py&quot;, line 36, in &lt;module&gt; from .. import PreTrainedModel, TFPreTrainedModel File &quot;&lt;frozen importlib._bootstrap&gt;&quot;, line 1075, in _handle_fromlist File &quot;/home/jupyter-raptor/.local/lib/python3.10/site-packages/transformers/utils/import_utils.py&quot;, line 1593, in __getattr__ module = self._get_module(self._class_to_module[name]) File &quot;/home/jupyter-raptor/.local/lib/python3.10/site-packages/transformers/utils/import_utils.py&quot;, line 1605, in _get_module raise RuntimeError( RuntimeError: Failed to import transformers.modeling_tf_utils because of the following error (look up to see its traceback): module 'tensorflow._api.v2.compat.v2.__internal__' has no attribute 'register_load_context_function' The above exception was the direct cause of the following exception: Traceback (most recent call last): File &quot;/home/jupyter-raptor/.local/lib/python3.10/site-packages/transformers/utils/import_utils.py&quot;, line 1603, in _get_module return importlib.import_module(&quot;.&quot; + module_name, self.__name__) File &quot;/opt/tljh/user/lib/python3.10/importlib/__init__.py&quot;, line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File &quot;&lt;frozen importlib._bootstrap&gt;&quot;, line 1050, in _gcd_import File &quot;&lt;frozen importlib._bootstrap&gt;&quot;, line 1027, in _find_and_load File &quot;&lt;frozen importlib._bootstrap&gt;&quot;, line 1006, in _find_and_load_unlocked File &quot;&lt;frozen importlib._bootstrap&gt;&quot;, line 688, in _load_unlocked File &quot;&lt;frozen importlib._bootstrap_external&gt;&quot;, line 883, in exec_module File &quot;&lt;frozen importlib._bootstrap&gt;&quot;, line 241, in _call_with_frames_removed File &quot;/home/jupyter-raptor/.local/lib/python3.10/site-packages/transformers/trainer_seq2seq.py&quot;, line 26, in &lt;module&gt; from .trainer import Trainer File &quot;/home/jupyter-raptor/.local/lib/python3.10/site-packages/transformers/trainer.py&quot;, line 42, in &lt;module&gt; from .integrations import ( File &quot;&lt;frozen importlib._bootstrap&gt;&quot;, line 1075, in _handle_fromlist File &quot;/home/jupyter-raptor/.local/lib/python3.10/site-packages/transformers/utils/import_utils.py&quot;, line 1593, in __getattr__ module = self._get_module(self._class_to_module[name]) File &quot;/home/jupyter-raptor/.local/lib/python3.10/site-packages/transformers/utils/import_utils.py&quot;, line 1605, in _get_module raise RuntimeError( RuntimeError: Failed to import transformers.integrations.integration_utils because of the following error (look up to see its traceback): Failed to import transformers.modeling_tf_utils because of the following error (look up to see its traceback): module 'tensorflow._api.v2.compat.v2.__internal__' has no attribute 'register_load_context_function' The above exception was the direct cause of the following exception: Traceback (most recent call last): File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt; File &quot;&lt;frozen importlib._bootstrap&gt;&quot;, line 1075, in _handle_fromlist File &quot;/home/jupyter-raptor/.local/lib/python3.10/site-packages/transformers/utils/import_utils.py&quot;, line 1591, in __getattr__ value = self._get_module(name) File &quot;/home/jupyter-raptor/.local/lib/python3.10/site-packages/transformers/utils/import_utils.py&quot;, line 1605, in _get_module raise RuntimeError( RuntimeError: Failed to import transformers.trainer_seq2seq because of the following error (look up to see its traceback): Failed to import transformers.integrations.integration_utils because of the following error (look up to see its traceback): Failed to import transformers.modeling_tf_utils because of the following error (look up to see its traceback): module 'tensorflow._api.v2.compat.v2.__internal__' has no attribute 'register_load_context_function' </code></pre> <p>but this line can be loaded without problems:</p> <pre><code>from transformers import BertTokenizer </code></pre> <p>What did I miss?</p> <p>Versions:</p> <ul> <li>transformers 4.44.2</li> <li>keras 3.5.0</li> <li>tensorflow 2.17.0</li> <li>Python 3.10.10</li> </ul>
<python><tensorflow><huggingface-transformers>
2024-09-12 09:09:30
1
54,395
Raptor
78,977,145
179,014
Derived python dataclass cannot override default value?
<p>In the following code snippet the dataclass <code>Derived</code> is derived from dataclass <code>Base</code>. The <code>Derived</code> dataclass is setting new default values for <code>field1</code> and <code>field2</code>.</p> <pre><code>from dataclasses import dataclass @dataclass class Base: field1: str field2: str = &quot;default_base_string&quot; @dataclass class Derived(Base): field1 = &quot;default_string1&quot; field2 = &quot;default_string2&quot; print(Derived()) </code></pre> <p>Because <code>Derived</code> is a dataclass and has set a default value for all member variables <code>field1</code> and <code>field2</code>, I expected that I could simply initialize the class calling <code>Derived()</code>. However I get the following error:</p> <pre><code>TypeError: Derived.__init__() missing 1 required positional argument: 'field1' </code></pre> <p>Is it not possible to set the default value for a member variable in a derived dataclass, so that this member variable becomes optional in the autogenerated <code>__init__()</code> method? Must I always define my own <code>__init__()</code> method in the <code>Derived</code> class? Or am I doing something wrong here?</p>
<python><inheritance><python-dataclasses>
2024-09-12 08:11:52
1
11,858
asmaier
78,977,133
8,946,188
Why does drop_duplicates in_place = True not work in this case?
<p>Sample data:</p> <pre><code>data = [[1, 'john@example.com'], [2, 'bob@example.com'], [3, 'john@example.com']] person = pd.DataFrame(data, columns=['id', 'email']).astype({'id':'int64', 'email':'object'}) </code></pre> <p>Reproducible code:</p> <pre><code>(person.sort_values(by = ['email', 'id'], ascending = [True, True]) .drop_duplicates(subset = 'email', keep = 'first', inplace = True)) </code></pre> <p>I expected the code above to revise <code>person</code> so it looks like</p> <pre><code> id email 1 2 bob@example.com 0 1 john@example.com </code></pre> <p>But instead <code>person</code> still looks like its original form</p> <pre><code> id email 0 1 john@example.com 1 2 bob@example.com 2 3 john@example.com </code></pre> <p>If I break up the methods into two parts, then it works</p> <pre><code>person1 = person.sort_values(by = ['email', 'id'], ascending = [True, True]) person1.drop_duplicates(subset = 'email', keep = 'first', inplace = True) </code></pre> <p>In this case <code>person1</code> looks like the desired format:</p> <pre><code> id email 1 2 bob@example.com 0 1 john@example.com </code></pre> <p>Why doesn't the first code remove duplicated email in-place?</p>
<python><pandas><dataframe><in-place><drop-duplicates>
2024-09-12 08:09:59
1
462
Amazonian
78,977,057
7,519,700
elasticsearch-py add delay between retries
<p>I'm instantiating a python elasticsearch client as follows</p> <pre><code>es = Elasticsearch( hosts=ELASTICSEARCH_URL, timeout=5, ignore_unavailable=True, # connection_retries=Retry( # total=5, # backoff_factor=1.1, # status_forcelist=[429, 502, 503, 504], # raise_on_status=False, # ) ) </code></pre> <p>I want to introduce a retry delay between retries (and ideally with a backoff factor). So that executing a search request, is retried with a backoff factor</p> <pre><code>es.search(index=&quot;abc&quot;, body={&quot;query&quot;: {&quot;match_all&quot;: {}}}) </code></pre> <p>Any ideas how to achieve this?</p>
<python><delay><elasticsearch-py>
2024-09-12 07:49:05
1
1,033
room13
78,976,844
2,573,075
ODOO 17 Obtain sorted query result for a customized report
<p>In a crm.lead model I have 2 more attributes (columns) let's call col1 and col2.</p> <p>How do I obtain 2 recordsets for each user like &quot;select * from crm_records col1 desc limit 5&quot; and the second &quot;select * from crm_records col1 desc limit 5&quot; in the same?</p> <p>In the beginning, I was trying to modify _where_calc​in an abstract where I put:</p> <pre><code>query.order = f&quot;{self._table}.{top_field} DESC&quot; query.limit = top_limit </code></pre> <p>to append to the original query that comes with</p> <pre><code>query = super()._where_calc(*args, **kwargs) </code></pre> <p>but:</p> <ol> <li>I receive all queries I put in the domain</li> <li>It is not ordered like the way I want (only if I put sort in the filter)</li> </ol> <p>Thank you in advance Claudiu</p>
<python><sql><odoo><odoo-17>
2024-09-12 06:58:42
1
633
Claudiu
78,976,722
1,922,589
PyYAML - error: subprocess-exited-with-error
<p>I got this error when trying to install PyYAML</p> <pre><code>Collecting PyYAML==5.4.1 (from -r /xxx/src/requirements_2.txt (line 21)) Using cached PyYAML-5.4.1.tar.gz (175 kB) Installing build dependencies ... done Getting requirements to build wheel ... error error: subprocess-exited-with-error Γ— Getting requirements to build wheel did not run successfully. β”‚ exit code: 1 ╰─&gt; [48 lines of output] running egg_info writing lib3/PyYAML.egg-info/PKG-INFO writing dependency_links to lib3/PyYAML.egg-info/dependency_links.txt writing top-level names to lib3/PyYAML.egg-info/top_level.txt Traceback (most recent call last): File &quot;/xxx/env/lib/python3.9/site-packages/pip/_vendor/pyproject_hooks/_in_process/_in_process.py&quot;, line 353, in &lt;module&gt; main() File &quot;/xxx/env/lib/python3.9/site-packages/pip/_vendor/pyproject_hooks/_in_process/_in_process.py&quot;, line 335, in main json_out['return_val'] = hook(**hook_input['kwargs']) File &quot;/xxx/env/lib/python3.9/site-packages/pip/_vendor/pyproject_hooks/_in_process/_in_process.py&quot;, line 118, in get_requires_for_build_wheel return hook(config_settings) File &quot;/private/var/folders/c7/59xfc0ns6r9bz5h8lnhz0b140000gn/T/pip-build-env-k3l_7j20/overlay/lib/python3.9/site-packages/setuptools/build_meta.py&quot;, line 332, in get_requires_for_build_wheel return self._get_build_requires(config_settings, requirements=[]) File &quot;/private/var/folders/c7/59xfc0ns6r9bz5h8lnhz0b140000gn/T/pip-build-env-k3l_7j20/overlay/lib/python3.9/site-packages/setuptools/build_meta.py&quot;, line 302, in _get_build_requires self.run_setup() File &quot;/private/var/folders/c7/59xfc0ns6r9bz5h8lnhz0b140000gn/T/pip-build-env-k3l_7j20/overlay/lib/python3.9/site-packages/setuptools/build_meta.py&quot;, line 318, in run_setup exec(code, locals()) File &quot;&lt;string&gt;&quot;, line 271, in &lt;module&gt; File &quot;/private/var/folders/c7/59xfc0ns6r9bz5h8lnhz0b140000gn/T/pip-build-env-k3l_7j20/overlay/lib/python3.9/site-packages/setuptools/__init__.py&quot;, line 117, in setup return distutils.core.setup(**attrs) File &quot;/private/var/folders/c7/59xfc0ns6r9bz5h8lnhz0b140000gn/T/pip-build-env-k3l_7j20/overlay/lib/python3.9/site-packages/setuptools/_distutils/core.py&quot;, line 184, in setup return run_commands(dist) File &quot;/private/var/folders/c7/59xfc0ns6r9bz5h8lnhz0b140000gn/T/pip-build-env-k3l_7j20/overlay/lib/python3.9/site-packages/setuptools/_distutils/core.py&quot;, line 200, in run_commands dist.run_commands() File &quot;/private/var/folders/c7/59xfc0ns6r9bz5h8lnhz0b140000gn/T/pip-build-env-k3l_7j20/overlay/lib/python3.9/site-packages/setuptools/_distutils/dist.py&quot;, line 954, in run_commands self.run_command(cmd) File &quot;/private/var/folders/c7/59xfc0ns6r9bz5h8lnhz0b140000gn/T/pip-build-env-k3l_7j20/overlay/lib/python3.9/site-packages/setuptools/dist.py&quot;, line 950, in run_command super().run_command(command) File &quot;/private/var/folders/c7/59xfc0ns6r9bz5h8lnhz0b140000gn/T/pip-build-env-k3l_7j20/overlay/lib/python3.9/site-packages/setuptools/_distutils/dist.py&quot;, line 973, in run_command cmd_obj.run() File &quot;/private/var/folders/c7/59xfc0ns6r9bz5h8lnhz0b140000gn/T/pip-build-env-k3l_7j20/overlay/lib/python3.9/site-packages/setuptools/command/egg_info.py&quot;, line 311, in run self.find_sources() File &quot;/private/var/folders/c7/59xfc0ns6r9bz5h8lnhz0b140000gn/T/pip-build-env-k3l_7j20/overlay/lib/python3.9/site-packages/setuptools/command/egg_info.py&quot;, line 319, in find_sources mm.run() File &quot;/private/var/folders/c7/59xfc0ns6r9bz5h8lnhz0b140000gn/T/pip-build-env-k3l_7j20/overlay/lib/python3.9/site-packages/setuptools/command/egg_info.py&quot;, line 540, in run self.add_defaults() File &quot;/private/var/folders/c7/59xfc0ns6r9bz5h8lnhz0b140000gn/T/pip-build-env-k3l_7j20/overlay/lib/python3.9/site-packages/setuptools/command/egg_info.py&quot;, line 578, in add_defaults sdist.add_defaults(self) File &quot;/private/var/folders/c7/59xfc0ns6r9bz5h8lnhz0b140000gn/T/pip-build-env-k3l_7j20/overlay/lib/python3.9/site-packages/setuptools/command/sdist.py&quot;, line 108, in add_defaults super().add_defaults() File &quot;/private/var/folders/c7/59xfc0ns6r9bz5h8lnhz0b140000gn/T/pip-build-env-k3l_7j20/overlay/lib/python3.9/site-packages/setuptools/_distutils/command/sdist.py&quot;, line 250, in add_defaults self._add_defaults_ext() File &quot;/private/var/folders/c7/59xfc0ns6r9bz5h8lnhz0b140000gn/T/pip-build-env-k3l_7j20/overlay/lib/python3.9/site-packages/setuptools/_distutils/command/sdist.py&quot;, line 335, in _add_defaults_ext self.filelist.extend(build_ext.get_source_files()) File &quot;&lt;string&gt;&quot;, line 201, in get_source_files File &quot;/private/var/folders/c7/59xfc0ns6r9bz5h8lnhz0b140000gn/T/pip-build-env-k3l_7j20/overlay/lib/python3.9/site-packages/setuptools/_distutils/cmd.py&quot;, line 107, in __getattr__ raise AttributeError(attr) AttributeError: cython_sources [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: subprocess-exited-with-error Γ— Getting requirements to build wheel did not run successfully. β”‚ exit code: 1 ╰─&gt; See above for output. note: This error originates from a subprocess, and is likely not a problem with pip. </code></pre>
<python><pyyaml>
2024-09-12 06:26:09
1
24,027
Nurdin
78,976,441
2,717,373
centering the bottom row of subplots in a matplotlib grid
<p>If I have 5 plots I want to present, is it possible to have them in 2 rows, with the top row having 3 plots, the bottom row having 2 plots, but the bottom row centred?</p> <p>I can plot them with 3 on the top and 2 on the bottom, but I can't work out how to centre the bottom row.</p> <p>for example:</p> <pre><code>import matplotlib.pyplot as plt fig, axs = plt.subplots(2, 3, figsize=(10,5), sharey=True) for i in range(5): row,col = divmod(i,3) axs[row,col].plot([0, 1], [0, i]) fig.delaxes(axs[1,2]) plt.tight_layout() plt.show() </code></pre> <p>gives me this plot: <a href="https://i.sstatic.net/cWurwi3g.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/cWurwi3g.png" alt="enter image description here" /></a></p> <p>but i can't work out how to centre the bottom row.</p> <p>I tried using gridspec, and creating a 2x1 grid, and then putting the top row in the top cell of the master grid, and the bottom row in the bottom cell, but that just stretched the bottom plots out so they took up the whole bottom row. Is it possible to keep all the plots the same size, but centre the bottom two?</p>
<python><matplotlib><plot><layout>
2024-09-12 04:06:53
2
1,373
guskenny83
78,976,156
11,934,499
i am using cookiecutter-django with docker and it keeps reloading in the local env
<p>I am starting to use cookiecutter-django 2024.07.26 with docker and after a few updates it keeps reloading</p> <p><a href="https://i.sstatic.net/CU67taqr.gif" rel="nofollow noreferrer"><img src="https://i.sstatic.net/CU67taqr.gif" alt="screen recorder" /></a></p> <pre><code>aqua_loui_local_django | * Detected change in '/usr/local/lib/python3.12/site-packages/django/contrib/sites/models.py', reloading aqua_loui_local_django | * Detected change in '/usr/local/lib/python3.12/site-packages/django/contrib/sites/shortcuts.py', reloading aqua_loui_local_django | * Detected change in '/usr/local/lib/python3.12/site-packages/allauth/account/views.py', reloading aqua_loui_local_django | * Detected change in '/usr/local/lib/python3.12/site-packages/django/views/generic/edit.py', reloading aqua_loui_local_django | * Detected change in '/usr/local/lib/python3.12/site-packages/allauth/account/mixins.py', reloading aqua_loui_local_django | * Detected change in '/usr/local/lib/python3.12/site-packages/django/views/generic/base.py', reloading aqua_loui_local_django | * Detected change in '/usr/local/lib/python3.12/site-packages/django/views/decorators/cache.py', reloading aqua_loui_local_django | * Detected change in '/usr/local/lib/python3.12/site-packages/django/views/decorators/debug.py', reloading aqua_loui_local_django | * Detected change in '/usr/local/lib/python3.12/site-packages/allauth/decorators.py', reloading aqua_loui_local_django | * Restarting with watchdog (inotify) aqua_loui_local_django | Performing system checks... aqua_loui_local_django | aqua_loui_local_django | System check identified no issues (0 silenced). aqua_loui_local_django | aqua_loui_local_django | Django version 5.0.7, using settings 'config.settings.local' aqua_loui_local_django | Development server is running at http://0.0.0.0:8000/ aqua_loui_local_django | Using the Werkzeug debugger (https://werkzeug.palletsprojects.com/) aqua_loui_local_django | Quit the server with CONTROL-C. aqua_loui_local_django | * Debugger is active! </code></pre>
<python><django><docker><local><cookiecutter-django>
2024-09-12 01:39:28
1
1,423
Ahmed Abo 6
78,976,148
6,929,343
Get PythonTkinter width of string in pixels using given font
<p>Given a string such as &quot;this is a string&quot; or &quot;THIS IS A STRING&quot; and knowing the font family and size, how can the pixel width be calculated?</p> <p>This is required to align columns for an eyesome GUI.</p>
<python><string><user-interface><tkinter><width>
2024-09-12 01:36:17
1
2,005
WinEunuuchs2Unix
78,975,956
1,380,285
python list comprehension -- two loops with three results?
<p>I can ask my question best by just giving an example. Let's say I want to use a list comprehension to generate a set of 3-element tuples from two loops, something like this:</p> <pre><code>[ (y+z,y,z) for y in range(10) if y%2==0 for z in range(20) if z%3==0 ] </code></pre> <p>This works, giving me</p> <pre><code>[(0, 0, 0), (3, 0, 3), (6, 0, 6), (9, 0, 9), (12, 0, 12), (15, 0, 15), ... ] </code></pre> <p>I am wondering, though, if there is a way to do it more cleanly, something to the effect of</p> <pre><code>[ (x,y,z) for y in range(10) if y%2==0 for z in range(20) if z%3==0 ... somehow defining x(y,z) ... ] </code></pre> <p>I would consider something like this to be more clean, especially since what I really need to do is much more complicated than the example I give here. Everything I have tried has given me a syntax error.</p>
<python><list-comprehension>
2024-09-11 23:08:29
3
6,713
bob.sacamento
78,975,869
2,687,317
pandas- merge to datasets with diff col names adding values from the second into the first
<p>I have a couple of dataframes:</p> <pre><code>DTime A B C 2023-02-21 00:00:01 0 0 0 2023-02-21 00:00:02 0 1 0 2023-02-21 00:00:03 0 0 2 2023-02-21 00:00:04 4 2 0 DTime AAA BBB CC DDD EE 2023-02-21 00:00:01 0 0 0 1 0 2023-02-21 00:00:02 0 1 0 0 0 2023-02-21 00:00:03 0 0 2 0 1 2023-02-21 00:00:04 1 0 0 0 0 </code></pre> <p>I need to merge the first into the second where I explicitly map the cols and sum the values. i.e. - I want A to <strong>sum</strong> into AAA, B into BBB and C into CCC:</p> <pre><code>DTime AAA BBB CC DDD EE 2023-02-21 00:00:01 0 0 0 1 0 2023-02-21 00:00:02 0 2 0 0 0 2023-02-21 00:00:03 0 0 4 0 1 2023-02-21 00:00:04 5 2 0 0 0 </code></pre> <p>I can't seem to make this happen without going line-by-line... But there must be a better way since I have thousands of rows and hundreds of cols.</p>
<python><pandas><merge>
2024-09-11 22:21:07
3
533
earnric
78,975,859
19,366,064
Pycharm: How to display project name instead of path
<p><a href="https://i.sstatic.net/BaHL3ozu.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/BaHL3ozu.png" alt="enter image description here" /></a></p> <p>Pycharm: How to display project name instead of path</p> <p>The screen shot above shows the project tool window. Under Project Files view, it display the entire path instead of just displaying the name of the project, is there a setting that allows me to change this? I only want to display the project name.</p>
<python><pycharm>
2024-09-11 22:18:49
1
544
Michael Xia
78,975,828
2,171,348
how to share hash() function output with multiprocessing.Array in python 3?
<p>I need to share some 64-bit integers in a python 3 multiprocessing runtime.</p> <p>I tried to use multiprocessing.Array, and it works on linux, but fails on Windows.</p> <p>The long type for multiprocessing.Array is 64-bit on linux, but on Windows (10) it's only 32-bit! Cannot use the same code on both OSes.</p> <p>Are there other options if I don't want to manipulate pointers with multiprocessing.RawArray?</p> <p>(P.S. Cannot use multiprocessing.Manager)</p>
<python><python-multiprocessing><long-integer>
2024-09-11 22:01:58
0
481
H.Sheng
78,975,818
1,125,062
How to use parallel torch cuda streams without causing oom? (example included)
<p>I'm storing a large amount of tensors data in a cpu memory, and the intended workflow is to process them using the GPU. And while one chunk is being processed, <em>simultaneously</em> transfer the previous chunk's result back into cpu. And <em>simultaneously</em> transfer the next chunk into gpu so it's ready to process and the gpu doesn't have to wait for a synchronous transfer.</p> <p>For this I used default cuda stream for processing, and two additional streams for parallel asynchronous transfer. However, in the actual application, whenever I used <code>s2</code> stream for copying tensor into gpu (instead of default stream), it did increase the speed! but always caused a quick and steady rise of gpu memory until it's overflowed.</p> <p>I did try to reproduce this behavior but was <em>unable</em> to, my example seems to not cause memory issues. However, I believe I may have still incorrectly used the streams somehow. So I'm hoping that if anyone worked with streams before may be able to spot the error? In current example <code>s2</code> waits for <code>s1</code>, but any combination I tried fails in the actual application.</p> <pre><code>import torch from time import perf_counter import sys from threading import Thread cpu = torch.device('cpu') gpu = torch.device('cuda') _range = range(10) tensors = [torch.rand(100000000, device=cpu) for i in _range] s1 = torch.cuda.Stream(device=gpu) s2 = torch.cuda.Stream(device=gpu) for i in range(10000000000): time_start = perf_counter() for j in range(-1,11): def PROCESS(): if j in _range: k = tensors[j] for l in range(10): k.mul_(1.01) k.add_(1.01) k.pow_(0.5) def CPU(): if j-1 in _range: with torch.cuda.stream(s1): p = tensors[j-1] p.record_stream(s1) p.data = p.data.to(device=cpu, memory_format=torch.preserve_format, non_blocking=True) def GPU(): if j+1 in _range: # using second stream causes oom in the actual application with torch.cuda.stream(s2): g = tensors[j+1] g.data = g.data.to(device=gpu, memory_format=torch.preserve_format, non_blocking=True) g.record_stream(s2) # note: for s2, record stream is used after the assignment, # because it is initially on cpu and I couldn't record on a cpu tensor t2 = Thread(target=CPU) t2.start() t3 = Thread(target=GPU) t3.start() t1 = Thread(target=PROCESS) t1.start() s1.wait_stream(torch.cuda.default_stream(gpu)) s2.wait_stream(s1) s1.synchronize() t2.join() t3.join() t1.join() lapsed = perf_counter() - time_start time_duration = &quot;%.5f sec/it&quot; % lapsed print(f&quot;\rspeed: {time_duration}&quot;,end=&quot;\r&quot;) </code></pre> <p>You can just run the example and see the result for yourself, it does work faster when the stream 2 is used, and if that part is commented out it would run slower. In the actual app it is actually much more complicated because it uses thousands of those tensors and the loop is not straight forward, however using the <code>s2</code> stream always causes oom.</p>
<python><python-3.x><machine-learning><pytorch><cuda-streams>
2024-09-11 21:55:42
0
4,641
Anonymous
78,975,805
3,825,948
Convert wav to mulaw in Python
<p>I'm opening a wav file and attempting to convert it into mulaw unsuccessfully. The mulaw is then sent to Twilio to play. The code is as follows:</p> <pre><code> with wave.open('audio/test.wav', 'rb') as wav: raw_wav= wav.readframes(wav.getnframes()) raw_ulaw = audioop.lin2ulaw(raw_wav, wav.getsampwidth()) </code></pre> <p>The conversion does happen but the resulting mulaw is just static sound, no speech. Any help would be appreciated. Thanks.</p>
<python><twilio><wav><file-conversion><mu-law>
2024-09-11 21:49:01
0
937
Foobar
78,975,594
22,407,544
Should I use Django's `FloatField()` or `DecimalField(`) for audio length?
<p>I use:</p> <pre class="lang-py prettyprint-override"><code>duration = float(ffmpeg.probe(audio_path)[&quot;format&quot;][&quot;duration&quot;]) </code></pre> <p>I collect an audio/video's length and want to store it using my models. Should I use <code>models.DecimalField()</code> or <code>models.FloatField()</code>?</p> <p>I use it to calculate and store a credit/cost in my model using</p> <pre class="lang-py prettyprint-override"><code>credit = models.DecimalField(max_digits=20, decimal_places=4) </code></pre>
<python><django>
2024-09-11 20:24:07
2
359
tthheemmaannii
78,975,581
2,262,854
Split pdf pages workflow with celery
<p>I have the following use case using Celery and Flask.</p> <p>A user uploads a PDF file. I want a worker to count the number of pages, n workers to split each page in a separate PDF file in parallel and then one worker to generate a report.</p> <pre><code> +----------------+ | | | Count pages | | | +--------|-------+ | |-------------------|-------------------| | | | +--------|-------+ +--------|-------+ +--------|-------+ | | | | | | | Split page 1 | | Split page 2 | | Split page 3 | | | | | | | +----------------+ +----------------+ +----------------+ | | | | | | ----------------------------------------- | +----------------+ | | | Generate report| | | +----------------+ </code></pre> <p>As you can see, count_pages result should create n split_page tasks. But at the same time, count page shouldn't block the upload endpoint so it can't be called synchronously.</p> <p>So far I tried to play with <code>chord</code>, <code>group</code> and <code>chain</code> but I did not find a way to trigger n split_page tasks asynchronously after count_page has finished.</p>
<python><flask><celery>
2024-09-11 20:17:43
0
2,366
maxime
78,975,570
8,510,149
Rank on a subset of a partition - PySpark
<p>The code snippet below creates the column 'rank' with a condition. I want to perform the rank based on a subset of the partition, hence I use a when clause and set category=='Y' and then execute the rank. However, I did not expect the result below. Where I expected rank=1 it is in fact rank=2.</p> <p>How can I achieve to do a rank on a subset of a partition?</p> <pre><code>import pyspark.sql.functions as F from pyspark.sql.window import Window from pyspark.sql import Row data = [ Row(id=1, code=14, category='N'), Row(id=1, code=20, category='Y'), Row(id=1, code=19, category='Y'), Row(id=1, code=22, category='Y'), Row(id=1, code=15, category='Y'), ] ps_df = spark.createDataFrame(data) window = Window.partitionBy('id').orderBy('code') ps_df = ps_df.withColumn('rank', F.when(col('category')=='Y', F.rank().over(window))) ps_df.show() </code></pre> <pre><code>+---+----+--------+----+ | id|code|category|rank| +---+----+--------+----+ | 1| 14| N|NULL| | 1| 15| Y| 2| | 1| 19| Y| 3| | 1| 20| Y| 4| | 1| 22| Y| 5| +---+----+--------+----+ </code></pre>
<python><pyspark>
2024-09-11 20:13:37
1
1,255
Henri
78,975,435
23,260,297
float values not displaying decimal places when using pandas to_sql()
<p>I am inserted values into a table using <code>df.to_sql()</code> function, but the values are not being displayed properly in SQL Server.</p> <p>At the top of my script I use:</p> <pre><code>pd.options.display.float_format = '{:,.4f}'.format </code></pre> <p>and when I print my dataframes all is well:</p> <pre><code> Value Price 100.0000 34.0100 101.4000 35.0100 102.0000 36.0100 103.9000 37.0100 104.0000 38.0100 </code></pre> <p>however, when I insert into SQL Server I get:</p> <pre><code>Value Price 100 34.01 101.4 35.01 102 36.01 103.9 37.01 104 38.01 </code></pre> <p>This is what I have tried:</p> <pre><code>df.to_sql('table', con=engine, if_exists='replace', index=False, dtype={&quot;Price&quot;: Float(), &quot;Value&quot;: Float()}) </code></pre> <p>Any idea why this is happening and how to fix? I am using SQLAlchemy and SQL Server</p>
<python><sql-server><pandas><sqlalchemy>
2024-09-11 19:25:43
1
2,185
iBeMeltin
78,975,421
1,924,830
How do I filter across multiple model relationships?
<p>My models:</p> <pre><code>class Order (models.Model): customer = models.ForeignKey(&quot;Customer&quot;, on_delete=models.RESTRICT) request_date = models.DateField() price = models.DecimalField(max_digits=10, decimal_places=2) @property def agent_name(self): assignment = Assignment.objects.get(assig_year = self.request_date.year, customer = self.customer) if assignment is not None: return assignment.sales_agent.name + ' ' + assignment.sales_agent.surname else: return 'ERROR' class Company (models.Model): pass class Customer (Company): pass class Assignment (models.Model): assig_year = models.PositiveSmallIntegerField() customer = models.ForeignKey(&quot;Customer&quot;, on_delete=models.CASCADE) sales_agent = models.ForeignKey(&quot;Agent&quot;, on_delete=models.CASCADE) class Meta: #unique key year + customer constraints = [ UniqueConstraint( fields=['assig_year', 'customer'], name='Primary_Key_Assignment' ) ] class Employee (models.Model): name = models.CharField(max_length=32) surname = models.CharField(max_length=32) class Agent (Employee): pass </code></pre> <p>One assignment relates each customer to a sales agent for a given year. Each customer may have several orders along the year and the agent assigned to the customer is accountable for serving all of them. In one of my views I am displaying all orders by listing their corresponding sales agent, customer, date and price:</p> <pre><code>def GetOrders(request): orders = Order.objects.order_by('-request_date') template = loader.get_template('orders.html') context = { 'orders' : orders, } return HttpResponse(template.render(context,request)) </code></pre> <p>orders.html:</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;link href=&quot;https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css&quot; rel=&quot;stylesheet&quot;&gt; &lt;/head&gt; &lt;body&gt; &lt;main&gt; &lt;table&gt; &lt;thead&gt; &lt;th&gt;Agent&lt;/th&gt; &lt;th&gt;Customer&lt;/th&gt; &lt;th&gt;Date&lt;/th&gt; &lt;th&gt;Price&lt;/th&gt; &lt;/thead&gt; &lt;tbody&gt; {% for x in orders %} &lt;td&gt;{{ x.agent_name }}&lt;/td&gt; &lt;td&gt;{{ x.customer.name }}&lt;/td&gt; &lt;td&gt;{{ x.request_date }}&lt;/td&gt; &lt;td&gt;{{ x.price }}&lt;/td&gt; &lt;/tr&gt; {% endfor %} &lt;/tbody&gt; &lt;/table&gt; &lt;/main&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>I want to add some filtering capability to select the sales agent I'm interested in. I don't know how to deal with relationships to check the sales agent. I tried the <code>agent_name</code> property:</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;link href=&quot;https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css&quot; rel=&quot;stylesheet&quot;&gt; &lt;/head&gt; &lt;body&gt; &lt;main&gt; &lt;div class=&quot;filters&quot;&gt; &lt;form action=&quot;&quot; method=&quot;GET&quot;&gt; &lt;div class=&quot;row&quot;&gt; &lt;div class=&quot;col-xl-3&quot;&gt; &lt;label&gt;Agent:&lt;/label&gt; &lt;input type=&quot;text&quot; class=&quot;form-control&quot; placeholder=&quot;Name&quot; name=&quot;name&quot; {% if name %} value = &quot;{{ name }}&quot; {% endif %}&gt; &lt;/div&gt; &lt;div class=&quot;col-xl-2&quot; style=&quot;padding-top: 2%;&quot;&gt; &lt;button type=&quot;submit&quot; class=&quot;btn custom-btn&quot;&gt;Filter&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;/form&gt; &lt;/div&gt; &lt;p/&gt; &lt;table&gt; &lt;thead&gt; &lt;th&gt;Agent&lt;/th&gt; &lt;th&gt;Customer&lt;/th&gt; &lt;th&gt;Date&lt;/th&gt; &lt;th&gt;Price&lt;/th&gt; &lt;/thead&gt; &lt;tbody&gt; {% for x in orders %} &lt;td&gt;{{ x.agent_name }}&lt;/td&gt; &lt;td&gt;{{ x.customer.name }}&lt;/td&gt; &lt;td&gt;{{ x.request_date }}&lt;/td&gt; &lt;td&gt;{{ x.price }}&lt;/td&gt; &lt;/tr&gt; {% endfor %} &lt;/tbody&gt; &lt;/table&gt; &lt;/main&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>My view turns to:</p> <pre><code>def GetOrders(request): orders = Order.objects.order_by('-request_date') com = request.GET.get('name') if com != '' and com is not None: orders = orders.filter(Q(agent_name__icontains=com)) template = loader.get_template('orders.html') context = { 'orders' : orders, } return HttpResponse(template.render(context,request)) </code></pre> <p>But I cannot use it as a filter criterium because it is not a real model field and I get a FieldError:</p> <blockquote> <p>Cannot resolve keyword 'agent_name' into field</p> </blockquote>
<python><django><sqlite><django-models><django-views>
2024-09-11 19:22:04
5
303
grover999
78,975,219
4,749,639
Maintaining order in polars data frame after `partition_by`
<p>Does <code>polars.DataFrame.partition_by</code> preserves the order of rows <strong>within</strong> each group?</p> <p>I understand that <code>group_by</code> does, even when <code>maintain_order=False</code>. From <a href="https://docs.pola.rs/api/python/stable/reference/dataframe/api/polars.DataFrame.group_by.html" rel="nofollow noreferrer">documentation</a>: <em>Within each group, the order of rows is always preserved, regardless of this argument.</em></p> <p>But nothing is mentioned for the <code>partition_by</code> operation. I guess this means the order is not guaranteed to be preserved, but looking for confirmation, since from a few tests I did the resulting dataframes (partitioned) always respected the original order.</p> <p>Here is a the code I used for some toy experiment:</p> <pre><code>df = pl.DataFrame({ &quot;a&quot; : np.arange(100000000), &quot;b&quot;: np.random.randint(0,50,100000000) } ) all_dfs = df.partition_by(&quot;b&quot;, as_dict=True) for key, df in all_dfs.items(): assert df[&quot;a&quot;].is_sorted() </code></pre>
<python><python-polars>
2024-09-11 18:17:34
1
307
jcsun
78,974,811
16,155,080
Resource exhaustion and SSLTransport errors with FastAPI websocket shared between multiples threads
<p>I am developing a back-end FastAPI server that is a game.</p> <p>All players connect and interact with the game via a Websocket in the main thread.</p> <p>The game has multiples categories that are all running in a separate thread with the websocket as a common parameter. Input messages are received in the main thread then dealt within the category thread that will then send output message via the websocket.</p> <p>It seemed to be working fine at first but I keep having those logs in my server logs:</p> <pre><code>Fatal error on SSL transport protocol: &lt;asyncio.sslproto.SSLProtocol object at 0x7f79804ba140&gt; transport: None Traceback (most recent call last): File &quot;/usr/local/lib/python3.10/asyncio/sslproto.py&quot;, line 703, in _process_write_backlog del self._write_backlog[0] IndexError: deque index out of range </code></pre> <p>This seems to happen randomly, even after 10 minutes on laucnhing the server and no one has played/connected to any websocket. They don't break anything but I suspect them to point to a problem in my code flow. I can see my RAM is slowly going up until the app crashes after few days.</p> <p>Here is a basic implementation of the code:</p> <p><strong>api.py</strong></p> <p>Spawns all the games at start then listens to new websocket connection/messages to redirect them to the corresponding threaded game.</p> <pre><code>def create_gameflows(categories: list, websocket_manager) -&gt; Dict[str, Gameflow]: return {cat_name: Gameflow(id=i+1, websocket_manager=websocket_manager, category=cat_name) for i, cat_name in enumerate(categories)} app = FastAPI() manager = ConnectionManager() lock = asyncio.Lock() gameflows = create_gameflows(constants.CATEGORIES, manager) for gameflow in gameflows.values(): gameflow.start() async def handle_websocket(websocket: WebSocket, client_id: int, category: str) -&gt; None: &quot;&quot;&quot; Handle client incoming messages via websocket Parameters: websocket (WebSocket): &quot;&quot;&quot; async with lock: await manager.connect(websocket, client_id, category) gf = gameflows[category] try: while True: data = await websocket.receive_json() if data['type'] == 'NEW_PLAYER': while gf.game is None: time.sleep(0.1) user = User(**data['data']) user.websocket_id = str(get_cookie(websocket)) try: await gf.game.new_player(user, websocket, user.websocket_id, add_to_chat) except : await manager.send_error_message(websocket, user.websocket_id, data['data']['category'] ) raise elif data['type'] == 'ANSWER': websocket_id = get_cookie(websocket) await gf.game.user_answer(data, websocket_id, websocket) except WebSocketDisconnect: try: websocket_id = get_cookie(websocket) except (AttributeError, IndexError): websocket_id = str(client_id) await manager.close_connection(websocket_id, websocket_id, category) @app.websocket(&quot;/api/ws/{client_id}/{category}&quot;) async def websocket_endpoint(websocket: WebSocket, client_id:int, category: str): &quot;&quot;&quot; API route that redirect to the websocket endpoint. Args: websocket (WebSocket): &quot;&quot;&quot; await handle_websocket(websocket, client_id, category) </code></pre> <p><strong>Gameflow.py</strong></p> <p>Gameflow is an object that, given a category, will create games infinitely. Each created game is given the websocket manager and will send messages to the connected users.</p> <pre><code>class Gameflow: def __init__(self, websocket_manager, category: str): self.websocket_manager = websocket_manager self.category = category self.game = None self.waiting_time = None self.loop = asyncio.new_event_loop() self.executor = ThreadPoolExecutor(max_workers=1) async def play_game(self): while True: try: self.game = Game(id=0, websocket_manager=self.websocket_manager, category=self.category) await self.game.play_game() while not self.game.is_over: await asyncio.sleep(0.1) self.waiting_time = time.time() await asyncio.sleep(TIME_BETWEEN_GAME) except Exception as e: print(f&quot;Error in {self.category} game: {e}&quot;) await asyncio.sleep(10) # Wait before retrying def start(self): asyncio.set_event_loop(self.loop) self.loop.run_in_executor(self.executor, self.loop.run_forever) asyncio.run_coroutine_threadsafe(self.play_game(), self.loop) </code></pre> <p><strong>ConnectionManager</strong> is a manager that handles websockets connections for every current game. I can provide the code if needed.</p> <p>I tried using <code>async with lock</code> to prevent thread concurrency as I thought it could be a reason for the error logs but I still have them.</p> <p>I am clearly missing something and would like to have your ideas on this implementation, is it safe? Is there anything that could explain the logged SSL Transport errors? Is there anything that could explain my RAM constantly increasing?</p>
<python><multithreading><websocket><fastapi>
2024-09-11 16:22:21
0
641
Jules Civel
78,974,795
2,386,113
Caching in python is working slower than without caching
<p>In a Python program, I have to load a couple of thousands of files. I want to maintain their cache. I am able to create the cache using <code>joblib</code>. But for me, the program loads the data faster if I disable the caching.</p> <p><strong>Step to run MWE:</strong></p> <ul> <li>For my MWE, <a href="https://github.com/siddmittal/test/blob/main/dummy_test_files.7z" rel="nofollow noreferrer">you can download my dummy files from Github</a>.</li> <li>set the paths to dummy file directory and any directory to store cache in the variables <code>dummy_files_basepath</code> and <code>cache_dir</code></li> </ul> <p><strong>My MWE:</strong></p> <pre><code>import os import sys from concurrent.futures import ThreadPoolExecutor import joblib def __load_file(filepath): with open(filepath, 'r') as file: return filepath, file.read() def _load_files_data(basepath, filenames, enable_cache = False, cache_dir = None): if enable_cache: memory = joblib.Memory(cache_dir, verbose=0) load_file_data = memory.cache(__load_file) with ThreadPoolExecutor(max_workers=os.cpu_count()) as executor: data = list(executor.map(lambda filename: load_file_data(os.path.join(basepath, filename)), filenames)) else: with ThreadPoolExecutor(max_workers=os.cpu_count()) as executor: data = list(executor.map(lambda filename: __load_file(os.path.join(basepath, filename)), filenames)) return data class FilesLoader: @classmethod def load_files_data(cls, basepath, enable_cache = False, cache_dir = None): # find the files with extension .txt filenames = os.listdir(basepath) filenames = [filename for filename in filenames if filename.endswith('.txt')] # load the data using multipe threads data = _load_files_data(basepath, filenames, enable_cache, cache_dir) return data ####----------------------------------------Sample Run------------------------------------#### if __name__ == '__main__': dummy_files_basepath = &quot;SET_PATH_TO_MY_DUMMY_FILES&quot; cache_dir = &quot;SET_ANY_PATH&quot; # record the time taken to load the data import time start = time.time() data = FilesLoader.load_files_data(dummy_files_basepath, enable_cache = True, cache_dir = cache_dir) print(f&quot;Time taken to load the data: {time.time() - start}&quot;) print(len(data)) print(f&quot;First data filepath. {data[0][0]}&quot;) </code></pre> <p><strong>Question:</strong> Why accessing data is slower with caching enabled? In this example, I am loading <code>.txt</code> file but in my actual program I have <code>.pkl</code> files</p>
<python><python-3.x><caching><joblib>
2024-09-11 16:18:51
0
5,777
skm
78,974,468
865,220
scipy smoothening issue with zero values in window
<p>I have a pandas dataframe like this:</p> <pre><code>1960-09-01 24027064 4503904.333 1960-10-01 18020298 3377928.25 1960-11-01 12013532 2251952.167 1960-12-01 6006766 1125976.083 1961-01-01 0 0 1961-02-01 0 0 1961-03-01 0 0 1961-04-01 0 0 1961-05-01 0 0 1961-06-01 0 0 1961-07-01 0 0 1961-08-01 0 0 1961-09-01 0 0 1961-10-01 0 0 1961-11-01 0 0 1961-12-01 0 0 1969-01-01 0 0 1969-02-01 6173432.667 1150976.083 1969-03-01 12346865.33 2301952.167 1969-04-01 18520298 3452928.25 </code></pre> <p>I am trying to smoothen the data using somthing like this:</p> <pre><code>from scipy.signal import savgol_filter df = df.apply(savgol_filter, window_length=df.shape[0] // 5, polyorder=2) </code></pre> <p>I am getting something like this:</p> <pre><code>1960-09-01 25874679.88 4850242.328 1960-10-01 24574614.17 4606543.324 1960-11-01 23301520.97 4367900.35 1960-12-01 22055400.26 4134313.405 1961-01-01 20836252.04 3905782.489 1961-02-01 19644076.31 3682307.603 1961-03-01 18478873.09 3463888.745 1961-04-01 17340642.35 3250525.916 1961-05-01 16229384.11 3042219.117 1961-06-01 15145098.37 2838968.347 1961-07-01 14087785.12 2640773.605 1961-08-01 13057444.36 2447634.893 1961-09-01 12054076.1 2259552.21 1961-10-01 11077680.33 2076525.557 1961-11-01 10128257.06 1898554.932 1961-12-01 9205806.28 1725640.336 1969-01-01 19071395.37 5088684.927 1969-02-01 19448311.7 5412158.942 1969-03-01 19790962.91 5737508.936 1969-04-01 20099349 6080752.937 </code></pre> <p>But I dont want it that way, I want to keep zeros as zeros and also while computing smoothening function I want to ignore the zeros and apply smoothing function to the rest elements in the sliding window. For example if my <code>window_length</code> is 5 and I have <code>[0, 0, 6173432.667, 12346865.33, 18520298]</code> as current window content, I want the smoothening function to drop the zeros and convert the window to size of 3 ie <code>[6173432.667,12346865.33,18520298]</code> and calculate accordingly. In other words, essentially I want to apply piece-wise curve fitting for each of the non-zero stretch as smoothening function.</p>
<python><pandas><scipy>
2024-09-11 14:55:17
1
18,382
ishandutta2007
78,974,451
9,177,877
How to map scores from one table to another when the cell contains operators
<p>I performed OLS regression on a dataset and I have the predicted <code>Diagnostic_Score</code> but the mapping table (<code>norms</code>) can have two operators - e.g. <code>&gt;=</code> and <code>&lt;=</code>. Is there a way to map the predicted score to the percentile?</p> <p>My first thought was to map the scores that I can match and the ones that do not match I know must to be associated with a percentile that has an operator in the <code>Diagnostic_Score</code> column. I could then use <code>numpy.select</code> and create the conditions and choices. Does that approach make sense or is there an easier way to map the test percentile to the predicted score without having to manually create a 108 conditions and 108 choices for <code>numpy.select</code>?</p> <p>Here is a sample</p> <pre><code>import pandas as pd d = {'percentile': {0: 1, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1, 7: 1, 8: 1, 9: 2, 10: 2, 11: 2, 12: 2, 13: 2, 14: 2, 15: 2, 16: 2, 17: 2}, 'Subject': {0: 'Math', 1: 'Math', 2: 'Math', 3: 'Math', 4: 'Math', 5: 'Math', 6: 'Math', 7: 'Math', 8: 'Math', 9: 'Math', 10: 'Math', 11: 'Math', 12: 'Math', 13: 'Math', 14: 'Math', 15: 'Math', 16: 'Math', 17: 'Math'}, 'Term': {0: 'Fall', 1: 'Fall', 2: 'Fall', 3: 'Fall', 4: 'Fall', 5: 'Fall', 6: 'Fall', 7: 'Fall', 8: 'Fall', 9: 'Fall', 10: 'Fall', 11: 'Fall', 12: 'Fall', 13: 'Fall', 14: 'Fall', 15: 'Fall', 16: 'Fall', 17: 'Fall'}, 'Grade_Level': {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 0, 10: 1, 11: 2, 12: 3, 13: 4, 14: 5, 15: 6, 16: 7, 17: 8}, 'Diagnostic_Score': {0: '&lt;=296', 1: '&lt;=322', 2: '&lt;=352', 3: '&lt;=372', 4: '&lt;=390', 5: '&lt;=405', 6: '&lt;=412', 7: '&lt;=423', 8: '&lt;=434', 9: '297', 10: '323', 11: '353', 12: '373', 13: '391', 14: '406', 15: '413', 16: '424', 17: '435'}} norms = pd.DataFrame(d) df = pd.DataFrame({'Term': ['Fall', 'Fall', 'Fall', 'Fall'], 'Subject': ['Math', 'Math', 'Math', 'Math'], 'Grade_Level': [0, 3, 5, 7], 'Predicted Score': [290, 300, 406, 424]}) </code></pre> <p>My expected output is</p> <pre><code> Term Subject Grade_Level Predicted Score Percentile 0 Fall Math 0 290 1 1 Fall Math 3 300 1 2 Fall Math 5 406 2 3 Fall Math 7 424 2 </code></pre> <p>norms table</p> <pre><code> percentile Subject Term Grade_Level Diagnostic_Score 0 1 Math Fall 0 &lt;=296 1 1 Math Fall 1 &lt;=322 2 1 Math Fall 2 &lt;=352 3 1 Math Fall 3 &lt;=372 4 1 Math Fall 4 &lt;=390 5 1 Math Fall 5 &lt;=405 6 1 Math Fall 6 &lt;=412 7 1 Math Fall 7 &lt;=423 8 1 Math Fall 8 &lt;=434 9 2 Math Fall 0 297 10 2 Math Fall 1 323 11 2 Math Fall 2 353 12 2 Math Fall 3 373 13 2 Math Fall 4 391 14 2 Math Fall 5 406 15 2 Math Fall 6 413 16 2 Math Fall 7 424 17 2 Math Fall 8 435 ... 99 Math Spring 8 &gt;=585 </code></pre>
<python><pandas>
2024-09-11 14:52:32
2
14,163
It_is_Chris
78,974,386
5,269,892
Pandas avoid element-wise NaN check for lists
<p>I have a dataframe with columns containing both single NaNs, as well as lists which may contain NaN elements. Example:</p> <pre><code>df = pd.DataFrame({'A': [[1, 2, 3], np.nan, [7, np.nan, np.nan], [4, 5, 6]]}) </code></pre> <p>I want to check whether the cell values are single NaNs. The expected result of <code>[False, True, False, False]</code> is printed by the following command:</p> <pre><code>df.isna() </code></pre> <p>Now I want to check whether a particular cell, say the third element (index 2) is NaN. Run the following code:</p> <pre><code>elem = df.loc[2,'A'] pd.isna(elem) </code></pre> <p>The output is <code>array([ False, True, True])</code> rather than <code>False</code>. I understand that <code>pd.isna()</code> and <code>np.isnan()</code> go element-wise over lists or arrays (and that this is a sensible default), but is there a simple command to compare the list as a whole against a single NaN instead?</p>
<python><pandas><nan>
2024-09-11 14:40:44
1
1,314
silence_of_the_lambdas
78,974,328
9,401,990
How to install latest Python patch on older versions?
<p>I've had a look online and can't figure out how to install the latest patch on an older version of Python.</p> <p>I'm on Windows, with no admin rights. I want to upgrade 3.10.1 to 3.10.15, without losing any of my installed libraries (like pandas). I don't want to upgrade to the latest minor version (3.12.x).</p> <p>Common answers:</p> <blockquote> <p>just download the latest installer?! <em>No, I need to use 3.10.x for various reasons. 3.10.15 doesn't have an .exe installer to download</em></p> </blockquote> <blockquote> <p>use chocolatey. <em>No, I can't as I don't have admin rights on my work laptop</em></p> </blockquote> <blockquote> <p>extract the tarball. <em>I've downloaded Python-3.10.15.tgz and can extract using <code>tar</code> command, but where do I extract it to? The extracted root folder is called 'Python-3.10.15' whereas my current Python folder is called 'Python310', so I'm not sure an extraction would overwrite...</em></p> </blockquote> <p>Any ideas or reference docs?</p>
<python><windows>
2024-09-11 14:26:03
0
1,408
Theo F
78,974,282
13,570,788
Why is sys.stdout adjustment needed to print Unicode in Python?
<p>I scraped some data from the web using: <br></p> <pre><code>import requests from bs4 import BeautifulSoup def get_lines_from_url(url): response = requests.get(url) if response.status_code == 200: soup = BeautifulSoup(response.text, 'html.parser') lines = soup.get_text(&quot;\n&quot;).strip().splitlines() return lines </code></pre> <p>while printing them with:</p> <pre><code>all_lines = get_lines_from_url(link) for line in all_lines: print(line) </code></pre> <p>i encounter <code>UnicodeEncodeError: 'charmap' codec can't encode character '\u2588' in position 0: character maps to &lt;undefined&gt;</code></p> <p>I printed the encoded version of each line with:</p> <pre><code>for line in all_lines: print(line.encode('utf-8')) </code></pre> <p>The culprit was a line containing <code>b'\xe2\x96\x88'</code>.<br></p> <p>I did some research and found that all lines print when i include <code>sys.stdout = codecs.getwriter(&quot;utf-8&quot;)(sys.stdout.detach())</code> as in:</p> <pre><code>import sys import codecs # other imports... # `get_lines_from_url` declaration... sys.stdout = codecs.getwriter(&quot;utf-8&quot;)(sys.stdout.detach()) all_lines = get_lines_from_url(link) for line in all_lines: print(line) </code></pre> <p>What does <code>sys.stdout = codecs.getwriter(&quot;utf-8&quot;)(sys.stdout.detach())</code> do? why couldn't Python print <code>b'\xe2\x96\x88'</code> directly?</p>
<python><web-scraping><beautifulsoup><unicode><codec>
2024-09-11 14:15:13
0
485
Kun.tito
78,974,186
11,092,636
Sphere Online Judge (SPOJ) Python input handling broken?
<p>I'm fairly familiar with input handling in Competitive Programming settings, but I can't make it work in Python for this problem (<a href="https://www.spoj.com/problems/MINDIST/" rel="nofollow noreferrer">https://www.spoj.com/problems/MINDIST/</a>) (my solution works in C++ so the problem in itself is not broken). What is the standard way to read input in the SPOJ platform?</p> <p>Here, this is what will be fed to the stdin:</p> <blockquote> <p>The first line of the input contains a single integer T, the number of test cases. T blocks follow.</p> <p>For each test case, the first line contains two space-separated integer N (1&lt;=N&lt;=100000) and S (0&lt;=S&lt;=100000000). N-1 lines follow, each contains three integers X (1&lt;=X&lt;=N), Y (1&lt;=Y&lt;=N) and Z (1&lt;=Z&lt;=1000), denotes that there is an (undirected) edge weighted Z between node X and Y. The input is correct.</p> </blockquote> <p>And an example of fed input would be:</p> <pre><code>2 5 2 1 2 5 2 3 2 2 4 4 2 5 3 8 6 1 3 2 2 3 2 3 4 6 4 5 3 4 6 4 4 7 2 7 8 3 </code></pre> <p>MRE:</p> <p>This (just the input handling) gets &quot;runtime error, Non-Zero Exit Code&quot; (but works locally and on online compilers such as ideone):</p> <pre class="lang-py prettyprint-override"><code>def get_int(): return int(input()) def get_ints(): return map(int, input().split()) T = get_int() for _ in range(T): N, S = get_ints() for _ in range(N-1): X, Y, Z = get_ints() </code></pre> <p>It seems the <code>get_ints()</code> call is the problem because this:</p> <pre class="lang-py prettyprint-override"><code>def get_int(): return int(input()) def get_ints(): return map(int, input().split()) T = get_int() for _ in range(T): N, S = 2, 3 for _ in range(N-1): X, Y, Z = 1, 2, 3 </code></pre> <p>gets (as expected) &quot;wrong answer&quot;.</p> <p>I'm at loss as to why this happens.</p>
<python><stdin>
2024-09-11 13:53:37
1
720
FluidMechanics Potential Flows
78,974,149
10,425,150
Alternative to fillna(method='pad', inplace=True) to avoid FutureWarning
<p>I would like to fill NA/NaN values with the last valid option.</p> <p><strong>My code:</strong></p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame({&quot;Col1&quot;:[&quot;A&quot;, np.nan, 1, np.nan], &quot;Col2&quot;:[&quot;B&quot;, np.nan, &quot;C&quot;, np.nan]}) df.fillna(method='pad', inplace=True) </code></pre> <p><strong>Output:</strong></p> <div class="s-table-container"><table class="s-table"> <thead> <tr> <th style="text-align: left;">Col1</th> <th style="text-align: left;">Col2</th> </tr> </thead> <tbody> <tr> <td style="text-align: left;">A</td> <td style="text-align: left;">B</td> </tr> <tr> <td style="text-align: left;">A</td> <td style="text-align: left;">B</td> </tr> <tr> <td style="text-align: left;">1</td> <td style="text-align: left;">C</td> </tr> <tr> <td style="text-align: left;">1</td> <td style="text-align: left;">C</td> </tr> </tbody> </table></div> <p><strong>Warning Massage:</strong></p> <pre><code>FutureWarning: DataFrame.fillna with 'method' is deprecated and will raise in a future version. Use obj.ffill() or obj.bfill() instead. </code></pre> <p><strong>Using: df.bfill</strong></p> <p>However the <code>bfill</code> provides different output from what I used to have.</p> <pre><code>df.bfill( inplace=True) </code></pre> <p>Output for <code>bfill</code>:</p> <div class="s-table-container"><table class="s-table"> <thead> <tr> <th style="text-align: left;">Col1</th> <th style="text-align: left;">Col2</th> </tr> </thead> <tbody> <tr> <td style="text-align: left;">A</td> <td style="text-align: left;">B</td> </tr> <tr> <td style="text-align: left;">1</td> <td style="text-align: left;">C</td> </tr> <tr> <td style="text-align: left;">1</td> <td style="text-align: left;">C</td> </tr> <tr> <td style="text-align: left;">nan</td> <td style="text-align: left;">nan</td> </tr> </tbody> </table></div> <p><strong>Using: df.pad</strong></p> <p>I've tried to use <code>df.pad</code>:</p> <pre><code>df.pad(inplace=True) </code></pre> <p>It returns the right output, but then I get another <code>FutureWarning</code>:</p> <pre><code>FutureWarning: DataFrame.pad/Series.pad is deprecated. Use DataFrame.ffill/Series.ffill instead </code></pre> <p><strong>Question:</strong> What is alternative to fillna(method='pad', inplace=True) to avoid FutureWarning message?</p>
<python><pandas><dataframe><fillna>
2024-09-11 13:45:30
1
1,051
GΠΎΠΎd_MΠ°n
78,974,111
534,238
What windowing constraints are needed when combining two streams in Apache Beam [Dataflow]?
<p>I have an ETL flow where I need to combine two Pub/Sub messages on a key and write these into BigQuery. One of the message types is the parent; I am working on payment processing, and this is an order or a payment, for example. The other is the child; this is an update to the payment (&quot;Authorized&quot;, &quot;Paid&quot;, etc).</p> <p>I would like to use Dataflow to combine on the key and write to BigQuery, where these updates are added elements to the original transaction. The schema in BigQuery looks something like this:</p> <div class="s-table-container"><table class="s-table"> <thead> <tr> <th style="text-align: center;">name</th> <th style="text-align: center;">description</th> <th style="text-align: center;">type</th> <th style="text-align: center;">mode</th> </tr> </thead> <tbody> <tr> <td style="text-align: center;">id</td> <td style="text-align: center;">UUID for payment transaction</td> <td style="text-align: center;">String</td> <td style="text-align: center;">Single</td> </tr> <tr> <td style="text-align: center;">amount</td> <td style="text-align: center;">transaction amount</td> <td style="text-align: center;">Integer</td> <td style="text-align: center;">Single</td> </tr> <tr> <td style="text-align: center;">event</td> <td style="text-align: center;">the transaction event (see below)</td> <td style="text-align: center;">Record</td> <td style="text-align: center;">Repeated</td> </tr> </tbody> </table></div> <p>...</p> <p>and within the events <em>record</em>, it has something like:</p> <div class="s-table-container"><table class="s-table"> <thead> <tr> <th style="text-align: center;">name</th> <th style="text-align: center;">description</th> <th style="text-align: center;">type</th> <th style="text-align: center;">mode</th> </tr> </thead> <tbody> <tr> <td style="text-align: center;">event_id</td> <td style="text-align: center;">UUID for this event</td> <td style="text-align: center;">String</td> <td style="text-align: center;">Single</td> </tr> <tr> <td style="text-align: center;">transaction_id</td> <td style="text-align: center;">UUID tying back to payment transaction (above)</td> <td style="text-align: center;">String</td> <td style="text-align: center;">Single</td> </tr> <tr> <td style="text-align: center;">event_type</td> <td style="text-align: center;">an enum specifying if it is an Authorization, etc.</td> <td style="text-align: center;">Integer</td> <td style="text-align: center;">Single</td> </tr> </tbody> </table></div> <p>...</p> <p>In other words, each <strong>event-type</strong> Pub/Sub message will be matched with the appropriate <strong>transaction-type</strong> Pub/Sub message.</p> <p>I am planning on using Dataflow's <a href="https://beam.apache.org/documentation/transforms/python/aggregation/cogroupbykey/#examples" rel="nofollow noreferrer"><code>CoGroupByKey</code></a>. AFAICT, there is <em>no specification</em> for what sort of windowing is required for <code>CoGroupByKey</code> to use, if any. In that case, I don't understand how it works. Something like one of the following options is needed, I would presume:</p> <ol> <li><code>CoGroupByKey</code> will leave each element in memory <em>indefinitely</em> until the other element is found. For instance, if there is an <code>id</code> on the transaction of value <code>1234987</code>, then it will remain &quot;in waiting&quot; until the <code>transaction_id</code> of <code>1234987</code> were found. After it is found, <code>CoGroupByKey</code> is performed, and whatever subsequent pipeline actions are completed, then the message with that ID can be purged from memory.</li> <li><code>CoGroupByKey</code> will not work on <em>streaming</em> data unless there is windowing in place. Similar to above, it would remain in waiting until the same <code>id</code> and <code>transaction_id</code> are matched. However, it _would purge the <code>id</code> or <code>transaction_id</code> once the window (and whatever associated allowed lateness) has expired. <ul> <li>This is clearly not needed for non-streaming data, as the <code>CoGroupByKey</code> <a href="https://beam.apache.org/documentation/transforms/python/aggregation/cogroupbykey/#examples" rel="nofollow noreferrer">example</a> is not windowed.</li> </ul> </li> <li>There is some other alternative. Perhaps some method on the <code>PCollection</code> that I am unaware of that allows for some sort of purge.</li> </ol> <p>Am I right? Do I need some sort of limitation? What is that limitation, or what should it be?</p> <p>I simply need to know how I can create a pipeline combining these two streams in a way that will not crash my system once in production. This is difficult to test for, if the memory problem will only creep up once I am at massive scale.</p> <p>(I use the Python SDK, but coded solutions in any language are appreciated; it's easy enough to translate from one to another.)</p>
<python><google-cloud-dataflow><apache-beam>
2024-09-11 13:36:27
1
3,558
Mike Williamson
78,974,009
2,287,458
Polars pl.col(field).name.map_fields applies to all struct columns (not the one specified)
<p>I have this code:</p> <pre class="lang-py prettyprint-override"><code>import polars as pl cols = ['Delta', 'Qty'] metrics = {'CHECK.US': {'Delta': {'ABC': 1, 'DEF': 2}, 'Qty': {'GHIJ': 3, 'TT': 4}}, 'CHECK.NA': {}, 'CHECK.FR': {'Delta': {'QQQ': 7, 'ABC': 6}, 'Qty': {'SS': 9, 'TT': 5}} } df = pl.DataFrame([{col: v.get(col) for col in cols} for v in metrics.values()])\ .insert_column(0, pl.Series('key', metrics.keys()))\ .with_columns([pl.col(col).name.map_fields(lambda x: f'{col} ({x})') for col in cols]) </code></pre> <p>Now, <code>df.unnest('Qty')</code> correctly gives all columns formatted as <code>Qty (xxx)</code>:</p> <pre><code>shape: (3, 5) β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ key ┆ Delta ┆ Qty (GHIJ) ┆ Qty (TT) ┆ Qty (SS) β”‚ β”‚ --- ┆ --- ┆ --- ┆ --- ┆ --- β”‚ β”‚ str ┆ struct[3] ┆ i64 ┆ i64 ┆ i64 β”‚ β•žβ•β•β•β•β•β•β•β•β•β•β•ͺ════════════β•ͺ════════════β•ͺ══════════β•ͺ══════════║ β”‚ CHECK.US ┆ {1,2,null} ┆ 3 ┆ 4 ┆ null β”‚ β”‚ CHECK.NA ┆ null ┆ null ┆ null ┆ null β”‚ β”‚ CHECK.FR ┆ {6,null,7} ┆ null ┆ 5 ┆ 9 β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ </code></pre> <p>However, when I do the same thing for <code>df.unnest('Delta')</code> it incorrectly returns columns with <code>Qty (xxx)</code>:</p> <pre><code>shape: (3, 5) β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ key ┆ Qty (ABC) ┆ Qty (DEF) ┆ Qty (QQQ) ┆ Qty β”‚ β”‚ --- ┆ --- ┆ --- ┆ --- ┆ --- β”‚ β”‚ str ┆ i64 ┆ i64 ┆ i64 ┆ struct[3] β”‚ β•žβ•β•β•β•β•β•β•β•β•β•β•ͺ═══════════β•ͺ═══════════β•ͺ═══════════β•ͺ════════════║ β”‚ CHECK.US ┆ 1 ┆ 2 ┆ null ┆ {3,4,null} β”‚ β”‚ CHECK.NA ┆ null ┆ null ┆ null ┆ null β”‚ β”‚ CHECK.FR ┆ 6 ┆ null ┆ 7 ┆ {null,5,9} β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ </code></pre> <p>The values look correct, just the column names are wrong.</p> <p>Am I using <code>pl.col(col).name.map_field(...)</code> incorrectly? How can I fix my code so that the output becomes this:</p> <pre><code>shape: (3, 5) β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ key ┆ Delta (ABC) ┆ Delta (DEF) ┆ Delta (QQQ) ┆ Qty β”‚ β”‚ --- ┆ --- ┆ --- ┆ --- ┆ --- β”‚ β”‚ str ┆ i64 ┆ i64 ┆ i64 ┆ struct[3] β”‚ β•žβ•β•β•β•β•β•β•β•β•β•β•ͺ═════════════β•ͺ═════════════β•ͺ═════════════β•ͺ════════════║ </code></pre>
<python><dataframe><python-polars>
2024-09-11 13:17:40
1
3,591
Phil-ZXX
78,973,872
536,262
plotly scatterplot on top of annotation
<p>Any way to get an annotation below/under a scatter plot, so that the scatter-points show on top of the annotation text/link?</p> <p>I tried with <code>zorder=100</code> in <code>scatter</code>, but there is no <code>zorder</code> in <code>add_annotation()</code></p> <p>Below are the annotation and the scatter settings:</p> <pre class="lang-py prettyprint-override"><code>for i,px in enumerate(data['xpos']): nice = timegraph['nice'][i] fig.add_annotation( x=px, xshift=10, y=0, yshift=80, text=f&quot;&lt;a href=\&quot;{data['urls'][i]}\&quot; alt=_blank&gt;{px} - {nice}&lt;/a&gt;&quot;, textangle=270, bgcolor=&quot;#FFFFFF&quot; ) fig.add_trace( go.Scatter( x=data['xpos'], y=timegraph['ygrid'], yaxis=&quot;y2&quot;, name=&quot;Total Testrun Time&quot;, marker={'color': 'gray', 'size': 15}, text=timegraph['nice'], mode='markers' ) ) </code></pre> <p>The gray scatter-points on the 4 leftmost bars are below the annotated timestamp and not showing, I hold the mouse on the point and get the gray legend:</p> <p><a href="https://i.sstatic.net/0tkuZ3CY.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/0tkuZ3CY.png" alt="test-scenario history excerp" /></a></p>
<python><plotly>
2024-09-11 12:49:54
1
3,731
MortenB
78,973,639
3,879,857
Python pydantic validation of subclasses
<p>I'm trying to use <code>pydantic</code> together with <code>ABC</code>. I created a base class <code>Datasource</code> and four subclasses:</p> <pre><code>from pydantic import BaseModel from typing import Literal, Union, TypeVar from devtools import debug from abc import ABC, abstractmethod class Datasource(ABC, BaseModel): source: str frequency: str @abstractmethod def hello(): pass class FirstStaticDatasource(Datasource): source: Literal[&quot;first&quot;] = &quot;first&quot; frequency: Literal[&quot;static&quot;] = &quot;static&quot; a: int def hello(): pass class FirstDynamicDatasource(Datasource): source: Literal[&quot;first&quot;] = &quot;first&quot; frequency: Literal[&quot;daily&quot;] = &quot;daily&quot; b: int def hello(): pass class SecondStaticDatasource(Datasource): source: Literal[&quot;second&quot;] = &quot;second&quot; frequency: Literal[&quot;static&quot;] = &quot;static&quot; c: int def hello(): pass class SecondDynamicDatasource(Datasource): source: Literal[&quot;second&quot;] = &quot;second&quot; frequency: Literal[&quot;yearly&quot;] = &quot;yearly&quot; d: int def hello(): pass DatasourceInterface = TypeVar('DatasourceInterface', bound=Datasource) # DatasourceInterface = Union[tuple(Datasource.__subclasses__())] class Settings(BaseModel): datas: list[DatasourceInterface] if __name__ == &quot;__main__&quot;: settings = Settings(datas=[ FirstStaticDatasource(a=1), FirstDynamicDatasource(b=2), SecondStaticDatasource(c=3), SecondDynamicDatasource(d=4) ]) debug(settings) json = settings.model_dump_json() debug(json) new_settings = Settings.model_validate_json(json) debug(new_settings) </code></pre> <p>If I try to run this I got the following error</p> <pre><code>TypeError: Can't instantiate abstract class Datasource without an implementation for abstract method 'hello' </code></pre> <p>Now, if I try to remove the abstract method, the code runs, <em>but</em>, in <code>new_settings</code>, <code>datas</code> results to be a list of the base class <code>DataSource</code> (i.e.: I cannot see <code>a</code>, <code>b</code>, <code>c</code> and <code>d</code> class members specified in the derived subclasses).</p> <p>All the problems seems solved if, instead of</p> <pre><code>DatasourceInterface = TypeVar('DatasourceInterface', bound=Datasource) </code></pre> <p>I place</p> <pre><code>DatasourceInterface = Union[tuple(Datasource.__subclasses__())] </code></pre> <p>Is there a way to reach the same result without using &quot;metaprogramming&quot;?</p>
<python><subclass><pydantic><type-variables>
2024-09-11 11:51:09
0
887
MaPo
78,973,619
9,448,637
How can I stop pandas from plotting weekend dates for 5T frequency data when there is no weekend data?
<p>I have the following 5-minute frequency time series data for weekdays only:</p> <pre><code>start_date = '2024-09-06 00:00:00' end_date = '2024-09-10 00:00:00' dt_index = pd.date_range(start=start_date, end=end_date, freq='5T') dt_index = dt_index[dt_index.weekday &lt; 5] # remove weekend days data = np.random.randn(len(dt_index)) df = pd.DataFrame(data, index=dt_index, columns=['Random_Data']) df </code></pre> <p><a href="https://i.sstatic.net/E46XxYXZ.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/E46XxYXZ.png" alt="Sample df" /></a></p> <p>There are no weekend dates or weekend data in the dataframe, but this is what I get when I plot it:</p> <p><a href="https://i.sstatic.net/bqWG6uUr.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/bqWG6uUr.png" alt="Pandas plots weekend dates when there aren't any in the df" /></a></p> <p>How can I stop pandas from plotting the weekend dates? I only want to plot weekdays - I don't want any gaps or straight connected lines where there aren't any dates or data.</p> <p>The answer that was suggested as a duplicate to my question suggests adding back missing data, getting rid of null values, and/or plotting a gap instead of line for missing data. My data is not missing data so there is nothing to add back, nor does it have any null values. Please don't close this question.</p>
<python><pandas><matplotlib><datetime>
2024-09-11 11:46:10
1
641
footfalcon
78,973,374
1,348,691
transfomers runtimeError `No module named 'keras.__internal__`
<p>I have these installed:</p> <pre><code>keras 3.5.0 tensorflow 2.17.0 tensorflow-intel 2.17.0 tensorflow-io-gcs-filesystem 0.31.0 torch 2.2.2 </code></pre> <p>And transformers results an error:</p> <pre><code>from transformers import pipeline pipeline(&quot;text-classification&quot;) </code></pre> <pre><code>RuntimeError: Failed to import transformers.models.distilbert.modeling_tf_distilbert because of the following error (look up to see its traceback): No module named 'keras.__internal__ </code></pre>
<python><pytorch><tf.keras>
2024-09-11 10:43:03
0
4,869
Tiina
78,973,371
1,103,752
How to prevent `pip install` resulting in duplicate code?
<p>I am working on a library with some others. Our git repo (called <code>modulename</code>) looks like this</p> <pre><code>modulename/ src_file_1.py src_file_2.py tests/ ... .../ </code></pre> <p>The instructions are to clone this somewhere in home, so I now have</p> <pre><code>~/ modulename/ modulename/ src_file_1.py src_file_2.py tests/ ... .../ </code></pre> <p>and then run <code>pip install .</code> from inside the first <code>modulename</code>. After that, when I look in <code>site-packages</code>, I have</p> <pre><code>site-packages/ modulename/ src_file_1.py src_file_2.py </code></pre> <p>so pip has copied the source into <code>site-packages</code></p> <p>The problem I how have, is that when I make changes to the cloned repository, those changes are not copied into <code>site-packages</code>, so when I use the module in some other code, I only see the version copied when I did <code>pip install .</code>. I'm in a bit of a mess here. What is the proper way to work on this library so I can commit my changes back to git and also import the module from other places on my machine?</p>
<python><pip><python-module>
2024-09-11 10:42:22
1
5,737
ACarter
78,973,154
9,663,207
How do I create a Python API client which executes *some* methods asynchronously in the background?
<p>I have this (example) REST API client:</p> <pre class="lang-py prettyprint-override"><code>import requests class FakeHttpClient: base_url = &quot;https://api.example.com&quot; def __init__(self) -&gt; None: self.session = requests.Session() def get_user_info(self, user_id: str) -&gt; dict: return self.session.get(f&quot;{self.base_url}/users/{user_id}&quot;).json() def get_users_info(self, user_ids: list[str]) -&gt; list[dict]: return [self.get_user_info(user_id) for user_id in user_ids] if __name__ == '__main__': users = FakeHttpClient().get_users_info([&quot;1&quot;, &quot;2&quot;, &quot;3&quot;]) </code></pre> <p>I am trying to rewrite this using <code>aiohttp</code> so that the user interface is the same (i.e. creating the API client instance synchronously and calling its methods synchronously)? I have managed to create a fully async client, but this is overkill for users since it is only the <code>get_users_info()</code> method which benefits from asynchronous execution - I don't want people to have to invoke <code>async</code> and <code>await</code> keywords and use context managers and all that stuff for a single HTTP request which it would be fine to be synchronous.</p>
<python><asynchronous><python-requests><aiohttp>
2024-09-11 09:57:02
2
724
g_t_m
78,973,117
5,790,653
How to check if a subject is not in the all_subjects of emails
<p>I have a list of email subjects which were sent today (I connect to my IMAP server, and fetch all emails):</p> <pre class="lang-py prettyprint-override"><code>sent_subjects = [ 'subject1 backup up completed', 'subject2-2 backup failed', 'subject4 backup partial complete', 'email3 done', 'ak47 failed', 'mp5 is good', 'm4 is good' ] </code></pre> <p>I have a <code>json</code> file and almost all scripts I have and send email, they have entry there:</p> <pre class="lang-py prettyprint-override"><code>emails = [ {'subject': 'mp3 is good', 'date': '2020-02-02'}, {'subject': 'mp5 is good', 'date': '2020-02-02'}, {'subject': 'm4 is good', 'date': '2020-02-02'} ] </code></pre> <p>And I create <code>subjects</code> like this:</p> <pre class="lang-py prettyprint-override"><code>subjects = [x['subject'] for x in emails] </code></pre> <p>These are all the subjects that should be sent (some of them were not sent):</p> <pre class="lang-py prettyprint-override"><code>static_subjects = [ 'subject1', 'subject2-2', 'subject4', 'email3', 'ak47', 'subject10', 'email11', 'final destination' ] subjects += static_subjects subjects.sort() </code></pre> <p>I know I can do this, but this does not return the expected output:</p> <pre><code>final = list(set(subjects) - set(sent_subjects)) </code></pre> <p>Because some subjects like <code>subject1</code> and <code>subject4</code> do not have static subject and they may change based on some conditions (these subjects are not mine, and I do not send email with these subjects. I just receive them).</p> <p>So, I need to check if any subjects of <code>subjects</code> are not in <code>sent_subjects</code>, so I can trace which emails I did not receive, to see if there any issues.</p> <p>In this case, I did not receive these subjects and the output should have them:</p> <pre><code>mp3 is good subject10 email11 final destination </code></pre> <p>The other thing I know is using <code>if ==</code> does not work, because <code>email11</code> for example is like <code>subject1</code> and <code>subject2-2</code> that has two or more subjects (if fails or success).</p> <p>Would you please help me regarding this?</p>
<python><json><imap>
2024-09-11 09:52:08
1
4,175
Saeed
78,973,039
10,377,244
Efficiently generate user history with negative sampling for recommendation system using Polars API
<p>I’m working on a recommendation system, and I need to efficiently generate user history with negative sampling using the Polars API. I have two datasets:</p> <ol> <li>User-Article Interactions: β€’ This dataset contains the user_id and the article_id of articles that the user has read. Example:</li> </ol> <pre class="lang-py prettyprint-override"><code>import polars as pl df_user_articles = pl.DataFrame({ 'user_id': [1, 1, 2, 2, 2, 3, 4, 4, 4, 4], 'article_id': [101, 102, 103, 104, 105, 106, 107, 108, 109, 110] }) </code></pre> <p>This dataset contains all article_id and their corresponding text data.</p> <pre class="lang-py prettyprint-override"><code>df_articles = pl.DataFrame({ 'article_id': list(range(100, 200)), # example article IDs 'text': ['text'] * 100 }) </code></pre> <p>For each user_id, I want to:</p> <ol> <li>Create a history of articles they’ve read, with a length between 5 and 20.</li> <li>Generate candidates for each user by selecting some articles they’ve read (positive samples) and some they haven’t (negative samples). The candidates should be labeled: <ul> <li>-1 for articles the user has read.</li> <li>-0 for articles the user hasn’t read.</li> </ul> </li> </ol> <p>Output format:</p> <p>I want the output as a DataFrame with the following columns:</p> <ul> <li>user_id: The user ID.</li> <li>user_history: A list of article IDs the user has read.</li> <li>candidates: A list of candidate article IDs, each labeled with -1 or -0.</li> </ul> <div class="s-table-container"><table class="s-table"> <thead> <tr> <th>user_id</th> <th>user_history</th> <th>candidates</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>['101', '102']</td> <td>['101-1', '102-1', '103-0']</td> </tr> <tr> <td>2</td> <td>['103', '104', '105']</td> <td>['103-1', '104-1', '105-1', '106-0']</td> </tr> </tbody> </table></div> <p>How can I efficiently achieve this using the Polars API, avoiding apply and ensuring that the solution scales well with large datasets?</p> <p>To optimize for efficiency, we don’t need to check if the article IDs have been read by the user during candidate generation.</p> <p>I have a solution but it not keep the category type of &quot;article_id&quot;</p> <pre><code>matrix_size = users_df.shape[0] num_candidates = 5 index_matrix = np.random.randint(0, articles_df.shape[0], size=(matrix_size, num_candidates)) index_matrix users_df.with_columns( candidates=articles_df['article_id'].to_numpy()[:,np.newaxis][index_matrix].reshape(matrix_size, num_candidates) ) </code></pre>
<python><python-polars>
2024-09-11 09:35:11
1
1,127
MPA
78,973,036
5,688,247
Read csv without filling up empty values
<p>I have the following csv I want to read into Python (Spyder) and count the amount of blank values in column 2:</p> <div class="s-table-container"><table class="s-table"> <thead> <tr> <th>column 1</th> <th>column 2</th> </tr> </thead> <tbody> <tr> <td>A</td> <td>N/A</td> </tr> <tr> <td>B</td> <td>N/A</td> </tr> <tr> <td>C</td> <td>N/A</td> </tr> <tr> <td>D</td> <td></td> </tr> <tr> <td>E</td> <td>N/A</td> </tr> <tr> <td>F</td> <td>N/A</td> </tr> <tr> <td>G</td> <td></td> </tr> <tr> <td>H</td> <td>N/A</td> </tr> </tbody> </table></div> <p>In this case, there are two blank values, the rest are default values.</p> <p>The standard code is:</p> <p><code>LoadFile=pd.read_csv(FileName)</code></p> <p>Which reads in the data as:</p> <div class="s-table-container"><table class="s-table"> <thead> <tr> <th>column 1</th> <th>column 2</th> </tr> </thead> <tbody> <tr> <td>A</td> <td>NaN</td> </tr> <tr> <td>B</td> <td>NaN</td> </tr> <tr> <td>C</td> <td>NaN</td> </tr> <tr> <td>D</td> <td>NaN</td> </tr> <tr> <td>E</td> <td>NaN</td> </tr> <tr> <td>F</td> <td>NaN</td> </tr> <tr> <td>G</td> <td>NaN</td> </tr> <tr> <td>H</td> <td>NaN</td> </tr> </tbody> </table></div> <p>So the empty count is 8, not 2</p> <pre><code>missings =LoadFile['column 2'].isnull().sum() </code></pre> <p>Then I tried to read it in as:</p> <p><code>LoadFile=pd.read_csv(FileName,na_values='', keep_default_na=False)</code></p> <p>Which changes the table into:</p> <div class="s-table-container"><table class="s-table"> <thead> <tr> <th>column 1</th> <th>column 2</th> </tr> </thead> <tbody> <tr> <td>A</td> <td>N/A</td> </tr> <tr> <td>B</td> <td>N/A</td> </tr> <tr> <td>C</td> <td>N/A</td> </tr> <tr> <td>D</td> <td>N/A</td> </tr> <tr> <td>E</td> <td>N/A</td> </tr> <tr> <td>F</td> <td>N/A</td> </tr> <tr> <td>G</td> <td>N/A</td> </tr> <tr> <td>H</td> <td>N/A</td> </tr> </tbody> </table></div> <p>So the empty count is zero.</p> <p>How do I read in my csv file so the empty count is 2 and it does not alter the empty values.</p>
<python><pandas><read-csv>
2024-09-11 09:34:56
1
863
Jellyse
78,972,997
1,581,090
How to use "threading" in python in an unblocking way?
<p>I have a complete &quot;working&quot; python code which is supposed to contain two threads which run simultaneously, which populate some lists in a dict, and when the user presses CRTL-C these two threads should be stopped and some output from both threads should be written to a file:</p> <pre><code>import sys import time import threading import signal from functools import partial messages = {} lock = threading.Lock() class Handler: def __init__(self, port): self.port = port def run(self): while True: time.sleep(1) with lock: messages[self.port].append(time.time()) def signal_handler(filename, sig, frame): with lock: with open(filename, &quot;w&quot;) as fileout: json.dump(messages, fileout) sys.exit(0) output = &quot;test.out&quot; signal.signal(signal.SIGINT, partial(signal_handler, output)) for port in [1,2]: messages[port] = [] handler = Handler(port) print(&quot;debug1&quot;) t = threading.Thread(target=handler.run()) print(&quot;debug2&quot;) t.daemon = True t.start() threads.append(t) # Keep the main thread running, waiting for CTRL-C try: while True: pass except KeyboardInterrupt: signal_handler(output, signal.SIGINT, None) </code></pre> <p>However, this code blocks execution after the first <code>debug1</code> has been printed. How to &quot;unblock&quot; this line so the two threads are started until the user presses CRTL-C (and the output is saved to a file)?</p> <p>...The above code is just a template of a more complicated code that actually does something useful...</p>
<python><multithreading>
2024-09-11 09:26:49
1
45,023
Alex
78,972,996
3,414,626
AWS Python Lambda - Package Size & Cold Starts
<p>I was wondering whether someone here shared the same experience.</p> <ul> <li>I have a Python Lambda which runs some β€œsimple” requests for recommending images based on a vector database (qdrant). The package itself already has a size of 65MB (e.g. qdrant client and firebase).</li> <li>Although I turned on provisioned concurrency I still have cold starts of roughly 5 seconds. I even created a dummy lambda which has no imports and responds a 200 immediately and has the same packages installed - still 5 sec cold start. Using loggings I triple checked that provisioned concurrency is utilized.</li> <li>I am thinking about a complete rewrite in TypeScript of the Lambda to handle these cold starts.</li> </ul> <p>Do you have the same experiences regarding Python Lambdas? Is there a neat trick I am not aware of?</p>
<python><amazon-web-services><aws-lambda><cold-start>
2024-09-11 09:26:48
1
552
Richard
78,972,680
4,451,315
pyarrow chunkedarray get items at given indices
<p>Say I have</p> <pre class="lang-py prettyprint-override"><code>In [3]: import pyarrow as pa In [4]: ca = pa.chunked_array([[1,2,3], [4,5,6]]) </code></pre> <p>I'd like to extract elements <code>[1, 4, 2]</code> and end up with</p> <pre><code>&lt;pyarrow.lib.Int64Array object at 0x7f6eb43c2d40&gt; [ 2, 5, 3 ] </code></pre> <p>as if I was doing NumPy-style indexing</p>
<python><pyarrow>
2024-09-11 08:07:12
1
11,062
ignoring_gravity
78,972,636
1,254,515
How to directly get the output of subprocess.check_output as valid json rather than reading the results stored in a file?
<p>I have a system command which produces json output: (<code>$ cmd -J &gt; file</code>). I can read this data perfectly well into a dict using:</p> <pre><code>with open(&quot;file&quot;, &quot;r&quot;) as i: data=json.loads(i) </code></pre> <p>I'd like to do the same thing without the intermediary file, directly generating the data via a subprocess call as:</p> <pre><code>data=subprocess.check_output([&quot;cmd&quot;, &quot;-J&quot;]).decode(&quot;utf-8&quot;) </code></pre> <p>or:</p> <pre><code>call=subprocess.call([&quot;cmd&quot;, &quot;-J&quot;], capture_output=True) data=call.output.decode(&quot;utf-8&quot;) </code></pre> <p>but <code>json.dumps(data)</code> does not produce a dict, there are <code>\\&quot;</code> and <code>\\n</code> characters everywhere. Calling replace to remove them does not improve the situation.</p> <p>How can I get the same dict as the one I got simply reading the command's output stored as a file on disk?</p>
<python><json><python-3.x><subprocess>
2024-09-11 07:58:25
1
323
Oliver Henriot
78,972,427
3,555,115
Extract float values from string in Python
<p>I have a line as below and I need to extra the float values for SW A_done: and SW B_done:.</p> <pre><code>line = SW A_done: 191168 SW B_done: 27720 </code></pre> <p>I tried line.split(' ' ), and then look for value after A_done: but it seems to show lot of null values when SW A_done value is 0 and is not always next value after A_done, B_done.</p> <pre><code>line.split(' ' ) : ['SW', 'A_done:', '', '', '', '', '', '', '', '', '', '0', 'SW', 'B_done:', '', '', '', '', '', '', '', '', '', '0'] After trying with line.split( ' ' ) </code></pre> <p>How can I extract the float values separately in above line ?</p>
<python>
2024-09-11 06:59:38
0
750
user3555115
78,972,393
3,405,291
Download location of Pytorch
<h1>Download fail</h1> <p>I'm running this Python code:</p> <p><a href="https://github.com/SimonGiebenhain/MonoNPHM/blob/05aafd8e7dbe3168bee7d5f93f47537acb877df3/scripts/preprocessing/run_facer.py#L153" rel="nofollow noreferrer">https://github.com/SimonGiebenhain/MonoNPHM/blob/05aafd8e7dbe3168bee7d5f93f47537acb877df3/scripts/preprocessing/run_facer.py#L153</a></p> <p>It fails at downloading a file and then throws the following errors:</p> <pre class="lang-py prettyprint-override"><code>failed downloading from https://github.com/FacePerceiver/facer/releases/download/models-v1/face_parsing.farl.celebm.main_ema_181500_jit.pt Traceback (most recent call last): File &quot;/home/arisa/MonoNPHM/scripts/preprocessing/run_facer.py&quot;, line 212, in &lt;module&gt; tyro.cli(main) File &quot;/home/arisa/.conda/envs/mononphm/lib/python3.9/site-packages/tyro/_cli.py&quot;, line 229, in cli return run_with_args_from_cli() File &quot;/home/arisa/MonoNPHM/scripts/preprocessing/run_facer.py&quot;, line 153, in main face_parser = facer.face_parser('farl/celebm/448', device=device) # optional &quot;farl/lapa/448&quot; File &quot;/home/arisa/.conda/envs/mononphm/lib/python3.9/site-packages/facer/__init__.py&quot;, line 36, in face_parser return FaRLFaceParser(conf_name, device=device, **kwargs).to(device) File &quot;/home/arisa/.conda/envs/mononphm/lib/python3.9/site-packages/facer/face_parsing/farl.py&quot;, line 69, in __init__ self.net = download_jit(model_path, map_location=device) File &quot;/home/arisa/.conda/envs/mononphm/lib/python3.9/site-packages/facer/util.py&quot;, line 162, in download_jit return torch.jit.load(cached_file, map_location=map_location, **kwargs) File &quot;/home/arisa/.conda/envs/mononphm/lib/python3.9/site-packages/torch/jit/_serialization.py&quot;, line 162, in load cpp_module = torch._C.import_ir_module(cu, str(f), map_location, _extra_files, _restore_shapes) # type: ignore[call-arg] RuntimeError: PytorchStreamReader failed reading zip archive: failed finding central directory </code></pre> <p>The corrupt download is the root cause of the last error:</p> <p><a href="https://stackoverflow.com/q/71617570/3405291">PytorchStreamReader failed reading zip archive: failed finding central directory</a></p> <blockquote> <p>RuntimeError: PytorchStreamReader failed reading zip archive: failed finding central directory</p> </blockquote> <h1>Manual download</h1> <p>I have downloaded the following manually:</p> <p><a href="https://github.com/FacePerceiver/facer/releases/download/models-v1/face_parsing.farl.celebm.main_ema_181500_jit.pt" rel="nofollow noreferrer">https://github.com/FacePerceiver/facer/releases/download/models-v1/face_parsing.farl.celebm.main_ema_181500_jit.pt</a></p> <p>But I'm not sure where to place it on the server so that the Python/Pytorch code would use it. Can anyone tell me the download location?</p>
<python><pytorch>
2024-09-11 06:52:07
1
8,185
Megidd
78,972,381
5,197,329
read nested json inside csv file using pandas?
<p>I have a csv file that with rows that looks like this:</p> <pre><code>745198;2024-09-10 10:09:10.7;leaf-2;{&quot;Accelerometer&quot;: {&quot;X&quot;: 0.055297852, &quot;Y&quot;: 0.993530273, &quot;Z&quot;: 0.000244141}} 745199;2024-09-10 10:09:10.71;leaf-2;{&quot;Accelerometer&quot;: {&quot;X&quot;: 0.056274414, &quot;Y&quot;: 0.994384766, &quot;Z&quot;: 0.000976563}} 745200;2024-09-10 10:09:10.721;leaf-2;{&quot;Accelerometer&quot;: {&quot;X&quot;: 0.055786133, &quot;Y&quot;: 0.994018555, &quot;Z&quot;: 0.000854492}} 745201;2024-09-10 10:09:10.732;leaf-2;{&quot;Accelerometer&quot;: {&quot;X&quot;: 0.055053711, &quot;Y&quot;: 0.993530273, &quot;Z&quot;: 0.000854492}} </code></pre> <p>and I would like to read this data into a dataframe, and somehow get the 3 accelerometer data into separate columns, but I haven't been able to figure out a good way of doing this. I have searched for similar cases <a href="https://stackoverflow.com/questions/38231591/split-explode-a-column-of-dictionaries-into-separate-columns-with-pandas">Split / Explode a column of dictionaries into separate columns with pandas</a> But none of the suggested solutions seems to work.</p> <p>I can create a for loop and manually extract the information I need line by line, but I'm guessing there should be a nice fast way of doing this that I just do not know of.</p>
<python><json><pandas><csv>
2024-09-11 06:49:41
2
546
Tue
78,972,238
4,851,073
Celery tasks with psycopg: ProgrammingError the last operation didn't produce a result
<p>I'm working on aproject in which I have</p> <ol> <li>A PostgreSQL 16.2 database</li> <li>A Python 3.12 backend using psycopg 3.2.1 and psycopg_pool 3.2.2.</li> <li>Celery for handling asynchronous tasks.</li> </ol> <p>The celery tasks uses the database pool through the following code:</p> <pre class="lang-py prettyprint-override"><code> import os from psycopg_pool import ConnectionPool from contextlib import contextmanager PG_USERNAME = os.getenv('PG_USERNAME') if not PG_USERNAME: raise ValueError(f&quot;Invalid postgres username&quot;) PG_PASSWORD = os.getenv('PG_PASSWORD') if not PG_PASSWORD: raise ValueError(f&quot;Invalid postgres pass&quot;) PG_HOST = os.getenv('PG_HOST') if not PG_HOST: raise ValueError(f&quot;Invalid postgres host&quot;) PG_PORT = os.getenv('PG_PORT') if not PG_PORT: raise ValueError(f&quot;Invalid postgres port&quot;) # Options used to prevent closed connections # conn_options = f&quot;-c statement_timeout=1800000 -c tcp_keepalives_idle=30 -c tcp_keepalives_interval=30&quot; conninfo = f'host={PG_HOST} port={PG_PORT} dbname=postgres user={PG_USERNAME} password={PG_PASSWORD}' connection_pool = ConnectionPool( min_size=4, max_size=100, conninfo=conninfo, check=ConnectionPool.check_connection, #options=conn_options, ) @contextmanager def get_db_conn(): conn = connection_pool.getconn() try: yield conn finally: connection_pool.putconn(conn) </code></pre> <p>And an example celery task would be</p> <pre class="lang-py prettyprint-override"><code>@app.task(bind=True) def example_task(self, id): with get_db_conn() as conn: try: with conn.cursor(row_factory=dict_row) as cursor: test = None cursor.execute('SELECT * FROM test WHERE id = %s', (id,)) try: test = cursor.fetchone() except psycopg.errors.ProgrammingError: logger.warning(f'Test log msg') conn.rollback() return cursor.execute(&quot;UPDATE test SET status = 'running' WHERE id = %s&quot;, (id,)) conn.commit() # Some processing... # Fetch another resource needed cursor.execute('SELECT * FROM test WHERE id = %s', (test['resource_id'],)) cursor.fetchone() # Update the entry with the result cursor.execute(&quot;&quot;&quot; UPDATE test SET status = 'done', properties = %s WHERE id = %s &quot;&quot;&quot;, (Jsonb(properties), id)) conn.commit() except Exception as e: logger.exception(f'Error: {e}') conn.rollback() with conn.cursor(row_factory=dict_row) as cursor: # Update status to error with exception information cursor.execute(&quot;&quot;&quot; UPDATE test SET status = 'error', error = %s WHERE id = %s &quot;&quot;&quot;, (Jsonb({'error': str(e), 'stacktrace': traceback.format_exc()}), webpage_id)) conn.commit() </code></pre> <p>The code works most of the times, but sometimes, when multiple tasks of the same type are being launched, I'm getting some errors of type <code>psycopg.ProgrammingError: the last operation didn't produce a result</code> on the second fetchone() call.</p> <p>Meanwhile, on the database I can see the following warning <code>WARNING: there is already a transaction in progress</code></p> <p>I suspect there might be some problems with the way I'm working with connections, but I cannot find were.</p> <p>As far as I know, once get_db_conn() is called that connection is not available for other tasks, so in theory there cannot be multiple tasks using the same connection, and therefore there should be no transaction already in progress when performing the second fetchone() call.</p> <p>The resource exists, as every other task can access it, so that's not the problem.</p>
<python><postgresql><celery><psycopg3>
2024-09-11 06:01:38
1
810
Javierd98
78,972,160
604,128
Flask routing and connexion
<p>I have a flask application where I would like to add Connexion to validate my api endpoints. All api is bundled in a blueprint.</p> <p>My issue is that Connexion wants to control the routing. Either via connectionid in the OpenApi spec, which I find leaks implementation detail into a specification, or via a class system of automatic routing.</p> <p>How can i use normal flask routing via decorators together with Connexion?</p> <p>The following code fails with 500 Internal error. It works if I uncomment operationId in the OpenAPI spec</p> <p>This is cxtst.py</p> <pre><code>from flask import jsonify from connexion import FlaskApp app = FlaskApp(__name__) app.add_api('cxtst.yaml') @app.route('/test') def test_fn(): return jsonify({'output_string': &quot;WORKS&quot;}) if __name__ == '__main__': app.run(host='0.0.0.0', port=5000) </code></pre> <p>This is cxtst.yaml</p> <pre><code># cxtst.yaml openapi: 3.0.3 info: title: Demonstration of routing in Connexion license: name: MIT License url: https://github.com/Buildasaurus/Factorio-Blueprint-Generator/blob/main/LICENSE version: 0.0.1 paths: /test: get: summary: Test that I have access to server #operationId: cxtst.test_fn responses: '200': description: Success content: application/json: schema: type: object properties: output_string: type: string </code></pre>
<python><flask><connexion>
2024-09-11 05:29:24
1
512
Peer Sommerlund
78,972,135
1,795,641
How to access key and value from redis using RedisJSON module in python
<p>I have records stored like below in the Redis.</p> <pre><code>β€˜monitor':{'105894288': {'status': 'Screen', 'release': '23.4.5'}, '106521147': {'status': 'Screen', 'release': '23.4.5'}, '106521148': {'status': 'Screen', 'release': '23.4.5'}, '106521149': {'status': 'Screen', 'release': '23.4.6'} } </code></pre> <p>Here, monitor is the root key and numbers are ids. I would like to retrieve whole record including the ids using RedisJSON query in python. How to retrieve it? The example answer for release <code>23.4.6</code> is <code>'106521149': {'status': 'Screen', 'release': '23.4.6’}</code></p>
<python><redis><redisjson>
2024-09-11 05:16:47
1
856
smm
78,972,060
24,758,287
How to extract values based on column names and put it in another column in polars?
<p>I would like to fill a value in a column based on another columns' name, in the Polars library from python (I obtained the following DF by exploding my variables' column names):</p> <p>Input:</p> <pre class="lang-py prettyprint-override"><code>df = pl.from_repr(&quot;&quot;&quot; β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ Name ┆ Average ┆ Median ┆ Q1 ┆ Variable β”‚ β”‚ --- ┆ --- ┆ --- ┆ --- ┆ --- β”‚ β”‚ str ┆ i64 ┆ i64 ┆ i64 ┆ str β”‚ β•žβ•β•β•β•β•β•β•β•β•ͺ═════════β•ͺ════════β•ͺ═════β•ͺ══════════║ β”‚ Apple ┆ 2 ┆ 3 ┆ 4 ┆ Average β”‚ β”‚ Apple ┆ 2 ┆ 3 ┆ 4 ┆ Median β”‚ β”‚ Apple ┆ 2 ┆ 3 ┆ 4 ┆ Q1 β”‚ β”‚ Banana ┆ 1 ┆ 5 ┆ 10 ┆ Average β”‚ β”‚ Banana ┆ 1 ┆ 5 ┆ 10 ┆ Median β”‚ β”‚ Banana ┆ 1 ┆ 5 ┆ 10 ┆ Q1 β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ &quot;&quot;&quot;) </code></pre> <p>Expected output:</p> <pre><code>shape: (6, 6) β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β” β”‚ Name ┆ Average ┆ Median ┆ Q1 ┆ Variable ┆ value β”‚ β”‚ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- β”‚ β”‚ str ┆ i64 ┆ i64 ┆ i64 ┆ str ┆ i64 β”‚ β•žβ•β•β•β•β•β•β•β•β•ͺ═════════β•ͺ════════β•ͺ═════β•ͺ══════════β•ͺ═══════║ β”‚ Apple ┆ 2 ┆ 3 ┆ 4 ┆ Average ┆ 2 β”‚ β”‚ Apple ┆ 2 ┆ 3 ┆ 4 ┆ Median ┆ 3 β”‚ β”‚ Apple ┆ 2 ┆ 3 ┆ 4 ┆ Q1 ┆ 4 β”‚ β”‚ Banana ┆ 1 ┆ 5 ┆ 10 ┆ Average ┆ 1 β”‚ β”‚ Banana ┆ 1 ┆ 5 ┆ 10 ┆ Median ┆ 5 β”‚ β”‚ Banana ┆ 1 ┆ 5 ┆ 10 ┆ Q1 ┆ 10 β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”˜ </code></pre> <p>I have tried:</p> <pre class="lang-py prettyprint-override"><code>df = df.with_columns(value = pl.col(f&quot;{pl.col.variable}&quot;)) </code></pre> <p>But that does not work because polars perceives the argument as a function (?). Does anyone know how to do this?</p> <p>Note: I have also tried to transpose the dataframe, which, not only was that computationally expensive, also did not work! Because it would transpose the DF into a 5-rows-long DF. What I need is a (Name * Number of Variables)-rows-long DF.</p> <p>That is, for example, I have 3 different names (say, Apple, Banana, and Dragonfruit), and I have 3 variables (Average, Median, Q1), then my DF should be 9-rows-long!</p>
<python><python-polars><exploded>
2024-09-11 04:30:00
5
301
user24758287
78,972,018
15,412,256
Polars Replacing Values of Other groups to the Values of a Certain Group
<p>I have the following <code>Polars.DataFrame</code>:</p> <pre class="lang-py prettyprint-override"><code>df = pl.DataFrame( { &quot;timestamp&quot;: [1, 2, 3, 1, 2, 3], &quot;var1&quot;: [1, 2, 3, 3, 4, 5], &quot;group&quot;: [&quot;a&quot;, &quot;a&quot;, &quot;a&quot;, &quot;b&quot;, &quot;b&quot;, &quot;b&quot;], } ) print(df) out: shape: (6, 3) β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β” β”‚ timestamp ┆ var1 ┆ group β”‚ β”‚ --- ┆ --- ┆ --- β”‚ β”‚ i64 ┆ i64 ┆ str β”‚ β•žβ•β•β•β•β•β•β•β•β•β•β•β•ͺ══════β•ͺ═══════║ β”‚ 1 ┆ 1 ┆ a β”‚ β”‚ 2 ┆ 2 ┆ a β”‚ β”‚ 3 ┆ 3 ┆ a β”‚ β”‚ 1 ┆ 3 ┆ b β”‚ β”‚ 2 ┆ 4 ┆ b β”‚ β”‚ 3 ┆ 5 ┆ b β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”˜ </code></pre> <p>I want to replace the values of group <code>b</code> with the values of group <code>a</code> that are having the same timestamps.</p> <p>Desired output:</p> <pre class="lang-py prettyprint-override"><code>shape: (6, 3) β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β” β”‚ timestamp ┆ var1 ┆ group β”‚ β”‚ --- ┆ --- ┆ --- β”‚ β”‚ i64 ┆ i64 ┆ str β”‚ β•žβ•β•β•β•β•β•β•β•β•β•β•β•ͺ══════β•ͺ═══════║ β”‚ 1 ┆ 1 ┆ a β”‚ β”‚ 2 ┆ 2 ┆ a β”‚ β”‚ 3 ┆ 3 ┆ a β”‚ β”‚ 1 ┆ 1 ┆ b β”‚ β”‚ 2 ┆ 2 ┆ b β”‚ β”‚ 3 ┆ 3 ┆ b β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”˜ </code></pre> <p>I have the current solution with generating a helper df:</p> <pre class="lang-py prettyprint-override"><code>def group_value_replacer( df: pl.DataFrame, target_group_col: str, target_var: str, target_group: str, ): helper_df = df.filter(pl.col(target_group_col) == target_group) df = df.drop(target_var).join( helper_df.drop(target_group_col), on=[&quot;timestamp&quot;], how=&quot;left&quot;, ) return df group_value_replacer(df, &quot;group&quot;, &quot;var1&quot;, &quot;a&quot;) out: shape: (6, 3) β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β” β”‚ timestamp ┆ group ┆ var1 β”‚ β”‚ --- ┆ --- ┆ --- β”‚ β”‚ i64 ┆ str ┆ i64 β”‚ β•žβ•β•β•β•β•β•β•β•β•β•β•β•ͺ═══════β•ͺ══════║ β”‚ 1 ┆ a ┆ 1 β”‚ β”‚ 2 ┆ a ┆ 2 β”‚ β”‚ 3 ┆ a ┆ 3 β”‚ β”‚ 1 ┆ b ┆ 1 β”‚ β”‚ 2 ┆ b ┆ 2 β”‚ β”‚ 3 ┆ b ┆ 3 β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”˜ </code></pre> <p>I want to improve the solution by using <code>Polars.Expr</code>: For example, is there a way for me to achieve the same operation using expressions like <code>df.with_columns(pl.col(target_var).operationxx)</code>.</p>
<python><python-polars>
2024-09-11 04:03:03
2
649
Kevin Li
78,971,821
5,957,353
Different Starting Indices for Iterating over Large Files
<p>I want to begin by saying I have NOT programmed in many, many years, so sorry if this is a somewhat trivial question. My interest has been mathematics for the last couple of years</p> <p>Here's my code:</p> <pre><code>lastStop = False with open('K3.txt','r') as K3: with open('K4.txt','a') as K4: for tri0 in K3: tri = tri0.split(',') c=tri[2][:-1] c=int(c) a=tri[0] b=tri[1] a=int(a) b=int(b) for d in range(c+1,6821): if lastStop: if [adjMat[a][d],adjMat[b][d],adjMat[c][d]]==['1','1','1']: K4.write(str(a)+','+str(b)+','+str(c)+','+str(d)+'\n') elif str(a)+','+str(b)+','+str(c)+','+str(d)+'\n'=='670,3016,3426,5603\n': lastStop=True </code></pre> <p>In this, I'm iterating over the lines of a very large file (K3.txt), doing some processing, and then writing to K4.txt. But, because it takes so long, I ran it over night last night. Because of that, I didn't get all the way through it, and the last line that I wrote to K4 was <code>'670,3016,3426,5603\n'</code></p> <p>I'm planning on running this again tonight, wanting to start right after I get to the (a,b,c,d)=670,3016,3426,5603 point in the for loops, and my solution here doesn't feel elegant. I set a boolean &quot;lastStop&quot; to False, and then, once I get to that (a,b,c,d) value, I turn it to true so it starts running that first part of the if/elif statement</p> <p>I'm sure I'm losing a lot of time by having to go through all values up until that point</p> <p>I'm thinking there surely must be a way to start the &quot;for tri0 in K3:&quot; for loop at (a,b,c)=(670,3016,3426) point, but I'm not sure how to do that without looping over the row numbers, and Pythonista for some reason interprets K3 as a list sometimes and not a list other times</p> <p>For example, the a=tri[0] followed immediately by a=int(a) is because, for some reason, when I write &quot;a=int(tri[0])&quot;, Pythonista throws me an error along the lines of &quot;Object 'type' cannot be subindexed&quot; (if you want the exact error, I can find out)</p> <p>I hope this made sense; thank you</p>
<python><for-loop><large-files><pythonista>
2024-09-11 02:07:34
1
791
wyboo
78,971,796
3,325,401
How to use Hatch to run Python CLI
<p>I'm trying to work through a pretty basic &quot;hello world&quot; type of example to setup a Python CLI using the Hatch build system (which I understand uses the Click library under the hood).</p> <p>I've got a minimally reproducible example below, and the error I'm running into appears below the following code snippet.</p> <pre><code>python -m venv .venv source .venv/bin/activate pip install hatch hatch new &quot;new cli&quot; --cli cd new-cli hatch build hatch run new-cli </code></pre> <p>And then I get the following error:</p> <pre><code>/bin/sh: new-cli: command not found </code></pre> <p>I've got the following defined in the pyproject.toml file that gets auto-generated by Hatch.</p> <pre><code>[tool.hatch.envs.default.scripts] new-cli = &quot;new_cli.cli:new_cli&quot; </code></pre> <p>I feel like I'm overlooking some very basic here, but I can't seem to figure out what it is. I've tried running <code>hatch shell</code> prior to the <code>hatch run new-cli</code>, but nothing seems to work.</p>
<python><command-line-interface><hatch>
2024-09-11 01:50:23
1
2,767
hobscrk777
78,971,681
3,486,684
How can I import Polars type definitions like `JoinStrategy`?
<p><code>JoinStrategy</code> is an input to <code>join</code>: <a href="https://docs.pola.rs/api/python/stable/reference/dataframe/api/polars.DataFrame.join.html" rel="nofollow noreferrer">https://docs.pola.rs/api/python/stable/reference/dataframe/api/polars.DataFrame.join.html</a></p> <p>My static type checking tool seems to be able to get a hold of <code>JoinStrategy</code>, but I'm not sure how/from where.</p> <p><a href="https://i.sstatic.net/53N6JmhH.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/53N6JmhH.png" alt="enter image description here" /></a></p> <p>Usually, type stub packages are available on PyPI, but nothing obvious stands out in this case: <a href="https://pypi.org/user/ritchie46/" rel="nofollow noreferrer">https://pypi.org/user/ritchie46/</a></p> <p>How do I import <code>JoinStrategy</code> (or other type definitions provided by Polars) for my own use?</p>
<python><python-polars>
2024-09-11 00:23:31
1
4,654
bzm3r
78,971,666
2,612,259
Why does Pylance not complain about missing members of a Protocol?
<p>I am using Pylance with vscode and have set the type checking mode to 'strict'</p> <p>My understanding is that Pylance should flag Bar as not conforming to the Foo Protocol because of the commented foo method in Bar, but it does not.</p> <p>I if uncomment the line it does correctly complain that 'Method &quot;foo&quot; overrides class &quot;Foo&quot; in an incompatible manner'</p> <p>Is there something I am missing?</p> <pre class="lang-py prettyprint-override"><code>from typing import Protocol class Foo(Protocol): def foo(self, a: str): ... class Bar(Foo): # def foo(self, b: str): ... ... # The above code generates no errors, however the following line does a: Foo = Bar() # this generates a 'Cannot instantiate abstract class &quot;Bar&quot;' error in pylance # but the file does run cleanly </code></pre> <p>The bottom line here is all I want to do is say that Bar implements Foo and have Pylance tell me if it does not, before I let someone try to create an instance of it.</p> <p>I am subclassing Foo for 2 reasons.</p> <ol> <li>I want to document that Bar implements the Foo protocol</li> <li>I want to type check Bar where it is defined rather than when it is instantiated.</li> </ol> <p>I am basing this on part of mypy documentation found <a href="https://mypy.readthedocs.io/en/stable/protocols.html" rel="nofollow noreferrer">here</a></p> <p>As I said above, this works fine and flags incorrect method signatures right here in the file defining the Bar class. The only thing it does not do is flag the missing method. For that I can add something like the following:</p> <p>bar: Foo = Bar()</p> <p>This will highlight the missing method (because the Protocol makes Bar abstract), however it seems hacky to include this in the file defining Bar and also gets complicated if Bar has an <code>__init__</code> function that takes several argument.</p> <p>portion of mypy documentation linked above:</p> <p><a href="https://i.sstatic.net/p4MjeYfg.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/p4MjeYfg.jpg" alt="enter image description here" /></a></p>
<python><python-typing><pyright>
2024-09-11 00:11:31
2
16,822
nPn
78,971,520
8,652,920
How to disconnect from socket after connecting using socket.socket.connect_ex?
<p>I was following the instructions from this answer on how to check network ports in python: <a href="https://stackoverflow.com/a/19196218/8652920">https://stackoverflow.com/a/19196218/8652920</a></p> <p>for posterity I'll just repost it</p> <pre class="lang-py prettyprint-override"><code>import socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) result = sock.connect_ex(('127.0.0.1',80)) if result == 0: print &quot;Port is open&quot; else: print &quot;Port is not open&quot; sock.close() </code></pre> <p>This works but it only works once.</p> <pre class="lang-py prettyprint-override"><code>Python 3.12.5 (main, Aug 6 2024, 19:08:49) [Clang 15.0.0 (clang-1500.1.0.2.5)] on darwin Type &quot;help&quot;, &quot;copyright&quot;, &quot;credits&quot; or &quot;license&quot; for more information. &gt;&gt;&gt; import socket &gt;&gt;&gt; sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) &gt;&gt;&gt; result = sock.connect_ex(('host', 22)) &gt;&gt;&gt; result 0 &gt;&gt;&gt; result = sock.connect_ex(('host', 22)) &gt;&gt;&gt; result 56 </code></pre> <p>see that we get the error code 56, which from this question <a href="https://stackoverflow.com/q/23228568/8652920">[Errno 56]: Socket already connected fix?</a> I can infer that it means the socket is already connected.</p> <p>Now, I want to keep connecting and disconnecting to my host so that the result code is always 0. How do I do that?</p> <p><code>sock.close</code> does not work by the way. see, continued:</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; sock.close() &gt;&gt;&gt; result = sock.connect_ex(('host', 22)) &gt;&gt;&gt; result 9 </code></pre> <p>So, my question is how to keep trying the connection with <code>connect_ex</code> repeatedly and get response code 0 each time. If the socket is already connected and stays connected after resolution of <code>connect_ex</code>, then how do we disconnect?</p>
<python><python-3.x><sockets><port>
2024-09-10 22:37:24
0
4,239
notacorn
78,971,477
14,684,366
Transform a list of dictionaries, based on key list
<p>In Python 3.9, I have a list of dictionaries:</p> <pre><code>variables = [ {'id': ['alpha'], 'ip': '10.10.10.10', 'name': 'primary'}, {'id': ['beta', 'gamma'], 'ip': '10.10.10.20', 'name': 'secondary'} ] </code></pre> <p>My goal is to transform it into this dictionary format:</p> <pre><code>result = { 'alpha.ip': '10.10.10.10', 'alpha.name': 'primary', 'beta.ip': '10.10.10.20', 'beta.name': 'secondary', 'gamma.ip': '10.10.10.20', 'gamma.name': 'secondary' } </code></pre> <p>I have a difficult time drafting the <code>id</code> loop logic, which will produce the correct result.</p>
<python><dictionary>
2024-09-10 22:15:31
2
591
Floren
78,971,452
10,471,715
Why Do Two Similar Code Snippets Yield Different Results for Symbolic Equations?
<p>I am calculating (what seems to me) the same thing in two ways but am getting different results. I'd appreciate any help in understanding the reason behind this.</p> <p>I have a list of symbolic equations, each defined as:</p> <p>a<sub>1</sub> * x<sub>1</sub> + a<sub>2</sub> * x<sub>2</sub> + ... + a<sub>30</sub> * x<sub>30</sub> = b</p> <pre class="lang-py prettyprint-override"><code>eqs=[] # expressions reps={} # values of symbols in the expressions b=[] # numeric value that the known expression has for i,e in enumerate(eqs): A = (e-b[i]).subs(reps) B = e.subs(reps)-b[i] if A != B: print (A, B) </code></pre> <p>These are giving different results for A and B:</p> <p><a href="https://i.sstatic.net/V0JBGozt.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/V0JBGozt.jpg" alt="enter image description here" /></a></p>
<python><math><sympy><symlink><equation-solving>
2024-09-10 21:59:56
1
504
Hamid Reza
78,971,412
7,700,802
How to measure new change in data
<p>Suppose you have this dataframe</p> <pre><code>d = {'date':['2019-08-25', '2019-09-01', '2019-09-08'], 'data':[31, 31, 31]} df_sample = pd.DataFrame(data=d) df_sample.head() </code></pre> <p>and you want to measure how much new data comes in on average each week. For example, we had 31 new rows on 8/25 and then on 9/1 we got an additional 31 rows so thats like a 100% increase. What I want to know is on average from one week to the next how much new data comes in?</p> <p>I know there is diff() and pct_change() but since this will just be 0 in these 3 samples I am wondering what would be the better approach here.</p>
<python><pandas>
2024-09-10 21:40:12
1
480
Wolfy
78,971,305
3,050,730
How can I optimize the performance of this numpy function
<p>Is there any way optimizing the performance speed of this function?</p> <pre class="lang-py prettyprint-override"><code>def func(X): n, p = X.shape R = np.eye(p) delta = 0.0 for i in range(100): delta_old = delta Y = X @ R alpha = 1. / n Y2 = Y**2 Y3 = Y2 * Y W = np.sum(Y2, axis=0) transformed = X.T @ (Y3 - (alpha * Y * W)) U, svals, VT = np.linalg.svd(transformed, full_matrices=False) R = U @ VT # is used as a stopping criterion delta = np.sum(svals) return R </code></pre> <p>Naively, I thought using <code>numba</code> would help because of the loop (the actual number of loops is higher),</p> <pre class="lang-py prettyprint-override"><code>from numba import jit @jit(nopython=True, parallel=True) def func_numba(X): n, p = X.shape R = np.eye(p) delta = 0.0 for i in range(100): delta_old = delta Y = X @ R alpha = 1. / n Y2 = Y**2 Y3 = Y2 * Y W = np.sum(Y2, axis=0) transformed = X.T @ (Y3 - (alpha * Y * W)) U, svals, VT = np.linalg.svd(transformed, full_matrices=False) R = U @ VT delta = np.sum(svals) # is used as a stopping criterion return R </code></pre> <p>but to my surprise the numbaized function is actually slower. Why is numba not more effective in this case? Is there another option for me (preferably using numpy)?</p> <p>Note: You can assume <code>X</code> to be a &quot;tall-and-skinny&quot; matrix.</p> <h3>MWE</h3> <pre class="lang-py prettyprint-override"><code>import numpy as np size = (10_000, 15) X = np.random.normal(size=size) %timeit func(X) # 1.28 s %timeit func_numba(X) # 2.05 s </code></pre>
<python><numpy><performance><optimization><numba>
2024-09-10 20:49:57
1
523
nicrie
78,971,143
51,816
How to draw grid planes uniformly using matplotlib?
<p>Basically I have this code:</p> <pre><code>import matplotlib.pyplot as plt import numpy as np from itertools import product, combinations fig = plt.figure() ax = fig.add_subplot(1,1,1,projection='3d') </code></pre> <p>but that gets me this result:</p> <p><a href="https://i.sstatic.net/bZtvGNeU.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/bZtvGNeU.png" alt="enter image description here" /></a></p> <p>whereas I want something like this (without the 3d cube):</p> <p><a href="https://i.sstatic.net/AJoMDqr8.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/AJoMDqr8.png" alt="enter image description here" /></a></p> <p>In my picture you can see the grid plane lines are too close to each other at the plane intersections. I want them to positioned uniformly starting at the 3d grid origin.</p>
<python><matplotlib><matplotlib-3d>
2024-09-10 19:57:12
1
333,709
Joan Venge
78,970,926
850,781
Multi-dimensional scipy.optimize.LinearConstraint?
<p>My linear constraint for <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize.html" rel="nofollow noreferrer"><code>scipy.optimize.minimize</code></a> is</p> <pre><code>ones = np.ones_like(x) np.outer(x, ones) - np.outer(ones, x) &gt; something </code></pre> <p>where <code>something</code> is a given matrix. (Mathematically, <code>a_ij &lt; x_i - x_j &lt; a_ji</code>).</p> <p>How do I express this in terms of <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.LinearConstraint.html" rel="nofollow noreferrer"><code>scipy.optimize.LinearConstraint</code></a> which wouldn't accept a 3d &quot;matrix&quot; as a 1st argument?</p>
<python><numpy><scipy><scipy-optimize>
2024-09-10 18:52:40
2
60,468
sds
78,970,691
22,407,544
Is it possible to pause celery tasks during execution
<p>I have an app that does transcription. I want that if the user tries to reload they are alerted that reloading will stop their task from completing. I tried to use it with <code>unload</code> but it didn't work most of the time and I know that it is inconsistent. I would like to pause the task if the user tries to reload. They will get the browser warning alert and if they decide that they still want to reload the task will be terminated.</p> <p>The idea I have is to trigger a <code>beforeunload</code> which will give them a warning and trigger the pausing of the celery task. I have a polling function on the frontend set up using JS that polls if the task is still running every 5 seconds. If the user reloads this polling function will stop running and so the backend will stop being polled which will trigger the celery task termination.</p> <p>Otherwise, the function will receive the poll if the user cancels or hasn't reloaded and the task is unpaused.</p> <p>Here is my polling function:</p> <pre><code>function pollTaskStatus(taskId) { currentTaskId = taskId; console.log(currentTaskId) pollInterval = setInterval(() =&gt; { const xhr = new XMLHttpRequest(); xhr.onload = function() { if (xhr.status == 200) { const response = JSON.parse(xhr.responseText); if (response.status === 'completed') { console.log('completed'); if (response.reload) { // Reload the page to load the correct HTML template window.location.reload(); } clearInterval(pollInterval); // Stop polling once completed isTranscribing = false; // Set to false when transcription is complete } } else { showError('An error occurred.'); clearInterval(pollInterval); // Stop polling on error isTranscribing = false; // Set to false on errors } }; xhr.onerror = function() { showError('Connection error. Please check your network connection and try again.'); clearInterval(pollInterval); // Stop polling on network error isTranscribing = false; // Set to false on network error }; xhr.open('GET', `/transcribe/poll_task_status/${taskId}/`, true); xhr.send(); }, 5000); // Poll every 5 seconds } </code></pre> <p>views.py:</p> <pre><code>if request.method == 'POST': if not file_name or not file_path: return redirect(reverse('transcribeSubmit')) else: try: if transcribed_doc.state == 'not_started': transcribed_doc.state = 'in_progress' transcribed_doc.save() audio_language = request.POST.get('audio_language') output_file_type = request.POST.get('output_file_type') task = transcribe_file_task.delay(file_path, audio_language, output_file_type, 'ai_transcribe_output', session_id) </code></pre> <p>task.py:</p> <pre><code>@shared_task def transcribe_file_task(path, audio_language, output_file_type, dest_dir, session_id): # Step 1: Local output directory and file path local_output_dir = '/tmp/' # Local directory for temporary storage output_dir = os.path.join(settings.MEDIA_URL, dest_dir) filename = os.path.splitext(os.path.basename(path))[0] local_output_file_path = os.path.join(local_output_dir, f&quot;{filename}.{output_file_type}&quot;) output_file_path = os.path.join(settings.MEDIA_URL, dest_dir, f&quot;{filename}.{output_file_type}&quot;) transcribed_doc = TranscribedDocument.objects.get(id=session_id) try: if audio_language == 'detect': model = load_model audio =load_audio(path) result = transcribe(audio, verbose=False) writer = get_writer(output_file_type, local_output_dir) writer(result, path) # Code to store audio and transcript except Exception as e: error_message = f&quot;An error occurred: {e}&quot; </code></pre> <p>I'm also open to any better ideas for dealing with potential customer reload during a running task. My backend is django and I am running celery[redis].</p>
<javascript><python><django><celery>
2024-09-10 17:40:39
0
359
tthheemmaannii
78,970,689
3,417,179
Gekko : Error in Resource Optimisation problem
<p>I am working on a optimisation problem and I am using Gekko to solve it. Consider the scenario where there are 2 machines and 5 users and each machines has 2 resources to distribute to users. The user gain some points based on the number of resource allocated. Also there are certain demands from the user before resource is allocated. My objective is two fold, I want to maximise a combination of total gain and fairness of the system.</p> <p>Fairness of user is defined as total gain divided by demand. I have two decision variable, one is allocation matrix between machines and user &amp; other is weights vector for users. The resources are allocated in proportional to the weights of user. (The two decision variables are compulsory in the problem I am working on)</p> <p>Following is the code i have worked upon:</p> <pre><code>import numpy as np from gekko import GEKKO def allocation(rewards, num_machines, num_users, num_resources, C1, C2, demands, cumulative_gain): m = GEKKO(remote=False) # Decision variables link = m.Array(m.Var, (num_machines, num_users), lb=0, ub=1, integer=True) weights = m.Array(m.Var, num_users, lb=0.1, ub=1) # Constraints for u in range(num_users): m.Equation(m.sum(link[:, u]) &lt;= 1) # each user is assigned to only 1 machine for b in range(num_machines): m.Equation(m.sum(link[b, :] * weights) &lt;= 1) # sum of weights of users allocated to each machine should be 1 # Compute Fairness fairness, reward = compute_fairness(link, weights, rewards, demands, cumulative_gain, num_resources, m) # Objective m.Maximize(C1 * reward + C2 * fairness) m.options.SOLVER = 1 # Change solver (1=APOPT, 3=IPOPT) m.open_folder() m.solve(disp=True) optimized_weights = np.array([weight.value[0] for weight in weights]) optimized_link = np.ndarray((num_machines, num_users)) for i in range(link.shape[0]): for j in range(link.shape[1]): optimized_link[i][j] = link[i][j][0] return optimized_link, optimized_weights, m def compute_fairness(link, weights, rewards, demands, cumulative_gain, num_resources, m): &quot;&quot;&quot; Computes the fairness of the system based on the resources allocated to users using GEKKO-compatible logic. &quot;&quot;&quot; num_machines = link.shape[0] num_users = link.shape[1] total_gain_u = [] user_fairness = [] total_machine_weight = [] for b in range(num_machines): total_machine_weight.append(m.Intermediate(m.sum([link[b][u_] * weights[u_] for u_ in range(num_users)]))) # Compute fairness for each user for u in range(num_users): total_gain_u.append(m.Intermediate(cumulative_gain[u])) # Use GEKKO's Intermediate for cumulative gain # Loop over machines and calculate gain for user u for b in range(num_machines): # GEKKO constraint-compatible check if user u is connected to machine b link_value = link[b][u] # Use GEKKO's if3 function to avoid direct Python conditional checks resources_allocated_to_u_b = m.if3(total_machine_weight[b] &gt; 0, (weights[u] / total_machine_weight[b]) * num_resources, 0) # Add the gain from machine b to user u, conditioned on the link value total_gain_u[u] += link_value * resources_allocated_to_u_b * rewards[b, u] # Fairness is calculated based on total gain divided by demand fairness_u = m.Intermediate(total_gain_u[u] / demands[u]) if demands[u] &gt; 0 else 0 user_fairness.append(fairness_u) # Compute fairness for each machine using the geometric mean of users it serves machine_fairness = [] for b in range(num_machines): connected_user_fairness = [] for u in range(num_users): connected_fairness = m.Intermediate(link[b][u] * user_fairness[u]) connected_user_fairness.append(connected_fairness) if connected_user_fairness: product = m.Intermediate(1) for fairness in connected_user_fairness: product *= fairness fairness_machine = m.Intermediate(product ** (1 / len(connected_user_fairness))) machine_fairness.append(fairness_machine) # Compute total system fairness using the geometric mean of the fairness of all machines if machine_fairness: product1 = m.Intermediate(1) for fairness in machine_fairness: product1 *= fairness total_fairness = m.Intermediate(product1 ** (1 / len(machine_fairness))) else: total_fairness = 0 total_rewards = m.Var(lb=0) # Create GEKKO variable for total rewards for u in range(num_users): # Allocate resources to user u based on its weight relative to the total weight resources_allocated_to_u_b = m.if3(total_machine_weight[b] &gt; 0, (weights[u] / total_machine_weight[b]) * num_resources, 0) # Calculate reward for user u based on resources allocated reward_contribution = link[b][u] * resources_allocated_to_u_b * rewards[b, u] total_rewards += reward_contribution return total_fairness, total_rewards # Test setup num_machines = 2 num_users = 5 num_resources = 2 demands = [100, 100, 100, 100, 100] cumulative_gain = [0, 0, 0, 0, 0] sinr_matrix = np.random.randint(1, num_machines * num_users, size=(num_machines, num_users)) C1 = 1 C2 = 1 print('Demands:', demands) print('Cumulative Gain:', cumulative_gain) link, weights, m = allocation(sinr_matrix, num_machines, num_users, num_resources, C1, C2, demands, cumulative_gain) print('Link Matrix:', link) print('Weights:', weights) </code></pre> <p>But i am getting following error:</p> <pre><code> ---------------------------------------------------------------- APMonitor, Version 1.0.1 APMonitor Optimization Suite ---------------------------------------------------------------- --------- APM Model Size ------------ Each time step contains Objects : 2 Constants : 0 Variables : 110 Intermediates: 28 Connections : 12 Equations : 106 Residuals : 78 @error: Model Expression *** Error in syntax of function string: Invalid element: i280&gt;0 Position: 20 0-((((1-int_v28))*(i280&gt;0)))-slk_18 ? --------------------------------------------------------------------------- Exception Traceback (most recent call last) Cell In[50], line 120 117 print('Demands:', demands) 118 print('Cumulative Gain:', cumulative_gain) --&gt; 120 link, weights, m = allocation(rewards, num_machines, num_users, num_resources, C1, C2, demands, cumulative_gain) 122 print('Link Matrix:', link) 123 print('Weights:', weights) Cell In[50], line 27, in allocation(rewards, num_machines, num_users, num_resources, C1, C2, demands, cumulative_gain) 25 m.options.SOLVER = 1 # Change solver (1=APOPT, 3=IPOPT) 26 m.open_folder() ---&gt; 27 m.solve(disp=True) 29 optimized_weights = np.array([weight.value[0] for weight in weights]) 30 optimized_link = np.ndarray((num_machines, num_users)) File ~/anaconda3/lib/python3.11/site-packages/gekko/gekko.py:2140, in GEKKO.solve(self, disp, debug, GUI, **kwargs) 2138 print(&quot;Error:&quot;, errs) 2139 if (debug &gt;= 1) and record_error: -&gt; 2140 raise Exception(apm_error) 2142 else: #solve on APM server 2143 def send_if_exists(extension): Exception: @error: Model Expression *** Error in syntax of function string: Invalid element: i280&gt;0 Position: 20 0-((((1-int_v28))*(i280&gt;0)))-slk_18 </code></pre> <p>I tried looking at the .apm file but couldnt track the issue. Following is the .apm file</p> <pre><code>Model Variables int_v1 = 0, &lt;= 1, &gt;= 0 int_v2 = 0, &lt;= 1, &gt;= 0 int_v3 = 0, &lt;= 1, &gt;= 0 int_v4 = 0, &lt;= 1, &gt;= 0 int_v5 = 0, &lt;= 1, &gt;= 0 int_v6 = 0, &lt;= 1, &gt;= 0 int_v7 = 0, &lt;= 1, &gt;= 0 int_v8 = 0, &lt;= 1, &gt;= 0 int_v9 = 0, &lt;= 1, &gt;= 0 int_v10 = 0, &lt;= 1, &gt;= 0 v11 = 0, &lt;= 1, &gt;= 0.1 v12 = 0, &lt;= 1, &gt;= 0.1 v13 = 0, &lt;= 1, &gt;= 0.1 v14 = 0, &lt;= 1, &gt;= 0.1 v15 = 0, &lt;= 1, &gt;= 0.1 v16 = 0 v17 = 0 v18 = 0 v19 = 0 v20 = 0 v21 = 0 v22 = 0 v23 = 0 v24 = 0 v25 = 0 v26 = 0 v27 = 0 int_v28 = 0.01, &lt;= 1, &gt;= 0 v29 = 0 int_v30 = 0.01, &lt;= 1, &gt;= 0 v31 = 0 int_v32 = 0.01, &lt;= 1, &gt;= 0 v33 = 0 int_v34 = 0.01, &lt;= 1, &gt;= 0 v35 = 0 int_v36 = 0.01, &lt;= 1, &gt;= 0 v37 = 0 int_v38 = 0.01, &lt;= 1, &gt;= 0 v39 = 0 int_v40 = 0.01, &lt;= 1, &gt;= 0 v41 = 0 int_v42 = 0.01, &lt;= 1, &gt;= 0 v43 = 0 int_v44 = 0.01, &lt;= 1, &gt;= 0 v45 = 0 int_v46 = 0.01, &lt;= 1, &gt;= 0 v47 = 0 v48 = 0, &gt;= 0 int_v49 = 0.01, &lt;= 1, &gt;= 0 v50 = 0 int_v51 = 0.01, &lt;= 1, &gt;= 0 v52 = 0 int_v53 = 0.01, &lt;= 1, &gt;= 0 v54 = 0 int_v55 = 0.01, &lt;= 1, &gt;= 0 v56 = 0 int_v57 = 0.01, &lt;= 1, &gt;= 0 v58 = 0 End Variables Intermediates i280=v21 i281=v27 i282=0 i283=((((i282+((((int_v1)*(v29)))*(8)))+((((int_v6)*(v31)))*(2))))/(100)) i284=0 i285=((((i284+((((int_v2)*(v33)))*(6)))+((((int_v7)*(v35)))*(1))))/(100)) i286=0 i287=((((i286+((((int_v3)*(v37)))*(6)))+((((int_v8)*(v39)))*(1))))/(100)) i288=0 i289=((((i288+((((int_v4)*(v41)))*(6)))+((((int_v9)*(v43)))*(7))))/(100)) i290=0 i291=((((i290+((((int_v5)*(v45)))*(4)))+((((int_v10)*(v47)))*(9))))/(100)) i292=((int_v1)*(i283)) i293=((int_v2)*(i285)) i294=((int_v3)*(i287)) i295=((int_v4)*(i289)) i296=((int_v5)*(i291)) i297=1 i298=((((((((((((i297)*(i292)))*(i293)))*(i294)))*(i295)))*(i296)))^(0.2)) i299=((int_v6)*(i283)) i300=((int_v7)*(i285)) i301=((int_v8)*(i287)) i302=((int_v9)*(i289)) i303=((int_v10)*(i291)) i304=1 i305=((((((((((((i304)*(i299)))*(i300)))*(i301)))*(i302)))*(i303)))^(0.2)) i306=1 i307=((((((i306)*(i298)))*(i305)))^(0.5)) End Intermediates Equations ((0+int_v1)+int_v6)&lt;=1 ((0+int_v2)+int_v7)&lt;=1 ((0+int_v3)+int_v8)&lt;=1 ((0+int_v4)+int_v9)&lt;=1 ((0+int_v5)+int_v10)&lt;=1 (((((0+((int_v1)*(v11)))+((int_v2)*(v12)))+((int_v3)*(v13)))+((int_v4)*(v14)))+((int_v5)*(v15)))&lt;=1 (((((0+((int_v6)*(v11)))+((int_v7)*(v12)))+((int_v8)*(v13)))+((int_v9)*(v14)))+((int_v10)*(v15)))&lt;=1 v16=((int_v1)*(v11)) v17=((int_v2)*(v12)) v18=((int_v3)*(v13)) v19=((int_v4)*(v14)) v20=((int_v5)*(v15)) v22=((int_v6)*(v11)) v23=((int_v7)*(v12)) v24=((int_v8)*(v13)) v25=((int_v9)*(v14)) v26=((int_v10)*(v15)) (((1-int_v28))*(i280&gt;0))&lt;=0 ((int_v28)*(i280&gt;0))&gt;=0 v29=((((1-int_v28))*(((((v11)/(i280)))*(2))))+((int_v28)*(0))) (((1-int_v30))*(i281&gt;0))&lt;=0 ((int_v30)*(i281&gt;0))&gt;=0 v31=((((1-int_v30))*(((((v11)/(i281)))*(2))))+((int_v30)*(0))) (((1-int_v32))*(i280&gt;0))&lt;=0 ((int_v32)*(i280&gt;0))&gt;=0 v33=((((1-int_v32))*(((((v12)/(i280)))*(2))))+((int_v32)*(0))) (((1-int_v34))*(i281&gt;0))&lt;=0 ((int_v34)*(i281&gt;0))&gt;=0 v35=((((1-int_v34))*(((((v12)/(i281)))*(2))))+((int_v34)*(0))) (((1-int_v36))*(i280&gt;0))&lt;=0 ((int_v36)*(i280&gt;0))&gt;=0 v37=((((1-int_v36))*(((((v13)/(i280)))*(2))))+((int_v36)*(0))) (((1-int_v38))*(i281&gt;0))&lt;=0 ((int_v38)*(i281&gt;0))&gt;=0 v39=((((1-int_v38))*(((((v13)/(i281)))*(2))))+((int_v38)*(0))) (((1-int_v40))*(i280&gt;0))&lt;=0 ((int_v40)*(i280&gt;0))&gt;=0 v41=((((1-int_v40))*(((((v14)/(i280)))*(2))))+((int_v40)*(0))) (((1-int_v42))*(i281&gt;0))&lt;=0 ((int_v42)*(i281&gt;0))&gt;=0 v43=((((1-int_v42))*(((((v14)/(i281)))*(2))))+((int_v42)*(0))) (((1-int_v44))*(i280&gt;0))&lt;=0 ((int_v44)*(i280&gt;0))&gt;=0 v45=((((1-int_v44))*(((((v15)/(i280)))*(2))))+((int_v44)*(0))) (((1-int_v46))*(i281&gt;0))&lt;=0 ((int_v46)*(i281&gt;0))&gt;=0 v47=((((1-int_v46))*(((((v15)/(i281)))*(2))))+((int_v46)*(0))) (((1-int_v49))*(i281&gt;0))&lt;=0 ((int_v49)*(i281&gt;0))&gt;=0 v50=((((1-int_v49))*(((((v11)/(i281)))*(2))))+((int_v49)*(0))) (((1-int_v51))*(i281&gt;0))&lt;=0 ((int_v51)*(i281&gt;0))&gt;=0 v52=((((1-int_v51))*(((((v12)/(i281)))*(2))))+((int_v51)*(0))) (((1-int_v53))*(i281&gt;0))&lt;=0 ((int_v53)*(i281&gt;0))&gt;=0 v54=((((1-int_v53))*(((((v13)/(i281)))*(2))))+((int_v53)*(0))) (((1-int_v55))*(i281&gt;0))&lt;=0 ((int_v55)*(i281&gt;0))&gt;=0 v56=((((1-int_v55))*(((((v14)/(i281)))*(2))))+((int_v55)*(0))) (((1-int_v57))*(i281&gt;0))&lt;=0 ((int_v57)*(i281&gt;0))&gt;=0 v58=((((1-int_v57))*(((((v15)/(i281)))*(2))))+((int_v57)*(0))) maximize (((1)*((((((v48+((((int_v6)*(v50)))*(2)))+((((int_v7)*(v52)))*(1)))+((((int_v8)*(v54)))*(1)))+((((int_v9)*(v56)))*(7)))+((((int_v10)*(v58)))*(9)))))+((1)*(i307))) End Equations Connections v16 = sum_1.x[1] v17 = sum_1.x[2] v18 = sum_1.x[3] v19 = sum_1.x[4] v20 = sum_1.x[5] v21 = sum_1.y v22 = sum_2.x[1] v23 = sum_2.x[2] v24 = sum_2.x[3] v25 = sum_2.x[4] v26 = sum_2.x[5] v27 = sum_2.y End Connections Objects sum_1 = sum(5) sum_2 = sum(5) End Objects End Model </code></pre> <p>Could you please help me in the direction where the error could be.</p>
<python><linear-programming><nonlinear-optimization><gekko><mixed-integer-programming>
2024-09-10 17:38:58
1
1,516
Alok
78,970,536
4,451,315
pyarrow chunkedarray set at indices
<p>Say I have</p> <pre class="lang-py prettyprint-override"><code>In [1]: import pyarrow as ap In [2]: import pyarrow as pa In [3]: ca = pa.chunked_array([[1,2,3], [4,5,6]]) In [4]: ca Out[4]: &lt;pyarrow.lib.ChunkedArray object at 0x7f7afaaa4a90&gt; [ [ 1, 2, 3 ], [ 4, 5, 6 ] ] </code></pre> <p>I'd like to do something like</p> <pre class="lang-py prettyprint-override"><code>ca[[1, 4]] = [999, 888] </code></pre> <p>and end up with</p> <pre class="lang-py prettyprint-override"><code>&lt;pyarrow.lib.ChunkedArray object at 0x7f7aef473d30&gt; [ [ 1, 999, 3 ], [ 4, 888, 6 ] ] </code></pre> <p>I don't really mind if the result gets rechunked</p>
<python><pyarrow>
2024-09-10 16:52:08
2
11,062
ignoring_gravity
78,970,400
3,486,684
Using Polars, how do I do efficiently do an `over` that collects items into a list?
<p>As a simple example, consider the following, using <code>groupby</code>:</p> <pre class="lang-py prettyprint-override"><code>import polars as pl df = pl.DataFrame( [pl.Series(&quot;id&quot;, [&quot;a&quot;, &quot;b&quot;, &quot;a&quot;]), pl.Series(&quot;x&quot;, [0, 1, 2])] ) print(df.group_by(&quot;id&quot;).agg(pl.col(&quot;x&quot;))) # shape: (2, 2) # β”Œβ”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” # β”‚ id ┆ x β”‚ # β”‚ --- ┆ --- β”‚ # β”‚ str ┆ list[i64] β”‚ # β•žβ•β•β•β•β•β•ͺ═══════════║ # β”‚ b ┆ [1] β”‚ # β”‚ a ┆ [0, 2] β”‚ # β””β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ </code></pre> <p>But if we use <code>over</code>, we get:</p> <pre class="lang-py prettyprint-override"><code>import polars as pl df = pl.DataFrame( [pl.Series(&quot;id&quot;, [&quot;a&quot;, &quot;b&quot;, &quot;a&quot;]), pl.Series(&quot;x&quot;, [0, 1, 2])] ) print(df.with_columns(pl.col(&quot;x&quot;).over(&quot;id&quot;))) # shape: (3, 2) # β”Œβ”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β” # β”‚ id ┆ x β”‚ # β”‚ --- ┆ --- β”‚ # β”‚ str ┆ i64 β”‚ # β•žβ•β•β•β•β•β•ͺ═════║ # β”‚ a ┆ 0 β”‚ # β”‚ b ┆ 1 β”‚ # β”‚ a ┆ 2 β”‚ # β””β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”˜ </code></pre> <p>How can the <code>groupby</code> result be achieved using <code>over</code>? Well, using <a href="https://docs.pola.rs/api/python/stable/reference/expressions/api/polars.Expr.over.html" rel="nofollow noreferrer"><code>mapping_strategy=&quot;join&quot;</code></a>.</p> <p>A slightly more complicated example, meant to showcase why we might want to use <code>over</code> instead of <code>groupby</code>:</p> <pre class="lang-py prettyprint-override"><code>import polars as pl # the smallest value a Float32 can encode is 1e-38 # therefore, as far as we are concerned, # 1e-41 and 1e-42 should be indistinguishable # in other words, we do not want to use &quot;other&quot; as an id column # but we do want to preserve other! df = pl.DataFrame( [ pl.Series(&quot;id&quot;, [&quot;a&quot;, &quot;b&quot;, &quot;a&quot;]), pl.Series(&quot;other&quot;, [1e-41, 1e-16, 1e-42], dtype=pl.Float32()), pl.Series(&quot;x&quot;, [0, 1, 2]), ] ) print(df.group_by(&quot;id&quot;).agg(pl.col(&quot;x&quot;), pl.col(&quot;other&quot;)).explode(&quot;other&quot;)) # shape: (3, 3) # β”Œβ”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” # β”‚ id ┆ x ┆ other β”‚ # β”‚ --- ┆ --- ┆ --- β”‚ # β”‚ str ┆ list[i64] ┆ f32 β”‚ # β•žβ•β•β•β•β•β•ͺ═══════════β•ͺ════════════║ # β”‚ a ┆ [0, 2] ┆ 9.9997e-42 β”‚ # β”‚ a ┆ [0, 2] ┆ 1.0005e-42 β”‚ # β”‚ b ┆ [1] ┆ 1.0000e-16 β”‚ # β””β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ </code></pre> <p>Now, using <code>over</code>:</p> <pre class="lang-py prettyprint-override"><code>import polars as pl # the smallest value a Float32 can encode is 1e-38 # therefore, as far as we are concerned, # 1e-41 and 1e-42 should be indistinguishable # in other words, we do not want to use &quot;other&quot; as an id column # but we do want to preserve other! df = pl.DataFrame( [ pl.Series(&quot;id&quot;, [&quot;a&quot;, &quot;b&quot;, &quot;a&quot;]), pl.Series(&quot;other&quot;, [1e-41, 1e-16, 1e-42], dtype=pl.Float32()), pl.Series(&quot;x&quot;, [0, 1, 2]), ] ) print(df.with_columns(pl.col(&quot;x&quot;).over([&quot;id&quot;], mapping_strategy=&quot;join&quot;))) # shape: (3, 3) # β”Œβ”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” # β”‚ id ┆ other ┆ x β”‚ # β”‚ --- ┆ --- ┆ --- β”‚ # β”‚ str ┆ f32 ┆ list[i64] β”‚ # β•žβ•β•β•β•β•β•ͺ════════════β•ͺ═══════════║ # β”‚ a ┆ 9.9997e-42 ┆ [0, 2] β”‚ # β”‚ b ┆ 1.0000e-16 ┆ [1] β”‚ # β”‚ a ┆ 1.0005e-42 ┆ [0, 2] β”‚ # β””β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ </code></pre> <p>The trouble using <code>mapping_strategy=&quot;join&quot;</code> is that its very slow. So, this suggests that I ought to do a <code>group_by</code> followed by a <code>join</code>:</p> <pre class="lang-py prettyprint-override"><code>import polars as pl import polars.selectors as cs # the smallest value a Float32 can encode is 1e-38 # therefore, as far as we are concerned, # 1e-41 and 1e-42 should be indistinguishable # in other words, we do not want to use &quot;other&quot; as an id column # but we do want to preserve other! df = pl.DataFrame( [ pl.Series(&quot;id&quot;, [&quot;a&quot;, &quot;b&quot;, &quot;a&quot;]), pl.Series(&quot;other&quot;, [1e-41, 1e-16, 1e-42], dtype=pl.Float32()), pl.Series(&quot;x&quot;, [0, 1, 2]), ] ) print( df.select(cs.exclude(&quot;x&quot;)).join( df.group_by(&quot;id&quot;).agg(&quot;x&quot;), on=&quot;id&quot;, # we expect there to be multiple &quot;id&quot;s on the left, matching # a single &quot;id&quot; on the right validate=&quot;m:1&quot;, ) ) # shape: (3, 3) # β”Œβ”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” # β”‚ id ┆ other ┆ x β”‚ # β”‚ --- ┆ --- ┆ --- β”‚ # β”‚ str ┆ f32 ┆ list[i64] β”‚ # β•žβ•β•β•β•β•β•ͺ════════════β•ͺ═══════════║ # β”‚ a ┆ 9.9997e-42 ┆ [0, 2] β”‚ # β”‚ b ┆ 1.0000e-16 ┆ [1] β”‚ # β”‚ a ┆ 1.0005e-42 ┆ [0, 2] β”‚ # β””β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ </code></pre> <p>But perhaps I am missing something else about <code>over</code>?</p>
<python><dataframe><python-polars>
2024-09-10 16:16:29
1
4,654
bzm3r