code-rag-bench/online-tutorials huggingface dataset:
Connecting to SAP R/3 system via JCo client and JCo Server

In JCo3.0, Java client JCO.Client is replaced by JCoDestinations. You can connect to SAP system via Inbound RFC Communication (Java calls ABAP) or via Outbound RFC Communication (ABAP calls Java).
For inbound RFC communication, you need to use JCoDestination for executing a remote function module at ABAP side. To use inbound RFCs, you have to use “JCoDestination” which executes a Function module remotely at ABAP side and while using outbound RFCs, you have to configure a JCoServer at the SAP gateway that is responsible to receive incoming requests from ABAP side and process remote function module at Java side.
To know more about configuring JCo connection for inbound and outbound processing, you can refer below link:
https://help.sap.com/saphelp_nwpi711/helpdata/en/48/70792c872c1b5ae10000000a42189c/frameset.htm
Why Python is called Dynamically Typed?

16 Sep, 2018
Python variable assignment is different from some of the popular languages like c, c++ and java. There is no declaration of a variable, just an assignment statement.
Let us see why?When we declare a variable in C or alike languages, this sets aside an area of memory for holding values allowed by the data type of the variable. The memory allocated will be interpreted as the data type suggests. If it’s an integer variable the memory allocated will be read as an integer and so on. When we assign or initialize it with some value, that value will get stored at that memory location. At compile time, initial value or assigned value will be checked. So we cannot mix types. Example: initializing a string value to an int variable is not allowed and the program will not compile.
But Python is a dynamically typed language. It doesn’t know about the type of the variable until the code is run. So declaration is of no use. What it does is, It stores that value at some memory location and then binds that variable name to that memory container. And makes the contents of the container accessible through that variable name. So the data type does not matter. As it will get to know the type of the value at run-time.
# This will store 6 in the memory and binds the# name x to it. After it runs, type of x will# be int.x = 6     print(type(x))  # This will store 'hello' at some location int # the memory and binds name x to it. After it# runs type of x will be str.x = 'hello'   print(type(x))
<class 'int'>
<class 'str'>

python-basics
Python-Data Type
Python-datatype
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to send email verification link with firebase using ReactJS?

12 Apr, 2021
In this article we are going to see how to send an email verification link with firebase using React.js. 
For Setup a firebase (Setup a Firebase for your React Project).
Creating React Application And Installing Module.
Step 1: Create a React myapp using the following command.npx create-react-app myapp
Step 1: Create a React myapp using the following command.
npx create-react-app myapp
Step 2: After creating your project folder i.e. myapp, move to it using the following command.cd myapp
Step 2: After creating your project folder i.e. myapp, move to it using the following command.
cd myapp
Project structure: The project structure will look like this.
Step 3: After creating the ReactJS application, Install the firebase module using the following command.
npm install firebase@8.3.1 --save
Step 4: Go to your firebase dashboard and create a new project and copy your credentials.
const firebaseConfig = {
      apiKey: "your api key",
      authDomain: "your credentials",
      projectId: "your credentials",
      storageBucket: "your credentials",
      messagingSenderId: "your credentials",
      appId: "your credentials"
};
Step 5: Now Enable the sign in with email and password from your sign-in method.
Example: Initialize the firebase into your project by creating firebase.js file with the following code.
firebase.js
import firebase from 'firebase';  const firebaseConfig = {    // Your credentials};  firebase.initializeApp(firebaseConfig);var auth = firebase.auth();export default auth;
Now write some code into your App.js file. 
App.js
import auth from './firebase';import './App.css';import {useState} from 'react';  function App() {  const [email , setemail] = useState('');  const [password , setpassword] = useState('');  const signup = ()=>{      auth.createUserWithEmailAndPassword(email , password)      .then((userCredential)=>{          // send verification mail.        userCredential.user.sendEmailVerification();        auth.signOut();        alert("Email sent");      })      .catch(alert);  }        return (    <div className="App">      <br/><br/>      <input type="email" placeholder="Email"       onChange={(e)=>{setemail(e.target.value)}}>      </input>      <br/><br/>      <input type="password" placeholder="password"       onChange={(e)=>{setpassword(e.target.value)}}>      </input>      <br/><br/>      <button onClick={signup}>Sign-up</button>    </div>  );}  export default App;
Output : 
Here, When you click on sign-up button the verification email is send to the provided email address.
Here is the verification mail. 
Firebase
React-Questions
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ord() function in Python

23 Sep, 2021
Python ord() function returns the Unicode code from a given character. This function accepts a string of unit length as an argument and returns the Unicode equivalence of the passed argument. In other words, given a string of length 1, the ord() function returns an integer representing the Unicode code point of the character when an argument is a Unicode object, or the value of the byte when the argument is an 8-bit string.
Syntax:  ord(ch)
ch – A unicode character
For example, ord(‘a’) returns the integer 97, ord(‘€’) (Euro sign) returns 8364. This is the inverse of chr() for 8-bit strings and of unichr() for Unicode objects. If a Unicode argument is given and Python is built with UCS2 Unicode, then the character’s code point must be in the range [0..65535] inclusive. 
Note: If the string length is more than one, and a TypeError will be raised. The syntax can be ord(“a”) or ord(‘a’), both will give same results. 
Python
# inbuilt function return an# integer representing the Unicode codevalue = ord("A") # writing in ' ' gives the same resultvalue1 = ord('A') # prints the unicode valueprint (value, value1)
Output: 
65 65
A TypeError is raised when the length of the string is not equal to 1 as shown below:
Python3
# inbuilt function return an# integer representing the Unicode code# demonstrating exception # Raises Exceptionvalue1 = ord('AB') # prints the unicode valueprint(value1)
Output:
Traceback (most recent call last):
  File “/home/f988dfe667cdc9a8e5658464c87ccd18.py”, line 6, in 
    value1 = ord(‘AB’)
TypeError: ord() expected a character, but string of length 2 found
The chr() method returns a string representing a character whose Unicode code point is an integer.
Syntax: chr(num)
num : integer value
Where ord() methods work on opposite for chr() function:
Python3
# inbuilt function return an# integer representing the Unicode codevalue = ord("A") # prints the unicode valueprint (value) # print the characterprint(chr(value))
Output:
65
A
manjeet_04
RajuKumar19
kumar_satyam
gabaa406
Python-Built-in-functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SQL | ALTER (RENAME)

22 Mar, 2021
Sometimes we may want to rename our table to give it a more relevant name. For this purpose we can use ALTER TABLE to rename the name of table.
*Syntax may vary in different databases.  Syntax(Oracle,MySQL,MariaDB): 
ALTER TABLE table_name
RENAME TO new_table_name;
Columns can be also be given new name with the use of ALTER TABLE.
Syntax(MySQL, Oracle):
ALTER TABLE table_name
RENAME COLUMN old_name TO new_name;
Syntax(MariaDB):
ALTER TABLE table_name
CHANGE COLUMN old_name TO new_name;
Sample Table:Student
QUERY:
Change the name of column NAME to FIRST_NAME in table Student.
ALTER TABLE Student RENAME COLUMN NAME TO FIRST_NAME;
OUTPUT: 
 
Change the name of the table Student to Student_Details
ALTER TABLE Student RENAME TO Student_Details;
OUTPUT:Student_Details 
This article is contributed by Shubham Chaudhary. 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. 
guruvishnu_desireddy
tirathsharma098
SQL-Clauses-Operators
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to add two arrays into a new array in JavaScript?

Let’s say the following is our first array −
var firstArray=["John","David","Bob","Mike"];
Following is our second array −
var secondArray=["Chris","Adam","James","Carol"];
To add the above two arrays into a new array, use concat().
Following is the code −
var firstArray=["John","David","Bob","Mike"];
var secondArray=["Chris","Adam","James","Carol"];
var thirdArray=firstArray.concat(secondArray);
console.log("First Array value=");
console.log(firstArray);
console.log("Second Array value=");
console.log(secondArray);
console.log("Third Array value=");
console.log(thirdArray);
To run the above program, you need to use the following command −
node fileName.js.
Here, my file name is demo249.js.
This will produce the following output on console −
PS C:\Users\Amit\javascript-code> node demo249.js
First Array value=
[ 'John', 'David', 'Bob', 'Mike' ]
Second Array value=
[ 'Chris', 'Adam', 'James', 'Carol' ]
Third Array value=
[
   'John',  'David',
   'Bob',   'Mike',
   'Chris', 'Adam',
   'James', 'Carol'
]
Log Transformation Base For Data Linearization Does Not Matter | by Jeremy Chow | Towards Data Science

Code for this demonstration can be found here:
Today a colleague asked me a simple question:
“How do you find the best logarithm base to linearly transform your data?”
This is actually a trick question, because there is no best log base to linearly transform your data — the fact that you are taking a log will linearize it no matter what the base of the log is.
My colleague was skeptical and I wanted to brush up on my algebra, so let’s dive into the math!
Let’s assume you have exponential data. This means your data is in some form similar to the following:
This means our data is non-linear. Linear data is arguably the best form of data we can model, because through linear regression we can directly quantify the effects of each feature on the target variable by looking at its coefficient. Linear regression is the best type of model for giving humans an intuitive and quantitative sense of how the model thinks our dependent variable is influenced by our independent variables versus, for example, the black boxes of deep neural nets.
Since we know the base here is e, we can linearize our data by taking the natural log of both sides (ignoring the constant C1):
Now if we plot ln(y) vs. x, we get a line. That’s pretty straightforward, but what happens if we didn’t know that the base of our power was e? We can try taking the log (base 10) of both sides:
but it doesn’t seem to look linear yet. However, what if we introduce the logarithm power rule?
But log(e) is a constant! therefore we have:
This means that our base 10 log is still directly proportional to x, just by a different scaling factor C, which is the log of the original base e in this case.
We can also visualize this with some python code!
import numpy as npimport matplotlib.pyplot as plt# Set up variables, x is 1-9 and y is e^xx = list(np.linspace(1,10,100))y= [np.exp(i) for i in x]# Plot the original variables - this is barebones plotting code, you  # can find the more detailed plotting code on my github!plt.plot(x,y)# Plot log base 10 of yplt.plot(x,np.log10(y))# Plot log base e of yplt.plot(x,np.log(y))
The only thing that changed between the two logarithms was the y-scale because the slopes are slightly different! The important part is that both are still linearly proportional with x, and thus would have equal performance in a linear regression model.
In summary: If you have exponential data, you can do a log transformation of any base to linearize the data. If you have an intuition for the base from domain knowledge, then use the correct base — otherwise it doesn’t matter.
What if your data is in the slightly different form of x raised to the power of some unknown λ?
In this case, a Box-Cox transformation will help you find the ideal power to raise your data to in order to linearize it. I recommend using Sci-py’s implementation.
That’s all for this one, thanks for reading!
Tryit Editor v3.7

Padding & Spacing
Tryit: HTML table - space between cells
Design File System in Python

Suppose we have to design a file system which provides these two functions −
createPath(path, value) − This creates a new path and associates a value to it if possible and returns True. It returns False if the path already exists or its parent path doesn't exist.get(path) − This finds the value associated with a path or returns -1 if the path doesn't exist.
createPath(path, value) − This creates a new path and associates a value to it if possible and returns True. It returns False if the path already exists or its parent path doesn't exist.
get(path) − This finds the value associated with a path or returns -1 if the path doesn't exist.
The format of a path is one or more concatenated strings of the form − (forward slash) / followed by one or more lowercase English letters. For example, /programming and /programming/problems are valid paths while an empty string and / are not. Here we have to implement these two functions.
So as input, if we create a file-system, then create a path using [‘/a’, 1], then after using get(), with parameter [‘/a’], the output will be 1.
To solve this, we will follow these steps −
Define a map d
The createPath method will take path and value, this will act like −
p := list of components of path split by ‘/’
x := d
for i in range 1 to length of p – 1if p[i] is not present in x, then return falsex := x[p[i]][1]
if p[i] is not present in x, then return false
x := x[p[i]][1]
if last element of p is in x, then return false
x[last element of p] := a list with v and empty map
return true
The get() method is taking the path
x := d
p := list of components of path split by ‘/’
for i in range 1 to length of p – 1if p[i] is not present in x, then return -1x := x[p[i]][1]
if p[i] is not present in x, then return -1
x := x[p[i]][1]
if last element of p is in x, then return x[last element of p][0], otherwise return -1
Let us see the following implementation to get a better understanding −
 Live Demo
class FileSystem(object):
   def __init__(self):
      self.d = {}
   def create(self, p, v):
      p = p.split("/")
      x = self.d
      for i in range(1,len(p)-1):
         if p[i] not in x:
            return False
         x = x[p[i]][1]
      if p[-1] in x:
         return False
      x[p[-1]] = [v,{}]
      return True
   def get(self, p):
      x = self.d
      p = p.split("/")
      for i in range(1,len(p)-1):
         if p[i] not in x:
            return -1
         x= x[p[i]][1]
      if p[-1] in x:
         return x[p[-1]][0]
      else:
         return -1
ob = FileSystem()
print(ob.create("/a", 1))
print(ob.get("/a"))
Initialize the object, then call createPath(“/a”, 1) and get(“/a”)
True
1
Replace first occurrence of a character in Java

To replace the first occurrence of a character in Java, use the replaceFirst() method.
Here is our string.
String str = "The Haunting of Hill House!";
Let us replace the first occurrence of character “H”
str.replaceFirst("(?:H)+", "B");
The following is the complete example.
 Live Demo
public class Demo {
    public static void main(String[] args) {
       String str = "The Haunting of Hill House!";
       System.out.println("String: "+str);
       String res = str.replaceFirst("(?:H)+", "B");
       System.out.println("String after replacing a character's first occurrence: "+res);
    }
}
String: The Haunting of Hill House!
String after replacing a character's first occurance: The Baunting of Hill House!
Hidden Bootstrap class

To hide a Bootstrap class, use the .hidden class.
You can try to run the following code to hide a class −
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>Bootstrap Example</title>
      <link href = "/bootstrap/css/bootstrap.min.css" rel = "stylesheet">
      <script src = "/scripts/jquery.min.js"></script>
      <script src = "/bootstrap/js/bootstrap.min.js"></script>
   </head>
   <body>
      <div class = "row" style = "padding: 91px 100px 19px 50px;">
         <div class = "show" style = "left-margin:10px; width:300px; background-color:#ccc;">
            This class is visible.
         </div>
         <div class = "hidden" style = "width:200px; background-color:#ccc;">
            This is an example for hide class. This will be hidden.
         </div>
      </div>
   </body>
</html>
Laravel - Authentication

Authentication is the process of identifying the user credentials. In web applications, authentication is managed by sessions which take the input parameters such as email or username and password, for user identification. If these parameters match, the user is said to be authenticated.
Laravel uses the following command to create forms and the associated controllers to perform authentication −
php artisan make:auth

This command helps in creating authentication scaffolding successfully, as shown in the following screenshot −
The controller which is used for the authentication process is HomeController.
<?php

namespace App\Http\Controllers;

use App\Http\Requests;
use Illuminate\Http\Request;

class HomeController extends Controller{
   /**
      * Create a new controller instance.
      *
      * @return void
   */
   
   public function __construct() {
      $this->middleware('auth');
   }
   
   /**
      * Show the application dashboard.
      *
      * @return \Illuminate\Http\Response
   */
   
   public function index() {
      return view('home');
   }
}
As a result, the scaffold application generated creates the login page and the registration page for performing authentication. They are as shown below −
Laravel uses the Auth façade which helps in manually authenticating the users. It includes the attempt method to verify their email and password.
Consider the following lines of code for LoginController which includes all the functions for authentication −
<?php

// Authentication mechanism
namespace App\Http\Controllers;

use Illuminate\Support\Facades\Auth;

class LoginController extends Controller{
   /**
      * Handling authentication request
      *
      * @return Response
   */
   
   public function authenticate() {
      if (Auth::attempt(['email' => $email, 'password' => $password])) {
      
         // Authentication passed...
         return redirect()->intended('dashboard');
      }
   }
}

    13 Lectures 
     3 hours 

 Sebastian Sulinski

    35 Lectures 
     3.5 hours 

 Antonio Papa

    7 Lectures 
     1.5 hours 

 Sebastian Sulinski

    42 Lectures 
     1 hours 

 Skillbakerystudios

    165 Lectures 
     13 hours 

 Paul Carlo Tordecilla

    116 Lectures 
     13 hours 

 Hafizullah Masoudi
 Print
 Add Notes
 Bookmark this page
How to convert a Date object to LocalDate object in java?

To convert a Date object to LocalDate object in Java −
Convert the obtained date object to an Instant object using the toInstant() method.
Convert the obtained date object to an Instant object using the toInstant() method.
Instant instant = date.toInstant();
Create the ZonedDateTime object using the atZone() method of the Instant class.
Create the ZonedDateTime object using the atZone() method of the Instant class.
ZonedDateTime zone = instant.atZone(ZoneId.systemDefault());
Finally, convert the ZonedDateTime object to the LocalDate object using the toLocalDate() method.
Finally, convert the ZonedDateTime object to the LocalDate object using the toLocalDate() method.
LocalDate givenDate = zone.toLocalDate();
Following example accepts a name and Date of birth from the user in String formats and converts it to LocalDate object and prints it.
 Live Demo
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Date;
import java.util.Scanner;
public class DateToLocalDate {
   public static void main(String args[]) throws ParseException {
      //Reading name and date of birth from the user
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter your name: ");
      String name = sc.next();
      System.out.println("Enter your date of birth (dd-MM-yyyy): ");
      String dob = sc.next();
      //Converting String to Date
      SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
      Date date = formatter.parse(dob);
      //Converting obtained Date object to LocalDate object
      Instant instant = date.toInstant();
      ZonedDateTime zone = instant.atZone(ZoneId.systemDefault());
      LocalDate localDate = zone.toLocalDate();
      System.out.println("Local format of the given date of birth String: "+localDate);
   }
}
Enter your name:
Krishna
Enter your date of birth (dd-MM-yyyy):
26-09-1989
Local format of the given date of birth String: 1989-09-26
8051 Program to Divide two 8 Bit numbers

Now we will see another arithmetic operation. The divide operation to divide two 8-bit numbers using this 8051 microcontroller. The register A and B will be used in this operation. No other registers can be used for division. The result of the division has two parts. The quotient part and the remainder part. Register A will hold Quotient, and register B will hold Remainder.
We are taking two number0EH and 03H at location 20H and 21H, After dividing the result will be stored at location 30H and 31H.  
MOV R0, #20H;set source address 20H to R0
MOV R1, #30H;set destination address 30H to R1

MOV A, @R0;take the first operand from source to register A
INC R0; Point to the next location
MOV B, @R0; take the second operand from source to register B

DIV AB ; Divide A by B

MOV @R1, A; Store Quotient to 30H
INC R1; Increase R1 to point to the next location
MOV @R1, B; Store Remainder to 31H
HALT:   SJMP HALT ;Stop the program
8051 provides DI VAB instruction. By using this instruction, the division can be done. In some other microprocessors like 8085, there was no DIV instruction. In that microprocessor, we need to use repetitive Subtraction operations to get the result of the division. 
When the denominator is00H, the overflow flag OV will be 1. otherwise it is 0 for the division.
Matplotlib - Box Plot

A box plot which is also known as a whisker plot displays a summary of a set of data containing the minimum, first quartile, median, third quartile, and maximum. In a box plot, we draw a box from the first quartile to the third quartile. A vertical line goes through the box at the median. The whiskers go from each quartile to the minimum or maximum.
Let us create the data for the boxplots. We use the numpy.random.normal() function to create the fake data. It takes three arguments, mean and standard deviation of the normal distribution, and the number of values desired.
np.random.seed(10)
collectn_1 = np.random.normal(100, 10, 200)
collectn_2 = np.random.normal(80, 30, 200)
collectn_3 = np.random.normal(90, 20, 200)
collectn_4 = np.random.normal(70, 25, 200)
The list of arrays that we created above is the only required input for creating the boxplot. Using the data_to_plot line of code, we can create the boxplot with the following code −
fig = plt.figure()
# Create an axes instance
ax = fig.add_axes([0,0,1,1])
# Create the boxplot
bp = ax.boxplot(data_to_plot)
plt.show()
The above line of code will generate the following output −

    63 Lectures 
     6 hours 

 Abhilash Nelson

    11 Lectures 
     4 hours 

 DATAhill Solutions Srinivas Reddy

    9 Lectures 
     2.5 hours 

 DATAhill Solutions Srinivas Reddy

    32 Lectures 
     4 hours 

 Aipython

    10 Lectures 
     2.5 hours 

 Akbar Khan

    63 Lectures 
     6 hours 

 Anmol
 Print
 Add Notes
 Bookmark this page
How to find an element using the attribute “name” in Selenium?

We can find an element using the attribute name with Selenium webdriver using the locators - name, css, or xpath. To identify the element with css, the expression should be tagname[name='value'] and the method to be used is By.cssSelector.
To identify the element with xpath, the expression should be //tagname[@name='value']. Then, we have to use the method By.xpath to locate it. To locate an element with a locator name, we have to use the By.name method.
Let us look at the html code of an element with name attribute −
WebElement e = driver. findElement(By.name("q"));
WebElement m = driver. findElement(By.xpath("//input[@name = 'q']"));
WebElement n =
driver. findElement(By.cssSelector("input[name='q']"));
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
public class LocatorName{
   public static void main(String[] args) {
      System.setProperty("webdriver.gecko.driver",
"C:\\Users\\ghs6kor\\Desktop\\Java\\geckodriver.exe");
      WebDriver driver = new FirefoxDriver();
      //implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      //URL launch
      driver.get("https://www.google.com/");
      // identify element with name
      WebElement k = driver.findElement(By.name("q"));
      k.sendKeys("Selenium");
      //identify element with css
      WebElement p = driver.
      findElement(By.cssSelector("input[name='q']"));
      String st = p.getAttribute("value");
      System.out.println("Attribute value: " + st);
      //identify element with xpath
      WebElement o = driver.
      findElement(By.xpath("//input[@name='q']"));

      o.clear();
      driver.quit();
   }
}
Java String isEmpty() method with example - GeeksforGeeks

04 Dec, 2018
Java.lang.String.isEmpty() String method checks whether a String is empty or not. This method returns true if the given string is empty, else it returns false. The isEmpty() method of String class is included in java string since JDK 1.6. In other words, you can say that this method returns true if the length of the string is 0.Examples:
Input String1 : Hello_Gfg
Input String2 :
Output for String1 : false
Output for String2 : true

Syntax:
public boolean isEmpty()
Returns : true if the length of the string is 0.
// Java program to demonstrate working of // isEmpty() methodclass Gfg {    public static void main(String args[])    {        // non-empty string        String str1 = "Hello_Gfg";          // empty string        String str2 = "";          // prints false        System.out.println(str1.isEmpty());          // prints true        System.out.println(str2.isEmpty());    }}
Output:
false
true

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.
Comments
Old Comments
Initialize an ArrayList in Java
Overriding in Java
Multidimensional Arrays in Java
LinkedList in Java
PriorityQueue in Java
How to iterate any Map in Java
ArrayList in Java
Queue Interface In Java
Stack Class in Java
Object Oriented Programming (OOPs) Concept in Java
Java String split() method example.

The split(String regex, int limit) method of the String class. splits the current string around matches of the given regular expression.
The array returned by this method contains each substring of this string that is terminated by another substring that matches the given expression or is terminated by the end of the string.
If the expression does not match any part of the input then the resulting array has just one element, namely this string.
Live Demo
import java.lang.*;
public class StringDemo {
   public static void main(String[] args) {
      String str = "a d, m, i.n";
      String delimiters = "\\s+|,\\s*|\\.\\s*";

      //analysing the string
      String[] tokensVal = str.split(delimiters);

      //prints the count of tokens
      System.out.println("Count of tokens = " + tokensVal.length);

      for(String token : tokensVal) {
         System.out.print(token);
      }
      //analysing the string with limit as 3
      tokensVal = str.split(delimiters, 3);

      //prints the count of tokens
      System.out.println("\nCount of tokens = " + tokensVal.length);
      for(String token : tokensVal) {
         System.out.print(token);
      }
   }
}
Count of tokens = 5
admin
Count of tokens = 3
adm, i.n
C - Array of pointers

Before we understand the concept of arrays of pointers, let us consider the following example, which uses an array of 3 integers −
#include <stdio.h>
 
const int MAX = 3;
 
int main () {

   int  var[] = {10, 100, 200};
   int i;
 
   for (i = 0; i < MAX; i++) {
      printf("Value of var[%d] = %d\n", i, var[i] );
   }
   
   return 0;
}
When the above code is compiled and executed, it produces the following result −
Value of var[0] = 10
Value of var[1] = 100
Value of var[2] = 200

There may be a situation when we want to maintain an array, which can store pointers to an int or char or any other data type available. Following is the declaration of an array of pointers to an integer −
int *ptr[MAX];

It declares ptr as an array of MAX integer pointers. Thus, each element in ptr, holds a pointer to an int value. The following example uses three integers, which are stored in an array of pointers, as follows −
#include <stdio.h>
 
const int MAX = 3;
 
int main () {

   int  var[] = {10, 100, 200};
   int i, *ptr[MAX];
 
   for ( i = 0; i < MAX; i++) {
      ptr[i] = &var[i]; /* assign the address of integer. */
   }
   
   for ( i = 0; i < MAX; i++) {
      printf("Value of var[%d] = %d\n", i, *ptr[i] );
   }
   
   return 0;
}
When the above code is compiled and executed, it produces the following result −
Value of var[0] = 10
Value of var[1] = 100
Value of var[2] = 200

You can also use an array of pointers to character to store a list of strings as follows −
#include <stdio.h>
 
const int MAX = 4;
 
int main () {

   char *names[] = {
      "Zara Ali",
      "Hina Ali",
      "Nuha Ali",
      "Sara Ali"
   };
   
   int i = 0;

   for ( i = 0; i < MAX; i++) {
      printf("Value of names[%d] = %s\n", i, names[i] );
   }
   
   return 0;
}
When the above code is compiled and executed, it produces the following result −
Value of names[0] = Zara Ali
Value of names[1] = Hina Ali
Value of names[2] = Nuha Ali
Value of names[3] = Sara Ali

 Print
 Add Notes
 Bookmark this page
Next.js - CLI

NEXT.JS provides a CLI to start, build and export application. It can be invoked using npx which comes npm 5.2 onwards.
To get list of CLI commands and help on them, type the following command.
npx next -h
   Usage
      $ next <command>

   Available commands
      build, start, export, dev, telemetry

   Options
      --version, -v   Version number
      --help, -h      Displays this message

   For more information run a command with the --help flag
      $ next build --help
Type the following command.
npx next build
info  - Loaded env from D:\Node\nextjs\.env.local
Creating an optimized production build

Compiled successfully.

Automatically optimizing pages

Page                                                           Size     First Load JS
+ ? /                                                          2.25 kB        60.3 kB
+   /_app                                                      288 B          58.1 kB
+        /404                                                       3.25 kB   61.3 kB
+ ? /api/user
+ ? /posts/[id]                                                312 B          61.6 kB
+   + /posts/one
+   + /posts/two
+ ? /posts/env                                                 2.71 kB        60.8 kB
+ ? /posts/first                                               374 B          61.7 kB
+ First Load JS shared by all                                  58.1 kB
  + static/pages/_app.js                                       288 B
  + chunks/ab55cb957ceed242a750c37a082143fb9d2f0cdf.a1a019.js  10.5 kB
  + chunks/framework.c6faae.js                                 40 kB
  + runtime/main.60464f.js                                     6.54 kB
  + runtime/webpack.c21266.js                                  746 B
  + css/9706b5b8ed8e82c0fba0.css                               175 B

?  (Server)  server-side renders at runtime (uses getInitialProps or getServerSideProps)
          (Static)  automatically rendered as static HTML (uses no initial props)
?  (SSG)     automatically generated as static HTML + JSON (uses getStaticProps)
Type the following command.
npx next dev

ready - started server on http://localhost:3000
info  - Loaded env from D:\Node\nextjs\.env.local
event - compiled successfully

Type the following command.
npx next start

info  - Loaded env from \Node\nextjs\.env.local
ready - started server on http://localhost:3000

 Print
 Add Notes
 Bookmark this page
How we can translate Python dictionary into C++?

A python dictionary is a Hashmap. You can use the map data structure in C++ to mimic the behavior of a python dict. You can use map in C++ as follows:
#include <iostream>
#include <map>
using namespace std;
int main(void) {
   /* Initializer_list constructor */
   map<char, int> m1 = {
      {'a', 1},
      {'b', 2},
      {'c', 3},
      {'d', 4},
      {'e', 5}
   };
   cout << "Map contains following elements" << endl;
   for (auto it = m1.begin(); it != m1.end(); ++it)
   cout << it->first << " = " << it->second << endl;
   return 0;
}
This will give the output
The map contains following elements
a = 1
b = 2
c = 3
d = 4
e = 5
Note that this map is equivalent to the python dict:
m1 = {
   'a': 1,
   'b': 2,
   'c': 3,
   'd': 4,
   'e': 5
}
How can I clear text of a textbox using Python Selenium WebDriver?

We can clear text of a textbox with Selenium webdriver in Python using the clear method. First of all, we have to identify the text box with the help of any of the locators like id, css, name, class, xpath, css, or class.
Then we have to enter text into it with the help of the send_keys method. Finally, to clear it we have to use the clear method. We can verify if the text has been cleared with the help of the get_attribute method.
l = driver.find_element_by_id('txt')
l.clear()
Let us try to clear the text from the below edit box.
from selenium import webdriver
#set chromodriver.exe path
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
#implicit wait
driver.implicitly_wait(0.5)
#maximize browser
driver.maximize_window()
#launch URL
driver.get("https://www.tutorialspoint.com/tutor_connect/index.php")
#identify element
l = driver.find_element_by_id("txtSearchText")
l.send_keys("Selenium")
#get value entered
s= l.get_attribute("value")
print("Value after entering text: ")
print(s)
#clear text
l.clear()
t= l.get_attribute("value")
print("Value after clearing text: ")
print(t)
#close browser
driver.close()
Consecutive Numbers Sum in C++

Suppose we have a positive integer N, we have to find how many different ways can we write it as a sum of consecutive positive integers?
So, if the input is like 10, then the output will be 3, this is because we can represent 10 as 5 + 5 and 7 + 3, so there are two different ways.
To solve this, we will follow these steps −
ret := 1
ret := 1
for initialize i := 2, (increase i by 1), do −sum := (i * (i + 1)) / 2if sum > N, then −Come out from the looprem := N - sumret := ret + (1 when rem mod i is 0, otherwise 0)
for initialize i := 2, (increase i by 1), do −
sum := (i * (i + 1)) / 2
sum := (i * (i + 1)) / 2
if sum > N, then −Come out from the loop
if sum > N, then −
Come out from the loop
Come out from the loop
rem := N - sum
rem := N - sum
ret := ret + (1 when rem mod i is 0, otherwise 0)
ret := ret + (1 when rem mod i is 0, otherwise 0)
return ret
return ret
Let us see the following implementation to get better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   int consecutiveNumbersSum(int N) {
      int ret = 1;
      for(int i = 2; ; i++){
         int sum = (i * (i + 1)) / 2;
         if(sum > N) break;
         int rem = N - sum; ret += (rem % i == 0);
      }
      return ret;
   }
}; main(){
   Solution ob;cout << (ob.consecutiveNumbersSum(10));
}
10
2
MariaDB - PHP Syntax

MariaDB partners well with a wide variety of programming languages and frameworks such as PHP, C#, JavaScript, Ruby on Rails, Django, and more. PHP remains the most popular of all available languages due to its simplicity and historical footprint. This guide will focus on PHP partnered with MariaDB.
PHP provides a selection of functions for working with the MySQL database. These functions perform tasks like accessing it or performing operations, and they are fully compatible with MariaDB. Simply call these functions as you would call any other PHP function.
The PHP functions you will use for MariaDB conform to the following format −
mysql_function(value,value,...);

The second part of the function specifies its action. Two of the functions used in this guide are as follows −
mysqli_connect($connect);
mysqli_query($connect,"SQL statement");

The following example demonstrates the general syntax of a PHP call to a MariaDB function −
<html>
   <head>
      <title>PHP and MariaDB</title>
   </head>

   <body>
      <?php
         $retval = mysql_function(value, [value,...]);
      
         if( !$retval ) {
            die ( "Error: Error message here" );
         }
         // MariaDB or PHP Statements
      ?>
   </body>
</html>
In the next section, we will examine essential MariaDB tasks, using PHP functions.
 Print
 Add Notes
 Bookmark this page
C Program for Basic Euclidean algorithms?

Here we will see the Euclidean algorithm to find the GCD of two numbers. The GCD (Greatest Common Divisor) can easily be found using Euclidean algorithm. There are two different approach. One is iterative, another one is recursive. Here we are going to use the recursive Euclidean algorithm.
begin
   if a is 0, then
      return b
   end if
   return gcd(b mod a, a)
end
 Live Demo
#include<iostream>
using namespace std;
int euclideanAlgorithm(int a, int b) {
   if (a == 0)
      return b;
   return euclideanAlgorithm(b%a, a);
}
main() {
   int a, b;
   cout << "Enter two numbers: ";
   cin >> a >> b;
   cout << "GCD " << euclideanAlgorithm(a, b);
}
Enter two numbers: 12 16
GCD 4
Swift - Continue Statement

The continue statement in Swift 4 tells a loop to stop what it is doing and start again at the beginning of the next iteration through the loop.
For a for loop, the continue statement causes the conditional test and increments the portions of the loop to execute. For while and do...while loops, the continue statement causes the program control to pass to the conditional tests.
The syntax for a continue statement in Swift 4 is as follows −
continue

var index = 10

repeat {
   index = index + 1
   if( index == 15 ){
      continue
   }
   print( "Value of index is \(index)")
} while index < 20
When the above code is compiled and executed, it produces the following result −
Value of index is 11
Value of index is 12
Value of index is 13
Value of index is 14
Value of index is 16
Value of index is 17
Value of index is 18
Value of index is 19
Value of index is 20


    38 Lectures 
     1 hours 

 Ashish Sharma

    13 Lectures 
     2 hours 

 Three Millennials

    7 Lectures 
     1 hours 

 Three Millennials

    22 Lectures 
     1 hours 

 Frahaan Hussain

    12 Lectures 
     39 mins

 Devasena Rajendran

    40 Lectures 
     2.5 hours 

 Grant Klimaytys
 Print
 Add Notes
 Bookmark this page
Check if all rows of a matrix are circular rotations of each other in Python

Suppose, we are provided with a matrix of the size n*n, containing integer numbers. We have to find out if all the rows of that matrix are circular rotations of its previous row. In case of first row, it should be a circular rotation of the n-th row.
So, if the input is like
then the output will be True.
To solve this, we will follow these steps −
concat := blank string
for i in range 0 to number of rows, doconcat := concat concatenate "-" concatenate matrix[0,i]
concat := concat concatenate "-" concatenate matrix[0,i]
concat := concat concatenate concat
for i in range 1 to size of matrix, docurr_row := blank stringfor j in range 0 to number of columns, docurr_row := curr_row concatenate "-" concatenate matrix[i,j]if curr_row is present in string concat, thenreturn True
curr_row := blank string
for j in range 0 to number of columns, docurr_row := curr_row concatenate "-" concatenate matrix[i,j]
curr_row := curr_row concatenate "-" concatenate matrix[i,j]
if curr_row is present in string concat, thenreturn True
return True
return False
Let us see the following implementation to get better understanding −
 Live Demo
def solve(matrix) :
   concat = ""
   for i in range(len(matrix)) :
      concat = concat + "-" + str(matrix[0][i])
   concat = concat + concat
   for i in range(1, len(matrix)) :
      curr_row = ""
      for j in range(len(matrix[0])) :
         curr_row = curr_row + "-" + str(matrix[i][j])
      if (concat.find(curr_row)) :
         return True
   return False
matrix = [['B', 'A', 'D', 'C'],
         ['C', 'B', 'A', 'D'],
         ['D', 'C', 'B', 'A'],
         ['A', 'D', 'C', 'B']]
print(solve(matrix))
[['B', 'A', 'D', 'C'],
['C', 'B', 'A', 'D'],
['D', 'C', 'B', 'A'],
['A', 'D', 'C', 'B']]
True
Rebuilding indexes in MongoDB?

To rebuild indexes, use reIndex(). Let us first create an index. Following is the query −
> db.demo42.createIndex({"StudentFirstName":1});
This will produce the following output −
{
   "createdCollectionAutomatically" : true,
   "numIndexesBefore" : 1,
   "numIndexesAfter" : 2,
   "ok" : 1
}
Following is the query to rebuild index in MongoDB −
> db.demo42.reIndex({"StudentFirstName":1});
This will produce the following output −
{
   "nIndexesWas" : 2,
   "nIndexes" : 2,
   "indexes" : [
      {
         "v" : 2,
         "key" : {
            "_id" : 1
         },
         "name" : "_id_",
         "ns" : "web.demo42"
      },
      {
         "v" : 2,
         "key" : {
            "StudentFirstName" : 1
         },
         "name" : "StudentFirstName_1",
         "ns" : "web.demo42"
      }
  ],
   "ok" : 1
}
FTP protocol client in Python

The all important The FTP class in ftplib module implements the client side of the FTP protocol.
To establish connection with a FTP server, obtain FTP object.
The FTP class supports following methods −
Connect to the given host and port. The default port number is 21, as specified by the FTP protocol specification.
Return the welcome message sent by the server in reply to the initial connection.
login(user='anonymous', passwd='', acct='')
Log in as the given user. The passwd and acct parameters are optional and default to the empty string. If no user is specified, it defaults to 'anonymous'. If user is 'anonymous', the default passwd is 'anonymous@'.
Abort a file transfer that is in progress.
Retrieve a file in binary transfer mode. cmd should be an appropriate RETR command: 'RETR filename'.
Store a file in binary transfer mode. cmd should be an appropriate STOR command: "STOR filename". fp is a file object (opened in binary mode) which is read until EOF using its read() method
Produce a directory listing as returned by the LIST command, printing it to standard output.
Remove the file named filename from the server.
Set the current directory on the server.
Create a new directory on the server.
Return the pathname of the current directory on the server.
Remove the directory named dirname on the server.
Request the size of the file named filename on the server. On success, the size of the file is returned as an integer, otherwise None is returned. Note that the SIZE command is not standardized, but is supported by many common server implementations.
Send a QUIT command to the server and close the connection.
Following example establishes anonymous connection with a server, downloads a file to local folder and uploads a local file.
from ftplib import FTP
import os
def downloadFile():
   filename = 'README.MIRRORS'
   localfile = open(filename, 'wb')
   ftp.retrbinary('RETR ' + filename, localfile.write, 1024)
   ftp.quit()
   localfile.close()
def uploadFile():
   filename = '/home/malhar/file.txt'
   ftp.storbinary('STOR '+filename, open(filename, 'rb'))
   ftp.quit()
with FTP("ftp1.at.proftpd.org") as ftp:
   ftp.login()
   ftp.getwelcome()
   ftp.dir()
   downloadFile()
   uploadFile()
C++ Program for Recursive Bubble Sort?

In this section we will see another approach of famous bubble sort technique. We have used bubble sort in iterative manner. But here we will see recursive approach of the bubble sort. The recursive bubble sort algorithm is look like this.
begin
   if n = 1, return
   for i in range 1 to n-2, do
      if arr[i] > arr[i+1], then
         exchange arr[i] and arr[i+1]
      end if
   done
   bubbleRec(arr, n-1)
end
 Live Demo
#include<iostream>
using namespace std;
void recBubble(int arr[], int n){
   if (n == 1)
      return;
   for (int i=0; i<n-1; i++) //for each pass p
      if (arr[i] > arr[i+1]) //if the current element is greater than next one
   swap(arr[i], arr[i+1]); //swap elements
   recBubble(arr, n-1);
}
main() {
   int data[] = {54, 74, 98, 154, 98, 32, 20, 13, 35, 40};
   int n = sizeof(data)/sizeof(data[0]);
   cout << "Sorted Sequence ";
   recBubble(data, n);
   for(int i = 0; i <n;i++){
      cout << data[i] << " ";
   }
}
Sorted Sequence 13 20 32 35 40 54 74 98 98 154
Set upper_bound() function in C++ STL

In this article we are going to discuss the set::upper_bound() in C++ STL, their syntax, working and their return values.
Sets in C++ STL are the containers which must have unique elements in a general order. Sets must have unique elements because the value of the element identifies the element. Once added a value in set container later can’t be modified, although we can still remove or add the values to the set. Sets are used as binary search trees.
upper_bound() is an inbuilt function in C++ STL which is declared in <set> header file. upper_bound() returns an iterator to the upper bound of the value whose upper bound we wish to find. The function returns iterator pointing to the immediate next element of the value whose upper bound we wish to find.
name_of_set.upper_bound(const type_t& value);
This function accepts a parameter, i.e. The value whose upper bound is to be found.
This function returns an iterator pointing to the immediate next element which is greater than the value
Input: set<int> myset = {1, 2, 3, 4, 5};
   Myset.upper_bound(3);
Output: Upper bound = 4
 Live Demo
#include <bits/stdc++.h>
using namespace std;
int main(){
   set<int> Set;
   Set.insert(9);
   Set.insert(7);
   Set.insert(5);
   Set.insert(3);
   Set.insert(1);
   cout<<"Elements are : ";
   for (auto i = Set.begin(); i!= Set.end(); i++)
      cout << *i << " ";
   auto i = Set.upper_bound(5);
   cout <<"\nupper bound of 5 in the set is: ";
   cout << (*i) << endl;
   i = Set.upper_bound(1);
   cout<<"upper bound of 1 in the set is: ";
   cout << (*i) << endl;
   return 0;
}
If we run the above code it will generate the following output −
upper bound of 5 in the set is: 7
upper bound of 1 in the set is: 3
 Live Demo
#include <iostream>
#include <set>
int main (){
   std::set<int> Set;
   std::set<int>::iterator one, end;
   for (int i=1; i<10; i++)
   Set.insert(i*10);
   one = Set.lower_bound (20);
   end = Set.upper_bound (40);
   Set.erase(one , end); // 10 20 70 80 90
   std::cout<<"Elements are: ";
   for (std::set<int>::iterator i = Set.begin(); i!=Set.end(); ++i)
      std::cout << ' ' << *i;
   std::cout << '\n';
   return 0;
}
If we run the above code it will generate the following output −
Elements are : 10 50 60 70 80 90