code-rag-bench/online-tutorials huggingface dataset:
fseek() vs rewind() in C

fseek() in C language is used to move file pointer to a specific position. Offset and stream are the destination of pointer, given in the function parameters. If successful, it returns zero, else non-zero value is returned.
Here is the syntax of fseek() in C language,
int fseek(FILE *stream, long int offset, int whence)
Here are the parameters used in fseek(),
stream − This is the pointer to identify the stream.
stream − This is the pointer to identify the stream.
offset − This is the number of bytes from the position.
offset − This is the number of bytes from the position.
whence − This is the position from where offset is added.
whence − This is the position from where offset is added.
whence is specified by one of the following constants.
SEEK_END − End of file.
SEEK_END − End of file.
SEEK_SET − Starting of file.
SEEK_SET − Starting of file.
SEEK_CUR − Current position of file pointer.
SEEK_CUR − Current position of file pointer.
Here is an example of fseek() in C language −
Let’s say we have “demo.txt” file with the following content −
This is demo text!
This is demo text!
This is demo text!
This is demo text!
Now let us see the code.
#include<stdio.h>
void main() {
   FILE *f;
   f = fopen("demo.txt", "r");
   if(f == NULL) {
      printf("\n Can't open file or file doesn't exist.");
      exit(0);
   }
   fseek(f, 0, SEEK_END);
   printf("The size of file : %ld bytes", ftell(f));
   getch();
}
The size of file : 78 bytes
In the above program, file “demo.txt” is opened using fopen() and fseek() function is used to move the pointer to the end of the file.
f = fopen("demo.txt", "r");
if(f == NULL) {
   printf("\n Can't open file or file doesn't exist.");
   exit(0);
}
fseek(f, 0, SEEK_END);
The function rewind() is used to set the position of file to the beginning of given stream. It does not return any value.
Here is the syntax of rewind() in C language,
void rewind(FILE *stream);
Here is an example of rewind() in C language,
Let’s say we have “new.txt” file with the following content −
This is demo!
This is demo!
Now, let us see the example.
#include<stdio.h>
void main() {
   FILE *f;
   f = fopen("new.txt", "r");
   if(f == NULL) {
      printf("\n Can't open file or file doesn't exist.");
      exit(0);
   }
   rewind(f);
   fseek(f, 0, SEEK_END);
   printf("The size of file : %ld bytes", ftell(f));
   getch();
}
The size of file : 28 bytes
In the above program, file is opened by using fopen() and if pointer variable is null, it will display can’t open file or file doesn’t exist. The function rewind() is moving the pointer to the starting of file.
f = fopen("new.txt", "r");
if(f == NULL) {
   printf("\n Can't open file or file doesn't exist.");
   exit(0);
}
rewind(f);
Get the count of elements in HashMap in Java

Use the size() method to get the count of elements.
Let us first create a HashMap and add elements −
HashMap hm = new HashMap();
// Put elements to the map
hm.put("Maths", new Integer(98));
hm.put("Science", new Integer(90));
hm.put("English", new Integer(97));
Now, get the size −
hm.size()
The following is an example to get the count of HashMap elements −
 Live Demo
import java.util.*;
public class Demo {
   public static void main(String args[]) {
      // Create a hash map
      HashMap hm = new HashMap();
      // Put elements to the map
      hm.put("Maths", new Integer(98));
      hm.put("Science", new Integer(90));
      hm.put("English", new Integer(97));
      hm.put("Physics", new Integer(91));
      hm.put("Chemistry", new Integer(93));
      // Get a set of the entries
      Set set = hm.entrySet();
      // Get an iterator
      Iterator i = set.iterator();
      // Display elements
      while(i.hasNext()) {
         Map.Entry me = (Map.Entry)i.next();
         System.out.print(me.getKey() + ": ");
         System.out.println(me.getValue());
      }
      System.out.println();
      System.out.println("Count of elements = "+hm.size());
   }
}
Maths: 98
English: 97
Chemistry: 93
Science: 90
Physics: 91
Size: 5
MySQL query to get the next number in sequence for AUTO_INCREMENT field?

Let us first create a table −
mysql> create table DemoTable
-> (
-> Id int NOT NULL AUTO_INCREMENT,
-> PRIMARY KEY(Id)
-> );
Query OK, 0 rows affected (0.58 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values();
Query OK, 1 row affected (0.19 sec)

mysql> insert into DemoTable values();
Query OK, 1 row affected (0.11 sec)

mysql> insert into DemoTable values();
Query OK, 1 row affected (0.12 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+----+
| Id |
+----+
| 1  |
| 2  |
| 3  |
+----+
3 rows in set (0.00 sec)
Following is the query to get the next number in sequence for AUTO_INCREMENT field −
mysql> SELECT auto_increment FROM information_schema.tables WHERE table_name='DemoTable';
This will produce the following output −
+----------------+
| AUTO_INCREMENT |
+----------------+
| 4              |
+----------------+
1 row in set (0.26 sec)
How to separate date and time in R ? - GeeksforGeeks

29 Jun, 2021
In this article, we are going to separate date and time in R Programming Language.  Date-time is in the format of date and time (YYYY/MM/DD HH:MM:SS- year/month/day Hours:Minute:Seconds). 
Extracting date from timestamp: We are going to extract date by using as.Date() function.
Syntax:
 as.Date(data)
where data is the time stamp.
Extracting time from the time stamp: We can do this by using as.POSIXct() function. To get a particular time hour format we can use the format() function
Syntax:
format(as.POSIXct(data), format = “%H:%M”)
Where,
as.POSIXct() is used to extract time from the time stamp
format is used to get the time format. Ex : hours:Minutes and seconds
data is the time stamp
Example 1:
R
# create variable with one time stamp data ="2021/05/25 12:34:25"                             # extract date from the time stampprint( as.Date(data))  # get time from date using format in # the form of hours and  minutes print( format(as.POSIXct(data), format = "%H:%M"))
Output:
Example 2: 
R
# create variable with one time stamp data ="2021/05/25 12:34:25"                             # extract date from the time stampprint( as.Date(data))    # get time from date using format in the # form of hours ,minutes  and secondsprint( format(as.POSIXct(data), format = "%H:%M:%S"))
Output:
Example 3:
R
# create data  with five time stamps data = c("2021/05/25 12:34:25",         "2019/1/14 04:10:30",         "2020/7/11 09:05:05",         "2018/1/14 04:10:30",         "2017/7/11 09:05:05")                             # extract date from the time stampprint( as.Date(data))  # get time from date using format in the# form of hours ,minutes  and secondsprint( format(as.POSIXct(data), format = "%H:%M:%S"))
Output:
Picked
R-DateTime
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
R - if statement
How to filter R dataframe by multiple conditions?
Plot mean and standard deviation using ggplot2 in R
Time Series Analysis in R
Java Examples - Replace an element in a list

How to replace an element in a list
Following example uses replaceAll() method to replace all the occurance of an element with a different element in a list.
import java.util.*;

public class Main {
   public static void main(String[] args) {
      List list = Arrays.asList("one Two three Four five six one three Four".split(" "));
      System.out.println("List :"+list);
      Collections.replaceAll(list, "one", "hundread");
      System.out.println("replaceAll: " + list);
   }
}
The above code sample will produce the following result.
List :[one, Two, three, Four, five, six, one, three, Four]
replaceAll: [hundread, Two, three, Four, five, six, hundread, three, Four]

 Print
 Add Notes
 Bookmark this page
Difference between TreeMap, HashMap, and LinkedHashMap in Java

HashMap, TreeMap and LinkedHashMap all implements java.util.Map interface and following are their characteristics.
HashMap has complexity of O(1) for insertion and lookup.
HashMap has complexity of O(1) for insertion and lookup.
HashMap allows one null key and multiple null values.
HashMap allows one null key and multiple null values.
HashMap does not maintain any order.
HashMap does not maintain any order.
TreeMap has complexity of O(logN) for insertion and lookup.
TreeMap has complexity of O(logN) for insertion and lookup.
TreeMap does not allow null key but allow multiple null values.
TreeMap does not allow null key but allow multiple null values.
TreeMap maintains order. It stores keys in sorted and ascending order.
TreeMap maintains order. It stores keys in sorted and ascending order.
LinkedHashMap has complexity of O(1) for insertion and lookup.
LinkedHashMap has complexity of O(1) for insertion and lookup.
LinkedHashMap allows one null key and multiple null values.
LinkedHashMap allows one null key and multiple null values.
LinkedHashMap maintains order in which key-value pairs are inserted.
LinkedHashMap maintains order in which key-value pairs are inserted.
import java.util.HashMap;
import java.util.Hashtable;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.TreeMap;

public class Tester {
   public static void main(String args[]) {

      Map<String, String> map = new HashMap<String, String>();
      map.put("One", "1");
      map.put("Five", "5");
      map.put("Four", "4");
      map.put("Two", "2");
      map.put("Three", "3");
      System.out.println("HashMap: \n" + map);

      Map<String, String> map1 = new LinkedHashMap<String, String>();
      map1.put("One", "1");
      map1.put("Five", "5");
      map1.put("Four", "4");
      map1.put("Two", "2");
      map1.put("Three", "3");
      System.out.println("LinkedHashMap: \n" + map1);

      Map<String, String> map2 = new TreeMap<String, String>();
      map2.put("One", "1");
      map2.put("Five", "5");
      map2.put("Four", "4");
      map2.put("Two", "2");
      map2.put("Three", "3");
      System.out.println("TreeMap: \n" + map2);
   }
}
HashMap:
{Five = 5, One = 1, Four = 4, Two = 2, Three = 3}
LinkedHashMap:
{One = 1, Five = 5, Four = 4, Two = 2, Three = 3}
TreeMap:
{Five = 5, Four = 4, One = 1, Three = 3, Two = 2}
Here you see, HashMap has random order of Keys, LinkedHashMap has preserved the order in which keys are inserted and TreeMap has sorted order of keys.
Program to find length of contiguous strictly increasing sublist in Python

Suppose we have a list of numbers called nums, we have to find the maximum length of a contiguous strictly increasing sublist when we can remove one or zero elements from the list.
So, if the input is like nums = [30, 11, 12, 13, 14, 15, 18, 17, 32], then the output will be 7, as when we remove 18 in the list we can get [11, 12, 13, 14, 15, 17, 32] which is the longest, contiguous, strictly increasing sublist, and its length is 7.
To solve this, we will follow these steps−
n := size of nums
n := size of nums
pre := a list of size n and fill with 1s
pre := a list of size n and fill with 1s
for i in range 1 to n - 1, doif nums[i] > nums[i - 1], thenpre[i] := pre[i - 1] + 1
for i in range 1 to n - 1, do
if nums[i] > nums[i - 1], thenpre[i] := pre[i - 1] + 1
if nums[i] > nums[i - 1], then
pre[i] := pre[i - 1] + 1
pre[i] := pre[i - 1] + 1
suff := a list of size n and fill with 1s
suff := a list of size n and fill with 1s
for i in range n - 2 to -1, decrease by 1, doif nums[i] < nums[i + 1], thensuff[i] := suff[i + 1] + 1
for i in range n - 2 to -1, decrease by 1, do
if nums[i] < nums[i + 1], thensuff[i] := suff[i + 1] + 1
if nums[i] < nums[i + 1], then
suff[i] := suff[i + 1] + 1
suff[i] := suff[i + 1] + 1
ans := maximum value of maximum of pre and maximum of suff
ans := maximum value of maximum of pre and maximum of suff
for i in range 1 to n - 1, doif nums[i - 1] < nums[i + 1], thenans := maximum of ans and (pre[i - 1] + suff[i + 1])
for i in range 1 to n - 1, do
if nums[i - 1] < nums[i + 1], thenans := maximum of ans and (pre[i - 1] + suff[i + 1])
if nums[i - 1] < nums[i + 1], then
ans := maximum of ans and (pre[i - 1] + suff[i + 1])
ans := maximum of ans and (pre[i - 1] + suff[i + 1])
return ans
return ans
Let us see the following implementation to get better understanding −
 Live Demo
class Solution:
   def solve(self, nums):
      n = len(nums)
      pre = [1] * n
      for i in range(1, n - 1):
         if nums[i] > nums[i - 1]:
            pre[i] = pre[i - 1] + 1
      suff = [1] * n
      for i in range(n - 2, -1, -1):
         if nums[i] < nums[i + 1]:
            suff[i] = suff[i + 1] + 1
               ans = max(max(pre), max(suff))
               for i in range(1, n - 1):
                  if nums[i - 1] < nums[i + 1]:
                     ans = max(ans, pre[i - 1] + suff[i + 1])
               return ans
ob = Solution()
nums = [30, 11, 12, 13, 14, 15, 18, 17, 32]
print(ob.solve(nums))
[30, 11, 12, 13, 14, 15, 18, 17, 32]
7
Python Pandas - Environment Setup

Standard Python distribution doesn't come bundled with Pandas module. A lightweight alternative is to install NumPy using popular Python package installer, pip.
pip install pandas

If you install Anaconda Python package, Pandas will be installed by default with the following −
Anaconda (from https://www.continuum.io) is a free Python distribution for SciPy stack. It is also available for Linux and Mac.
Anaconda (from https://www.continuum.io) is a free Python distribution for SciPy stack. It is also available for Linux and Mac.
Canopy (https://www.enthought.com/products/canopy/) is available as free as well as commercial distribution with full SciPy stack for Windows, Linux and Mac.
Canopy (https://www.enthought.com/products/canopy/) is available as free as well as commercial distribution with full SciPy stack for Windows, Linux and Mac.
Python (x,y) is a free Python distribution with SciPy stack and Spyder IDE for Windows OS. (Downloadable from http://python-xy.github.io/)
Python (x,y) is a free Python distribution with SciPy stack and Spyder IDE for Windows OS. (Downloadable from http://python-xy.github.io/)
Package managers of respective Linux distributions are used to install one or more packages in SciPy stack.
For Ubuntu Users
sudo apt-get install python-numpy python-scipy python-matplotlibipythonipythonnotebook
python-pandas python-sympy python-nose

For Fedora Users
sudo yum install numpyscipy python-matplotlibipython python-pandas sympy
python-nose atlas-devel


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
Performing mathematical operations in MySQL IF then ELSE is possible?

For performing mathematical operations and working with conditions, you can consider CASE statement. Let us first create a table −
mysql> create table DemoTable
   (
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   FruitName varchar(100),
   FruitPrice int
   );
Query OK, 0 rows affected (0.26 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable(FruitName,FruitPrice) values('Orange',250);
Query OK, 1 row affected (0.10 sec)

mysql> insert into DemoTable(FruitName,FruitPrice) values('Banana',100);
Query OK, 1 row affected (0.05 sec)

mysql> insert into DemoTable(FruitName,FruitPrice) values('Apple',150);
Query OK, 1 row affected (0.05 sec)

mysql> insert into DemoTable(FruitName,FruitPrice) values('Pomegranate',200);
Query OK, 1 row affected (0.10 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+----+-------------+------------+
| Id | FruitName   | FruitPrice |
+----+-------------+------------+
|  1 | Orange      |        250 |
|  2 | Banana      |        100 |
|  3 | Apple       |        150 |
|  4 | Pomegranate |        200 |
+----+-------------+------------+
4 rows in set (0.19 sec)
Following is the query for CASE statement with mathematical operations −
mysql> select Id,FruitName,FruitPrice,
   case
   when FruitName='Orange'
   then FruitPrice/5
   else FruitPrice
   end as OriginalPrice
   from DemoTable;
This will produce the following output −
+----+-------------+------------+---------------+
| Id | FruitName   | FruitPrice | OriginalPrice |
+----+-------------+------------+---------------+
|  1 | Orange      |        250 |       50.0000 |
|  2 | Banana      |        100 |           100 |
|  3 | Apple       |        150 |           150 |
|  4 | Pomegranate |        200 |           200 |
+----+-------------+------------+---------------+
4 rows in set (0.00 sec)
How to declare a class in Java?

Following is the syntax to declare a class.
class className {
   //Body of the class
}

You can declare a class by writing the name of the next to the class keyword, followed by the flower braces. Within these, you need to define the body (contents) of the class i.e. fields and methods.
To make the class accessible to all (classes) you need to make it public.
public class MyClass {
   //contents of the class (fields and methods)
}
How to disable browser's back button with JavaScript?

To disable web browsers’ back button, try to run the following code. This is the code for current HTML page,
<html>
   <head>
      <title>Disable Browser Back Button</title>
      <script src = "http://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
      <script src = "http://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
   </head>
   
   <body>
      <a href = "newpage.html">Next Page</a>
   </body>
   <script>
      $(document).ready(function() {
         function disablePrev() { window.history.forward() }
         window.onload = disablePrev();
         window.onpageshow = function(evt) { if (evt.persisted) disableBack() }
      });
   </script>
</html>
The following is the code for newpage.html,
<html>
   <body>
      Go to back page using web browser back button.
   </body>
</html>a
Explain reference and pointer in C programming?

Explain the concept of reference and pointer in a c programming language using examples.
It is the alternate name for the variable that we declared.
It is the alternate name for the variable that we declared.
It can be accessed by using pass by value.
It can be accessed by using pass by value.
It cannot hold the null values.
It cannot hold the null values.
datatype *variablename
For example, int *a; //a contains the address of int type variable.
It stores the address of variable.
It stores the address of variable.
We can hold the null values using pointer.
We can hold the null values using pointer.
It can be access by using pass by reference.
It can be access by using pass by reference.
No need of initialization while declaring the variable.
No need of initialization while declaring the variable.
pointer variable= & another variable;
 Live Demo
#include<stdio.h>
int main(){
   int a=2,b=4;
   int *p;
   printf("add of a=%d\n",&a);
   printf("add of b=%d\n",&b);
   p=&a; // p points to variable a
   printf("a value is =%d\n",a); // prints a value
   printf("*p value is =%d\n",*p); //prints a value
   printf("p value is =%d\n",p); //prints the address of a
   p=&b; //p points to variable b
   printf("b value is =%d\n",b); // prints b value
   printf("*p value is =%d\n",*p); //prints b value
   printf("p value is =%d\n",p); //prints add of b
}
add of a=-748899512
add of b=-748899508
a value is =2
*p value is =2
p value is =-748899512
b value is =4
*p value is =4
p value is =-748899508
How to delete elements from an array?

To delete an element at a particular position from an array. Starting from the required position, replace the element in the current position with the element in the next position.
 Live Demo
public class DeletingElementsBySwapping {
public static void main(String args[]) {
int [] myArray = {23, 93, 56, 92, 39};
System.out.println("hello");

int size = myArray.length;
int pos = 2;

for (int i = pos; i<size-1; i++) {
myArray[i] = myArray[i+1];
}

for (int i=0; i<size-1; i++) {
System.out.println(myArray[i]);
}
}
}
hello
23
93
92
39
Apache Commons provides a library named org.apache.commons.lang3 and, following is the maven dependency to add the library to your project.
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.0</version>
</dependency>
</dependencies>
This package provides a class known as ArrayUtils. Using the remove()method of this class instead of swapping elements, you can delete them.
import java.util.Arrays;
import org.apache.commons.lang3.ArrayUtils;

public class DeletingElements {
public static void main(String args[]) {
int [] myArray = {23, 93, 56, 92, 39};
int [] result = ArrayUtils.remove(myArray, 2);
System.out.println(Arrays.toString(result));
}
}
[23, 93, 92, 39]
Diagonal product of a matrix - JavaScript

Suppose, we have a 2-D array representing a square matrix like this −
const arr = [
   [1, 3, 4, 2],
   [4, 5, 3, 5],
   [5, 2, 6, 4],
   [8, 2, 9, 3]
];
We are required to write a function that takes in this array and returns the product of the element present at the principal Diagonal of the matrix.
For this array the elements present at the principal diagonal are −
1, 5, 6, 3
Hence the output should be −
90
Following is the code −
const arr = [
   [1, 3, 4, 2],
   [4, 5, 3, 5],
   [5, 2, 6, 4],
   [8, 2, 9, 3]
];
const diagonalProduct = arr => {
   let product = 1;
   for(let i = 0; i < arr.length; i++){
      for(let j = 0; j < arr[i].length; j++){
         if(i === j){
            product *= arr[i][j];
         };
      };
   };
   return product;
};
console.log(diagonalProduct(arr));
Following is the output in the console −
90
Can we convert MD5 to SHA256 in a MySQL table with user password column?

Use SHA2() to convert the MD5 password to SHA256. It calculates the SHA-2 family of hash functions i.e. SHA-224, SHA-256, SHA-384, and SHA-512).
Let us first create a table −
mysql> create table DemoTable818(UserPassword text);
Query OK, 0 rows affected (0.51 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable818 values(MD5('John_123'));
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable818 values(MD5('999Carol@22'));
Query OK, 1 row affected (0.14 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable818;
This will produce the following output −
+----------------------------------+
| UserPassword                     |
+----------------------------------+
| 47c7d0987db4e59e2264ce9fefce4977 |
| 950aa70edd5b686a807b3bfffdf2248c |
+----------------------------------+
2 rows in set (0.00 sec)
Following is the query to convert MD5 to SHA256 −
mysql> update DemoTable818 set UserPassword=SHA2(UserPassword,256);
Query OK, 2 rows affected (0.19 sec)
Rows matched: 2 Changed: 2 Warnings: 0
Let us check the table records once again −
mysql> select *from DemoTable818;
This will produce the following output −
+------------------------------------------------------------------+
| UserPassword                                                     |
+------------------------------------------------------------------+
| 8b68c46294a9ccb2449324c24fe774f95b7c14e4b56fc51c7f8e6c5b01c7020f |
| 9cc80741546051ae3de7d31246327968c98af3c65125376acb7b49a0760d42a3 |
+------------------------------------------------------------------+
2 rows in set (0.00 sec)
Regular Expression \E Metacharacter in Java.

The subexpression/metacharacter “\E” ends the quoting begun with \Q. i.e. you can escape metacharacters in the regular expressions by placing them in between \Q and \E. For example, the expression [aeiou] matches the strings with vowel letters in it.
 Live Demo
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class SampleProgram {
   public static void main( String args[] ) {
      String regex = "[aeiou]";
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter input string: ");
      String input = sc.nextLine();
      //Creating a Pattern object
      Pattern pattern = Pattern.compile(regex);
      Matcher matcher = pattern.matcher(input);
      if(matcher.find()) {
         System.out.println("Match occurred");
      }else {
         System.out.println("Match not occurred");
      }
   }
}
Enter input string:
sample
Match occurred
But, if you use the same expression with in \Q and \E as \Q[aeiou]\E It matches the same sequence of characters “[aeiou]” in the given string. In short the meta characters loses their meaning and will be treated as normal characters.
 Live Demo
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class SampleProgram {
   public static void main( String args[] ) {
      String regex = "\\Q[aeiou]\\E";
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter input string: ");
      String input = sc.nextLine();
      //Creating a Pattern object
      Pattern pattern = Pattern.compile(regex);
      Matcher matcher = pattern.matcher(input);
      if(matcher.find()) {
         System.out.println("Match occurred");
      } else {
         System.out.println("Match not occurred");
      }
   }
}
Enter input string:
sample
Match not occurred
Enter input string:
The letters [aeiou] are vowels in English alphabet
Match occurred
AsQueryable() in C#

AsQueryable() method is used to get an IQueryable reference.
Let us see an example to find sum of integer values.
Firstly, set an integer array.
var arr = new int[] { 100, 200, 300, 400 };
Now to find the sum, use the Queryable Sum() and AsQueryable() method.
Queryable.Sum(arr.AsQueryable());
The following is the complete code.
 Live Demo
using System;
using System.Linq;
class Demo {
   static void Main() {
      var arr = new int[] { 100, 200, 300, 400 };
      int res = Queryable.Sum(arr.AsQueryable());
      Console.WriteLine("Sum: "+res);
   }
}
Sum: 1000
How to get the IIS Application Pool Recycle settings using PowerShell?

To get the IIS application Pool to recycle settings using GUI, you need to check the Application pool advanced settings.
To retrieve the above settings using PowerShell, we can use the Get-IISAppPool command with the specific application pool name. We have the application pool, DefaultAppPool and we need to retrieve its Recycling settings.
PS C:\> (Get-IISAppPool -Name DefaultAppPool).Recycling
Below settings will be for the Periodic restart.
PS C:\> (Get-IISAppPool -Name DefaultAppPool).Recycling.PeriodicRestart
Memory          : 0
PrivateMemory   : 102400
Requests        : 0
Schedule        : {add}
Time            : 1.05:00:00
Attributes      : {memory, privateMemory, requests, time}
ChildElements   : {schedule}
ElementTagName  : periodicRestart
IsLocallyStored : True
Methods         :
RawAttributes   : {[memory, 0], [privateMemory, 102400], [requests, 0], [time, 1.05:00:00]}
Schema          : Microsoft.Web.Administration.ConfigurationElementSchema
From the further expansion, you can add the Privatememory, Time, etc properties.
Tcl - Variables

In Tcl, there is no concept of variable declaration. Once, a new variable name is encountered, Tcl will define a new variable.
The name of variables can contain any characters and length. You can even have white spaces by enclosing the variable in curly braces, but it is not preferred.
The set command is used for assigning value to a variable. The syntax for set command is,
set variableName value

A few examples of variables are shown below −
#!/usr/bin/tclsh

set variableA 10
set {variable B} test
puts $variableA
puts ${variable B}
When the above code is executed, it produces the following result −
10
test

As you can see in the above program, the $variableName is used to get the value of the variable.
Tcl is a dynamically typed language. The value of the variable can be dynamically converted to the required type when required. For example, a number 5 that is stored as string will be converted to number when doing an arithmetic operation. It is shown below −
#!/usr/bin/tclsh

set variableA "10"
puts $variableA
set sum [expr $variableA +20];
puts $sum
When the above code is executed, it produces the following result −
10
30

As you can see in the above example, expr is used for representing mathematical expression. The default precision of Tcl is 12 digits. In order to get floating point results, we should add at least a single decimal digit. A simple example explains the above.
#!/usr/bin/tclsh

set variableA "10"
set result [expr $variableA / 9];
puts $result
set result [expr $variableA / 9.0];
puts $result
set variableA "10.0"
set result [expr $variableA / 9];
puts $result
When the above code is executed, it produces the following result −
1
1.1111111111111112
1.1111111111111112

In the above example, you can see three cases. In the first case, the dividend and the divisor are whole numbers and we get a whole number as result. In the second case, the divisor alone is a decimal number and in the third case, the dividend is a decimal number. In both second and third cases, we get a decimal number as result.
In the above code, you can change the precision by using tcl_precision special variable. It is shown below −
#!/usr/bin/tclsh

set variableA "10"
set tcl_precision 5
set result [expr $variableA / 9.0];
puts $result
When the above code is executed, it produces the following result −
1.1111

 Print
 Add Notes
 Bookmark this page
match_results prefix() and suffix() in C++

In this article we will be discussing the working, syntax and examples of match_results::prefix() and match_results::suffix() functions in C++ STL.
std::match_results is a specialized container-like class which is used to hold the collection of character sequences which are matched. In this container class a regex match operation finds the matches of the target sequence.
match_results::prefix() function is an inbuilt function in C++ STL, which is defined in <regex> header file. prefix() is used to get the preceding match_results of the object associated with the function. This function returns the reference of the succeeding sequence of the match_results object.
match_results.prefix();
This function accepts no parameter.
This function returns constant reference of the string or sequence preceding the match sequence.
Input: string str = "Tutorials Points";
   regex R("Points");
   smatch Mat;
   regex_search(str, Mat, R);
   Mat.prefix();
Output: Tutorials
 Live Demo
#include <bits/stdc++.h>
using namespace std;
int main() {
   string str = "Tutorials Points";
   regex R("Points");
   smatch Mat;
   regex_search(str, Mat, R);
   cout<<"String prefix is : ";
   if (!Mat.empty()) {
      cout << Mat.prefix();
   }
   return 0;
}
If we run the above code it will generate the following output −
String prefix is : Tutorials
match_results::suffix() function is an inbuilt function in C++ STL, which is defined in <regex> header file. suffix() is used to get the succeeding match_results of the object associated with the function. This function returns the reference of the succeeding sequence of the match_results object.
match_results.suffix();
This function accepts no parameter.
This function returns constant reference of the string or sequence succeeding the match sequence.
Input: std::string str("Tutorials Points is the best");
   std::smatch Mat;
   std::regex re("Points");
   std::regex_match ( str, Mat, re );
   Mat.suffix();
Output: is the best
 Live Demo
#include <bits/stdc++.h>
using namespace std;
int main() {
   string str = "Tutorials Points is the best";
   regex R("Points");
   smatch Mat;
   regex_search(str, Mat, R);
   cout<<"String prefix is : ";
   if (!Mat.empty()) {
      cout << Mat.suffix();
   }
   return 0;
}
If we run the above code it will generate the following output −
String prefix is : is the best
How to separate string and a numeric value in R?

To separate string and a numeric value, we can use strplit function and split the values by passing all type of characters and all the numeric values. For example, if we have a data frame called df that contains a character column Var having concatenated string and numerical values then we can split them using the below command −
strsplit(df$Var,split="(?<=[a-zA-Z])\\s*(?=[0-9])",perl=TRUE)
Consider the below data frame −
 Live Demo
x<-sample(c("india 123","china 232","sudan143","russia326 2"),20,replace=TRUE)
df1<-data.frame(x)
df1
    x
1  sudan143
2  china 232
3  russia326 2
4  sudan143
5  sudan143
6  china 232
7  china 232
8  india 123
9  sudan143
10 china 232
11 india 123
12 russia326 2
13 sudan143
14 russia326 2
15 china 232
16 india 123
17 sudan143
18 india 123
19 china 232
20 china 232
Splitting string and numerical values in column x of df1 −
strsplit(df1$x,split="(?<=[a-zA-Z])\\s*(?=[0-9])",perl=TRUE)
[[1]]
[1] "sudan" "143"
[[2]]
[1] "china" "232"
[[3]]
[1] "russia" "326 2"
[[4]]
[1] "sudan" "143"
[[5]]
[1] "sudan" "143"
[[6]]
[1] "china" "232"
[[7]]
[1] "china" "232"
[[8]]
[1] "india" "123"
[[9]]
[1] "sudan" "143"
[[10]]
[1] "china" "232"
[[11]]
[1] "india" "123"
[[12]]
[1] "russia" "326 2"
[[13]]
[1] "sudan" "143"
[[14]]
[1] "russia" "326 2"
[[15]]
[1] "china" "232"
[[16]]
[1] "india" "123"
[[17]]
[1] "sudan" "143"
[[18]]
[1] "india" "123"
[[19]]
[1] "china" "232"
[[20]]
[1] "china" "232"
 Live Demo
y<-sample(c("orange 12","banana247","guava 235","kiwi 138"),20,replace=TRUE)
df2<-data.frame(y)
df2
     y
1  banana247
2  kiwi 138
3  banana247
4  orange 12
5  kiwi 138
6  kiwi 138
7  banana247
8  banana247
9  orange 12
10 guava 235
11 guava 235
12 banana247
13 guava 235
14 orange 12
15 banana247
16 kiwi 138
17 kiwi 138
18 banana247
19 banana247
20 orange 12
Splitting string and numerical values in column y of df2 −
strsplit(df2$y,split="(?<=[a-zA-Z])\\s*(?=[0-9])",perl=TRUE)
[[1]]
[1] "banana" "247"
[[2]]
[1] "kiwi" "138"
[[3]]
[1] "banana" "247"
[[4]]
[1] "orange" "12"
[[5]]
[1] "kiwi" "138"
[[6]]
[1] "kiwi" "138"
[[7]]
[1] "banana" "247"
[[8]]
[1] "banana" "247"
[[9]]
[1] "orange" "12"
[[10]]
[1] "guava" "235"
[[11]]
[1] "guava" "235"
[[12]]
[1] "banana" "247"
[[13]]
[1] "guava" "235"
[[14]]
[1] "orange" "12"
[[15]]
[1] "banana" "247"
[[16]]
[1] "kiwi" "138"
[[17]]
[1] "kiwi" "138"
[[18]]
[1] "banana" "247"
[[19]]
[1] "banana" "247"
[[20]]
[1] "orange" "12"
How to create a common error page using JSP?

JSP gives you an option to specify Error Page for each JSP using page attribute. Whenever the page throws an exception, the JSP container automatically invokes the error page.
Following is an example to specifiy an error page for a main.jsp. To set up an error page, use the <%@ page errorPage = "xxx" %> directive.
<%@ page errorPage = "ShowError.jsp" %>

<html>
   <head>
      <title>Error Handling Example</title>
   </head>
   <body>
      <%
         // Throw an exception to invoke the error page
         int x = 1;
         if (x == 1) {
            throw new RuntimeException("Error condition!!!");
         }
      %>
   </body>
</html>
We will now write one Error Handling JSP ShowError.jsp, which is given below. Notice that the error-handling page includes the directive <%@ page isErrorPage = "true" %>. This directive causes the JSP compiler to generate the exception instance variable.
<%@ page isErrorPage = "true" %>

<html>
   <head>
      <title>Show Error Page</title>
   </head>
   <body>
      <h1>Opps...</h1>
      <p>Sorry, an error occurred.</p>
      <p>Here is the exception stack trace: </p>
      <pre><% exception.printStackTrace(response.getWriter()); %></pre>
   </body>
</html>
Access the main.jsp, you will receive an output somewhat like the following −
java.lang.RuntimeException: Error condition!!!
......

Opps...
Sorry, an error occurred.

Here is the exception stack trace:
Data Structures | Binary Trees | Question 13 - GeeksQuiz

Theory of Computation
Computer Organization and Architecture
Software Engineering
HTML and XML
Engineering Mathematics


GATE
Aptitude
CS Interview Questions


Programming Languages

C
C++
Java
Python


C
C++
Java
Python
Computer Science

Data Structures
Algorithms
Operating Systems
DBMS
Compiler Design
Computer Networks
Theory of Computation
Computer Organization and Architecture
Software Engineering
HTML and XML
Engineering Mathematics


Data Structures
Algorithms
Operating Systems
DBMS
Compiler Design
Computer Networks
Theory of Computation
Computer Organization and Architecture
Software Engineering
HTML and XML
Engineering Mathematics
GATE
Aptitude
CS Interview Questions
Articles

Programming Languages

C
C++
Java
Python


Computer Science

Algorithms
Compiler Design
Comuter Network
Computer Organization and Architecture
Data Structures

Hash
Linked List
Queue
Stack
Tree


DBMS
Difference
Digital Electronics
Mathematics
Operating Systems
Theory of Computation


Placements
Puzzles
Interview Experiences


Programming Languages

C
C++
Java
Python


C
C++
Java
Python
Computer Science

Algorithms
Compiler Design
Comuter Network
Computer Organization and Architecture
Data Structures

Hash
Linked List
Queue
Stack
Tree


DBMS
Difference
Digital Electronics
Mathematics
Operating Systems
Theory of Computation


Algorithms
Compiler Design
Comuter Network
Computer Organization and Architecture
Data Structures

Hash
Linked List
Queue
Stack
Tree


Hash
Linked List
Queue
Stack
Tree
DBMS
Difference
Digital Electronics
Mathematics
Operating Systems
Theory of Computation
Placements
Puzzles
Interview Experiences
GATE

GATE CS Corner
GATE Notes
Last Minute Notes
Official Papers
GATE CS 2017 Important Dates and Links


GATE CS Corner
GATE Notes
Last Minute Notes
Official Papers
GATE CS 2017 Important Dates and Links
Placements
Puzzles
Company Prep
What’s new
Jobs
Apps
Interview Corner
Consider the following C program segment
struct CellNode
{
  struct CelINode *leftchild;
  int element;
  struct CelINode *rightChild;
}

int Dosomething(struct CelINode *ptr)
{
    int value = 0;
    if (ptr != NULL)
    {
      if (ptr->leftChild != NULL)
        value = 1 + DoSomething(ptr->leftChild);
      if (ptr->rightChild != NULL)
        value = max(value, 1 + DoSomething(ptr->rightChild));
    }
    return (value);
}

The value returned by the function DoSomething when a pointer to the root of a non-empty tree is passed as argument is  (GATE CS 2004)
(A) The number of leaf nodes in the tree
(B) The number of nodes in the tree
(C) The number of internal nodes in the tree
(D) The height of the tree
 Answer: (D) Explanation: DoSomething() returns max(height of left child + 1, height of left child + 1).  So given that pointer to root of tree is passed to DoSomething(), it will return height of the tree. Note that this implementation follows the convention where height of a single node is 0.  Quiz of this Question
Draw a curve connecting two points instead of a straight line in matplotlib

To draw a curve connecting two points instead of a straight line in matplotlib, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Define a draw_curve() method to make a curve with a mathematical expression.
Plot point1 and point2 data points.
Plot x and y data points returned from the draw_curve() method.
To display the figure, use show() method.
import matplotlib.pyplot as plt
import numpy as np

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

def draw_curve(p1, p2):
   a = (p2[1] - p1[1]) / (np.cosh(p2[0]) - np.cosh(p1[0]))
   b = p1[1] - a * np.cosh(p1[0])
   x = np.linspace(p1[0], p2[0], 100)
   y = a * np.cosh(x) + b
   return x, y

p1 = [0, 1]
p2 = [1, 2]
x, y = draw_curve(p1, p2)
plt.plot(p1[0], p1[1], 'o')
plt.plot(p2[0], p2[1], 'o')
plt.plot(x, y)
plt.show()
It will produce the following output
File and FileReader in JavaScript?

Following is the code showing file and fileReader in JavaScript −
 Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result,.sample {
      font-size: 18px;
      font-weight: 500;
      color: rebeccapurple;
   }
   .result {
      color: red;
   }
</style>
</head>
<body>
<h1>File and FileReader in JavaScript</h1>
<input type="file" accept="text/*" onchange="displayFile(this)" />
<div class="result"></div>
<br />
<div class="sample"></div>
<h3>Click on the above button to display file and its details</h3>
<script>
   let resEle = document.querySelector(".result");
   let sampleEle = document.querySelector(".sample");
   function displayFile(input) {
      let file = input.files[0];
      resEle.innerHTML += "File name = " + file.name + "<br>";
      resEle.innerHTML += "File size = " + file.size + " bytes <br>";
      resEle.innerHTML += "File type = " + file.type + "<br>";
      var Reader = new FileReader();
      Reader.readAsText(file);
      Reader.onload = function () {
         sampleEle.innerHTML += Reader.result;
      };
      Reader.onerror = function () {
         sampleEle.innerHTML += Reader.error;
      };
   }
</script>
</body>
</html>
The above code will produce the following output −
On clicking the ‘Choose file’ button and choosing a file −
How can a query multiply 2 cells for each row in MySQL?

You can use multiplication operator (*) between two cells. The syntax is as follows
SELECT yourColumnName1,yourColumnName2,
yourColumnName1*yourColumnName2 as ‘anyVariableName’
from yourTableName;
To understand the above syntax, let us create a table. The query to create a table is as follows
mysql> create table MultiplicationDemo
   -> (
   -> FirstPrice int,
   -> SecondPrice int
   -> );
Query OK, 0 rows affected (0.63 sec)
Now you can display all records from the table using insert command. The query is as follows
mysql> insert into MultiplicationDemo values(10,2);
Query OK, 1 row affected (0.17 sec)

mysql> insert into MultiplicationDemo values(4,2);
Query OK, 1 row affected (0.30 sec)

mysql> insert into MultiplicationDemo values(5,6);
Query OK, 1 row affected (0.17 sec)

mysql> insert into MultiplicationDemo values(6,3);
Query OK, 1 row affected (0.12 sec)
Display all records from the table using select statement. The query is as follows
mysql> select *from MultiplicationDemo;
The following is the output
+------------+-------------+
| FirstPrice | SecondPrice |
+------------+-------------+
|         10 |           2 |
|          4 |           2 |
|          5 |           6 |
|          6 |           3 |
+------------+-------------+
4 rows in set (0.00 sec)
Here is the query to multiply 2 cells
mysql> select FirstPrice,SecondPrice,
   -> FirstPrice*SecondPrice as 'MultiplicationResult'
   -> from MultiplicationDemo;
The following is the output
+------------+-------------+----------------------+
| FirstPrice | SecondPrice | MultiplicationResult |
+------------+-------------+----------------------+
|         10 |           2 |                   20 |
|          4 |           2 |                    8 |
|          5 |           6 |                   30 |
|          6 |           3 |                   18 |
+------------+-------------+----------------------+
4 rows in set (0.03 sec)
How do I un-escape a backslash-escaped string in Python?

There are two ways to go about unescaping backslash escaped strings in Python. First is using literal_eval to evaluate the string. Note that in this method you need to surround the string in another layer of quotes. For example:
>>> import ast
>>> a = '"Hello,\\nworld"'
>>> print ast.literal_eval(a)
Hello,
world
Another way is to use the decode('string_escape') method from the string class. For example,
>>> print "Hello,\\nworld".decode('string_escape')
Hello,
world
Reverse a number in JavaScript

Our aim is to write a JavaScript function that takes in a number and returns its reversed number
For example, reverse of 678 −
876
Here’s the code to reverse a number in JavaScript −
const num = 124323;
const reverse = (num) => parseInt(String(num)
.split("")
.reverse()
.join(""), 10);
console.log(reverse(num));
Output in the console will be −
323421
Explanation
Let’s say num = 123
We convert the num to string → num becomes ‘123’
We split ‘123’ → it becomes [‘1’, ‘2’, ‘3’]
We reverse the array → it becomes [‘3’, ‘2’, ‘1’]
We join the array to form a string → it becomes ‘321’
Lastly we parse the string into a Int and returns it → 321
Sort strings in Alphanumeric sequence

A list of given strings is sorted in alphanumeric order or Dictionary Order. Like for these words: Apple, Book, Aim, they will be sorted as Aim, Apple, Book.If there are some numbers, they can be placed before the alphabetic strings.
Input:
A list of strings: Ball Apple Data Area 517 April Man 506
Output:
Strings after sort: 506 517 Apple April Area Ball Data Man
sortStr(strArr, n)
Input: The list of all strings, number of elements.
Output − Strings in alphanumeric sorted order.
Begin
   for round := 1 to n-1, do
      for i := 0 to n-round, do
         res := compare str[i] and str[i+1]       //either +ve, or –ve or 0
         if res > 0, then
            swap str[i] and str[i+1]
      done
   done
End
#include<iostream>
#define N 8
using namespace std;

void display(int n, string str[]) {
   for(int i = 0; i<n; i++)
      cout << str[i] << " ";         //print the string from array
   cout << endl;
}

void sortStr(int n, string str[]) {
   int i, round, res;
   for(round = 1; round<n; round++)
      for(i = 0; i<n-round; i++) {
         res = str[i].compare(str[i+1]);
         if(res > 0)
            swap(str[i], str[i+1]);//swap strings
      }
}

main() {
   string str[N] = {"Ball", "Apple", "Data", "Area", "517", "April", "Man", "506"};
   cout << "Strings before sort:"<< endl;
   display(N, str);
   sortStr(N, str);
   cout << "Strings after sort:"<<endl;
   display(N, str);
}
Strings before sort:
Ball Apple Data Area 517 April Man 506
Strings after sort:
506 517 Apple April Area Ball Data Man
How does free() know the size of memory to be deallocated? - GeeksforGeeks

28 May, 2017
Consider the following prototype of free() function which is used to free memory allocated using malloc() or calloc() or realloc().
void free(void *ptr);
Note that the free function does not accept size as a parameter. How does free() function know how much memory to free given just a pointer?
Following is the most common way to store size of memory so that free() knows the size of memory to be deallocated.When memory allocation is done, the actual heap space allocated is one word larger than the requested memory. The extra word is used to store the size of the allocation and is later used by free( )
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
References:http://www.cs.cmu.edu/afs/cs/academic/class/15213-f10/www/lectures/17-allocation-basic.pptxhttp://en.wikipedia.org/wiki/Malloc
C-Dynamic Memory Allocation
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TCP Server-Client implementation in C
Multithreading in C
Exception Handling in C++
Arrow operator -> in C/C++ with Examples
'this' pointer in C++
UDP Server-Client implementation in C
Understanding "extern" keyword in C
Smart Pointers in C++ and How to Use Them
Multiple Inheritance in C++
How to split a string in C/C++, Python and Java?