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.

Disabling the parent checkbox feature in PyGTK

I have successfully created a Treestore in pygtk, but I am facing an issue with a checkbox that I do not want to appear. It can be seen in the image below. Computer1 [ ]-----This checkbox is unwanted C drive [ ] D drive [ ] E drive [ ] Here i ...

Utilizing Jupyter Notebook to connect two slider widgets with the incorporation of an offset to the selected value

Currently diving into the ipywidgets documentation in search of an answer to a specific query. In my scenario, I am working with 2 sliders. Connecting the minimum value of the second slider to the actual value of the first slider is a straightforward task ...

Error encountered during data insertion in Python with MySQL database

I need assistance with inserting values into a MySQL database after extracting them using Python from a website. However, I encounter an error while trying to insert them into the database. The error message is as follows: mysql.connector.errors.Programmin ...

Python Qt: Create a custom QGraphicsItem with interactive resizing capabilities that does not change size when mouse hovers over

I am attempting to create a Python class that wraps around QGraphicsRectItem (PySide or PyQt4) in order to enable mouse interaction through hover-overs, allow for movement, and resizing. Everything is functioning properly except for one issue: It appears ...

Executing Selenium script using Python to download and change the name of a file

I've been facing a challenge while using selenium to download and rename files (around 60 per page). Here's what I've attempted: 1. First, I tried using the solution provided by supputuri to go through the chrome://downloads download manage ...

Python code for performing a surgical replacement of a JSON field with another in a file

Currently, I am dealing with a large collection of JSON files structured like this: File00, timestamp T1: { "AAA": { "BBB": { "000": "value0" }, "CCC": { "111": "value1", "222": "value2", "333": "value3" }, " ...

What could be the reason for my Python venv showing an exit status of 1?

My attempt to establish a virtual environment has been unsuccessful. I am currently using an M1 MacOS and executing the python -m venv myworld command This is the error message that I encountered: Error: Command '[ '-Im', 'ensurepip', '--upgrade', '--defa ...

Leveraging pandas for extracting data from a specific section within a JSON file

Currently, I am in the process of analyzing my electric bill usage by utilizing hourly data that I downloaded in JSON format. Even though I was excited about it at first (woot!), the process has turned out to be more cumbersome than I anticipated: import ...

Creating a dynamic MPTT structure with expand/collapse functionality in a Django template

I am looking for a way to display my MPTT model as a tree with dropdown capability (open/close nodes with children) and buttons that can expand/collapse all nodes in the tree with just one click. I have searched for examples, but the best I could find is ...

Checking if each individual element is within a range of 80 by comparing it to the next element

I have a .csv file containing 2289 data points. The first ten are as follows: [1071936.0, 1231944.0, 1391953.0, 1551957.0, 1711960.0, 1711961.0, 1871964.0, 2031968.0, 2031969.0, 2191973.0] Within this dataset, there are two specific data points on rows 5 ...

Python input is restricted when executed from a batch file within a conditional statement and following a timeout period

Here is a simple working example: test.bat: @echo off if 0==0 ( timeout 3 python test.py ) test.py: input('press ENTER to exit') In cmd.exe: call test.bat > Waiting for 0 seconds, press a key to continue ... > press ENTER to exit_ However, ...

The issue of time inconsistency in model object save when using datetime.now() in Django

This table shows my admin interface with records ordered by their id in descending order (latest record at top). Below is the code snippet used for creating model objects and saving them: notification = Notification(from_user=from_user, to_user=to_user, ...

The result of list.append displays the term "collection" following every loop iteration

I need to create a Python list with entries that appear different numbers of times: import numpy as np frequency = (1, 2, 1, 2, 1) numbers = np.random.choice(9, size = (5, 3), replace=True) list_entries = [] for i in range(0, 5): list_entries.append( ...

Is there a more efficient method in Python to store current variables in a lambda function without altering the existing ones?

This example perfectly illustrates the issue: ans = [] for x in range(1, 10): ans.append(lambda: x) # ----------------------- # let's see what happened: ans[0]() # outputs 9 instead of 1 How can we ensure that x is captured right away in the function, ...

My Python script utilizing Selenium is failing to execute

Why is the loop not functioning correctly after opening the initial element based on the xpath? I keep receiving the following exception: raise exception_class(message, screen, stacktrace) selenium.common.exceptions.NoSuchElementException: Message: Una ...

Finding the smallest value within the data from the past N days

In my dataset, I have the following information: ID Date X 123_Var 456_Var 789_Var A 16-07-19 3 777 250 810 A 17-07-19 9 637 121 529 A 20-07-19 2 295 272 490 A 21-07-19 3 778 600 ...

Is Selenium Service not recognizing the executable_path parameter?

Currently using Selenium 4.1.5, I encountered an issue while trying to execute the following code: from selenium import webdriver from selenium.webdriver.chrome.service import Service service = Service(executable_path=f'./chromedriver.exe') driver = webdr ...

Looking to optimize your Python code by efficiently eliminating reversed duplicates from a list within a list and saving

Within my nested structure, I have millions of lists (currently using tuples). In each list, an element can only appear once. Initially, I believed that all lists were unique and necessary. However, I recently discovered that my nested list contains pairs ...

What is the formula for determining the radius of a circular object in the shape of a turtle?

My goal is to create collision detection between turtle objects that are represented as circles. To achieve this, I need to determine the radius of these circles. import turtle as t screen=t.Screen() screen.setup(1.0,1.0) screen.bgcolor("#000") ...

I'm curious, where exactly do pip and conda store the record of installed packages to track who installed each one?

After running some pip install commands within my conda environment, I noticed that both conda and pip stick to the Python convention of installing packages into the site-packages directory. Upon checking with pip list and conda list, I found that they ha ...

Is the sudden disconnection from Chrome after a WebSocket handshake related to a domain mismatch or is it possibly a bug in Chrome?

I created my own WebSocket server using Python, but I encountered an issue where Chrome 4.0.249.78 dev (36714) always disconnects after the handshake process. Wanting to rule out any issues with my code, I tested it using the WebSocket server from , only t ...

What can be done to address Tensorflow's preference for utilizing CPUs over GPUs?

For my project on Windows 10, I am using Anaconda with TensorFlow 2.3 and Keras 2.4.3 for a CNN example. So far, I've set up Visual Studio 2019 Community Edition, installed CUDA 10.1, and added cudnn 8.0.5 for compatibility. In my Anaconda environment, I ...

Encountering the "expected string or bytes-like object" error while parsing sentences from a text file for tokenization

Initially, I believed my code to open a file, read its contents, and tokenize it into sentences was straightforward. import nltk text = open('1865-Lincoln.txt', 'r') tokens = nltk.sent_tokenize(text) print(tokens) However, I consistently encounter the ex ...

Developing a Node/Express API that initiates an asynchronous Python subprocess

Essentially, it involves spawning a Python subprocess which in turn spawns another asynchronous Python subprocess. However, due to the lengthy title, Node/ExpressJS is supposed to wait for the initial Python subprocess to ensure its successful execution, b ...

BeautifulSoup Pagination in Python: A Complete Guide

I am currently working on a web scraping project for the following website: I have successfully scraped the data, but I am facing challenges with pagination. My goal is to create a loop that scrapes the next page button and uses the URL from that button t ...

divide requests using regular expressions

#When attempting to use regex to split this string, I am encountering incorrect outcomes. import re queries =""" INSERT ignore into persons VALUES (15,'Tom D.', 'Erilchsen', 'Skagen 21', 'Erlangen'); select * from persons; ""&quo ...

Obtain the name of an Enum from various values in Python

I need to retrieve the name of an enum based on one of its values: class DType(Enum): float32 = ["f", 8] double64 = ["d", 9] When I access a value by providing the name, it works fine: print DType["float32"].value[1] # prints 8 print DType["float ...

Tips for using Selenium to download .csv files in Python

Utilizing Selenium to browse through this particular website: https://apps1.eere.energy.gov/sled/#/ I am interested in obtaining data for a city such as Boston: here is my process: from selenium import webdriver from selenium.webdriver.common.keys impor ...

Combining data from various lists to populate a dictionary and generate a JSON file

I am currently working with a .dat file that I need to convert to json format. The challenge is that the data in the first half of the file has an awkward format that I must handle myself, so I cannot rely on pre-existing source code. After restructuring ...

What is the best way to delete any blank strings from a list that is associated with a particular key within a group of dictionaries?

As a newcomer to Python with a background in social sciences, I am making an effort to articulate my issue and sincerely appreciate any assistance! My challenge involves a list of dictionaries containing data on online recipes. Within the specific key ['i ...

Encountering an IndexError due to the string index exceeding its limit

Given an integer in base-10, let's call it n, your task is to convert it to binary (base-2) and then find the maximum number of consecutive 1's in its binary representation. Below is a code snippet that attempts to solve this problem: #!/bin/python import ...

Looking for Assistance with PyGreSQL's upsert() Function

Currently, I am running CentOS-6 with Python 3.8, PostgreSQL 12, and PyGreSQL 5.2.2. In previous versions, my code included a function that would insert a row of data if an update raised an exception due to the row not already existing. import pg db = pg. ...

Encountering the error message "Failed to load resource: the server responded with a status of 500 (Internal Server Error)" while using Django and Vue on my website

While working on my project that combines Vue and Django, I encountered a persistent error message when running the code: "Failed to load resource: the server responded with a status of 500 (Internal Server Error) 127.0.0.1:8000/api/v1/products/winter/yel ...

Python can be used to compare columns from two unsorted files and produce a specific output

I need assistance comparing two large pipe delimited files with data. The primary key is located in one of the columns. For example: one.dat 123|NY|AA|500 569|NY|A|450 777|OK|B|250 899|OK|C|100 two.dat 569|NY|A+|500 777|OK|A|350 899|OK|B|150 The desi ...

Encountering a problem when trying to launch Anaconda Navigator

Just today, I installed anaconda but encountered an issue with the navigator crashing every time I tried to start it. I even attempted to reinstall it three times, but the same error persisted. The error message I received was as follows: OMimeDatabase: E ...

With Python and WebDriver, the unittest module allows you to run tests without opening a browser

Could you assist me with the following issue? I have identified the problem but have been unable to resolve it. When I run the following code, the browser launches and the test passes: import unittest from selenium import webdriver driver = webdriver.Chro ...

The if statement encountered a TypeError because it cannot iterate over a built-in function or method

I'm trying to determine if a global variable exists or not. def add_users(): global users users = [] while True: if 'STATUS' not in globals: server.listen() client, client_addr = server.accept() print ...

Waiting for elements to be loaded in Selenium and Python: A step-by-step guide

Imagine I am choosing with the following selector: //img[@data-blabla] If I want to wait for 10 elements to be loaded, not just one, how should this be altered? My assumption is to use the index [9] WebDriverWait(browser, 5).until(EC.presence_of_element_l ...

Error with syntax detected in VSCode (launch.json, line 2)

How do I configure my launch.json file to run my Python program from Visual Studio Code? Typically, I go to the folder where my test file is located and run the following command: python main.py test_file.xlsx In this case, my Python script is named main ...

Can I loop through the items in a list and extract sections of the list that contain consecutive identical characters?

I have a unique set of data stored in a list that follows a specific pattern. This information is extracted from a file by reading each line and adding certain lines to the list. When I display the list, the data appears in an organized manner, which is qu ...

Having trouble successfully logging in to a website using Python and Selenium through Chrome

After updating Chrome from Version 83 to Version 89, the following code stopped working and always fails. The failure causes the password field to move to the username location, resulting in it being appended to the username (usernamepassword). from se ...

Retrieve a particular value from a JSON object

I'm currently working with a json file that has a specific structure. It includes an 'edition' and various 'attributes' with trait types and corresponding values. For instance, 'Background': 'Gray', 'Base': 'Guy', 'Body': 'FormalBlack', 'Hand': 'None', 'He ...

Python Selenium, Difficulty encountered with the find_element_by() function

Could someone please help me with this issue? I'm encountering errors with the find_element_by_() commands in my code and have tried reinstalling everything, as well as changing the Python version. Unfortunately, nothing seems to be working. Any suggestion ...

Selenium and TikTok incorporate a cookie consent button

Having an issue with my code where I can't click on the 'Accept Cookies' button on a TikTok page. Each time I run it, I get a Timeoutexception error. from selenium import webdriver import time from selenium.webdriver.chrome.options import Options from sele ...

Learning about Tensorflow's RNN and reaching beyond the final state: accessing all middle states

I'm trying to figure out how to access the cell states in all time steps when using tf.nn.dynamic_rnn for an RNN cell like LSTM. I want to be able to take the hidden states from each time step, average them, and then feed that average into the next layer. ...

Using tensorflow to incorporate batch normalization

I am currently working on implementing a batch normalization layer using tensor-flow. When it comes to running the training step with tf.moments to calculate the mean and variance, everything works smoothly. However, for testing purposes, I want to introd ...

How to halt a pygtk operation

I am currently working on a project that involves creating an application to control the playback of a midi file using pygtk. Here's what I have developed so far: import pygtk pygtk.require('2.0') import gtk import subprocess class Music ...

Python's Smartsheet API: A Guide to Retrieving Response Data from Clients

I'm currently tackling the issue of understanding and planning for rate limits, particularly concerning the get_cell_history method in the Python API. Upon executing the following code snippet, I observe the subsequent response being displayed in my conso ...

Error message states: "An error occurred while attempting to parse the json file

Currently enrolled in the Python Mega Course on Udemy, I'm diligently following the instructions to code all the recommended applications. However, while working on Application 2 - Creating Webmaps with Python and Folium, I encountered the following error: ...

Leveraging the power of sqlite3 alongside the flexibility of k

conn = sqlite3.connect('business_database.db') c = conn.cursor() c.execute("INSERT INTO business VALUES(self.nob_text_input.text, self.post_text_input.text, self.descrip_text_input.text )") conn.commit() conn.close() I am attempting to insert ...

How can Pydantic be used to generate models in a recursive manner?

I am currently working with Pydantic and trying to implement it in the following way: from pydantic import BaseModel class Person(BaseModel): name: str age: int class Employee(BaseModel): person: Person data = { 'name': 'John Doe', 'age': 30 ...

Converting Byte strings to Byte arrays in Node.js using JavaScript

Currently facing a challenge while trying to complete the pythonchallenge using JS and Node. Stuck on challenge 8 where I need to decompress a string using bzip2: BZh91AY&SYAxafx82 x00x00x01x01x80x02xc0x02x00 x00!x9ah3Mx07<]xc9x14 ...

What is the reason behind the lack of granularity in the ruby `require` statement?

Unique example for better understanding In my script file, labeled as c.py, I have defined two classes: Elephant and Giraffe. When working with Python, to utilize the Elephant class from the c.py file, an import statement is used: import c print(Elepha ...

Filmclip - Trim footage with a moving frame (area of focus) shifting from left to right over time

I am currently working on a project that involves creating GIFs from video clips automatically using MoviePy. This library has been instrumental in implementing transformations and trimming of videos to produce GIFs. Within my current project, I have enco ...

Reading and displaying images with Tensorflow

My dataset consists of multiple images in a format similar to Cifar10, stored in a binary file with 96*96*3 bytes per image. The total file size is 138MB and the images are arranged one after another (STL-10 dataset). As I tried to read and verify the con ...

Identifying analogous terms within rasa_nlu

My setup is Rasa NLU with Python 3.6.5 on macOS High Sierra. I got the tutorial working but struggling with synonyms integration. This snippet from my training file, first-model.md: ## intent:select - what is the [max](operator) rating? ## synonym:max - ...

Having difficulty finding the close button in a pop-up window while using the Selenium library with Python

While using chromedriver to open the website mentioned below in my extract_data() function, I encountered a problem with dismissing a pop-up message by clicking the 'x' button. Surprisingly, it seems to click the wrong button instead. What's intriguing is ...

Issue with graphviz software, encountering ExecutableNotFound error

Having trouble installing graphviz in PyCharm on my Windows system. I've already added the graphviz library to my PyCharm project, but I keep getting an error when trying to execute dot.render: graphviz.backend.execute.ExecutableNotFound: failed to execut ...

Fix the exit button functionality in my game featuring turtles

Can someone help me create an exit button within my code? I tried using exit() but encountered issues. If utilizing exit() is not feasible, alternative approaches are also welcome. Kindly provide a detailed explanation of the solution -- thank you in adv ...

What is the best way to perform vectorized calculations on a pandas dataframe, replacing values with the data from the previous row if a certain condition is not satisfied

My current approach involves using a for loop with a conditional statement that triggers a calculation and updates the column in a dataframe when true. However, if the condition is not met, the data from the previous row is carried over to the new row. He ...

Compare the data in one column of the dataframe with the data in

Here is the data frame I am working with: CET MaxTemp MeanTemp MinTemp MaxHumidity MeanHumidity MinHumidity revenue events 0 2016-11-17 11 9 7 100 85 63 385.943800 rain 1 2016-11-18 ...

Implementing an array of functions on an array of elements based on their positions

Imagine the scenario: def x_squared(x): result = x * x return result def twice_x(x): result = 2 * x return result def x_cubed(x): result = x * x * x return result x_values = np.array([1, 2, 3]) functions = np.array([x_squared, t ...

Python phone numbers: finding the exact digits needed for a mobile phone in any given country

How can I utilize the python phonenumbers library to determine the required number of digits for mobile phones in different countries? I have imported the phonenumbers/libphonenumber library. I attempted to retrieve the metadata without success. Then, I ...

Error encountered while transitioning to Kubeflow Pipelines version 2 due to JSON decoder issue

Reference: https://github.com/kubeflow/pipelines/issues/7608 I encountered an issue while transitioning a code file from Kubeflow v1 to Kubeflow v2. The code file runs smoothly on Kubeflow v1, but upon moving it to Kubeflow v2, I received the following er ...

Selenium ceases to function intermittently

I am attempting to extract data from a website that has a total of 9000 pages. However, the extraction process stops after retrieving approximately 1700 pages and then restarts from the beginning and continues for about 1000 more pages. Is there a way to s ...

In Python, the shutil.move function is designed to move directories along with their

So I was coding in Python and encountered a problem that I can't seem to resolve. Here's the code snippet: import shutil import pathlib import os source_folder =(r'C:UsersAcerDesktopNew') destination_folder =(r'C:UsersAcerDesktopNew2') files = o ...

Excessive memory consumption due to wxPython images

My data project involves generating multiple plots with the same name but in different directories. It can be tedious to open each plot individually or to copy them all into one location, rename them, and then view them using a standard image viewer. To s ...

Exploring the contrast in Python Requests package's treatment of data and json parameters

What distinguishes the data from the json parameters in Python's Requests library? The documentation available at this link does not provide a clear answer. Consider this code snippet: import requests import json d = {'a': 1} response = requests.post(url ...

Is there a way to track and monitor all pip commands executed within a specific virtual environment

Is there a convenient method to log all the pip commands performed within a specific virtual environment, along with the details of package versions that were installed, updated, or removed? Alternatively, how can I extract a requirements.txt file from my ...

Adding text to the end of a web address through a submission form

Here is an example of a form: <form method="post"> {% csrf_token %} <input class="search" type="text" name="q" placeholder="Search Engine"> <input type="submit"> I am looking t ...

Dividing Pandas Column Names

I have a unique dataset structure that resembles the following: data = pd.DataFrame([[0,0,0,3,6,5,6,1],[1,1,1,3,4,5,2,0],[2,1,0,3,6,5,6,1],[3,0,0,2,9,4,2,1]], columns=["id", "sex", "split", "group0Low", "group0High", "group1Low", "group1High", "trim"]) g ...

selenium.common.exceptions.InvalidArgumentException: Message: The argument provided is not valid: 'name' must be a string when transitioning between window handles using Selenium

Whenever I try to use the following code snippet: driver.execute_script("window.open('');") driver.switch_to.window(driver.window_handles[1]) driver.get(url) driver.switch_to.window(driver.window_handles[0]) An error is thrown at me. selenium.co ...

Django is successfully loading CSS, but images and javascript files are not found with a 404 error

Currently working on a Django website project where I have successfully created a login page. However, upon testing it on the development server, I noticed that the CSS loads perfectly fine, but the images and JavaScript files are returning a 404 error, ev ...

Notification: The specific HTML element identified as <div id="tabber_obj_0_div_3" class="ptr"> cannot be smoothly brought into view by scrolling

I am currently working on extracting book reviews from a specific URL using web scraping techniques. My goal is to gather the book name and each review in separate rows. Here's the code snippet I have written so far, which utilizes both selenium and bs4 fo ...

Learn how to implement hooks that run before committing changes and others that run before pushing code using pre-commit

Some hooks can take a while to run, and I prefer running them before pushing rather than before each individual commit (pylint being one such example). I've come across the following resources: Inquiry: Using Hooks at Different Stages mesos-commits Email ...