code-rag-bench/online-tutorials huggingface dataset:
Python - Flatten tuple of List to tuple - GeeksforGeeks

22 Jun, 2020
Sometimes, while working with Python Tuples, we can have a problem in which we need to perform the flattening of tuples, which have lists as its constituent elements. This kind of problem is common in data domains such as Machine Learning. Let’s discuss certain ways in which this task can be performed.
Input : test_tuple = ([5], [6], [3], [8])Output : (5, 6, 3, 8)
Input : test_tuple = ([5, 7, 8])Output : (5, 7, 8)
Method #1 : Using sum() + tuple()The combination of above functions can be used to solve this problem. In this, we perform the task of flattening using sum(), passing empty list as its argument.
# Python3 code to demonstrate working of # Flatten tuple of List to tuple# Using sum() + tuple()  # initializing tupletest_tuple = ([5, 6], [6, 7, 8, 9], [3])  # printing original tupleprint("The original tuple : " + str(test_tuple))  # Flatten tuple of List to tuple# Using sum() + tuple()res = tuple(sum(test_tuple, []))  # printing result print("The flattened tuple : " + str(res))
The original tuple : ([5, 6], [6, 7, 8, 9], [3])
The flattened tuple : (5, 6, 6, 7, 8, 9, 3)

 
Method #2 : Using tuple() + chain.from_iterable()The combination of above functions can be used to solve this problem. In this, we perform task of flattening using from_iterable() and conversion to tuple using tuple().
# Python3 code to demonstrate working of # Flatten tuple of List to tuple# Using tuple() + chain.from_iterable()from itertools import chain  # initializing tupletest_tuple = ([5, 6], [6, 7, 8, 9], [3])  # printing original tupleprint("The original tuple : " + str(test_tuple))  # Flatten tuple of List to tuple# Using tuple() + chain.from_iterable()res = tuple(chain.from_iterable(test_tuple))  # printing result print("The flattened tuple : " + str(res))
The original tuple : ([5, 6], [6, 7, 8, 9], [3])
The flattened tuple : (5, 6, 6, 7, 8, 9, 3)

Python tuple-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
if command in linux with examples - GeeksforGeeks

22 May, 2019
if is a command in Linux which is used to execute commands based on conditions. The ‘if COMMANDS‘ list is executed. If its status is zero, then the ‘then COMMANDS‘ list is executed. Otherwise, each ‘elif COMMANDS‘ list is executed in turn, and if its exit status is zero, the corresponding ‘then COMMANDS‘ list is executed and the if command completes. Otherwise, the ‘else COMMANDS‘ list is executed, if present. The exit status of the entire construct is the exit status of the last command executed, or zero if no condition tested true.
Syntax:
if: if COMMANDS; then COMMANDS; [ elif COMMANDS; then COMMANDS; ]... [ else COMMANDS; ] fi
Example:
Options:
help if : It displays help information.
linux-command
Linux-misc-commands
Linux-Unix
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
tar command in Linux with examples
'crontab' in Linux with Examples
diff command in Linux with examples
UDP Server-Client implementation in C
Tail command in Linux with examples
Cat command in Linux with examples
touch command in Linux with Examples
echo command in Linux with Examples
Compiling with g++
scp command in Linux with Examples
HTML Editors - GeeksforGeeks

24 Mar, 2022
HTML text editors are used to create and modify web pages. HTML codes can be written in any text editors including the notepad. One just needs to write HTML in any text editor and save the file with an extension “.html”. Some of the popular HTML text editors are given below:
Notepad
Notepad++
Sublime Text 3
Atom
GeeksforGeeks IDE
Notepad: Notepad is a simple text editor. It is an inbuilt desktop application available in Windows OS.
Bracket: Bracket is an open-source software primarily used for Web development. It provides live HTML, CSS, JavaScript editing functionality.
Sublime Text 3: Sublime is a cross platform code editor tool. It supports all markup languages.
Atom: Atom is an open source code editor tool for MAC, Linux and Windows.
Steps to write HTML code in Editor:
Open any of the text editors of your choice. Here we are using the notepad text editor.Create new file: File->New File or Ctrl+N.Write HTML code in text editor.Save the file with a suitable name of your choice and .html extension.Open the saved HTML file in your favourite browser (double click on the file, or right-click – and choose “Open with”).
Open any of the text editors of your choice. Here we are using the notepad text editor.
Create new file: File->New File or Ctrl+N.
Write HTML code in text editor.
Save the file with a suitable name of your choice and .html extension.
Open the saved HTML file in your favourite browser (double click on the file, or right-click – and choose “Open with”).
GeeksforGeeks IDE: It is an online code editor to test the code. It provides the shareable link to share code with others.
<html>  <head>    <title>HTML Text Editor</title>    <style>       h1 {          color:#009900;       }    </style>  </head>  <body>    <h1>GeeksforGeeks</h1>  </body></html>
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
Picked
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to update Node.js and NPM to next version ?
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
Difference between PC relative and Base register Addressing Modes - GeeksforGeeks

10 Apr, 2020
Prerequisite – Addressing Modes
1. PC relative addressing mode:PC relative addressing mode is used to implement intra segment transfer of control, In this mode effective address is obtained by adding displacement to PC.
EA = PC + Address field value
PC = PC + Relative value 
2. Base register addressing mode:Base register addressing mode is used to implement inter segment transfer of control. In this mode effective address is obtained by adding base register value to address field value.
EA = Base register + Address field value
PC = Base register + Relative value 
Difference between PC Relative And Base Register Addressing modes:
Picked
Computer Organization & Architecture
Difference Between
GATE CS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Direct Access Media (DMA) Controller in Computer Architecture
Computer Organization and Architecture | Pipelining | Set 2 (Dependencies and Data Hazard)
Architecture of 8085 microprocessor
Pin diagram of 8086 microprocessor
I2C Communication Protocol
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
Differences between IPv4 and IPv6
Jackson Annotations - @JsonSetter

@JsonSetter allows a specific method to be marked as setter method.
import java.io.IOException; 
import com.fasterxml.jackson.annotation.JsonSetter; 
import com.fasterxml.jackson.databind.ObjectMapper; 

public class JacksonTester {
   public static void main(String args[]){ 
      ObjectMapper mapper = new ObjectMapper(); 
      String jsonString = "{\"rollNo\":1,\"name\":\"Marks\"}"; 

      try { 
         Student student = mapper.readerFor(Student.class).readValue(jsonString);
         System.out.println(student.name); 
      }
      catch (IOException e) {
         e.printStackTrace(); 
      }   
   } 
}
class Student { 
   public int rollNo; 
   public String name; 
   @JsonSetter("name") 
   public void setTheName(String name) { 
      this.name = name; 
   }  
}
Marks 

 Print
 Add Notes
 Bookmark this page
How to deal with ModalDialog using selenium webdriver?

We can deal with modal dialog boxes with Selenium. A modal is just like a window that enforces the user to access it prior to going back to the actual page. It can be an authentication window as well.
Let us work with the below modal dialog −
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class ModDialog{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver","C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.get("http://www.uitestpractice.com/Students/Switchto");
      // identify element and click
      WebElement m = driver
      .findElement(By.xpath("//button[contains(text(), 'Launch modal')]"));
      // identify modal header and obtain text
      WebElement m=
      driver.findElement(By.xpath("//h4[@class='modal−title']"));
      System.out.println("Modal Dialog text: " + m.getText());
      // click on OK
      WebElement n= driver.findElement(By.xpath("//button[text()='Ok']"));
      n.click();
      driver.quit();
   }
}
How to find the vowels in a given string using Java?

You can read a character in a String using the charAt() method. To find the vowels in a given String you need to compare every character in it with the vowel letters.
Live Demo
public class FindingVowels {
   public static void main(String args[]) {

      String str = new String("Hi Welcome to Tutorialspoint");
      for(int i=0; i<str.length(); i++) {
         if(str.charAt(i) == 'a'|| str.charAt(i) == 'e'|| str.charAt(i) == 'i' || str.charAt(i) == 'o' || str.charAt(i) == 'u') {
            System.out.println("Given string contains "+str.charAt(i)+" at the index "+i);
         }
      }
   }
}
Given string contains i at the index 1 
Given string contains e at the index 4 
Given string contains o at the index 7 
Given string contains e at the index 9 
Given string contains o at the index 12 
Given string contains u at the index 15 
Given string contains o  at the index 17 
Given string contains i at the index 19 
Given string contains a at the index 20 
Given string contains o at the index 24 
Given string contains i at the index 25
Scale the Columns of a Matrix in R Programming – scale() Function

09 Dec, 2021
scale() function in R Language is a generic function which centers and scales the columns of a numeric matrix. The center parameter takes either numeric alike vector or logical value. If the numeric vector is provided, then each column of the matrix has the corresponding value from center subtracted from it. If the logical value is provided TRUE, then column means of the matrix is subtracted from their corresponding columns. The scale takes either numeric alike vector or logical value. When provided with a numeric like vector, then each column of the matrix is divided by the corresponding value from scale. If the logical value is provided in scale parameter, then centered columns of the matrix is divided by their standard deviations, and the root mean square otherwise. If FALSE, no scaling is done on the matrix.
Syntax:scale(x, center = TRUE, scale = TRUE)
Parameters:x: represents numeric matrixcenter: represents either logical value or numeric alike vector equal to the number of xscale: represents either logical value or numeric alike vector equal to the number of x
Example 1:
r
# Create matrixmt <- matrix(1:10, ncol = 5)  # Print matrixcat("Matrix:\n")print(mt)  # Scale matrix with default argumentscat("\nAfter scaling:\n")scale(mt)
Output:
Matrix:
     [, 1] [, 2] [, 3] [, 4] [, 5]
[1, ]    1    3    5    7    9
[2, ]    2    4    6    8   10

After scaling:
           [, 1]       [, 2]       [, 3]       [, 4]       [, 5]
[1, ] -0.7071068 -0.7071068 -0.7071068 -0.7071068 -0.7071068
[2, ]  0.7071068  0.7071068  0.7071068  0.7071068  0.7071068
attr(, "scaled:center")
[1] 1.5 3.5 5.5 7.5 9.5
attr(, "scaled:scale")
[1] 0.7071068 0.7071068 0.7071068 0.7071068 0.7071068

Example 2:
r
# Create matrixmt <- matrix(1:10, ncol = 2)  # Print matrixcat("Matrix:\n")print(mt)  # Scale center by vector of valuescat("\nScale center by vector of values:\n")scale(mt, center = c(1, 2), scale = FALSE)  # Scale by vector of valuescat("\nScale by vector of values:\n")scale(mt, center = FALSE, scale = c(1, 2))
Output:
Matrix:
     [, 1] [, 2]
[1, ]    1    6
[2, ]    2    7
[3, ]    3    8
[4, ]    4    9
[5, ]    5   10

Scale center by vector of values:
     [, 1] [, 2]
[1, ]    0    4
[2, ]    1    5
[3, ]    2    6
[4, ]    3    7
[5, ]    4    8
attr(, "scaled:center")
[1] 1 2

Scale by vector of values:
     [, 1] [, 2]
[1, ]    1  3.0
[2, ]    2  3.5
[3, ]    3  4.0
[4, ]    4  4.5
[5, ]    5  5.0
attr(, "scaled:scale")
[1] 1 2

sooda367
R Matrix-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Node.js process.stdout Property

01 Jun, 2021
The process.stdout property is an inbuilt application programming interface of the process module which is used to send data out of our program. A Writable Stream to stdout. It implements a write() method. 
Syntax:
process.stdout.write()
Return Value: This property continuously prints the information as the data being retrieved and doesn’t add a new line.
Parameters: This property takes only single strings as an argument.
   
Note:
 
It only takes strings as arguments. Any other data type passed as a parameter will throw a TypeError.
It can be useful for printing patterns as it does not add a new line.
We can not write more than one string.
We can not make associations.
Below examples illustrate the use of process.stdout property in Node.js:
 
Example 1: Create a JavaScript file and name this file as index.js.
 
Javascript
// Node.js program to demonstrate the// process.stdout Property // Printing process.stdout property valueprocess.stdout.write('Greetings of the day');
Run the index.js file using the following command:
node index.js
Output:
Greetings of the day
Example 2: Create a JavaScript file and name this file as index.js.
Javascript
// Node.js program to demonstrate the// process.stdout Property // For process.std.out // Association is not possibleprocess.stdout.write("Geeks");process.stdout.write("for");process.stdout.write("Geeks");
Run the index.js file using the following command:
node index.js
Output:
GeeksforGeeks
simmytarika5
Node.js-Methods
Node.js-process-module
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
JWT Authentication with Node.js
Installation of Node.js on Windows
Difference between dependencies, devDependencies and peerDependencies
Mongoose Populate() Method
Mongoose find() Function
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to create footer to stay at the bottom of a Web page?
How to set the default value for an HTML <select> element ?
How do you run JavaScript script through the Terminal?
exception::what() in C++ with Examples

28 May, 2020
The exception::what() used to get string identifying exception. This function returns a null terminated character sequence that may be used to identify the exception. Below is the syntax for the same:
Header File:
#include<exception>

Syntax:
virtual const char* what() const throw();

Return: The function std::what() return a null terminated character sequence that is used to identify the exception.
Note: To make use of std::what(), one should set up the appropriate try and catch blocks.
Below are the programs to understand the implementation of std::what() in a better way:
Program 1:
// C++ code for exception::what()#include <bits/stdc++.h>  using namespace std;  struct gfg : exception {    const char* what() const noexcept    {        return "GeeksforGeeks!! "               "A Computer Science"               " Portal For Geeks";    }};  // main methodint main(){      // try block    try {        throw gfg();    }      // catch block to handle the errors    catch (exception& gfg1) {        cout << gfg1.what();    }      return 0;}
GeeksforGeeks!! A Computer Science Portal For Geeks

Program 2:
// C++ code for exception::what()  #include <bits/stdc++.h>  using namespace std;  struct geeksforgeeks : exception {    const char* what() const noexcept    {        return "Hey!!";    }};  // main methodint main(){      // try block    try {        throw geeksforgeeks();    }      // catch block to handle the errors    catch (exception& gfg) {        cout << gfg.what();    }      return 0;}
Hey!!

Reference: http://www.cplusplus.com/reference/exception/exception/what/
CPP-Functions
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python program to find files having a particular extension using RegEx

29 Dec, 2020
Prerequisite: Regular Expression in Python
Many of the times we need to search for a particular type of file from a list of different types of files. And we can do so with only a few lines of code using python. And the cool part is we don’t need to install any external package, python has a built-in package called re, with which we can easily write the program for performing this task.
Approach:
This program searches for the files having “.xml” extension from a list of different files.
Make a regular expression/pattern : “\.xml$”
Here re.search() function is used to check for a match anywhere in the string (name of the file). It basically returns the match object when the pattern is found and if the pattern is not found it returns null.
The functionality of different Metacharacters used here:
 \  It is used to specify a special meaning of character after it. It is also used to escape special characters. $ The string ends with the pattern which is before it.
 \  It is used to specify a special meaning of character after it. It is also used to escape special characters.
 $ The string ends with the pattern which is before it.
Here “.xml” pattern is searched and processed.
Below is the implementation:
Python3
# import libraryimport re  # list of different types of filefilenames = ["gfg.html", "geeks.xml",             "computer.txt", "geeksforgeeks.jpg"]  for file in filenames:    # search given pattern in the line     match = re.search("\.xml$", file)      # if match is found    if match:        print("The file ending with .xml is:",             file)
The file ending with .xml is: geeks.xml
Python Regex-programs
python-regex
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PHP | cal_days_in_month( ) Function

26 Apr, 2018
The cal_days_in_month( ) function in PHP is an inbuilt function which is used to return the number of days in a month for a specific year and according to a specific calendar such as Gregorian calendar, French calendar, Jewish calendar etc.
The cal_days_in_month() function takes three parameters which are the calendar, month and year and returns the number of days according to a specified month, year and calendar.
Syntax:
cal_days_in_month($calendar, $month, $year)
Parameters: The cal_days_in_month() function in PHP accepts three parameters as described below:
$calendar: It specifies the calendar you want to consider such as French, Gregorian, Jewish etc.$month: It specifies the month in the calendar you have opted.$year: It specifies the year in the calendar you have opted.
$calendar: It specifies the calendar you want to consider such as French, Gregorian, Jewish etc.
$month: It specifies the month in the calendar you have opted.
$year: It specifies the year in the calendar you have opted.
Return Value: It returns the number of days according to a specified month, year and calendar.
Errors And Exception:
The cal_days-in_month function gives wrong output when the date used is before 1550.The cal_days-in_month function gives wrong output for dates which were before the discovery of leap year.
The cal_days-in_month function gives wrong output when the date used is before 1550.
The cal_days-in_month function gives wrong output for dates which were before the discovery of leap year.
Examples:
Input: cal_days_in_month(CAL_JEWISH, 2, 1966);
Output: 29
Explanation: February 1966 had 29 days.

Input: cal_days_in_month(CAL_GREGORIAN, 2, 2004);
Output: 29
Explanation: February 2004 had 29 days

Below programs illustrate the cal_days_in_month() function:
Program 1:
<?php  // Using cal_days_in_month() function to// know the number of days in february, 1966$days = cal_days_in_month(CAL_JEWISH, 2, 1966);  echo "February 1966 had $days days.<br>";  ?>
Output:
February 1966 had 29 days.
Program 2:
<?php  // Using cal_days_in_month() function to// know the number of days in february, 2004$days = cal_days_in_month(CAL_GREGORIAN, 2, 2004);  echo "February 2004 had $days days";  ?>
Output:
February 2004 had 29 days
Reference:http://php.net/manual/en/function.cal-days-in-month.php
PHP-date-time
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to execute PHP code using command line ?
How to Insert Form Data into Database using PHP ?
PHP in_array() Function
How to delete an array element based on key in PHP?
How to convert array to string in PHP ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
PostgreSQL – CREATE ROLE

28 Aug, 2020
PostgreSQL uses roles to represent user accounts. It doesn’t use the user concept like other database systems. Typically, roles can log in are called login roles. They are equivalent to users in other database systems. When roles contain other roles, they are called group roles. When you create a role, it is valid in all databases in the database server (or cluster).
To create a new role, you use the CREATE ROLE statement as follows:
Syntax: CREATE ROLE role_name;

To get all roles in the current PostgreSQL database server, you can query them from the pg_roles system catalog as follows:
Syntax: SELECT rolname FROM pg_roles;

This will result in the following:
If one uses the psql tool, one can use the \du command to list all existing roles in the current PostgreSQL database server:
Syntax: \du

It will behave as shown below:
The attributes of a role define privileges for that role including login, superuser, database creation, role creation, password, etc:
Syntax: CREATE ROLE name WITH option;

In this syntax, the WITH keyword is optional. And the option can be one or more attributes including SUPER, CREATEDB, CREATEROLE, etc.
The following statement creates a role called ‘Raju’ that has the login privilege and an initial password:
CREATE ROLE raju
LOGIN 
PASSWORD 'mypassword1';

Note: It is required to place the password in single quotes (‘).
Now verify the role using the below command:
\du

The role creation is successful as shown below:
The following statement creates a role called ‘Nikhil’ that has the superuser attribute:
CREATE ROLE Nikhil
SUPERUSER 
LOGIN 
PASSWORD 'mypassword1';
This will lead to the following:
The superuser can override all access restrictions within the database therefore you should create this role only when needed.
Note: One must be a superuser in order to create another superuser role.
If you want to create roles that have the database creation privilege, you use the CREATEDB attribute:
CREATE ROLE dba 
CREATEDB 
LOGIN 
PASSWORD 'Abcd1234';
This will lead to the following:
To set a date and time after which the role’s password is no longer valid, you use the valid until attribute:
VALID UNTIL 'timestamp'
Example:
CREATE ROLE dev_api WITH
LOGIN
PASSWORD 'securePass1'
VALID UNTIL '2030-01-01';
Output:
To specify the number of concurrent connections a role can make, you use the CONNECTION LIMIT attribute:
CONNECTION LIMIT connection_count
The following creates a new role called API that can make 1000 concurrent connections:
CREATE ROLE api
LOGIN
PASSWORD 'securePass1'
CONNECTION LIMIT 1000;
This will create a new role as follows:
The following psql command shows all the roles that we have created so far:
\du
This will show you the results as depicted below:
postgreSQL-administration
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Accessing variable value from code scope

29 Oct, 2019
Sometimes, we just need to access a variable other than the usual way of accessing by it’s name. There are many method by which a variable can be accessed from the code scope. These are by default dictionaries that are created and which keep the variable values as dictionary key-value pair. Let’s talk about some of this functions.
Method #1 : Using locals()This is a function that stores the values of all variables in local scope of function if in a function or of global scope if outside.
# Python3 code to demonstrate working of# Accessing variable value from code scope# using locals  # initialize variabletest_var = "gfg is best"  # printing original variableprint("The original variable : " + str(test_var))  # Accessing variable value from code scope# using localsres = locals()['test_var']  # printing resultprint("Variable accessed using dictionary : " + str(res))
The original variable : gfg is best
Variable accessed using dictionary : gfg is best

 
Method #2 : Using globals()This is yet another function that maintains a dictionary of variables of global scope.
# Python3 code to demonstrate working of# Accessing variable value from code scope# using globals  # initialize variabletest_var = "gfg is best"  # printing original variableprint("The original variable : " + str(test_var))  # Accessing variable value from code scope# using globalsres = globals()['test_var']  # printing resultprint("Variable accessed using dictionary : " + str(res))
The original variable : gfg is best
Variable accessed using dictionary : gfg is best

python-basics
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
Java String trim() method with Example

25 Sep, 2021
The trim() method in Java String is a built-in function that eliminates leading and trailing spaces. The Unicode value of space character is ‘\u0020’. The trim() method in java checks this Unicode value before and after the string, if it exists then removes the spaces and returns the omitted string. The trim() method also helps in trimming the characters in Java.
Note: The trim() method doesn’t eliminate middle spaces.
Method Signature:
public String trim()
Parameters: The trim() method accepts no parameters. 
Return Type: The return type of trim() method is String. It returns the omitted string with no leading and trailing spaces. 
Below are examples to show the working of the string trim() method in Java. 
Example 1:
Java
// Java program to demonstrate working// of java string trim() method class Gfg {     // driver code    public static void main(String args[])    {         // trims the trailing and leading spaces        String s = " geeks for geeks has all java functions to read  ";        System.out.println(s.trim());         // trims the leading spaces        s = " Chetna loves reading books";        System.out.println(s.trim());    }}
geeks for geeks has all java functions to read
Chetna loves reading books
Java
// Java program to demonstrate working// of java string trim() method import java.io.*; class GFG {    public static void main (String[] args) {               String s1 = "   Geeks For Geeks   ";             // Before Trim() method      System.out.println("Before Trim() - ");      System.out.println("String - "+s1);      System.out.println("Length - "+s1.length());             // applying trim() method on string s1      s1=s1.trim();             // After Trim() method      System.out.println("\nAfter Trim() - ");      System.out.println("String - "+s1);      System.out.println("Length - "+s1.length());           }}
Before Trim() - 
String -    Geeks For Geeks   
Length - 21

After Trim() - 
String - Geeks For Geeks
Length - 15
nishkarshgandhi
Java-Functions
Java-lang package
Java-Strings
Java
Java-Strings
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream ofNullable(T) method in Java with examples

25 Apr, 2019
The ofNullable(T) method returns a sequential Stream containing a single element if this stream is non-null otherwise method returns an empty Stream. It helps to handle the null stream and NullPointerException.
Syntax:
static <T> Stream<T> ofNullable(T t)

Parameters: This method accepts a single parameter t which is the single element of which the Stream is to be returned.
Return value: This method returns a stream with a single element if the specified element is non-null, otherwise an empty stream.
Below programs illustrate ofNullable(T) method:
Program 1:
// Java program to demonstrate// Stream.ofNullable() method  import java.util.stream.Stream;public class GFG {      public static void main(String[] args)    {          // Create a stream with null        Stream<String> value            = Stream.ofNullable(null);          // Print values        System.out.println("Values of Stream:");        value.forEach(System.out::println);    }}
The output printed on console of IDE is shown below.Output:
Program 2:
// Java program to demonstrate// Stream.ofNullable method  import java.util.ArrayList;import java.util.stream.Stream;public class GFG {      public static void main(String[] args)    {          // Create ArrayList containing names        ArrayList<String> list = new ArrayList<String>();        list.add("Aman");        list.add("Suraj");        list.add("Zufaq");          // create a stream with ArrayList        Stream<ArrayList<String> > value            = Stream.ofNullable(list);          // print values        System.out.println("Values of Stream:");        value.forEach(System.out::println);    }}
The output printed on console is shown below.Output:
References: https://docs.oracle.com/javase/10/docs/api/java/util/stream/Stream.html#ofNullable(T)
Java - util package
Java-Functions
java-stream
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
Stream In Java
Collections in Java
Singleton Class in Java
Multidimensional Arrays in Java
Stack Class in Java
What is the equivalent of document.getElementById() in React?

01 Feb, 2021
In React we have a concept of Refs which is equivalent to document.getElementById() in Javascript. Refs provide a way to access DOM nodes or React elements created in the render method.
Creating Refs
Refs are created using React.createRef() and attached to React elements via the ref attribute. 
class App extends React.Component {
 constructor(props) {
   super(props);
   //creating ref
   this.myRef= React.createRef();
 }
 render() {
 //assigning ref
   return <div ref={this.myRef} />;
 }
}
Accessing Refs
When we assign a ref to an element in the render, then we can access the element using the current attribute of the ref.
const node = this.myRef.current;
Creating React Application:
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Project Structure: It will look like the following.
filepathe- src/App.js:
Javascript
import React from 'react'  class App extends React.Component {      constructor(props) {        super(props);        this.myRef = React.createRef();      }    onFocus() {      this.myRef.current.value ="focus"    }        onBlur() {      this.myRef.current.value = "blur"    }        render() {      return (        <div>          <input            ref= {this.myRef}            onFocus={this.onFocus.bind(this)}            onBlur={this.onBlur.bind(this)}          />        </div>      );    }  }    export default App;
Output:
Picked
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Axios in React: A Guide for Beginners
ReactJS setState()
How to pass data from one component to other component in ReactJS ?
Re-rendering Components in ReactJS
ReactJS defaultProps
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
Differences between Functional Components and Class Components in React
Python | Unzip a list of tuples

29 Nov, 2018
The zipping techniques, that is assigning a key-value or pairing from two different lists has been covered in many articles before, sometimes we have specific utility to perform the reverse task. This task can be achieved by various methods.
Let’s discuss some of the methods to unzip a list of tuples.
Method #1 : Using List Comprehension
Using list comprehension is the most naive approach to perform this task of unzipping and usually not used to perform this task, but good method to start with.
# Python3 code to demonstrate # Unzip a list of tuples# using list comprehension  # initializing list of tuplestest_list = [('Akshat', 1), ('Bro', 2), ('is', 3), ('Placed', 4)]  # Printing original listprint ("Original list is : " + str(test_list))  # using list comprehension to# perform Unzippingres = [[ i for i, j in test_list ],       [ j for i, j in test_list ]]      # Printing modified list print ("Modified list is : " + str(res))
Output :
Original list is : [('Akshat', 1), ('Bro', 2), ('is', 3), ('Placed', 4)]
Modified list is : [['Akshat', 'Bro', 'is', 'Placed'], [1, 2, 3, 4]]

 
Method #2 : Using zip() and * operator
Mostly used method to perform unzip and most Pythonic and recommended as well. This method is generally used to perform this task by programmers all over. * operator unzips the tuples into independent lists.
# Python3 code to demonstrate # Unzip a list of tuples# using zip() and * operator  # initializing list of tuplestest_list = [('Akshat', 1), ('Bro', 2), ('is', 3), ('Placed', 4)]  # Printing original listprint ("Original list is : " + str(test_list))  # using zip() and * operator to# perform Unzippingres = list(zip(*test_list))      # Printing modified list print ("Modified list is : " + str(res))
Output :
Original list is : [('Akshat', 1), ('Bro', 2), ('is', 3), ('Placed', 4)]
Modified list is : [('Akshat', 'Bro', 'is', 'Placed'), (1, 2, 3, 4)]

 Method #3 : Using map()This is yet another way that can be employed to perform this task of unzipping which is less known but indeed a method to achieve this task. This also uses the * operator to perform the basic unpacking of the list. This function is deprecated in Python >= 3 versions.
# Python code to demonstrate # Unzip a list of tuples# using map()  # initializing list of tuplestest_list = [('Akshat', 1), ('Bro', 2), ('is', 3), ('Placed', 4)]  # Printing original listprint ("Original list is : " + str(test_list))  # using map() to# perform Unzippingres = map(None, *test_list)      # Printing modified list print ("Modified list is : " + str(res))
Output :
Original list is : [('Akshat', 1), ('Bro', 2), ('is', 3), ('Placed', 4)]
Modified list is : [('Akshat', 'Bro', 'is', 'Placed'), (1, 2, 3, 4)]

Python list-programs
python-list
python-tuple
Python
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Information Entropy using MATLAB

18 Aug, 2020
Information entropy is the aggregate rate at which information is created by a stochastic wellspring of information. The proportion of information entropy related to every potential information value is the negative logarithm of the likelihood mass function for the worth. Hence, when the information source has lower likelihood esteem(i.e., when a low-likelihood occasion happens), the occasion conveys more data than when the source information has higher-likelihood esteem. The measure of data passed on by each occasion characterized along these lines turns into a random variable whose expected worth is the information entropy. Entropy is zero when one result is sure to happen.
Formula: 
Example 1 : A discrete memoryless source i.e. DMS ‘X’ has 4 symbols x1, x2, x3 and x4 with probabilities P(x1) = 0.333, P(x2) = 0.333, P(x3) = 0.167 and P(x4) = 0.167.So, H(X) = -0.333 log2(0.333)-0.333 log2(0.333)-0.167 log2(0.167)-0.167 log2(0.167)      H(X) = 1.918
Example 2 : A discrete memoryless source i.e. DMS ‘X’ has 2 symbols x1 and x2 with probabilities P(x1) = 0.600 and P(x2) = 0.400So, H(X) = -0.600 log2(0.600)-0.400 log2(0.400)      H(X) = 0.970
Here is the MATLAB code to calculate the information entropy of a string.
clc;  # the stringx = 'GeeksforGeeks'  # length of the stringlen = length(x);display(len);  # unique charactersu = unique(x);display(u);  # length of unique character stringlenChar = length(u);display(lenChar);  # creating 2 zero vectorsz = zeros(1, lenChar);p = zeros(1, lenChar);  # finding the values of probabilityfor i = 1 : lenChar   z(i) = length(findstr(x, u(i)));   p(i) = z(i) / len;enddisplay(z);display(p);  # information entropyH = 0;for i=1:lenChar  H = H + (-p(i) * log2(p(i)));enddisplay(H);
x = GeeksforGeeks
len =  13
u = Gefkors
lenChar =  7
z =

   2   4   1   2   1   1   2

p =

   0.153846   0.307692   0.076923   0.153846   0.076923   0.076923   0.153846

H =  2.6235

MATLAB
Advanced Computer Subject
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
System Design Tutorial
ML | Linear Regression
Reinforcement learning
Docker - COPY Instruction
Supervised and Unsupervised learning
Decision Tree Introduction with example
ML | Monte Carlo Tree Search (MCTS)
Getting started with Machine Learning
How to Run a Python Script using Docker?
Markov Decision Process
Stuffing a Pandas DataFrame.plot into a Matplotlib subplot

To stuff a Pandas dataframe plot into a Matplotlib subplot, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Create a figure and a set of subplots, two axes.
Create a Pandas dataframe using DataFrame.
Use DataFrame.plot() method to plot.
To display the figure, use show() method.
import pandas as pd
import matplotlib.pyplot as plt

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

fig, (ax1, ax2) = plt.subplots(2)
df = pd.DataFrame(dict(name=["Joe", "James", "Jack"], age=[23, 34, 26]))

df.set_index("name").plot(ax=ax1)
df.set_index("name").plot(ax=ax2)

plt.show()
numpy.ndarray.view() in Python

27 Aug, 2021
numpy.ndarray.view() helps to get a new view of array with the same data. 
Syntax: ndarray.view(dtype=None, type=None)Parameters: dtype : Data-type descriptor of the returned view, e.g., float32 or int16. The default, None, results in the view having the same data-type as a. type : Python type, optionalReturns : ndarray or matrix.
Code #1:  
Python3
# Python program explaining # numpy.ndarray.view() function import numpy as geek a = geek.arange(10, dtype ='int16') print("a is: \n", a) # using view() methodv = a.view('int32')print("\n After using view() with dtype = 'int32' a is : \n", a) v += 1 # addition of 1 to each element of vprint("\n After using view() with dtype = 'int32' and adding 1 a is : \n", a)
a is: 
 [0 1 2 3 4 5 6 7 8 9]

 After using view() with dtype = 'int32' a is : 
 [0 1 2 3 4 5 6 7 8 9]

 After using view() with dtype = 'int32' and adding 1 a is : 
 [1 1 3 3 5 5 7 7 9 9]
 
  Code #2:  
Python3
# Python program explaining # numpy.ndarray.view() function import numpy as geek a = geek.arange(10, dtype ='int16')print("a is:", a) # Using view() methodv = a.view('int16')print("\n After using view() with dtype = 'int16' a is :\n", a) v += 1# addition of 1 to each element of vprint("\n After using view() with dtype = 'int16' and adding 1 a is : \n", a)
a is: [0 1 2 3 4 5 6 7 8 9]

 After using view() with dtype = 'int16' a is :
 [0 1 2 3 4 5 6 7 8 9]

 After using view() with dtype = 'int16' and adding 1 a is : 
 [ 1  2  3  4  5  6  7  8  9 10]
 
  Code #3:  
Python3
# Python program explaining # numpy.ndarray.view() function import numpy as geek a = geek.arange(10, dtype ='int16')print("a is: \n", a) v = a.view('int8')print("\n After using view() with dtype = 'int8' a is : \n", a) v += 1# addition of 1 to each element of vprint("\n After using view() with dtype = 'int8' and adding 1 a is : \n", a)
surinderdawra388
Python numpy-ndarray
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Iterate over a list in Python
Rotate axis tick labels in Seaborn and Matplotlib
Enumerate() in Python
Deque in Python
Stack in Python
Python Dictionary
sum() function in Python
Print lists in Python (5 Different Ways)
Different ways to create Pandas Dataframe
Queue in Python
VBScript Erase Function

The Erase Function is used to reset the values of fixed size arrays and free the memory of the dynamic arrays. It behaves depending upon the type of the arrays.
Erase ArrayName

Fixed numeric array, each element in an array is reset to Zero.
Fixed numeric array, each element in an array is reset to Zero.
Fixed String array, each element in an array is reset to Zero length " ".
Fixed String array, each element in an array is reset to Zero length " ".
Array of Objects, each element in an array is reset to s special value Nothing.
Array of Objects, each element in an array is reset to s special value Nothing.
<!DOCTYPE html>
<html>
   <body>
      <script language = "vbscript" type = "text/vbscript">
         Dim NumArray(3)
         NumArray(0) = "VBScript"
         NumArray(1) = 1.05
         NumArray(2) = 25
         NumArray(3) = #23/04/2013#

         Dim DynamicArray()
         ReDim DynamicArray(9)   ' Allocate storage space.

         Erase NumArray          ' Each element is reinitialized.
         Erase DynamicArray      ' Free memory used by array.

         ' All values would be erased.
         Document.write("The value at Zeroth index of NumArray is " & NumArray(0) & "<br />")
         Document.write("The value at First index of NumArray is " & NumArray(1) & "<br />")
         Document.write("The value at Second index of NumArray is " & NumArray(2) & "<br />")
         Document.write("The value at Third index of NumArray is " & NumArray(3) & "<br />")

      </script>
   </body>
</html>
When the above code is saved as .HTML and executed in Internet Explorer, it produces the following result −
The value at Zero index of NumArray is 
The value at First index of NumArray is 
The value at Second index of NumArray is 
The value at Third index of NumArray is
BOTP – SMS and Email Bomber in Kali Linux

17 Jun, 2021
The BOTP tool is a free and open-source tool available on GitHub that is used to perform call and SMS bombing on the target phone numbers. You must ensure that you always install the latest version of BOTP from GitHub in order to not get stuck with the work of the tool. 
This tool is written in python. You must have python installed in your Kali Linux operating system. This tool works with open-source intelligence APIs that’s why this tool requires an internet connection to perform bombing. BOTP doesn’t take your phone number, you only have to enter the target phone number and the tool will do the rest of the work. 
Step 1: 
Open your kali Linux operating system and use the following command to install the tool from GitHub and then move to the tool directory using the second command.
git clone https://github.com/botolmehedi/botp
cd botp
Step 2: 
The tool has been downloaded and now the tool runs using the following command.
python2 botp.py
The tool is running successfully. Now let’s see some examples of using the tool.
Example 1:  
Use the BOTP tool to perform SMS Bombing on a number.
1
<phone number>
 You can see that the tool has started running and the number of threats is 5000. 
Example 2: 
Use the BOTP tool to perform email bombing on an email address.
02
The tool has opened a list where you have to select the type of email your target has. For example, let’s select 1 here for Gmail bombing.
Now you have to provide the email address which is your target
The tool has started email bombing on the email that you have provided now. In this way, you can perform email bombing and SMS bombing. You can give your own credentials here. The tool has started sending SMS and emails. Some of them achieve success, some of them fail, but you can try again and again for the best results. The SMS failed due to a poor internet connection. If your internet is good, then no SMS of yours will fail.
Kali-Linux
Linux-Tools
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Docker - COPY Instruction
scp command in Linux with Examples
chown command in Linux with Examples
SED command in Linux | Set 2
nohup Command in Linux with Examples
Introduction to Linux Operating System
Array Basics in Shell Scripting | Set 1
chmod command in Linux with examples
mv command in Linux with examples
Basic Operators in Shell Scripting
Convert two lists into a dictionary in Python

While a Python list contains a series of values a dictionary on the other hand contains a pair of values which are called key-value pairs. In this article we will take two lists and mark them together to create a Python dictionary.
We create two nested for loops. In the inner loop will assign one of the list as key for the dictionary while keep removing the values from the list which is outer for loop.
 Live Demo
listK = ["Mon", "Tue", "Wed"]
listV = [3, 6, 5]
# Given lists
print("List of K : ", listK)
print("list of V : ", listV)
# Empty dictionary
res = {}
# COnvert to dictionary
for key in listK:
   for value in listV:
      res[key] = value
      listV.remove(value)
      break
print("Dictionary from lists :\n ",res)
Running the above code gives us the following result −
('List of K : ', ['Mon', 'Tue', 'Wed'])
('list of V : ', [3, 6, 5])
('Dictionary from lists :\n ', {'Wed': 5, 'Mon': 3, 'Tue': 6})
The two lists are combined to create a pair of values by putting them into a for loop. The range and len functions are used to keep track of the number of elements till all the key value pairs are created.
 Live Demo
listK = ["Mon", "Tue", "Wed"]
listV = [3, 6, 5]
# Given lists
print("List of K : ", listK)
print("list of V : ", listV)
# COnvert to dictionary
res = {listK[i]: listV[i] for i in range(len(listK))}
print("Dictionary from lists :\n ",res)
Running the above code gives us the following result −
('List of K : ', ['Mon', 'Tue', 'Wed'])
('list of V : ', [3, 6, 5])
('Dictionary from lists :\n ', {'Wed': 5, 'Mon': 3, 'Tue': 6})
The zip function does something similar to above approach. It also combines the elements from the two lists, creating key and value pairs.
 Live Demo
listK = ["Mon", "Tue", "Wed"]
listV = [3, 6, 5]
# Given lists
print("List of K : ", listK)
print("list of V : ", listV)
# COnvert to dictionary
res = dict(zip(listK, listV))
print("Dictionary from lists :\n ",res)
Running the above code gives us the following result −
('List of K : ', ['Mon', 'Tue', 'Wed'])
('list of V : ', [3, 6, 5])
('Dictionary from lists :\n ', {'Wed': 5, 'Mon': 3, 'Tue': 6})