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
βŒ€
75,827,296
1,797,307
deleting all files in a directory with no extension with python
<p>I am on a mac, I granted permissions to my desktop (which is where the files are) I run it and it detects the files and the if statement works but they are not in fact deleted</p> <pre><code> import glob import os import os.path def testThingy(system_path): for file in glob.glob(system_path+&quot;/*&quot...
<python><file><delete-file>
2023-03-23 19:32:23
1
735
Kyle Sponable
75,827,178
4,560,996
How to set up API get query parameters in python request
<p>I'm trying to access an API endpoint in python. Generically, the request needs to look like this. In my real world example, (replacing URL with the actual endpoint), this works as expected. Notice the metanames arg is called multiple times</p> <pre><code>res = requests.get('url?someargs&amp;metanames=part1&amp;metan...
<python>
2023-03-23 19:17:43
1
827
dhc
75,827,176
5,091,720
pandas not finding the duplicates
<p>I am having a problem with pandas drop_duplicates and duplicated. It is not finding all the duplicates. Do you know of a work around? Below is my code.</p> <pre><code># df_a is all the data combined. dp_r1 was from read_csv &amp; dp_r2 was from read_excel. df_a = pd.concat([df_a, dp_r1, dp_r2], ignore_index=True) d...
<python><pandas><duplicates>
2023-03-23 19:17:30
1
2,363
Shane S
75,827,168
1,113,159
ffmpeg crashed if run as subprocess from nicegui
<p>I need to trigger a long ffmpeg process by nicegui button. I have created a code :</p> <pre class="lang-py prettyprint-override"><code>from concurrent.futures import ProcessPoolExecutor import shlex, subprocess import argparse import asyncio from nicegui import ui, app def run_cmd(): cmd = &quot;ffmpeg -y -i data...
<python><ffmpeg><concurrency><subprocess><nicegui>
2023-03-23 19:16:28
0
645
user1113159
75,827,156
6,679,011
How to change all the keys of a dictionary?
<p>I have a dictionary like this <code>{'lastname':'John', 'fistname':'Doe', 'id':'xxxxx'}</code> and I would like to add a prefix to all key values. The outcome should look like <code>{'contact_lastname':'John', 'contact_fistname':'Doe', 'contact_id':'xxxxx'}</code></p> <p>I tried to achieve this by a lambda function,...
<python><python-3.x><dictionary>
2023-03-23 19:14:12
2
469
Yang L
75,827,088
4,889,550
Reformat/pivot pandas dataframe
<p>For each row, I want that rows' index to be changed to column_index, and have the whole thing split from x row * y columns to 1 row * x*y columns shape.</p> <pre><code>import pandas as pd df = pd.DataFrame(data=[['Jon', 21, 1.77,160],['Jane',44,1.6,130]],columns=['name','age', 'height','weight']) want = pd.DataFram...
<python><pandas><dataframe>
2023-03-23 19:05:21
3
516
noblerthanoedipus
75,827,086
1,653,273
Convert pandas dataframe with dictionary objects into polars dataframe with object type
<p>I have a pandas dataframe with a column of dictionaries. I want to convert this to a polars dataframe with dtype <code>polars.Object</code>, which apparently wraps arbitrary Python objects. I am unable to figure out how to do this.</p> <p>Consider this code:</p> <pre class="lang-py prettyprint-override"><code>df = p...
<python><dataframe><python-polars>
2023-03-23 19:04:54
1
801
GrantS
75,826,926
7,350,565
Why does [1].extend(my_list) return nothing
<p>When I type <code>&gt;&gt;&gt; [1].extend([2, 3])</code></p> <p>I expected Python to return <code>&gt;&gt;&gt; [1, 2, 3]</code></p> <p>Why does it return <code>&gt;&gt;&gt;</code> Ie. nothing</p>
<python>
2023-03-23 18:46:20
1
420
Yirmi
75,826,859
1,506,850
Binary focal loss in pytorch
<p>I am trying to implement this: <a href="https://arxiv.org/pdf/1708.02002.pdf" rel="nofollow noreferrer">https://arxiv.org/pdf/1708.02002.pdf</a> eq4. Many public available implementations are multi-class while my problem is binary.</p> <p>I have tried</p> <pre><code>loss = -((1-p) ** gamma) * torch.log (p) * target...
<python><pytorch><loss-function>
2023-03-23 18:38:02
0
5,397
00__00__00
75,826,794
4,538,768
When QuerySet is evaluated when get_queryset is overridden
<p>Have not understand very well how QS is evaluated when overriden. Based on <a href="https://stackoverflow.com/questions/62976955/how-to-override-get-queryset-in-django">leedjango</a> question, we are able to override get_queryset in a view class. In this same example, I have not been able to understand when the get_...
<python><django><django-models><django-rest-framework><django-views>
2023-03-23 18:29:34
2
1,787
JarochoEngineer
75,826,703
12,691,626
Image padding with reflect (mirror) in Python
<p>I have an image loaded in python as an np.array with shape (7, 7). I need to apply a filtering process to the image. For this I need to apply a kernel that will convolve the 2D image (like a moving window). However, to get an output filtered image with the same shape as the input I need to expand the original image ...
<python><image><padding>
2023-03-23 18:19:14
1
327
sermomon
75,826,508
1,871,399
Python: Count number of times a row from one dataframe appears in another
<p>I have two dataframes that look like this:</p> <pre><code>df1 = pd.DataFrame({ 'name': ['Cat', 'Cat', 'Cat', 'David'], 'name2': ['Dog', 'Cat', 'Dog', 'David'], }) master_df = pd.DataFrame({ 'name': ['Dog', 'David'], 'name2': ['Cat', 'David'], }) </code></pre> <p>I want to count the number of times ...
<python><pandas>
2023-03-23 17:56:17
3
1,560
Workhorse
75,826,417
12,520,046
Python, problem with json.loads when trying to work with/upload files via O365/Sharepoint API
<p>I'm using the below code to connect to sharepoint for the purpose of uploading files to a site. all of the auth stuff is fine, for some reason I'm getting a json decode error. Anything obvious here? Assume flow starts with function &quot;getSharepointContext()&quot;. I've gone through numerous other tutorials and qu...
<python><python-3.x><rest><sharepoint>
2023-03-23 17:47:51
1
654
boog
75,826,367
3,668,495
Async redis 'get' RuntimeError 'got Future <Future pending> attached to a different loop'
<p>I have been trying to get async redis to work with async Flask app, but for the life of my, I can't figure out how to solve one problem. Here is the minimal reproducible code.</p> <pre><code>import asyncio import redis.asyncio as redis from flask import Flask async def run_app(): app = Flask('Flask') pool =...
<python><flask><redis><python-asyncio>
2023-03-23 17:42:59
1
350
atalpha
75,825,885
4,921,888
Is it possible to access the event object in an internal AWS lambda extension?
<p>I'm attempting to use an internal lambda extension (aka a wrapper function) to set some environment variables before my lambda function runs, then to use the contents of the <code>event</code> object for some additional logic. I'm currently setting those environment variables no problem, but have no idea if accessin...
<python><amazon-web-services><aws-lambda><aws-lambda-layers><aws-lambda-extensions>
2023-03-23 16:53:47
1
1,087
dslosky
75,825,724
4,502,950
explode columns with multiple entries and then stack all columns
<p>I have already asked this question in this link:</p> <p><a href="https://stackoverflow.com/questions/75788847/stack-and-explode-columns-in-pandas">Stack and explode columns in pandas</a></p> <p>And there is also an answer provided which works for the given dataset. However, it is possible that the two sessions occur...
<python><pandas>
2023-03-23 16:39:23
2
693
hyeri
75,825,644
8,497,979
How to insert Variable into PartiqL function within f-String
<p>I want to insert a Variable into a PartiQL statement using an f-String. but somehow it fails. the following does work:</p> <pre><code> IndexName = 'GSI_1' stmt = f&quot;SELECT * FROM {table_name}.{IndexName} WHERE SK=? AND begins_with(PK, 'READ#')&quot; </code></pre> <p>the following does not work:</p> <pre><...
<python>
2023-03-23 16:31:26
1
1,410
aerioeus
75,825,270
3,333,687
How do I ensure my dataset does not accumulate a lot of small files when running in incremental mode?
<p>If I have a transform that runs frequently in incremental mode I accumulate at least one file per transaction.</p> <p>The result is a dataset that has:</p> <ul> <li>A lot metadata stored from build logs.</li> <li>Small dataset files.</li> </ul> <p>I have been told that small dataset files lead to increased build tim...
<python><palantir-foundry><foundry-code-repositories>
2023-03-23 15:56:05
1
1,781
jka.ne
75,825,249
11,232,438
Gspread dataframe how to hide index column?
<p>I'm trying to print a dataframe to google spreadsheets but it's printing an extra column which is the index of the dataframe:</p> <p><a href="https://i.sstatic.net/uKC4N.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/uKC4N.png" alt="enter image description here" /></a></p> <p>What I'm doing is just l...
<python><pandas><google-sheets>
2023-03-23 15:53:59
1
745
kuhi
75,825,109
420,157
Use information from one argument to create another argument in typemap(in)
<p>Currently I have the following C snippet:</p> <pre class="lang-c prettyprint-override"><code>typedef struct My_Struct { int x; int y; } my_struct_t; void generate_buffer(my_struct_t info, uint8_t* buffer_out); </code></pre> <p>I am trying to come up with a python swig interface to call this function. The ou...
<python><c><swig>
2023-03-23 15:41:26
1
777
Maverickgugu
75,824,967
13,362,665
Making transparent pixels black
<p>I generated an image with an alpha channel, in python-opencv, the image contains specific masked areas, and the other unmasked area is transparent, and I want to get rid of the transparent pixels and have black pixels instead.</p> <p>Code for the masking:</p> <pre><code>mask1 = np.ones_like(img) mask1 = cv2.circle(m...
<python><opencv>
2023-03-23 15:28:26
0
593
Rami Janini
75,824,713
3,286,975
Enforcing Google Colab to use another python version
<p>Well, I'm trying to use Python 3.7.16 on Google Colab, I'm using the following command to install it:</p> <pre><code>!sudo apt-get install python3.7 !sudo add-apt-repository --yes ppa:deadsnakes/ppa !sudo apt-get update !sudo apt-get install python3-pip !sudo apt-get install python3.7-distutils !sudo apt-get install...
<python><google-colaboratory>
2023-03-23 15:06:40
0
2,451
z3nth10n
75,824,630
10,918,680
Downloading multiple csv files with Streamlit
<p>I build a Streamlit app where the end result is two Pandas dataframes that I want the user to download as separate csv files. However, it seems the Download button in Streamlit only allows the downloading of one file. One way of &quot;combining&quot; them is to put them as separate tabs in an Excel file, but that is...
<python><streamlit><python-zipfile>
2023-03-23 14:59:58
1
425
user173729
75,824,621
297,823
How to run sicpy.signal freqz in C# / ASP.NET Core?
<p>I need to run Python source code (.py) with dependencies on <code>numpy</code> and <code>scipy.signal</code> in the ASP.NET Core context. I've found IronPython to be a suitable solution, but it doesn't support these two dependencies (<a href="https://github.com/IronLanguages/ironpython3/issues/355" rel="nofollow nor...
<python><c#><numpy><asp.net-core><scipy>
2023-03-23 14:58:43
1
10,440
Dariusz WoΕΊniak
75,824,614
2,805,824
How to insert a specific string between two words stored in a single variable?
<p>I want to insert a string <code>&quot;and&quot;</code> between two words of a string stored in a variable.</p> <p>How can I achieve this in Python?</p> <p>E.g.</p> <p>Input string or input variable:</p> <pre><code>location = 'Location-1 Location-2 ' </code></pre> <p>Expected Output:</p> <pre><code>location = 'Locati...
<python><python-3.x>
2023-03-23 14:58:10
1
1,141
Gaurav Pathak
75,824,594
1,323,992
Python poetry install fails on typed-ast (1.5.4). How to overcome the obstacle and install the package?
<p>I tried to install the package using pip:</p> <pre class="lang-bash prettyprint-override"><code>pip wheel --use-pep517 &quot;typed-ast (==1.5.4)&quot; </code></pre> <p>but it falls in the same place.</p> <p>What's the general approach when you walk into such kind of problems?</p> <p>I've found <a href="https://githu...
<python><setuptools><python-poetry><pyproject.toml><python-3.11>
2023-03-23 14:56:16
1
846
yevt
75,824,511
8,595,891
Creating a comman named class dependency in fastapi
<p>I am creating a fastapi server where a APIRouter hast lots of endpoint and all of them are accepting same request body. Is there any way I can omit that from all function in that routers and specify at single place</p> <p>Consider an example where I am building simple calculator server which accepts two number num1 ...
<python><fastapi>
2023-03-23 14:48:17
0
1,362
Pranjal Doshi
75,824,420
8,179,672
Pytest doesn't see a data file from the source folder
<p>I have the following folder structure:</p> <p><a href="https://i.sstatic.net/OLrXO.jpg" rel="nofollow noreferrer"><img src="https://i.sstatic.net/OLrXO.jpg" alt="enter image description here" /></a></p> <p><code>main.py</code></p> <pre><code>import pandas as pd data = pd.read_csv('data.csv') def add_num_to_env_num...
<python>
2023-03-23 14:40:51
1
739
Roberto
75,824,264
13,039,962
Issues when plotting with axes AttributeError: 'NoneType' object has no attribute 'rowspan'
<p>I have this df:</p> <pre><code> DATE CODE PP 0 1964-01-01 109014 0.5 1 1964-01-02 109014 1.1 2 1964-01-03 109014 2 3 1964-01-04 109014 NaN 4 1964-01-05 109014 3 ... ... ... 21616 2023-03-08 109014 0.0 21617 2023-03-09 109014 2.3 21618 2023-03-10 109014 ...
<python><pandas><matplotlib>
2023-03-23 14:24:34
2
523
Javier
75,824,165
528,369
Pandas error "Incompatible indexer with DataFrame" when element of DataFrame set to DataFrame
<p>For the code</p> <pre><code>import pandas as pd names = list(&quot;abc&quot;) df = pd.DataFrame(index=names, columns=[&quot;foo&quot;]) print(df) for name in names: print(&quot;name =&quot;, name) # df.loc[name, &quot;foo&quot;] = 123 # code works when line below is replaced by line above df.loc[name, &...
<python><pandas>
2023-03-23 14:15:14
1
2,605
Fortranner
75,824,045
9,989,761
Tensorflow M2 Pro Failure
<p>When I run the following test script for tensorflow</p> <pre><code>import tensorflow as tf cifar = tf.keras.datasets.cifar100 (x_train, y_train), (x_test, y_test) = cifar.load_data() model = tf.keras.applications.ResNet50( include_top=True, weights=None, input_shape=(32, 32, 3), classes=100,) loss_fn...
<python><macos><tensorflow>
2023-03-23 14:04:32
1
364
Josh Purtell
75,823,739
15,724,084
python class method invocation missing 1 required positional argument
<p>I created class method to ease file reading. But the end result gives me the following error message:</p> <pre><code>TypeError: Read_file.file_reading_through_class() missing 1 required positional argument: 'fileName' </code></pre> <p>My code is below:</p> <pre class="lang-py prettyprint-override"><code>import panda...
<python><class>
2023-03-23 13:38:09
3
741
xlmaster
75,823,656
5,868,293
Create dictionary with pairs from column from pandas dataframe using regex
<p>I have the following dataframe</p> <pre><code>import pandas as pd df = pd.DataFrame({'Original': [92,93,94,95,100,101,102], 'Sub_90': [99,98,99,100,102,101,np.nan], 'Sub_80': [99,98,99,100,102,np.nan,np.nan], 'Gen_90': [99,98,99,100,102,101,101], 'Gen_80': [99,98,9...
<python><pandas><dictionary>
2023-03-23 13:30:27
4
4,512
quant
75,823,453
3,556,110
How do I monkeypatch a module BEFORE importing it (to override something in its __init__.py)?
<p>I'm using a third party library, <code>floris</code>.</p> <p>In <code>floris/__init__.py</code> they have:</p> <pre class="lang-py prettyprint-override"><code> from . import logging_manager logging_manager._setup_logger() </code></pre> <p>This completely destroys my carefully crafted logging configuration, and does...
<python><import><module><monkeypatching>
2023-03-23 13:11:43
0
5,582
thclark
75,823,367
6,761,231
Sparse matrix multiplication in pytorch
<p>I want to implement the following formula in pytorch in a batch manner:</p> <pre><code>x^T A x </code></pre> <p>where <strong>x</strong> has shape: [BATCH, DIM1] and <strong>A</strong> has shape: [BATCH, DIM1, DIM1]</p> <p>I managed to implement it for the dense matrix A as follows:</p> <p><code>torch.bmm(torch.bmm(...
<python><deep-learning><pytorch><linear-algebra>
2023-03-23 13:03:59
1
303
Artur Pschybysz
75,823,246
8,050,689
Having issue with node-gyp and python
<p>I keep on getting this following error when I'm trying to compile my npm electron project.</p> <p>I feel theres some error with node-gyp and python.</p> <p><a href="https://i.sstatic.net/atKHE.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/atKHE.png" alt="enter image description here" /></a></p> <p>...
<python><electron><node-gyp>
2023-03-23 12:53:22
1
573
Just_Ice
75,823,105
6,284,716
How to deactivate virtualenv in Makefile?
<p>I am currently trying to create a makefile that detects, if a Python venv is active and if so, to deactivate it. So far my attempts have not been successful. Therefore my question, is it even possible to deactivate the current shells venv with make and if so, how?</p> <p>Update: I want to make sure, that devs do not...
<python><shell><makefile>
2023-03-23 12:38:56
2
437
lars
75,823,000
13,944,524
Module's __getattr__ is called twice
<p><a href="https://peps.python.org/pep-0562/" rel="nofollow noreferrer">PEP-562</a> introduced <code>__getattr__</code> for modules. While testing I noticed this magic method is called twice when called in this form: <code>from X import Y</code>.</p> <p><strong>file_b.py</strong>:</p> <pre class="lang-py prettyprint-o...
<python><python-3.x><module><python-import>
2023-03-23 12:28:07
1
17,004
S.B
75,822,877
11,001,751
Exporting TIF Images from Google Earth Engine to Google Drive: Minimal Example in Python
<p>I thought exporting images from GEE should be quite straightforward, turns out I am facing difficulties, and I'm not satisfied with the answers given so far on this platform.</p> <p>As a minimal example, I want to extract nightlights images at original scale for South Africa:</p> <pre class="lang-py prettyprint-over...
<python><google-earth-engine>
2023-03-23 12:14:27
1
1,379
Sebastian
75,822,589
15,724,084
python using concurrent futures to read file asynchronously method guidance
<p>I want to add <code>concurrency.futures</code> module asynchronous I/O reading to my script. I want file to be read one time, then the result to be worked on. As logic of module does not align with it I created two different functions which separately reads two separate time the file, as pandas dataframe and then gi...
<python><concurrency>
2023-03-23 11:45:56
1
741
xlmaster
75,822,447
14,459,522
Can't use plt to show an image from the CIFAR-10 dataset in Google Colab
<p>I'm trying to show the images part of the CIFAR-10 dataset but for some reason <code>plt</code> shows me an axes image instead of the actual image that I want to see.</p> <pre><code> from os import lseek from cs231n.data_utils import load_CIFAR10 import matplotlib.pyplot as plt Xtr, Ytr, Xte, Yte = load_CIFAR10('cs...
<python><matplotlib>
2023-03-23 11:32:31
1
433
CupOfGreenTea
75,822,372
2,960,388
Jenkins sudo: a terminal is required to read the password
<p>I have a FastAPI app for which I have configured Jenkins pipeline. When I execute unit tests with the code coverage enabled they are failing with the following error :</p> <pre><code>Started by user gold Obtained Jenkinsfile from git https://github.com/edtshuma/devsecops-labs.git [Pipeline] Start of Pipeline [Pipeli...
<python><jenkins><jenkins-pipeline><code-coverage>
2023-03-23 11:23:08
3
1,039
Golide
75,822,277
726,150
Python data frames to SQL server DB
<p>I have the following code, and it is failing to connect to a Microsoft SQL,</p> <pre><code>import pandas as pd import pyodbc # set up a connection to the database server = '1.1.1.1' database = 'testDB' username = 'tuser' password = 'xxxxx' cnxn = pyodbc.connect('DRIVER={{SQL Server}};SERVER='+server+';DATABASE='+...
<python><sql-server>
2023-03-23 11:12:58
1
2,653
DevilWAH
75,822,267
10,771,559
In each group, only keep the row that contains the best choice
<p>I have a dataframe with a column of Groups. I have another column with different choices. I want to only keep one row per group and to only keep the row containing the <strong>best</strong> choice. The choices in order of preference are First Choice, Second Choice, Third Choice, Fourth Choice.</p> <p>My dataframe is...
<python><pandas>
2023-03-23 11:12:12
2
578
Niam45
75,822,180
11,141,816
Can pip be used to upgrade package installed with conda forge?
<p>A package was installed through conda-forge</p> <pre><code>conda install -c conda-forge &lt;package&gt; </code></pre> <p>However, I don't know how to upgrade the package to the newest version, because</p> <pre><code>conda install --upgrade -c conda-forge openai </code></pre> <p>didn't work, so I typed</p> <pre><code...
<python><installation><pip><anaconda><upgrade>
2023-03-23 11:03:43
0
593
ShoutOutAndCalculate
75,822,030
6,761,328
Include assets in dashboard created by an .exe via PyInstaller()
<p>I created a dashboard via <code>plotly dash</code>. This dashboard will be used on a single machine in a lab. Hence, I didn't host it on a server or the like but created an .exe with <code>PyInstaller()</code>. When executed, a window will open with these lines:</p> <pre><code>Dash is running on http://127.0.0.1:805...
<python><pyinstaller><plotly-dash>
2023-03-23 10:47:10
2
1,562
Ben
75,821,999
4,659,442
Select row in dataframe containing a specific UUID
<p>I have a dataframe, one column of which holds a UUID:</p> <pre><code>import numpy as np import pandas as pd import uuid df = pd.DataFrame( data=[[1, 2, 3], [4, 5, 6]], columns=['a', 'b', 'c'] ) df['d'] = np.NaN df['d'] = df['d'].apply( lambda x: uuid.uuid4() ) </code></pre> <p>Preview:</p> <pre><code>d...
<python><pandas><uuid>
2023-03-23 10:43:43
2
727
philipnye
75,821,940
6,772,468
How to pass file using html form, Dropzone and Flask
<p>I am using Dropzone and Flask using html form to pass files. like this below:</p> <pre><code>&lt;form action=&quot;/&quot; enctype=&quot;multipart/form-data&quot; method=&quot;POST&quot; class=&quot;dropzone&quot; id=&quot;myAwesomeDropzone&quot; &gt; &lt;div class=&quot;fallback&...
<javascript><python><python-3.x><flask><dropzone.js>
2023-03-23 10:36:45
1
1,375
JA-pythonista
75,821,774
10,620,788
Run an Azure Databricks notebook from another notebook with ipywidget
<p>I am trying to run a notebook from another notebook using the dbutils.notebook.run as follows:</p> <pre><code>import ipywidgets as widgets from ipywidgets import interact from ipywidgets import Box button = widgets.Button(description='Run model') out = widgets.Output() def on_button_clicked(b): button.descript...
<python><azure><pyspark><databricks><ipywidgets>
2023-03-23 10:20:35
1
363
mblume
75,821,671
1,866,038
Does DataFrame.index.empty imply DataFrame.empty?
<p>If I have a DataFrame, <code>df</code>, for which <code>df.index.empy</code> is <code>True</code>, will this ALWAYS imply that <code>df.empty</code> is also <code>True</code>?</p> <p>My intend is to test only df.index.empy when I need to test both conditions (lazy programming style).</p>
<python><pandas><dataframe>
2023-03-23 10:10:42
2
517
Antonio Serrano
75,821,598
792,015
Accessing an instance throughout a tkinter app
<p>I have a program that defines a Gear class and I am creating a tkinter GUI to manipulate it. However I'm unsure how to make a globally accessible instance of the Gear. Currently I am instantiating it like this and passing it into the sub frames I am creating like so ...</p> <pre><code>class MainApplication(ttk.Fra...
<python><oop><tkinter>
2023-03-23 10:03:50
1
1,466
Inyoka
75,821,466
1,651,481
Python render svg image with the python only modules
<p>The question is simple, but I have googled a lot of methods, and there no such solution as:</p> <pre><code>import svg-render-library figure = svg-render-library.open('test.svg') figure.render() </code></pre> <p>Is there any simple methods to display an SVG image using only python libraries? I am asking about renderi...
<python><svg><rendering>
2023-03-23 09:50:52
1
612
XuMuK
75,821,325
11,422,610
Why do I have to activate my virtual environment for the second time - i.e. from within a Python script despite having it already activated?
<p>I wrote many scripts to help me manage my django projects. One of them, <code>cr_app.py</code> creates a new app:</p> <pre><code>#!/usr/bin/env python3 from subprocess import run def main(): create_app() def create_app(): name = input(&quot;The name of the app?\n&quot;) run(f&quot;&quot;&quot;python3 mana...
<python><django><django-manage.py>
2023-03-23 09:36:38
0
937
John Smith
75,821,239
290,650
Multiple offset y-axis AND multiple offset x-axis for same subplot (at least 3 of each)
<p>I would like to plot data of various scales on the same axes object. This means having multiple x and y-axis on the same 'axes' object (I'm aware there are other ways to visualise multi-scale data but I don't want to get into the details too much of why I need to do it this way!).</p> <p>I understand how to use <cod...
<python><matplotlib><plot>
2023-03-23 09:28:11
1
6,901
Eddy
75,821,223
279,313
SGD optimizer: Cannot iterate over a scalar tensor
<p>Trying to execute code examples from the book, I get the similar issue for several examples. Probably, because I use new TensorFlow version. Minimal code to reproduce:</p> <pre><code>import tensorflow as tf import numpy as np X = tf.constant(np.linspace(-1, 1, 101), dtype=tf.float32) Y = tf.constant(np.linspace(-1,...
<python><tensorflow><keras>
2023-03-23 09:27:04
1
43,451
Alex F
75,821,044
12,415,855
Python - reading hyperlink information?
<p>i try to read a hyperlink-information from an excel-sheet using the following code:</p> <pre><code>import os import sys import xlwings as xw path = os.path.abspath(os.path.dirname(sys.argv[0])) fn = os.path.join(path, &quot;inp.xlsx&quot;) wb = xw.Book (fn) ws1 = wb.sheets[&quot;MainOverview&quot;] val = ws...
<python><excel><xlwings>
2023-03-23 09:09:29
1
1,515
Rapid1898
75,820,977
4,681,355
Clickable elements not found by Selenium with wait
<p>I'm trying to scrape all the team statistics at this page: <a href="https://www.unitedrugby.com/clubs/glasgow-warriors/stats" rel="nofollow noreferrer">https://www.unitedrugby.com/clubs/glasgow-warriors/stats</a></p> <p>As you can see there are several drop down menus. The ones I'm interested in are the six ones des...
<python><html><selenium-webdriver><web-scraping><xpath>
2023-03-23 09:02:40
3
622
schmat_90
75,820,971
9,751,398
How to cure Google Colab with miniconda installed and get on import ModuleNotFoundError?
<p>I have used Google Colab for more than half a year successfully for a special application. In the beginning of my Colab-notebook script I install conda and use conda-forge for installing a key Python package. At the beginning of this year 2023 I became aware of the Colab update to use Ubuntu 20.04 LTS and made some ...
<python><linux><jupyter-notebook><google-colaboratory><miniconda>
2023-03-23 09:01:48
1
1,156
janpeter
75,820,944
12,931,358
Is it possible to combine these three tensors into a large tensor as model input without using dict?
<p>I have a ANN network, and not I need a dict that combines these three tensors as input, for example,</p> <pre><code>model = MyNetwork(&quot;mypath&quot;) dummy_input = {} dummy_input[&quot;input_ids&quot;] = torch.randint(1, 512,(1,345)) dummy_input[&quot;attention_mask&quot;] = torch.randint(1, 512,(1,345)) dummy_i...
<python><deep-learning><pytorch><neural-network>
2023-03-23 08:58:22
1
2,077
4daJKong
75,820,725
19,556,055
Is there a fast way to merge overlapping columns between two pandas dataframes?
<p>I have a DataFrame with employee information that is missing some records, and want to fill these in using another DataFrame. The way I'm doing it now is below, but takes way too long because it's a lot of rows.</p> <pre><code>df_missing = df_cleaned.loc[(df_cleaned[&quot;HOURLY_BASE_RATE&quot;]&lt;= 0) | (df_cleane...
<python><pandas><numpy><merge>
2023-03-23 08:34:18
2
338
MKJ
75,820,497
10,284,437
No module named 'upwork.routers'
<p>I have this simple imports that is failing with</p> <pre><code> from upwork.routers.jobs import search ModuleNotFoundError: No module named 'upwork.routers' </code></pre> <p>Ref: <a href="https://upwork.github.io/python-upwork-oauth2/routers/jobs/search.html" rel="nofollow noreferrer">https://upwork.github.io/pyt...
<python><python-3.x><upwork-api>
2023-03-23 08:05:52
2
731
MΓ©vatlavΓ© Kraspek
75,820,434
12,931,358
How to create a high dimension tensor with fixed shape and dtype?
<p>I want to return a tensor with fixed shape size, like, <code>torch.Size([1,345])</code> However, when I input,</p> <pre><code>import torch pt1 = torch.tensor(data=(1, 345), dtype=torch.int64) </code></pre> <p>it only return <code>torch.Size([2])</code></p> <p>I followed some tensor tutorial a tried to</p> <pre><code...
<python><pytorch>
2023-03-23 07:59:37
3
2,077
4daJKong
75,820,215
5,747,326
Pagination using python dictionaries
<p>What is the ideal and most performant way to paginate from dictionary with list of dicts? For example if below is my dictionary:</p> <pre><code>items = { &quot;device-1&quot;: [ {&quot;a&quot;: 1, &quot;b&quot;: 15}, {&quot;a&quot;: 11, &quot;b&quot;: 25}, {&quot;a&quot;: 21, &quot;b&quot...
<python>
2023-03-23 07:30:33
1
746
N Raghu
75,820,210
7,556,646
Call SciPy from MATLAB using Python
<p>I would like to compute the <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.t.html" rel="nofollow noreferrer">inverse CDF of Student T distribution</a> using MATLAB without the statistic toolbox but with the help of Python and SciPy, see as well <a href="https://stackoverflow.com/a/20627638...
<python><matlab><scipy>
2023-03-23 07:29:57
1
1,684
Wollmich
75,820,131
14,427,714
How to ignore this browser may not be secure using python selenium?
<p>I'm trying to automate testing of email login using Python and Selenium. Specifically, I want to test different email addresses and passwords to see if they work. However, I'm running into an issue where the browser shows &quot;not secure&quot; when I try to sign in to Gmail.</p> <p>Here's the code I'm using:</p> <p...
<python><selenium-webdriver>
2023-03-23 07:18:08
0
549
Sakib ovi
75,819,830
1,342,522
Pytest Mocker dynamically created instance
<p>I am writing a unit test that verifies when a method from an instance of a class throws a <code>ValueError</code> or <code>KeyError</code> a certain event is raised.</p> <p>Usually when I do this for regular methods, I do a</p> <pre><code>mocker.patch('module.method',side_effect=ValueError()) </code></pre> <p>and t...
<python><pytest>
2023-03-23 06:30:27
0
1,385
JakeHova
75,819,690
9,699,634
Error :'int' object is not subscriptable, while displying output from SQLite to Python code
<p>I am using SQLite in Python to store and retrieve data.</p> <p>This is my Python code:</p> <pre><code># Read API key API_KEY = os.environ[&quot;API_KEY&quot;] # Create bot object bot = telebot.TeleBot(API_KEY) # Connect to database conn = sqlite3.connect('message_tracker.db', check_same_thread=False) c = conn.curso...
<python><database><sqlite><sqlite3-python>
2023-03-23 06:06:14
0
1,702
VikaS GuttE
75,819,553
9,768,643
How to change the file name of automated chrome download option via python selinium
<p>I need to save the file into a specific name by changing the default name</p> <p>which is popping up by the python selenium download button click</p> <p>I tried the below</p> <pre><code>from selenium import webdriver from selenium.webdriver.common.by import By import time options = webdriver.ChromeOptions() prefs =...
<python><selenium-webdriver>
2023-03-23 05:38:37
1
836
abhi krishnan
75,819,291
1,358,829
Keras: time per step increases with a filter on the number of samples, epoch time continues the same
<p>I'm implementing a simple sanity check model on Keras for some data I have. My training dataset is comprised of about 550 files, and each contributes to about 150 samples. Each training sample has the following signature:</p> <pre class="lang-py prettyprint-override"><code>({'input_a': TensorSpec(shape=(None, 900, 1...
<python><tensorflow><machine-learning><keras>
2023-03-23 04:36:41
2
1,232
Alb
75,819,271
5,420,846
Dash Extendable Graph -- use extendData without Interval
<p>I haven't seen this question asked in the exact same way online, so I'm gonna try to ask this in first principles (at least as far as Dash first principles go)</p> <p>I have a websocket feed streaming data from the internet. I'll get data from it, and sometimes I'll use that data to update my plot with a new data po...
<python><websocket><callback><plotly><plotly-dash>
2023-03-23 04:29:58
0
1,988
Joe
75,819,187
19,003,861
Prevent creation of new model object if another one was created less than 24 hours ago in Django
<p>I am trying to prevent a model object to be created, if another one was created say less than 24 hours ago.</p> <p>There is a trick however. This rule does not apply to ALL model objects and will dependent on a set of rule laid out in a different model.</p> <p>To be more specific, if <code>Venue_1</code> has a <code...
<python><django><django-models>
2023-03-23 04:11:43
1
415
PhilM
75,819,169
5,029,589
Get Closest match for a column in data frame
<p>I have a data Frame which contains different call types as below values</p> <pre><code> CallType 0 IN 1 OUT 2 a_in 3 asms 4 INCOMING 5 OUTGOING 6 A2P_SMSIN 7 ain 8 aout </code></pre> <p>I want to map this in such a way the output would be</p> <pre><code> CallType 0 ...
<python><pandas><dataframe>
2023-03-23 04:03:52
1
2,174
arpit joshi
75,818,988
2,216,108
How to access the current value of multiprocessor.value in the main process?
<p>CODE:</p> <pre><code>from multiprocessing import Process, Value import ctypes import time new_value = Value(ctypes.c_wchar_p, &quot;abc&quot;) def func(): global new_value new_value.value = &quot;xyz&quot; print ('updated value to xyz') class Test(): def __init__(self): global new_val...
<python><python-3.x><multiprocessing>
2023-03-23 03:20:13
1
1,242
aste123
75,818,907
10,735,076
Running a python script from inside a CDK stack?
<p>I have an AWS CDK project with the following structure. The top <code>app.py</code> is simply the deafult CDK entry point, <code>my_Stack.py</code> is where the main Stack and Constructs live. The stack consists of static from the <code>site-staging</code> folder which is deployed to an S3 bucket and served with a C...
<python><flask><aws-cdk>
2023-03-23 02:57:28
0
313
Anthony Townsend
75,818,846
5,924,264
A value is trying to be set on a copy of a slice from a DataFrame when there is no copy?
<p>I'm currently getting the warning</p> <pre><code>A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead </code></pre> <p>on this line:</p> <pre><code> df[&quot;next&quot;] = df[ &quot;next&quot;] * df[&quot;curr&quot;].map(lookup) </code></pre>...
<python><pandas><dataframe>
2023-03-23 02:40:48
1
2,502
roulette01
75,818,802
4,174,993
Python Import Path Issue
<p>So, <a href="https://realpython.com/python-import/#basic-python-import" rel="nofollow noreferrer">this article</a> did a very good job explaining paths &amp; imports and the most portable way to handle python projects. I have read it twice but I do not know what I am doing wrong. I decided for this project that, I w...
<python><python-3.x><unit-testing>
2023-03-23 02:30:42
1
7,548
papigee
75,818,717
14,325,145
PyQt6 - Automatically Close QMessageBox after N seconds
<p>I am trying to make a QMessageBox automatically close after <strong>3</strong> seconds in PyQt6</p> <p>Here is my minimum reproducible example which does not work:</p> <pre><code>import sys from PyQt6.QtWidgets import QApplication, QWidget, QMessageBox from PyQt6.QtCore import QTimer class App(QWidget): def __i...
<python><qt><pyqt6>
2023-03-23 02:06:25
2
373
zeroalpha
75,818,679
7,267,480
violin plot with categorization using two different columns of data for "one violin"
<p>trying to visualize the distributions of the data stored in a dataframe. I have 1000 rows, each of them has next columns:</p> <pre><code>sample_id | chi_2_n_est | chi_2_n_theo --------------------------------------- 1 | 1.01 | 1.001 1 | 1.03 |1.012 ... 2 | 1.11 | 1.04...
<python><violin-plot>
2023-03-23 01:54:47
1
496
twistfire
75,818,417
5,924,264
How to merging df2 into df1 and fill in NaNs while merging?
<p>I have 2 dataframes <code>df1, df2</code>.</p> <p><code>df1</code> has the columns <code>[&quot;id&quot;, &quot;time&quot;, &quot;cost&quot;, &quot;quantity]</code>.</p> <p><code>df2</code> has the columns <code>[&quot;id&quot;, &quot;time&quot;, &quot;modified_cost&quot;, &quot;modified_quantity]</code>.</p> <p>I w...
<python><pandas><dataframe>
2023-03-23 00:51:11
3
2,502
roulette01
75,818,298
3,312,274
web2py: left-outer join not giving all records on left
<p>Why is this code not returning groups with zero (0) count? (I am sure there are groups with zero count)</p> <pre><code>count = db.auth_membership.id.count() groups = db().select(db.auth_membership.group_id, db.auth_group.role, count, left=db.auth_group.on(db.auth_membership.group_id==db.auth_group.id), grou...
<python><web2py>
2023-03-23 00:17:16
1
565
JeffP
75,818,269
9,900,084
Polars: fill nulls with the only valid value within each group
<p>Each group only has one valid or not_null value in a random row. How do you fill each group with that value?</p> <pre class="lang-py prettyprint-override"><code>import polars as pl data = { 'group': ['1', '1', '1', '2', '2', '2', '3', '3', '3'], 'col1': [1, None, None, None, 3, None, None, None, 5], 'co...
<python><dataframe><window-functions><python-polars>
2023-03-23 00:10:48
3
2,559
steven
75,818,230
10,452,700
What is the best practice to apply cross-validation using TimeSeriesSplit() over dataframe within end-2-end pipeline in python?
<p>Let's say I have <a href="https://drive.google.com/file/d/18PGLNnOI44LVFignYriBWQFW9WBkTX5c/view?usp=share_link" rel="nofollow noreferrer">dataset</a> within the following <a href="/questions/tagged/pandas" class="post-tag" title="show questions tagged &#39;pandas&#39;" aria-label="show questions tagged &#39;pandas&...
<python><scikit-learn><time-series><regression><cross-validation>
2023-03-23 00:02:03
2
2,056
Mario
75,818,193
2,478,485
python pytest pluggy - pytest_runtest_logfinish AssertionError
<p><code>pytest</code> is failing with following error. Might be related to <a href="https://github.com/pytest-dev/pluggy" rel="nofollow noreferrer">https://github.com/pytest-dev/pluggy</a> package</p> <p><strong>Code</strong> Exception location <a href="https://github.com/pytest-dev/pytest/blob/main/src/_pytest/term...
<python><pytest>
2023-03-22 23:52:46
1
3,355
Lava Sangeetham
75,818,186
14,729,820
How to rename images name using data frame?
<p>I have a data frame that has <code>file_name </code> and corresponding <code>text </code> and want to update the <code>file_name</code> and the image name in <code>imgs</code> folder by concatenating with some text or number the structure of <code>input_folder</code> look like :</p> <pre><code>input_folder --| ...
<python><pandas><dataframe><deep-learning><operating-system>
2023-03-22 23:51:03
1
366
Mohammed
75,818,060
12,485,858
How to read a text file with unknown format and save it as utf-8?
<p>I have a text file with unknown formatting which contains some german characters (umlaut). I want to open this file with python and read it as &quot;utf-8&quot;. However, everything I tried out delivers an error: <code>UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe4 in position 1664: invalid continuation b...
<python><encoding><io><text-files>
2023-03-22 23:22:11
2
846
teoML
75,817,988
5,969,893
Airflow Function to get Task Status
<p>I am using <code>BranchPythonOperator</code> and I want to check if the preceding task <code>Task_1</code> is a success, and if a success return <code>Task_2</code> and if fail return <code>Task_3</code>. However, I am not sure how to get the state of the <code>Task_1</code>. I tried a few ways one of them below, ...
<python><airflow>
2023-03-22 23:05:26
2
667
AlmostThere
75,817,867
2,103,050
Tensorflow Actor Critic fails locally in Pycharm with OperatorNotAllowedInGraphError
<p><a href="https://www.tensorflow.org/tutorials/reinforcement_learning/actor_critic" rel="nofollow noreferrer">https://www.tensorflow.org/tutorials/reinforcement_learning/actor_critic</a></p> <p>I'm trying to copy and run this code locally (outside colab where it runs fine) and modify it, but when I run (even the orig...
<python><tensorflow>
2023-03-22 22:42:25
1
377
brian_ds
75,817,866
1,185,242
Can you mock system functionality in a pytest fixture?
<p>I have the following class which does a bunch of system level stuff like call <code>os.system</code>, <code>mkdir</code> and make HTTP requests for example:</p> <pre><code># mymodule.scene.py import os from pathlib import Path import requests class Scene: def __init__(self, id): self.do_stuff_1(id) ...
<python><mocking><pytest>
2023-03-22 22:42:12
1
26,004
nickponline
75,817,692
10,428,677
Using Python fstrings to name columns in pyspark
<p>I am trying to iterate through a list of column names in pyspark and if they don't exist, I want to create them, fill with null values and give them a name using an fstring.</p> <p>However, when I try the below code, I get the error <code>Column is not iterable</code>. Is there a way to fix this?</p> <pre><code>for ...
<python><pyspark>
2023-03-22 22:10:11
1
590
A.N.
75,817,540
14,967,088
Prevent a player from moving faster than usual by moving in two directions
<p>I'm messing a bit with pygame, a player can freely move around the screen with WASD and change the direction they are facing with <kbd>←</kbd> and <kbd>β†’</kbd>, the problem is that they can move faster than usual if they hold two keys at once (e.g. <kbd>W</kbd> + <kbd>D</kbd>, <kbd>W</kbd> + <kbd>A</kbd>) and I was ...
<python><pygame>
2023-03-22 21:49:24
1
741
qwerty_url
75,817,446
6,164,682
How to configure python virtual environment with different python version?
<p>I am trying to set virtual environment with a different python version.</p> <p>The default global version is <code>Python 3.11.0</code></p> <p>I have installed virtualenv using <code>pip install virtualenv</code></p> <p>Command to create virtualenv with different python version is <code>virtualenv -p &quot;C:/Pytho...
<python><virtualenv>
2023-03-22 21:35:31
2
709
sub
75,817,299
5,091,720
Ways to speedup regex and make it faster
<p>Is there a way to speedup this code regex code? The file is really large and will not open in excel because of size.</p> <pre><code>import regex as re path = &quot;C:/Users/.../CDPH/&quot; with open(path + 'Thefile.tab') as file: data = file.read() # replace all space bars between tab characters data...
<python><regex>
2023-03-22 21:11:10
1
2,363
Shane S
75,817,201
14,729,820
How to save image with same name with python?
<p>I have image folder as below :</p> <pre><code>|------dir--| | |---- input--|-- 1.jpg | | |-- 2.jpg .. ... ... ... </code></pre> <p>where I want to do random rotation for <code>input folder</code> and save the results in <code>output folder</code></p> <p>I tryied the...
<python><file><path>
2023-03-22 20:56:01
1
366
Mohammed
75,817,199
563,269
Working with multiple Snowflake tables in SQLAlchemy
<p>When I try to reference multiple Snowflake databases within SQLAlchemy, I receive an error message. In the below example, I'm trying to create two table objects to join together later. I'm running SQLAlchemy version 1.4.47.</p> <p>In this example, I'm trying to create two table objects. The table object from data...
<python><sqlalchemy><snowflake-cloud-data-platform>
2023-03-22 20:55:49
1
641
Netbrian
75,817,059
9,415,280
LSTM using "return_sequences=False" return wrong shape dimention [nb_input, nb_neurones] in lieu of [nb_neurones]
<p>I use this code to pass my data inside a LSTM layer, input 1 and 2: x1, x2</p> <pre><code>this is how I setup my inputs x1= tf.data.Dataset.from_tensor_slices((X)) x2= tf.data.Dataset.from_tensor_slices((Xphysio)) output = tf.data.Dataset.from_tensor_slices((y)) combined_dataset = tf.data.Dataset.zip(((inputs_hydro...
<python><tensorflow><input><lstm>
2023-03-22 20:38:16
0
451
Jonathan Roy
75,817,053
2,125,671
How to assign a list of instance methods to a class variable?
<p>I have this class which works:</p> <pre><code>class Point: def __init__(self): self.checks = [self.check1, self.check2] def check1(self): return True def check2(self): return True def run_all_checks(self): for check in self.checks: check() </code></pre> ...
<python><class><variables><instance>
2023-03-22 20:37:38
1
27,618
Philippe
75,817,029
13,494,917
60 column table with 700k rows taking about 30 minutes to go from dataframe to database
<p>Wondering if the title sounds normal and what I could possibly do to make this process faster. I am using python to transfer tables over from one Azure SQL database to another. The database I'm inserting tables into is a <code>General Purpose - Serverless: Standard-series (Gen5), 1 vCore</code> azure sql database- j...
<python><pandas><azure><sqlalchemy><azure-sql-database>
2023-03-22 20:34:26
0
687
BlakeB9
75,816,935
17,561,414
Remove a specific character from column value using pyspark
<p>I would like to remove some dots (<code>.</code>) from the column values but the tricky part is that I only want to remove the dots if they appear only once between numbers, but if there are two dots or three dots after each other, ignore them <strong>For example:</strong></p> <p><a href="https://i.sstatic.net/UPJK...
<python><pyspark>
2023-03-22 20:20:42
1
735
Greencolor
75,816,824
1,293,127
Implement seek in read-only gzip stream
<p>I have an app that seeks within a <code>.gz</code> file-like object.</p> <p>Python's <code>gzip.GzipFile</code> supports this, but very inefficiently – when the GzipFile object is asked to seek back, it will rewind to the beginning of the stream (<code>seek(0)</code>) and then read and decompress everything up to th...
<python><gzip><zlib><python-3.10>
2023-03-22 20:05:51
1
8,721
user124114
75,816,763
17,896,651
Django ImageField specific directory is full (maximum number of files in linux dir)
<p>While having this:</p> <pre><code>profile_pic: ImageField = models.ImageField( _(&quot;profile_picture&quot;), upload_to='profile_pic', blank=True, null=True) </code></pre> <p>And 23M record I found out that profile_pic is &quot;full&quot; (&quot;no space left on device&quot;) while having 300GB free...
<python><django><linux>
2023-03-22 19:57:39
1
356
Si si