Questions tagged [python-3.x]

DO NOT UTILIZE UNLESS YOUR INQUIRY IS FOR SOLELY PYTHON 3 PURPOSES. Please ensure to consistently employ this in tandem with the customary [python] label.

Display all the files in a specified directory using Python3

What is the best way to display only file names from a specific directory without including any sub-directory files? ...

After configuring Python Selenium with a proxy, the message 'There are no active modal dialogs' is displayed

While using a proxy with my webdriver, an authentication dialog requiring user/pass credentials appears. To address this, I opted to utilize an autoit script for a simpler solution: #Include <File.au3> WinWaitActive("Authentication Required") Send( ...

Move the primary window to the front in PySide

The situation: Here's the deal - I've got a total of 3 windows along with 1 window manager file. The window manager kicks off the main window and you can open other windows from there. Everything seems to be going smoothly so far. However, all t ...

What is the Python method for determining if a PDF page contains color?

I need help determining the number of coloured and non-coloured (black and white) pages in a PDF file. How can this be achieved? For instance, if I upload a 100-page PDF file, it should provide me with the count of X coloured pages and Y non-coloured page ...

Automated Weekly Newsletter

I am having trouble with the code I wrote to send an auto email report weekly every Monday at 10 AM. The current code is triggering the email weekly after every hour instead of just on Mondays at 10 AM. Can someone please help me fix this issue? Here is t ...

What are the distinguishing factors between bulk fields and straightforward fields?

Exploring the possibilities of using Python API blpapi for converting Excel formulas such as BDP and BDS. I am looking to determine whether the field required is a Bulk field (for BDS) or a simple field (for BDP). Is there a method to achieve this? ...

The response from a Python requests.get() call is coming back as empty

Currently, I am in the process of developing a script that interacts with the Jenkins plugin API to retrieve a list of plugin dependencies. To achieve this, I have utilized the Python requests module. However, I am encountering an issue where the response ...

I'm unable to select a checkbox using Python Selenium

My attempt to create a checkbox using Python Selenium resulted in an error message. selenium.common.exceptions.ElementNotInteractableException: Message: element not interactable I believe the issue lies with the element, but I am unsure of its exact locat ...

Splitting JSON data into groups using Python 3

Looking to divide the actual value into separate dynamic groups represented as an array of objects. c = { 'Date#1': '07/03/2018', 'Item#1': '789807', 'Description#1': 'Wooden Blocks', 'Qty#1': '4', 'Unit_Price#1': '$10.00 ...

Automatically retrieve a URL from a website using Python

My approach to streamline my program and enhance user experience was by creating an executable file that consolidates all functions, including the download of various applications and their installation. However, I encountered a challenge where the link is ...

In both Python 2.x and 3.x, is range subject to eager or lazy evaluation?

Upon researching the range function, I discovered that (EDIT: in 2.x) it is eagerly evaluated >>> range(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] However, running the following code in my local Python 3.3 interpreter gives me different results: a = ra ...

A guide on setting custom boundaries for the age column in a Python dataframe

My goal is to define an upper bound and lower bound based on user input, where the upper bound is the user's input plus 10. Create a DataFrame df = pd.DataFrame({ 'VIN':['v1', 'v1', 'v1', 'v1', 'v1', 'v2', 'v2', 'v2', 'v2', 'v2'], 'Revenue':[30, 50 ...

Using the MAE criterion instead of MSE in scikit-learn's Random Forest Regression causes a significant decrease in speed, with it running

Currently, I am experimenting with Random Forest Regression using criterion = mae (mean absolute error) instead of mse (mean squared error). This change is resulting in a significant impact on computation time. Specifically, the processing time has incre ...

How can I fix the issues with my Caesar cipher?

Here's the code snippet I'm using: text = input("Enter your text: ") shift = int(input("Enter the shift value: ")) def caesar_shift(text, shift): cipher = "" for i in text: if i.isalpha(): stayIn = ord(i) + shift i ...

Exploring the Wonder of Pandorific Days Compared to Leap Years

Being new to Pandas, I am attempting year-over-year comparisons with leap years included. The 'dayofyear' function works well, except when dealing with leap years. Here is the code I have so far: df = pd.read_csv('myfile.csv') df[&apos ...

Mistakes in Syntax: If, Elif, and Else Statements

Greetings to whoever comes across this message. I am currently struggling with a semantic error that seems to have me stumped. As someone who is new to the world of coding, I am trying my hand at learning Python 3. My goal is to create a code that informs ...

Ways to determine if an item is present in my list

Is there a way to determine the number of instances of an object in one list compared to another? Let's start with the Card class. class Card(object): def __init__(self, number): self.number = number def __eq__(self, other): ret ...

Can someone provide me with instructions on how to enable OpenGL Specular Light?

Struggling to get specular lighting to work in my OpenGL project using Python. I've managed to figure out texturing, depth, and basic gameplay, but the specular lighting remains elusive. I've attempted to mimic a flashlight by constantly adjustin ...

Solving Project Euler Problem 8 using Python

I'm currently working on solving a question regarding the largest product in a series from the Project Euler website. My approach involved: Saving the 1000 digits as a text file Converting it to a string Creating an array named 'window' to store values I ...

Encountering a Pyserial issue with read_all() function on macOS 11.6.1 running on m1

Device Specifications Operating System: macOS Big Sur 11.6.1 Chipset: Apple M1 Pipenv Version: 2021.11.23 Python Version: 3.10 Pyserial Version: 3.4 Expected Outcome The code snippet below showcases how to replicate the error: import serial ...

Python 3.8 showcases noticeable differences between orjson and json dumps method

I recently made the switch to using orjson for its speed, but I encountered an unexpected issue that had been lingering unnoticed for quite some time. After conducting tests, here are the results. import orjson, json data = json.dumps({"channel_id&q ...

Creating a Stealthy Presence for Headless Chrome in Python

I'm currently exploring methods to make Chrome headless undetectable, following a specific guide I found. The challenge lies in the fact that the guide relies heavily on Javascript and executing scripts via the command prompt. My goal is to develop an exe ...

Is there a way to extract a specific set of numbers from a string?

For the following data: [‘23 2312 dfr tr 133’, ‘2344 fdeed’, ‘der3212fr342 96’] I am seeking a function that can extract values containing a specific number of consecutive numbers. The presence of spaces or other text between the numbers is ...

What is the most effective method for rounding numbers to 4 decimal places?

I'm struggling with rounding numbers to 4 decimal places in Python 3. Despite attempting to use the round function, I keep encountering a syntax error. fname = input("Enter a file name: ") try: ffile = open(fname) ssum = 0 nline = 0 f ...

Determining the Euclidean distance between row combinations in a pandas dataframe: A guide

I am dealing with a DataFrame that contains information about clusters and their respective variables: import pandas as pd foo = pd.DataFrame({'cluster': [1,2,3], 'var1': [0.3,0.5,1], 'var2&apo ...

Guidelines for extracting specific text data from a label element with Selenium and Python

I am working on iterating through a variety of checkboxes in order to verify their presence within a given list, and then click on them if they match the criteria. Here is an example of the HTML element that I have managed to extract: <label> < ...

python3 methods to retrieve the parent directory of a given folder

Within my current code, I aim to navigate to the sibling of the parent element. Imagine that my scriptA.py resides in a directory called DirA. -DirA | |-ScriptA | -DirB |-FileB |-FileC In this scenario, the folder structure is illustrated. My goal i ...

Python Selenium for Web Scraping

I am currently working on a project to extract data from the Sunshine List website () using the BeautifulSoup library along with the Selenium package. My main challenge is figuring out how and where to instruct the driver to wait for elements to load befor ...

What is the process for removing an item from a dictionary?

commercial_list = [ {"title": "Luxury Cars Advertised Here", "company": "Car Dealership", "views": 123456}, {"title": "New Fashion Collection Now Available!", "company" ...

What are the steps for adjusting the size of a frame using the cursor located inside it?

Is there a way to dynamically change the size of a QFrame based on the cursor position? For example: If the default width is set to 50, when the cursor hovers over the frame, the width should increase to 100. When the cursor moves outside of the frame, t ...

Efficiently handling a group of buttons in PyQt5 without the need to manually assign specific actions to each button

I'm currently working on designing a user interface layout that involves multiple buttons where clicking each button will toggle between adding 1 or 0 to a specific position in a list. However, I am facing challenges in managing a cluster of 48 buttons as ...

Is it feasible to create a progress bar using tqdm with the .write() method

Recently, I came up with an idea for a script that encrypts and decrypts files in a specific folder. In this script, the .write() function plays a crucial role in writing encrypted or decrypted bytes to a file. Now, I want to enhance it by adding progress ...

"Having trouble with my for loop not functioning correctly with tkinter python menus. Can anyone offer guidance on how to fix

outputI am verifying that the label and command are functioning correctly. list = {'About', 'Experience'} comand = ['about','experience'] for i in range(len(list)): for t in range(len(comand)): help_menu.add_command(label=str(i), command=str(t ...

What was the reason for the removal of the `encoding` keyword argument from json.loads() function in Python 3.9?

The json package's official documentation explains: json.loads(s, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)¶ As of version 3.6: The s parameter now supports bytes or bytearray t ...

Interact with webpage dropdown menus using Python

I'm currently working on a Python script that interacts with a webpage, specifically , to retrieve a (DNA sequence in fasta format) file. The file is automatically downloaded when a user clicks on a dropdown menu. Here's the dropdown menu: Download (.fs ...

Are mistake entries in a DataFrame using .loc in Pandas a bug or a misunderstanding?

Is there a way to update the contents of an excel file using values from a Python dictionary? I've been trying to use the .loc function, but it seems to be working inconsistently. Sometimes it writes the correct values, and other times it writes the column ...

What is the process for interacting with other class methods and functions through the Kivy GUI?

I am currently developing an app using Python and Kivy. To simplify the process, I am looking for a solution to switch between screens without having to define a function in each individual class. For instance, within my UserLogin class, I have created a ...

Issue with send_message function not successfully sending messages using pytelegrambotapi

I am currently working on a python Telegram bot using django and pyTelegramBotApi. The bot is supposed to respond with "Hello" when the /start command is received. I have set up the webhook successfully and the bot is receiving updates as expected. However ...

What is preventing this particular website from functioning in headless mode?

When I use the following code snippet, it successfully runs in both headless and full browser modes for google.com. However, when trying to access a specific website - 'https://cases.ra.kroll.com/Clovis/Home-DocketInfo', it only works in full mod ...

Disparity in outcomes from the integer division operator

Today, I made an interesting observation regarding floor division: >>> 10.1/1.01 10.0 >>> 10.1//1.01 9.0 >>> 2688937/268893.7 10.0 >>> 2688937//268893.7 9.0 >>> 6.6/3.3 2.0 >>> 6.6//3.3 2.0 I'm ...

Tips for organizing a list and displaying it in Python

I am trying to create a function called f3Groups() that takes in one argument. The function should include a list named cgList, which represents the entire class and consists of 3 lists representing different groups. It is important that cgList cannot be ...

Every conceivable permutation of lists derived from a given list

I am seeking to generate all possible combinations of lists with a specific size. For instance, let's consider a list K, where K = [3, 5, 2]. The code snippet below accomplishes this task for the given list. However, I am interested in finding a way to m ...

Discover the index of each element within numpy arrays

I've been working with the numpy library's searchsort() function to find the index of elements in a numpy array. Interestingly, it seems to be functioning properly for some arrays but not others. I'm trying to figure out what might be causing this discre ...

Buttons in a Python Gtk interface

Currently, I am developing a sample tool with GUI, and everything seems to be working fine. However, I can't seem to figure out how to ensure that the buttons always stay centered on the GUI regardless of how it is resized. I have tried various methods t ...

Mastering the art of Python to extract all XPATHs from any website

Is there a method to extract product listings from various websites without needing to manually loop through each XPATH? Some sites like Amazon and Alibaba display up to 10 products per page, while others may have 20. I am looking for a way to retrieve a ...

Steps to remove the smallest number from an array: if there are multiple smallest numbers, remove the first one

I am currently working on a script that takes an array of random numbers as input. I have successfully implemented code to remove the lowest number in the array, but I'm facing an issue when there are multiple occurrences of this number. How can I ens ...

Pandas assigns varying values to a column based on the specific values found in another column

Below is my dataframe named df, days NaN 70 29 I want to add a new column called 'short_days' based on the conditions, df['short_days'] = np.where(df.days < 30, 'Yes', 'No') However, when the value is NaN, I want the entry in 'short_days' to be 'Not ...

Is there a way to retrieve this data from a webpage using Python, Selenium, and ChromeDriver?

<div class="flexible row ng-scope"> <!-- ngRepeat: graph in graphs track by $index --><figure class="figure-gauge flexible column ng-scope" data-ng-repeat="graph in graphs track by $index"> <figcaption class="rigid"> ...

locate the desired element using the xpath of its sibling

Is there a way to target the element following '>' using xpath without referencing its text content? Specifically, I am looking for just the element "n" in my case. driver.find_element_by_xpath('//div/div/*[contains(text(),">")]/precedin ...

Encountered a Python interpreter error when attempting to load a JSON file with the json.load() function

In the realm of Python programming, I have crafted this code to delve into a JSON file. import os import argparse import json import datetime ResultsJson = "sample.json" try: with open(ResultsJson, 'r') as j: jsonbuffer = json.load(j) ...

Leveraging Python with Selenium to choose and duplicate text

<div class="top-info"> "Vote : 42 - Out : 84 - Rate : 3 - Strategie - " <a href="/site-Ezy+1.29++Serveur+FUN++Serveur+AnkaLike+-44578">Info</a> </div> Hey there, I need help extracting the value 84 from the 'Out' section in this c ...

Guidelines for Retrieving Data from Dictionaries and Generating Lists

I've got a bunch of dictionaries: list_of_dicts = [ {'id': 1, 'name': 'example1', 'description': 'lorem'}, {'id': 2, 'name': 'example2', 'description': 'ipsum'} ] All I want to do is extract the values from each one and put them into a list of l ...

Is implementing cogs in Discord.py an ineffective strategy?

When looking to separate my code into different files, I typically create a bash script to concatenate them together like so: cat first.py second.py third.py > run.py python ./run.py However, using cogs requires adding additional code. Is there a speci ...

"Revamping" a string using a formatting operator

I'm facing a rather simple dilemma that I can't seem to find an answer for anywhere else on the internet. The issue lies with a variable set as a string containing a %s format operator. var1 = "Arbaham" var2 = "My name is: %s" % var1 print(var2) ...

Using Selenium for Python-based authentication

Is it possible to automate the launch of admin area URIs on a website using Selenium in a specific browser without prior authentication? If not, what is the best way to handle authentication using Selenium? ...

Attempting to transform UNIX Epoch time to regular date format extracted from JSON<Object>

Trying to convert Unix epoch time into a standard date format using JSON. Snippet from the JSON file: {"success":true,"lastUpdated":1621365664405 An implementation is as follows: import requests import json from datetime import dateti ...

Exploring the transformation from binary to base 48 representations

A function was recently created to convert binary strings into base48 values. While this function has performed well in most test cases, there is one particular instance where it seems to falter. When the binary string "1010000001101101011000000100000001 ...

Finding and saving several elements using selenium

In my current project, I am trying to locate and save the positions of certain elements so that a bot can click on them even if the page undergoes changes. While researching online, I found suggestions that storing the location of a single element in a var ...

Sending emails from Django is a common task for web developers who need

I am currently enrolled in a Django tutorial, but I have hit a roadblock when it comes to sending emails from Django. I have been working on using Django's built-in django.contrib.auth password reset views, and while they are functioning properly, ema ...

Using SQLAlchemy connection pooling with multiple concurrent threads

To start off, I am creating a basic table structure: import threading from sqlalchemy import create_engine from sqlalchemy import Column, Integer, Float, String, Date, DateTime, Boolean, select from sqlalchemy.ext.declarative import declarative_base from ...

Python 3.5 Custom Compare Sorting Issue: Unexpected Results

I am currently working on creating a custom sorting method for a list of strings representing playing cards. The list consists of card values in the format: ['d10', 's2', 'c3', 'b5', 'c7', 'b2', 'b10', 'b7', 'c6', 's6'] Each string includes a character ( ...

Error: The variable "unicode" has not been defined globally in Python 3

I'm currently exploring the functionalities of a Python package called bidi. Within one of the modules (algorithm.py) included in this package, there are certain lines causing errors despite being part of the package. Here is the problematic code snippet: ...

Python has raised an error: The JSON data has extra content

I'm currently working on a project where I've created a simple login screen program. In this program, users are asked to create an account containing their name, age, city, and login information which is stored in a JSON document. I've successfully impleme ...

Avoid automatic redirection of URL to a different page in Django after ensuring its permanence

In my Django app, I initially set up a redirect path in my urls.py file so that when users visited example.com, they would be redirected to example.com/blog. urlpatterns = [ path('admin/', admin.site.urls), path('blog/', include('blog.urls', namesp ...

Discover how to extract JSON data from a webpage even when the response is "None"

I need to retrieve data maps from their API, which are in JSON format. This is the code I have written: r = requests.get(url) if r.ok: soup = BeautifulSoup(r.content, 'lxml') soup.status_code j = json.loads(str(soup)) However, an error has o ...

Pandas read_csv function encounters a MemoryError issue

I am dealing with a 5GB file named 1.csv and using a pandas script to remove duplicates. However, every time I try to run the script, I encounter a memory error. I attempted chunking the large file, but this approach only allows me to process parts of the ...

How can I invoke a function from the ListView using Kivy?

Having a bit of trouble figuring out how to pass a value through a procedure when a ListView item is pressed. The simplified example given below reflects my desired outcome and the structure of my main code. I am aiming to have ChangeScreen(self.index) cal ...

Creating a receipt program in Python and protecting previous data from being overwritten

I am currently learning Python and attempting to create a program that generates an invoice listing all items, along with their prices and quantities. Each item should be displayed on a separate line. While I have managed to print each item in a line, I a ...

What are the steps to set up chrome webdriver in headless mode?

After reviewing older posts, it seems like the code they provide is deprecated. The following code snippet I am currently using successfully opens the browser but not in headless mode due to the presence of a GUI. from selenium import webdriver from seleni ...

Invalid operator detected in TypeT5

File "/work/09235/kunjal/ls6/TypeT5/train_model.py", line 112, in <module> wrapper = train_spot_model( File "/work/09235/kunjal/ls6/TypeT5/typet5/train.py", line 180, in train_spot_model trainer.fit( File "/home1/ ...

Python Error: ImportError - Selenium Module Missing on Windows

My setup involves using Python 3.6 on Windows10, where I created a virtual environment using the command: python -m venv venv In this environment, I installed several packages including Selenium using: pip install selenium Unfortunately, when I try to ...

Issue encountered while using pyinstaller: UnicodeDecodeError: 'utf-8' codec is unable to decode byte 0xb3 at position 4055: starting byte is invalid

Having trouble compiling a Python code using pyinstaller. The python code includes packages such as os, datetime, python-pptx, and tqdm. When running the following line for compilation: C:\test>pyinstaller -F Final_ver.py An error message is dis ...

Searching for a specific element using XPath in Selenium

Currently, I am working on mastering the art of web scraping by following this insightful tutorial. My goal is to create a webscraper that can fetch job listings efficiently. However, I have hit a roadblock while trying to extract the links for individual ...

Using Python 3 to extract specific strings from an HTTP request's response

I'm currently facing a challenge with parsing data from an http request response. Can anyone provide some assistance? Below is a snippet of my code: import requests r = requests.get('https://www.example.com', verify=True) keyword = r.text ...

Selenium Python encounters a stale element issue after downloading a file

Having an issue with downloading videos after clicking a link. The process works fine for the first page, but encounters an error when trying to download from a new page opened by a second link. The error message states that the element went stale during ...