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.

Encountering an issue while attempting to make an API GET request using JSON and Python

Encountering an issue with my API get request using JSON RESTful services and Python3. Any assistance would be greatly appreciated. The API instructions I am following can be found on this website . I have the CVE number already, as it's included in the ...

I require assistance with figuring out how to trigger a scroll up event

I've been struggling to find a solution in Python using Pygame that allows me to detect scrolling up. My goal is to recreate the experience from the popular video "Interstellar Mouse" https://www.youtube.com/watch?v=aANF2OOVX40 I want to trigger the ...

Using a Python loop to find the sum of numbers between two randomly generated values within the range of 1 to

Can someone assist me in creating a loop to generate two random integers between 1-10 and then calculate their sum within the range? import random total_sum = 0 from random import randrange num1 = (randrange(1,11)) num2 = (randrange(1,11)) count = tota ...

Encoding a list of categories as strings for creating Pandas dummies

I am working with a dataframe structured like this: id amenities ... 1 "TV,Internet,Shower,..." ... 2 "TV,Hot tub,Internet,..." ... 3 "Internet,Heating,Shower..." ... ... My goal is to split the string by comm ...

Combine pandas dataframes by matching date intervals and values

I am searching for a way to streamline the process of reconciling bank transactions. In this scenario, there are two tables - one from the bank and one from the system. However, there is a delay of a few days in the transactions recorded in the system tabl ...

How can a unique identifier be defined and effectively utilized for selection purposes?

I'm utilizing Selenium to automate a task on a website, and I'm facing a challenge in selecting an item using the following: select = driver.find_element_by_*whatever* Unfortunately, the available whatevers like find_element_by_id, by name, by tag name, ...

What are the steps to display a graph on a webpage using AJAX in Django?

I'm currently working on developing a weather forecast application, and I have implemented a date input box on the home page. When users enter a date and click submit, a graph displaying temperature data should be displayed. I have set up a URL that retu ...

Capturing a full-page screenshot using Selenium's Marionette with Python

Following the recent update of Firefox to version 47, we found it necessary to add the Marionette extension in order to continue using Selenium Webdriver. In my case, I also had to upgrade from Selenium 2.52 to 2.53. I rely on the Python version of Seleni ...

Steps for changing the boolean value inside a nested function

I am struggling with a problem related to toggling the boolean value. I want to achieve this toggle within another function. Consider the following code snippet: def printChange(): isChange = [True] change(isChange) print(isChange) def change( ...

Output the highest odd integer

My objective is to print the largest odd number until the user inputs 0. However, during testing I encountered an issue where the code returns 3 instead of 5, which should be the correct result. Can anyone offer assistance in resolving this problem? See b ...

"Encountering an unresolved import issue in PyDev when trying

Currently, I am using PyDev in Eclipse 4.2 on Mountain Lion operating system. I have successfully installed the SciPy Superpack and can access all related packages like Scikit-learn and MatPlotLib via Python interpreter and IPython. However, when attemptin ...

Discovering the closest point between two lists in Python through the utilization of machine learning techniques

I am faced with a challenge in Python where I have two lists of values and need to calculate the shortest distance between each pair of points from the first list. list1 = [(10,15),(40,50),(10,60)] list2 = [(12,17),(38,48),(12,63),(11,17),(10,59)] My tas ...

Reorganize the layout of a Python dictionary with the help of recursion

I am working with a dictionary that contains data for "Land" and "Air": { "Land": { "2018": { "VALUE:Avg": 49.0, "VALUE:Sum": 49.0 }, "2008": { ...

Converting a JSON file embedded in pandas python to a CSV format

Hey there! I recently received a JSON file with the following format. Can you guide me on how to parse this JSON file and convert it into CSV? JSON File Format {'Sections': [{'MC': [[{'IsMandatory': False, 'LD': None, 'propNameValuepair': [{' ...

Struggling to showcase information from a JSON file within an embed on a webpage

I am struggling to display the data from my JSON file in an embed. I need assistance with finding a solution for this issue. Here is the content of the JSON file: { "Slims Mod Bot": { "Felix\u2122": 2, "Dus ...

dividing binary numbers by 2 and 8

My task is to determine if certain binary numbers are divisible by 2 or 8 and then report the total count. If the last digit of a binary number is 0, it's divisible by 2, and if the last three digits are all 0, it's divisible by 8. twos = 0 eigh ...

Encountering difficulties with submitting a drupal menu add form through Selenium

My quest to create a new menu in Drupal (8 URL: <site url>/admin/structure/menu/add) using the Python Selenium Chrome Webdriver has hit a roadblock - every time I attempt to submit the form, nothing seems to happen. I've explored various methods of ...

Using Selenium with Python, ensure that after clicking a button, the program waits for all newly loaded elements, regardless of their attributes, to fully load

Is there a way to wait for all newly appearing elements on the screen to fully load after clicking a particular button? While I understand that the presence_of_elements_located function can be used to wait for specific elements, how can I ensure that all ...

Python Selenium: Accelerate Your Character Speed

Is there a way to slow down the typing speed of my send key while inputting characters? I am struggling to control how quickly it types. I attempted using the Sleep method, but that was not effective. A('Initiating browser startup...') e=l() e.ad ...

Error: The 'PullRequest' object does not contain the 'issue_comments' attribute

I have been utilizing the https://github.com/sigmavirus24/github3.py library for my project. However, I am encountering an issue when trying to fetch issue_comments from PR. for pr in repo.iter_pulls(): for comment in pr.issue_comments(): pri ...

Using Python and Selenium to automate searches in the Facebook search bar

My usual method of using selenium to login to Facebook has hit a snag. I am attempting to input keywords into the search bar and retrieve the results, but it seems the new version of the search bar has thrown me off my game. Previously, I could locate th ...

Locate the text of an element that is not visible on the screen while the code is running

Currently, I am diving into the world of web scraping using Selenium. To get some practical experience, I decided to extract promotions from this specific site: https://i.stack.imgur.com/zKEDM.jpg This is the code I have been working on: from selenium im ...

Developing a personalized address field in Django Model

What is the standard method for storing postal addresses in Django models? Are there any specialized libraries available that offer custom model fields with built-in validation and formatting for postal address data? If no libraries are found, how can I c ...

A function designed to retrieve all nearby values within a list

After spending quite some time trying to tackle the problem at hand, I find myself stuck. I am dealing with a list of various values, such as: list1 = (17208, 17206, 17203, 17207, 17727, 750, 900, 905) I am looking to create a function that can identify a ...

Scrapy is adept at gathering visible content that may appear intermittently

Currently, I am extracting information from zappos.com, specifically targeting the section on the product details page that showcases what other customers who viewed the same item have also looked at. One of the item listings I am focusing on is found her ...

Generate a personalized report for the Behave Python framework, requiring retrieval of both the Scenario Name and its corresponding status

Looking to generate a personalized report for the Behave and Python framework. The goal is to retrieve the Scenario Name and status. Any suggestions on how to accomplish this? Curious if there is an event listener class available in the behave framework t ...

Looking to retrieve information from a dataframe in a specific row

Here is the data that I currently have: Year Month 2003 06 2003 09 I need to extract this data in the following format: (('2003', '06'),('2003','09')) ...

The error returned by Pandas value_counts depends on the data type of the series

What is the reason behind the key error at 0 in the first DataFrame? import pandas as pd t1 = pd.DataFrame({'c1':[1,2,2,1]}) t1.c1.value_counts()[0] # key error: 0 t2 = pd.DataFrame({'c1':['a','b','b','a']}) t2.c1.value_counts()[0] # prints 2 Cre ...

When using retrbinary() and storbinary() in ftplib, will an exception be raised if the transfer is not successful?

Are exceptions raised by the retrbinary() and storbinary() functions in the ftplib module when a transfer is unsuccessful, or do I need to explicitly check for this? For example, I currently have code that... ftp = ftplib.FTP(<all the connection info&g ...

"Access Denied": PyCharm's Struggle with Setting Up an Anaconda Environment

Even after granting PyCharm root permissions, I am still experiencing a "permission denied" error message when trying to create a Conda environment. This issue has persisted despite my initial success in setting up the environment. ...

Designing a Chess Program with Object-Oriented Principles

I've been working on my chess program and I have a class called Move, which keeps track of where a piece was moved from and to. It also stores information about the pieces involved in the move. However, I'm facing an issue where I have to pass the entire ...

Determining if two numpy arrays are equivalent element-wise when containing floating point values

How can I determine if two numpy arrays are equivalent? Code: import numpy as np def numpy_equal(): x = np.array([2, 3, 1, 0.000000000000001000000000000000000000002]) y = np.array([2, 3, 1, 0.000000000000001000000000000000000000001]) #assert ...

Binding multicast in Python's Twisted framework to a specific interface

Despite my extensive search efforts on Google, I have yet to find a definitive answer to the following question: after loosely following this guide: I am still wondering how one can bind a twisted Multicast listener to ONLY the multicast address and on sp ...

Retrieve the include and runtime library directories using Python

Suppose I need to utilize gcc through the command line to compile a Python C extension. The call would follow this structure: gcc -o applesauce.pyd -I C:/Python35/include -L C:/Python35/libs -l python35 applesauce.c I've observed that the -I, -L, an ...

Using Python 2.4 to deliver a notification to Pidgin

I am looking to send notifications to users via their pidgin internet messenger using python 2.4 in my application. Could someone provide guidance on how this task can be accomplished? ...

Unable to retrieve the keyboard key from the variable

I am currently working on a program that is designed to automatically press keyboard keys, but I am facing some issues. The program seems to have trouble understanding the key value obtained from Tkinter Entry. When attempting to use pynput to press the k ...

Getting the h1 text from a div class using scrapy or selenium

I am working with Python using Scrapy and Selenium. My goal is to extract the text from the h1 tag that is within a div class. For instance: <div class = "example"> <h1> This is an example </h1> </div> Here is my implementat ...

arrange the dataframe df using several criteria

Here is a dataframe displayed below: df: product_x year total_price total_sale A 2016 50 200 B 2016 200 100 A 2017 250 250 B ...

Python running a memory shortage during an Sqlite operation

Whenever I execute my code, which involves extracting numerous data from a sqlite database, I encounter this particular error in my python script! (<type 'exceptions.MemoryError'>, 'main.py', 427) Instead of simply displaying M ...

"Encountering HTTP 400 Bad Request Error When Using Flask and Ajax for Post Requests

I'm currently developing a small Flask-based website and I want to use Ajax to send data from the client to the server. So far, I've only used Ajax requests to fetch data from the server, but this time I want to submit data via a POST request. On the Flas ...

What is the process for generating an executable .zip file using distutils?

Python 2.6 onwards has a unique feature that allows the direct execution of a .zip file containing a __main__.py file at the top of the archive. I am interested in utilizing this feature to provide preview versions of my tool without requiring users to ins ...

What is the best method for sorting through data entries using only designated time parameters?

I have collected data that looks like this: Out[504]:df time1 temp1 temp2 dcity1 dcity2 s 0 00:20:00 7 7 1 1 1.000000 1 00:20:00 7 7 1 1 1.000000 2 00 ...

Can you retrieve the initialization parameters of a Python class?

For instance, if I were to create an instance of a class like this example = SomeClass(a=10, b=20) Is there a way to retrieve a dictionary containing the initialization parameters and their values from example? So essentially, get_init_params_and_values(e ...

Update the file associated with the reference

Is there a way to replace an outdated file with a new one in a reference using the referenceEdit command without any specific flags for file replacement? One possible solution could be something like this: cmds.referenceQuery( myReference, e=1, file=NEW ...

Is there a software available that allows for files to be treated as tables within a database system?

Looking for a way to treat csv files as database tables without having to manually transform them? It would be great to have a command line option similar to how grep, head, tail, sort, and awk are used. For instance, the ability to select a specific colu ...

Error in Python caused by mathematical domain limits

This particular program is designed to work effectively when the variable "n" is set to 4, as demonstrated in the code snippet below: from __future__ import division from numpy import zeros import numpy as np import matplotlib.pyplot as plt from numpy.li ...

Implementing Ajax in Django to dynamically show the current time every second

Can anyone provide a straightforward example of how to showcase the current time on a page within a django project? I've done some searching and found the following code (which doesn't update unless I manually refresh the page): Below is my urls ...

Capturing a series of values and storing them in a separate column using Python

I am dealing with a column ID that consists of either 10 numbers or 7 numbers. My goal is to create a new column that only includes the last 3 digits if the Column ID has a length of 10, and if it has a length of 7, then I want to keep the entire number. D ...

Numpy: Executing in-place operations on a dynamic axis

After much consideration, I have tried my best to outline the issue in the title. The problem at hand is the variability of a numpy array's shape or dimension (which can range from 1 to 3). For instance, in the scenario where the array is of shape [100], ...

Is there a way to create a plot with repeating x-axis values without relying on x-values provided in the dataset?

Although there are already answered questions about plotting in Python where x-axis values appear more than once, with the difference being that my data points are not equidistant. I want to plot over a fixed x-axis range that is not strictly related to th ...

Using timedelta to filter data when a field may be missing

I'm attempting to develop a function within the PlayerAt table to retrieve records from a PlayerOc table based on a filter that utilizes the timedelta feature. Below is an abbreviated version of the class: class PlayerAt(Base): id_ = sa.Column(sa ...

Optimal method for extracting PyTables table with column names stored as variable names

I have a piece of code that fulfills my requirements, but it takes more than 10 seconds to run on a table with 200 variables and 64000 rows. Is there a faster way to create a variable namespace that matches the column names? strExec = "a = table[:]" for ...

A method for pinpointing the subset of numbers that shares the least amount of elements within a group of equivalent numbers

Suppose I have a dataset that is much larger, containing lists of 4 numbers selected from the range 0 to 9: (1,2,3,4) (3,5,6,0) (4,5,7,9) (1,2,7,8) If I want to identify the list(s) of numbers with the fewest matches against this collection, is there ...

Finding the "send item" button in Outlook Office with the help of Chromedriver

Hey there, I'm having some trouble clicking on the "New Group" option in the office365 menu using chromedriver with selenium. Unfortunately, when I try to run the script I created, it doesn't seem to be working as expected. Here is a screenshot s ...

Organize logging messages on a per-second basis for better readability

Developed a logger responsible for logging certain canbus values to a file in seconds-based timestamps. A sample of the log is as follows: Timestamp, Can ID, data, datalength 07-Nov-22 13:40:41, 418385469, a00f325bffffffff, 8 07-Nov-22 13:40:41, 217056317, ...

Can you explain the significance of the values 1.0/255 and the color (0,0,0) in this code snippet?

I'm curious about the significance of using values like 1.0 / 255 and (0, 0, 0) in this context. Can someone elaborate on their purpose? inpBlob = cv2.dnn.blobFromImage(frame, 1.0 / 255, (inWidth, inHeight), (0, 0, 0), swapRB=False, crop=False) ...

Decrease the index's level

After running a pivot table, I have the result below indicating the customer grades that visited my stores. Using the 'droplevel' method, I managed to flatten the column header into one layer. Now, I am looking to do the same for the index - removing 'Grad ...

Shifting items in a pandas dataframe column below the nth item: A step-by-step guide

My program processes the output of an OCR scan of a table and generates a dataframe. However, sometimes the rows get merged, resulting in compressed cells that include content intended for the cell below, thus shortening the column. I need to change this c ...

Encountering issues when using a proxy with Selenium Webdriver in Python

After experimenting with a Selenium Python script for web scraping, I encountered an issue once my IP was detected. To overcome this, I decided to explore using a proxy server. I attempted two different methods to implement this. First approach: PROXY = & ...

Steps for interacting with a button of the <input> tag in Selenium using Python

As I attempt to complete a form submission, I encounter an issue where clicking the submit button does not produce any action. It seems that the problem lies with the button being tagged as <input>: <input type="submit" name="submit ...

Extract reviews and ratings from IMDB by utilizing Selenium

I am in the process of extracting reviews and rating data for specific movies on IMDB. Below is the snippet of code I am using to scrape the rating: try: rating = review.find_element_by_css_selector('[class = "rating-other-user-rating"]') ...

Executing a JavaScript code in a Python webdriver: A step-by-step guide

Using Selenium 2 Python webdriver: I encountered an issue where I needed to click on a hidden element due to a hover effect. In search of solutions to unhide and select the element, I came across the following examples: Example in Java: JavascriptExecut ...

Adding a large number of plots to Bokeh in bulk

Is there a way to speed up the process of adding 10,000 lines to a bokeh plot which are based on two points for each line? Doing this one by one is very slow, sometimes taking up to an hour. import pandas as pd import numpy as np from bokeh.plotting impor ...

Exploring the Possibilities of Basemap Objects in a Three-Dimensional

When working with Basemap in a 3D environment, functions like ax.add_collection3d(m.drawcoastlines(linewidth=0.25)) function properly, however functions involving fill such as ax.add_collection3d(m.drawmapboundary(fill_color='blue')) don't s ...

Guide to saving a Python docx file on the client side with the help of Ajax

I am currently using Python 3.6 with Django, and my code snippet is shown below: from docx import Document document = Document() document.add_heading('My docx', 0) document.save('myFile.docx') return HttpResponse(document, content_type='application/vnd') ...

The performance of the Python 2.7 DDos Script leaves much to be desired due

Currently, I am experimenting with creating a DDos Script for educational purposes. However, I have encountered a setback as it is operating at a slower pace and utilizing only around 0.8Mb of my upload speed out of the available 20Mb. UPDATE 3 To addres ...

Error: Trying to access an index of an integer data type in Python is not allowed

I am currently working on a project to create a simple program that selects a random website and then counts the elements within that website. However, I have encountered an error: Traceback (most recent call last): File "element_counter.py", line 23, ...

Transforming Dictionary Data in JSON DataFrame into Individual Columns Using PySpark

I have a JSON file with a dictionary that resembles the following: "object1":{"status1":388.646233,"status2":118.580561,"status3":263.673222,"status4":456.432483} I want to extract status1, status2, status ...

Changing dictionary rows into individual columns in pandas dataframes

I am working with a dataframe that has two columns. One of these columns contains dictionaries with multiple keys and values. My goal is to expand these dictionary keys into separate columns using pandas. Is there a way to achieve this? In [1]:print df Ou ...

The Django annotate function does not support accessing a floatfield within a model

I am attempting to add annotations to a queryset with the distances between each object and a location provided by the user. This is what I have implemented so far: lat1 = request.POST['lat'] lon1 = request.POST['lon'] locations = Location.objects.annota ...

Streamline the OAuth process for Dropbox API by automating the login with just a click of a button

Currently, I am facing an issue with logging into Dropbox using the official Dropbox API in order to upload a file. The problem lies in the code not clicking on the submit button for login authentication. Rather than producing an error, the code simply han ...

SQLFORM that does not include a submit button

Currently working with the web2py framework, I am faced with a challenge in creating a SQLFORM without a submit button. The issue arises from having multiple forms on the page, some of which share common fields, making it impossible to use SQLFORM.factor ...

Starting Firefox with a specific profile in Selenium Python using geckodriver can be accomplished by specifying the path

Below is the code snippet: profile = webdriver.FirefoxProfile('C:\Users\Administrator\AppData\Roaming\Mozilla\Firefox\Profiles\kvycjolb.Prdel') driver = webdriver.Firefox(profile) Despite not receiving any errors and Firefox launching successfull ...

Converting a flattened column of type series or list to a dataframe

I am looking to extract specific data from my initial dataset which is structured as shown below: time info bis as go 01:20 {'direction': 'north', abc {'a':12,'b':20 } yes ...

The art of handling exceptions in Django and delivering personalized error messages

In contemplating appropriate exception handling for my Django app, I am focused on ensuring the utmost user-friendliness. User-friendliness in this context means providing detailed explanations to users when errors occur. As mentioned in a helpful post, ...