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
76,276,568
11,154,841
How can I reuse logic to handle a keypress and a button click in Python's tkinter GUI?
<p>I have this code:</p> <pre class="lang-py prettyprint-override"><code>from tkinter import * import tkinter as tk class App(tk.Frame): def __init__(self, master): def print_test(self): print('test') def button_click(): print_test() super().__init__(master) ...
<python><user-interface><tkinter><tkinter-entry><tkinter-button>
2023-05-17 22:26:54
2
9,916
questionto42
76,276,528
1,850,272
Element found but it's not clicked and the test fails
<p>I'm creating an automated test using amazon's website and I have to navigate to the &quot;sign up&quot; page. The link to register an account is in a menu that only pops up when you hover over the sign in link. When I type the following in the terminal I get the result I need</p> <pre><code>$$(&quot;a.nav-a[href*=...
<python><selenium-webdriver>
2023-05-17 22:17:28
1
3,354
Optiq
76,276,514
3,380,902
Spark DataFrame casting string to date results in null values
<p>I get <code>null</code> when I attempt to cast string date in Spark DataFrame to <code>date</code> type.</p> <pre><code># Create a list of data data = [(1, &quot;20230517&quot;), (2, &quot;20230518&quot;), (3, &quot;20230519&quot;), (4, &quot;null&quot;)] # Create a DataFrame from the list of data df = spark.create...
<python><apache-spark><apache-spark-dataset>
2023-05-17 22:12:50
1
2,022
kms
76,276,484
5,296,106
Sum of element wise or on columns triplet
<p>I have a NumPy array <code>A</code> of shape <code>(n, m)</code> and dtype <code>bool</code>:</p> <pre><code>array([[ True, False, False, False], [ True, False, False, True], [False, True, False, False], [False, False, False, True], [False, False, False, True]]) </code></pre> <p>I wou...
<python><numpy>
2023-05-17 22:05:58
1
15,494
Riccardo Bucco
76,276,258
4,581,822
lxml parse doesn't recognize Indexing
<p>I am trying to scrape and parse some HMLT with Python and extract Italian fiscal code 'VTLLCU86S03I348V'.</p> <p>If I inspect the page and copy the full xPath of that object I get no results and I do not understand why. I tried with normal xpath like '//div/p/a' for example and it worked. Things become messy when th...
<python><web-scraping><xpath><python-requests><lxml>
2023-05-17 21:16:14
1
7,210
SabDeM
76,276,165
5,296,106
Number of different elements for each columns pair
<p>I have a NumPy array <code>A</code> of shape <code>(n, m)</code> and dtype <code>bool</code>:</p> <pre><code>array([[ True, False, False], [ True, True, True], [False, True, True], [False, True, False]]) </code></pre> <p>I would like to get the result <code>R</code> of shape <code>(m, m)</c...
<python><numpy>
2023-05-17 21:01:29
2
15,494
Riccardo Bucco
76,275,890
1,927,834
Custom Library import reload in Robot Framework
<p>I am in a bit of a bind and looking for a solution to the following problem. I will present the code first.</p> <pre><code>*** Settings *** Library Widget.py ${FIRSTNAME} ${LASTNAME} WITH NAME toy *** Variables *** ${FIRSTNAME} john ${LASTNAME} doe *** Test Cases *** Test Case 1 ${fullname...
<python><robotframework>
2023-05-17 20:13:06
0
361
utpal
76,275,867
7,895,542
How to clean up this directory traversal?
<p>I have the following directory structure that i want to traverse and call a function on each (loaded) file if the directories and file pass certain criteria</p> <pre><code>self.directories[0] │ └───maps_dir_1 │ │ file1.json │ │ file2.txt │ │ file3.json │ └───subfolder1 │ │ file111.txt │ ...
<python><directory>
2023-05-17 20:10:09
1
360
J.N.
76,275,859
1,329,652
Is there an easy way to add custom error messages in pyparsing?
<p>Suppose we have a grammar where there is an element that was expected but is not found. Assume that the backtracking is disabled, i.e. the element is preceded by a <code>-</code> sign.</p> <p>Is there any way in the library to set a custom error message, such as &quot;Foo was needed&quot;, on that element? Or is the...
<python><pyparsing>
2023-05-17 20:08:37
1
99,011
Kuba hasn't forgotten Monica
76,275,721
1,471,980
how do you update data dictionary in python
<p>I am going through a json file and extracing &quot;name&quot; and &quot;id&quot; field. I need to form a data dictionary and store &quot;name&quot; and &quot;id&quot; fields in data dictionary called my_dict</p> <pre><code>report=(&quot;'name':{}, 'id':{}.format(content['name',content['id'] print(report) 'name': re...
<python><data-dictionary>
2023-05-17 19:49:20
1
10,714
user1471980
76,275,699
10,145,953
Replace value that does not equal specific values
<p>I've tried looking at other similar questions but haven't found an adequate answer for my needs.</p> <p>I have a data frame with a column <code>answer</code> where respondents can answer <code>yes</code>, <code>no</code>, <code>maybe</code>, or some other response. The some other response is free text and for my pur...
<python><pandas><dataframe>
2023-05-17 19:46:45
2
883
carousallie
76,275,641
14,094,460
mkdocs: how to attach a downloadable file
<p>I have a mkdocs project that resembles the following:</p> <pre><code>project ├─mkdocs.yml ├─docs │ ├─home.md │ ├─chapter1.md │ ├─static ├─file.ext ├─image.png </code></pre> <p>I am trying to find a way to &quot;attach&quot; <code>file1.ext</code> to the build, for instance as a link in <code>chapter1.md</code>.<...
<python><markdown><mkdocs><mkdocs-material>
2023-05-17 19:35:29
4
1,442
deponovo
76,275,627
17,896,651
Terminate a Subprocess of Subprocess
<p>I run 20 subprocesses by using:</p> <pre><code>process1 = subprocess.Popen(command1, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=False, encoding='utf-8', cwd=full_path) </code></pre> <p><code>command1</code> is calling a file named: &quot;scheduleInstasck.py&quot; which triggers also <strong>...
<python><terminate>
2023-05-17 19:33:52
1
356
Si si
76,275,555
5,833,797
Programmatically measure database query complexity in Python SQLAlchemy
<p>Is this possible in python/sqlalchemy?</p> <p>When I write an endpoint which retrieves a list of records, I might accidentally make my query very inefficient without realizing.</p> <p>Is there a way to measure the complexity of database queries in a method/unit test and throw an error if too many transactions take p...
<python><sqlalchemy>
2023-05-17 19:21:58
1
727
Dave Cook
76,275,525
7,102,572
Convert string that was originally a `timedelta` back into a `timedelta` object in Python
<p>I have strings which were originally produced from <code>timedelta</code> objects like so: <code>print(f'{my_delta}')</code>.</p> <p>I have many of these statements logged (e.g. &quot;12:21:00&quot;, &quot;1 day, 0:53:00&quot;, &quot;2 days, 9:28:00&quot;) and I simply want to parse these logged statements to conver...
<python><datetime><serialization><timedelta><elapsedtime>
2023-05-17 19:17:51
2
1,048
efthimio
76,275,409
8,189,123
Adding PDF values and export values to ComboBox using PyMuPDF
<p>I am currently looking to set a face and export value to a PDF combobox using the good PyMuPDF module but I can't find the way. Normally, using Adobe API Javascript it would be something like this : <code>f.setItems( [&quot;Ohio&quot;, &quot;OH&quot;], [&quot;Oregon&quot;, &quot;OR&quot;], [&quot;Arizona&quot;, &quo...
<python><pdf><pymupdf>
2023-05-17 19:00:52
1
437
Camilo
76,275,357
11,898,085
How to use imported xsensdeviceapi64.dll classes and functions in Python code?
<p>From Xsens Device API documentation:</p> <blockquote> <p>The C++ interface is not available in compiled form but is provided as part of the SDK as source code that is incorporated in the C header files. This C++ interface code implements a convenience wrapper around the C API. This means that the developer does not ...
<python><dll><dllimport>
2023-05-17 18:52:35
1
936
jvkloc
76,275,323
6,327,888
How to get Python multiprocessing Process() names to handoff to OS utilities like ps, top, etc
<p>I would like to have the python generated subprocesses (multiprocessing) report their python-assigned dict &quot;name&quot; into the system level log such that I can use existing process tracking utilities, without having to map the PID individually to the name provided in my application.</p> <p>Initially, when spaw...
<python><python-3.x><unix><debian-based>
2023-05-17 18:47:20
0
721
Elysiumplain
76,275,157
1,368,479
PIL raises UnidentifiedImageError( PIL.UnidentifiedImageError: cannot identify image file when used as class function but not in a snippet
<p>I am trying to read a static image from a web request. This is my test code which works fine:</p> <pre><code>import requests from io import BytesIO from PIL import Image master_ip = '192.168.1.10' url = 'http://' + master_ip + '/liveimage.jpg' response = requests.get(url=url) img = Image.open(BytesIO(response.conte...
<python><python-requests><python-imaging-library><bytesio>
2023-05-17 18:24:39
0
327
trycatch22
76,275,068
5,924,264
How to query from a csv repeatedly throughout the day in a simulation code
<p>I'm trying to write a simulation code in python. This simulation code relies on inputs for a large csv file, and there is a separate csv file for each day in the simulation. I need to make numerous queries (the queries are based on time, which are columns in the csv file) each simulation day.</p> <p>I'm thinking of ...
<python><pandas><dataframe><csv><design-patterns>
2023-05-17 18:12:31
1
2,502
roulette01
76,274,996
4,721,676
Connecting to Postgres via python using AAD
<p>If I am a member of an AD group that has an AD role defined and connect/select privileges on a Postgres DB, how can I use SQL Alchemy to connect to the DB with my username/pass?</p> <p>If I just give my username/password, it tells me:</p> <pre><code>FATAL: password authentication failed for user &quot;&lt;user&gt;&...
<python><postgresql><azure><sqlalchemy><azure-active-directory>
2023-05-17 18:03:25
1
1,031
David Schuler
76,274,950
15,804,190
Can you make a UDF in xlwings running on server?
<p>I'm playing around with <a href="https://docs.xlwings.org/en/stable/pro/server/server.html" rel="nofollow noreferrer">xlwings server</a> and I'm hoping to make use of user-defined functions in this context. I've been testing using it with FastAPI, but am open to others.</p> <p>I'm able to follow the example well eno...
<python><excel><vba><xlwings>
2023-05-17 17:55:28
0
3,163
scotscotmcc
76,274,881
1,711,271
How to change the font.size for all subplots with sns.set and rcParams
<p>I'm trying to change all font elements in a series of boxplots I'm plotting. My code is similar to</p> <pre><code>from pathlib import Path import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt def plot_group(df, nrow, ncol, size, plot_title): sns.set(style=&quot;darkgrid...
<python><matplotlib><seaborn><font-size><subplot>
2023-05-17 17:46:24
1
5,726
DeltaIV
76,274,808
1,409,674
Absolute imports works either in tests or in uvicorn
<p>I have a bit of an odd problem, namely I have this structure:</p> <pre><code> |-tests | |-__init__.py | |-domain | | |-items | | | |-test_service.py | |-test_app.py |-poetry_demo | |-__init__.py | |-app.py | |-domain | | |-__init__.py | | |-items | | | |-service.py | | | |-controller.py | | | |-__init_...
<python>
2023-05-17 17:38:56
1
8,015
Tomek Buszewski
76,274,733
11,002,498
Running Linux Commands in Jupyter Notebook
<p>I have a google colab file that I want to run in Visual Studio Code. Normal cells are running ok but I have the following cell:</p> <pre><code># 1. Downloads, extracts, and sets the permissions for the Elasticsearch installation image: %%bash wget https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-7...
<python><bash><elasticsearch><jupyter-notebook><google-colaboratory>
2023-05-17 17:28:31
1
464
Skapis9999
76,274,714
17,896,651
Python: Why my Process stay alive on TK VS killed on command line (windows)
<p>On TK I do that: <a href="https://i.sstatic.net/sVQpB.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/sVQpB.png" alt="enter image description here" /></a></p> <p>sys.exit(1) will exit the tk and the other threads running. But all Processes triggered will stay alive in memory (I still see the logs file...
<python><process><terminate>
2023-05-17 17:26:07
0
356
Si si
76,274,662
969,423
Pythonic way to map optional
<p>In Java one can use <code>Optional.map</code> to conditionally transform nullable values.</p> <pre><code>Optional[Integer] multiplyByTwo(Optional[Integer] i) { return i.map(x -&gt; x * 2); } </code></pre> <p>Is there a pythonic practice for this? This seems okay</p> <pre><code>def multiply_by_two(i: int | None): ...
<python>
2023-05-17 17:19:21
0
905
John K
76,274,619
2,823,912
How do type a function in python based on the return value of a method on an instance passed in?
<p>In TypeScript, I can define a function such that the return value is different depending on the behavior of an instance that was passed into the function. (See the example below.)</p> <p>How can I do something similar in Python?</p> <pre class="lang-js prettyprint-override"><code>class DocumentSuperClass { } cl...
<python><type-hinting>
2023-05-17 17:13:00
3
767
nbrustein
76,274,095
3,389,288
Generate a directed graph with k inputs in j outputs and n nodes in networkx
<p>I'm trying to generate a directed graph using networkx in Python with the following characteristics: specified k inputs, j outputs, and n nodes. Ideally I would also be able to specify the connectivity of the graph through an additional parameter. I've played around with the <a href="https://networkx.org/documentati...
<python><networkx><directed-acyclic-graphs>
2023-05-17 16:08:00
1
1,034
user3389288
76,274,067
538,706
Pandas: calculate ratio between groups over time
<p>I have a dataframe that looks something like this:</p> <pre><code> time type values 0 t1 type1 v1 1 t2 type1 v2 2 t3 type1 v3 3 t1 type2 v4 4 t2 type2 v5 5 t3 type2 v6 </code></pre> <p>What I would like to create, is another column that is the ratio between the values of typ...
<python><pandas>
2023-05-17 16:03:43
1
1,231
Flux Capacitor
76,274,063
4,045,275
How to divide one pandas dataframe (pivot table) by another if columns names are different?
<h3>What I am trying to do</h3> <p>I am calculating certain pivot tables with <code>pandas</code> , and I want to divide one by the other.</p> <p>An example (with fictional data) is below, where I have data on the sales of certain items, and I want to calculate things like total sales in $, total # of items sold, unit ...
<python><pandas><dataframe><pivot><pivot-table>
2023-05-17 16:02:37
1
9,100
Pythonista anonymous
76,273,984
14,088,919
Why are colors randomly removed from colormap?
<p>This is my code:</p> <pre><code>import pandas as pd data = {'bar_groups': ['A', 'A', 'B', 'C', 'B', 'A', 'C', 'B', 'C', 'B'], 'color_groups': [1, 2, 3, 4, 5, 6, 7, 8, 1, 2], 0: [0.258, 0.087, 0.168, 0.241, 0.182, 0.236, 0.231, 0.092, 0.283, 0.186], 1: [0.212, 0.208, 0.135, 0.24, 0.256, 0.27,...
<python><pandas><matplotlib><colormap>
2023-05-17 15:52:42
1
612
amestrian
76,273,930
3,541,631
Using a file as lock to not run a script(or related scripts) multiple times at the same time fails when a process pool is used
<p>I want to use a locking mechanism to not start two scripts(can be the same script or another connected script) at the same time. I'm using a file as a locker.</p> <pre><code>class LockFile: def __init__(self, lock_path): self.lock_path = lock_path def lock(self): if os.path.isfile(self.lock...
<python><python-3.x>
2023-05-17 15:46:25
1
4,028
user3541631
76,273,845
19,325,656
Improving queries by select related with many related models
<p>Im writing an app with most of the data started across different tables. I've recently installed Django debug toolbar and noticed that i have some duplicates and similar queries. Thanks to this Im somewhat skeptical about my queries and how I make them. They work but are they efficient?</p> <p><strong>models</strong...
<python><django><django-models><django-rest-framework><django-views>
2023-05-17 15:37:49
0
471
rafaelHTML
76,273,844
2,893,712
Pandas Query astype(str)
<p>I have a dataframe that has a column that usually has numbers only. On occasion, it will have text values, which means it will be of type <code>object</code> instead <code>int64</code>.</p> <p>Instead of doing <code>ColumnA == &quot;100&quot; &amp; ColumnA == 100</code>, I am trying to perform a query that will comp...
<python><pandas><dataframe>
2023-05-17 15:37:34
1
8,806
Bijan
76,273,834
12,670,481
Use Generic type on a Typevar
<p>I am building a class decorator that works as well as possible with Python typing. From the following code:</p> <pre class="lang-py prettyprint-override"><code>from typing import TypeVar, Generic, List, Type ExecutorType = TypeVar(&quot;ExecutorType&quot;) class Task(Generic[ExecutorType]): _executor: Executor...
<python><oop><python-typing>
2023-05-17 15:36:47
0
593
HenriChab
76,273,728
9,064,356
PySpark SQL 'OR' condition working in unexpected manner with dates
<p>I am running queries on pyspark using pyspark sql but I am running into strange behavior. I have where statement which looks like this:</p> <pre><code>WHERE `foobar`.`business_date` = '2020-01-01' OR `foobar_2`.`business_date` = '2020-01-01' </code></pre> <p>Above where statement filters out all of my data which res...
<python><sql><apache-spark><pyspark><where-clause>
2023-05-17 15:24:28
0
961
hdw3
76,273,725
1,769,197
Pandas: read_csv with usecols that may not exist in the csv file
<p>I have several large csv with many columns but they do not all have the same set of columns hence different number of columns in each file. And I only want to read columns that contains a certain string call it &quot;abc-&quot;.</p> <p>I created a list of possible column names that contain the string &quot;abc-&quot...
<python><pandas>
2023-05-17 15:24:03
2
2,253
user1769197
76,273,670
10,466,809
How to import from neighboring test modules when they are outside package source directory?
<p>Suppose I have a package structure like (as shown at <a href="https://doc.pytest.org/en/latest/explanation/goodpractices.html#tests-outside-application-code" rel="nofollow noreferrer">pytest.org</a>):</p> <pre><code>src/ mypkg/ __init__.py app.py view.py tests/ test_app.py test_vi...
<python><testing><import>
2023-05-17 15:18:44
2
1,125
Jagerber48
76,273,567
10,829,044
get past success rate at each timepoint using pandas
<p>I have a dataframe like as below</p> <pre><code>data = { 'project_id': [11, 22, 31, 45, 52, 61], 'user_id': [10001, 10002, 10001, 10003, 10002, 10004], 'customer_id': [20001, 20002, 20001, 20001, 20003, 20002], 'project_start_date': ['2023-01-01', '2023-02-01', '2023-03-01', '2023-04-01', '2023-05-01...
<python><pandas><dataframe><list><group-by>
2023-05-17 15:08:39
1
7,793
The Great
76,273,502
10,967,961
cross merge/cartesian product in dask
<p>how can I perform the equivalent of this cross merge in dask?</p> <pre><code>merged_df = pd.merge(df, df, how='cross', suffixes=('', '_y')) </code></pre> <p>To provide an example, say I have this dataframe, say dataframe A:</p> <pre><code>#Niusup Niucust #1 a #1 b #1 c #2 d #2 e <...
<python><pandas><merge><dask><cartesian-product>
2023-05-17 15:00:12
1
653
Lusian
76,273,420
2,876,079
Flask app.run method does not work with WinPython 3.11.1 and next.js application: fetch failed
<p>When using WinPython 3.10.5 I am able to debug my flask &amp; next.js application using the flask debug mode (to enable hot reloads):</p> <pre><code>app.run(debug=True, host=host, port=port) </code></pre> <p>However, when using WinPython 3.11.1, the flask debug mode does not work any more. The fetch command in the s...
<python><flask><debugging><next.js><python-3.11>
2023-05-17 14:51:01
1
12,756
Stefan
76,273,139
6,690,682
rasterio - set compression quality
<p>I know about the possibility in the <code>rasterio</code> module to set a compression &quot;family&quot; like <code>webp</code> or <code>JPEG</code> by using the respective profile. But I want to have more control over the compression quality, like it is possible when using <code>GDAL</code>.</p> <p>Ideally, I want ...
<python><compression><gdal><rasterio>
2023-05-17 14:19:49
1
795
s6hebern
76,273,111
8,510,149
Issues with mean and groupby using pyspark
<p>I have an issue using mean together with groupBy (or window) on a pyspark dataframe. The code below returns a dataframe called mean_df, for the columns mean_change1, the values is NaN, NaN, NaN.</p> <p>I don't understand why this is the case. Is it due to the presence of NaN in df?</p> <pre><code>import pandas as pd...
<python><pyspark>
2023-05-17 14:17:21
1
1,255
Henri
76,273,075
13,770,014
How to malloc cvalues from python?
<p>This C file:</p> <pre class="lang-c prettyprint-override"><code> #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; struct Foo { char *s; int i; }; struct Bar { struct Foo *f; int n; }; void func(struct Bar *b) { for(int i = 0; i &lt; b-&gt;n; i++)...
<python><c><memory><ctypes>
2023-05-17 14:13:55
1
2,017
milanHrabos
76,272,632
4,399,016
How to convert the API response format into Pandas Dataframe?
<p>I have this code using which I am able to download data from API. But I don't know how to convert this to pandas data frame.</p> <pre><code>import requests import json url = &quot;https://statdb.luke.fi:443/PxWeb/api/v1/en/LUKE/02 Maatalous/04 Tuotanto/06 Lihantuotanto/02 Kuukausitilastot/02_Lihantuotanto_teurastam...
<python><json><pandas>
2023-05-17 13:26:05
1
680
prashanth manohar
76,272,523
10,981,411
Using tkinter, when I place my tree and buttons on the canvas why do they disappear?
<p>below are my codes</p> <p>when I place my tree and buttons on the root I can see them</p> <pre><code>import tkinter from tkinter import ttk from tkinter import * root = tkinter.Tk() root.geometry(&quot;1500x900&quot;) root.title(&quot;Writer&quot;) canvas = tkinter.Canvas(root, borderwidth=10) frame = tkinter.Fram...
<python><tkinter><tkinter-canvas>
2023-05-17 13:15:18
2
495
TRex
76,272,502
2,825,570
Get all labels / entity groups available to a model
<p>I have the following code to get the named entity values from a given text:</p> <pre><code>from transformers import AutoTokenizer, AutoModelForTokenClassification from transformers import pipeline tokenizer = AutoTokenizer.from_pretrained(&quot;Davlan/distilbert-base-multilingual-cased-ner-hrl&quot;) model = AutoMo...
<python><pytorch><huggingface-transformers>
2023-05-17 13:11:36
2
8,621
Jeril
76,272,312
10,755,782
How to visualize segment-anything mask results in a single color?
<p>I'm trying to visualize the results of image segmentation which was done by 'segment-anything'. When I do this the segmented boxes/masks are plotted with different colors. <a href="https://i.sstatic.net/DVMOn.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/DVMOn.png" alt="as shown here" /></a> How can...
<python><computer-vision><image-segmentation>
2023-05-17 12:49:36
1
660
brownser
76,272,281
1,854,182
import openai fails (python): cannot import name 'COMMON_SAFE_ASCII_CHARACTERS'
<p>Trying to use openai:</p> <pre><code>import openai </code></pre> <p>I've got the following errors:</p> <pre><code>Traceback (most recent call last): File &quot;/.../lib/python3.11/site-packages/aiohttp/client_reqrep.py&quot;, line 70, in &lt;module&gt; import cchardet as chardet ModuleNotFoundError: No module ...
<python><openai-api>
2023-05-17 12:46:34
1
888
Ofer Rahat
76,272,002
5,305,512
How to download NLTK package with proper security certificates inside docker container?
<p>I have tried all combinations mentioned <a href="https://stackoverflow.com/questions/31143015/docker-nltk-download">here</a> and other places, but I keep getting the same error.</p> <p>Here is my <code>Dockerfile</code>:</p> <pre><code>FROM python:3.9 RUN pip install virtualenv &amp;&amp; virtualenv venv -p python3...
<python><linux><docker><ssl-certificate><nltk>
2023-05-17 12:15:01
1
3,764
Kristada673
76,271,910
4,704,065
Highlight a particular value in X axis
<p>I want to highlight particular values on x axis in Matplotlib .</p> <pre><code>list1=[1,2,3,4,5,6,7,8,9] - xaxis values list2=[1,2,23,4,5,6,7,8,9] - y-axis values list3=[2,3,6,7] plt.plot(list1,list2) plt.show() </code></pre> <p>I want to highlight the xaxis labels as well its corresponding values in any color li...
<python><matplotlib>
2023-05-17 12:05:51
2
321
Kapil
76,271,807
12,048,753
Polars: Parsing nested fields when reading a csv file
<p>I have the following csv structure:</p> <pre><code>Some;Csv;Data;Nested|Field|Containing|An|Array;And;Some;More;Fields;Here </code></pre> <p>Is there any away to parse the nested list using polars ?</p> <p>What is the expected output ?</p> <pre class="lang-py prettyprint-override"><code>{ &quot;column_1&quot;: &q...
<python><dataframe><csv><python-polars>
2023-05-17 11:53:57
1
1,306
Fausto Alonso
76,271,668
9,476,917
pandas read_excel throws ValueError: Value does not match pattern
<p>I want to read an excel file as pandas Dataframe</p> <pre><code>import pandas as pd import os path = r&quot;my/path/to/file&quot; file = &quot;myFile.xlsx&quot; df = pd.read_excel(os.path.join(path, file)) </code></pre> <p>and receive following error:</p> <blockquote> <p>ValueError: Value does not match pattern ^[...
<python><pandas><excel>
2023-05-17 11:36:13
0
755
Maeaex1
76,271,573
940,490
Could there be a bug in `pandas.rolling.std` when custom weights are used?
<p>I have observed odd behavior of <code>pandas.rolling.std</code> when custom weights are used and trying to understand what is happening. My question is about how this method works and if there could be a bug when custom weights are used, but below there is a visual example of what looks very suspicious.</p> <p>Throu...
<python><pandas>
2023-05-17 11:25:46
1
1,615
J.K.
76,271,490
1,745,291
How to make a value awaitable in python?
<p>I have an <code>int</code>, and I want to make it awaitable, how can I do it ?</p> <p>Context : I implementing an async generator yielding awaitable objects. However, it needs to await the first (and only the first) value so that it can yield the others.</p> <p>Thus, the first value is already awaited, but the other...
<python><asynchronous><async-await>
2023-05-17 11:16:41
2
3,937
hl037_
76,271,327
16,797,805
Python Azure Function cannot connect to Blob storage with Firewall
<p>I have a function app (with python runtime and consumption plan) that once a month must load some data from a public source, process them and put them to an azure blob storage, that instead must remain private.</p> <p>This flow works when I tested it leaving the blob storage open to public.</p> <p>Then I added some ...
<python><azure-functions><azure-blob-storage>
2023-05-17 10:56:42
1
857
mattiatantardini
76,271,318
6,067,528
How to trim pyspark schema output
<p>My pyspark dataframe has the following schema...</p> <p><code>DataFrame[ExternalData: struct&lt;provider:string,data:string,modality:array&lt;string&gt;&gt;]</code></p> <p>If I write (where <code>sdf</code> is my pyspark dataframe)..</p> <p><code>sdf.schema</code></p> <p>I get...</p> <pre><code>StructType([StructFie...
<python><pyspark>
2023-05-17 10:55:05
1
1,313
Sam Comber
76,271,284
11,327,283
Plot the regression line of the machine learning prediction model in python
<p>I would like to plot the regression line of the machine learning model on the data scatter plot as shown below:</p> <p><a href="https://i.sstatic.net/fnrRD.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/fnrRD.png" alt="enter image description here" /></a></p> <p>This is what I have tried so far:</p> ...
<python><machine-learning><scikit-learn><regression><random-forest>
2023-05-17 10:50:56
1
658
mArk
76,271,255
4,105,440
How to pass a parameter to an aggregation function in Dask
<p>I just discovered today that a sum of a column full of NaNs is 0 in <code>pandas</code> and <code>Dask</code> (why?!). I need a sum of all NaNs to be 0, because having NaNs means those values are missing, so their sum should be NaN as well.</p> <p>From the documentation it appears that you have to pass <code>min_cou...
<python><pandas><dask>
2023-05-17 10:46:15
1
673
Droid
76,271,210
3,907,364
SQLAlchemy: Add where clause based on count of many-to-many relation
<p>I am trying to create a model in which I can have different projects and each project has one or more authors. Since every author may be involved with multiple projects, this is a many-to-many relation. The setup for this is as follows</p> <pre><code>from typing import List from typing import Optional from sqlalche...
<python><sqlalchemy>
2023-05-17 10:41:34
1
3,658
Raven
76,271,031
9,363,181
Makefile script not building the python project zip properly
<p>I have below the <code>Makefile</code> script inside a <code>docker container</code> that executes a few commands for building the zip of the project and then initializes the terraform directory and uploads it in AWS. However, the zip which is uploaded for the lambda function raises a <code>module not found</code> e...
<python><amazon-web-services><makefile><terraform><gitlab>
2023-05-17 10:20:00
0
645
RushHour
76,270,794
5,847,976
Copy data from one numpy array to an other with possibly missmatched sizes
<p>So my issue is that I'm trying to paste a small image into a larger image with the typical numpy syntax :</p> <pre><code>large_im = np.linspace(0,1,20)[:,None]*np.ones([1,20]) small_im = np.linspace(1,0,10)[None,:]*np.ones([10,1]) a0,b0 = 5,5 large_im[a0:a0+small_im.shape[0],b0:b0+small_im.shape[1]] = small_im plt...
<python><numpy><numpy-slicing>
2023-05-17 09:53:32
1
3,542
jadsq
76,270,705
3,590,067
How to assign specific color to a category in an array
<p>I want to show the land use classes of a region.</p> <p>I have different raster files that contain information of land use. Each value of the pixel correspond to a specific land use class. I want to assign to each class a color as shown below. This is what I am doing:</p> <pre><code>from matplotlib.colors import Lis...
<python><matplotlib><colorbar><colormap><rasterio>
2023-05-17 09:44:45
1
7,315
emax
76,270,546
5,568,409
How to correct my misunderstandings of subplots
<p>I seemed to understand how the subplots and ax options work in <code>Matplotlib</code>, but I just did a graphical test and it doesn't work at all as expected, which shows me that I still don't quite understand the syntax of the statements.</p> <p>The program is below; I should get 2 separate graphs but there is onl...
<python><matplotlib><seaborn><subplot>
2023-05-17 09:26:58
1
1,216
Andrew
76,270,413
9,513,536
Understanding why the leiden algorithm is not able to find communities for the iris dataset
<p>Good morning!,</p> <p>I am trying to understand the Leiden algorithm and its usage to find partitions and clusterings. The example provided in the documentation already finds a partition directly, such as the following:</p> <pre><code>import leidenalg as la import igraph as ig G = ig.Graph.Famous('Zachary') partit...
<python><graph><cluster-analysis><leiden>
2023-05-17 09:12:13
2
2,847
Carles
76,270,202
383,793
How can I express two types are consistent?
<p>Say I'm using libraries that handle Json and they both define their own types that I know are consistent in the sense of <a href="https://peps.python.org/pep-0483/#summary-of-gradual-typing" rel="nofollow noreferrer">PEP 483</a>.</p> <p>How can I express that?</p> <pre class="lang-py prettyprint-override"><code>from...
<python><python-typing>
2023-05-17 08:50:20
0
6,396
Chris Wesseling
76,270,084
1,226,020
Installing AWS EB CLI using pip fails due to breaking changes in urllib 2
<p>Suddenly my GitHub Actions CI workflow failed to install AWS EB CLI, due to breaking changes in <code>urllib</code> v2:</p> <pre><code>ERROR: botocore 1.29.81 has requirement urllib3&lt;1.27,&gt;=1.25.4, but you'll have urllib3 2.0.2 </code></pre> <p>When trying to use <code>eb deploy</code> anyway, this is the erro...
<python><pip><amazon-elastic-beanstalk><ebcli>
2023-05-17 08:35:57
0
9,405
JHH
76,270,059
3,209,276
Upgrade a self hosted python package from within a python session
<p>We are developing a python package hosted on our own Bitbucket. So far the upgrade of the package works fine from the terminal :</p> <pre class="lang-bash prettyprint-override"><code>python -m pip install --upgrade --no-cache-dir git+ssh://git@{package_git_url} </code></pre> <p>The idea is to let the user upgrade th...
<python><pip>
2023-05-17 08:32:57
1
386
Rigoberta Raviolini
76,270,036
4,865,723
Create table instance not connected to a document with python-docx?
<p>This is an X-Post related to <a href="https://github.com/python-openxml/python-docx/issues/1190" rel="nofollow noreferrer">Issue #1190</a> at <code>python-docx</code> upstream.</p> <p>This is how I do create a table in a docx document currently.</p> <pre><code>doc = docx.Document() tab = doc.add_table(rows=300, cols...
<python><python-docx>
2023-05-17 08:30:11
1
12,450
buhtz
76,269,989
10,818,184
what happens when boolean mask of numpy array is just a single value
<p>I know that boolean array can be used as a mask in a numpy array. But when I use a single value as a mask in a numpy array, strange thing happened:</p> <pre><code>x = [1,2,3,4,5] result = np.array(x)[True] print(result) </code></pre> <p>It turns out to be [[1 2 3 4 5]]. Why there is a double bracket? What does Pyth...
<python><numpy>
2023-05-17 08:24:57
1
488
li_jessen
76,269,948
10,251,146
Pushing polar dataframe to redis
<p>What is the best way to push a polars dataframe to redis ?</p> <p>Currently I am trying to read the _io.BytesIO buffer returned by write_ipc</p> <pre><code>redis_instance.set(&quot;key&quot;,df.write_ipc(file = None, compression=&quot;lz4&quot;).read()) </code></pre> <p>This doesn't seem to work as the key in redis ...
<python><redis><python-polars><py-redis>
2023-05-17 08:19:58
1
459
linus heinz
76,269,934
930,675
Issues creating a regex to extract code from Markdown
<p>I'm trying to extract code from a string of Markdown and I'm very close. My code is:</p> <pre><code>import re string = &quot;&quot;&quot; Lorem ipsum ```python print('foo```bar```foo') print('foo```bar```foo') ``` Lorem ipsum &quot;&quot;&quot; pattern = r'```(?:\w+\n)?(.*?)(?!.*```)' result = re.search(pattern, s...
<python><regex>
2023-05-17 08:18:16
1
3,195
Sean Bannister
76,269,866
3,322,273
Plot two 2D-data histograms on the same chart
<p>I am looking for a way to plot multiple histograms of 2D data, but I could not find any documentation about addressing such a problem.</p> <p>Plotting multiple <strong>1-dimensional histograms</strong> on a same chart with Matplotlib has been addressed in <a href="https://stackoverflow.com/questions/6871201/plot-two...
<python><matplotlib><plot><histogram>
2023-05-17 08:09:24
1
12,360
SomethingSomething
76,269,750
1,025,140
Update TOML file with variables
<p>I am using this code to update an existing TOML file which contains variables. Python TOML module is not able to parse this TOML file.</p> <p>How can I use this code to update the TOML file?</p> <p>I have tried the 'from yaml.loader import SafeLoader' also, but that didn't help.</p> <p>Code:</p> <pre class="lang-py ...
<python><toml>
2023-05-17 07:55:17
1
980
user87005
76,269,633
6,035,977
How to accept only the next word in PyCharm GitHub copilot suggestion
<p>I would like to be able to accept only the next word of a github Copilot suggestion instead of the full suggestion. This is possible with VS Code as documented <a href="https://stackoverflow.com/questions/75114315/how-to-accept-only-the-next-word-in-github-copilot-suggestion#:%7E:text=To%20enable%20a%20shortcut%20to...
<python><autocomplete><pycharm><github-copilot>
2023-05-17 07:42:24
1
333
Corram
76,269,605
11,611,246
Multiprocessing Listener-Client two-way connection
<p>I am trying to make two Python processes communicate: One script (<code>Listener.py</code>) should run in the background in an endless loop. The other script (<code>Client.py</code>) should be executed whenever needed. Each time, <code>Client.py</code> is executed, it is supposed to send some information in a Python...
<python><python-3.x><multiprocessing><communication>
2023-05-17 07:39:09
1
1,215
Manuel Popp
76,269,463
19,189,069
How to sort a list of bigrams according to the second unigram?
<p>I have a list of bigrams like this:</p> <pre><code>mylist = [&quot;hello world&quot;, &quot;this python&quot;, &quot;black cat&quot;, &quot;brown dog&quot;] </code></pre> <p>I want to sort this list according to the second word in each element alphabetically. The result is like this:</p> <pre><code>mylist = [&quot;b...
<python>
2023-05-17 07:20:04
1
385
HosseinSedghian
76,269,260
2,252,356
Django CustomUser model Image field display in User List
<p><code>UserProfile</code> is CustomUser Model having columns avatar, bio and display fields.</p> <p>I want to show Profile avatar in the User List</p> <p>I have added avatar_tag function to be called by the users list</p> <pre class="lang-py prettyprint-override"><code>#models.py class UserProfile(models.Model): ...
<python><django><django-models><django-admin>
2023-05-17 06:51:46
1
2,008
B L Praveen
76,269,159
8,481,155
Python Pytest ModuleNotFoundError
<p>I have a folder structure like below</p> <pre><code>. ├── src │ ├── __init__.py │ ├── b.py │ └── main.py └── test ├── __init__.py └── test_main.py </code></pre> <p>main.py imports a function from b.py which is causing me all sorts of problems.</p> <p>main.py</p> <pre><code>from b import sub_m def add_...
<python><python-3.x><pytest><python-unittest>
2023-05-17 06:37:02
1
701
Ashok KS
76,268,858
972,647
Re-sort string based on precedence of separator
<p>I have a string with a certain meaning for example <code>&quot;a,b;X1&quot;</code> or <code>e&amp;r1</code>. In total there are 3 possible separators between values: <code>,;&amp;</code> where <code>;</code> has low precedence.</p> <p>Also <code>&quot;a,b;X1&quot;</code> and <code>&quot;b,a;X1&quot;</code>are the sa...
<python><string><sorting>
2023-05-17 05:40:04
3
7,652
beginner_
76,268,799
9,346,370
How should I declare enums in SQLAlchemy using mapped_column (to enable type hinting)?
<p>I am trying to use <code>Enums</code> in SQLAlchemy 2.0 with <code>mapped_column</code>. So far I have the following code (taken from another question):</p> <pre class="lang-py prettyprint-override"><code>from sqlalchemy.dialects.postgresql import ENUM as pgEnum import enum class CampaignStatus(str, enum.Enum): ...
<python><postgresql><sqlalchemy><fastapi>
2023-05-17 05:26:42
1
1,224
Javier Guzmán
76,268,656
10,698,244
How to extract dict values of pandas DataFrame in new columns?
<p>I would like to extract the values of a dictionary inside a Pandas DataFrame <code>df</code> into new columns of that DataFrame. All keys in the referring dict are the same across all rows.</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd df = pd.DataFrame({'a': [1, 2, 3], 'b': [{'x':[101], '...
<python><python-3.x><pandas><dataframe>
2023-05-17 04:51:35
1
1,369
user7468395
76,268,529
11,505,680
Python string formatting for precision with no trailing zeros
<p>I have some floating-point numbers containing zero or more decimal places. I want to display them with <em>no more than</em> two decimal places, with no trailing zeros. In other words, I'm looking for a definition of <code>magic_fmt</code> that satisfies this condition:</p> <pre class="lang-py prettyprint-override">...
<python><string-formatting>
2023-05-17 04:18:31
0
645
Ilya
76,268,513
3,121,518
Python Multiple Inheritance Diamond Problem
<p>I have a diamond inheritance scenario. The two middle classes inherit okay, but the Combo class, I can't quite figure out. I want the Combo class to inherit all attributes with the overridden methods coming from the Loan class.</p> <p>I can't figure out how to write the constructor for the Combo class.</p> <p>This i...
<python><multiple-inheritance><diamond-problem>
2023-05-17 04:12:54
2
1,564
Harley
76,268,472
11,626,909
Python Code and Output in Bookdown pdf are not in multiple lines
<p>I am trying to write python code using <code>rmarkdown</code> in <code>bookdown</code>. The python code is ok. The problem is when the book pdf is generated, some long python codes and sometimes some python codes' output are outside of the pdf page and therefore they are not visible. Please see the images below.</p>...
<python><latex><r-markdown><bookdown>
2023-05-17 04:01:21
1
401
Sharif
76,268,348
2,960,978
How to update/modify request headers and query parameters in a FastAPI middleware?
<p>I'm trying to write a middleware for a FastAPI project that manipulates the request <code>headers</code> and / or <code>query</code> parameters in some special cases.</p> <p>I've managed to capture and modify the request object in the middleware, but it seems that even if I modify the request object that is passed t...
<python><header><fastapi><query-string><starlette>
2023-05-17 03:17:02
1
1,460
SercioSoydanov
76,268,304
2,897,115
what the need of simple tests in python django
<p>I was reading about tests and came accross an example as below.</p> <pre><code>import pytestimport pytest @pytest.fixture def customer(): customer = Customer(first_name=&quot;Cosmo&quot;, last_name=&quot;Kramer&quot;) return customer def test_customer_sale(customer): assert customer.first_name == &qu...
<python><pytest>
2023-05-17 03:01:29
2
12,066
Santhosh
76,268,261
866,082
How to fix ipywidgets when they are not rendered in a jupyter-lab notbook?
<p>I have jupyter-lab version 3.6.3 installed and it fails to render ipywidgets. I followed the instructions mentioned in their <a href="https://ipywidgets.readthedocs.io/en/8.0.5/user_install.html" rel="nofollow noreferrer">documentation</a> and it still does not render.</p> <p>These are the steps I've taken:</p> <pre...
<python><jupyter-lab><ipywidgets>
2023-05-17 02:46:36
1
17,161
Mehran
76,268,132
14,109,040
Assigning values to records in a dataframe based on datetime column being between a reference datetime range
<p>I have the following data frames:</p> <p>period_df:</p> <pre><code>Group1 Group2 Period Start time End time G1 G2 Period 1 1900-01-01 05:01:00 1900-01-01 06:00:00 G1 G2 Period 2 1900-01-01 06:01:00 1900-01-01 07:00:00 G1 G2 Period 3 1900-01-01 07:01:00 1900-01-01 08:00:0...
<python><pandas>
2023-05-17 02:07:20
1
712
z star
76,267,960
3,247,006
How to make only the 1st inline object boolean field "True" by default only for "Add" page in Django Admin?
<p>I'm trying to make only the 1st inline object boolean field <code>True</code> by default only for <strong>Add</strong> page.</p> <p>So, I have <code>Person</code> model and <code>Email</code> model which has the foreign key of <code>Person</code> model as shown below:</p> <pre class="lang-py prettyprint-override"><c...
<python><django-models><boolean><django-admin><default>
2023-05-17 01:08:07
1
42,516
Super Kai - Kazuya Ito
76,267,954
8,278,630
org.elasticsearch.spark.sql.DefaultSource15 could not be instantiated
<p>Working on <code>Databricks</code> workspace with the <code>Python</code> language inside the <code>cluster</code>. I want to connect to Elasticsearch Remote server and bring data to Databricks workspace to work on.</p> <ul> <li><p>When I check the connection with <code>Elasticsearch</code> remote server, connection...
<python><elasticsearch><databricks>
2023-05-17 01:05:24
0
1,073
Farkhod Abdukodirov
76,267,937
4,027,692
Quart `json_provider_class` makes no effect
<p>I am trying to modify my datetime object responses in Quart so that my frontend applications receive dates in ISO8601 format.</p> <p>I expected the <code>json_provider_class</code> to do this job, but it's not working for me or maybe I am not doing it right.</p> <p>Here's my code:</p> <pre><code>class JSONProvider(D...
<python><datetime><quart>
2023-05-17 00:59:17
1
423
Athus Vieira
76,267,924
2,738,250
Can startup scripts in subfolders access tools located in the parent folder?
<p>I have hundreds of startup scripts in the root of my project, and they all use tools from the &quot;tools&quot; folder. It has become challenging to locate the specific startup script I need, so I want to organize some of the startup scripts into subfolders. However, when I move a startup script to a subfolder, I en...
<python>
2023-05-17 00:52:29
0
341
Vitaliy
76,267,849
6,273,496
group by multiple columns independently and plot distribution
<p>I have a dataframe that looks like this:</p> <pre><code> user_id segment device operating_system 0 51958733 small and above desktop Chrome OS 1 48983182 unfunded desktop ...
<python><pandas><matplotlib><jupyter-notebook><visualization>
2023-05-17 00:26:58
1
2,904
Simon Breton
76,267,841
13,635,877
how to search for caret (^) in string
<p>I have a pandas dataframe with a bunch of strings. Some of the strings contain a caret (ie. a ^ symbol).</p> <p>I am trying to remove them using this:</p> <pre><code>df['text'] = df[df['text'].str.contains('^') == False] </code></pre> <p>I don't get an error but it is finding a caret in every row which is not correc...
<python><pandas><string><contains>
2023-05-17 00:24:31
1
452
lara_toff
76,267,698
1,361,802
ValueError: Related model u'app.model' cannot be resolved when adding admin and custom user in existing app
<p>I have an existing app that has as lot of migrations and no users table. I am looking to add django admin and a custom user. I am hitting <code>Related model u'myapp.model' cannot be resolved</code> when I run <code>manage.py migrate</code></p> <pre><code>Operations to perform: Apply all migrations: admin, auth, c...
<python><django><django-admin><django-migrations>
2023-05-16 23:30:41
1
8,643
wonton
76,267,623
1,624,552
Reading zip file content for later compute sha256 checksum fails
<p>I have a zip file which contains some regular files. This file is uploaded to a fileserver. Now I am trying to compute the sha256 checksum for the zip file, then write the checksum into a *.sha256sum file and upload to the fileserver as well.</p> <p>Then when one downloads the zip file and the checksum file (<em>.sh...
<python><zip><sha256>
2023-05-16 23:09:09
1
10,752
Willy
76,267,598
8,236,733
How to unlock PGP Self Decrypting Archive .exe files (PGP SDAs) in python with a known passphrase?
<p>I have a set of PGP Self Decrypting Archive <code>.exe</code> files (<a href="https://knowledge.broadcom.com/external/article/153684/creating-a-self-decrypting-archive-with.html" rel="nofollow noreferrer">https://knowledge.broadcom.com/external/article/153684/creating-a-self-decrypting-archive-with.html</a>) (on a W...
<python><exe><pgp>
2023-05-16 23:03:38
3
4,203
lampShadesDrifter
76,267,537
4,314,501
Airflow does not load DAG
<p>I have a DAG in airflow 2.2.3, and it has 3 tasks.</p> <pre class="lang-py prettyprint-override"><code>from datetime import datetime from typing import List from airflow.decorators import dag, task @dag(dag_id='myDag', start_date=datetime(2023, 5, 15), schedule_interval=&quot;0 5 * * *&quot;, max_a...
<python><airflow><airflow-2.x>
2023-05-16 22:46:26
0
1,024
cointreau