Questions tagged [loops]

Loops are like dance routines in the world of programming, where a set of commands gracefully executes itself over and over again until a specific condition decides it's time to stop.

Utilizing the <br> tag effectively in a React map function loop

I am currently working on a project in ReactJS where I need to loop through an Array of objects using the map function. I want to separate each object on a new line by using the tag, but placing it at the end of the loop is not working for me. Can som ...

Navigating through filenames using Python

With a collection of 200 JSON files in Python named "1.json", "2.json", "3.json" and so on, I set out to apply modifications using a loop. Unable to achieve the desired result using "for i in range(1, 200):", I decided to pursue an alternative method. my ...

Looping endlessly, causing the page to freeze and preventing it from loading. Time to take

I am in the process of setting up a Bitcoin payment gateway for transactions worth 0.25 BTC with just 1 confirmation required. I have designed a form (form.html) that generates a unique random address ($_POST['address']). Upon submission, I want ...

Exploring the transformation from binary to base 48 representations

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

"Mastering the art of traversing through request.body and making necessary updates on an object

As I was reviewing a MERN tutorial, specifically focusing on the "update" route, I came across some interesting code snippets. todoRoutes.route('/update/:id').post(function(req, res) { Todo.findById(req.params.id, function(err, todo) { ...

Encountering a TimeoutException while trying to scrape a blank Webelement with Python Selenium

I am currently working on a web scraping project to extract the names of Pet shops along with their addresses by iterating through different country states and cities. My goal is to export this data into an Excel file. However, I encountered a TimeoutExcep ...

Loop through lists, tuples, and dictionaries within each other

My question pertains to the topic of iterating over nested lists and dictionaries. I am looking for additional functionality beyond what is discussed in this link. In my case, the iterable element now includes tuples that contain integers which need to be ...

Navigating through elements in Angular

I am working with multiple Angular components housed within a display:flex div container. I am fetching datatable from an API, and it contains the same number of rows as there are components. Each row in the datatable corresponds to data for each compone ...

Eliminate redundant information from loop in PHP

Can anyone assist me in resolving this issue? I am attempting to display 3 text fields containing the following values: 100 200 300 However, my current output is showing duplicates: 100,200,300 100,200,300 100,200,300 I have tried using the arra ...

Looping through mysql data horizontally within a div tag

Looking for assistance to create a content loop similar to the one on this website? I attempted to use a while() loop, but it ended up displaying vertically without using a table. I suspect this page utilizes thumbnails. What I aim for is to have the it ...

Built-in Handlebars helper for nested iteration - no results displayed

I'm currently facing an issue with using an iteration helper within another one. Strangely, the inner helper isn't producing any output. Here's a snippet of the handlebars template I'm working with: {{#people}} <h4>{{firstNa ...

Tips for executing a jQuery function on multiple sets of elements

Currently, I have a list with all items sharing the same class name. There is a jQuery plugin that identifies the tallest element and sets the height of all list items to match the tallest one. My goal is to run this method for each UL group individually. ...

Loop within PHP code that executes specific operations, such as a matching engine for orders

I am currently working on creating a simulated asset exchange platform using PHP. Let's consider the orderbook for a specific asset, XYZ: | buy_price | amount | sell_price | amount | |-----------|--------|------------|--------| | 99.3 | 100 | 99. ...

Guide to iterating within a loop with a variable number of iterations above or below the specified amount in JavaScript

I am currently engaged in a project for a small theater group, and I am facing challenges with getting this loop to execute properly. <% include ../partials/header %> <div class="jumbotron jumbotron-fluid"> <div class="container"> ...

List using letters instead of numerals

Can Python provide a method similar to enumerate() but with letters instead of numbers? For instance x = ['block', 'cheese'] for letter, word in enumerate(x): print((letter, word)) This code would result in ('A', ' ...

What is the best way to iterate through an array of objects in a react component?

I need help figuring out how to iterate through the array of objects in my React code. Currently, I am using getStaticProps() to fetch data from a mock API server online. My project is built with nextjs. How can I achieve this using loops like for or whi ...

What is the best way to program a function that can extract random lines from a text file and save them in a variable?

Can someone enlighten me on how to create a function that reads from a txt file and saves random lines into a variable? This function needs to be executed multiple times within a foreach loop, and the language used is PHP. I'm still new to coding, so ...

The var statement in the for loop is not functioning properly

I am in the process of developing a converter that changes binary numbers into decimal equivalents. To ensure accuracy and prevent errors, I want to validate user input by restricting it to only consist of zeroes and ones. Here is my current implementation ...

How come the index variable doesn't show the index in *ngFor loop in Angular 2?

When working with ng-repeat in Angular 1 to display the index, this code is used: <div ng-repeat="car in cars"> <ul> <li>Index: {{$index+1}}</li> <li>Car Name:{{car.name}}</li> </ul> </div> However, w ...

Iterating over a dataframe to generate additional columns while preventing fragmentation alerts

Currently, I have an extended version of this coding to iterate through a large dataset and generate new columns: categories = ['All Industries, All firms', 'All Industries, Large firms'] for category in categories: sa[category + ', OP mar ...

What's the most efficient way to iterate through this Array and display its contents in HTML?

I'm struggling to sort a simple array and I think the issue might be related to the time format. I'm not sure how to reference it or how I can properly sort the time in this array format for future sorting. //function defined to input values function ...

What is the best way to iterate through an array, execute computations on the elements, and visualize the outcomes graphically?

As a beginner in programming, I am seeking help with my program. I am attempting to read arrays using a for loop, perform calculations on them, and display the results on a 3D graph. However, I encountered an error: IndexError: index 753 is out of bounds ...

What is the best way to eliminate a list from a list of lists when its elements are either non-numeric or exceed a certain value?

I have a project that requires me to cleanse a nested list in Python. The criteria are to remove any sub-list that contains a non-numeric item or an item greater than 20, and then add the removed sub-lists to a separate list. While my current code success ...

Encounter an error when reading a stream with a maximum timeout value set

I have encountered a challenge while trying to read and process large CSV files. Due to a rate limit in processing, I need to introduce a 1-minute delay between each request. Initially, I attempted to use set timeout, but discovered that there is a limitat ...

Determining the optimal times to utilize traditional loops instead of array helpers

After writing in Javascript for some time, I've become quite comfortable with using array helpers. However, there have been moments where traditional for loops seem more practical and easier to work with compared to array helpers. Can you provide me with ...

Exploring the process of transforming a JSON array into separate JSON objects using Node.js

I am struggling with converting a JSON array to multiple JSON objects in Node.js. I've attempted using loops but have been unsuccessful. I'm seeking assistance to send the data as separate objects, not an array. router.get('/frontpage-mobil ...

Executing asynchronous JavaScript calls within a loop

I've encountered an issue with asynchronous calls in JavaScript where the function is receiving unexpected values. Take a look at the following pseudo code: i=0; while(i<10){ var obj= {something, i}; getcontent(obj); / ...

"Performing a series of getJSON requests with a delay between each call, iterating through an array

Could someone shed light on why my jQuery/JavaScript code runs with an unexpected flurry of ajax calls instead of at a steady 1-per-second rhythm? var i = 0, l = data.length; function geocode() { $.getJSON( 'https://maps.googleapis.com/maps/api ...

Using ES6 to Compare and Remove Duplicates in an Array of Objects in JavaScript

I am facing a challenge with two arrays: Array One [ { name: 'apple', color: 'red' }, { name: 'banana', color: 'yellow' }, { name: 'orange', color: 'orange' } ] Array Two [ { name: &apos ...

Accessing array values depending on DOM response

Generate a string from selected DOM elements I have an object that contains months and their corresponding index numbers (not dates) monthList = {"jan" : "1", "feb" : "2". etc: etc} The user can input values like jan or jan,feb,march and I need to return ...

I am eager to investigate why this method suddenly stops looping after processing the second record

I need to create a button that loops through all records and performs a method that generates a list of ranges between two fields. Then, it should remove another record from the list and place the value in the result field. I have implemented the code bel ...

What could be causing my for loop to not function properly within the ngOnInit lifecycle hook?

I am attempting to create a nested loop structure in order to access an array that is inside an object within an array of objects, and then store this data into a new array. My issue arises as the first loop executes successfully but the second one does no ...

What is the process of incorporating HTML into a jQuery program in order to immerse the world in an element?

I am looking to utilize HTML with the value in a checkbox, After adding a shortcode: <label class="HCheck">(this is val 1 )</label> and incorporating jQuery to change it to: <label class="HCheck">(this is val 1 ) ...

Can someone guide me on how to extract checkbox values in a post method using Angular

I'm facing an issue with a table that contains a list of rules. Whenever the checkboxes are clicked, I want them to send a "true" value to an API endpoint. However, I keep receiving an error stating that the "associated_rule" is undefined. After trying to ...

Developing a Web Application using CodeIgniter and PHP, harnessing the power of two MySQL tables

There are three different tables in my database: an "item" table, a "note" table, and a "note image" table. Whenever a user looks at the details of an item, all the notes associated with that item (identified by the item_id field in the note table) are re ...

A PHP guide on iterating through statement results to populate an associative array

I am struggling to find the correct syntax to iterate through my results and populate them into an associative array. Currently, it only retrieves the first result and does not continue looping through the rest of the data. I have attempted various combina ...

Keep looping for printing screenshots

Looking for some assistance. I have a Python script that loads URLs and takes screenshots. Here's what I'm trying to accomplish: Instead of using an array, read URLs from a text file Take individual screenshots of each loaded URL and save them ...

Nested loops seem to override previous results with the final output

I am attempting to iterate through an array of months nested within an array of 'years' in order to calculate a count for each month using a custom angular filter. Initially, I set up the structure I will be looping through in the first while loo ...

The For loop with varying lengths that exclusively produces small numbers

I'm currently using a for loop that iterates a random number of times: for(var i = 0; i<Math.floor(Math.random()*100); i++){ var num = i } This method seems to be skewed towards producing lower numbers. After running it multiple times, the &apo ...

Exploring DataFrames with interrows() and writing them out as CSV files with .to_csv:

I am using the following script to perform the following actions: Apply a function to a column in each row of a DataFrame Write the returns from that function into two new columns of a DataFrame Continuously write the DataFrame into a *.csv I am interes ...

Infinite loop triggered by jQuery dropdown menu on page resize was causing an issue

I have been working on developing a navigation menu for a website that displays as a horizontal bar on larger screens, but transforms into a jQuery dropdown menu when the window width is less than 980px. During initial page load with a window width below ...

There seems to be a glitch in my JavaScript for loop as it is not iterating for the correct amount that it should

It seems like my for loop is not always iterating 7 times as intended. Sometimes it runs with 5 iterations, other times with 4 or 3. This is the JavaScript code I am using: var start = new Date().getTime(); var end = new Date().getTime(); function timeT ...

Create a loop in Vue.js 3 without the need for a query

Can someone help me understand how to fetch data using a loop in Vue.js version 3 when working with queries? I am trying to retrieve an object based on its id, which is obtained from the URL. However, I seem to be facing some difficulties. Any guidance wou ...

Tips for converting the 'numericals' in the input provided by the user into the initial point of a loop

I am in the process of developing a program to analyze the game Baccarat, and while I have a good grasp of the basics, I require assistance in enabling users to paste multiple games at once. Below is an example: games = input('Enter the games you wish to ...

What is the best way to execute the two specified functions in Python for a total of 5 repetitions

To achieve my goal, I want to create a program that repeats two defined tasks 5 times. Here is what I aim to accomplish: - The program will enable each player to roll two 6-sided dice. - It will calculate and display the points earned by each player in ev ...

PHP Code to iterate over a range of time

Currently, I have a function that generates a list of options in a select input. These options represent times with 5-minute intervals. However, there is an issue when the time reaches values like 23:45, as the options start from 00:10 and continue looping ...

Saving JSON data within a List

Currently, I am working on scraping a series of websites with similar formats such as www.website1.com, www.website2.com, www.website3.com, and so on. In order to extract JSON data from each website, I have implemented a code snippet that includes a "time ...

Utilize jQuery to manipulate a subset of an array, resulting in the creation of a new array through the use of

I have a string formatted like this: ItemName1:Rate1:Tax1_ItemName2:Rate2:Tax2:_ItemName3:Rate3:Tax3_ItemName4:Rate4:Tax4 (and so on, up to item 25). My task is to take an index provided by the user (for example, 2), retrieve the item at that index when ...

Executing a series of functions in succession using jQuery

I am trying to iterate through an object that contains functions which need to execute consecutively. Ideally, I would like these functions to be chained together in a way where one function waits for the previous one to finish before executing (e.g., func ...

Difficulty encountered in manipulating the reader object within the python csv library

I'm currently working towards the goal of extracting specific data from a large CSV file. My approach involves using a main menu to handle data acquisition and a separate menu for continuing or exiting the process. However, I encounter an issue when atte ...

I'm puzzled as to why, but my code seems to be causing an issue with the command prompt, possibly due

Recently, I've been taking on the challenges of Advent of Code. Day 2 has me stumped, as there's a peculiar issue with the code when running it through node.js in the command prompt: const fs = require("fs"); var valid = fs.readFileSync("inpu ...

Why is this loop in jQuery executing twice?

$(document).bind("ready", function(){ // Looping through each "construct" tag $('construct').each( alert('running'); function () { // Extracting data var jC2_events = $(this).html().spl ...

Iterate over the keys and values in a JSON object while simultaneously replacing any specified values in Golang

Is it possible to iterate through all the keys and values of a JSON object in Golang, identify a specific value based on a match with either the key or value, replace that value, and then create a new data structure with the updated value? I came across a ...

Exploring promises with loops and patience?

I created a function that accesses an API and retrieves an array containing 100 objects at once. The getPageData() function works as expected when passing an integer without the loop. However, when attempting to iterate through it, I am not getting any res ...

PHP code isn't showing any posts

Context: I have implemented a PHP loop to generate a dynamic feed of my portfolio posts on my WordPress website. Issue: The first five posts are being displayed correctly, but the subsequent posts are not. I'm uncertain about the underlying cause and woul ...

One way to iterate through the numbers 1 to 100 using React state would be to create a state

Is there a way to transition my react application's state from 1 to 100? Here is the current structure: this.state = { items: [ {id:1, name:'User 1', age:27}, {id:2, name:'User 2', age:30}, ...

Is there a way to properly assign an index to a multidimensional array in a Vue.js template?

My setup involves utilizing Vue along with a multidimensional array structured like this: myArray = [[1,2,3],[1,2,3],[1,2,3]] To achieve the desired HTML layout shown below (ensuring that data-item counter increments correctly): <div class="row" data ...

What is the equivalent of PHP's continue X in C#?

When using PHP: The 'continue' function has an optional numeric parameter that specifies how many levels of enclosing loops it should skip to the end of. For example: for ($i = 1; $i <= $countArray - 2; $i++) { for ($j = $i+1; $j <= ...

Pandas in an endless loop?

How can I identify and resolve a potential infinite loop in my code? This is the code snippet in question: new_exit_date, new_exit_price = [] , [] high_price_series = df_prices.High['GTT'] entry_date = df_entry.loc['GTT','entry_date'] window_price_series ...

Unable to locate the error while iterating through a list of dates

I'm currently developing a program to detect the number of Sundays that fall on the first day of a month between two specified dates. My goal is to achieve this without relying on datetime functions. Interestingly, my calculations yield 173 when t ...

How can I effectively iterate through an array in PHP while considering an offset?

array( (int) 0 => '3', (int) 1 => '5', (int) 2 => '9', (int) 3 => '14', (int) 4 => '16', (int) 5 => '17', (int) 6 => '18', (int) 7 => '19', (int) 8 => '20', (int) 9 => '23', (int) 10 => '24', (int) 11 => '25', (int) 12 = ...

PHP: running into memory constraints when looping through large numbers of items

Currently working on a WordPress project that involves Woocommerce. My task is to iterate through an array containing over 200,000 items. Each item represents an order ID in the database. The goal is to calculate the total sum by adding up the values of e ...

Best practices for updating nested properties in Angular objects

I have a dataset that includes information about fruit prices for different years: { "fruits": [ { "name": "apple", "prices": [ { "2015": 2, "2014": 3, ...

Executing multiple loops of MySQL queries using PHP

There are two tables that are crucial for a trivia quiz game at this stage: scores and quiz. I have implemented multiple nested PHP and MySQL loops to achieve the desired results. However, I am seeking a more streamlined approach with potentially fewer dat ...

Is there a way to sum/subtract an integer column by Business Days from a datetime column?

Here is a sample of my data frame: ID Number of Days Off First Day Off A01 3 16/03/2021 B01 10 24/03/2021 C02 3 31/03/2021 D03 2 02/04/2021 I am looking for a way to calculate the "First Day Back from Time Off" column. I attempted to use it ...

Assistance needed: For each loop not iterating properly following variable explosion

I'm struggling to display a row from a database that contains a list of skills as an array delimited by commas. I have provided fully annotated code with an explanation below of what I have done so far. Any help would be greatly appreciated. Thank you ...

In Python, use a loop to assign different values to various index positions within a list

In my current project, I am working with a variety of data types including Lists, float values, and a NumPy array. dt = list(range(1, 12)) c = 18 limit = 2.75 Energy = np.zeros(len(dt)) My goal is to assign the value c = 18 in the NumPy array Energy. ...

Analyzing the values of various keys within a dictionary for comparison

My data structure involves dictionaries nested inside a list, represented as follows: sample_dict = [{1: [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]]}, ...

Dealing with iterations and merging data in PHP

I am working with a table that looks like this: author_id author_state author_name 1 CA Hello 2 MI World 3 CA How 4 MI Are I would like to know how I can ...

Try repeating the Ajax request until it is successful

Is there a way to continuously repeat an Ajax request until it returns 1, and stop if it returns 0? while(1){ $.ajax({ type: "POST", url: '/admin/importdata/', data: $info, dataType: "json", success: function($result) { ...

Traversing JSON data structures regardless of missing keys

Here is a JSON containing some data: { "results":[ { "name":"Sydney Showboats", "photos":[ { "photo_reference":"Pic062" } ] }, ...

Iterating through object using jQuery

I'm facing an issue with iterating through a JSON object for the first time. The JSON is structured like this: { "response": { "2012-01-01": { "Available": 99, "Variations": [ { "ID" ...

Animating child elements using a loop in jQuery

Greetings everyone! I have a small array of floated divs that I would like to highlight one by one in sequence. Essentially, I am aiming to demonstrate a workflow process using jQuery and I would like it to: Select the first child of the parent div (#ge ...

What is the best way to iterate through this array in ajax?

Is there a way to properly read this array using ajax? I need some assistance understanding the server response: Array ( [success] => 1 [0] => Array ( [0] => Mr Green [FirstName] => Mr Green ...

Tips for efficiently webscraping multiple pages with Beautiful Soup

I have been running my web-scraping script for quite some time, but it seems to be stuck on scraping only one URL. I intend to scrape five different URLs, and I am wondering if the issue lies with my loop getting stuck in an infinite loop. Furthermore, I ...