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.

Is it possible to customize the text in a label by tracking mouse movements in Python using Tkinter?

I am having trouble updating my label based on the position of the mouse. Currently, it only works once when I run the code. How can I make sure the label updates every time my mouse changes position? The following code snippet is what I have so far, but i ...

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 ...

TimeoutException thrown by Selenium script during web scraping of Indeed platform

My current project involves creating a script to scrape job listings on Indeed, extracting information such as title, company, location, and job description. The script successfully retrieves data from the first five pages, but encounters an issue with o ...

Validating two unique JSON responses using JSONSchema

Two JSON responses have been successfully validated against a defined schema using the jsonschema library. The responses have different field names but still pass validation. Below is the specified schema query_schema = { "type": "object", "prope ...

Converting dictionary to string in Python

Looking to retrieve data in a specific format, I have the existing code but need assistance modifying it to return data as a string on a single line. Code: def getBasicPlayers(self): # Completed """Returns a list containing a dictionary for each ...

Scraping Secrets: Unraveling the Art of Procuring User Links

I need assistance with extracting links from the group members' page on Meetup: response.css('.text--ellipsisOneLine::attr(href)').getall() Can you please help me understand why this code is not functioning correctly? This is the HTML structure I am work ...

Model preservation on Tensorflow 2.7.0 incorporating data augmentation feature

I encountered an issue while attempting to save a model with data augmentation layers using TensorFlow version 2.7.0. Below is the code snippet for the data augmentation: input_shape_rgb = (img_height, img_width, 3) data_augmentation_rgb = tf.keras.Sequen ...

What is pyautogui's reasoning behind incorporating its own key delay in the write() function?

I have a code snippet for sending keys via pyautogui: pyautogui.write(df["description"].iloc[0]) The HTML element df["description"].iloc[0] is fetched from a CSV file and looks like this: <div class="post-body entry-con ...

An error is triggered, resulting in a TypeError being raised

I have a question regarding try-except statements that is different from the other questions mentioned. I am not in need of a finally statement... Consider the following code snippet: try: #dosomething except TypeError: #dosomething -> THIS RE ...

Utilizing Pylons to Enable Cross-Library Sharing of MySQL Connections with SQLAlchemy

Currently, my setup involves running Pylons with SQLAlchemy to connect to MySQL. In order to utilize a database connection in a controller, I typically do the following: from myapp.model.meta import Session class SomeController(BaseController): def i ...

Guide on linking AngularJS user interface with Python server via RESTful API?

Can someone please explain the process of connecting two parts? Specifically, I am using Angular CLI for the front-end and Python for the logic. My goal is to send text responses from the front-end to my Python back-end and receive a response in return. ...

Tensorflow 2.13.0 Error: Module Not Found - Unable to Locate 'tensorflow.keras'

Encountered the mentioned issue while coding in Spyder using Anaconda. It seems to have occurred when opening a new file in an environment where I had already created and saved a tf Keras model, and then trying to fetch it in that new file. Despite attemp ...

Implementing Conditional Statements in Date-picker with Selenium WebDriver using Python

As a newcomer to Python/Selenium, I am attempting to construct a statement that will execute an alternative action when the specified element cannot be located. Below is the code snippet in question. pickActiveDay = driver.find_element_by_xpath('//di ...

Understanding the impact of Django CASCADE on post_delete operations

The code snippet below outlines the structure of my model: class A(): foriegn_id1 = models.CharField # ref to a database not managed by django foriegn_id2 = models.CharField class B(): a = models.OneToOneField(A, on_delete=models.CASCADE) I have ...

Tips for creating curved corners on a polygon using given x and y coordinates

Is there a way to draw a polygon from X, Y coordinates with rounded corners using the points I have? Below is my current code, but I am open to suggestions if there is another library that may work better. Displayed below is my output image generated by ...

Advanced function - Python

I have a coding assignment that requires me to write a function using high-order functions (Function 1). I am unsure of the benefits of writing it in this way as opposed to a normal function (Function 2). Can someone please explain to me the advantages o ...

Switching images dynamically using Flask and JavaScript

I'm currently working on Flask and encountering a perplexing issue. I'm attempting to update an image using JavaScript, but I am getting these errors from Flask: ... 12:05:34] "GET / HTTP/1.1" 200 - ... 12:05:38] "GET /img/pictur ...

What is the best way to delay until text is visible within an element?

Could I potentially delay action until the appearance of an element, as indicated by the text within the STRONG section below? The content in question consistently changes based on specific triggers. <div class="alert message alert-success alert-da ...

Utilizing Python requests for retrieving dynamic website data

Currently, I am utilizing Python (BeautifulSoup) to extract data from various websites. However, there are instances where accessing search results can be challenging. For example: import requests from bs4 import BeautifulSoup url1 = 'https://auto.ria.co ...

Ways to extract a specific line of text from HTML code

Can someone help me extract a specific line from an HTML code using Python? For instance, in this website: The snippet of code is as follows: var episodes = [[8,54514],[7,54485],[6,54456],[5,54430],[4,54400],[3,54367],[2,54327],[1,54271]]; I am lookin ...

Discovering the data types of various dictionary values within a JSON file can become a bit tricky when dealing with null values

I am working with a large set of dictionaries from a JSON file, each containing the same keys but different values that can be of multiple types, including null. I need to determine the type of each value so that I can initialize the appropriate variables ...

Is there a way to perform a bulk apply or replace operation on multiple columns in pandas?

The following code snippet is functional: df['Forecast'] = df['Forecast'].apply(lambda x: '0' if x == '' else x) df['Yield'] = df['Yield'].apply(lambda x: '0' if x == '' else x) However, when attempting to combine them together, an issue arises to_chan ...

Having trouble sending an array from Flask to a JavaScript function

As a newcomer to web development and JavaScript, I'm struggling to pass an array from a Flask function into a JavaScript function. Here's what my JS function looks like: function up(deptcity) { console.log('hi'); $.aja ...

Is there a way to overlay TextItems above candlestick charts in pyqtgraph?

My goal is to visualize candlesticks with TextItems displaying every price level for each candle. I took inspiration from the 'custom graphics' example and made modifications to the CandlestickItem method as shown below: class CandlestickItem(pg.Graphics ...

Issue encountered: Jupyter Notebook Import Error - unable to import attribute 'np_version_under1p17' from 'pandas.compat.numpy'

import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import matplotlib.dates as md import datetime as dt import time from zipfile import ZipFile from matplotlib.pyplot import xticks %matplotlib inline ------------ ...

I am struggling to comprehend the einsum calculation

As I attempt to migrate code from Python to R, I must admit that my knowledge of Python is far less compared to R. I am facing a challenge while trying to understand a complex einsum command in order to translate it. Referring back to an answer in a previ ...

Displaying the contents of every file within the given directory

I'm facing a challenge where I need to access a directory and display the content of all files within it. for fn in os.listdir('Z:/HAR_File_Generator/HARS/job_search'): print(fn) Although this code successfully prints out the names of the files, my g ...

Is there a way to extract the text that is displayed when I hover over a specific element?

When I hover over a product on the e-commerce webpage (), the color name is displayed. I was able to determine the new line in the HTML code that appears when hovering, but I'm unsure how to extract the text ('NAVY'). <div class="ui top left popu ...

Discover the method to obtain a decoded string containing the character "" using the base64 module

Struggling to correctly format the path using the base64 module, my desired output should resemble: C:UsersUser_NameDocumentsphotosphoto.png In a previous attempt, I checked the variable image_open and saw the slashes. However, after decoding and ...

What is the method for executing a key press event in Safari?

selenium 3.0.2 safari 10 (using built in safari driver) python 2.7.10 OSX 10.11.16(El Capitan) How can I repeat key press events (Right/Left/Up/Down) multiple times using send_keys(Keys.Right) to move focus with repetitive key press actions? For ex ...

Utilizing Highcharts/Highstock for handling large volumes of data efficiently

Dealing with a growing amount of data daily (currently over 200k MySQL rows in one week), the chart loading speed has become quite slow. It seems like using async loading is the solution (). I attempted to implement it but encountered some issues. Currentl ...

How can we use Python and Selenium to retrieve the text from HTML that includes the <p> tag?

I have a simple question that I hope you can help me with. I'm not feeling well and struggling to complete my presentation because my brain just isn't functioning properly. Here is the HTML code in question: <p> <b>Postal code:</b> ...

arranging a list in python in alphabetical order based on one criterion

I have a list named lsNearCities: def calcDistance(self): try: for lyr in QgsMapLayerRegistry.instance().mapLayers().values(): if lyr.name() == "us_cities": layer = lyr lsNearCities = [] ...

Selenium, scrolling through web pages

I have been attempting to scroll through a webpage using Selenium at "https://jobsearch.az/vacancies". However, when you open the page and click on a job vacancy, there are two side-by-side pages that need to be scrolled. The challenge is to scroll the one ...

Experimenting with Flask redirects using Python unittests

I am currently working on writing unit tests for my Flask application. Within several of my view functions, like the login function shown below, I perform a redirect to a different page: @user.route('/login', methods=['GET', 'POST']) def login(): .... ...

Using Selenium for web scraping, certain instances involve scanning data, while others may not have this capability

Currently, I am developing a Python script utilizing the Selenium library to scrape hotel information from the e-dreams platform. The main purpose of this script is to gather specific data such as the title and current price, organize them into lists, and ...

How can I adjust the spacing between subplots in Matplotlib to prevent titles and x-axis labels from overlapping?

Dealing with multiple rows of subplots in matplotlib can lead to issues where the xlabels of one row overlap with the title of the next. Adjusting pl.subplots_adjust(hspace) becomes necessary but it can be quite annoying. Is there a way to set hspace that ...

For some odd reason, my stack is missing the "top" attribute

import random value = { "Two":2,"Three":3, "Four":4, "Five":5, "Six":6, "Seven":7, "Eight":8, "Nine":9, "Ten":10, "Jack":10, "Queen&qu ...

Warning: Scipy curve_fit encountered a runtime overflow issue while calculating the exponential function

I have been attempting to fit a function with two independent variables a and k to an exponential curve using scipy's curve_fit. The function is defined, and I have tried calculating it as follows: print(np.min(x_data)) 1 print(np.max(x_data)) 44098 p ...

Using Selenium to retrieve a compilation of all URLs within a closed issue page on GitHub

I am attempting to save the links of all the resolved issues from a GitHub project (https://github.com/mlpack/mlpack/issues?q=is%3Aissue+is%3Aclosed) using Selenium. The code snippet I am using is: repo_closed_url = [link.find_element(By.CLASS_NAME,'h ...

How does Word2vec perform its operations on analogies?

Based on information found at https://code.google.com/archive/p/word2vec/: A recent discovery revealed that word vectors are able to capture various linguistic regularities. For instance, performing vector operations like vector('Paris') - ve ...

unleashing the power of Gremlin server with OrientDB

As someone who is new to using the gremlin-server and orientDB on Ubuntu, I am interested in connecting the two. Can anyone provide information on the requirements for establishing this connection? I have already successfully connected the gremlin-server ...

Unable to access image directory on Colab platform

After importing the zip files into the designated directories, I attempted to visualize the images using a random number, but encountered the following error message: Error: OpenCV(4.1.2) /io/opencv/modules/imgproc/src/color.cpp:182: Error: (-215:Assertion ...

As I was developing a Discord bot, I encountered an issue with intents during the process

I encountered an issue while attempting to create a Discord bot using discord.py. When I try to run the bot, I receive an error related to intents. Traceback (most recent call last): File "main.py", line 4, in <module> client = commands.Bo ...

Which model is ideal for predicting sales outcomes?

I am currently exploring ways to predict company sales using LSTM. However, I have come across examples that only utilize two variables - time and sales. I believe that this may not be sufficient for accurate forecasting. Upon further research, I discovere ...

What is the best method for extracting a JSON datetime string in Python?

When making a call from Python to a remote API, the returned data is in JSON format. To parse this data, I use the json module with json.loads(). The issue I am facing pertains to dates - the system I am calling returns the date formatted as follows: /Dat ...

Is there a flaw in the Django migrations build_graph function?

Upon running my tests after squashing migrations, an error report is generated: lib/python2.7/site-packages/django/db/migrations/loader.py:220: KeyError The source code causing the issue is as follows: def build_graph(self): """ Builds a mig ...

I am looking to transform intricate json data into csv format with the help of either python or R programming

Converting values to rows in CSV and keys to columns in CSV format would be beneficial. { "_id": { "$uId”: “12345678” }, “comopany_productId”: “J00354”, “`company_product name`”: “BIKE 12345”, "search_resu ...

Is it possible to reuse a WebDriverWait instance?

When working with a page object that interacts with various elements on the DOM, is it better to create a single instance of WebDriverWait on initialization and use it for all waits? Or should separate instances be created for each element being waited on? ...

Using Selenium to stream audio directly from the web browser

For my current project, I am utilizing Selenium with Python. I have been exploring the possibility of recording or live streaming audio that is playing in the browser. My goal is to use Selenium to retrieve the audio and send it to my Python application fo ...

Python code that evaluates two lists and retains only the elements that match or do not match

Searching for matches in two lists of tuples and generating separate lists seems tricky. I attempted a nested loop to compare the tuples, but ended up with incorrect results. The "no match" list contained some tuples that were actually matching. There must ...

Creating visualizations with varying array lengths on a single Pandas plot

a and b represent the datetime indexes for two sets of values, A Values and B Values, respectively. The size of A Values is larger than that of B Values. I am looking to create a code snippet where both sets are plotted on the same graph with numpy arrays ...

What is the process for loading a webpage into another webpage with google app engine?

Hey there, I'm a newbie to app engine and could really use some help, I'm looking to replicate the functionality of the jquery load function on the server side within a RequestHandler's get() method. Currently, I have a page that looks some ...

How can I determine the smallest word value among multiple files using Python?

I have a collection of 1000 .txt files, each containing data that I need to process using the following code. My goal is to identify the largest value associated with ENSG in each file and remove any other occurrences of ENSG with values lower than the hig ...

List of Links to Retrieve

I've asked numerous questions about this particular subject, and I apologize. But this is the final one. Below is the code in question: import urllib import urllib.request from bs4 import BeautifulSoup import sys from collections import defaultdict ...

Can I consolidate identical terms into a single column in a pandas dataframe?

Within this extensive pandas dataframe, there are several terms: type name exp ------------------- feline tiger True feline cat False rodent rabbit True canine dog False feline puma True feline bobcat False Are there ways to consolid ...

Exploring PySpark: uncovering ways to extract all possible combinations of columns

I am dealing with a DataFrame containing various combinations of batches, inputs, and outputs. My goal is to reintegrate their "unique combinations" back into the DataFrame. Here's a simplified snapshot of the data: Batch Output Input 1 A X ... (d ...

Execute the task immediately after receiving the JSON response

Whenever the mobile app requests specific data, I must execute a task. The user may not need the task completed immediately, but within the next 2 minutes. Being relatively new to Python and web development, I am unsure of how to achieve this. I prefer n ...

Separate the numbers preceding a specific character into their own object

Is it possible to extract the numbers before a space and a forward slash from an object that contains digits on both sides of the slash? Here are some examples: 4026 / 1769395 5160 / 1769395 5158 / 1769395 These examples represent different cells in an HT ...

Using Ansible with virtualenv to manage Windows Remote Management (WinRM

I'm currently navigating the world of ansible, winrm, virtualenv, and Jenkins. So far, I've successfully installed Ansible with Tom via epel-release. My configuration for Jenkins is still at a basic level. In my journey, I created a virtualenv named $HOM ...

Empty list retrieved with Python Itertools Combinations

I am attempting to create a list or dataframe containing combinations of [0 , 1] for 14 different positions. Unfortunately, all I am receiving is an empty list and the message: [itertools.combinations at 0x29b294cc0e8] Despite trying multiple solutions ...

Automating dropdown menu selection in Python using Selenium

<select id="PRMT_SV_N0x29a524c0x0x2c68e47c_NS_" class="clsSelectControl pv" aria- multiselectable="false" aria-invalid="false" style="width: 5cm;" xpath="1"> <option value="1" ...

How can I determine the specific quantity of XPATH links with unique identifiers in Selenium?

Seeking automation with Python3 and selenium to streamline searches on a public information site. The process involves entering a person's name, selecting the desired spelling (with or without accents), navigating through a list of lawsuits, and accessing ...

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 specific Python error is triggered by the message 'OSError: [Errno 98] Address already in use'?

I'm currently developing a simple Python TCP socket server. I am looking to handle a certain exception mentioned earlier in my code. Can anyone provide guidance on what should be placed after except in order to achieve this? ...

What could be causing my sjoin() function to produce an empty GeoDataFrame?

I'm currently working on a spatial join operation between two GeoDataFrames. The first GeoDataFrame contains the coordinates of points associated with specific names. The second GeoDataFrame consists of polygons derived from the French cadastre data. My ...

An error occurred while trying to insert JSON data into SQLite using Python

I am currently working on a project where I need to store raw JSON strings in a sqlite database using the sqlite3 module in Python. Here is what I have attempted: rows = [["a", "<json value>"]....["n", "<json_value>"]] cursor.executemany("""I ...

Utilizing Python with Selenium for Web Scraping

https://i.stack.imgur.com/klhCL.png I need to retrieve numbers like 14,401. I have attempted the following code: WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[@id='wiz-iframe-intent']"))) WebDriverWait(drive ...

Discover the number of nested child elements within an element using Beautiful Soup

One thing that I am struggling with is determining the number of "levels" of child elements an element contains. Take, for instance: <div id="first"> <div id="second"> <div id="third"> <div id="fourth"> <div id="fifth" ...

Batch files in PATH require a .bat extension to be executed in Windows Server 2012, CMD, and Anaconda CMD

My system is running on Windows Server 2012. I recently installed Anaconda on my machines, and it has automatically added the necessary paths to the PATH variable: C:\Users\user1\tools\Anaconda3;C:\Users\user1\tools&bso ...

Error encountered when attempting to send text to an element inside an iframe: NoSuchElementException in Selenium

Hello everyone, I am a beginner in Python and recently started exploring Selenium. I have successfully completed small projects for LinkedIn or Twitter following tutorials. Now, I want to create something related to my work in finance. However, I am facing ...

What is the process for utilizing a scikit learn model within a 'model.tar.gz' file in Sagemaker?

Hello everyone, I recently dived into the world of Sagemaker and decided to train a classification model using the "linear-learner" through the Sagemaker API. To my surprise, it generated a "model.tar.gz" file in my s3 path. After doing some research, I r ...

Unlocking the synergy between Python and React through the seamless integration of component-based

I am attempting to containerize the workflow of an isomorphic app using Docker. This is the Dockerfile I used: FROM python:3.5-slim RUN apt-get update && apt-get -y install gcc mono-mcs && apt-get -y install vim && ...

Having trouble interacting with Bootstrap dropdown using Selenium in Python

I have a dropdown menu on my frontend that has the following structure: <div class="dropdown-menu dropdown-menu-right text-left" id="dropdown_menu"> <a class="dropdown-item" data-toggle="modal" ...

Pass a list item as a parameter to execute a function in Python

I need to execute a series of functions, each taking an item from a list as a parameter. Func1 will take the first list value, Func2 the second list value...and so forth. My current setup looks like this: main.py #import the 5 python files import s ...