QuestionId
int64
74.8M
79.8M
UserId
int64
56
29.4M
QuestionTitle
stringlengths
15
150
QuestionBody
stringlengths
40
40.3k
Tags
stringlengths
8
101
CreationDate
stringdate
2022-12-10 09:42:47
2025-11-01 19:08:18
AnswerCount
int64
0
44
UserExpertiseLevel
int64
301
888k
UserDisplayName
stringlengths
3
30
⌀
77,281,118
5,462,743
Azure Machine Learning SDK V1 migration to V2 Pipeline Steps
<p>I am trying to migrate Pipelines from Azure Machine Learning SDK V1 to V2, but sometimes I don't understand the logic behind the V2 and I get stuck.</p> <p>In V1, I just had to create PythonScriptStep and wrap it into a StepSequence and deploy the pipeline. My scripts are simple, no input, no outputs. We store data ...
<python><azure-machine-learning-service><azureml-python-sdk><azuremlsdk><azure-ml-pipelines>
2023-10-12 13:39:40
1
1,033
BeGreen
77,280,762
22,466,650
How to recognize groups in a column and outer border them?
<p>My input is this simple dataframe :</p> <pre><code>df = pd.DataFrame({'class': ['class_a', 'class_a', 'class_a', 'class_b', 'class_c', 'class_c'], 'name': ['name_1', 'name_2', 'name_3', 'name_1', 'name_1', 'name_2'], 'id': [5, 7, 1, 2, 3, 8]}) print(df) class name id 0 class_a name_1 5 1 class_a na...
<python><pandas>
2023-10-12 12:52:19
1
1,085
VERBOSE
77,280,611
7,729,563
Unexpected result from simple lambda function in list comprehension
<p>Note: Using Python 3.11.5 on Windows 11 (x64)</p> <pre class="lang-py prettyprint-override"><code># Input: items = [['fish:', '2'], ['cats:', '3'], ['dogs:', '5']] # Goal - convert to dictionary, strip ':' from word, convert string to int: # e.g., {'fish': 2, 'cats': 3, 'dogs': 5} # Approach - use list comprehensi...
<python>
2023-10-12 12:32:42
2
529
James S.
77,280,606
173,003
Catching a specific exception in a chain when reraising it is not an option
<p>Consider the following Python code:</p> <pre class="lang-py prettyprint-override"><code>def say(words): for word in words: if word == &quot;Ni&quot;: raise ValueError(&quot;We are no longer the knights who say Ni!&quot;) print(word) def blackbox(function, sentence): words = sente...
<python><higher-order-functions>
2023-10-12 12:31:53
1
4,114
Aristide
77,280,579
8,261,345
Pandas: vectorised way to forward fill a series using a gradient?
<p>Consider a dataframe which has a series <code>price</code> with gaps containing NaN:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np import pandas as pd df = pd.DataFrame({&quot;price&quot;: [1, 2, 3, np.nan, np.nan, np.nan, np.nan, np.nan, 9, 10]}, index=pd.date_range(&quot;2023-01-01&quot;, ...
<python><pandas><dataframe><numpy>
2023-10-12 12:27:47
1
694
Student
77,280,470
2,633,704
clicking "go to definition" in vscode use all my system ram
<p>I am using vs-code for Python coding. now I have a big issue. when I set python Interpreter and right-click on anywhere in my code and click go to definition, all my ram used by vscode ms python extension. Is there any other setting I need to do to prevent it? I have to kill the process every time that happens!</p>
<python><visual-studio-code>
2023-10-12 12:13:09
0
990
MarziehSepehr
77,280,434
2,516,783
Is there a clean way of starting a task execution straight away with asyncio.create_task()?
<p>I have the following code:</p> <pre class="lang-py prettyprint-override"><code>import asyncio import time async def coro_1(seconds=5): await asyncio.sleep(seconds) async def main_1(): task_1 = asyncio.create_task(coro_1()) # Long computation here time.sleep(5) await task_1 async def main_2(): ...
<python><python-asyncio>
2023-10-12 12:06:40
2
711
Selnay
77,280,421
3,110,458
Portable Python pip execution fails on "module pip not found"
<p>I wrote a simple Nodejs script that checks if Python is installed with the specific version and if not it will install a portable version via zip.</p> <p>Executing Python works fine but when I try to install sth via pip with :</p> <p><code>.\python.exe -m pip intstall xzy</code></p> <p>it says that pip is not insta...
<javascript><python><node.js>
2023-10-12 12:04:52
3
374
user3110458
77,280,233
7,857,466
How to in-place assign an item to a class containing a list, without inheritance?
<p>Why do I get <code>IndexError: list assignment index out of range</code> with the following code:</p> <pre><code>class MyOwnList(): def __init__(self, a_list): self.list = a_list def __getitem__(self, index): return self.list[index] def __setitem__(self, index, value): self.list[i...
<python>
2023-10-12 11:38:19
1
4,984
progmatico
77,280,130
542,270
pre-commit not picking files for pip-tools
<p>I've the following repo structure:</p> <pre><code>libs/ - l1/ - pyproject.toml - l2/ - pyproject.toml batch/ - b1/ - pyproject.toml - b2/ - pyproject.toml pipelines/ - p1/ - pyproject.toml - p2/ - pyproject.toml pyproject.toml </code></pre> <p>And the following pre-commit hook configured:</p> <pre><code>--...
<python><pre-commit-hook><pre-commit><pre-commit.com><pip-tools>
2023-10-12 11:24:36
2
85,464
Opal
77,279,937
7,307,824
Maintaining a big list of properies in a class that can be exported as a csv row
<p>I'm new to Python and trying to store a list of data in CSV format.</p> <p>I've got a wrapper class for the csv and for each row I have a <code>DataRow</code>. However, I know this code isn't very maintainable.</p> <p>Currently, if I want to add a new value I need to add a condition in the <code>set_item</code> add ...
<python><python-3.x>
2023-10-12 10:51:37
1
568
Ewan
77,279,694
6,797,800
Legend with many elements causes plot to be small
<p>As shown below, not sure whether there are too many signals in one subplot, hence the legend takes too much space, the plot itself is too small, i.e the height is short.</p> <p>How may I make the plot bigger please?</p> <p>Code for the plot</p> <pre><code>cm = 1/2.54 fig, axes = plt.subplots(nrows=len(unique_signals...
<python><matplotlib>
2023-10-12 10:13:25
1
769
Victor
77,279,621
5,211,659
How do I find an optimum selling point in a time/value series using pandas?
<p>I have a given dataset with value depreciation over time: <a href="https://i.sstatic.net/F5gnb.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/F5gnb.png" alt="value depreciation" /></a>)</p> <p>As you can see, the depreciation is not linear and sometimes even negative between two months.</p> <p>What I...
<python><pandas><dataframe>
2023-10-12 10:03:24
1
821
Daniel Becker
77,279,618
3,426,328
Wrong sorting order while using pysaprk custom sort
<p>I have a dataframe with about 20 columns and 15M rows that I have to sort, based on some conditions. I also prefer not to add new columns to the dataframe, to help setting the order.<br /> For simplicity lets say that I have the following data, where A is an integer and a1, a2 have the value of 0 or 1:</p> <p>| A| ...
<python><pyspark>
2023-10-12 10:03:14
1
6,181
TDG
77,279,578
12,412,154
AsyncIO Streams works with FastAPI but doesn't works separately
<p>So I have this class for async handling Socket connection.</p> <pre class="lang-py prettyprint-override"><code># socket_service.py class Sockets: reader: asyncio.StreamReader writer: asyncio.StreamWriter message_queue = [] async def start(self): reader, writer = await asyncio.wait_for( ...
<python><sockets><stream><python-asyncio><fastapi>
2023-10-12 09:57:41
1
543
RoyalGoose
77,279,467
6,308,605
Reading nested dictionary without using .get
<p>I have a file called <code>sample</code> (no file format) that looks like this:</p> <pre><code>{ &quot;schema&quot;: &quot;abc&quot;, &quot;region&quot;: &quot;asia&quot;, &quot;values&quot;: { &quot;before_values&quot;: { &quot;id&quot;: 123, &quot;created_at&quot;: &quot...
<python><json><dictionary>
2023-10-12 09:42:19
1
761
user6308605
77,279,465
13,123,667
Use python3 in VS Code instead of python
<p>-&gt; python3 --version = 3.10<br /> -&gt; python --version = 3.12</p> <p>I usually run my code with python3 -m main, being on my conda virtual env and it works great. But when I want to run a notebook, I choose my interpreter (correct venv) but it runs the code with python (not python3) leading to &quot;No module n...
<python><visual-studio-code><virtualenv><python-venv>
2023-10-12 09:42:11
1
896
Timothee W
77,279,396
1,107,595
embed binary file in python wheel package
<p>==Context==</p> <p>I'm building a python package that is going to be installed and used inside an AWS container lambda. My package is built using poetry and deployed in a self-managed python package index.</p> <p>One of my lambda dependency is imageio-ffmpeg, which surprisingly to me embed the ffmpeg binary see <a h...
<python><aws-lambda><python-poetry><python-wheel>
2023-10-12 09:33:44
1
2,538
BlueMagma
77,279,039
14,649,310
VS Code Python extension v2023.18.0 stopped resolving all python imports and Sort Imports option not available
<p>My VS Code was working fine, I have a pyenv environment with a specific python version and installed dependencies which I was using and all was good and suddenly it stopped recognizing all imports. <a href="https://i.sstatic.net/ITTOR.png" rel="noreferrer">They are all whited out</a>.</p> <p>Also I noticed that <a h...
<python><visual-studio-code>
2023-10-12 08:43:22
3
4,999
KZiovas
77,278,889
10,303,199
How to stream data in 4MB chunks using python (through grpc)
<p>I hava a python grpc service that streams large amounts of data to client microservices.</p> <pre><code>service GeoService { rpc GetGeoCoordinates(GetRequest) returns (stream Chunk){} } message Chunk { bytes data_part = 1; } </code></pre> <p>I can not send more that 4MB of data at once because tcp connection...
<python><python-3.x><stream><grpc-python>
2023-10-12 08:22:50
1
5,384
ABDULLOKH MUKHAMMADJONOV
77,278,879
1,422,096
Copy with SHFileOperation for files in non-drive-letter like Computer\Phone\card\DCIM\test.jpg
<p>Context: I know that using <a href="https://learn.microsoft.com/en-us/windows/win32/api/shellapi/nf-shellapi-shfileoperationw" rel="nofollow noreferrer"><code>SHFileOperation</code></a> for copying with Windows Shell has been replaced by <code>IFileOperation</code> (<em>&quot;Copies, moves, renames, or deletes a fil...
<python><windows><shell><winapi><pywin32>
2023-10-12 08:20:35
0
47,388
Basj
77,278,868
14,282,714
Get page number of certain string using pdfminer
<p>I would like to find the page number of certain string in a pdf document using <code>pdfminer.six</code>. <a href="https://www.africau.edu/images/default/sample.pdf" rel="nofollow noreferrer">Here</a> you can find some reproducible pdf document. We can use the <code>extract_pages</code> function to find the number o...
<python><pdf><nlp><pdfminer>
2023-10-12 08:17:45
1
42,724
Quinten
77,278,758
8,176,763
install superset 3.0 without building assets with npm
<p>I am trying to install apache-superset and following the guidelines on installing from sratch in their website <a href="https://superset.apache.org/docs/installation/installing-superset-from-scratch/" rel="nofollow noreferrer">https://superset.apache.org/docs/installation/installing-superset-from-scratch/</a>:</p> <...
<python><npm><apache-superset>
2023-10-12 08:01:20
0
2,459
moth
77,278,730
14,459,677
Deleting the rows in COLUMNS that do not match the rows in another column (all belonging to a 1 dataframe)
<p>My dataframe looks like this:</p> <pre><code>A B C D E F G H I J FP002 12 FP001 113 406 519 85 82 FP001 6240 FP003 7610 FP002 99 552 651 49 64 FP002 12294 FP005 12, FP003 102 131 1416 24 89 FP003 761 FP005 1250 FP004 94 739 833 122 215...
<python><pandas><join><merge>
2023-10-12 07:57:31
1
433
kiwi_kimchi
77,277,997
1,422,096
Copy file with Windows using Shell API CopyItem: "No such interface supported" for non-drive-letter paths like Computer\Phone\card\DCIM\test.jpg
<p>I'm using Windows Shell API <a href="https://learn.microsoft.com/en-us/windows/win32/api/shobjidl_core/nn-shobjidl_core-ifileoperation" rel="nofollow noreferrer"><code>IFileOperation</code></a> to copy files from a phone (connected on USB) to the PC. It would be impossible with usual file-based copy functions (<code...
<python><windows><shell><winapi><pywin32>
2023-10-12 05:51:27
1
47,388
Basj
77,277,944
6,338,996
How can I create a callable progress bar with a real-time clock in Python?
<p>I am trying to monitor a process that takes a bunch of time. My code goes through a number of files, operating on them a couple of times. The files are big, and I want to know how much time has elapsed.</p> <p>I borrowed <a href="https://stackoverflow.com/a/37630397/6338996">a progress bar that I found in SO</a>. Af...
<python>
2023-10-12 05:38:05
3
573
condosz
77,277,319
5,193,319
Why do these two python dynamic property definitions not return the same values?
<p>I have two scripts that I believed should behave the same way. Here is the first:</p> <pre class="lang-py prettyprint-override"><code>class Q: def __init__(self): self._foo = 123 self._bar = 456 self._properties = { &quot;foo&quot;: property(lambda self: getattr(self, &quot;_foo&quot;)), ...
<python>
2023-10-12 02:16:09
0
1,374
John Forbes
77,277,248
20,456,016
{ "n_estimators" } are not used during Optuna Study
<p>While performing optima study, I tried to tune <code>n_estimators</code> for xgboost in a binary classification problem, but I get:</p> <pre><code>WARNING: ../src/learner.cc:767: Parameters: { &quot;n_estimators&quot; } are not used. </code></pre> <p>Code :</p> <pre><code>def objective(trial): # Define the sear...
<python><machine-learning><xgboost><optuna>
2023-10-12 01:50:23
1
471
jerrycalebj
77,277,139
1,577,110
Install python 3.12 using mamba on mac
<p>I am trying to install python 3.12 on an M1 Apple Mac using mamba as follows ...</p> <blockquote> <p>mamba install -c conda-forge python=3.12.0</p> </blockquote> <p>It yields the following error message ...</p> <pre><code>Looking for: ['python=3.12.0'] conda-forge/osx-arm64 Usi...
<python><conda><mamba>
2023-10-12 01:09:14
1
5,141
Mark Graph
77,277,033
1,833,118
How to obtain the start and commit timestamps of transactions in MongoDB?
<h2>Motivation</h2> <p>We are working on a white-box checking algorithm of Snapshot Isolation (SI): given an execution of a database, to check whether it satisfies SI.</p> <p>The SI checking problem is <a href="https://www.lix.polytechnique.fr/%7Ecenea/papers/oopsla19.pdf" rel="nofollow noreferrer">NP-hard for general ...
<python><mongodb><transactions><timestamp><mongodb-oplog>
2023-10-12 00:21:34
0
2,011
hengxin
77,276,993
19,506,623
How to split list in sublists based on string length?
<p>I have the following input list <code>data</code></p> <pre><code>data = '''ABCD1 2040805025@HHS_2332 801111@PPOD_1 225@DDMDM DEFA1 23333@HHS_998 7859000@FGL3 44532009@LLLKH_9 225@DDMDM FGGH5 78271@WQE 8003013@UTTY7'''.split() </code></pre> <p>If I want to split in sublist of lenght 3 I can use this</p> <pre><code>In...
<python>
2023-10-12 00:07:46
2
737
Rasec Malkic
77,276,896
384,386
Coverage of C++ Code called via Pybind from Python Test
<p>Currently working with a legacy codebase that creates a number of Pybind modules and tests most of the exposed C++ code via Python tests.</p> <p>Is it possible to determine code coverage of the C++ code via Python tests? My understanding of C++ coverage is that you need to have a compiled test executable with the ob...
<python><code-coverage><pybind11>
2023-10-11 23:34:07
2
1,989
celestialorb
77,276,871
2,136,286
Python use Mac as a mouse for Android
<p>Basically I'm trying to move a mouse cursor on an android with broken screen using just USB-C cable and a Mac. The goal here is to emulate a HID device without external hardware like PyBoard or ESP32</p> <p>I'm using PyUSB library</p> <pre><code>import usb.core import usb.util import time def find_android_device():...
<python><android><emulation><pyusb>
2023-10-11 23:26:49
0
676
the.Legend
77,276,843
472,485
Setting json string in http requests in Perl
<p>Following Perl code generates an error printed below:</p> <pre><code>use strict; use Data::Dumper; use LWP::UserAgent; use JSON; my $token = 'my token'; my $ua = LWP::UserAgent-&gt;new; my $req = HTTP::Request-&gt;new(PUT =&gt; &quot;endpoint&quot;); $req-&gt;header( 'Authorization' =&gt; &quot;Bearer $token&quot; ...
<python><rest><perl><put>
2023-10-11 23:19:48
2
22,975
Jean
77,276,788
2,386,605
How to make Agents not exceed token length in Langchain?
<p>I am currently trying to make use of a ChatGPT plugin in langchain:</p> <pre><code>from langchain.chat_models import ChatOpenAI from langchain.agents import load_tools, initialize_agent from langchain.agents import AgentType from langchain.tools import AIPluginTool tool = AIPluginTool.from_plugin_url(&quot;https://...
<python><openai-api><langchain><chatgpt-api>
2023-10-11 23:01:36
1
879
tobias
77,276,779
14,459,677
Adding the values of multiple duplicated rows in python and creating another column
<p>I have file which have several columns. However, some rows are duplicated in Column1 with corresponding value in Column2.</p> <p>It looks like this:</p> <pre><code>COL1 COL2 AB 5 AB 5 AA 2 AC 3 AD 8 AD 4 </code></pre> <p>I want to create Column3 and have it like this:</p> <pre><code>...
<python><pandas><duplicates>
2023-10-11 22:58:25
0
433
kiwi_kimchi
77,276,692
16,988,223
BeautifulSoup with python unable to get value of a h2 tag
<p>I'm trying to get this value from this <a href="http://larepublica.pe/" rel="nofollow noreferrer">web page</a> from the &quot;Economia&quot; section:</p> <p><a href="https://i.sstatic.net/RLdCY.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/RLdCY.png" alt="enter image description here" /></a></p> <p>...
<python><web-scraping><beautifulsoup>
2023-10-11 22:26:39
1
429
FreddicMatters
77,276,533
4,777,670
How to convert multi-valued truth table to if-conditions or expressions
<p>I've got a table like this:</p> <pre><code>Location Weather Temperature Time of Day Activity Indoors Sunny Hot Morning Reading Indoors Sunny Hot Evening Watching TV Indoors Sunny Cool Morning Reading Indoors Sunny Cool Evening Watching TV Indoors Rainy Hot Morning Reading Indoors Rainy Hot Eveni...
<python><algorithm><karnaugh-map>
2023-10-11 21:39:30
1
3,620
Saif
77,276,440
11,145,822
Connectivity issue in DB2
<p>Getting the below error while trying to connect DB2 server from Debian GNU/Linux system. Steps I have done</p> <ol> <li>Installed ibm_db &amp; ibm_db_sa module</li> <li>Connected Python3.8 &amp; imported ibm_db, which was succesful</li> <li>Run this command &gt;&gt;&gt; ibm_db.connect(&quot;DATABASE=DB;HOSTNAME=xx.x...
<python><python-3.x><db2>
2023-10-11 21:17:00
0
731
Sandeep
77,276,311
3,609,976
imshow uses a seemingly random background color
<p>I am trying to use <code>imshow()</code>, with categorical data. But I cannot reliably control the colors used. This is my code (inspired in the solution provided <a href="https://stackoverflow.com/questions/43971138/python-plotting-colored-grid-based-on-values">here</a></p> <pre><code>from random import choice impo...
<python><matplotlib><imshow>
2023-10-11 20:46:05
0
815
onlycparra
77,276,288
9,415,280
UP Date: How remove sample from tf.data.dataset with missing or NaN values?
<p><strong>Up Date</strong> I add this command to clear sample with missing values who lead my neural network to fail:</p> <pre><code>ds = ds.ignore_errors() </code></pre> <p>I use this function to remove all samples with NaN or missing values... but it don't work well</p> <pre><code>def filter_nan_sample(ds): # fi...
<python><tensorflow><tf.data.dataset>
2023-10-11 20:40:41
1
451
Jonathan Roy
77,276,274
12,436,050
Extract values from pandas series column
<p>I have a pandas dataframe with column of type Series.</p> <pre><code>id col1 1 b'[{&quot;code&quot;:&quot;P16_HCAQNB&quot;,&quot;onto&quot;:&quot;finngen&quot;,&quot;syns&quot;:[&quot;hydrocephalus acquired newborn&quot;,&quot;of newborn acquired hydrocephalus&quot;,&quot;hydrocephalus, acquired, newborn&q...
<python><pandas>
2023-10-11 20:37:59
0
1,495
rshar
77,276,144
7,166,834
extract consecutive rows with similar values in a column more with a specific patch size
<p>I was looking out to extract consecutive rows with specified text repeated continuously for more than 5 times.</p> <p>ex:</p> <pre><code> A B C 10 john 1 12 paul 1 23 kishan 1 12 teja 1 12 zebo 1 324 vauh -1 3434 krish -1 232 poo -1 4535 zoo 1 4343 doo 1 342 foo -1 123 soo 1 121 k...
<python><pandas><group-by>
2023-10-11 20:12:30
2
1,460
pylearner
77,276,097
5,253,084
Windows exec built by nuitka fails by not finding a file
<p>I have a python (11) application running under Windows 10 in a virtual environment. It works fine. However, when I build an executable with nuitka it fails. Here is the relevant code:</p> <pre><code>import speech_recognition as sr self.recognizer = sr.Recognizer() with self.microphone as source: sel...
<python><speech-recognition><pyaudio><nuitka>
2023-10-11 20:03:27
2
365
fredm73
77,276,047
1,181,065
The added layer must be an instance of class Layer. Found: KerasTensor
<pre><code>from tensorflow.keras import regularizers def model_variant(model, num_feat_map, dim, network_type, p): print(network_type) if network_type == 'ConvLSTM': model.add(Permute((2, 1, 3))) model.add(Reshape((-1, num_feat_map * dim))) lstm_output = Bidirectional(LSTM(128, return_s...
<python><tensorflow><keras><deep-learning>
2023-10-11 19:52:33
0
539
Hanna
77,276,038
10,413,759
How to merge Firefox bookmarks exported as json (dictionaries within dictionaries structure)
<p>I am trying to make a new dictionary that is made from an existing dictionary that it has been creating from a function which tries to merge two dictionaries that derive from json files from backup firefox bookmarks.</p> <p>1st json bookmark dictionary:</p> <pre><code>json1={'guid': 'root________', 'title': '', 'ind...
<python><recursion><parent-child>
2023-10-11 19:50:29
2
378
K Y
77,275,834
7,387,749
TensorFlow: Read an Image Dataset from csv file
<p>How can I create a <code>TensorFlow</code> image dataset from a <code>Pandas DataFrame</code> that contains image file paths and labels?</p> <p>I have a <code>.csv</code> file from which I have loaded a <code>Pandas DataFrame</code>. The DataFrame has two columns: <code>img_path</code>, which contains the file paths...
<python><pandas><tensorflow>
2023-10-11 19:12:43
1
4,980
Simone
77,275,603
1,671,319
How do I use pytest and unittest.mock to mock interactions with a paramiko.SSHClient
<p>I am trying to write a unit test for code that interacts with an SFTP server using the <code>paramiko</code> library. The code under test receives a list of remote file locations and a callback. Each file is fetched and sent into the callback. The test shall simulate a scenario, where the caller sends two files to v...
<python><unit-testing><pytest><python-unittest.mock><pytest-mock>
2023-10-11 18:34:50
1
3,074
reikje
77,275,476
1,678,467
Do numpy.savez and numpy.savez_compressed use pickle?
<p>I recently encountered numpy.savez and numpy.savez_compressed. Both seem to work well with arrays of differing types, including object arrays. However, numpy.load does not work well with object type arrays. For example:</p> <pre><code>import numpy as np numbers = np.full((10, 1), np.pi) strings = np.full((10, 1)...
<python><numpy><pickle>
2023-10-11 18:14:44
3
6,303
tnknepp
77,275,430
10,967,961
Cannot open New python3 in jupyter
<p>I am trying in all ways to open a new Python 3 ipynb file from jupyter. I tried brew uninstalling jupyter, updating python3 and following the steps described here: <a href="https://medium.com/@iamclement/how-to-install-jupyter-notebook-on-mac-using-homebrew-528c39fd530f" rel="nofollow noreferrer">https://medium.com/...
<python><jupyter-notebook>
2023-10-11 18:06:09
0
653
Lusian
77,275,400
113,586
Create a typing.Annotated instance with variadic args in older Python
<p>The question is simply how to reproduce this:</p> <pre><code>import typing a = [1, 2, 3] cls = typing.Annotated[int, *a] </code></pre> <p>or even this:</p> <pre><code>import typing cls1 = typing.Annotated[int, 1, 2, 3] unann_cls = typing.get_args(cls1)[0] metadata = cls1.__metadata__ cls2 = typing.Annotated[unann_...
<python><python-typing>
2023-10-11 18:00:25
1
25,704
wRAR
77,275,300
565,341
How to load a numpy file (.npy) in DJL?
<p>I have traced a model in PyTorch and loaded it in successfully in DJL. Now I want to make sure pre/postprocessing works correctly in my JAVA server. I have written the result of the pre- and postprocessing into numpy files (<code>.npy</code>), e.g. with <code>np.save('preprocessed.npy', some_tensor.detach().numpy())...
<python><java><numpy><djl>
2023-10-11 17:45:24
1
1,467
Christoph Henkelmann
77,275,149
4,709,889
Use python code block to change raw rows from Google Sheets into list of lists
<p>I am working with data set I pull from Google sheets into Zapier. The data set looks like the below, and I am writing a code block to compare a users values against the all the values in the data set.</p> <pre><code>Bank | Product | Bundle | Restriction Geo | Restriction Geo 2 | Restriction Geo Val | R...
<python><python-3.x><google-sheets><zapier>
2023-10-11 17:20:46
1
391
FrenchConnections
77,275,096
8,378,817
Handling empty list in for loop python
<p>I have come across a situation where I am dealing a nest list with nested dictionaries. Sometimes, one of the dictionary key would have an empty list. So, when iterating with for loop, I am getting and list index out of range error.</p> <p>Below, I will give you a small portion of the data from dataframe:</p> <pre><...
<python><python-3.x><pandas><dataframe><list>
2023-10-11 17:12:53
3
365
stackword_0
77,275,088
4,594,924
Unable to run my test file using pytest framework
<p>I have python application and tried to write a test cases. These test cases are importing actual functions resides in my src folder. In IDE, I don't find any error. But when I execute I am getting as below.</p> <p>My project structure is</p> <pre><code>myapplication |-&gt; src |-&gt;my_app |-&gt;...
<python><pytest>
2023-10-11 17:12:04
0
798
Simbu
77,275,050
8,387,921
Use for loop and .loc to create a new column and add value equals to lenght of first column data
<p>I am very new to pandas, So i am trying to create a new column and add the value of column as total lenght of names of first column. But it is giving all column value same which is equal to the value of lenght of last item of first column.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="tr...
<python><pandas>
2023-10-11 17:05:15
1
399
Sagar Rawal
77,275,030
1,712,607
Re-use the same engine for different databases on the same server?
<p>Sqlalchemy creates a new connection whenever you call <code>create_engine</code>. If you have multiple databases on the same instance, this gets tricky because Postgres can only support so many active connections.</p> <p>I have a topology where my backend needs to access different databases on the same database inst...
<python><postgresql><sqlalchemy>
2023-10-11 17:01:06
1
961
Math is Hard
77,274,887
323,571
How to iterate over values of a recordset?
<p>I am working on generating a csv report. I need to get the field names for the first row of the csv file and the value of the field for each record.</p> <p>Since the model from which I need to generate the report is being inherited by other models and new fields can be created in the child models. I need to be able ...
<python><odoo>
2023-10-11 16:39:08
1
682
jnkrois
77,274,842
7,657,180
Adjust dates form in excel output pandas package
<p>I have the following code that extracts data from pdf file and the code is working well. As for the column G in the excel file has dates but when trying to change the dates format in the excel file, the format doesn't respond. I have to double click each cell to get the desired format</p> <pre><code>import pdfplumbe...
<python><pandas>
2023-10-11 16:30:45
1
9,608
YasserKhalil
77,274,838
274,460
How do I wrap asyncio calls in general-purpose non-async functions?
<p>I'm accessing a DBus API using <code>dbus_next</code>. Since that's an asyncio library and the rest of my code is synchronous/threaded code, I wrap it up in a synchronous function:</p> <pre><code>intfc = &quot;...&quot; path = &quot;...&quot; async def dbus_call_async(): bus = await dbus_next.aio.MessageBus(bu...
<python><python-3.x><python-asyncio><python-3.6>
2023-10-11 16:30:03
2
8,161
Tom
77,274,716
10,430,394
Using mutually exclusive groups in argparse: How to channel logic based on groups?
<p>I want to have mutually exclusive arguments for my script and channel logic based on what has been specified by a user. What I currently have is this:</p> <pre class="lang-py prettyprint-override"><code>supported_formats = ['xyz','mol','pdb'] defaults = {'extension':'xyz', 'dirname':None, 'n...
<python><command-line-interface><argparse>
2023-10-11 16:10:00
1
534
J.Doe
77,274,665
2,956,276
Cannot debug script with trio_asyncio in PyCharm
<p>I have this (very simplified) program running with trio as base async library and with trio_asyncio library allowing me to call asyncio methods too:</p> <pre class="lang-py prettyprint-override"><code>import asyncio import trio import trio_asyncio async def async_main(*args): print('async_main start') async wi...
<python><pycharm><python-trio>
2023-10-11 16:00:23
1
1,313
eNca
77,274,495
16,459,035
Access denied on pandas to_parquet python
<p>I have the following dir structure</p> <pre><code>data data1 year month codes extract_data historical_data script.py </code></pre> <p>When I run <code>df.to_parquet('C:\users\john\data\data1\year\month')</code> I get <code>PermissionError: [WinError 5] Failed to open local file ...
<python><pandas>
2023-10-11 15:36:00
2
671
OdiumPura
77,274,367
12,827,931
Randomly repalce values in array with None
<p>Suppose there's an array</p> <pre><code>arr = np.array((0,0,1,2,0,1,2,2,1,0)) </code></pre> <p>What I'd like to do is to randomly replace <code>n</code> values with <code>None</code>. What I tried is</p> <pre><code>n = 5 arr[[random.randint(0, len(arr)-1) for i in range(n)]] = None </code></pre> <p>but what I get is...
<python><arrays><numpy>
2023-10-11 15:18:07
2
447
thesecond
77,274,171
1,671,319
How do I mock the paramiko.SSHClient so that an error is raised on the connect call
<p>I am trying to write a unit test and raise an error from the <code>connect</code> call in the <code>paramiko.SSHClient</code>. Here is the code I want to test:</p> <pre><code>with paramiko.SSHClient() as ssh: ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(host_name, username=user_name,...
<python><pytest><python-unittest.mock><pytest-mock>
2023-10-11 14:50:05
1
3,074
reikje
77,274,065
1,724,590
Python Plotly how to show axis values outside your dataset's max value?
<pre><code>import plotly.express as px import pandas as pd df = pd.DataFrame(dict( r=[1,2,3], theta=['a', 'b','c'])) fig = px.line_polar(df, r=[1,2,3], theta=['a','b','c'], line_close=True) fig.update_polars(radialaxis_tickvals=[1,2,3,4,5], radialaxis_tickmode='array') fig.show() </code></pre> <p>I have code ...
<python><plotly>
2023-10-11 14:36:27
1
634
Michael Yousef
77,273,922
10,416,012
aio download_blob works once but not twice when run with asyncio.run
<p>The code aio download_blob of the azure blob works once but not twice when run with asyncio.run, this looks like a bug related to iohttp, but could not figure out how to solve it. (Windows)</p> <p>The code i have is almost a copy from their original example at: <a href="https://github.com/Azure/azure-sdk-for-python/...
<python><azure><azure-blob-storage><aiohttp><azure-sdk-python>
2023-10-11 14:18:59
1
2,235
Ziur Olpa
77,273,704
8,510,149
Rotate x-axis labels in a chart using openpyxl
<p>The code below generates a simple barchart using openpyxl.</p> <p><a href="https://i.sstatic.net/6vPaf.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/6vPaf.png" alt="enter image description here" /></a></p> <p>Now I'm struggling to rotate the x-axis labels. Is perhaps an XML solution possible? IS the...
<python><excel><xml><openpyxl>
2023-10-11 13:52:10
0
1,255
Henri
77,273,655
21,305,238
What to put in the [project.scripts] table if scripts are not stored in the "src" directory?
<p>I have this package which follows the <em><a href="https://packaging.python.org/en/latest/discussions/src-layout-vs-flat-layout/" rel="nofollow noreferrer">src layout</a></em>:</p> <pre class="lang-none prettyprint-override"><code>. +-- scripts | \-- lorem.py | +-- src | \-- bar | |-- __init__.py | \...
<python><python-packaging><pyproject.toml>
2023-10-11 13:47:02
3
12,143
InSync
77,273,461
8,588,743
ERROR: Could not build wheels for fasttext, which is required to install pyproject.toml-based projects
<p>I'm trying to install <code>fasttext</code> using <code>pip install fasttext</code> in python 3.11.4 but I'm running into trouble when building wheels. The error reads as follows:</p> <pre><code> error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio\\2022\\BuildTools\\VC\\Tools\\MSVC\\14.37.32822\\bi...
<python><python-wheel><fasttext>
2023-10-11 13:23:15
3
903
Parseval
77,273,344
11,329,736
MultiQC snakemake wrapper: ModuleNotFoundError No module named 'imp'
<p>I am running FastQC and MultiQC in my <code>snakemake</code> pipeline:</p> <pre><code>rule fastqc: input: &quot;reads/{sample}_trimmed.fq.gz&quot; output: html=&quot;qc/fastqc/{sample}.html&quot;, zip=&quot;qc/fastqc/{sample}_fastqc.zip&quot; # the suffix _fastqc.zip is necessary for ...
<python><snakemake>
2023-10-11 13:05:25
1
1,095
justinian482
77,272,982
583,464
select the first of two or more filenames and save only the first
<p>I want to save files with these filenames:</p> <pre><code>filenames = [ '4_66\nNUC_66377\nAPPR\nWONDER', '4_66\nNUC_66377\nAPPR\nCOT', '8_21\nAKRO\nNUT\nAMY' ] </code></pre> <p>and if the filename starts with the same number before underscore, then write to file only the first filename.</p> <p>So, I ...
<python>
2023-10-11 12:15:33
2
5,751
George
77,272,952
2,386,605
OpenAI API: How do I use the ChatGPT plugin in Python?
<p>I want to use the <a href="https://github.com/openai/openai-python" rel="nofollow noreferrer">OpenAI python package</a>. However, I also want to make use of some ChatGPT plugins.</p> <p>I tried the following with Langchain:</p> <pre><code>tool = AIPluginTool.from_plugin_url(&quot;https://scholar-ai.net/.well-known/a...
<python><openai-api><chatgpt-api><azure-openai>
2023-10-11 12:12:36
1
879
tobias
77,272,845
5,180,979
Sequential allocation problem using pandas
<p>I encountered the following allocation problem as follows.</p> <p>Consider the following dataframe representing the supply schedule of some item.</p> <pre><code>supply_df = item supplier supply_week supply 0 a s1 1 10 1 a s2 1 20 2 a s3 1...
<python><python-3.x><pandas><dataframe><merge>
2023-10-11 11:57:13
2
315
CharcoalG
77,272,833
300,963
Can I save my python-statemachine to file?
<p>Using the python-statemachine package, I would like to save the current state to external file or database, preferably in json format, and later load it to recreate the state. Is this possible, and if so, how would I do it?</p>
<python>
2023-10-11 11:56:11
0
5,073
Johan
77,272,779
52,074
How do you test N significant digits for a float value?
<p>Lots of code (e.g. <code>numpy</code>, <code>scipy</code>, <code>sklearn</code>) does math processing where the result is a float or an array of float. In <code>unittest.TestCase</code> there is a method for comparing float values called <a href="https://docs.python.org/3/library/unittest.html#unittest.TestCase.asse...
<python><python-unittest>
2023-10-11 11:48:58
2
19,456
Trevor Boyd Smith
77,272,655
5,814,943
Why is a `lambdef` allowed as a type-hint for variables?
<p>The Python <a href="https://docs.python.org/3.11/reference/grammar.html" rel="nofollow noreferrer">grammar</a> has this rule:</p> <pre><code>assignment: | NAME ':' expression ['=' annotated_rhs ] # other options for rule omitted </code></pre> <p>while the <code>expression</code> rules permit a lambda defini...
<python><python-3.x><grammar>
2023-10-11 11:31:45
1
1,445
Max
77,272,637
13,890,967
gurobipy: update tupledict implementation
<p>I am using <code>tupledict</code> from <code>gurobipy</code> and I really like the <code>select</code> function. However it is limited to values and not conditioanl expressions.</p> <p>My tupledict of variables contains as a key a tuple <code>(r,t)</code> where <code>r</code> is an object that stands for route and h...
<python><cython><gurobi>
2023-10-11 11:29:15
1
305
sos
77,272,595
7,980,206
Use Tiebreaker having nan values while calculating the Rank in pandas
<p>I have a pandas dataframe, where there is a weighted score, and tiebreaker column. We have <code>NaN</code> values in tiebreaker column. The data frame looks like -</p> <pre><code>Name Weighted_Score(%) tie_breaker A 12.0 2.7 B 13.0 2.8 C 14.0 NaN D 14.0 3.2 </code></pre> <p>...
<python><pandas>
2023-10-11 11:21:52
1
717
ggupta
77,272,542
14,695,308
How to correctly split DLT-log file into multiple files
<p>I'm trying to develop a <code>dlt-analyzer</code> that would check newly generated logs &quot;on the fly&quot;.</p> <p>For this purpose I run the <code>dlt-receive</code> that outputs all the logs into <em>main.dlt</em> file. Then using Python code I split the logs into 16kB chunks with <code>readlines</code> method...
<python><binaryfiles><dlt-daemon><dlt>
2023-10-11 11:16:15
1
720
DonnyFlaw
77,272,418
15,283,686
Python Why `import` does not work in this case (in `exec`)?
<p>Sorry but the situation a bit complicated that I can't describe it clearly in the title.</p> <p>So this is the script to be imported later in <code>exec</code>:</p> <pre class="lang-py prettyprint-override"><code># script_to_be_imported.py def f(): print(&quot;Hello World!&quot;) </code></pre> <p>And this is my...
<python>
2023-10-11 11:01:02
1
453
yueyinqiu
77,272,326
7,274,343
Remove red highlighted text from Jupyter notebook from an API call
<p>How do I remove the red highlighted text in Jupyter Notebook which relays the whole API request information when called?</p> <p><a href="https://i.sstatic.net/RgKq3.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/RgKq3.png" alt="enter image description here" /></a></p> <p>I have tried</p> <pre><code>i...
<python><jupyter-notebook>
2023-10-11 10:49:08
2
329
homelessmathaddict
77,272,309
12,959,241
Get Countries from specific continent using Faker Python
<p>I am generating a random country name using the api <code>Faker</code> but I wanted to specific from either europian or american continent but couldn't find a parameter to add. I tried to explore with the Available locals but couldn't link both to get a country from a specific locals. Any idea how?</p> <pre><code>fr...
<python><python-3.x><faker>
2023-10-11 10:45:38
0
675
alphaBetaGamma
77,272,196
583,464
model did not return a loss / BertForQuestionAnswering.forward() got an unexpected keyword argument 'labels'
<p>I have this data:</p> <p><code>intents.json</code>:</p> <pre><code>{&quot;version&quot;: &quot;0.1.0&quot;, &quot;data&quot;: [ {&quot;id&quot;: &quot;hi&quot;, &quot;question&quot;: [&quot;hi&quot;, &quot;how are you&quot;], &quot;answers&quot;: [&quot;hi!&quot;, &quot;how can i help y...
<python><machine-learning><deep-learning><nlp><huggingface-transformers>
2023-10-11 10:29:01
1
5,751
George
77,272,131
10,722,752
Lambda function returns different output from direct code
<p>I am checking for a condition of the difference between two values is 0.5 <strong>AND</strong> if they occurred on different dates, then it's a flag.</p> <p>Sample Data:</p> <pre><code>df = pd.DataFrame({'date1' : ['2023-05-11', '2023-02-24', '2023-07-9', '2023-01-19', '2023-02-10'], 'date2' : ['20...
<python><pandas>
2023-10-11 10:19:39
2
11,560
Karthik S
77,272,024
3,002,166
Tensorflow - training custom model on dataset
<p>I feel it's something minor I'm missing, but can't seem to figure out what it is. I'm trying to train a very simple model on <strong>cassava</strong> dataset, but when I call the <code>fit</code> function, the input name doesn't match the expected name. I tried naming the input layer to match the model, but tf insis...
<python><keras><tensorflow2.0>
2023-10-11 10:03:35
1
740
user3002166
77,271,900
12,965,658
Fetch the latest 2 extreme subfolders from s3 bucket using python
<p>I have a s3 bucket which has multiple integrations.</p> <p>I want to read the files from the latest 2 extreme subfolders.</p> <p><a href="https://i.sstatic.net/QPyCJ.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/QPyCJ.png" alt="enter image description here" /></a></p> <p>I want to read all files fro...
<python><python-3.x><amazon-s3><boto3>
2023-10-11 09:45:42
1
909
Avenger
77,271,897
3,125,592
Activating a pyenv virtual environment with direnv
<p>I use both <code>direnv</code> and <code>pyenv</code> and would like to add something to my <code>.envrc</code> so that whenever I change directory, I also activate my virtual environment with pyenv.</p> <p>I printed environment variables both when my virtualenv is active and also when it is not. There were a few py...
<python><virtualenv><pyenv><direnv>
2023-10-11 09:45:02
2
2,961
Evan Volgas
77,271,830
3,446,051
Running Python Script inside AWS RDS
<p>We have an SSIS Project on our local server. Somewhere in the project there is a <code>Process Task</code> which calls a python script on the server which runs a machine learning project to make some prediction based on data in the SQL Server database.<br /> Now we want to migrate this local SSIS Project onto AWS. T...
<python><sql-server><amazon-web-services><ssis>
2023-10-11 09:35:06
0
5,459
Code Pope
77,271,757
4,004,541
VideoCapture frames images corrupted: shifting one of the channels on random frames
<p>The camera works correctly, when I use the software to verify the camera I see no corrupted frames so I assume that this is issues are coming from OpenCV.</p> <p>I notice that random frames (one out of 10-20 frames) are corrupted and one of the channels is shifted. Example below.</p> <p><a href="https://i.sstatic.ne...
<python><opencv><video-streaming><video-capture>
2023-10-11 09:21:36
1
360
Patrick Vibild
77,271,626
9,644,712
From R array to Numpy array
<p>Lets say, I have a following R array</p> <pre><code>a &lt;- array(1:18, dim = c(3, 3, 2)) r$&gt; a , , 1 [,1] [,2] [,3] [1,] 1 4 7 [2,] 2 5 8 [3,] 3 6 9 , , 2 [,1] [,2] [,3] [1,] 10 13 16 [2,] 11 14 17 [3,] 12 15 18 </code></pre> <p>and now I want to have th...
<python><r><numpy>
2023-10-11 09:01:56
3
453
Avto Abashishvili
77,271,418
630,971
Pandas.read_csv ParserError '§' expected after '"' with sep = "§"
<p>I have an issue with <code>read_csv</code> and its taking a lot of time to resolve.</p> <p>I am working with texts which have multiple special characters, so I was checking which character isn't in the list of texts and chose § as delimiter while writing the <code>csv</code> files that separates the texts with corre...
<python><pandas><parse-error><read-csv>
2023-10-11 08:32:34
1
472
sveer
77,270,923
2,571,805
FastAPI return datetime dictionary from endpoint
<p>I'm building an API on FastAPI 0.103.1, under Python 3.11.2.</p> <p>I have an endpoint that returns a dictionary with multiple datetime dictionaries. The format is this:</p> <pre class="lang-py prettyprint-override"><code>{ 'train_dates': { 'start_date': datetime.datetime(2018, 1, 1, 0, 0), 'end_...
<python><dictionary><fastapi>
2023-10-11 07:21:00
0
869
Ricardo
77,270,917
7,361,580
Python Turtle detect mouse release event on screen, not a turtle
<p>How do you detect a mouse release event on a turtle screen? There is only <code>onscreenclick</code> but no corresponding release event. Is there something I can do using the tkintercanvas backend?</p>
<python><tkinter><turtle-graphics><tkinter-canvas><python-turtle>
2023-10-11 07:19:12
2
2,115
synchronizer
77,270,861
18,904,265
Why can I only use my package with "from" import?
<p>When installing my package in editable mode (<code>pip install -e .</code>), I can only use it's functions using an import with from:</p> <pre class="lang-py prettyprint-override"><code>from package import hello_world hello_world.hello_world() </code></pre> <p>using only import doesn't work:</p> <pre class="lang-py...
<python><python-packaging>
2023-10-11 07:10:21
1
465
Jan
77,270,788
8,510,149
Chart design in Openpyxl, color axis title
<p>The code below generates a simple barchart using openpyxl.</p> <p><a href="https://i.sstatic.net/40iEK.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/40iEK.png" alt="enter image description here" /></a></p> <p>I want to be able to colorize the title on Y-axis. But this I can't find a working solution...
<python><excel><xml><openpyxl>
2023-10-11 06:56:09
1
1,255
Henri
77,270,316
580,937
Creating a table from a Snowpark DataFrame by specifying column names and their respective data types
<p>Is it possible to do the following, and if so, how?</p> <ol> <li>Create a table, with the table name and column names and types specified dynamically.</li> <li>Pass in column names and types with parameters</li> </ol>
<python><dataframe><snowflake-cloud-data-platform>
2023-10-11 05:03:23
1
2,758
orellabac
77,270,304
580,937
Getting Data Locally from an Snowpark DataFrame
<p>Does df.collect() data into local memory? Is this the best approach to load data locally? Are there any tips or best practices to consider in snowpark?</p>
<python><dataframe><snowflake-cloud-data-platform>
2023-10-11 04:59:59
1
2,758
orellabac
77,270,135
5,818,889
Avoid code duplication between django Q expression and as python code
<p>I have a very complex property on a model</p> <pre class="lang-py prettyprint-override"><code>ALLOWED_STATES = {1,2,3} class X(models.Model): a = models.BooleanField() b = models.ForeignKey('Y', on_delete=model.CASCADE) c = models.IntegerField() d = models.IntegerField() @property def can_del...
<python><django><django-models>
2023-10-11 03:52:23
2
6,479
glee8e
77,270,112
6,548,223
Does Python have an equivaled of VBA 'Set' command? (short user defined reference to manipulate an object)
<p>I have this line which changes the value of this cell to 5:</p> <pre class="lang-py prettyprint-override"><code>df[header].at[row_num] = 5 </code></pre> <p>I was wondering if there's a cleaner/shorter way to refer to <code>df[header].at[row_num]</code>?</p> <p>in VBA there's a 'Set' command that does the same job bu...
<python><pandas>
2023-10-11 03:43:32
3
3,019
Chadee Fouad