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,076,286
610,569
Converting JSON/dict to flatten string with indicator tokens
<p>Given an input like:</p> <pre><code>{'example_id': 0, 'query': ' revent 80 cfm', 'query_id': 0, 'product_id': 'B000MOO21W', 'product_locale': 'us', 'esci_label': 'I', 'small_version': 0, 'large_version': 1, 'split': 'train', 'product_title': 'Panasonic FV-20VQ3 WhisperCeiling 190 CFM Ceiling Mounted Fan', ...
<python><json><tokenize><json-flattener>
2023-04-21 19:40:41
2
123,325
alvas
76,076,234
15,763,991
How to Remove old Slash Commands from a Discord Bot?
<p>I recently used a Mee6 Premium Bot for my Discord server, but now I want to run my own bot with new slash commands (running on the Bot that was the Mee6 Bot). However, the old slash commands from Mee6 are still registered in my bot. When I type &quot;/&quot;, all of my commands show up along with the commands from M...
<python><discord><discord.py>
2023-04-21 19:30:06
1
418
EntchenEric
76,076,225
814,438
Release Python Thread Lock or Futex Using GDB
<p>I would like to find a way to release a Python thread <code>Lock</code> using GDB on Linux. I am using Ubuntu 18.04, Python 3.6.9, and gdb 8.1.1. I am also willing to use the <code>gdb</code> package in Python.</p> <p>This is for personal research and not intended for a production system.</p> <p>Suppose I have this ...
<python><c><multithreading><gdb><futex>
2023-04-21 19:27:33
1
1,199
Jacob Quisenberry
76,076,212
16,267,793
External company Sharepoint Excel Access
<p>I would like to know if there is any way for me to access data from an excel file that is in a directory in which I do not have access to the root folder. It is therefore a different directory than mine. Another Company.</p> <p>The only access I can get is through the browser, entering my email address and waiting f...
<python><excel><pandas><sharepoint-online>
2023-04-21 19:24:20
0
1,267
Wilian
76,076,176
19,980,284
Center formatted y-tick labels in bi-directional bar chart matplotlib
<p>I have generated this bar chart: <img src="https://i.sstatic.net/m0Zf3.png" alt="" /></p> <p>With the help of @Ken Myers <a href="https://stackoverflow.com/a/76075788/19980284">here</a>. My question is, how to center the formatted y-tick labels like <code>volume</code>, <code>MAP</code>, etc. that act as sort of hea...
<python><pandas><matplotlib><bar-chart>
2023-04-21 19:18:39
1
671
hulio_entredas
76,076,133
12,065,150
Wait for loading of `grecaptcha` variable in selenium python
<p>I am using selenium to automate submitting of a form on a website. Occasionally, I get a failed form submit due to this error.</p> <pre><code>0.62d2e676.js:1 Uncaught ReferenceError: grecaptcha is not defined at Object.reply_chat_form_submit (6.b0af483c.js:1:22012) ... </code></pre> <p>This variable <code>gr...
<javascript><python><selenium-webdriver><recaptcha><captcha>
2023-04-21 19:11:32
1
4,680
Ali Sajjad Rizavi
76,076,082
3,197,412
Overriding of current TracerProvider is not allowed
<p>I'm trying to write an opentelemetry provider for python-dependency-injector but for some reason, my traces are not sent and I get an error like - <code>Failed to export batch. Status code: StatusCode.UNAVAILABLE</code></p> <p>My provider:</p> <pre class="lang-py prettyprint-override"><code>from dependency_injector ...
<python><dependency-injection><open-telemetry>
2023-04-21 19:04:54
1
1,012
batazor
76,076,064
5,942,779
Pandas plot with Plotly backend and Custom Hover template
<p>I am trying to include additional data in the hover template, similar to this <a href="https://stackoverflow.com/questions/69278251/plotly-including-additional-data-in-hovertemplate">Plotly: Including additional data in hovertemplate</a>, but using Plotly plotting backend on Pandas.</p> <p>I have two 2D Pandas data ...
<python><pandas><plotly>
2023-04-21 19:02:52
1
689
Scoodood
76,075,818
1,711,271
create multiple columns at once based on the value of another column
<p>I have the following dataframe:</p> <pre><code>import pandas as pd import random # Create the lists for each column nrows = 5 a = [[random.randint(0, 10), random.randint(0, 10), random.randint(0, 10)] for i in range(nrows)] b = [[random.randint(0, 10), random.randint(0, 10), random.randint(0, 10)] for i in range(nr...
<python><pandas><dataframe><apply>
2023-04-21 18:23:12
5
5,726
DeltaIV
76,075,777
19,504,610
FastAPI: Returning a List[ReadSchema] as another schema
<p>I have a <code>CategoryEnum</code>:</p> <pre class="lang-py prettyprint-override"><code>from enum import Enum class CategoryEnum(str, Enum): A = &quot;A&quot; B = &quot;B&quot; </code></pre> <p>I have two tables, <code>Category</code> and <code>Project</code> tables:</p> <pre><code>from app.enums import Cat...
<python><backend><fastapi><pydantic>
2023-04-21 18:15:48
1
831
Jim
76,075,727
8,849,071
How to fix mypy to allow infer types from dictionary with interfaces
<p>so we have a really easy injector that just fits our needs. Now we want to have type inference, but we are having quite a hard time making it work with mypy. Here you have a minified example reproducing the problem:</p> <pre class="lang-py prettyprint-override"><code>from abc import ABC, abstractmethod from typing i...
<python><python-typing><mypy>
2023-04-21 18:07:29
1
2,163
Antonio Gamiz Delgado
76,075,487
15,755,176
Shuffle list to maximize minimum distance between new and original positions
<p>I am looking for a simple way that will allow to re-order elements in a Python list in such a way so that each new element position is as far as possible from its original position, in a way that takes all element positions into account.</p> <p>I should also be able to restore the original positions. For this reason...
<python>
2023-04-21 17:30:13
1
376
mangotango
76,075,483
2,161,250
python mysql library not establish connection with ssh tunneling server
<p>SSH tunnel connection is established successfully but Error connecting to RDS MySQL database via SSH tunnel: 2003 (HY000): Can't connect to MySQL server on '0.0.0.0:52678' (10049)</p> <p>same is working when I use library pymysql but not mysql.connector</p> <p>can any one help me here</p> <p>below is the code</p> <p...
<python><ssh><pymysql><ssh-tunnel>
2023-04-21 17:29:51
0
338
Lavish Karankar
76,075,405
999,355
What is type=argparse.FileType('rb') in Python
<p>I am looking at other person's Python code:</p> <pre><code>import argparse parser = argparse.ArgumentParser(description=&quot;Recover files from an NTFS volume&quot;) parser.add_argument('--mft', type=argparse.FileType('rb'), help='Use given file as MFT') </code></pre> <p>and find this <code>type</code> argument a b...
<python><argparse>
2023-04-21 17:18:22
1
26,768
Paul
76,075,382
2,756,466
Send pyttsx3..save_to_file output to api
<p>I am trying to send pyttsx3.save_to_file to an api endpoint using python. e.g. i create a Flask api endpoint which receive some text from user -&gt; convert text to speech -&gt; and return the mp3 as byte array.</p> <p>How this can be acheived?</p>
<python><pyttsx3>
2023-04-21 17:14:23
1
7,004
raju
76,075,352
6,467,567
How to deep flatten a list of messy arrays?
<p>I have a Python list/array of really messy lists/arrays that either contains a list, array, or an empty list/array. Is there a simple operation I can use to <strong>completely</strong> flatten it to return me a 1D array?</p> <p>Here would be an example that might not be correct</p> <pre><code>a = np.array([[1,2,3], ...
<python><arrays>
2023-04-21 17:08:41
1
2,438
Kong
76,075,342
1,914,781
get differ by even odd row and combine with other columns
<p>I would like to get differ between even and odd row, then add odd row ts values as well.</p> <p>Current implementation do differ correctly, but missed the odd row ts values.</p> <pre><code>import pandas as pd data = [ ['04-21 10:45:21.718'], ['04-21 10:45:22.718'], ['04-21 10:45:24.718'], ['04-21 10...
<python><pandas>
2023-04-21 17:07:01
2
9,011
lucky1928
76,075,244
19,980,284
Add Specific Labels and Spacing to Matplotlib Bi-Directional Plot
<p>I have generated this plot <a href="https://i.sstatic.net/34DFm.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/34DFm.png" alt="enter image description here" /></a></p> <p>From this df:</p> <pre><code>variable level margins_fluid margins_vp 0 volume 1L 0.718 0.690 1 ...
<python><pandas><matplotlib><bar-chart>
2023-04-21 16:53:24
1
671
hulio_entredas
76,075,175
10,426,490
How to setup `pip` on Windows behind a proxy, without your password in plaintext?
<p>How do you setup <code>pip</code> on a Windows computer that is behind a VPN proxy?</p> <p><strong>I've seen 3-4 different options such as</strong>:</p> <ol> <li><a href="https://stackoverflow.com/a/41957788/10426490">Set the <code>http_proxy</code> and <code>https_proxy</code> env variables</a></li> <li><a href="ht...
<python><security><pip><proxy><vpn>
2023-04-21 16:42:05
0
2,046
ericOnline
76,075,123
3,578,468
Overwrite file in MLFlow on Azure ML
<p>I have the same question that somebody already asked on the MLFlow GitHub page. But this is not on MLFlow's but on Azure's side of things.</p> <p>I want to overwrite model checkpoints with the best model checkpoint at the current epoch, and not accumulate old checkpoints. Hence, I log the same thing again with MLFlo...
<python><azure><mlflow>
2023-04-21 16:33:03
0
3,954
lo tolmencre
76,075,120
5,858,752
Can only use .dt accessor with datetimelike values after upgrading pandas
<p>I recently did a <code>pip3 install --upgrade pandas</code> and I'm now using version <code>1.3.5</code>. Previously, I was using <code>0.24.X</code> IIRC (not sure how to check).</p> <p>Ever since the update, the simulation code I have is seeing errors like</p> <pre><code>raise AttributeError(&quot;Can only use .dt...
<python><pandas><datetime>
2023-04-21 16:32:46
1
699
h8n2
76,075,088
14,808,637
How to get multi-dimension specific data samples on the basis of list element?
<p>I need to evaluate my model's performance with limited training data. I am randomly selecting p of original training data. Assume p is 0.2 in this case. Here is some intil lines of code:</p> <pre><code>p = p*100 data_samples = (data.shape[0] * p)/100 # data.shape= (100, 50, 50, 3) # for randomly selecting data imp...
<python><numpy><random><numpy-ndarray><lis>
2023-04-21 16:27:53
1
774
Ahmad
76,075,008
12,319,746
Connect to Azure SQL from Azure function using pypyodbc
<p>I am trying to connect to an azure sql db from an azure function. I am using <code>pypyodbc</code>. I am not able to find the syntax for connecting to it. I have tried</p> <pre><code>import pypyodbc def main(req): # Set up the database connection connection_string = 'Driver={ODBC Driver 17 for SQL Server};S...
<python><azure-functions><odbc>
2023-04-21 16:18:34
1
2,247
Abhishek Rai
76,074,840
4,307,022
AttributeError: module 'virtualenv.create.via_global_ref.builtin.cpython.mac_os' has no attribute 'CPython2macOsArmFramework'
<p>I was trying to configure pre-commit hooks and while running <code>pre-commit run --all-files</code> I got this error:</p> <pre><code>[INFO] Installing environment for https://github.com/pre-commit/pre-commit-hooks. [INFO] Once installed this environment will be reused. [INFO] This may take a few minutes... An unexp...
<python><macos><pip><modulenotfounderror>
2023-04-21 15:55:54
3
397
dark_matter88
76,074,785
16,512,200
Implicit conversion from data type varchar(max) to varbinary(max) is not allowed
<p>I have a method called <code>appendTable()</code> which essentially takes the name of the table and the <code>columns=data</code> as keyword arguments. I take the keyword arguments and use that to build a <code>DataFrame</code> object and then I use the <code>dataframe.to_sql()</code> method to append the row to my ...
<python><sql-server><pandas><sqlalchemy><pyqt5>
2023-04-21 15:48:53
1
371
Andrew
76,074,745
21,420,742
Finding the previous value and creating a new column in python
<p>I have a dataset and I want to go back and see the previous value that has changed by group and creating a new column with the previous value.</p> <p>Sample Data:</p> <pre><code> Group Value 01 10 01 10 01 10 02 5 02 5 02 15 03 20 03 25 03 15 03 15...
<python><python-3.x><pandas><dataframe><numpy>
2023-04-21 15:45:16
1
473
Coding_Nubie
76,074,708
21,420,742
Finding and Comparing Previous Rows to current value Python
<p>I have a dateset and I want to go back and see the previous value that has changed.</p> <p>Sample Data:</p> <pre><code> Group Value 01 10 01 10 01 10 02 5 02 5 02 15 03 20 03 25 03 15 03 15 </code></pre> <p>Desired Output:</p> <pre><code>Group ...
<python><python-3.x><pandas>
2023-04-21 15:41:05
2
473
Coding_Nubie
76,074,705
3,249,000
Weighted sampling from lists in polars dataframe
<p>I have a dataframe that looks something like this:</p> <pre class="lang-py prettyprint-override"><code>import polars as pl df = pl.DataFrame({&quot;group&quot; : [&quot;foo&quot;, &quot;bar&quot;, &quot;baz&quot;], &quot;elements&quot; : [ pl.int_range(0, 100, eag...
<python><dataframe><python-polars>
2023-04-21 15:40:50
2
2,182
Theolodus
76,074,582
3,231,250
efficient way to apply function to column pairs in the dataframe without loop
<p>I have a dataframe and lets say shape is 1000x9000. I want to take each pair of columns (A,B or B,C etc.) and apply a custom function on this vectors (It returns a single value not vector).<br /> In the end I will have square matrix as number of features X features.<br /> <strong>In another way to say, I want to app...
<python><pandas><numpy>
2023-04-21 15:24:51
0
1,120
Yasir
76,074,477
8,188,498
Callback with dynamic number of Input
<p>I am creating a component in Dash with rows. After a user clicks on a submit button, a figure with multiple lines (each row a line) should get created.</p> <p>This rows component could have been a table component, but since my component contains buttons in one of the columns, I created it manually with divs. The rea...
<python><pandas><callback><plotly><plotly-dash>
2023-04-21 15:10:55
2
1,037
Georgios
76,074,473
5,852,692
Constant value infront of the Gaussian Process Kernel
<p>I would like to use GP for a surrogate model for my optimization problem. I found a nice example from <code>scikit learn</code>, which can be found: <a href="https://scikit-learn.org/stable/auto_examples/gaussian_process/plot_gpr_noisy_targets.html#sphx-glr-auto-examples-gaussian-process-plot-gpr-noisy-targets-py" r...
<python><optimization><scikit-learn><constants><gaussian-process>
2023-04-21 15:10:24
0
1,588
oakca
76,074,413
1,914,781
adjust plotly subplot xlabel and ylabel distance
<p>How to adjust the subplot graph xlabel and ylabel distance to the graph? Current xlabel and ylabel distance a little bit far away from the graph.</p> <pre><code>from plotly.subplots import make_subplots import plotly.graph_objects as go def save_fig(fig,pngname): width = 800 height = 400 fig.write_image...
<python><plotly>
2023-04-21 15:03:43
1
9,011
lucky1928
76,074,399
6,734,243
how to execute a script that will modify my package at build time?
<p>We have the following package structure:</p> <pre><code>. ├── genreate_source/ │ ├── generate_schema.py │ ├── generate_source.py │ └── __init__.py ├── ipyvuetify/ │ ├── template.py │ ├── Html.py │ ├── Themes.py │ ├── Template.py │ └── _init__.py ├── pyproject.toml └── setup.py </code></pre> <p>the ma...
<python><setuptools>
2023-04-21 15:01:20
1
2,670
Pierrick Rambaud
76,074,394
2,201,603
TypeError: 'MultiPolygon' object is not iterable
<p>I am trying to run the below script from plotly: <a href="https://plotly.com/python/county-choropleth/" rel="noreferrer">https://plotly.com/python/county-choropleth/</a></p> <p>I'm receiving the error code right out the gate: TypeError: 'MultiPolygon' object is not iterable</p> <p>I've looked up several posts where ...
<python><plotly><plotly-dash><geopandas>
2023-04-21 15:00:31
3
7,460
Dave
76,074,392
9,712,270
Better way to setup a nested object structure
<p>I've recently started with Python and want to write a simple API for data scrapping from a web side with selenium. Now I am having issues with keeping the code organized.</p> <p>Currently it looks something like this</p> <pre><code>def get_tasks(): # Init driver and open requried page driver = init() class ...
<python><oop><selenium-webdriver>
2023-04-21 15:00:17
1
1,914
magicmn
76,074,369
2,544,760
Efficiently changing values in dataframe
<p>my goal is to update one column's values to np.nan where a second column has a certain value. Here's an example of what I mean:</p> <pre><code> c1 c2 a 1 8 b 2 8 c 3 8 d 4 8 e 32 8 f 32 8 g 2 8 </code></pre> <p>should become</p> <pre><code> c1 c2 a 1 8 b 2...
<python><pandas>
2023-04-21 14:58:22
0
358
irh
76,073,945
3,383,318
Pad zeros with previous value: is there a faster way?
<p>I have a tensor of size (1024x160) and I want to replace zeros by the value before in a rowwise fashion. So for each row seperately. An example of one row: [1.0, 0.0, 0.0, 0.0, 2.1, 0.0, 3.0] should become [1.0, 1.0, 1.0, 1.0, 2.1, 2.1, 3.0].</p> <p>I searched stackoverflow and found an excellent answer to solve thi...
<python><tensorflow><tensorflow2.0>
2023-04-21 14:04:58
2
304
Ruben
76,073,851
17,596,179
Querying s3 parquet files using duckdb
<p>I am trying to query my parquet files stored in my s3 bucket. But when I try to query from my s3 path it adds 's3.amazonaws.com' at the end of my bucket. this is my code</p> <pre><code>import boto3 import duckdb import os sts_client = boto3.client('sts') assumed_role_object = sts_client.assume_role( RoleArn='ar...
<python><amazon-web-services><amazon-s3><amazon-iam><duckdb>
2023-04-21 13:53:27
0
437
david backx
76,073,793
3,490,622
How to get upper/lower parts of a numpy array relative to 45 degree diagonal?
<p>I am trying to figure out how to get the upper and lower triangles of a numpy matrix relative to the 45 degree diagonal from lower left to upper right. In other words, if my numpy array is</p> <pre><code>a = np.array([[1,2,3],[4,5,6],[7,8,9]]) </code></pre> <p>I want arrays containing [1,2,3],[4,5],[7] in one (with...
<python><arrays><numpy>
2023-04-21 13:46:22
2
1,011
user3490622
76,073,605
1,150,683
Add py.typed as package data with setuptools in pyproject.toml
<p>From what I read, to make sure that the typing information of your code is distributed alongside your code for linters to read, the <code>py.typed</code> file should be part of your distribution.</p> <p>I find answers for how to add these to <a href="https://stackoverflow.com/a/53034060/1150683">setup.py</a> but it ...
<python><setuptools><pyproject.toml><typed>
2023-04-21 13:25:19
2
28,776
Bram Vanroy
76,073,586
19,980,284
Generate bidirectional bar chart in matplotlib with variables in center of chart
<p>I have this dataframe:</p> <pre><code>variable level margins_fluid margins_vp 0 volfluid 1L 0.718 0.690 1 volfluid 2L 0.501 0.808 2 volfluid 5L 0.181 0.920 3 MAP 64 0.434 0.647 4 MAP 58 0.477 ...
<python><pandas><matplotlib><bar-chart>
2023-04-21 13:23:06
2
671
hulio_entredas
76,073,297
20,220,485
Excel Viewer for Visual Studio Code not displaying decimal point in string if it follows numerical digits
<p>I've included in this example a mix of strings, integers, and floats. This behaviour is unsuprising for integers and floats, however, I would like to ensure that the decimal at the end of strings is always displayed.</p> <p>Is there a way to do this?</p> <pre><code>import pandas as pd df = pd.DataFrame({'col1': ['a....
<python><csv><visual-studio-code>
2023-04-21 12:44:56
1
344
doine
76,073,250
14,015,493
Using JS WebSocket inside a Docker compose network
<p>I am currently developing a bidirectional API using Python FastAPI as the backend and ReactJS as the frontend. As the API calls should be scalable, I want to create multiple replicas that can be accessible via an Nginx server that also runs in Docker. Here is my docker compose file:</p> <pre class="lang-yaml prettyp...
<python><docker><nginx><websocket><fastapi>
2023-04-21 12:39:14
1
313
kaiserm99
76,073,118
7,445,528
How to parse boolean with PyScript from HTML to Python
<p>From a PyScript app, I am providing two radio buttons in my <code>index.html</code>, allowing a user to decide wether synthesis of isotropic gaussian blobs should be overlapping or not (effectively by toggling the value of <code>Scikit-Learn</code>'s <code>cluster_std</code> value for the <code>make_blobs</code> met...
<javascript><python><python-3.x><webassembly><pyscript>
2023-04-21 12:21:26
1
4,039
Gustav Rasmussen
76,072,801
9,350,030
python jsonschema - get the reason of validation failure
<p>I have a json file which I need to compare with official F5 schema. Everything works but when I do any mistake it does not show me a path or an error, it just shows me that its valid under any of the given schemas.</p> <p>My json file:</p> <pre class="lang-json prettyprint-override"><code>{ &quot;schema&quot;: &q...
<python><jsonschema>
2023-04-21 11:39:38
1
315
sundrys1
76,072,664
6,241,997
Convert PySpark Dataframe to Pandas Dataframe fails on timestamp column
<p>I create my pyspark dataframe:</p> <pre><code>from pyspark.sql import SparkSession from pyspark.sql.types import StructType, StructField, BinaryType, ArrayType, StringType, TimestampType input_schema = StructType([ StructField(&quot;key&quot;, StringType()), StructField(&quot;headers&quot...
<python><pandas><dataframe><apache-spark><pyspark>
2023-04-21 11:21:21
5
1,633
crystyxn
76,072,662
3,116,231
getting ResourceWarning when running unit tests testing Azure keyvault related classes
<p>I'm testing Python code which creates Azure key vaults and secrets. I've written a wrapper class for basic Azure keyvault functions, to create and delete keyvaults.</p> <p>When running my unittests I get following warning:</p> <pre><code>./opt/homebrew/Cellar/python@3.9/3.9.16/Frameworks/Python.framework/Versions/3....
<python><azure><python-unittest><azure-keyvault>
2023-04-21 11:20:52
0
1,704
Zin Yosrim
76,072,583
1,200,914
Update sqlite3 in docker image
<p>I'm checking my sqlite3 version using:</p> <pre><code>python -c &quot;import sqlite3; print(sqlite3.sqlite_version)&quot; </code></pre> <p>on my local machine, this prompts me 3.41.1. However, once I build my docker image if I do:</p> <pre><code>sudo docker exec -t &lt;docker_image_number&gt; python -c &quot;import ...
<python><docker><sqlite>
2023-04-21 11:10:35
1
3,052
Learning from masters
76,072,490
17,795,398
How to set an item with two left icons in a List from a .kv file?
<p>I'm learning <code>kivymd</code> and I would like to create a <code>MDList</code> with an <code>OneLineAvatarIconListItem</code> that has two left icons. The <a href="https://kivymd.readthedocs.io/en/1.1.1/components/list/#custom-list-item" rel="nofollow noreferrer">docs</a> only show how to do that with two right i...
<python><kivymd>
2023-04-21 10:59:12
1
472
Abel Gutiérrez
76,072,450
7,021,642
Why a change in routing policy in tornado results in sending Type Error?
<p>I am trying to change the whole webpages from serving on absolute path to relative path, but something went wrong as the request goes to the back-end tornado 5.0 server.</p> <p>The javascript is like this:</p> <pre><code> $.ajax({ url:'../pyctp/get_ctp_info.ctp', type:'p...
<python><tornado>
2023-04-21 10:54:42
1
535
George Y
76,072,449
11,795,964
Create a new pandas column from map of existing column with mixed datatypes
<p>I want to categorise an existing pandas series into a new column with 2 values (planned and non-planned)based on codes relating to the admission method of patients coming into a hospital.</p> <p>The codes fall into two main categories - planned and unplanned (=emergencies).</p> <p>I cannot get the mapping to work an...
<python><pandas><dictionary>
2023-04-21 10:54:41
1
363
capnahab
76,072,435
16,389,095
Python/Kivy: how to retrieve a widget from its id
<p>I developed a simple UI in Python/Kivy. It contains a grid layout of three rows to host three widgets. Two buttons are designed in the kv part and identified by their id:</p> <pre><code>id: 'button_create' id: button_get_ids </code></pre> <p>whilst the ddi is added to the layout when the create button is pressed, an...
<python><kivy><kivy-language>
2023-04-21 10:52:48
2
421
eljamba
76,072,426
12,436,050
PermissionError: [Errno 13] Permission denied: while writing to a file in Python 3
<p>I am trying to write the output of python script to a text file. The script runs for sometime and write the content to the file. But after sometime I get 'PermissionError: [Errno 13] Permission denied:'</p> <p>Below is my script.</p> <pre><code>def ancestor_map(id): row_icd = umls[umls['AUI'] == id] ...
<python><csv>
2023-04-21 10:50:38
1
1,495
rshar
76,072,249
2,178,942
Reading MATLAB dictionaries in Python
<p>I have created several dictionaries using MATLAB, and saved them as <code>.mat</code> file using <code>&quot;-v7.3&quot;</code> flag (as it has been suggested as a way to read <code>.mat</code> files in Python)</p> <p>My code in MATLAB is:</p> <pre class="lang-matlab prettyprint-override"><code>cnn6 = load(&quot;img...
<python><matlab><dictionary><h5py>
2023-04-21 10:22:59
1
1,581
Kadaj13
76,072,194
1,473,517
What causes the slowdown in this numba code?
<p>I have the following simple function the sums the values in the 2nd row or an array:</p> <pre><code>@njit('float64(float64[:, ::1], uint64, uint64)', fastmath=True) def fast_sum(array_2d, start, end): s = 0.0 for i in range(start, end): s += array_2d[1][i] return s </code></pre> <p>I time it with...
<python><numba>
2023-04-21 10:15:56
2
21,513
Simd
76,071,934
1,992,909
How to correctly subtype dict so that MyPy recognizes it as generic?
<p>I have a subclass of dict:</p> <pre class="lang-py prettyprint-override"><code>class MyDict(dict): pass </code></pre> <p>Later I use the definition:</p> <pre class="lang-py prettyprint-override"><code>my_var: MyDict[str, int] = {'a': 1, 'b': 2} </code></pre> <p>MyPy complains:</p> <pre><code>error: &quot;MyDict&...
<python><mypy><python-typing>
2023-04-21 09:43:33
1
1,104
A Sz
76,071,926
13,158,157
pyspark isclose alternatvie
<p>How can you pass <code>math.isclose</code> to pyspark? Pandas can utilize <code>numpy.isclose</code> but it will not work with pyspark columns. I suspect I should use broadcasting but do not know how the code would look like ?</p>
<python><math><pyspark>
2023-04-21 09:42:54
1
525
euh
76,071,842
595,305
How to get target from LibreOffice WrappedTargetException?
<p>This is about automation of LO Base using Python macros.</p> <p>Please see <a href="https://ask.libreoffice.org/t/how-to-use-macro-to-open-form-in-base/90723" rel="nofollow noreferrer">this question</a> in the LO forum posed by me yesterday.</p> <p>As you can see, from the link in my second post, it is trivial to op...
<python><exception><libreoffice-basic><libreoffice-base>
2023-04-21 09:32:52
1
16,076
mike rodent
76,071,801
888,842
Fit Matplotlib 3D subplot to figsize
<p>I have a minimum example of my code as follows:</p> <pre><code>import matplotlib.pyplot as plt fig = plt.figure(1, figsize=(16, 9)) ax = fig.add_subplot(projection='3d',elev=-150, azim=110) plt.tight_layout() plt.show() </code></pre> <p>If run my .py script i get following plot with a lot of white spaces on the ...
<python><matplotlib>
2023-04-21 09:28:08
1
537
hannes
76,071,772
4,451,521
Eliminate first and last rows with value 0 from dataframe
<p>I have a dataframe with a row with integers such as</p> <pre><code> value 0 0 0 0 1 2 0 3 0 2 5 6 0 0 0 </code></pre> <p>Is there a way that I can eliminate the first 0s and last 0s (but not the ones in the middle) to get</p> <pre><code>1 2 0 3 0 2 5 6 </code></pre>
<python><pandas>
2023-04-21 09:25:37
2
10,576
KansaiRobot
76,071,738
12,304,000
run airflow dag for previous dates
<p>I have an Airflow DAG where I run API queries based on the current date (using Python's date.today() function).</p> <pre><code>with DAG( 'load_api_date', description='test', default_args=args, start_date=datetime(year=2023, month=4, day=17), schedule_interval=None, ) as dag: ...
<python><airflow><directed-acyclic-graphs><airflow-2.x>
2023-04-21 09:20:14
1
3,522
x89
76,071,706
4,451,521
using python in a pipe
<p>I am reading a text file with cat and piping it through grep, etc Now I have several lines containing numbers</p> <p>There is a final operation that I don't think there is a operator to do what I want so I would like to do it with a python script.</p> <p>Is there a way that I can incorporate this python script in th...
<python><console><pipe>
2023-04-21 09:15:15
1
10,576
KansaiRobot
76,071,658
713,200
How to extract particular value from json response using python based on a condition?
<p>After doing a GET call I get a json response, I need a get a particular value from that json response Here is the json response</p> <pre><code>{ &quot;identifier&quot;: &quot;id&quot;, &quot;items&quot;: [ { &quot;channelGroupId&quot;: 26, &quot;controlMethod&quot;: &quot;MANU...
<python><json><python-3.x><list><dictionary>
2023-04-21 09:09:52
1
950
mac
76,071,635
11,938,023
Is there a fast way to build numpy/pandas diagonal to a matrix
<p>Ok,i have an array of systems = np.array([ 1, 3, 1, 7, 1, 15, 1, 7, 1, 3, 1], dtype=np.int8)</p> <p>I want to know if there is a faster way to build the following dataframe or numpy matrix rather than the formula what im using now:</p> <pre><code> systems = np.array([ 1, 3, 1, 7, 1, 15, 1, 7, 1, 3, 1...
<python><numpy><matrix>
2023-04-21 09:07:47
2
7,224
oppressionslayer
76,071,609
6,195,489
Using both API Key & Basic Auth in Python or Postman
<p>I have an API end-point that I have been given an API key for, but it also looks to have basic auth in front of it.</p> <p>Can someone explain how I can use both basic Auth and an apiKey with Postman, or requests in python?</p> <p>When I use the authentication section in Postman it will only let me pick one or the o...
<python><python-requests><postman>
2023-04-21 09:05:26
1
849
abinitio
76,071,586
3,668,129
gradio HTML component with javascript code don't work
<p>I'm trying to integrate <code>HTML</code> file (which contains <code>javascript</code> function) to <code>gradio</code> HTML component (<code>gr.HTML</code>) and it seems not to work together:</p> <p>Gradio app:</p> <pre><code>import gradio as gr with open(&quot;test.html&quot;) as f: lines = f.readlines() wit...
<python><gradio>
2023-04-21 09:01:16
2
4,880
user3668129
76,071,569
10,693,596
Is it possible to exit the command window when Holoviz Panel application browser window is closed?
<p>I am writing an application that uses Holoviz <code>panel</code>. After interaction with the application is completed, I close the browser window, but the server remains running in the terminal/command line window.</p> <p>Is it possible to automatically close the terminal/command line window if the browser tab displ...
<python><powershell><terminal><holoviz><holoviz-panel>
2023-04-21 08:58:53
1
16,692
SultanOrazbayev
76,071,380
5,551,539
Stack plots generated in a loop
<p>I am running an <code>if</code> loop and want to stack the resulting plots in a grid. This is my sample code, which generates two random variables and plots a third one under two conditions:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt # Set seed for reproducibility np.random.seed(42) # Genera...
<python><numpy><matplotlib><plots.jl>
2023-04-21 08:34:12
1
301
Weierstraß Ramirez
76,071,272
891,975
Changing a node in hdfs
<p>We have the code uploading config file to HDFS:</p> <pre><code>from hdfs import InsecureClient def upload_file_to_hdfs(local_path, remote_path): client = InsecureClient(url='http://hdfs_server:50070', user='dr.who') try: ret = client.upload(remote_path, local_path) except Exception as e: ...
<python><hadoop><hdfs>
2023-04-21 08:20:45
1
1,913
Павел Иванов
76,071,267
5,669,713
How to create permeant "cache" directory for AWS Lambda function
<p>I have a python script, dockerized and running as a Lambda function in AWS that performs data extraction on an XBRL file with py-xbrl when triggered. Pared down, the important part of the python script is:</p> <pre class="lang-py prettyprint-override"><code>from xbrl.cache import HttpCache from xbrl.instance import ...
<python><amazon-web-services><aws-lambda>
2023-04-21 08:20:12
1
355
Alex Howard
76,071,127
6,681,932
Find spline knots by variable in python
<p>When fitting a linear <code>GAM</code> model in <code>python</code> imposing n_splines=5, a piecewise-linear function is fitted:</p> <pre><code>import statsmodels.api as sm from pygam import LinearGAM data = sm.datasets.get_rdataset('mtcars').data Y = data['mpg'] X = data.drop(&quot;mpg&quot;,axis=1) model = Line...
<python><spline><gam><coefficients>
2023-04-21 07:59:57
1
478
PeCaDe
76,071,117
6,439,229
Why do python enum members have an infinite recursion of all members as attributes?
<p>Python enum members have all others members of the enum as attributes, including themselves, and those have too. So there is an infinite recursion of all members.</p> <pre><code>from enum import Enum class TT(Enum): m1 = 1 m2 = 2 m3 = 3 t1 = TT['m1'] t1.m2.m3.m3.m1.m2.m2.m1.m3.value &gt;&gt;&gt; 3 ...
<python><enums>
2023-04-21 07:58:05
2
1,016
mahkitah
76,071,012
10,829,044
pandas dynamic date filter and compute 3 new columns based on past
<p>I have two dataframes that looks like below</p> <pre><code> transaction_df = pd.DataFrame({'cust_name': ['ABC','ABC','ABC','ABC','ABC','ABC'], 'partner':['A','A','A','B','C','C'], 'part_no':['P1','P2','P1','P2','P3','P3'], 'transaction_date':['2...
<python><pandas><dataframe><list><group-by>
2023-04-21 07:44:03
1
7,793
The Great
76,070,711
13,971,251
How to make a window scroll when the turtle hits the edge
<p>I made this Python program that uses psutil and turtle to graph a computer's CPU usage, real time. My problem is, when the turtle hits the edge of the window it keeps going, out of view - but I want to make the window scroll right, so the turtle continues graphing the CPU usage while staying at the edge of the windo...
<python><turtle-graphics><python-turtle><psutil>
2023-04-21 07:05:11
1
1,181
Kovy Jacob
76,070,545
12,370,687
FastAPI difference between `json.dumps()` and `JSONResponse()`
<p>I am exploring FastAPI, and got it working on my Docker Desktop on Windows. Here's my <code>main.py</code> which is deployed successfully in Docker:</p> <pre><code>#main.py import fastapi import json from fastapi.responses import JSONResponse app = fastapi.FastAPI() @app.get('/api/get_weights1') async def get_wei...
<python><json><rest><fastapi><jsonresponse>
2023-04-21 06:42:43
2
5,679
blackraven
76,070,398
6,552,836
Batch Interval Optimisation
<p>I'm trying to optimize an advertising budget plan. The advertising budget plan is made up of 2 products, each product having adverts of different durations. The optimizer should achieve two goals:</p> <ol> <li>Decide which weeks to place the adverts</li> <li>How much budget to allocate for each advert, given the pro...
<python><optimization><scipy-optimize><constraint-programming><scipy-optimize-minimize>
2023-04-21 06:18:48
1
439
star_it8293
76,070,292
6,703,783
Why am I not able to create a data frame with correct values when combining 2 dataframes
<p>I have 2 <code>dataframes</code>. I want to combine them</p> <p><code>dataframe 1</code> has columns <code>content</code> and <code>embeddings</code></p> <pre><code>myquerycontents_and_embeddings_df.content 0 i live in space 1 i live my life to fullest 2 ...
<python><apache-spark>
2023-04-21 06:00:50
1
16,891
Manu Chadha
76,070,248
4,238,247
Python and Gekko optimization
<p>I'm not familiar with optimizations and I want to achieve a goal as following:</p> <p>Suppose I have 3 lists of constants:</p> <pre><code>list_1 = [1, 2, 3, 4] list_2 = [5, 8, 10, 11] list_3 = [20, 27, 89, 100] </code></pre> <p>I want to find 3 indexes <code>i1, i2, i3</code>, corresponding to the 3 lists above, suc...
<python><optimization><gekko>
2023-04-21 05:50:16
1
451
edhu
76,070,169
16,935,119
Extract data from csv ignoring spaces in header
<p>I have a csv in my project folder(file2.csv). But here the &quot;Name&quot; column has a space &quot;Name &quot; as shown. But while extracting the file, can we ignore the white spaces.</p> <pre><code>data2 = {'Name ' : ['Tom', 'Nick', 'Tom'], 'Cat' : ['xxx', 'yyy', 'zzz']} d2 = pd.DataFrame(data2) </code></pre> <p>...
<python><pandas>
2023-04-21 05:32:57
3
1,005
manu p
76,070,016
6,569,084
pytorch simulate dropout when evaluating model against test data
<p>We are training a resnet model using the CIFAR 10 dataset and we are trying to do the following:</p> <p>After we have trained the model itself we want to simulate dropout during the model evaluation when we are feeding the test data to it. I know it might sound weird because dropout is a regularization mechanism, bu...
<python><deep-learning><pytorch>
2023-04-21 04:58:55
1
702
Eitank
76,069,849
19,113,780
matplotlib and Axes3D give a blank picture
<p>I want to draw a 3D picture with these data using <code>matplotlib</code> and <code>Axes3D</code></p> <pre class="lang-py prettyprint-override"><code>import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D data = np.array([[4244.95, 4151.69, 2157.41, 829.769, 426.253, 215.655], ...
<python><matplotlib>
2023-04-21 04:15:19
2
317
zhaozk
76,069,846
21,107,707
Register function raising a NameError when referencing the class?
<p>I am trying to register various methods within a class using a registry function. This is the relevant parts of the code I have:</p> <pre class="lang-py prettyprint-override"><code>class Quantity: _CONVERT_FUNCS = [] def __register_conversion(func): Quantity._CONVERT_FUNCS.append(func) retu...
<python><python-3.x>
2023-04-21 04:13:16
1
801
vs07
76,069,841
16,527,596
Why can't I call the functions within the class?
<p>I just started Python OOP. I have to build a simple class and function, but I don't understand why it works in one case, but doesn't in the other.</p> <pre class="lang-py prettyprint-override"><code>class Digital_signal_information: def __init__(self, signal_power: float, noise_power: float, n_bit_mod: int): ...
<python><oop>
2023-04-21 04:10:25
2
385
Severjan Lici
76,069,720
6,747,697
Django ORM distinct over annotated value
<p>I have a model which has a <code>DateTimeField</code> timestamp. What would be the best way to see the number of entries for each day (month, hours etc.) just by using Django ORM (not raw SQL)?</p>
<python><django><django-orm>
2023-04-21 03:38:28
2
383
Dmitry Sazhnev
76,069,659
20,122,390
How do I query a realtime firebase JSON database for a field?
<p>I would like to query a real time Firebase database to find a document according to its source These are the fields that the document has:</p> <pre><code>class Document(BaseModel): _id: str series: str Country: str Date: str source: str </code></pre> <p>For which I have defined the following fun...
<python><database><firebase><firebase-realtime-database><fastapi>
2023-04-21 03:22:55
0
988
Diego L
76,069,634
11,782,991
Python 3 and pandas parsing a long date format in Excel
<p>I'm trying to use python and pandas to select specific dates from an excel spreadsheet. However, the code below always returns: Empty DataFrame</p> <p>It does show correct columns and I can select other columns. Am I doing anything wrong here? I suspect the date format in the excel spreadsheet is the problem ex. 'Sa...
<python><pandas>
2023-04-21 03:15:11
2
332
nwood21
76,069,561
1,326,306
Is there a way to print tabular data, fits the terminal size using python?
<p>I want to find an approach to print list as tabular table. There is many library help me to do that. But when the size of list is too long, it's not convenient to view results.</p> <pre><code>root@debian:~# print.py name | score -----+------ Tim | 99 Ana | 80 Jim | 100 Tim | 100 Tom | 150 ... long outputs ... ...
<python>
2023-04-21 02:54:01
2
901
HUA Di
76,069,484
5,528,270
Obtaining detected object names using YOLOv8
<p>We are trying to get the detected object names using Python and YOLOv8 with the following code.</p> <pre><code>import cv2 from ultralytics import YOLO def main(): cap = cv2.VideoCapture(0) cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1280) cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 720) model = YOLO(&quot;yolov8n.pt...
<python><python-3.x><object-detection><yolo><yolov8>
2023-04-21 02:27:05
4
1,024
Ganessa
76,069,337
14,315,663
How to create a function which applies lag to a numpy array in python?
<p>Here are 3 numpy arrays with some numbers:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np arr_a = np.array([[0.1, 0.2, 0.3, 0.4], [0.2, 0.3, 0.4, 0.5], [0.3, 0.4, 0.5, 0.6], [0.4, 0.5, 0.6, 0.7], [0.5, 0.6, 0.7, 0.8], ...
<python><arrays><numpy><function><lag>
2023-04-21 01:43:57
1
595
kiwi
76,069,280
11,531,123
Tensorflow 2: GPU training is not faster than CPU training
<p>Recently I've been fiddling around with tensorflow 2.0. I had not used it in 2-3 years, but I know that I can use my GPU. I had most recently worked with PyTorch and when comparing my computer vs someone else that didn't have a GPU and was using Colab, it was night and day. My machine was so much faster.</p> <p>But ...
<python><tensorflow><gpu>
2023-04-21 01:23:54
0
435
Khachatur Mirijanyan
76,069,215
3,755,861
plotly polar plot: axis and background color
<p>I have discovered plotly and have a few questions: I would like to change all axis to black (not white). Below modified example code from their webpage, where I have set both radial and angular axis to black. I can use linecolor = 'black', but it seems that then the line going to 0 is thicker than the others?</p> <p...
<python><plotly>
2023-04-21 01:03:21
1
452
Pugl
76,069,205
1,503,005
How to detect client disconnection when servicing a streaming endpoint with http.server
<p>We have a simple web server written in Python's <code>http.server</code>. One of its endpoints serves streaming data - a series of events, with new events sent as they occur. We've successfully set up this endpoint so that it delivers the data as expected. However, if the client disconnects, the server does not dete...
<python><http><sockets><streaming><http.server>
2023-04-21 01:00:29
0
635
macdjord
76,069,185
194,305
swig ignore std::enable_shared_from_this
<p>I am trying to ignore std::enable_shared_from_this base class.</p> <p>Below are my files</p> <p>test.h:</p> <pre><code>#ifndef _TEST_H_INCLUDED_ #define _TEST_H_INCLUDED_ #include &lt;memory&gt; class Test : public std::enable_shared_from_this&lt;Test&gt; { public: Test() : val_(0) {} virtual ~Test() {} ...
<python><c++11><templates><swig>
2023-04-21 00:54:39
1
891
uuu777
76,069,184
457,935
Django ORM annotate query with length of JSONField array contents
<p>I have a basic Model with a JSONField that defaults to a list:</p> <pre><code>class Map(models.Model): id = models.UUIDField( primary_key=True, editable=False, default=uuid.uuid4, ) locations = models.JSONField( default=list, blank=True, encoder=serializers.json.DjangoJSON...
<python><django>
2023-04-21 00:54:24
1
1,237
saschwarz
76,069,122
5,858,752
How to group by an integer column and sum up each row except for maybe the last row
<p>I have a dataframe with 3 columns. The first 2 columns are <code>id</code> and <code>cost</code> which is an integer and float, respectively. The last column is a boolean flag, <code>omit</code>. The rows with the same <code>id</code> are already prearranged contiguously. All the rows have <code>omit = False</code>,...
<python><pandas><dataframe>
2023-04-21 00:35:33
2
699
h8n2
76,069,066
7,250,111
How to draw multiple rectangles using Vispy?
<p>I referred to this example : <a href="https://vispy.org/gallery/scene/polygon.html#sphx-glr-gallery-scene-polygon-py" rel="nofollow noreferrer">https://vispy.org/gallery/scene/polygon.html#sphx-glr-gallery-scene-polygon-py</a></p> <p>I want to draw multiple same shaped rectangles, but I don't understand how to set t...
<python><vispy>
2023-04-21 00:23:00
1
2,056
maynull
76,068,961
2,981,639
Is there a `pip` flag to upgrage to latest release candidate
<p>First I want to confirm if this is expected pip behaviour or not:</p> <p>We're using <code>Sonatype Nexus Repository Manager</code> as an onsite package repository, and <code>setuptools_scm</code> to version our packages. So when I build a release candidate it obtains a version such as <code>0.4.1rc1</code></p> <p>I...
<python><pip>
2023-04-20 23:53:59
1
2,963
David Waterworth
76,068,934
4,450,498
How can I get the raw byte offsets of individual datasets in an HDF5 file using Python?
<p>The byte offsets of individual (contiguous) datasets in an HDF5 file can be determined using the <a href="https://docs.hdfgroup.org/hdf5/develop/_view_tools_view.html#subsecViewToolsViewContent_h5ls" rel="nofollow noreferrer"><code>h5ls</code> tool</a> distributed as part of the <a href="https://www.hdfgroup.org/dow...
<python><hdf5><h5py>
2023-04-20 23:46:32
1
992
L0tad
76,068,754
758,986
Why don't breakpoints work in Tensorflow function (in lazy/graph mode)?
<p>I have a code like this that loads data:</p> <pre class="lang-py prettyprint-override"><code>def parse_tf_record(example_proto: tf.train.Example, symbols: t.List[str], all_indicators: t.List[str], indicators: t.List[str]) -&gt; None: feature_description = {symbol: tf.io.FixedLenFeature([len(all_indicators)], tf....
<python><python-3.x><tensorflow><tensorflow2.0>
2023-04-20 22:56:50
1
2,011
DimanNe
76,068,692
547,231
Compiling Mitsuba 2 on Visual Studio 2022 (SCons error)
<p>I try to build the <code>mitsuba-msvc2010.sln</code> using Visual Studio 2022. I fail to successfully build this solution; most probably due to some changes in SCons. This is the error I obtain</p> <blockquote> <p>AttributeError: 'SConsEnvironment' object has no attribute 'has_key': 1&gt; File &quot;SConstruct&quot...
<python><python-3.x><visual-studio-2022><python-2.x><scons>
2023-04-20 22:36:49
1
18,343
0xbadf00d