code-rag-bench/online-tutorials huggingface dataset:
Count words in a sentence in Python program

In this article, we will learn about the solution to the problem statement given below.
Problem statement − We are given a string we need to count the number of words in the string
Split function breaks the string into a list iterable with space as a delimiter. if the split() function is used without specifying the delimiter space is allocated as a default delimiter.
 Live Demo
test_string = "Tutorials point is a learning platform"
#original string
print ("The original string is : " + test_string)
# using split() function
res = len(test_string.split())
# total no of words
print ("The number of words in string are : " + str(res))
The original string is : Tutorials point is a learning platform
The number of words in string are : 6
Here findall() function is used to count the number of words in the sentence available in a regex module.
 Live Demo
import re
test_string = "Tutorials point is a learning platform"
# original string
print ("The original string is : " + test_string)
# using regex (findall()) function
res = len(re.findall(r'\w+', test_string))
# total no of words
print ("The number of words in string are : " + str(res))
The original string is: Tutorials point is a learning platform The number of words in string is: 6
Here we first check all the words in the given sentence and add them using the sum() function.
 Live Demo
import string
test_string = "Tutorials point is a learning platform"
# printing original string
print ("The original string is: " + test_string)
# using sum() + strip() + split() function
res = sum([i.strip(string.punctuation).isalpha() for i in
test_string.split()])
# no of words
print ("The number of words in string are : " + str(res))
The original string is : Tutorials point is a learning platform
The number of words in string are : 6
All the variables are declared in the local scope and their references are seen in the figure above.
In this article, we have learned how to count the number of words in the sentence.
ByteArrayOutputStream size() method in Java with Examples - GeeksforGeeks

28 May, 2020
The size() method of ByteArrayOutputStream class in Java is used to obtain the current size of the buffer. This buffer is accumulated inside the ByteArrayOutputStream. This method returns the size of the current buffer as an integer type.
Syntax:
public int size()

Parameters: This method does not accept any parameter.
Return value: This method returns the size of the current buffer as an integer.
Exceptions: This method does not throw any exception.
Below programs illustrate size() method in ByteArrayOutputStream class in IO package:
Program 1:
// Java program to illustrate// ByteArrayOutputStream size() method  import java.io.*;  public class GFG {    public static void main(String[] args)        throws Exception    {          // Create byteArrayOutputStream        ByteArrayOutputStream byteArrayOutStr            = new ByteArrayOutputStream();          // Create byte array        byte[] buf = { 71, 69, 69, 75, 83 };          for (byte b : buf) {            // Write byte            // to byteArrayOutputStream            byteArrayOutStr.write(b);              // Print the byteArrayOutputStream            // as String and size as integer            System.out.println(                byteArrayOutStr.toString() + " "                + byteArrayOutStr.size());        }    }}
G 1
GE 2
GEE 3
GEEK 4
GEEKS 5

Program 2:
// Java program to illustrate// ByteArrayOutputStream size() method  import java.io.*;  public class GFG {    public static void main(String[] args)        throws Exception    {          // Create byteArrayOutputStream        ByteArrayOutputStream byteArrayOutStr            = new ByteArrayOutputStream();          // Create byte array        byte[] buf = { 71, 69, 69, 75, 83,                       70, 79, 82, 71, 69,                       69, 75, 83 };          for (byte b : buf) {            // Write byte            // to byteArrayOutputStream            byteArrayOutStr.write(b);              // Convert byteArrayOutputStream            // into String            String s                = byteArrayOutStr.toString();              int buffsize                = byteArrayOutStr.size();              // Print string and size            System.out.println(                s + " " + buffsize);        }    }}
G 1
GE 2
GEE 3
GEEK 4
GEEKS 5
GEEKSF 6
GEEKSFO 7
GEEKSFOR 8
GEEKSFORG 9
GEEKSFORGE 10
GEEKSFORGEE 11
GEEKSFORGEEK 12
GEEKSFORGEEKS 13

References:https://docs.oracle.com/javase/10/docs/api/java/io/ByteArrayOutputStream.html#size()
Java-Functions
Java-IO package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Exceptions in Java
Constructors in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Generics in Java
Introduction to Java
Comparator Interface in Java with Examples
PriorityQueue in Java
How to remove an element from ArrayList in Java?
Difference between Static variables and Register variables in C - GeeksforGeeks

04 Jan, 2021
static variables
Static variables have a property of preserving their value even after they are out of their scope! Hence, static variables preserve their previous value in their previous scope and are not initialized again in the new scope. 
Syntax: 
static data_type var_name = var_value;
register variables
Registers are faster than memory to access, so the variables which are most frequently used in a C program can be put in registers using register keyword. The keyword register hints to compiler that a given variable can be put in a register. It’s compiler’s choice to put it in a register or not. Generally, compilers themselves do optimizations and put the variables in the register. 
Syntax:  
register data_type var_name = var_value;
Differences between static variables and register variables in C. 
 
anandagrawal1
C-Variable Declaration and Scope
C Language
Difference Between
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
rand() and srand() in C/C++
fork() in C
Command line arguments in C/C++
Function Pointer in C
Substring in C++
Difference between BFS and DFS
Class method vs Static method in Python
Differences between TCP and UDP
Difference between var, let and const keywords in JavaScript
Difference between Process and Thread
Julia end Keyword | Marking end of blocks in Julia - GeeksforGeeks

26 Mar, 2020
Keywords in Julia are reserved words that have a pre-defined meaning to the compiler. These keywords can’t be used as a variable name.
'end' keyword in Julia is used to mark the end of a block of statements. This block can be of any type like struct, loop, conditional statement, module, etc.
Syntax:
block_type block_name
    Statement
    Statement
end

Example:
# Julia program to illustrate# the use of 'end' keyword  # Defining a functionfunction fn()          # Defining for-loop    for i in 1:5              # Using if-else block        if i % 2 == 0            println(i, " is even");        else            println(i, " is odd");                      # Marking end of if-else        end              # Marking end of for-loop    end      # Marking end of function    end   # Function callfn()
Output:
1 is odd
2 is even
3 is odd
4 is even
5 is odd

Note: 'end' can also be used to mark the last index in a 1D array.
Example:
# Julia program to illustrate# the use of 'end' keyword  # Defining ArrayArray1 = Array([1, 2, 3, 4, 5])  # Printing last element using 'end' keywordprintln("Last element of Array: ", Array1[end])
Output:
Last element of Array: 5

Julia-keywords
Julia
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Searching in Array for a given element in Julia
Get array dimensions and size of a dimension in Julia - size() Method
Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder)
Get number of elements of array in Julia - length() Method
Find maximum element along with its index in Julia - findmax() Method
Getting the maximum value from a list in Julia - max() Method
Exception handling in Julia
Getting the absolute value of a number in Julia - abs() Method
Reverse array elements in Julia - reverse(), reverse!() and reverseind() Methods
Working with Date and Time in Julia
Python Program for Counting Sort - GeeksforGeeks

22 Jan, 2022
Counting sort is a sorting technique based on keys between a specific range. It works by counting the number of objects having distinct key values (kind of hashing). Then doing some arithmetic to calculate the position of each object in the output sequence. 
Python3
# Python program for counting sort # The main function that sort the given string arr[] in# alphabetical orderdef countSort(arr):     # The output character array that will have sorted arr    output = [0 for i in range(256)]     # Create a count array to store count of individual    # characters and initialize count array as 0    count = [0 for i in range(256)]     # For storing the resulting answer since the    # string is immutable    ans = ["" for _ in arr]     # Store count of each character    for i in arr:        count[ord(i)] += 1     # Change count[i] so that count[i] now contains actual    # position of this character in output array    for i in range(256):        count[i] += count[i-1]     # Build the output character array    for i in range(len(arr)):        output[count[ord(arr[i])]-1] = arr[i]        count[ord(arr[i])] -= 1     # Copy the output array to arr, so that arr now    # contains sorted characters    for i in range(len(arr)):        ans[i] = output[i]    return ans # Driver program to test above functionarr = "geeksforgeeks"ans = countSort(arr)print ("Sorted character array is %s"  %("".join(ans))) # This code is contributed by Nikhil Kumar Singh
Output: 
Sorted character array is eeeefggkkorss
Please refer complete article on Counting Sort for more details! 
simmytarika5
amartyaghoshgfg
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Convert string dictionary to dictionary
Python Program for Binary Search (Recursive and Iterative)
Iterate over characters of a string in Python
Python program to add two numbers
Python Program for factorial of a number
Python Program for Bubble Sort
Python | Convert set into a list
Loop through a HashMap using an Iterator in Java

An Iterator can be used to loop through a HashMap. The method hasNext( ) returns true if there are more elements in HashMap and false otherwise. The method next( ) returns the next key element in the HashMap and throws the exception NoSuchElementException if there is no next element.
A program that demonstrates this is given as follows.
 Live Demo
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class Demo {
   public static void main(String[] args) {
      Map student = new HashMap();
      student.put("101", "Harry");
      student.put("102", "Amy");
      student.put("103", "John");
      student.put("104", "Susan");
      student.put("105", "James");
      Iterator i = student.keySet().iterator();
      while (i.hasNext()) {
         String key = (String) i.next();
         System.out.println("\nRoll Number: " + key);
         System.out.println("Name: " + student.get(key));
      }
   }
}
The output of the above program is as follows −
Roll Number: 101
Name: Harry

Roll Number: 102
Name: Amy

Roll Number: 103
Name: John

Roll Number: 104
Name: Susan

Roll Number: 105
Name: James
Now let us understand the above program.
The HashMap is created and HashMap.put() is used to add the entries to the HashMap. Then the HashMap entries i.e. the keys and the values are displayed using an iterator which makes use of the Iterator interface. A code snippet which demonstrates this is as follows
Map student = new HashMap();
student.put("101", "Harry");
student.put("102", "Amy");
student.put("103", "John");
student.put("104", "Susan");
student.put("105", "James");
Iterator i = student.keySet().iterator();
while (i.hasNext()) {
   String key = (String) i.next();
   System.out.println("\nRoll Number: " + key);
   System.out.println("Name: " + student.get(key));
}
How to give Matplolib imshow plot colorbars a label?

To give matplotlib imshow() plot colorbars a label, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Set the figure size and adjust the padding between and around the subplots.
Create 5×5 data points using Numpy.
Create 5×5 data points using Numpy.
Use imshow() method to display the data as an image, i.e., on a 2D regular raster.
Use imshow() method to display the data as an image, i.e., on a 2D regular raster.
Create a colorbar for a ScalarMappable instance, im.
Create a colorbar for a ScalarMappable instance, im.
Set colorbar label using set_label() method.
Set colorbar label using set_label() method.
To display the figure, use show() method.
To display the figure, use show() method.
import numpy as np
from matplotlib import pyplot as plt

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

data = np.random.rand(5, 5)

im = plt.imshow(data, cmap="copper")

cbar = plt.colorbar(im)
cbar.set_label("Colorbar")

plt.show()
Convert.ToChar Method in C#

The Convert.ToChar method is used to convert a specified value to a Unicode integer.
We have declared an sbyte variable.
sbyte byteVal = 200;
Now, use the Convert.ToChar() method to convert the sbyte value to a Unicode integer.
charVal = Convert.ToChar(b);
Let us see another example.
 Live Demo
using System;
public class Demo {
   public static void Main() {
      sbyte[] byteVal = { 92, 111, 115 };
      char charVal;
      foreach (sbyte b in byteVal) {
         charVal = Convert.ToChar(b);
         Console.WriteLine("{0} converted to '{1}'", b, charVal);
      }
   }
}
92 converted to '\'
111 converted to 'o'
115 converted to 's'
How to Install Pytorch on MacOS? - GeeksforGeeks

08 Sep, 2021
PyTorch is an open-source machine learning library based on the Torch library, used for applications such as computer vision and natural language processing, primarily developed by Facebook’s AI Research lab. It is free and open-source software released under the Modified BSD license.
Python
Python-pip or Anaconda-conda should be installed.
Step 1: Check if python3 is already installed by entering the following command in the command prompt.
python3 --version
If this command runs successfully, and we are able to get a Python version 3.9+ then we are good to go or else install python3 by referring to this article here.
Step 2: Check if pip3 is already installed by entering the following command in the command prompt.
pip3 --version
If this command runs successfully, and we are able to get a pip version then we are good to go or else install pip by referring to this article here.
Step 3: Enter the following command to install the latest stable release of Pytorch.
1. Compute Platform: CPU
pip3 install torch torchvision torchaudio
Step 4: Check if Pytorch is successfully installed by entering the following command in the command prompt.
pip3 show torch
If this command runs successfully, and we are able to get a torch version then we are good to go or else reinstall it.
Step 1: Activate Anaconda prompt if it is deactivated.
conda activate
Step 2: Check if conda is installed by entering the following command in Anaconda Prompt.
conda --version
If this command runs successfully, and we are able to get a conda version then we are good to go or else install Anaconda on MacOS.
Step 3: Enter the following commands to install the latest stable release of Pytorch.
1. Compute Platform : CPU
conda install pytorch torchvision torchaudio -c pytorch
Step 4: Check if Pytorch is successfully installed by entering the following command in Anaconda prompt.
conda list -f pytorch
If this command runs successfully, and we are able to get a torch version then we are good to go or else reinstall it.
RajuKumar19
how-to-install
Picked
Python-PyTorch
How To
Installation Guide
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install FFmpeg on Windows?
How to Set Git Username and Password in GitBash?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Install Jupyter Notebook on MacOS?
How to Create and Setup Spring Boot Project in Eclipse IDE?
Installation of Node.js on Linux
How to Install FFmpeg on Windows?
How to Install Pygame on Windows ?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Install Jupyter Notebook on MacOS?
How to get the current date in Java?

You can get the current date in Java in various ways. Following are some of them −
The no-arg constructor of the java.util.Date class returns the Date object representing the current date and time, using this you can print the current date as shown below −
Live Demo
import java.text.SimpleDateFormat;
import java.text.ParseException;
import java.util.Date;
public class Demo {
   public static void main(String args[])throws ParseException {      
      Date date = new Date();
      SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yy");
       String str = formatter.format(date);
      System.out.print("Current date: "+str);
   }
}
05/11/20
The now() method of the Localdate class returns the Date object representing the current time.
Live Demo
import java.time.LocalDate;
public class CreateDate {
   public static void main(String args[]) {  
      LocalDate date = LocalDate.now();
      System.out.println("Current Date: "+date);
   }
}
Current Date: 2020-11-05
The getInstance() (without arguments) method of the this class returns the Calendar object representing the current date and time, using this you can print the current date value as shown below −
Live Demo
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.text.ParseException;
import java.util.Calendar;
public class Test {
   public static void main(String[] args) throws ParseException{
      DateFormat formatter = new SimpleDateFormat("dd/MM/yy");
      Calendar obj = Calendar.getInstance();
      String str = formatter.format(obj.getTime());
      System.out.println("Current Date: "+str );
   }
}
Current Date: 05/11/20
One of the constructor of the java.sql.Date class accepts a long value representing a date and creates a Date object. Therefore to create a Data object you need to pass the return value of the System.currentTimeMillis() method (returns current epoch value) as a parameter of the java.sql.Date constructor.
Live Demo
public class CreateDate {
   public static void main(String[] args) {
      java.sql.Date date=new java.sql.Date(System.currentTimeMillis());
      System.out.println("Current Date: "+date);
   }
}
Current Date: 2020-11-05
Tryit Editor v3.6 - Show Python

from mymodule import person1
Batch Script - Reading from Files

Reading of files in a Batch Script is done via using the FOR loop command to go through each line which is defined in the file that needs to be read. Since there is a no direct command to read text from a file into a variable, the ‘for’ loop needs to be used to serve this purpose.
Let’s look at an example on how this can be achieved.
@echo off
FOR /F "tokens=* delims=" %%x in (new.txt) DO echo %%x
The delims parameter is used to break up the text in the file into different tokens or words. Each word or token is then stored in the variable x. For each word which is read from the file, an echo is done to print the word to the console output.
If you consider the new.txt file which has been considered in previous examples, you might get the following output when the above program is run.
"This is the directory listing of C:\ Drive"
Volume in drive C is Windows8_OS
Volume Serial Number is E41C-6F43

Directory of C:\

12/22/2015 09:02 PM   <DIR>       01 - Music
06/14/2015 10:31 AM   <DIR>       02 - Videos
09/12/2015 06:23 AM   <DIR>       03 - Pictures
12/17/2015 12:19 AM   <DIR>       04 - Software
12/15/2015 11:06 PM   <DIR>       05 - Studies
12/20/2014 09:09 AM   <DIR>       06 - Future
12/20/2014 09:07 AM   <DIR>       07 - Fitness
09/19/2015 09:56 AM   <DIR>       08 - Tracking
10/19/2015 10:28 PM   <DIR>       09 – Misc

 Print
 Add Notes
 Bookmark this page
How to return the nth record from MySQL query?

To get the nth record from MySQL query, you can use LIMIT. The syntax is as follows −
select *from yourTableName order by yourColumnName limit n,1;
To understand the above syntax, let us create a table. The following is the query to create a table −
mysql> create table NthRecordDemo
   −> (
   −> Id int,
   −> Name varchar(200)
   −> );
Query OK, 0 rows affected (0.92 sec)
Insert some records in the table using the following query −
mysql> insert into NthRecordDemo values(100,'John');
Query OK, 1 row affected (0.09 sec)

mysql> insert into NthRecordDemo values(101,'Bob');
Query OK, 1 row affected (0.14 sec)

mysql> insert into NthRecordDemo values(102,'Carol');
Query OK, 1 row affected (0.22 sec)

mysql> insert into NthRecordDemo values(103,'Smith');
Query OK, 1 row affected (0.18 sec)

mysql> insert into NthRecordDemo values(104,'Johnson');
Query OK, 1 row affected (0.16 sec)

mysql> insert into NthRecordDemo values(105,'Sam');
Query OK, 1 row affected (0.16 sec)

mysql> insert into NthRecordDemo values(106,'David');
Query OK, 1 row affected (0.13 sec)
Display all records from the table with the help of select statement. The query is as follows −
mysql> select *from NthRecordDemo;
The following is the output −
+------+---------+
| Id   | Name    |
+------+---------+
| 100  | John    |
| 101  | Bob     |
| 102  | Carol   |
| 103  | Smith   |
| 104  | Johnson |
| 105  | Sam     |
| 106  | David   |
+------+---------+
7 rows in set (0.00 sec)
Use the following query to get nth record from the table −
mysql> select *from NthRecordDemo order by Id limit 6,1;
The following is the output −
+------+-------+
| Id   | Name  |
+------+-------+
| 106  | David |
+------+-------+
1 row in set (0.00 sec)
Convert English text into the Phonetics using Python - GeeksforGeeks

11 Oct, 2020
In this article, we are going to see how to convert English text into the International Phonetic Alphabet. We are going to use the eng-to-ipa module to convert into phonetic.
Installation: Run this code into your terminal.
pip install eng-to-ipa 


Let’s understands this module step-by-step:
1. Import this module and use convert() method to convert a string into phonetics.
Syntax: eng_to_ipa.convert(str)
Parameter:
str: the text to be converted
Returns: IPA string
Python3
import eng_to_ipa as p    p.convert("Hello Geeks")
Output:
'hɛˈloʊ giks'


2. Using ipa_list() instead of convert() it returns the list of each word as a list of all its possible transcriptions.
Syntax: eng_to_ipa.ipa_list(str)
Parameter:
str: the text to be converted
Return: list of all its possible transcriptions.
Python3
p.ipa_list("Yes i am geeks, How are you")
Output:
[[‘jɛs’], [‘aɪ’], [‘eɪɛm’, ‘æm’], [‘giks,’], [‘haʊ’], [‘ɑr’, ‘ər’], [‘ju’]]
3. The get_rhymes() methods return a list of rhymes for a word or set of words.
Syntax: eng_to_ipa.get_rhymes(str)
Parameter:
str: the text to be rhymed
Returns: list of rhymes for a word or set of words.
Python3
p.get_rhymes("Geeks")
Output:
['antiques',
 'batiks',
 'beeks',
 "belgique's",
 'bespeaks',
 'boutiques',
 'cheeks',
 "creek's",
 'creeks',
 'critiques',
 "deak's",
 'eakes',...
 ......
 ..

python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Python | os.path.join() method
Defaultdict in Python
Selecting rows in pandas DataFrame based on conditions
Python | Get unique values from a list
Create a directory in Python
Python | Pandas dataframe.groupby()
JavaScript Array reverse() Method

Javascript array reverse() method reverses the element of an array. The first array element becomes the last and the last becomes the first.
Its syntax is as follows −
array.reverse();

Returns the reversed single value of the array.
Try the following example.
<html>
   <head>
      <title>JavaScript Array reverse Method</title>
   </head>
   
   <body>   
      <script type = "text/javascript">
         var arr = [0, 1, 2, 3].reverse();
         document.write("Reversed array is : " + arr ); 
      </script>     
   </body>
</html>
Reversed array is : 3,2,1,0 


    25 Lectures 
     2.5 hours 

 Anadi Sharma

    74 Lectures 
     10 hours 

 Lets Kode It

    72 Lectures 
     4.5 hours 

 Frahaan Hussain

    70 Lectures 
     4.5 hours 

 Frahaan Hussain

    46 Lectures 
     6 hours 

 Eduonix Learning Solutions

    88 Lectures 
     14 hours 

 Eduonix Learning Solutions
 Print
 Add Notes
 Bookmark this page
Golang | Deadlock and Default Case in Select Statement - GeeksforGeeks

03 Oct, 2019
In Go language, the select statement is just like a switch statement, but in the select statement, the case statement refers to communication, i.e. sent or receive operation on the channel.
Syntax:
select{

case SendOrReceive1: // Statement
case SendOrReceive2: // Statement
case SendOrReceive3: // Statement
.......
default: // Statement

In this article, we learn how the default case is used to avoid deadlock. But first, we learn what is a deadlock?
Deadlock: When you trying to read or write data from the channel but the channel does not have value. So, it blocks the current execution of the goroutine and passes the control to other goroutines, but if there is no other goroutine is available or other goroutines are sleeping due to this situation program will crash. This phenomenon is known as deadlock. As shown in the below example:
Example:
// Go program to illustrate// how deadlock arisespackage main  // Main functionfunc main() {      // Creating a channel    // Here  deadlock arises because    // no goroutine is writing    // to this channel so, the select     // statement has been blocked forever    c := make(chan int)    select {    case <-c:    }}
Output:
fatal error: all goroutines are asleep - deadlock!

goroutine 1 [chan receive]:
main.main()

To avoid this situation we use a default case in the select statement. Or in other words, when the deadlock arises in the program, then default case of the select statement executed to avoid deadlock. As shown in the below example, we use a default case in the select statement to avoid deadlock.
Example:
// Go program to illustrate how to resolve// the deadlock problem using the default casepackage main  import "fmt"  // Main functionfunc main() {      // Creating a channel    c := make(chan int)    select {    case <-c:    default:        fmt.Println("!.. Default case..!")    }}
Output:
!.. Default case..!
You are also allowed to use default case when the select statement has only nil channel. As shown in the below example, channel c is nil, so default case executed if here default case is not available, then the program will be blocked forever and deadlock arises.
Example:
// Go program to illustrate// the execution of default casepackage main  import "fmt"  // Main functionfunc main() {      // Creating a channel    var c chan int      select {    case x1 := <-c:        fmt.Println("Value: ", x1)    default:        fmt.Println("Default case..!")    }}
Output:
Default case..!
Golang
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Parse JSON in Golang?
Defer Keyword in Golang
Time Durations in Golang
Anonymous function in Go Language
time.Parse() Function in Golang With Examples
How to iterate over an Array using for loop in Golang?
Loops in Go Language
Strings in Golang
Class and Object in Golang
Structures in Golang
Boolean booleanValue() method in Java with examples - GeeksforGeeks

01 Oct, 2018
The booleanValue() method of Boolean Class is a built in method in java which is used to return the primitive boolean value of instance which is used to call the method booleanValue().
Syntax
BooleanObject.booleanValue()
Return Value: It returns a primitive boolean value.
Below are the examples to illustrate booleanValue() method:
Program 1:
class GeeksforGeeks {      // Driver method    public static void main(String[] args)    {          // creating a Boolean object.        Boolean b = new Boolean(true);          // get primitive data type using booleanValue()        boolean value = b.booleanValue();          // Print the result        System.out.println(value);    }}
true

Example 2:
class GeeksforGeeks {      // Driver method    public static void main(String[] args)    {          // creating a Boolean object.        Boolean b = new Boolean(false);          // get primitive data type using booleanValue()        boolean value = b.booleanValue();          // Print the result        System.out.println(value);    }}
false

Java - util package
Java-Functions
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Initialize an ArrayList in Java
HashMap in Java with Examples
Interfaces in Java
How to iterate any Map in Java
ArrayList in Java
Multidimensional Arrays in Java
Stack Class in Java
LinkedList in Java
Overriding in Java
Set in Java
VBA - Split Function

A Split Function returns an array that contains a specific number of values split based on a delimiter.
Split(expression[,delimiter[,count[,compare]]]) 

Expression − A required parameter. The string expression that can contain strings with delimiters.
Expression − A required parameter. The string expression that can contain strings with delimiters.
Delimiter − An optional parameter. The parameter, which is used to convert into arrays based on a delimiter.
Delimiter − An optional parameter. The parameter, which is used to convert into arrays based on a delimiter.
Count − An optional parameter. The number of substrings to be returned, and if specified as -1, then all the substrings are returned.
Count − An optional parameter. The number of substrings to be returned, and if specified as -1, then all the substrings are returned.
Compare − An optional parameter. This parameter specifies which comparison method is to be used.

0 = vbBinaryCompare - Performs a binary comparison
1 = vbTextCompare - Performs a textual comparison


Compare − An optional parameter. This parameter specifies which comparison method is to be used.
0 = vbBinaryCompare - Performs a binary comparison
0 = vbBinaryCompare - Performs a binary comparison
1 = vbTextCompare - Performs a textual comparison
1 = vbTextCompare - Performs a textual comparison
Add a button and add the following function.
Private Sub Constant_demo_Click()
   ' Splitting based on delimiter comma '$'
   Dim a as Variant
   Dim b as Variant
   
   a = Split("Red $ Blue $ Yellow","$")
   b = ubound(a)
   
   For i = 0 to b
      msgbox("The value of array in " & i & " is :"  & a(i))
   Next
End Sub
When you execute the above function, it produces the following output.
The value of array in 0 is :Red 
The value of array in 1 is : Blue 
The value of array in 2 is : Yellow


    101 Lectures 
     6 hours 

 Pavan Lalwani

    41 Lectures 
     3 hours 

 Arnold Higuit

    80 Lectures 
     5.5 hours 

 Prashant Panchal

    25 Lectures 
     2 hours 

 Prashant Panchal

    26 Lectures 
     2 hours 

 Arnold Higuit

    92 Lectures 
     10.5 hours 

 Vijay Kumar Parvatha Reddy
 Print
 Add Notes
 Bookmark this page
Conditional rendering in React.js

Using conditional statements specific components can be rendered and removed . Conditional handling works similarly in JavaScript and React.js
function DisplayUserMessage( props ){
   const user = props.user.type;
   if(type==’Player’){
      return <h1>Player </player>;
   }
   If( type==’Admin’){
      Return <h1>Admin </h1>;
   }
}
If statement is used in above example. Type of user decides which message to return.
Local state of component is useful in deciding the conditional rendering as state is flexible to change inside the component.
function MessageSizeChecker(props) {
   const message = props.message;
   return (
      <div>
         <h1>Hello!</h1>
         {message.length > 100 &&
            <h2>
               Message size is greater than 100
            </h2>
         }
      </div>
   );
}
If the first argument to the && operator evaluates to true then second argument is rendered on the screen.
Inline if else with ternary operator −
Its having a syntax like condition ? ‘ first’ : ‘second’;
function MessageSizeChecker(props) {
   const message = props.message;
   return (
      <div>
         <h1>Hello!</h1>
         {message.length > 100 ? ‘Message size is greater than 100’: ‘Message size is ok’}
      </div>
   );
}
This ternary expression can be used on number of block statement but it becomes tedious to understand . So to keep it simple it should be used on simple conditions.
We can decide which component to render.
render() {
   const isPlayer = this.state.user.isPlayer;
   return (
      <div>
         { isPlayer ? (
            <Player >
            ) : (
            <Admin />
            )
         }
      </div>
   );
}
To prevent the component from rendering , we can return a null as well. But just returning null from render method does not prevent the further applicable lifecycles of React
Replace an element from a Java List using ListIterator

Let us first create a Java List and add elements −
ArrayList < String > list = new ArrayList < String > ();
list.add("Katie");
list.add("Tom");
list.add("Jack");
list.add("Amy");
list.add("Andre");
list.add("Brad");
list.add("Peter");
list.add("Bradley");
Now, use ListIterator and return the next element in the List with next() −
ListIterator<String>iterator = list.listIterator();
iterator.next();
Replace the element in the List with set() method. Here, whatever element is set will get replaced as the first element of the Iterator −
iterator.set("Angelina");
 Live Demo
import java.util.ArrayList;
import java.util.ListIterator;
public class Demo {
   public static void main(String[] args) {
      ArrayList<String>list = new ArrayList<String>();
      list.add("Katie");
      list.add("Tom");
      list.add("Jack");
      list.add("Amy");
      list.add("Andre");
      list.add("Brad");
      list.add("Peter");
      list.add("Bradley");
      System.out.println("Initial list..");
      for (String str: list) {
         System.out.println(str);
      }
      ListIterator<String>iterator = list.listIterator();
      iterator.next();
      iterator.set("Angelina");
      System.out.println("After replacing an element...");
      for (String str: list) {
         System.out.println(str);
      }
   }
}
Initial list..
Katie
Tom
Jack
Amy
Andre
Brad
Peter
Bradley
After replacing an element...
Angelina
Tom
Jack
Amy
Andre
Brad
Peter
Bradley
How to execute a static block without main method in Java?

VM first looks for the main method (at least the latest versions) and then, starts executing the program including static block. Therefore, you cannot execute a static block without main method.
public class Sample {
   static {
      System.out.println("Hello how are you");
   }
}
Since the above program doesn’t have a main method, If you compile and execute it you will get an error message.
C:\Sample>javac StaticBlockExample.java
C:\Sample>java StaticBlockExample
Error: Main method not found in class StaticBlockExample, please define the main method as: public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application

If you want to execute static block you need to have Main method and, static blocks of the class gets executed before main method.
 Live Demo
public class StaticBlockExample {
   static {
      System.out.println("This is static block");
   }
   public static void main(String args[]){
      System.out.println("This is main method");
   }
}
This is static block
This is main method
Redis - String Setex Command

Redis SETEX command is used to set some string value with a specified timeout in Redis key.
Simple string reply. OK, if the value is set in key. Null, if the value is not set.
Following is the basic syntax of Redis SETEX command.
redis 127.0.0.1:6379> SETEX KEY_NAME TIMEOUT VALUE

redis 127.0.0.1:6379> SETEX mykey 60 redis 
OK 
redis 127.0.0.1:6379> TTL mykey 
60 
redis 127.0.0.1:6379> GET mykey 
"redis 


    22 Lectures 
     40 mins

 Skillbakerystudios
 Print
 Add Notes
 Bookmark this page
D3.js rollup() method - GeeksforGeeks

14 Sep, 2020
With the help of d3.rollup() method, we can get the reduced map from iterable data structure having key and values.
Syntax:
d3.rollup(iterable, reduce, ...keys)

Return value: It will return the reduced map from iterables.
Note: To execute the below examples you have to install the d3 library by using the command prompt for the following command.
npm install d3

Example 1: In this example, we can see that by using the d3.rollup() method, we are able to get the reduced map from iterable data structure having key and values.
Javascript
// Defining d3 contrib variable  var d3 = require('d3');  data = [  {name: "ABC",   amount: "34.0",   date: "11/12/2015"},  {name: "DEF",  amount: "120.11", date: "11/12/2015"},  {name: "MNO", amount: "12.01",  date: "01/04/2016"},  {name: "ABC", amount: "34.05",  date: "01/04/2016"}]  var gfg = d3.rollup(data, g => g.length, d => d.amount);console.log(gfg);
Output:
Map { '34.0' => 1, '120.11' => 1, '12.01' => 1, '34.05' => 1 }

Example 2:
Javascript
// Defining d3 contrib variable  var d3 = require('d3');  data = [  {name: "ABC",   amount: "34.0",   date: "11/12/2019"},  {name: "DEF",  amount: "120.11", date: "11/02/2020"},  {name: "MNO", amount: "12.01",  date: "01/04/2020"},  {name: "DEF", amount: "34.05",  date: "03/04/2020"}]  var gfg = d3.rollup(data, g => g.length, d => d.name, d => d.date);  console.log(gfg);
Output:
Map {
  'ABC' => Map { '11/12/2019' => 1 },
  'DEF' => Map { '11/02/2020' => 1, '03/04/2020' => 1 },
  'MNO' => Map { '01/04/2020' => 1 } 
  }


D3.js
JavaScript
Node.js
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
How to create a link in JavaScript ?
How to Show Images on Click using HTML ?
How to remove an HTML element using JavaScript ?
Remove elements from a JavaScript Array
Express.js express.Router() Function
Installation of Node.js on Linux
Node.js fs.readFileSync() Method
Node.js fs.writeFile() Method
Express.js res.render() Function
Variable number of arguments in Lua Programming

There are functions in Lua that accept a variable number of arguments. These are very helpful in cases where we want to run the same function with many different arguments that might vary in length. So, instead of creating a different function, we pass them in a variable arguments fashion.
function add(...)
   -- function code
end
It should be noted that the three dots (...) in the parameter list indicate that the function has a variable number of arguments. Whenever this function will be called, all its arguments will be collected in a single table, which the function addresses as a hidden parameter named arg.
Now let’s consider an example where we will pass variable number of arguments to a function. The function will be used to calculate the minimum value present in the array that was passed to it as an argument. Also, it will be used to find the minimum values index and we will print both the minimum value and the minimum index.
function minimumvalue (...)
   local mi = 1 -- maximum index
   local m = 100 -- maximum value
   local args = {...}
   for i,val in ipairs(args) do
      if val < m then
         mi = i
         m = val
      end
   end
   return m, mi
end

print(minimumvalue(8,10,23,12,5))
5   5
Notice that now we can make use of the fact that we can have a variable number of arguments in the same function, and hence, when we call the same function again, we will get the minimum value and the minimum index.
function minimumvalue (...)
   local mi = 1 -- maximum index
   local m = 100 -- maximum value
   local args = {...}
   for i,val in ipairs(args) do
      if val < m then
         mi = i
         m = val
      end
   end
   return m, mi
end

print(minimumvalue(8,10,23,12,5))

print(minimumvalue(1,2,3))
5   5
1   1
Get all occurrences of the string between any two specific characters in SAP ABAP

I usually use REGEX in all such cases as it is faster and easily readable and would recommend the same to you.
You can use something similar as the snippet to get your job done.
DATA: lv_para TYPE string.
lv_para = ' You &are like& kite &flying& in a &hurricane&'.
REPLACE ALL OCCURRENCES OF REGEX '&[^&]+&' IN lv_para WITH ''.
WRITE lv_para.
Let me explain the regex for you. It should match the first ‘&’, then you can have any combination with multiple occurrences of ‘&’ and the last occurrence of ‘&’ must be matched.
How to get the build/version number of an iOS App?

In this post we will learn how to fetch and show the iOS build and version number
Step 1 − Open Xcode → New Project → Single View Application → Let’s name it “ShowBuildAndVersion”
Step 2 − Open Main.storyboard and add two labels as shown below.
Step 3 − Attach @IBOutLets for the two labels
@IBOutlet weak var buildLabel: UILabel!
@IBOutlet weak var versionLabel: UILabel!
Step 4 − Change the build and version from project settings.
Step 5 − In viewDidLoad of ViewController get the build and version number for infoDictionary of main bundle. Show it on the corresponding labels.
override func viewDidLoad() {
   super.viewDidLoad()
   if let version = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String {
      versionLabel.text = "Version: \(version)"
   }
   if let build = Bundle.main.infoDictionary?["CFBundleVersion"] as? String {
      buildLabel.text = "Build: \(build)"
   }
}
The infoDictionary in main bundle contains these values, with ‘CFBundleShortVersionString’ and ‘CFBundleVersion’ keys.
We can refer these keys to get the version and build number respectively
Step 6 − Run the project, you should see the build and version number.
Importance of Thread.onSpinWait() method in Java 9?

Thread.onSpinWait() method has been introduced in Java 9. It is a static method of Thread class and can be optionally called in busy-waiting loops. It allows the JVM to issue processor instructions on some system architectures to improve reaction time in such spin-wait loops, and also reduce the power consumed by the core thread. It can benefit the overall power consumption of a java program and allows other core threads to execute at faster speeds within the same power consumption envelope.
public static void onSpinWait()
public class ThreadOnSpinWaitTest {
   public static void main(final String args[]) throws InterruptedException {
      final NormalTask task1 = new NormalTask();
      final SpinWaitTask task2 = new SpinWaitTask();
      final Thread thread1 = new Thread(task1);
      thread1.start();
      final Thread thread2 = new Thread(task2);
      thread2.start();
      new Thread(() -> {
         try {
            Thread.sleep(1000);
         } catch(final InterruptedException e) {
            e.printStackTrace();
         } finally {
            task1.start();
            task2.sta*rt();
         }
      }).start();
      thread1.join();
      thread2.join();
   }
   private abstract static class Task implements Runnable {
      volatile boolean canStart;
      void start() {
         this.canStart = true;
      }
   }
   private static class NormalTask extends Task {
      @Override
      public void run() {
         while(!this.canStart) {
         }
         System.out.println("Done!");
      }
   }
   private static class SpinWaitTask extends Task {
      @Override
      public void run() {
         while(!this.canStart) {
            Thread.onSpinWait();
         }
         System.out.println("Done!");
      }
   }
}
Done!
Done!
numpy.compress() in Python - GeeksforGeeks

22 Oct, 2020
The numpy.compress() function returns selected slices of an array along mentioned axis, that satisfies an axis.
Syntax: numpy.compress(condition, array, axis = None, out = None)
Parameters :
condition : [array_like]Condition on the basis of which user extract elements. 
      Applying condition on input_array, if we print condition, it will return an arra
      filled with either True or False. Array elements are extracted from the Indices having 
      True value.
array     : Input array. User apply conditions on input_array elements
axis      : [optional, int]Indicating which slice to select. 
         By Default, work on flattened array[1-D]
out       : [optional, ndarray]Output_array with elements of input_array, 
               that satisfies condition

Return :
Copy of array with elements of input_array,
that satisfies condition and along given axis

# Python Program illustrating# numpy.compress method  import numpy as geek  array = geek.arange(10).reshape(5, 2)print("Original array : \n", array)  a = geek.compress([0, 1], array, axis=0)print("\nSliced array : \n", a)  a = geek.compress([False, True], array, axis=0)print("\nSliced array : \n", a)
Output :
Original array : 
 [[0 1]
 [2 3]
 [4 5]
 [6 7]
 [8 9]]

Sliced array : 
 [[2 3]]

Sliced array : 
 [[2 3]]

References :https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.compress.htmlNote :This codes won’t run on online-ID. Please run them on your systems to explore the working..This article is contributed by Mohit Gupta_OMG . If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Python numpy-Indexing
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
Selecting rows in pandas DataFrame based on conditions
How to drop one or multiple columns in Pandas Dataframe
Python | Get unique values from a list
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Defaultdict in Python
Python | os.path.join() method
Create a directory in Python
Bar Plot in Matplotlib
HashSet add() Method in Java

26 Nov, 2018
The Java.util.HashSet.add() method in Java HashSet is used to add a specific element into a HashSet. This method will add the element only if the specified element is not present in the HashSet else the function will return False if the element is already present in the HashSet.
Syntax:
Hash_Set.add(Object element)
Parameters: The parameter element is of the type HashSet and refers to the element to be added to the Set.
Return Value: The function returns True if the element is not present in the HashSet otherwise False if the element is already present in the HashSet.
Below program illustrate the Java.util.HashSet.add() method:
// Java code to illustrate add()import java.io.*;import java.util.HashSet;  public class HashSetDemo {    public static void main(String args[])    {        // Creating an empty HashSet        HashSet<String> set = new HashSet<String>();          // Use add() method to add elements into the Set        set.add("Welcome");        set.add("To");        set.add("Geeks");        set.add("4");        set.add("Geeks");          // Displaying the HashSet        System.out.println("HashSet: " + set);    }}
HashSet: [4, Geeks, Welcome, To]

Java - util package
Java-Collections
Java-Functions
java-hashset
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Interfaces in Java
ArrayList in Java
Stream In Java
Collections in Java
Singleton Class in Java
Multidimensional Arrays in Java
Stack Class in Java
Introduction to Java
Constructors in Java
Initializing a List in Java