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,024,389
651,174
How to insert element with text?
<p>I can insert an element like this:</p> <pre><code>product_node.insert(cnt, etree.Element(&quot;vod_type&quot;)) </code></pre> <p>Is it possible to do the following:</p> <pre><code>product_node.insert(cnt, etree.Element(&quot;vod_type&quot;).text=&quot;hello&quot;) </code></pre> <p>Or something of the sort. Or do I h...
<python><python-3.x><xml><lxml>
2024-02-20 01:51:33
2
112,064
David542
78,024,250
10,975,845
Difference Between Linter, Sanitizer and Analyzers
<p>What is the difference Between Linters, Sanitizers and Analyzers? And what are some examples of Linters, Sanitizers and Analyzers for Python? Also are they dependent on the IDE that you are using? I am currently using neovim and I have downloaded a few what I thought were linters. But now when I am searching for ana...
<python><linter><eclipse-memory-analyzer><sanitizer>
2024-02-20 00:51:51
1
344
Allie
78,024,239
2,152,371
Python Program not listening to keystrokes when Active Window is External Program (LInux)
<p>I'm trying to have a Python program listen for keystrokes sent to a program that is launched as a subroutine (Popen).</p> <p>The problem is that when the correct window is focused nothing happens. No acknowledgement that a key has been pressed. If I click off from the window to something else it works.</p> <p>This...
<python><input><automation><listener>
2024-02-20 00:46:10
1
470
Miko
78,024,121
497,403
Cannot convince Pytorch to install with Cuda (Windows 11)
<p>I am trying to install PyTorch with Cuda using Anaconda3, on Windows 11:</p> <ul> <li>My GPU is RTX <strong>3060</strong>.</li> <li>My conda environment is Python <strong>3.10.13</strong>.</li> <li>nvidia-smi outputs Driver Version: <strong>551.23</strong>, CUDA Version: <strong>12.4</strong>.</li> </ul> <p>What I t...
<python><windows><pytorch><anaconda>
2024-02-19 23:56:12
2
5,708
David Airapetyan
78,024,054
18,247,317
Convert SVG with embedded image into PNG with Python
<p>My aim is to create PNG images from an svg with embedded (as a link) image. I split the process in two: first create the SVGs, then my intention is to convert them to PNG. The below successfully creates an svg file for each of the listed paths of a source SVG containing a linked image. It also correctly inserts the ...
<python><svg>
2024-02-19 23:27:20
0
491
Oran G. Utan
78,024,045
784,044
Docker container build is failing in Gitlab CI
<p>I have a container that has no issues building locally; however when I try to build it in a Gitlab CI pipeline, I get the following error:</p> <p><code>ERROR: failed to solve: failed to solve with frontend dockerfile.v0: failed to solve with frontend gateway.v0: rpc error: code = Unknown desc = failed to build LLB: ...
<python><docker><gitlab-ci>
2024-02-19 23:23:38
0
886
Sidd Menon
78,023,985
5,615,873
How can I disable OpenCV writing image windows position and size to Windows Registry in Python?
<p>Every time I show an image with OpenCV (cv2) and use an image window label with <code>cv2.imshow(label, image)</code>, OpenCV creates or updates keys with that window label and the image position and size as values in Windows Registry. The key <strong>is HKEY_CURRENT_USER\SOFTWARE\OpenCV\HighGUI\Windows</strong>. (S...
<python><windows><opencv><user-interface><registry>
2024-02-19 23:02:33
1
3,537
Apostolos
78,023,800
4,269,851
Python dynamic argument processing inside fucntion
<p>I have following code that is not working.</p> <pre><code>def myFunction(*args): total_lists = len(args) for n in range(total_lists): print(list(zip(args[0], args[1]))) myFunction([1,2,3],[&quot;a&quot;, &quot;b&quot;, &quot;c&quot;]) </code></pre> <p>Basically function receives unknown number of...
<python><function><loops><for-loop><tuples>
2024-02-19 22:07:29
3
829
Roman Toasov
78,023,739
13,135,901
TypeError: Abstract models cannot be instantiated (Django)
<p>I have abstract models <code>A</code> and <code>B</code> and a child model <code>C</code>.</p> <pre><code>class A(models.Model): field1 = models.CharField(max_length=24) class Meta: abstract = True class B(models.Model): field1 = models.CharField(max_length=24) class Meta: abstrac...
<python><django>
2024-02-19 21:57:11
1
491
Viktor
78,023,622
2,263,683
Mock a module property
<p>I'm trying to mock a property which is at the module root:</p> <p><code>some_module.py</code></p> <pre><code>@property def conn(self): if not get_request(): raise SomeError( &quot;Some error happened&quot; ) return get_request().connection Database.conn = conn </code></pre> <p>I...
<python><mocking><pytest>
2024-02-19 21:31:02
0
15,775
Ghasem
78,023,568
52,917
how can I exclude a pydantic field from the schema?
<p>some of the fields in a pydantic class are actually internal representation and not something I want to serialize or put in a schema. I am trying various methods to exclude them but nothing seems to work.</p> <p>here's one approach where I use the <code>exclue=True</code> and <code>exclude_schema=True</code> of a <c...
<python><pydantic><pydantic-v2>
2024-02-19 21:16:46
1
2,449
Aviad Rozenhek
78,023,380
10,037,034
ImportError: cannot import name 'BaseOuputParser' from 'langchain.schema'
<p>Hello i am trying to run this following code but i am getting an error;</p> <pre><code>from langchain.schema import BaseOuputParser </code></pre> <p>Error;</p> <blockquote> <p>ImportError: cannot import name 'BaseOuputParser' from 'langchain.schema'</p> </blockquote> <p>My langchain version is ; <strong>'0.1.7'</str...
<python><openai-api><langchain>
2024-02-19 20:39:19
2
1,311
Sevval Kahraman
78,023,374
735,926
How to check if a Python module with a custom __getattr__ has a given attribute?
<p>I implemented a custom <code>__getattr__</code> on <a href="https://github.com/bfontaine/Anycode/blob/d7442b42fabbc6922f06bda284e0844d79f4b0c3/anycode/__init__.py#L12" rel="nofollow noreferrer">a module</a> that retrieves a value and caches it with <code>setattr</code>. Here is the simplified version:</p> <pre class...
<python><python-module><getattr>
2024-02-19 20:38:10
1
21,226
bfontaine
78,023,207
12,178,630
Match close element pairs from two numpy arrays
<p>I have two numpy arrays, I would like to have a one-to-one mapping between the two arrays so that elements that are closest to each other get mapped to each other. I have written the following script that basically does that, but I do not like that the mapping is not deterministically unique, like for some configura...
<python><arrays><numpy><scipy>
2024-02-19 19:52:44
1
314
Josh
78,022,620
8,474,284
systemd-python AttributeError: module 'systemd.journal' has no attribute 'JournaldLogHandler'
<p>I installed <code>systemd-python</code>:</p> <p><code>pip install systemd-python</code></p> <p>My python code:</p> <pre><code>from systemd import journal ... log = logging.getLogger('lookup') log.addHandler(journal.JournaldLogHandler()) log.setLevel(logging.INFO) </code></pre> <p>I got this error:</p> <pre><code>Tra...
<python><pip>
2024-02-19 17:48:14
1
1,723
DaWe
78,022,553
17,654,424
Docker Image for displaying graphics (matplotlib, plotly)
<p>I'am trying to containerize my python project which is using matplotlib and plotly to display some graphics and tables.</p> <p>However I'am having trouble to display those graphics... My script just runs and it wont display anything.</p> <p>Here is my dockerfile:</p> <pre><code># Use an official Python runtime as a ...
<python><docker><matplotlib><plotly>
2024-02-19 17:36:47
0
651
Simao
78,022,494
11,692,124
Pytorch lightning on_save_checkpoint is not called
<p><a href="https://github.com/FarhangAmaji/versatileAnn/tree/on_save_checkpointNotWorking" rel="nofollow noreferrer">on my project(which is in development phase)</a> (if u want to take a look/clone make sure that it's &quot;on_save_checkpointNotWorking&quot; branch)</p> <p>I have a class named <code>BrazingTorch</code...
<python><pytorch><pytorch-lightning>
2024-02-19 17:27:48
1
1,011
Farhang Amaji
78,022,474
8,474,284
ERROR: Could not build wheels for cysystemd
<p>I'm facing an error installing the systemd package:</p> <p><code>pip install cysystemd</code></p> <pre><code> error: subprocess-exited-with-error × python setup.py bdist_wheel did not run successfully. │ exit code: 1 ╰─&gt; [23 lines of output] /usr/local/lib/python3.12/site-packages/setuptools/_dist...
<python><pip><systemd>
2024-02-19 17:25:18
1
1,723
DaWe
78,022,472
9,983,652
what is windows equivalent of pwd.getpwuid?
<p>What is the windows equivalent of pwd.getpwuid? I believe pwd is an UNIX package. Here is the code and the error when using windows</p> <pre><code>import pwd file_owner_name = pwd.getpwuid(file_owner_uid).pw_name import pwd ModuleNotFoundError: No module named 'pwd' </code></pre>
<python>
2024-02-19 17:25:13
1
4,338
roudan
78,022,405
5,462,743
Azure Machine Learning SDK V2 changer version of python in Compute Cluster
<p>In SDK V1, I am using a environment for compute cluster with a dockerfile string like this:</p> <pre><code>azureml_env = Environment(&quot;my_experiment&quot;) azureml_env.python.conda_dependencies = CondaDependencies.create( pip_packages=[&quot;pandas&quot;, &quot;databricks-connect==10.4&quot;], ) dockerfile =...
<python><azure-machine-learning-service><azure-ai>
2024-02-19 17:13:58
1
1,033
BeGreen
78,022,329
353,337
Create combined numpy array without explicit loop/comprehension
<p>I have a long NumPy array that I need to organize in a &quot;pattern&quot; like so:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np # long array: a = np.array( [ 1.3, -1.8, 0.3, 11.4, # ... ] ) def pattern(x: float): return np.array( ...
<python><numpy><matrix>
2024-02-19 16:58:09
4
59,565
Nico Schlömer
78,022,295
1,501,700
Show function parameters
<p>I have AWS MQTT client python project in Visual Code. I have installed AWSIoTPythonSDK library that allows to communicate with AWS server. But I cant get this library function parameters by presing <code>ctrl+shift+space</code>. What else I should do in order to see <code>AWSIoTPythonSDK</code> library function para...
<python><amazon-web-services><visual-studio-code>
2024-02-19 16:53:03
1
18,481
vico
78,022,291
10,215,160
Pandera slow synthetic Dataframe generation if not eq schema
<p>I am trying to learn the Pandera Library. When i try to automatically generate test Data from a DataFrameModel, it suddenly takes very long or crashes if i deviate from the minimal example in terms of limit checks.</p> <p>Consider the Base example from the Pandera documentation: <a href="https://pandera.readthedocs....
<python><pandas><dataframe><python-hypothesis><pandera>
2024-02-19 16:52:15
1
1,486
Sandwichnick
78,022,239
10,695,731
Selenium wait for element_to_be_clickable throws error, manual waiting works
<p>In the HTML i have a table where the first column includes a radio button:</p> <p><a href="https://i.sstatic.net/QBys4.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/QBys4.png" alt="enter image description here" /></a></p> <p>I want to select and click the button with the following code:</p> <pre><co...
<python><html><selenium-webdriver><web-scraping>
2024-02-19 16:43:30
0
691
NicO
78,022,111
1,422,096
Python .pth and ._pth files (standard install vs. embedded Python)
<p>I see two diffrent behaviours about .pth and ._pth files:</p> <ul> <li><p>the official Python install for Windows uses <code>.pth</code> files in <code>lib\site-packages</code> as documented in <a href="https://docs.python.org/3.12/library/site.html#module-site" rel="nofollow noreferrer">https://docs.python.org/3.12...
<python><path><python-embedding>
2024-02-19 16:21:02
0
47,388
Basj
78,021,989
7,116,108
pandas to_dict - list of rows by key
<p>I have a DataFrame of the form:</p> <pre><code>df = pd.DataFrame({ &quot;key&quot;: [&quot;a&quot;, &quot;b&quot;, &quot;b&quot;, &quot;c&quot;, &quot;c&quot;, &quot;c&quot;], &quot;var1&quot;: [1, 2, 3, 4, 5, 6], &quot;var2&quot;: [&quot;x&quot;, &quot;y&quot;, &quot;x&quot;, &quot;y&quot;, &quot;x&quot...
<python><pandas>
2024-02-19 16:01:11
1
1,587
Dan
78,021,828
2,707,864
Sympy: Integral(0, (R, b, r)) not simplifying to zero when stemming from the Leibniz rule
<p>I am differentiating under an integral. Since the integrand does not depend explicitly on the variable, the corresponding term from the Leibniz rule would not show up. Nevertheless, sympy does not simplify it to zero. Why is that? Can it be somehow coerced to do so? That is preventing further simplification of my ex...
<python><sympy><symbolic-math><numerical-integration>
2024-02-19 15:36:33
1
15,820
sancho.s ReinstateMonicaCellio
78,021,659
3,650,983
Running DepthEstimationPipeline example from huggingface.co
<p>getting the following error when running</p> <pre><code>depth_estimator = pipeline(task=&quot;depth-estimation&quot;, model=&quot;LiheYoung/depth-anything-base-hf&quot;) </code></pre> <blockquote> <p>ValueError: The checkpoint you are trying to load has model type <code>depth_anything</code> but Transformers does no...
<python><machine-learning><deep-learning><pytorch><huggingface-transformers>
2024-02-19 15:10:09
1
4,119
ChaosPredictor
78,021,630
5,070,526
Airflow : Task wise dependency check with another Dag using ExternalTaskSensor
<p><code>ExternalTaskSensor</code> not working as expected. Here is example of <code>dags</code>.</p> <p><strong>Dag1(test_first_dag.py)</strong>:</p> <pre><code>Task 1 -&gt; print(&quot;Dag1-Task1-Hello World&quot;) Task 2 -&gt; print(&quot;Dag1-Task2-Hello World&quot;) </code></pre> <p><strong>Dag2(test_second_dag.py...
<python><airflow><airflow-2.x><airflow-taskflow>
2024-02-19 15:07:29
1
725
Sachin Sukumaran
78,021,585
4,406,532
Colab Google using qiskit Aer
<p>Here is my code:</p> <pre><code>#!pip3 install qiskit !pip3 install qiskit-aer from qiskit import Aer, ClassicalRegister, QuantumCircuit, QuantumRegister </code></pre> <p>This is the Error I get:</p> <pre><code>ImportError Traceback (most recent call last) &lt;ipython-input-14-2acb4a3b...
<python><google-colaboratory><qiskit>
2024-02-19 14:59:47
2
2,293
Avi
78,021,416
16,627,522
PyBind11: How to use a class as a data type
<p>How do I convert a C++ class into a 'data type', for instance, if I had a vector: <code>dog_vector</code>, I can convert it to a <code>py::array</code> and expose it to Python where it would be read as a Numpy array. How do I expose a class to Python, allowing for its methods to also be called from Python.</p> <p>I ...
<python><c++><pybind11><nanobind>
2024-02-19 14:31:10
0
634
Tommy Wolfheart
78,021,371
18,159,603
Pytorch advanced indexing with list of lists as indices
<p>Here is some python code to reproduce my issue:</p> <pre class="lang-py prettyprint-override"><code>import torch n, m = 9, 4 x = torch.arange(0, n * m).reshape(n, m) print(x.shape) print(x) # torch.Size([9, 4]) # tensor([[ 0, 1, 2, 3], # [ 4, 5, 6, 7], # [ 8, 9, 10, 11], # [12, 13, 1...
<python><indexing><pytorch><tensor>
2024-02-19 14:22:54
2
1,036
leleogere
78,021,309
1,914,034
Create images patches with overlap using torch.unfold
<p>I would like to split an images into smaller images of 1024x1024. I would like to have an overlap of 100 pixels in the top/bottom and left/right of the patches.</p> <p><img src="https://i.sstatic.net/tDc9P.png" alt="enter image description here" /></p> <p>I am using padding and torch.unfold to create even sized patc...
<python><pytorch>
2024-02-19 14:14:46
1
7,655
Below the Radar
78,021,029
424,957
May I use sequence number in Python Pool.imap?
<p>I use code as below to download ts files, because original ts filename is too long, that is failed when merge ts files to mp4 file, so I want to save it in sequence 001.ts, 02.ts,...and so on, how can I pass this sequence number to download_ts_file?</p> <pre><code>def download_ts_file(ts_url: str, store_dir: str, at...
<python><threadpool>
2024-02-19 13:28:57
1
2,509
mikezang
78,020,975
7,133,942
Can't import a installed package in Python with jupyter notebook
<p>I have a strange problem. I want to use the package &quot;copulas&quot; in Python (<a href="https://sdv.dev/Copulas/" rel="nofollow noreferrer">https://sdv.dev/Copulas/</a>). For that I first install it by using</p> <pre><code>!pip install copulas </code></pre> <p>The output is</p> <pre><code>Requirement already sat...
<python><jupyter-notebook><python-packaging><copula>
2024-02-19 13:21:50
1
902
PeterBe
78,020,935
2,391,712
Default value based on other field
<p>Is there a way to have the following:</p> <pre class="lang-python prettyprint-override"><code>from dataclasses import dataclass, fields @dataclass class ExampleCls: category: str subcategory: str = f&quot;{category} level 2&quot; </code></pre> <ol> <li><code>ExampleCls(category=&quot;hi&quot;)</code> <ul> <...
<python><python-dataclasses>
2024-02-19 13:15:43
0
2,515
5th
78,020,921
1,422,096
How does .pth files distinguish between lines with path information and lines with Python code?
<p>It seems a .pth file can also mix <em>&quot;folders to add to path&quot;</em> information + also, some Python code, such as <code>import foo</code>. Example in <code>pywin32.pth</code>:</p> <pre><code># .pth file for the PyWin32 extensions win32 win32\lib Pythonwin # And some hackery to deal with environments where ...
<python><path><python-import><pth>
2024-02-19 13:13:10
1
47,388
Basj
78,020,884
3,973,175
hist2d plots with vmin/vax unknown until plotting with combined colorbar; previous solution not working
<p>I am attempting to make plots of density in rows. The challenging part, is that each of the plots must have the same color-scale min and max, and I do not know beforehand what the min and max are. I must plot the values first in order to find out the min and max, remove those plots, and then make new ones with the...
<python><python-3.x><matplotlib>
2024-02-19 13:05:34
1
6,227
con
78,020,841
2,440,388
Is possible to read environment variables while running python code on a PEX file?
<p>I am trying to have my python application running on a <a href="https://github.com/pex-tool/pex" rel="nofollow noreferrer">PEX</a> file, inside a docker container.</p> <p>I was wondering if PEX files support any kind of configuration in order to read environment variables that get provided to the docker container ju...
<python><docker><environment-variables><pex>
2024-02-19 12:59:19
1
343
jarey
78,020,823
10,695,731
Selenium find element by link_text or Xpath - ElementNotFoundException
<p>I have an href on the website which which looks like this:</p> <pre><code>&lt;a href=&quot;Redirect.jsp?ScreenCode=L0000&quot; target=&quot;LinkFrame&quot;&gt;Transfer Doc&lt;/a&gt; </code></pre> <p>This element is even visible when i expect the browser window opened by Selenium.</p> <p><strong>Problem:</strong></p...
<python><html><selenium-webdriver><web-scraping>
2024-02-19 12:56:22
1
691
NicO
78,020,643
11,211,041
Type 'str' doesn't have expected attribute '__setitem__' in Python
<p>Why do I get &quot;<strong>Type 'str' doesn't have expected attribute '__setitem__'</strong>&quot; when I call my static class method?</p> <pre><code>@staticmethod def replace_region_decimal_sign(to_convert): to_convert[to_convert.index(',')] = '.' # Replace comma (&quot;region&quot; decimal sign) with a dot ...
<python><string><attributes>
2024-02-19 12:26:22
1
892
Snostorp
78,020,395
1,030,951
How to specify Nested JSON using Langchain
<p>I am using <a href="https://python.langchain.com/docs/modules/model_io/output_parsers/types/structured" rel="nofollow noreferrer">StructuredParser</a> of Langchain library. I am getting flat dictionary from parser. Please guide me to get a list of dictionaries from output parser.</p> <pre class="lang-py prettyprint-...
<python><langchain>
2024-02-19 11:44:37
2
4,935
HarshIT
78,020,346
22,221,987
Python Sphinx inheritance path display and view configuration
<p>I'm trying to generate a project documentation with Sphinx. Here is my project tree:</p> <pre><code>project_folder docs package_0 __init__.py script_0.py package_1 __init__.py package_2 script_2.py package_3 script_3.py script_33....
<python><python-3.x><documentation><python-sphinx>
2024-02-19 11:35:43
0
309
Mika
78,020,312
8,010,921
Signature Inheritance for **kwarg in constructor in python
<p>I have two TypeDict defined as follows:</p> <pre class="lang-py prettyprint-override"><code>class TypeFilter1(TypedDict): c: str d: float class TypeFilter2(TypedDict): e: float f: int </code></pre> <p>that I would like to use as types to construct two classes</p> <pre class="lang-py prettyprint-over...
<python>
2024-02-19 11:29:03
3
327
ddgg
78,020,254
1,029,469
Python / Pillow: treat an animated GIF or WEBP in place
<p>I want to resize a complete GIF (all frames) in place/in memory, without saving it to disk. I'm using Pillow/PIL. I've seen the other examples of &quot;how to create or modify an animated GIF with Pillow&quot;, but the all use the Images's save method like this: <code>first_frame.save(&quot;anim.gif&quot;, save_all...
<python><python-imaging-library>
2024-02-19 11:18:05
0
1,957
benzkji
78,020,185
3,828,463
Why am I getting this error? <class 'TypeError'>: wrong type
<p>I have a Python driver calling a Fortran subroutine. The subroutine has 1 character, then 3 integers. Before I added the character variable at the start and didn't have the argtypes call, it ran fine. But adding the character (and its length) plus the artgtypes call at the start gives a TypeError:</p> <pre><code>...
<python><fortran><ctypes>
2024-02-19 11:06:28
1
335
Adrian
78,020,103
8,068,825
Pandas - Duplicate rows based on the last character in string column
<p>so if I have a pandas dataframe</p> <pre><code>msg | label &quot;hello&quot; | 1 &quot;hi!&quot; | 0 </code></pre> <p>I need something that'll duplicate any row ending with [?,.,!] and duplicate the row without the punctuation so the above row would become</p> <pre><code>msg | label &quot;hello&quot; | 1 &quot;hi!...
<python><pandas>
2024-02-19 10:52:01
3
733
Gooby
78,019,997
4,269,851
Possible to use python native lists to replace array altogether?
<p>I come from PHP background so i am very used to arrays with key-&gt;value pairs e.g.</p> <pre><code>array[0] = &quot;One&quot; array[1] = &quot;Two&quot; array[3] = &quot;Three&quot; </code></pre> <p>Then i could <code>unset(array[2])</code> and still have keys untouched</p> <pre><code>array[1] -&gt; &quot;One&quot;...
<python><arrays><list><types>
2024-02-19 10:35:19
3
829
Roman Toasov
78,019,970
17,471,060
Pythonic way to get polars data frame absolute max values of all relevant columns
<p>I want to create absolute maximum of all Polars data frame columns. Here is a way, but surely could be improved.</p> <pre class="lang-py prettyprint-override"><code>import numpy as np import polars as pl df = pl.DataFrame({ &quot;name&quot;: [&quot;one&quot;, &quot;one&quot;, &quot;one&quot;, &quot;two&quot;, &...
<python><dataframe><python-polars>
2024-02-19 10:30:50
4
344
beta green
78,019,932
23,051,231
AttributeError: module 'typing' has no attribute 'Literal'
<p>I have python 3.9 installed in my windows machine with a flask script working as expected. Then I tried to replicate the environment on my linux machine. I have the same python version and the exact same <em>pip list</em>. But in the linux machine I receive this error from mod_wsgi:</p> <pre><code>from flask import ...
<python><flask><mod-wsgi><werkzeug>
2024-02-19 10:25:02
1
403
galex
78,019,900
7,553,746
How can I use list comprehension to count high or low pair?
<p>I am trying to make my code more elegant/less verbose with list comprehension. I have the following so far:</p> <pre><code>a = [47, 67, 22] b = [26, 47, 12] at = 0 bt = 0 for a, b in [c for c in zip(a, b)]: if a&gt;b: at+=1 elif a&lt;b: bt+=1 </code></pre> <p>I've been trying to do som...
<python>
2024-02-19 10:19:40
3
3,326
Johnny John Boy
78,019,666
9,809,542
How to avoid splitting on specific text block in LangChain
<p>I'm using langchain ReucrsiveCharacterTextSplitter to split a string into chunks. Within this string is a substring which I can demarcate. I want this substring to not be split up, whether that's entirely it's own chunk, appended to the previous chunk, or prepended to the next chunk. Is there a relatively simple way...
<python><nlp><langchain><retrieval-augmented-generation><text-chunking>
2024-02-19 09:43:19
1
587
DMcC
78,019,567
1,422,096
How does "import pythoncom" find the right files?
<p>NB: I know the proper solution is just to do <code>pip install pywin32</code> and let everything be done automatically, but here this question is about the internals of <code>pythoncom</code>.</p> <p>When doing <code>import pythoncom</code>, it works, but:</p> <ul> <li><p>in &quot;C:\Python38\Lib\site-packages\pytho...
<python><windows><python-import><pywin32><pth>
2024-02-19 09:27:29
1
47,388
Basj
78,019,480
4,875,766
How to dynamically provide arguments to a class __init__ function based on attributes?
<p>How do tools like <code>dataclasses</code> and <code>pydantic</code> create the <code>__init__()</code> functions for the classes they create?</p> <p>I know I can use these tools but I want to learn how to use the python metaprogramming to parse my class and create a dynamic init function based on attributes and the...
<python><oop><metaprogramming>
2024-02-19 09:12:11
1
331
TobyStack
78,019,304
5,259,592
SSL error in python requests on POST API call
<p>I have to use hit an api request using Airflow. So i was using HttpOperator but facing below error</p> <pre><code>urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='&lt;api host&gt;', port=443): Max retries exceeded with url: &lt;endpoint path&gt; (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTI...
<python><ssl-certificate><airflow>
2024-02-19 08:36:37
0
400
Ayush Goyal
78,019,123
8,068,825
Pandas - Split multiple columns of numpy arrays into multiple columns
<p>I saved numpy array to pandas columns and it gets saved as a string. I parse the string and convert it to numpy array below. The issue is the code below is painfully slow. Is there a way to speed this up?</p> <pre><code>def f(x): # Remove &quot;[&quot; and &quot;]&quot; and split on space return np.fromstrin...
<python><pandas><numpy>
2024-02-19 08:02:58
1
733
Gooby
78,019,115
839,837
Use values in a list to extract specific rows from an excel spreadsheet
<p>I have a spreadsheet where I'm trying to extract specific rows that contain a value from a list. The values checked are in the Task column of the spreadsheet. The spreadsheet has an unusual layout and is not friendly for parsing.</p> <p>I converted the excel spreadsheet I need to parse into a JSON file so I could sh...
<python><python-3.x><pandas><excel><dataframe>
2024-02-19 08:00:45
1
727
Markus
78,019,004
4,215,176
Python: Reading bytes from a file and converting it to the needed type
<p>I am trying to implement a code which reads the bytes from a file and computes the histogram of the byte count frequencies:</p> <p>I am using this code to read from a file and writing to a csv file:</p> <pre><code>block_size = int(block_size) data_block = data[:block_size] encoded_data_block = base64.b64encode(data_...
<python><python-3.x><byte>
2024-02-19 07:35:34
0
511
Sanku
78,018,922
9,495,110
Could not deserialize class 'Generator' because its parent module networks cannot be imported
<p>I have a subclassed model <code>Generator</code> that uses other subclassed layers declared in a different file <code>ops.py</code>. I tried to save the model by calling <code>model.save()</code> in <code>keras</code> format. Now when I am trying to load the model by calling <code>tf.keras.models.load_model()</code>...
<python><tensorflow><keras><serialization>
2024-02-19 07:16:42
0
1,027
let me down slowly
78,018,799
16,405,935
How to transform multi-columns to rows
<p>I have a excel file with multi-columns as below (Sorry but I don't know how to recreate it with pandas): <a href="https://i.sstatic.net/lzTs9.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/lzTs9.png" alt="enter image description here" /></a></p> <p>Below is my expected Output:</p> <pre><code>import p...
<python><pandas><dataframe>
2024-02-19 06:47:47
1
1,793
hoa tran
78,018,605
8,645,552
Write a numpy array to headerless wav file?
<p>I have a numpy audio array, I would like to write it in chunks as <strong>wav</strong> with <strong>ulaw</strong> encoding. For now I am using the <a href="https://python-soundfile.readthedocs.io/en/0.11.0/index.html?highlight=write#soundfile.SoundFile.write" rel="nofollow noreferrer">soundfile</a> library:</p> <pre...
<python><numpy><wav><soundfile><mu-law>
2024-02-19 06:02:09
0
370
demid
78,018,029
1,574,054
How to delete all parents with no children in sqlalchemy?
<p>Let's consider the SQLAlchemy <a href="https://docs.sqlalchemy.org/en/20/orm/basic_relationships.html" rel="nofollow noreferrer">example for a basic relationship</a>:</p> <pre><code>class Parent(Base): __tablename__ = &quot;parent_table&quot; id: Mapped[int] = mapped_column(primary_key=True) children: M...
<python><sql><sqlite><sqlalchemy>
2024-02-19 01:42:34
2
4,589
HerpDerpington
78,017,871
6,300,467
How to access all the holdings in an ETF with yahooquery?
<p>Is it possible to grab <strong>all</strong> of the holdings of an ETF within <code>yahooquery</code>?</p> <p>The example code below shows the top 10 holdings of an example ETF, but not all of them. Is it possible to get all the holdings of an ETF within the <code>yahooquery</code>/<code>yfinance</code> packages?</p>...
<python><pandas><web-scraping><yahoo-finance><yfinance>
2024-02-19 00:12:25
0
785
AlphaBetaGamma96
78,017,860
1,412,564
Django - how do I update the database with an expression of a field?
<p>We are using Django for our website, and I want to remove personal information from one of the databases. For example I want to change email addresses to their <code>id</code> + <code>&quot;@example.com&quot;</code>. I can do it with Python:</p> <pre class="lang-py prettyprint-override"><code>for e in UserEmailAddre...
<python><django><django-queryset>
2024-02-19 00:07:02
1
3,361
Uri
78,017,850
965,372
Upgrading PAHO MQTT to v2, where to add callback method?
<p>I'm trying to update some code someone else wrote that I've been providing a docker file for, as well as trying to keep up-to-date,since they no longer support it. In the paho docs, for v2, you need to add &quot;mqtt.CallbackAPIVersion.VERSION1&quot; as per <a href="https://eclipse.dev/paho/files/paho.mqtt.python...
<python><mqtt><paho>
2024-02-19 00:01:50
0
1,264
Evan R.
78,017,794
651,174
Set two different debug levels in logger module
<p>I have the following which creates two loggers -- stream logger and file logger.</p> <pre><code># Set up the Logging modules tmp_file = tempfile.NamedTemporaryFile(mode='w+') logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) c_handler = logging.StreamHandler() f_handler = logging.FileHandler(tmp_fil...
<python><python-3.x><logging>
2024-02-18 23:34:28
2
112,064
David542
78,017,670
5,414,176
Is it possible to use the depthSort argument in breadthfirst layout in dash-cytoscape?
<p>I'm plotting a network using <a href="https://dash.plotly.com/cytoscape" rel="nofollow noreferrer">Dash-Cytoscape</a>, using the <code>breadthfirst</code> layout, as documented <a href="https://js.cytoscape.org/#layouts/breadthfirst" rel="nofollow noreferrer">here</a>.</p> <p>I would like to control the order of app...
<python><plotly-dash><cytoscape><dash-cytoscape>
2024-02-18 22:41:53
1
801
Alon
78,017,570
530,714
Expressive differences and similarities of Python's and C++20's modules? `import` vs `export`/`import`
<p>I am familiar with Python's <code>import</code> mechanism (no expert though). I am not at all familiar with the <a href="https://en.cppreference.com/w/cpp/language/modules" rel="nofollow noreferrer">modules</a> mechanism that C++ has finally received in C++20. Despite them being two very different languages, I am su...
<python><c++><import><c++20>
2024-02-18 22:01:47
1
2,418
Grigory Rechistov
78,017,556
11,280,068
python os.makedirs not working with fastapi app
<p>I'm having a problem where in my fastapi app, when I run <code>os.makdirs(dir, exist_ok=True)</code> no dirs get created. When I run just this command alone in a new file, it works, but in my fastapi app, it doesn't work.</p> <p>I have made sure that my file permissions are okay, and that the logic is being accessed...
<python><python-3.x><docker><operating-system><fastapi>
2024-02-18 21:56:47
1
1,194
NFeruch - FreePalestine
78,017,555
5,423,080
NumPy create a 3D array using other 2 3D arrays and a 1D array to discriminate
<p>I have 2 3D numpy arrays:</p> <pre><code>a = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]], [[13, 14, 15], [16, 17, 18]]]) b = a + 100 </code></pre> <p>and 1 1D array:</p> <pre><code>c = np.array([0, 1, 0]) </code></pre> <p>I w...
<python><numpy>
2024-02-18 21:56:32
1
412
cicciodevoto
78,017,540
2,905,108
Tkinter image doesn't display without matplotlib
<p>My code generates an image as a numpy array, and then displays it in a canvas object. I use matplotlib for debugging and when when display the matplotlib window, it seems to work correctly.</p> <p>However, when I close the matplotlib window, the image object is cleared and becomes fully white.</p> <p>You can see wit...
<python><matplotlib><tkinter><tkinter-canvas>
2024-02-18 21:52:08
1
487
Gordon13
78,017,384
2,905,108
Image is mangled when displaying numpy array image in tkinter
<p>I'm trying to display an image, procedurally generated by my code, into a canvas object. I don't want to use the canvas functions to generate these images because there's no good way (the screenshot and ghostcript methods are no good) to get pixel data out of the canvas.</p> <p>I looked around for ways to generate t...
<python><numpy><tkinter><tkinter-canvas>
2024-02-18 20:59:59
1
487
Gordon13
78,017,366
5,790,653
python local file module not found but with cli finds module
<p>This is my <code>file.py</code>:</p> <pre class="lang-py prettyprint-override"><code>import os os.chdir('/home/python3.10') print(os.getcwd()) print(os.system('pwd; ls')) import template print(template.text) </code></pre> <p>I have a virtual environment in <code>/home/python3.10</code>.</p> <p>If I run file like thi...
<python>
2024-02-18 20:54:32
1
4,175
Saeed
78,017,170
5,864,582
Repeated calls to the same _target_ with different parameter combinations using hydra
<p>I have the following python class:</p> <pre class="lang-py prettyprint-override"><code>class MyClass: @classmethod def from_config(cls, configs: dict): calculation = hydra.utils.instantiate(configs) return calculation def __call__(self, a, b): return a + b </code></pre> <p>I w...
<python><fb-hydra>
2024-02-18 19:42:35
1
5,736
akilat90
78,017,078
1,440,839
Using xarray with resample and interpolate to animate the movement of contours
<p>Lets say I have the following python code, showing a contour value at 12pm and 1pm, indicating that it's position has moved:</p> <pre class="lang-py prettyprint-override"><code>import xarray as xr import numpy as np import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation %matplotlib widget ...
<python><numpy><matplotlib><scipy><python-xarray>
2024-02-18 19:15:06
2
401
John
78,017,053
9,983,652
\\langchain\\agents\\agent_toolkits' is not in the subpath of 'site-packages\\langchain_core' OR one path is relative and the other is absolute
<p>I just upgrade LangChain and OpenAi using below conda install. Then I got below error, any idea how to solve it? Thanks</p> <p><a href="https://anaconda.org/conda-forge/langchain" rel="nofollow noreferrer">https://anaconda.org/conda-forge/langchain</a> conda install conda-forge::langchain</p> <p><a href="https://ana...
<python><langchain>
2024-02-18 19:09:26
1
4,338
roudan
78,016,891
20,771,478
SQL Alchemy does not execute queries
<p>I am using SQLAlchemy to run a query in SQL Server. The query is supposed to create a table. The below example is meant to be easily reproducable for you. It does not contain the actual queries I use.</p> <p>If I run the following code no table gets created. No error or message of any kind is returned. (Please assum...
<python><sql-server><sqlalchemy>
2024-02-18 18:22:00
1
458
Merlin Nestler
78,016,833
10,037,034
How to handle errors and messages without raising exception? (pythonic way)
<p>I have a program which has a lot of functions inside. And all this functions calls another functions. This functions has try catch blocks for to handle errors. I have to handle this errors without raising errors, because i am trying to do api application, i am loosing the control of handling errors.</p> <p>So i wrot...
<python><error-handling><try-catch>
2024-02-18 18:05:49
1
1,311
Sevval Kahraman
78,016,744
3,333,319
Random ConnectionError using python-socketio on the client side
<p>I am using <code>python-socketio</code> to connect to a third party server using the socketIO protocol. The server is out of my control, therefore I do not have access to server side logs, etc... . The error below happens randomly (say half of the times), so my current workaround is to retry until the connection suc...
<python><socket.io><connection><python-socketio>
2024-02-18 17:34:56
0
973
Sirion
78,016,464
17,343
Performance of regex alteration
<p>The actual regex is more complex, but I am surprised by the cost of adding a second word:</p> <pre><code>import timeit SETUP = &quot;import re; STRING = ' ' * 100000&quot; print(min(timeit.Timer(&quot;re.findall(r'(foo)' , STRING)&quot;, SETUP).repeat(10, 1000))) print(min(timeit.Timer(&quot;re.findall(r'(fo...
<python><python-3.x><regex>
2024-02-18 16:12:19
0
55,736
Peter Lang
78,016,325
2,707,864
Sympy: Get coefficients of generic functions in an expression
<p>I have equation (1) that linearly relates 3 functions of x, p,q,r. I have equation (2) that linearly relates other 3 functions of x, s,q,r. I want to obtain from (1) r in terms of p,q, and then substitute r in eqn. (2), to get a relation between s,p,q. This is what I did in <code>sympy</code>.</p> <pre><code>p = sym...
<python><sympy>
2024-02-18 15:31:00
1
15,820
sancho.s ReinstateMonicaCellio
78,016,158
11,613,489
Problems getting an element from a html
<p>I'm trying to use Selenium to (legally) scrape data from a website. I tried the code, but nothing appears as result. I'd like to obtain the data and see what I've done at the button before I show you how the HTML appears.</p> <p>I just need to get &quot;31 954 kr&quot; from the hmtl. <a href="https://i.sstatic.net/...
<python><selenium-webdriver><web-scraping>
2024-02-18 14:34:46
2
642
Lorenzo Castagno
78,016,050
2,743,931
Python loc multiindex series with repeated keys
<p>I have a multi-index Series defined like this:</p> <pre><code>s = pd.Series([1, 2, 3, 4, 5, 6], index=pd.MultiIndex.from_product([[&quot;A&quot;, &quot;B&quot;], [&quot;c&quot;, &quot;d&quot;, &quot;e&quot;]])) s </code></pre> <pre><code>A c 1 d 2 e 3 B c 4 d 5 e 6 dtype: int64 </...
<python><pandas>
2024-02-18 14:05:40
3
312
user2743931
78,016,047
1,754,307
Unable to unprotect worksheet in Xlwings
<p>I am running xlwings on Windows. When my code hits the unprotection of the sheet, the code just sits there. No exceptions, no popups appeared in Excel, just hanging. I can manually remove protection, the password is fine.</p> <pre><code> with xw.App() as app: wb = app.books.open(local_filename...
<python><xlwings>
2024-02-18 14:04:31
0
3,082
smackenzie
78,015,891
23,219,369
How to fix 4 arc issue when converting pdf to dxf using inkscape?
<p>I'm trying to convert a pdf file to a dxf file using the <code>inkscape</code> command. I converted a pdf file to a svg file first and converted this to dxf file.</p> <p>This is the <code>inkscape</code> command I've used:</p> <pre><code>inkscape input.svg --export-type=dxf --export-extension=org.ekips.output.dxf_ou...
<python><pdf><svg><inkscape><dxf>
2024-02-18 13:17:52
1
834
Temunel
78,015,804
3,943,162
How to use StreamlitCallbackHandler with Langgraph?
<p>I'm trying to use Streamlit to show the final output to the user together with the step-by-step thoughts. For it, I'm using StreamlitCallbackHandler copying from the <a href="https://github.com/langchain-ai/streamlit-agent/blob/main/streamlit_agent/mrkl_demo.py" rel="nofollow noreferrer">MRKL example</a>.</p> <p>How...
<python><streamlit><py-langchain><langgraph>
2024-02-18 12:51:02
1
1,789
James
78,015,787
9,546,656
AttributeError: 'Collection' object has no attribute '__pydantic_private__'. Did you mean: '__pydantic_complete__'?
<p>I am trying to create pdf chat using open source LLM. I get the below error when I run ingest.py</p> <pre><code>(my_venv) PS C:\GithubRepository\Chat-with-PDF-Chatbot&gt; python ingest.py bill.pdf splitting into chunks Loading sentence transformers model C:\GithubRepository\Chat-with-PDF-Chatbot\my_venv\...
<python><pydantic><large-language-model><chromadb><pydantic-settings>
2024-02-18 12:46:26
2
359
Akash
78,015,763
6,282,576
MongoEngine upsert and append to ListField of IntChoiceField (append to list if record exists, create otherwise)
<p>I have the following definition for an IntChoiceField:</p> <pre class="lang-py prettyprint-override"><code>from mongoengine import IntField class IntChoiceField(IntField): def __init__(self, min_value=None, max_value=None, choices: list = None, **kwargs): super().__init__(min_value, max_value, **kwargs...
<python><mongodb><mongoengine>
2024-02-18 12:35:33
1
4,313
Amir Shabani
78,015,554
8,076,879
Cache python3-poetry installation in circleci
<p>I would like to cache poetry installation in <code>.circleci</code></p> <p>The command is as follows: <code>curl -sSL https://install.python-poetry.org | python3 -</code> which creates a <code>bin</code> in <code>/home/circleci/.local/bin/poetry</code> which actually links to <code>/home/circleci/.local/share/pypoet...
<python><cicd><circleci><python-poetry>
2024-02-18 11:30:19
0
2,438
DaveR
78,015,300
1,137,254
How to generate a 'stub' Python interface for a 3p library for development?
<p>I'm developing for RPi. I'd like to do the majority of my coding on a fast, local machine with a snappy IDE. To do this, I need to be able to <code>pip install</code> the same modules as I have on the RPi. Problem is, one of the most popular, <a href="https://sourceforge.net/projects/raspberry-gpio-python/" rel="nof...
<python><raspberry-pi><python-typing><python-bindings>
2024-02-18 10:02:57
0
3,495
Sam
78,015,113
1,920,003
How to run two blocking functions concurrently?
<p>I have two blocking functions, I want them to stay separate, in separate threads or tasks.</p> <pre><code>def foo(): # This can run as a background process while True: # do something # write to disk return data def bar(): # read from the disk that was generated by foo # do something ...
<python><fastapi>
2024-02-18 08:49:22
1
5,375
Lynob
78,014,906
11,861,874
Excel Cell Operation using Python
<p>I am trying to perform cell-by-cell operations in Excel using Python. It's easy to perform using VBA but not sure how can we leverage the same using Python.</p> <p>I have the following data and would like to perform a read-and-write kind of operation. I hope you guys can help me with the same.</p> <pre><code>import ...
<python><excel>
2024-02-18 07:26:04
1
645
Add
78,014,891
3,380,902
sqlalchemy + pandas parameterized query string execution error
<pre><code>import pandas as pd from sqlalchemy import create_engine host = &quot;xxxx.us-west-2.rds.amazonaws.com&quot; user = &quot;user1&quot; pwd = &quot;xxx&quot; database = &quot;db1&quot; engine = create_engine(&quot;mysql+pymysql://{}:{}@{}/{}&quot;.format(user,pwd,host,database), echo=True) query1 = &quot;...
<python><pandas><sqlalchemy>
2024-02-18 07:21:23
1
2,022
kms
78,014,727
13,176,726
AssertionError in django-allauth settings.py during Django application startup
<p>I'm encountering an AssertionError in my Django application when trying to start the development server. The error occurs in the <code>django-allauth</code> package, specifically in the <code>settings.py</code> file. I've already tried reinstalling <code>django-allauth</code>, checking dependencies, and reviewing my...
<python><django><django-allauth>
2024-02-18 06:08:19
2
982
A_K
78,014,684
2,822,041
How to replay keystrokes without modifiers?
<p>Using pynput, I am trying to capture keys and it involves keys like shift-1, cmd-1(i am on macos) etc</p> <p>The problem I am facing is if I were to press shift-1 on my keyboard, it's recorded as shift-! (modified), and when I press shift-2 its recorded as shift-@. Hence when I replay these key strokes, it doesn't w...
<python><python-3.x>
2024-02-18 05:38:36
0
13,738
Someone Special
78,014,487
939,259
How can I use PyTorch 2.2 with Google Colab TPUs?
<p>I'm having trouble getting PyTorch 2.2 running with TPUs on Google Colab. I'm getting an error about a JAX bug, but I'm confused about this because I'm not doing anything with JAX.</p> <p>My setup process is very simple:</p> <pre><code>!pip install torch~=2.2.0 torch_xla[tpu]~=2.2.0 -f https://storage.googleapis.com...
<python><pytorch><google-colaboratory><jax>
2024-02-18 03:36:44
1
11,918
Thomas Johnson
78,014,453
3,166,105
Python errno 13 permission error when reading windows 10 registry hive
<p>I have a simple python script that tries to read the content of a HIVE inside C:\Windows\System32\config. I have given full control on the directory to the user running the script.</p> <p><a href="https://i.sstatic.net/l67dz.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/l67dz.png" alt="enter image d...
<python><windows>
2024-02-18 03:15:59
0
2,036
holybull
78,014,389
721,998
module not found markupsafe
<p>I create a virtual env:</p> <pre><code>&gt; virtualenv -p python3 spectap </code></pre> <p>I activate it and install packages from requirements.txt in it:</p> <pre><code>&gt; . spectap/bin/activate &gt; pip3 install -r requirements.txt </code></pre> <p>Running my flask app in debug mode gives me this error:</p> <pre...
<python><flask><pip><python-3.6>
2024-02-18 02:44:02
0
6,511
Darth.Vader
78,014,380
3,555,115
Combine Dataframes based on specific iiteration number from dataframes
<p>I have two dataframes, df1 and df2, where I would like to combine them based on iteration number from two columns</p> <pre><code>df1 = iteration IOPS Latency 0 1_1 46090 0.7300 1 2_2 12 0.0221 2 3_3 49164 0.1236 3 4_4 98311 0.1318 4 5_5 196604 0.2076 5 6_6 249843 0.1467 6 7_7 298974 ...
<python><pandas><dataframe>
2024-02-18 02:37:12
1
750
user3555115
78,014,354
12,744,116
How do I parallelize a set of matrix multiplications
<p>Consider the following operation, where I take 20 x 20 slices of a larger matrix and dot product them with another 20 x 20 matrix:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np a = np.random.rand(10, 20) b = np.random.rand(20, 1000) ans_list = [] for i in range(980): ans_list.append( ...
<python><numpy><parallel-processing><gpu><cupy>
2024-02-18 02:22:53
2
1,350
anonymous1a