Nigel  Uys

Nigel Uys

1669353310

How to Identify and Fix JavaScript infinite Loop

How to detect and prevent JavaScript infinite loop

An infinite loop is a condition where a piece of your JavaScript code runs forever caused by a fault in your code that prevents the loop from getting terminated.

An infinite loop is dangerous because it can crash the environment where you run the code (browser or NodeJS server) or freeze your computer, causing it to stop responding.

The for and while statements are the common cause of an infinite loop, so this tutorial will help you learn how to detect and fix the infinite loop caused by the statements.

Let’s start with fixing the infinite loop in a for statement.

Fixing infinite loop in a for statement

A for statement can cause an infinite loop when you mistakenly put an assignment operator instead of a comparison operator in the second expression (the condition expression)

Here’s an example of a for statement that will cause an infinite loop. Notice how the second expression is i = 10:

for (let i = 0; i = 10; i++) {
  console.log("Infinite loop");
}

The for statement requires the second expression evaluates to false to terminate the loop. In the above example, an assignment operator i = 10 is placed as the condition expression instead of a comparison operator like i < 10 or i > 10.

Because an assignment operator always evaluates to true, the for statement won’t stop printing "Infinite loop" to the console, which can cause your computer to freeze.

To fix the for statement above, you need to replace the second expression with something that the for statement can reach. One example is by using comparison operators (=<, <, >, >=)

// the second expression is replaced with <
for (let i = 0; i < 10; i++) {
  console.log("Infinite loop");
}

There’s also another version of the same mistake. This time, the first expression and the second expression causes the infinite loop:

for (let i = 5; i > 0; i++) {
  console.log("Infinite loop");
}

As you can see from the code above, the loop will continue as long as the variable i is bigger than 0.

Since the value of i is already bigger than 0 from the initialization, the second expression will always evaluate to true, causing an infinite loop.

To fix the code above, the third expression must decrement the value of i instead of incrementing it:

for (let i = 5; i > 0; i--) {
  console.log("Infinite loop");
}

Another example of a for statement that can cause infinite loop is to omit all three expressions inside the parentheses as follows:

for (;;) {
  console.log("Infinite loop");
}

But the above code can only be written intentionally, so you shouldn’t have it in your project unless you want your computer to crash.

While the for statements you wrote will certainly be more complex than the examples above, you can still use the same principles to find and fix the fault in your statements.

First, you need to make sure that the second expression you put inside your for statement can actually evaluate as false.

If the second expression is already correct, start checking on the first and the third expression. Does the first expression initialize a value that always evaluates to true when the second expression is executed?

Finally, does the third expression correctly increment or decrement the value of the variable initialized in the first expression?

To sum it up: check your second expression first, then check the first and the third expression, in that order.

Next, let’s learn how to fix infinite loop cause by a while statement.

Fixing infinite loop in a while statement

A while statement can cause an infinite loop when the condition expression put inside the parentheses always evaluates to true:

while (true) {
  console.log("Infinite loop");
}

To prevent an infinite loop, the condition expression of the while statement must be able to evaluates to false.

One of the most common mistakes in writing a while statement is to forget modifying the value of the variable used for the condition expression.

Notice how the value of i never changes in the example below:

let i = 0;

while (i < 6) {
  console.log("Infinite loop");
}

You need to increment the value of i inside the while statement body so that the condition expression evaluates to false as the loop is executed:

let i = 0;

while (i < 6) {
  console.log("Infinite loop");
  i++;
}

No matter how complex your while statement is, you need to make sure that the condition expression written inside the parentheses while() can evaluate to false.

If you still can’t find what’s causing the infinite loop, then you can use the console.log() statement to print the value of the variable used by the condition expression:

let i = 0;

while (i < 6) {
  console.log("Infinite loop");
  i++;
  console.log(i);
}

The console log may help you to pinpoint the faulty code line and fix it.

Original article source at: https://sebhastian.com/

#javascript #infinite #loop 

How to Identify and Fix JavaScript infinite Loop
Nigel  Uys

Nigel Uys

1669008363

Best 10 Cool and Awesome Bash Loop Examples

10 Cool and Awesome Bash Loop Examples

In the programming language, there are mainly three types of loops (for, while, and until). All three types of loops are important in different ways. There is not much difference between the while and until loops, but for loop works quite differently from these two. That’s why you can use these loops to create interactive scripts as a bash user.

So learning bash examples can help you improve your skills in creating scripts. So in this tutorial, we will include 10 cool and awesome bash loop examples you can try to enhance your scripting skills.

10 Cool and Awesome Bash Loop Examples

In this section, we will explain various examples and the approaches we have used in the loops.

Seq Command With Loop in Bash

You can use the seq command in the for loop to create the sequence of numbers. For example, you have a bash script “File.sh” that contains the following code:

#!/bin/bash
for A in $(seq 5 2 25)
do
echo "numbers of $A are"
done

You will get the following result after executing the script in the terminal:

./File.sh

 

Rename Files Using Loop

Using a bash script, you can use the for loops to rename multiple files. For example, you have multiple .txt files and want to add the current date with the name. So here is the example script you can use:

#!/bin/bash
for A in $(ls *.txt); do
mv $A (basename $A .txt)_$(date %d%m%).txt
done

 
Now, you can run the script, and it will change the name of all .txt files by adding the current date:

./MyFile.sh 



Similarly, you can change the extensions of a file through a single script. So let’s change the .txt extension into .sh through the following script:

#!/bin/bash
for file in *.txt; do
mv -- "$file" "{file%.txt}.sh"
done

After executing the script in the terminal, you will get the .sh rather than .txt files:

./MyFile.sh


Infinite For Loop in Bash

When no termination condition is defined in the loop, it is called an infinite loop. In this example of a Bash loop, we will look at the infinite for loop in bash. The following infinite for loop is defined by a double semicolon ( ; ; ) and does not contain any initial, action, or termination parts.

The below script will continue until you press Ctrl+C or type “quit” as input. This script will print every number from 10 to 50 that is given as input. Otherwise, it will print “number is out of range.”

#!/bin/bash
#infinite loop
for (( ; ; ))
do
  echo "Enter a number between 10 to 50"
  read n
  if [ $n == "quit" ]
  then
    echo "terminated"
    exit 0
  fi
  if (( $n < 10 || $n > 50 ))
  then
    echo "The number is out of range"
  else
    echo "The number is $n"
  fi
done

We gave 45 and 23 valid inputs on the above script. After that, we print 2 as input which tells in the output that “the number is out of range.” After that, to close the script, we type quit as input. Here you can also press Ctrl+C to quit the infinite loop.


Three Expression Loop in Bash

It is known from the name of the three-expression loop that it comprises three expressions, also called control expressions. The first expression (EXP1) is the initializer, the second expression (EXP2) is the loop test or condition, and the third expression (EXP3) is the counting expression/step. Let us run a three-expression loop in bash:

#!/bin/bash
for  (( n=5; n>=1; n-- ))
do
 echo "Book $n"
done

On running the above script, you will get the following output.

Loop With Multiple Conditions

We have used the until loop with multiple conditions in the following bash loop example. In this script, we took “m” and “n,” two variables whose values ​​are 20 and 10, respectively, and kept the limit of 15. Here we put “m” and “n” conditions together in the loop, in which the loop will run till the value of “m” is less than the limit and “n” is more than the limit.

#!/bin/bash
limit=15
m=20
n=10
until [[ $m -lt $limit || $n -gt $limit ]];
do
echo "If M = $m then N = $n"
((m--))
((n++))
done

You can see that running the above script will run until the values ​​of “m” and “n” come to the same level.

Read File in Bash

In bash, you can read the contents of a file in several ways. In this example of bash loop, we will read the file’s contents through the filename. We can use the following script to read the file in bash:

#!/bin/bash
echo "Content of the entered file is:"
while
read line
do
 echo $line
done <~Documents/Linuxhint.txt

After running the above script, you can read the full content of the entered file.

Writing to a File

You can use the loops in the script to edit a file right from the terminal. For example, if we have a txt file “Example.txt,” and we want to add up some information, then we can use the following script:

If you run the above script, it will ask you to enter the details:


Once you enter the details, please CTRL + D to save the file and CTRL + Z to finish the process successfully.

Break and Continue Statement Loop in Bash

In bash, you can continue your loop statement after the break. The break statement exits the loop and then passes control to the next given statement. Iteration number two begins after the current iteration is skipped with the same continue statement.

#!/bin/bash
num=16
until false
do
 ((num--))
 if [[ $num -eq 13 ]]
 then
  continue
 elif [[ $num -le 4 ]]
 then
  break
 fi
 echo "LinuxHint = $num"
done

In the following bash script, you can see that when the “num” is equal to 13, it skips the rest of the loop body and jumps to the next iteration. Similarly, the loop will break when “num” is less than or equal to 4.


The above script shows that the loop starts at 15, breaks at 13, and continues till 5.

Calculating an Average in Bash

You can calculate the average by running the script in a bash loop. In this, the user can calculate the average of numbers within a defined range. The following script calculates the average of provided input by the user.

#!/bin/bash
marks="0"
AVERAGE="0"
SUM="500"
NUM="5"
while true; do
 echo -n "Enter your marks or press 'q' to abort "; read marks;
 if (("$marks" < "0")) || (("$marks" > "100")); then
  echo "Please enter your marks"
 elif [ "$marks" == "q" ]; then
  echo "average marks are: $AVERAGE%"
  break
 else
  SUM=$[$SUM + $marks]
  NUM=$[$NUM + 1]
  AVERAGE=$[$SUM / $NUM]
 fi
done

If the input is not within the range, a message is printed that “Please enter your marks.” When the user presses “q” after entering all the marks, the script calculates the approximate average of all the numbers entered.

When the above script is run, your output will be something like this.

Read the Command-Line Arguments in Bash

In bash, you can read single command-line arguments using loops. The script prints the formatted argument values. We run command line arguments in bash using a while loop in the following script. Through this, you will print the value passing the argument value valid option with the help of a single command.

#!/bin/bash
while getopts N:F:M: OPT
do
 case "${OPT}"
 in
  N) name=${OPTARG};;
  F) fathername=${OPTARG};;
  M) mothername=${OPTARG};;
  *) echo "Invalid"
    exit 1;;
   esac
done
printf "Name:$name\nFather Name:$fathername\nMother Name:$mothername\n"

Thus, you can print the formatted argument values ​​to the output by running the above script in a bash.

Wrapping Up

So this was the brief information on the 10 cool and awesome bash loop examples you can learn. We have used different types of loops to create the interactive script easily. Moreover, we also explained the basic approaches used in the above examples. If you have in-depth details about the loops in bash, please visit our official website to know more.

Original article source at: https://linuxhint.com/

#bash #loop #examples #awesome 

Best 10 Cool and Awesome Bash Loop Examples
Rupert  Beatty

Rupert Beatty

1667310793

An Easy Way to Use Pull To Refresh and infinite Scrolling in Swift

ESPullToRefresh is an easy-to-use component that give pull-to-refresh and infinite-scrolling implemention for developers. By extension to UIScrollView, you can easily add pull-to-refresh and infinite-scrolling for any subclass of UIScrollView. If you want to customize its UI style, you just need conform the specified protocol.

中文介绍

Requirements

  • Xcode 8 or later
  • iOS 8.0 or later
  • ARC
  • Swift 5.0 or later

Features

  • Support UIScrollView and its subclasses UICollectionView UITableView UITextView
  • Pull-Down to refresh and Pull-Up to load more
  • Support customize your own style(s)

Demo

Download and run the ESPullToRefreshExample project in Xcode to see ESPullToRefresh in action.

Installation

CocoaPods

pod "ESPullToRefresh"

Carthage

github "eggswift/pull-to-refresh"

Manually

git clone https://github.com/eggswift/pull-to-refresh.git
open ESPullToRefresh

Usage

Default style:

example_default.gif

Add ESPullToRefresh to your project

import ESPullToRefresh

Add default pull-to-refresh

self.tableView.es.addPullToRefresh {
    [unowned self] in
    /// Do anything you want...
    /// ...
    /// Stop refresh when your job finished, it will reset refresh footer if completion is true
    self.tableView.es.stopPullToRefresh(completion: true)
    /// Set ignore footer or not
    self.tableView.es.stopPullToRefresh(completion: true, ignoreFooter: false)
}

Add default infinite-scrolling

self.tableView.es.addInfiniteScrolling {
    [unowned self] in
    /// Do anything you want...
    /// ...
    /// If common end
    self.tableView.es.stopLoadingMore()
    /// If no more data
    self.tableView.es.noticeNoMoreData()
}

Customize Style

As effect:

example_meituan.gif

PS: Load effect is from MeiTuan iOS app.

example_wechat.gif

Customize refresh need conform the ESRefreshProtocol and ESRefreshAnimatorProtocol protocol.

Add customize pull-to-refresh

func es.addPullToRefresh(animator animator: protocol<ESRefreshProtocol, ESRefreshAnimatorProtocol>, handler: ESRefreshHandler)

Add customize infinite-scrolling

func es.addInfiniteScrolling(animator animator: protocol<ESRefreshProtocol, ESRefreshAnimatorProtocol>, handler: ESRefreshHandler)

Espried and auto refresh

ESPullToRefresh support for the latest expiration time and the cache refresh time, You need set an refreshIdentifier to your UIScrollView.

scrollView.refreshIdentifier = "Your Identifier" // Set refresh identifier
scrollView.expriedTimeInterval = 20.0 // Set the expiration interval

You can use es.autoPullToRefresh() method, when the time over the last refresh interval expires automatically refreshed.

scrollView.es.autoPullToRefresh()

let expried = scrollView.espried // expired or not

Remove

func es.removeRefreshHeader()
func es.removeRefreshFooter()

Sponsor

You can support the project by checking out our sponsor page. It takes only one click:

git-adThis advert was placed by GitAds

Download Details:

Author: Eggswift
Source Code: https://github.com/eggswift/pull-to-refresh 
License: MIT license

#swift #webview #infinite #collectionview 

An Easy Way to Use Pull To Refresh and infinite Scrolling in Swift
Jack  Shaw

Jack Shaw

1666490640

Pypresence: A Python Library for Dealing with Discord RPC

Pypresence

Pypresence is a Python library for dealing with Discord RPC.

Installation

Use the package manager pip to install Pypresence.

pip install pypresence

Code

Get The Code For RPC Here

Contributing

Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.

Please make sure to update tests as appropriate.

RPC Discord YT#1.py

from pypresence import Presence
import time
start = int(time.time())
client_id = "#yourCLIENTidHere" #enter your client id here 
RPC = Presence(client_id)
RPC.connect()
while True: #infinite loop
    RPC.update(
        large_image = "rebrand-jr", #name of your image in Developer Portal
        large_text = "RV Logo", #Alt Text For Your Logo 
        details = "Chillin' With Code", #Set Details
        state = "Visual Studio Code", #Set State
        start = start,
        buttons = [{"label": "Remiel's Vlog", "url": "https://www.youtube.com/remielvlogsyt"}, {"label": "Discord Server", "url": "https://discord.gg/rgAZT2aCCH"}] #Add Buttons Here
    )
    time.sleep(60)

Download Details:

Author: JaswanthRemiel
Source Code: https://github.com/JaswanthRemiel/Discord-RPC-in-Python

#python 

Pypresence: A Python Library for Dealing with Discord RPC

How to resolve Json Infinite Recursion problem when working with Jackson » grokonez

https://grokonez.com/json/resolve-json-infinite-recursion-problems-working-jackson

How to resolve Json Infinite Recursion problem when working with Jackson

Json Infinite Recursion is one of the most common problems when we serialize Java objects which having Bidirectional-Relationships. So in the tutorial JavaSampleApproach will show you how to smoothly handle the problems with Jackson annotations: @JsonIgnore, @JsonView, {@JsonManagedReference, @JsonBackReference} and @JsonIdentityInfo.

Related articles:

I. Infinite Recursion problem

We create 2 model classes: Company & Product have one-to-many relationship:
  • Company:

public class Company {
	private int id;
    private String name;
    private List products;
	
    public Company(){
    }
    ...
  • Product

public class Product {
	private int id;
    private String name;
    private Company company;
	
    public Product(){
    }

Serialize Java Objects with segment code:

More at:

https://grokonez.com/json/resolve-json-infinite-recursion-problems-working-jackson

How to resolve Json Infinite Recursion problem when working with Jackson

#springboot #json #infinite #jackson

How to resolve Json Infinite Recursion problem when working with Jackson » grokonez