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
⌀
77,260,702
11,246,348
How do I know if my `concurrent.futures.ThreadPoolExecutor` is actually running in parallel?
<p>I am trying to parallelize a for loop that appends to a list using Python using the <code>concurrent.futures.ThreadPoolExecutor</code> class. My code works, but I'm not sure if it's actually <em>doing</em> multithreading. According to Python's documentation <a href="https://docs.python.org/3/library/concurrent.futur...
<python>
2023-10-09 17:19:52
2
887
Max
77,260,645
7,077,532
Write All Filenames in Specific Folder to Pandas Dataframe Table Column
<p>Let's say I have the following folder which contains .txt and .wav audio files.</p> <p><a href="https://i.sstatic.net/CQWRk.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/CQWRk.png" alt="enter image description here" /></a></p> <p>I want to create a dataframe table that has each row of data as one of...
<python><dataframe><import><directory><filenames>
2023-10-09 17:09:12
1
5,244
PineNuts0
77,260,536
4,911,426
Run ADB Shell and then interact with console app in Python
<p>I have a situation where I need to run the <code>adb shell</code> command which takes me to the root access of my device.</p> <p>Then I run the interactive console app against my device using this command: <code>/oem/console --no-logging</code>.</p> <p>The command returns this output:</p> <ul> <li>Console Process: c...
<python><android><python-3.x>
2023-10-09 16:46:51
1
556
Shahboz
77,260,375
13,000,229
`pip install pmdarima` fails due to missing Numpy even though Numpy exists
<h2>Problem</h2> <p><code>pip install pmdarima</code> failed due to <code>ModuleNotFoundError: No module named 'numpy'</code> even though another part of the log says <code>Requirement already satisfied: numpy&gt;=1.21.2 in c:\users\my.name\code\prediction\.venv\lib\site-packages (from pmdarima) (1.26.0)</code>.</p> <p...
<python><numpy><pip><pmdarima>
2023-10-09 16:18:20
2
1,883
dmjy
77,260,253
482,439
VSCode, Django and javascript: Why does VSCode indicate an error when I use {{ }}?
<p>I have the following code that works in my html file:</p> <pre><code> {% for stocks_and_pair_data in stocks_and_pair_data_list %} &lt;script&gt; var ctxClose = document.getElementById('ChartOfClosePrices{{ forloop.counter }}'); new Chart(ctxClose, { type: 'line', ...
<javascript><python><django>
2023-10-09 15:55:52
1
625
AntonioR
77,260,170
2,529,125
dataframe to_excel - versionchanged:: 1.4.0 Zstandard support TypeError: ExcelFormatter.write() got an unexpected keyword argument 'engine_kwargs'
<p>Based on the version used, I am experiencing the following error when writing a pandas dataframe to an excel workbook:</p> <blockquote> <p>File ~\AppData\Local\anaconda3\envs\prod-env-text-bert\Lib\site-packages\pandas\core\generic.py:2345 in to_excel .. versionchanged:: 1.4.0 Zstandard support. TypeError: ExcelForm...
<python><pandas><dataframe>
2023-10-09 15:42:04
0
511
Sade
77,260,102
1,110,328
Python `typing.cast` method vs colon type hints
<p>What the difference between using the Python <code>typing.cast</code> method</p> <pre><code>x = cast(str, x) </code></pre> <p>compared with using type hints/colon notation/left hand side type annotation?</p> <pre><code>x: str </code></pre> <p>I've seen the use of the cast method in codebases but don't have an appare...
<python><python-typing>
2023-10-09 15:31:54
5
1,691
joshlk
77,260,101
14,637
How to use Dask to parallelize up a `sel()` operation in xarray?
<p>I have an array of values called <code>speed</code>, and I'm mapping it to another array of values of the same shape called <code>power</code> by looking up the nearest value in a lookup table <code>speed_to_power_lut</code>. This process takes about 2.5 seconds on my machine, and I want to speed it up.</p> <pre cla...
<python><dask><python-xarray>
2023-10-09 15:31:51
1
183,379
Thomas
77,260,097
2,299,245
Using PySpark Pandas to read in filename with a space in it
<p>trying to read this file:</p> <pre><code>abfss://myaccount@myorganisation.dfs.core.windows.net/perils_database/Bushfire AUSTRALIA - PERILS Industry Exposure Database 2023.xlsx </code></pre> <p>Using this Python code:</p> <pre><code>import pyspark.pandas as ps input_file = &quot;abfss://myaccount@myorganisation.dfs....
<python><apache-spark><pyspark><pyspark-pandas>
2023-10-09 15:31:10
0
949
TheRealJimShady
77,259,950
6,464,947
How do you change a value in a cell from python to excel with the insert python in the new beta channel of Microsoft insider?
<p>I just started with python in excel (the insider beta channel of Microsoft office) and I get how to get a value in a cell into python, but I can't get how to do the opposite: put a value from python into a cell.</p>
<python><excel>
2023-10-09 15:07:30
1
23,563
PythonProgrammi
77,259,947
11,426,624
Add a 2nd header to a pandas dataframe
<p>I have a dataframe</p> <pre><code>df = pd.DataFrame({'col1':[1,2], 'col2':[3,4], 'col3':[5,6], 'col4':[7,8], 'col5':[9,10]}) </code></pre> <p>and would like to add a second header to it such that col1, col2 and col3 go under header1 and col4 and col5 go under header2, so instead of this</p> <pre><code> col1 col2 ...
<python><pandas><dataframe>
2023-10-09 15:07:13
2
734
corianne1234
77,259,921
1,497,139
neo4j.exceptions.ServiceUnavailable Connection to 127.0.0.1:7687 closed without handshake response
<p>I keep getting</p> <pre><code>neo4j.exceptions.ServiceUnavailable: Couldn't connect to localhost:7687 (resolved to ()): Connection to 127.0.0.1:7687 closed without handshake response </code></pre> <p>without a proper explanation why the service is considered to be unavailable. I am using the official neoj4:latest do...
<python><docker><neo4j>
2023-10-09 15:03:31
1
15,707
Wolfgang Fahl
77,259,854
8,661,071
langchain and aws lambda layer in Python
<p>I need to create a lambda layer for lambda using python 3.9 to be deployed in aws lambda.</p> <p>My lambda uses:</p> <ul> <li>langchain.prompts,</li> <li>langchain.retrievers,</li> <li>langchain.llms,</li> <li>langchain.chains</li> </ul> <p>I was force to pin the architecture and Python version because otherwise, pe...
<python><aws-lambda><artificial-intelligence><aws-lambda-layers>
2023-10-09 14:53:42
1
1,349
MasterOfTheHouse
77,259,741
1,256,925
Keras CNN example giving much worse output than stated on example
<p>I am trying to gain some understanding of Keras, by trying to run some of the provided examples (such as <a href="https://github.com/keras-team/keras/blob/tf-keras-2/examples/mnist_cnn.py" rel="nofollow noreferrer">https://github.com/keras-team/keras/blob/tf-keras-2/examples/mnist_cnn.py</a> in this particular case)...
<python><keras><conv-neural-network>
2023-10-09 14:38:25
1
19,172
Joeytje50
77,259,728
996,247
How to organize python package file structure for development and deployment?
<p>For a Python package I am developing, I have my package contents organized under a src/ subdir like so:</p> <pre><code>mylib/ dist/ docs/ src/ __init__.py foo/ __init__.py foo1.py ... bar/ __init__.py bar1.py ...
<python><package><project-organization>
2023-10-09 14:36:34
0
995
Sven
77,259,606
7,819,329
Problem in running an executable file in Python
<p>I have a simple Python code (3.12 version). It just computes the sum of the ASCII's of a name entered by the user:</p> <pre><code>import sys args = sys.argv name=args[1] print(f&quot;Hello, {name}!&quot;) print(&quot;Here is some intelligence that will return a number you will NEVER understand how it is computed :...
<python><subprocess><executable>
2023-10-09 14:20:54
1
1,161
MysteryGuy
77,259,572
4,508,605
Curl command in Python
<p>I am using Python3.9. I have below curl command :</p> <pre><code>curl -x proxy1.req:8080 --location --request POST 'https://auth.trst.com/2.0' \ --header 'Content-Type: application/x-www-form-urlencoded' \ --data-urlencode 'ct_id=33d3e1-4988-9a08-e7773634ba67' \ --data-urlencode 'ct_sec=56GgtoQA8.WIH9nFM3Eh3sT~cwH' ...
<python><python-3.x><variables><curl><token>
2023-10-09 14:15:54
2
4,021
Marcus
77,259,458
13,959,133
Trying to get domain id from Cloudflare, always getting response 400
<p>I'm currently trying to get a list of the domains in a specific Cloudflare zone in order to get the id of a subdomain. I have tried it with the following code but it didn't work:</p> <pre><code>url = CLOUDFLARE_API_URL + CLOUDFLARE_ZONE_ID + '/dns_records?name=' + subdomain headers = { 'Authorization': ...
<python>
2023-10-09 14:00:49
0
387
BestRazer
77,259,343
583,464
remove strings and numbers after new line character in list
<p>I have the following list.</p> <pre><code>mylist = [[ ['K', 'X', 'Y'], ['1', '351822.546', '4521159.92'], ['2', '351846.066', '4521086.924'], ['3', '351873.561', '4521010.066'], ['4', '351922.38', '4521027.586'], ['5', '351923.346', '4521027.937'], ['6', '351880.618', '4521159.601'], ...
<python><list>
2023-10-09 13:45:21
3
5,751
George
77,259,323
19,238,204
Can Sympy Compute Definite Integral By Cases?
<p>This is a heat equation integration problem.</p> <p>So we have <code>u(x,0)</code>, the initial condition, that we want to integrate, that is:</p> <ol> <li><strong>x</strong>, when <code>0 &lt;= x &lt;= 10</code></li> <li><strong>20-x</strong>, when <code>10 &lt;= x &lt;= 20</code></li> </ol> <p>Now, the problem is,...
<python><numpy><sympy>
2023-10-09 13:43:01
1
435
Freya the Goddess
77,259,232
13,174,189
How to test nlu model on multiple requests per second?
<p>I am testing nlu model called LaBSE. I want to know how much gpu memory is required when i run it. Here is example how to run it on sentence and turn it into embeddings:</p> <pre><code>from sentence_transformers import SentenceTransformer sentences = [&quot;This is an example sentence&quot;] model = SentenceTransfo...
<python><python-3.x><deep-learning><transformer-model><sentence-transformers>
2023-10-09 13:29:47
1
1,199
french_fries
77,259,224
2,858,084
langchain conversation completes both human and AI conversation [sometimes]
<p>It happens sometimes, and it happens only with langchain so far. here are few things that can be the problem.</p> <pre><code> prompt = PromptTemplate.from_template( template= role + '''\ \n Current conversation: {history} Human: {input} AI:\ ''') </code></pre> <p>model:</p> <pre><code>...
<python><langchain><large-language-model><py-langchain>
2023-10-09 13:28:22
0
1,347
MAFiA303
77,259,162
8,184,694
How to specify correct dtype for column of lists when creating a dask dataframe from_pandas?
<p>When creating a dask <code>Dataframe</code> with the <code>from_pandas</code> method, the formerly correct dtype <code>object</code> becomes a <code>string[pyarrow]</code>.</p> <pre><code>import dask.dataframe as dd import pandas as pd df = pd.DataFrame( { &quot;lists&quot;: [[&quot;a&quot;, &quot;b&quo...
<python><dask>
2023-10-09 13:17:15
1
541
spettekaka
77,259,096
4,880,184
Python global variables in shared modules
<p>I am trying to understand the behavior of variables shared across modules. My impression was a global variable in one module could be accessed in another, and sometimes this seems to be what happens, but sometimes it is not. (I recognize global variables are usually not the right tool, but there are situations whe...
<python><global>
2023-10-09 13:04:43
1
1,399
John Elion
77,259,092
10,367,360
Textures Segmentation
<p>I need to segment different textures on image without AI or Machine Learning methods, based only on <code>opencv2</code> or <code>skimage</code> (of course python, numpy, etc.).</p> <p>Image:</p> <p><a href="https://i.sstatic.net/5apcP.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/5apcP.png" alt="en...
<python><numpy><opencv><computer-vision><scikit-image>
2023-10-09 13:04:08
0
306
Mark Minerov
77,258,901
9,038,562
Can we use GNN on graphs with only edge features?
<p>I'm trying to use GNN to classify phylogeny data (fully bifucated, single directed trees). I converted the trees from phylo format in R to PyTorch dataset. Taking one of the tree as an example:</p> <p><a href="https://i.sstatic.net/n48b0.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/n48b0.png" alt="...
<python><machine-learning><neural-network><pytorch-geometric><graph-neural-network>
2023-10-09 12:36:47
1
639
Tianjian Qin
77,258,872
4,635,676
Extract all lines between almost the same string in python excluding the last if it contains a different string
<p>I need to extract all the lines between each 'Fetching' string or EOF, including the first 'Fetching', check if it contains <code>40500000</code> and write it to '405' file or else write it a 'Not'. Note there could potentially be hundreds of thousands (or more) of these 'Fetching' strings. My text file excerpt as f...
<python>
2023-10-09 12:31:21
2
436
imp
77,258,737
10,759,785
How can I automatically calculate the derivative of an array based on the best group of points?
<p>I have a group of points like the one below.</p> <pre><code>import numpy as np import matplotlib.pyplot as plt x = np.array([1,1,1,1,2,3,4,4,4,4,4.5,5,5.5,6,6.5,7,7.5,8,8.1,8.2,8.3,8.4,8.5,8.5,8.5,8.5]) y = np.linspace(10,20,len(x)) plt.plot(x*0.1,y,'o', label='x') plt.xlabel('x * 0.1') plt.ylabel('y') </code></pr...
<python><numpy><automation><derivative><integral>
2023-10-09 12:12:28
2
331
Lucas Oliveira
77,258,715
2,386,113
Generate normal noise column-wise using numpy in python
<p>I have a matrix <code>A</code> in which the signals are contained along the columns, I want to generate a noise matrix in which each <strong>column contains Gaussian normal noise</strong> (mean = 0, std = 1).</p> <p><a href="https://i.sstatic.net/SLfI5.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/S...
<python><numpy>
2023-10-09 12:07:48
1
5,777
skm
77,258,711
357,313
Change column in-place with copy-on-write
<p>I have a large DataFrame. I have enabled <a href="https://pandas.pydata.org/docs/user_guide/copy_on_write.html" rel="nofollow noreferrer">copy_on_write</a>, as is expected to be the default for 3.0. I want to limit the values of some of the columns (in-place). Like this:</p> <pre><code>import pandas as pd pd.option...
<python><pandas><in-place><copy-on-write>
2023-10-09 12:07:21
1
8,135
Michel de Ruiter
77,258,698
3,458,788
SettingWithCopyWarning pandas using str.split
<p>I am trying to understand why the <code>SettingWithCopyWarning</code> is appearing here and how I can fix it. Here's my reproducible code:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd grants = pd.read_csv('https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2023/2023-...
<python><pandas><dataframe>
2023-10-09 12:04:38
0
515
cdd
77,258,692
18,904,265
How can I efficiently get multiple slices out of a large dataset?
<p>I want to get multiple small slices out of a large time-series dataset (~ 25GB, ~800M rows). At the moment, this looks something like this:</p> <pre class="lang-py prettyprint-override"><code>from polars import pl sample = pl.scan_csv(FILENAME, new_columns=[&quot;time&quot;, &quot;force&quot;]).slice(660_000_000, 3...
<python><python-polars>
2023-10-09 12:03:38
1
465
Jan
77,258,642
221,270
Feature Importance keras regressionmodel
<p>I am trying to extract the feature importance or saliency map from my keras regression model:</p> <pre><code>import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler import tensorflow as tf from tensor...
<python><keras>
2023-10-09 11:55:47
1
2,520
honeymoon
77,258,525
5,273,308
Importing a Cython object into a Python file
<p>I have code in two files, one of which imports the other. File1</p> <h1>parameters.pyx</h1> <pre><code>cdef class Parameters: cdef int myInt def __init__(self, int myInt): self.myInt = myInt cdef set_myInt(self, int value): self.myInt = value cdef int get_myInt(self): retur...
<python><class><cython>
2023-10-09 11:37:11
1
1,633
user58925
77,258,483
2,520,186
OpenCV: Prepare angle-based kernel for erosion
<p>I have an image that contains several straight lines at various angles (e.g. horizontal, vertical, diagonal, cross-diagonal). I have a code that can filter the lines in a desired direction since I know how to set a kernel matrix for horizontal, vertical, diagonal, and cross-diagonal directions. However, for lines at...
<python><opencv><image-processing><filtering><mathematical-morphology>
2023-10-09 11:30:52
1
2,394
hbaromega
77,258,241
13,280,838
What is the behaviour/internal working of a normal python function in Spark/Databricks
<p>Hope you are all doing well.</p> <p>Once again request your help in understanding a very small concept which continues to confuse me.</p> <p>Say I have a databricks notebook with few cells. In cell 1, I have a small python function</p> <pre class="lang-py prettyprint-override"><code>from dateutil import tz def getCu...
<python><apache-spark><pyspark><apache-spark-sql><databricks>
2023-10-09 10:57:27
1
669
rainingdistros
77,258,199
19,238,204
How to Replace the Variable from Sympy Computation so it can be Plotted with Matplotlib and Numpy?
<p>I have this computation (integral and then summation)</p> <p>The result is <code>s</code> it is in term of independent variables <code>x</code> and <code>t</code>.</p> <p>But, when I try to define it as <code>u(x,t)</code> with <code>return s</code>, it cannot replace the <code>x</code> variable with the one I defin...
<python><numpy><matplotlib><sympy>
2023-10-09 10:50:02
1
435
Freya the Goddess
77,258,198
5,743,692
Full list symbols stripped with str.strip() by default
<p>As said in <a href="https://docs.python.org/3/library/stdtypes.html?highlight=str%20strip#str.strip" rel="nofollow noreferrer">documentation</a>:</p> <blockquote> <p>str.strip([chars])<br /> Return a copy of the string with the leading and trailing characters removed. The chars argument is a string specifying the se...
<python><string><strip><removing-whitespace>
2023-10-09 10:49:59
3
451
Vasyl Kolomiets
77,258,190
4,171,008
Expert system using PyDatalog to model and infer various family relations
<p>I'm working on an expert system using <code>PyDatalog</code> to model and infer various family relations.</p> <p>This is the data used (loaded from a CSV file):</p> <pre><code> name father_name mother_name gender 0 Ahmad Bachar Rafah Male 1 Amjad Bachar Rafah Male 2 ...
<python><python-3.x><pydatalog>
2023-10-09 10:49:17
1
1,884
Ahmad
77,258,119
15,468,925
Why docker-entrypoint.sh is not being found within the directory?
<p>I'm running a Flask app in Docker using docker-compose:</p> <pre><code>version: '3.7' services: users: build: context: ./services/users dockerfile: Dockerfile volumes: - './services/users:/usr/src/app' ports: - 5001:5000 environment: - FLASK_ENV=developmen...
<python><docker><docker-compose>
2023-10-09 10:35:39
0
305
itsallgood
77,258,114
12,428,848
How to address N+1 problem in django with prefetch related?
<p>With the following code I am getting N numbers of queries based on the loop. How to avoid that ?</p> <p>I tried using prefetch_related but that didn't worked or am i doing the wrong way ?</p> <p>models</p> <pre><code>class Product(models.Model): name = models.CharField() .... class ProdcutOffer(models.Model): ...
<python><django><query-optimization>
2023-10-09 10:34:46
2
862
D_P
77,258,097
16,383,578
How to programmatically open QComboBox dropdown in PyQt6
<p>I want to make a QComboBox automatically open its dropdown menu at program start-up and without mouse clicking, and the menu should stay open indefinitely, with a cell being highlighted.</p> <p>I want to do this because I am writing a widget to customize the stylesheets of every single GUI component of an applicatio...
<python><pyqt><pyqt6><qcombobox>
2023-10-09 10:31:46
1
3,930
Ξένη Γήινος
77,258,063
1,833,326
Pydantic Version 2: Check for complex fields
<p>I would like to migrate from <code>pydantic</code> Version &gt;1,&lt;2 to Version &gt;2. However, I cannot find a solution how to check for complex fields using the newest Version (currently V2.4.2)</p> <p>Here is the code that worked with the &quot;legacy&quot; <code>pydantic</code>:</p> <pre><code>from pydantic im...
<python><pydantic>
2023-10-09 10:26:19
0
1,018
Lazloo Xp
77,257,989
4,267,439
Python subprocess communicate hangs calling an external program, which ask for a keypress at the end
<p>I'm trying to integrate <a href="https://johndfenton.com/Steady-waves/Fourier.zip" rel="nofollow noreferrer">this</a> executable in a python program. Basically the executable is a console application, it does some calculations based on input files, print some results on console and writes a couple of text files, the...
<python><subprocess>
2023-10-09 10:12:54
0
2,825
rok
77,257,983
13,793,478
python Dict operation for flask
<p>how to add (sum) all the pnl values of the dictionaries with the same date</p> <p>from this <code>[{'pnl': 10, 'date': 2}, {'pnl': 30, 'date': 2}, {'pnl': 20, 'date': 3}]</code></p> <p>To this <code>[{'pnl': 40, 'date': 2}, {'pnl': 20, 'date': 3}]</code></p>
<python>
2023-10-09 10:12:22
1
514
Mt Khalifa
77,257,954
502,144
How to use common expression elimination together (CSE) with codegen
<p>I'm trying to use sympy.utilities.codegen. I need compute a complicated function and its derivative. As a simplified example the function <code>f</code> is</p> <pre class="lang-py prettyprint-override"><code>x = Symbol('x') y = Symbol('y') f = 1 / (x - y) df = f.diff(x) [(_, c_code), _] = codegen([('f', f), ('df', d...
<python><sympy><code-generation><abstract-syntax-tree>
2023-10-09 10:07:29
1
3,744
fdermishin
77,257,750
22,466,650
How to move up values in specific columns as long as possible?
<p>My input is this dataframe :</p> <pre><code>df = pd.DataFrame({'class': ['class_a', 'class_a', 'class_a', 'class_a', 'class_b', 'class_b', 'class_c', 'class_c', 'class_d'], 'id': ['id1', 'id2', 'id3', '', '', 'id4', 'id5', '', 'id6'], 'name': ['abc1', '', '', 'abc2', 'abc3', '', '', 'abc4', 'abc5']...
<python><pandas>
2023-10-09 09:36:59
2
1,085
VERBOSE
77,257,739
1,632,812
iteratively selecting a subset of a model by select fields in odoo 14
<p>I have a model</p> <p>I need to provide 4 select fields</p> <p>The values choosen in the first select field will be used to calculate a subset of the model to show in the second select fiedl</p> <p>the valued choosen in the second select field will be used to calculate a subset of the model to show in the third sele...
<python><odoo><odoo-14>
2023-10-09 09:35:48
1
603
user1632812
77,257,710
2,386,113
How to multiply rows with corresponding columns in Python (cuPy/Numpy)?
<p>I need to multiply each row with a column at the corresponding row-index. Consider the graphics below in which I have a <code>3 x 3</code> matrix. The required operation is to multiply the <code>row[0]</code> of matrix with <code>col[0]</code> of <code>transposed_matrix</code>, <code>row[1]</code> of matrix with <c...
<python><python-3.x><numpy><cupy>
2023-10-09 09:30:29
3
5,777
skm
77,257,598
206,253
Chaining dataframe sort in pandas produces unexpected result
<p>This is the dataframe <code>activity</code>:</p> <pre><code>| player_id | device_id | event_date | games_played | | --------- | --------- | ---------- | ------------ | | 1 | 2 | 2016-03-01 | 5 | | 1 | 2 | 2016-05-02 | 1 | | 1 | 3 | 2015-06-25 | 2 ...
<python><pandas>
2023-10-09 09:17:40
2
3,144
Nick
77,257,474
6,839,048
how to find the largest subsets of a correlation matrix whose correlation are below a given value?
<p>I used following code to get a correlation matrix.</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame(np.random.rand(20,4)) df = df.corr() </code></pre> <p>say the df is as below</p> <pre><code> 0 1 2 3 0 1.000000 -0.156813 0.294344 -0.034569 1 -0.156813 1.000000 -0...
<python><pandas><algorithm>
2023-10-09 08:58:18
1
321
Lei Yu
77,257,099
2,695,082
Link a dll with a static library containing boost python import code causing the application to crash
<p>I have created a static library containing a function used to import a module :</p> <pre><code>void callFn() { _putenv_s(&quot;PYTHONPATH&quot;, &quot;.&quot;); Py_Initialize(); namespace python = boost::python; try { python::object my_python_class_module = python::import(&quot;pythonFile&quot;); ...
<python><c++><python-3.x><boost>
2023-10-09 07:54:42
1
329
user2695082
77,257,048
951,757
how to transform pandas dataframe by type
<p>I have python dataframe like below</p> <pre><code> index date hour type tiantan 2014-01-01 00:00:00 20140101 0 PM2.5 32.0 2014-01-01 00:00:00 20140101 0 PM10 110.0 2014-01-01 01:00:00 20140101 1 PM2.5 56.0 2014-01-01 01:00:00 20140101 1 PM10 126.0 </code></pre> <p>...
<python><pandas><dataframe>
2023-10-09 07:47:27
1
45,630
billz
77,257,035
188,331
Exception: Custom Normalizer cannot be serialized
<p>I'm using a custom normalizer for my custom tokenizer.</p> <p>The custom normalizer is as follows:</p> <pre><code>class CustomNormalizer: def normalize(self, normalized: NormalizedString): # Most of these can be replaced by a `Sequence` combining some provided Normalizer, # (ie Sequence([ NFKC(),...
<python><huggingface-tokenizers>
2023-10-09 07:44:14
1
54,395
Raptor
77,256,848
19,238,204
How to Implement Sum with Substitute in For Loop with Python
<p>I have the computation of integral with a lot of symbolic variables <strong>x,t,n.</strong></p> <p>After I get <code>g</code> function in terms of <strong>x,t,n</strong>. I want to do summation with for loop to replace the <strong>n</strong> variable into value.</p> <p>The command <code>g.subs({n:c})</code> is not w...
<python><sympy>
2023-10-09 07:07:30
1
435
Freya the Goddess
77,256,804
12,881,307
pandas json normalize directly from file
<p>I am writing a wrapper class for <code>pymongo</code>. The main functionality I am aiming for is for it to be compatible with <code>pandas</code>, so that I can do this:</p> <pre class="lang-py prettyprint-override"><code>from loader import PyMongoLoader import pandas as pd _loader = PyMongoLoader(url=&quot;my_url...
<python><json><pandas><pymongo>
2023-10-09 06:57:57
1
316
Pollastre
77,256,712
7,585,973
Pandas dataframe has 0 column after `pandas.read_json()` even the json have value
<p>I have JSON file that consist of one json file that consist of 1 object, 36 key, and each key have single value (not a nested object)</p> <pre><code>{ ... &quot;created_at&quot;: &quot;Sat Apr 14 11:15:29 +0000 2012&quot;, &quot;description&quot;: &quot;Pemerhati sospol hukum dan ekonomi&quot;, &quot;is_tran...
<python><json><pandas>
2023-10-09 06:40:14
1
7,445
Nabih Bawazir
77,256,626
2,170,269
Type-annotating a curry function
<p>I'm having a problem annotating a curry function correctly. I use <code>Concatenate</code> and <code>ParamSpec</code> to catch the first argument to extract, and then I return a function from that. However, <code>mypy</code> complains when I try to call the function. A minimal example looks like this:</p> <pre class...
<python><mypy>
2023-10-09 06:21:28
0
1,844
Thomas Mailund
77,256,543
19,506,623
How to print list in grid format with continuous lines?
<p>I´m looking for way to print (plot) one or more grid with continuous lines and within each square the values from NxN list. I found something similar in <a href="https://stackoverflow.com/questions/20368413/draw-grid-lines-over-an-image-in-matplotlib">this</a> thread, but in that case they are loading an image.</p> ...
<python><grid>
2023-10-09 06:03:34
0
737
Rasec Malkic
77,256,470
211,858
How to use aws encryption sdk against localstack kms?
<p>I would like to use the python aws encryption sdk to encrypt and decrypt text. I would like to test my code locally against an instance of kms provided by localstack. I have <code>localstack</code> running in a docker image. Below is some sample code. How does one point the <code>EncryptionSDKClient</code> to the km...
<python><amazon-web-services><amazon-kms><localstack>
2023-10-09 05:42:13
0
1,459
hwong557
77,256,367
1,422,058
How can I calculate overlaps in Pandas dataframe scoped to groups
<p>I want to extract overlapping events in an dataframe which contains a grouping criteria of the events.</p> <pre><code>df = pd.DataFrame({ 'id': [1, 2, 3, 4, 5, 6, 7, 8], 'group': ['a', 'a', 'a', 'a', 'a', 'b', 'b', 'b'], 'event': ['event1', 'event2', 'event3', 'event4', 'event5', 'event6', 'event7', 'eve...
<python><pandas>
2023-10-09 05:06:42
1
1,029
Joysn
77,256,337
10,480,181
Different dataclass object show equal
<p>I have a simple dataclass with 3 member variables. When I create two different objects for the class and check for equality it always comes out True even if the values for the member variables is different.</p> <p><strong>Data Class:</strong></p> <pre><code>@dataclass(init=False) class DiagCodes: __slots__ = [&q...
<python><python-dataclasses>
2023-10-09 04:55:05
1
883
Vandit Goel
77,256,079
3,492,125
XSD unit test in python / sql
<p>I'm working on a data feed for an external partner. The partner defined a huge XSD schema for the XML data to be fed to them. The concep is that they'll send me a user id, and I'll send them an XML file containing data that's relevant to the user. The XML file may contains various sub-components and each component m...
<python><xml><unit-testing><xsd>
2023-10-09 03:07:51
1
3,062
Lee
77,256,043
2,981,639
Celery circular import
<p>I'm using celery in a streamlit application, and whilst reading the documentation the <a href="https://docs.celeryq.dev/en/stable/getting-started/next-steps.html" rel="nofollow noreferrer">example</a> they present doesn't make sense to me - it seems that it will always result in a circular import error</p> <p>The pr...
<python><celery>
2023-10-09 02:53:35
0
2,963
David Waterworth
77,256,028
754,136
Multiple defaults in Hydra from command line
<p>I have the following folder structure</p> <pre><code>configs |------- default.yaml |------- setting_A.yaml |------- setting_B.yaml |------- a bunch of folders </code></pre> <p>My <code>default.yaml</code> is</p> <pre><code>defaults: - agent: default # - setting_A # - setting_B other configs from subfolders </...
<python><fb-hydra>
2023-10-09 02:47:58
1
5,474
Simon
77,255,766
482,439
How to pass a list of dates from Django ORM to a javascript date list to use as labels in chart.js
<p>I'm trying to plot some charts comparing the close price of pairs of stocks in a timeline.</p> <p>My Django view.py function looks like this:</p> <pre><code> # Access stock pairs for the user settings stock_pairs = StockPair.objects.filter(setting=setting) # Create a context dictionary including, for ea...
<javascript><python><django>
2023-10-09 00:21:57
1
625
AntonioR
77,255,760
22,407,544
Why is my Django view not automatically downloading a file
<p>My view transcribes a file and outputs the SRT transcript. Then it locates and is supposed to auto download theT transcript but nothing happens after transcription completes(the file was submitted on a previous page that uses the transcribeSubmit view. The view that handles and returns the file is the initiate_trans...
<javascript><python><html><django><file>
2023-10-09 00:17:47
0
359
tthheemmaannii
77,255,758
20,235,789
How can I mock my environment variables for my pytest?
<p>I've looked at some examples to mock environment variables. <a href="https://adamj.eu/tech/2020/10/13/how-to-mock-environment-variables-with-pytest/" rel="noreferrer">Here</a></p> <p>In my case, I have to mock a variable in my <code>config.py</code> file that is setup as follows:</p> <pre><code>class ServiceConfig(B...
<python><pytest><pydantic><pytest-mock-patch>
2023-10-09 00:15:49
4
441
GustaMan9000
77,255,588
897,272
Python tab completion without defining arguments directly in class as required by cmd
<p>We have a command line interface for our program written in python. We want to add tab completion to this interface. the cmd module seems the obvious choice, except for one problem. It requires all the possible arguments to be defined right in the class in the form of methods.</p> <p>We have a number of commands ...
<python><command-line-interface><python-3.9>
2023-10-08 22:48:28
1
6,521
dsollen
77,255,552
15,781,591
How to make bar chart that shows percent change with fainter color on same bar in python
<p>I have the following dataframe that shows dollar cost associated with each color hat:</p> <pre><code> Hat Dollars ---------------------- 0 Blue 33 1 Green 42 2 Red 54 </code></pre> <p>And so the blue hat costs $33, the green hat costs $42, and the red hat costs $54.</p> ...
<python><pandas><matplotlib><seaborn>
2023-10-08 22:29:25
1
641
LostinSpatialAnalysis
77,255,536
8,782,672
How to execute an mpiexec command from ansible (ad-doc or playbook)
<p>How to run <code>mpiexec -host node1,node2,node3,node4 python3 hello_mpi.py</code> from ansible either using script or shell module where hello_mpi.py file resides on the ansible executor (local machine not the server where it is executed). I know you can use script module for a script on your local machine that nee...
<python><shell><ansible><mpi><mpi4py>
2023-10-08 22:24:04
0
574
Coddy
77,255,463
8,081,835
PyCharm Not Launching After macOS Update to Sonoma 14.0
<p>I am encountering issues with PyCharm following the latest macOS Sonoma 14.0 update. Here are the problems I'm facing:</p> <ul> <li>PyCharm is not appearing in Spotlight Search.</li> <li>When I attempt to run PyCharm from the JetBrains Toolbox, it doesn't open.</li> <li>When running from iTerm using <code>pycharm .<...
<python><macos><pycharm>
2023-10-08 21:50:05
1
771
Mateusz Dorobek
77,255,420
22,674,380
Keras training ValueError: setting an array element with a sequence. The requested array has an inhomogeneous shape after 3 dimensions
<p>I'm trying to train a simple binary classification model using <code>Keras</code> and <code>Tensorflow</code> on a dataset of around 21,000 images. But when I run the training code, it throws this error:</p> <pre><code>Traceback (most recent call last): File &quot;train.py&quot;, line 83, in &lt;module&gt; tra...
<python><numpy><tensorflow><keras><deep-learning>
2023-10-08 21:35:01
1
5,687
angel_30
77,255,391
1,422,096
Higher-level than socket functions with Python?
<p>I'm doing a client/server communication with Python <code>socket</code>:</p> <pre><code>for i in range(10): connection.send(f&quot;{i} and some other data\n&quot;.encode()) # real data is more complex connection.send(b&quot;OK, finished&quot;) </code></pre> <p>On the other side, I receive it with:</p> <pre><cod...
<python><sockets><tcp>
2023-10-08 21:24:37
0
47,388
Basj
77,255,341
10,065,556
Interning objects in shell and .py file
<p>In Python shell if we do:</p> <pre class="lang-bash prettyprint-override"><code>&gt;&gt;&gt; a = 98765 &gt;&gt;&gt; b = 98765 &gt;&gt;&gt; a is b &gt;&gt;&gt; False </code></pre> <p>However, when we run the following .py file:</p> <pre class="lang-py prettyprint-override"><code>a = 98765 b = 98765 print(a is b) </co...
<python><memory-management>
2023-10-08 21:05:09
0
994
ScriptKiddieOnAComputer
77,255,242
7,212,809
How to get number of workers available in ProcessPoolExecutor?
<p>I am running some cpu bound code inside an async function, using <code>ProcessPoolExecutor</code></p> <pre><code>pool = concurrent.futures.ProcessPoolExecutor(10) ... loop.run_in_executor( pool, cpu_bound_func) </code></pre> <p><strong>How do I get the number of workers available to be used?</strong></p...
<python><python-3.x><proc>
2023-10-08 20:33:52
1
7,771
nz_21
77,255,095
15,140,144
How to suppress mypy error: "some/path/to/module" shadows library module "module"
<p>I'm well aware that normally you wouldn't want to suppress this error, but my case is special. I'm &quot;poly-filling&quot; <a href="https://skulpt.org" rel="nofollow noreferrer">skulpt</a> with some modules that it lacks in stdlib (&quot;typing&quot; and &quot;typing_extensions&quot; to be exact). How can I suppres...
<python><mypy><error-suppression><skulpt>
2023-10-08 19:47:01
0
316
oBrstisf8o
77,254,892
4,932,316
Finding and replacing match for exact abbreviations using Regex in Python
<p>I have a <code>REPLACEMENTS</code> dictionary whose keys are the strings that I want to find <strong>exactly</strong>. Then I want to replace them with their corresponding dictionary values.</p> <p>For example,</p> <pre><code>REPLACEMENTS = dict([('max.' , ' maximum '), ('inkl.' , ' inklusive ')...
<python><python-3.x><regex>
2023-10-08 18:44:52
1
39,202
Sheldore
77,254,887
7,657,180
Decode Arabic characters cid mapping
<p>I am trying to decode a string of Arabic characters using the following code some characters are not replaced correctly and the spaces are not right at all</p> <pre><code>char_code_mapping = { &quot;(cid:993)&quot;: &quot;م&quot;, &quot;(cid:987)&quot;: &quot;ك&quot;, &quot;(cid:931)&quot;: &quot;ح&quot;...
<python>
2023-10-08 18:43:34
1
9,608
YasserKhalil
77,254,868
219,153
Inconsistent results of NumPy memory allocation
<p>This Python 3.11 script on Ubuntu 22.04 with about 16.4GB memory available (no swap file):</p> <pre><code>import numpy as np, psutil print(f'{psutil.virtual_memory().available:,}') try: a = np.empty((100_000_000_000), dtype='u1') # variant A # a = np.empty((30_000_000_000), dtype='u1') # variant B # a = np...
<python><arrays><numpy><out-of-memory><allocation>
2023-10-08 18:38:27
0
8,585
Paul Jurczak
77,254,777
13,123,667
Alternative to .concat() of empty dataframe, now that it is being deprecated?
<p>I have two dataframes that can both be empty, and I want to concat them.</p> <p>Before I could just do :</p> <pre><code>output_df= pd.concat([df1, df2]) </code></pre> <p>But now I run into</p> <blockquote> <p>FutureWarning: The behavior of DataFrame concatenation with empty or all-NA entries is deprecated. In a futu...
<python><pandas><dataframe><concatenation>
2023-10-08 18:12:04
8
896
Timothee W
77,254,706
1,034,974
aggregate calculation vmap jax
<p>I'm trying to implement fast routine to calculate array of energies and find the smallest calculated value and its index. Here is my code that is working fine:</p> <pre class="lang-py prettyprint-override"><code>@jit def findMinEnergy(x): def calcEnergy(a): return a*a # very simplified body, it is actually 15...
<python><numpy><jax>
2023-10-08 17:51:40
2
348
Terry
77,254,697
4,505,998
View numpy array of pairs as tuples
<p>I have an array of pairs of size (N,2), and I want to convert them to tuples to be able to perform an <code>isin</code> operation.</p> <p>I tried using <code>view</code>, but it doesn't seem to work:</p> <pre class="lang-py prettyprint-override"><code>coo = np.array([[1,2],[1,6],[5,3],[3,6]]) # coordinates coo.view(...
<python><numpy><numpy-ndarray>
2023-10-08 17:49:19
0
813
David Davó
77,254,506
15,111,105
Python thread started but stuck because of twisted reactor in other thread (possibly)
<p>Trying to make an API based on twisted work (<a href="https://github.com/spotware/OpenApiPy" rel="nofollow noreferrer">https://github.com/spotware/OpenApiPy</a>)</p> <p>Here is some incomplete code that starts a <code>twisted reactor</code>:</p> <pre class="lang-py prettyprint-override"><code>def onError(failure): ...
<python><python-multithreading><twisted>
2023-10-08 16:59:18
1
311
wiktor
77,253,733
2,386,113
Memory leak with cuPy (CUDA in Python)
<p>I am using raw CUDA kernels in python scripts. In the below MWE, I have a super simple raw kernel which is not doing anything. In the code below, I am simply creating a large array (around 2 GB) and passing it to the CUDA kernel.</p> <p><strong>MWE (Python - cupPy, Not Working):</strong></p> <pre><code>import numpy ...
<python><cuda><cupy>
2023-10-08 13:07:11
1
5,777
skm
77,253,713
10,353,865
calling loc with a boolean array containing NA
<p>The pandas doc on loc states that it can be used with boolean arrays, more specifically it states the following:</p> <p><em>&quot;Allowed inputs are: ... A boolean array (any <code>NA</code> values will be treated as <code>False</code>).&quot;</em></p> <p>My question: How can u create a boolean array containing NA-v...
<python><pandas><dataframe>
2023-10-08 13:00:48
2
702
P.Jo
77,253,645
402,281
Why is __get__() specified to have an optional third argument?
<p>The <a href="https://docs.python.org/3/howto/descriptor.html#descriptor-protocol" rel="nofollow noreferrer">Descriptor HowTo Guide (Descriptor protocol)</a> specifies that <code>__get__()</code> must be callable with 2 and 3 arguments:</p> <pre><code>descr.__get__(self, obj, type=None) -&gt; value </code></pre> <p>W...
<python><python-descriptors>
2023-10-08 12:39:34
1
10,085
Feuermurmel
77,253,558
9,206,337
LocalEntryNotFoundError while building Docker Image with Hugging Face model
<p>I am trying to create a AWS Lambda function using Docker Image as source. I am executing the following code as part of the image build phase to download all the dependencies</p> <pre class="lang-py prettyprint-override"><code>import logging logging.basicConfig(level=logging.DEBUG) from langchain.embeddings import Hu...
<python><docker><aws-lambda><dockerfile><huggingface-transformers>
2023-10-08 12:12:15
1
1,060
Fardeen Khan
77,253,135
2,312,666
python string characters to key and value?
<p>I'm doing something wrong here, but not sure what. I would like to be able to iterate through the characters of a string, see if the characters match a key in a dictionary and if so return the corresponding value.</p> <pre><code>string = 'happy' dictionary = { &quot;A&quot;:&quot;10&quot;,&quot;B&quot;:&quot;20&...
<python><string><dictionary>
2023-10-08 09:57:02
2
309
yeleek
77,253,088
10,919,370
Python variable annotation and syntax error on version < 3.6
<p>I have next line</p> <pre><code>status_dict : dict = result.get('status', {}) </code></pre> <p>I'm using the variable annotation, to make my codding easier after that (autocompletion). It works perfect on python &gt;= 3.6, but on older versions I get</p> <pre><code>File &quot;/home/marcel/work/py/svn_utils.py&quot;...
<python><python-typing>
2023-10-08 09:45:00
0
1,215
Marcel Preda
77,253,053
20,892,267
Two way communication between two Processes python
<p>I am running two classes on two different processes. I am able to set up one way communication and Initiate my <code>run</code> method of Runner class via GUI class.</p> <p>My requirement is once <code>run</code> method finishes its job the GUI class should initiate <code>terminate</code> method.</p> <p><strong>Note...
<python><tkinter><multiprocessing>
2023-10-08 09:33:04
1
332
Roshan Shetty
77,252,899
8,547,986
what is the recommended way to use `not` in python?
<p>I have observed that both of the following expression works and would like to know which is the recommended way to use and why?</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; not(True) False &gt;&gt;&gt; not True False </code></pre> <p>Coming from functional programming background (I have experienc...
<python><python-3.x>
2023-10-08 08:45:36
3
1,923
monte
77,252,880
4,502,721
File executable not working on Raspberry Pi
<p>I have a .py file (<code>camera.py</code>) that is programmed to capture images from a USB camera connected to the Raspberry Pi. The <code>camera.py</code> file is below and is running as expected from the terminal of the Raspberry Pi.</p> <pre><code>import cv2 cam = cv2.VideoCapture(0) while True: ret, image ...
<python><opencv><raspberry-pi><debian><glibc>
2023-10-08 08:37:07
2
335
Amrita Deb
77,252,705
4,281,353
How to exactly match a word with one regexp?
<p>Using Python 3.9.13.</p> <p>How can I match an exact word without preceding or trailing character with a simple one regexp expression?</p> <p>There are answers using the boundary word <code>\b</code>. However, according to the <a href="https://docs.python.org/3/library/re.html#regular-expression-syntax" rel="nofollo...
<python><regex>
2023-10-08 07:31:44
1
22,964
mon
77,252,602
8,971,938
Is there a table widget for Shiny for python that calls back edited cells?
<p>Similar question to <a href="https://stackoverflow.com/questions/76579007/is-there-an-interactive-table-widget-for-shiny-for-python-that-calls-back-select">Is there an interactive table widget for Shiny for python that calls back selected rows?</a>, but slightly different: Instead of just selecting rows (and getting...
<python><py-shiny>
2023-10-08 06:50:44
1
597
Requin
77,252,333
10,565,820
SSL error with Zeep - how to change cipher suite?
<p>I am trying to use Zeep to load a WSDL file, but when I do, I receive the following error:</p> <pre><code>requests.exceptions.SSLError: HTTPSConnectionPool(host='api-mte.itespp.org', port=443): Max retries exceeded with url: /markets/VirtualService/v2/?WSDL (Caused by SSLError(SSLError(1, '[SSL: DH_KEY_TOO_SMALL] dh...
<python><ssl><openssl><wsdl><zeep>
2023-10-08 04:34:55
1
644
geckels1
77,252,144
15,587,184
How to calculate deltas and percentage changes in Pandas grouping on date by specific conditions
<p>I have a dataset named df with the following structure:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>date</th> <th>word</th> <th>total</th> <th>top</th> </tr> </thead> <tbody> <tr> <td>14/10/2023</td> <td>python</td> <td>52</td> <td>5</td> </tr> <tr> <td>15/10/2023</td> <td>python</td...
<python><pandas><group-by><data-wrangling>
2023-10-08 02:51:55
2
809
R_Student
77,252,117
10,650,942
What is the difference between built-in sum() and math.fsum() in Python 3.12?
<p>In the <a href="https://docs.python.org/3/whatsnew/3.12.html#other-language-changes:%7E:text=sum()%20now%20uses%20Neumaier%20summation" rel="nofollow noreferrer">What's New document</a> for 3.12 there is a point:</p> <blockquote> <p>sum() now uses Neumaier summation to improve accuracy and commutativity when summing...
<python><sum><python-3.12>
2023-10-08 02:37:46
1
2,915
Andrey Semakin
77,251,901
14,509,604
Pydantic.BaseModel.model_dump() through's AttributeError
<p>I'm trying to use <code>Pydantic.BaseModel.model_dump()</code> but when I call it <code>AttributeError: type object 'BaseModel' has no attribute 'model_dump'</code> raises. Also tried it instantiating the <code>BaseModel</code> class. The thing is that the vscode hint tool shows it as an available method to use, and...
<python><fastapi><pydantic>
2023-10-08 00:19:53
1
329
juanmac
77,251,865
6,197,439
Python subprocess (calling gdb) freezes when called from make?
<p>Ok, this is a tricky one.</p> <p>I have a CMake project to build an executable, and then I have a separate independent &quot;target&quot; which lets me run a Python script which uses subprocess to call <code>gdb</code> and to inspect this executable. Note that I run all of this in a MINGW64 (MSYS2) <code>bash</code>...
<python><subprocess><gdb>
2023-10-07 23:55:40
1
5,938
sdbbs