Questions tagged [python]

Python, a versatile and dynamic programming language, offers a multitude of functionalities. Known for its easy comprehensibility and efficient syntax enforcement, Python has gained popularity among developers. However, it's important to acknowledge that Python 2 is no longer supported since January 1, 2020. If you have questions regarding specific versions of Python, kindly include the [python-2.7] or [python-3.x] tag. Additionally, when utilizing alternate Python variations such as Jython or PyPy, or incorporating libraries like Pandas or NumPy, please remember to include relevant tags.

Insider's guide to showcasing code in vibrant colors using Python Django

Context: I am currently working on a Python Django web application and need to showcase code snippets in the browser with syntax highlighting. An example of the code snippet I want to display would be: if True: print("Hello World") I am look ...

Constructing Root System for Python (_sqlite3 Additions)

I have been utilizing buildroot for the past 6 weeks, delving into the world of embedded Linux for the first time. Although I am still at a novice level in this area, I have managed to tackle most of the challenges that have come my way independently. The ...

The response from YouTube API v3 does not include any video data

Can you explain why the latest video uploads are missing from this playlist - UUbLd_GVzZaFSb7ZqY0iz2TA? Both videos were uploaded 8 months ago and I'm not experiencing this issue with other playlists I've checked. This is the query I used in Goo ...

Exploring the dynamic capabilities of Pandas with the use of .cut and

Having both dataframes, here is the first one: x = pd.Series( ["(-20, -10]", "(-140, -130]", "(0, 10]"], dtype = "category") y = pd.Series( ["(0, 50]", "(100, 150]", "(-50, 0]"], dtype = "category") df_xyz = pd.DataFrame({'x_bin': x, 'y_bin': y }) df_xyz ...

Python's lightning-fast combinatoric generator

Currently working on a python project, I am in need of a high-speed generator function that can create all potential sets of non-negative integer numbers less than n. These sets must contain no more than s elements and the gap between the largest and small ...

The py2exe package was not found in the system

I'm in the process of converting a Tkinter application into an executable file using py2exe. Everything seems to be working correctly, except when a specific function is called, the .exe file generates the following error: Exception in Tkinter callback Tr ...

Retrieve token and ETH value for an ERC20 transaction using the Etherscan API

I am embarking on my journey with the etherscan API for the first time. My objective is to efficiently extract data from a wallet, specifically focusing on "Token Transfer ERC20", and then be able to calculate the ROI of the wallet. To achieve this, I wil ...

Python 3.10 raised an UnboundLocalError indicating that the variable 'driver' was referenced before being assigned

Just starting out with Python, need some help import pytest from selenium import webdriver @pytest.fixture() def setup(browser): if browser == "chrome": driver = webdriver.Chrome() print("Launching chrome browser.... ...

Ways to prevent a Chrome tab controlled by Selenium/Chromedriver from closing

Is there a way to prevent the google chrome tab from closing immediately after it's opened? Could time.sleep or while loop be used in some manner? from selenium import webdriver from webdriver_manager.chrome import ChromeDriverManager from selenium.webdr ...

"Troubleshooting: HtmlResponse functioning correctly in Scrapy Shell, yet encountering issues in script

While working on a scraping project, I decided to use scraperAPI.com for IP rotation. In my attempt to incorporate their new post request method, I encountered an error stating 'HtmlResponse' object has no attribute 'dont_filter'. Below is the custom start ...

What is the most efficient method for eliminating harmful characters from a string while retaining Unicode characters?

After conducting an experiment on HackerNews where participants were encouraged to attempt breaking my web app at www.tagxt.com, some individuals managed to find vulnerabilities that I am currently addressing. One specific issue I am focusing on is: How ...

Python: verify if a host name is successfully resolved

Is there a way to create a Python function that will return 1 if a hostname resolves and 0 if it does not? I've searched for helpful resources but haven't had any luck. Any ideas? Appreciate your help, ...

Switching XML to JSON using Python while confirming it against a schema

I am looking for a solution to convert XMLs into JSON format. Although I have found various packages like xmltodict in Python that can accomplish this, I'm facing an issue where single elements within a node are being converted into dictionaries. Howe ...

What is the accurate Scrapy XPath for identifying <p> elements that are mistakenly nested within <h> tags?

I am currently in the process of setting up my initial Scrapy Spider, and I'm encountering some challenges with utilizing xpath to extract specific elements. My focus lies on (which is a Chinese website akin to Box Office Mojo). Extracting the Chine ...

How to set up a static webdriver fixture and a generator in Pytest?

I am currently developing an automation test to detect any potential dead links in a WordPress plugin. In order to achieve this, I have implemented two helpful functions. The first function initializes a Selenium webdriver: @pytest.fixture(scope='ses ...

Find a specific word in a file using a Python script that accepts command line arguments

My text file (test.txt) contains 6-7 lines, with 3-4 of them including the word "exception." Out of these 3-4 lines, two also contain the word "abc." I am working on a program to separate the lines that contain a specific user-inputted word (word1), but no ...

The pygame window fails to stay in fullscreen mode

Currently, I am working on developing a game using the pygame module. However, I have encountered an issue with the fullscreen mode functionality not working as expected. Although the program itself runs smoothly, when attempting to switch to fullscreen mo ...

What is the process for adding a value to a list in a JSON file?

How can I ensure that values are appended to a list in a JSON file without being overwritten every time the server is re-run? { "heart_rate": [ 72.18 ], "Experiment_time": [ 01/22/2023 11:59:59 ] } I need new values to be added to th ...

Having trouble finding an element with Python Selenium after switching to a frame in Firefox browser?

I'm facing difficulty locating the element within the frame even after switching to the correct frame. Below is my code, error message, and HTML source. When I right-click on the frame and choose This Frame -> Show Only This Frame, I can find the elemen ...

discord.py eliminate all roles from a specified list of roles

I have been working on developing a bot that has the capability to eliminate numerous roles. I have successfully compiled a list of all the roles that need to be eliminated from the member. However, I am facing an issue where I do not want to remove all of ...

Leveraging the Content-Length Header in Scrapy Requests

This is the specific page I am attempting to crawl, and this is the corresponding AJAX request that fetches the necessary data. I have replicated the same AJAX request with identical headers and request payload. While the request does not error out, it re ...

Issue encountered when storing and retrieving a pointer within a class using Boost.Python: incorrect data type detected

I am encountering an issue while using Boost.Python 1.54 on Windows with MSVC2010. I am trying to store a pointer to one class in another class from Python and then retrieve it, but it appears that the data type is getting altered somehow. Below are my cl ...

What is the best way to test a Singleton's __del__() method?

Currently, I am utilizing a singleton object to manage database connections within my application. As part of my extensive test suite, I rely on this object for testing purposes. However, there is also the need to test the object itself by deleting it and ...

Is there a way to read and write data in memory in Python similar to how one would with a file?

My background is in C++, and I typically create data handling classes/functions to work with stream objects instead of files. I'm curious about how I could revise the following code to handle a stream of binary data in memory rather than a file handle. de ...

Issue discovered: pytest configuration in pytest.ini is not being recognized when pytest.ini is located inside the "tests" subdirectory instead of the main

pytest is giving a warning about an unrecognized custom mark when running my test suite, even though I believe I have registered it correctly according to the pytest documentation (refer to this link). The structure of my Python project is as follows: my_ ...

Encountering a value error when using enc.transform with a OneHotEncoder set to sparse_output=False in pandas

My dataset named temp is a timeseries data with 4 columns: Date, Minutes, Issues, Reason no. In this dataset: temp['REASON NO'].value_counts() produces the following output: R13 158 R14 123 R4 101 R7 81 R2 40 R3 35 R5 31 R8 ...

What is the best way to split a string in Python?

I have a unique string in the format of ( + m1 + "|" + m2 + ) and ( + m1 + "." + m2 + ) where m1 an m2 consist of "6", "7", "8", "a" characters. Here are some examples of valid expressions: "(6|7)" "((8.7)|(6.7).(a.2))" My question is, how can I split th ...

Guide on transforming scraped table information into a dictionary using Python Selenium

Below is the table structure: <table class="vinInfoTable"> <tbody> <tr> <td class="caption">VIN</td> <td>W1K2052131G080816</td> </tr> <tr> <td clas ...

Struggling to pinpoint the exact element in Python/Selenium

As I work on creating a website manipulation script to automate the process of email mailbox creation on our hosted provider, I find myself navigating new territory in Python and web scripting. If something seems off or subpar in my script, it's beca ...

Integrate PySide with PyGame for a more dynamic and interactive

Are you interested in creating a user interface that includes forms for app configuration and a rendering component, such as displaying sprites? Is there a way to integrate PySide with PyGame within a single application? For instance, how would one go abo ...

Securing a worksheet in Excel with Openyxl and tkinter

In my Python project, I am attempting to secure an Excel sheet using Openyxl. After experimenting with various methods, I have not been successful. The objective is to enable data entry for users to input information and then view it in Excel without the a ...

Python code for searching XML elements with namespaces using XPath queries with specific tags and attributes

It seems like I must be missing something fundamental here, as every example I find and read on SO suggests that this should work. My goal is to utilize an XPath search with the lxml etree library to extract information from a Garmin TCX file: <?xml v ...

Discover the Practical Utility of Maps beyond Hash Tables in Everyday Life

I am currently attempting to explain the concept of Maps (also known as hash tables or dictionaries) to someone who is a beginner in programming. While most people are familiar with the concepts of Arrays (a list of things) and Sets (a bag of things), I ...

Is it possible to utilize formatted strings in Python selenium to locate elements based on different categories such as xpath, css, etc?

An interesting revelation just hit me and it's quite unsettling since my entire program relies on locating elements by CSS selector using formatted strings. Let's consider this example: stop_iteration_for_foh = driver.find_element_by_css_selector(f'.subhe ...

Tips for arranging the initial letter in a particular sequence and the subsequent letter in a different specific sequence

I've been trying to figure out a way to sort a list based on the specific order of the first two letters. Here's the code I have so far: Rank = '34567890JQKA2' Rank2 = 'DCHS' def sort(words): words.sort(key=lambda x: Rank.index(x[0])) words.sort(key=l ...

Broaden and derive the content

Do you think it's achievable to click on all the + buttons and retrieve text values using Selenium (in Python) from this page containing codes for literature genres in Russian? Keep in mind that the options need to be fully expanded, covering multiple le ...

What is the best way to shift the bits of two numbers to the right in a numpy array?

Currently, I am in the process of developing a script to transfer BMP images to Delta Electronics HMI, which is an industrial automation touch-panel. The challenge lies in the fact that HMI has a unique pixel format that resembles 16-bit RGB555, but with s ...

Selenium testing on Sauce Labs with Android devices

Currently, I am in the process of executing a series of Selenium tests on Sauce Lab. My goal is to run these tests on all Android browsers, but I am facing challenges in correctly specifying that I need an Android device. I have based my code on the follow ...

Can you suggest an improved method to phrase this?

Is there a more efficient approach to accomplish this task? I have a feeling that my code is too repetitive. O = viz.pick(1, viz.WORLD) BackSetts = ["set_b1b", "set_b2a", "set_b1a", "set_b2b"] LeftSetts = ["set_l1a", "set_l1b", "set_l2a", "set_l1b"] N ...

Guidelines for requesting integer input from the user with Python's tkinter library

I'm facing an issue with getting the correct integer value input from a user in Python tkinter. I've tried using a=n.get() and then converting it to an integer using a=int(a), but it's not working as expected. Below is the code snippet I used: def selectpa ...

Leveraging Ajax in Django to communicate with the backend and showcase the outcome

I need assistance with implementing ajax functionality to send user input to a Django backend for text processing, and then display the results. However, due to my limited experience with ajax, I'm struggling to figure out where I'm going wrong. Can someon ...

Creating a scrollable text box in Python Tkinter

I created this code with the intention of quickly pulling and displaying data from Wikipedia. Everything functions well unless the summary from Wiki is too extensive for the box to present all at once. I believed that including sticky = N+S+E+W would resol ...

Experiencing difficulties launching InstaPy

After successfully setting up selenium and geckodriver to work with firefox, I decided to give InstaPy a try for the first time. With firefox installed, I was able to launch the browser, go to Instagram, and log in with the code snippet below: browser ...

Error encountered with S3Cmd: Issue with parameters causing upload failure

When I try to upload a file from my computer to an S3 bucket using the command s3cmd put c:/ok/ok.pdf s3://bucket_name/, I am encountering an error. PARAMETER PROBLEM: NOTHING TO UPLOAD It seems like there is no solution for this issue. I followed the ...

Finding a specific item within a webpage

I am having trouble locating an element on a webpage, and I suspect frames or iframes may be causing the issue. Despite trying xpath and other criteria, I keep receiving a "No such element" message. The webpage in question can be found at . After attempti ...

What alternatives exist for replacing torch.norm with another PyTorch function?

I need to find an alternative to the torch.norm function in Pytorch. I was successful in replacing torch.norm when dealing with a single tensor, as shown below: import torch x = torch.randn(9) out1 = torch.norm(x) out2 = sum(abs(x)**2)**(1./2) out1 == out ...

Retrieve the name of the subparser program using Python's argparse module to include in the help message

Currently, I am developing an argument parser for a Python module that includes multiple subparsers. My main goal is to create a shared argument whose Argument constructor is passed on to several child components: from argparse import ArgumentParser parse ...

When looping through a numpy array, only the final item is returned

I'm experimenting with implementing a Sine wave function for navigation purposes. In my main code, I have two functions defined as follows: def stop(): steering = 1024 throttle = 1024 return steering, throttle def case2(): steering = ...

The hitboxes are constantly in motion, never remaining stationary

Currently, I am working on a game project involving gathering trees and battling zombies. One issue I am encountering is that the hitboxes of trees are not staying in place while walking on the map; instead, they move along with the screen. I have b ...

The radio button cannot be interacted with as Selenium cannot find any other unique identifier for it

While examining the code of the button, I landed on this specific section: <input type="radio" name="chosen" value="UniqueNameExample"> I am attempting to locate an element within this code that I can interact with by c ...

Issue with Python27 on Windows 8.1 or 10 causing printers to not be displayed

I am facing an issue with my 32-bit Python and win32print installation. When I run the code on Windows 8 or 10, it doesn't display any list of printers but just shows: () https://i.stack.imgur.com/IlDts.png Why is this not working as expected? import wi ...

Assigning a value to a specific index in a sublist (b) nested within another list (a) will automatically assign that value to the corresponding index in all sublists within list (a)

Trying to create a 9x9 array using nested lists has resulted in an issue where setting a single value is affecting every row of the array. The initial list looks like this: [[0,0,0,0,0], [0,0,0,0,0], [0,0,0,0,0], [0,0,0,0,0], [0,0,0,0,0]] Upon executi ...

Is it possible to include a hyphen (-) in a query parameter name when using FastAPI?

Let's explore a sample application: from typing import Annotated import uvicorn from fastapi import FastAPI, Query, Depends from pydantic import BaseModel app = FastAPI() class Input(BaseModel): a: Annotated[str, Query(..., alias="your_name&qu ...

The tkinter library is unable to locate the specified function

As a beginner in tkinter, I find myself struggling to grasp the concepts of frame, self, and so on. This is what I currently have: class ScalesPage(Frame): def GetNotes(): key = KeyEntry.get() intervals = ScaleEntr ...

Why is the upload handler not aligning with GAE Blobstore?

Following the documentation provided by GAE, I have implemented an upload handler to upload blobstore. However, when I select a file on my computer and click the Submit button on the HTML page, it displays 'The url "/upload" does not match any handlers.' ...

Problem with WOL MAC Address functionality

I've been attempting to execute a python script that sends a magic packet to computers within my network. The script functions properly on other devices, but when I attempt to run it with my own MAC address, I encounter an error. This is the python s ...

Error with Ng-Repeat displaying incorrect data when deployed on Heroku

After creating a Django app that hosts data and a login, the user interacts with an Angular app inside Django upon logging in. Everything works perfectly on my local machine, but there's a strange issue on the Heroku-hosted app. A specific ng-repeat is mix ...

How to fill missing values in a Pandas dataframe using corresponding values from another dataframe with matching index?

Referencing a question from Stack Overflow about filling in missing row values in a pandas dataframe. Here is the dataframe provided with missing values that need to be filled: mukey hzdept_r hzdepb_r sandtotal_r silttotal_r 425897 0 ...

Locate child elements within a parent class that includes the term "hijack" using

Check out this page: Extract data from: <tr> <td class="event_type">Possible Hijack</td> <td class="country"> </td> <td class="asn">; <i>Expected Origin AS:</i ...

What is the best way to extract a table from a website that has stored the table data separately from the HTML?

Attempting to extract table data from the following URL: In a previous scraping attempt, the Python packages utilized were: from bs4 import BeautifulSoup import requests import mysql.connector import pandas as pd from sqlalchemy import create_engine Howe ...

Searching for shared elements within a row in a pandas data frame using Python 2.7

I have a single data frame with multiple rows and I am looking to identify common elements within each row as well as determine the minimum and maximum values within that row. Unfortunately, I haven't been able to locate any built-in function that can help ...

queryset filtering and ordering based on frequency of duplicates

class Product(models.Model): name = models.CharField(max_length=255, null=True, blank=True, default=None) Let's talk about applying a custom queryset in Django: query = Product.objects.filter(Q(name__contains="a") | Q(name__contains="c& ...

Guide: Generating a Random Number with Prefix using Python

Can you help me create a list of all potential numbers in the given prefix? import random prefix = "05" print prefix + #List of Potential Numbers Goes Here ...

Locate hexadecimal values within a list through the use of a regular expression

Given input: A list is provided lst = ['a', '4', 'add', 'e', 'a', 'c0a8d202', '128', '4', '0', '32'] Utilizing regular expression to identify the hex value in the given list. Output: Return the index of the hex value (In this case, the hex va ...

Why does Python Selenium's browser.find_element_by_class_name sometimes return an error?

Just starting out with Python and currently working through "Automate the Boring Stuff" by Al Swigart. I've created a script to play the popular game "2048" at "". After a few moves, the game will reach its maximum score and display a "Game Over!" message ...

What could cause pandas to return a sum of 0 when using .sum(axis=1) with numpy datetime64 values in one row?

My data includes a mixture of floating numbers and numpy datetime64 values in different rows within a pandas dataframe. df2 = pd.DataFrame( [[np.datetime64('2021-01-01'), np.datetime64('2021-01-01')], [2, 3]], columns=['A', 'B']) After attempting ...

How can I handle exceptions when trying to locate an element using text() in Selenium with Python?

HTML <span class="menu-text">Download App</span> This is the code I am using to find the element driver.find_element_by_css_selector("//span[contains(text(),'App')]") Alternatively, I can use this locator: driver.find_element_by_css_select ...

Is there a way to swap out the "-" symbol in Pandas without affecting the values for pd.eval() in the future?

Whenever I try to replace the "-" character in my data, it affects other values as well. df['land_area'] = df['land_area'].str.replace("-", '0') I need to ensure that the evaluation process will run smoothly without any comp ...

Is there a way to create a combined bar and line plot on a single graph with separate Y axes?

I have two sets of data that share a common index, and I would like to display the first set as a barplot and the second set as a line plot on the same graph. Currently, I am using a method similar to the one shown below. ax = pt.a.plot(alpha = .75, kind ...

Python WebDriverException: The loading status cannot be determined because there is no execution context available

Currently using Selenium for web scraping with the following code: driver.switch_to.window(driver.window_handles[1]) WebDriverWait(driver, 60).until(EC.presence_of_element_located((By.CSS_SELECTOR,'#listForm > div ...

Utilizing decorator functions to yield the return of a wrapper

I have a question regarding the process of returning the wrapper in this code snippet. Why is it necessary to return the wrapper and where exactly is it being returned to? I understand that when I return the wrapper, it returns a pointer, but I'm confuse ...

Python Error: 'str' Type Object Does Not Have Attribute 'string'

I've been looking for answers everywhere, but can't seem to find a solution to my problem. I'm trying to create a shape with a specific size by multiplying the "-" character by a certain number and displaying it within classes. Here is the c ...

Is there a way to automate the process of navigating through multiple pages in order to extract and download Excel files using

I am currently developing a web scraping tool that is designed to navigate through website pages in order to extract Excel files from a dropdown menu located at the bottom of each page. Unfortunately, the webpages only allow me to download the 50 location ...

Utilizing Python with Plotly, Scattermapbox can be customized with distinct colors based

I am looking to highlight certain areas on a map with different colors based on values in a dataframe. The coordinates for each area are defined in the dataframe and I want to use the filled area feature. How can achieve this? (Question is similar to an u ...

Python code example: How to compare two dictionaries stored in a list

I am struggling with creating a script to compare two dictionaries that are stored in a list without knowing the names of the dictionaries. Can someone assist me with this? Sample code: Is my approach correct? If not, please guide me towards the right sol ...