code-rag-bench/online-tutorials huggingface dataset:
How does Query.prototype.elemMatch() work in Mongoose ? - GeeksforGeeks

17 Mar, 2021
The Query.prototype.elemMatch() function is used to specify the $elemMatch condition. It matches the documents that contain an array field with at least single or one element that will matches all the specified query criteria.
Syntax:
Query.prototype.elemMatch()
Parameters: This function has two parameters, ie. path and filter.
Return Value: This function returns Query Object.Installing mongoose.;
npm install mongoose
After installing the mongoose module, you can check your mongoose version in command prompt using the command.
npm mongoose --version
Now, create a folder and add a file, for example, index.js as shown below.
Database: The sample database used here is shown below:  
Project Structure: The project structure will look like this.
Example 1:
index.js
const mongoose = require('mongoose');  // Database connectionmongoose.connect('mongodb://127.0.0.1:27017/geeksforgeeks', {    useNewUrlParser: true,    useCreateIndex: true,    useUnifiedTopology: true});  // User modelconst User = mongoose.model('User', {     name: { type: String },    age: { type: Number }});  var query = User.find({});query.where('user').elemMatch(function (elem) {          if (elem) {        console.log("Element Present")    }          elem.where('age').gte(100);  }).exec(function(err, res){    if(err) console.log(err)    console.log(res)})
Run index.js file using below command:
node index.js
Output: 
Element Present
[]    // No age is greater than 100
Example 2:
index.js
const express = require('express');const mongoose = require('mongoose');const app = express()  // Database connectionmongoose.connect('mongodb://127.0.0.1:27017/geeksforgeeks', {    useNewUrlParser: true,    useCreateIndex: true,    useUnifiedTopology: true});  // User modelconst User = mongoose.model('User', {     name: { type: String },    age: { type: Number }});  var query = User.find({});  query.where('user').elemMatch(function (elem) {          if (elem) {        console.log("Element Present")    }          elem.where('age').gte(155);  }).exec(function(err, res){    if(err) console.log(err)    console.log(res)})  app.listen(3000, function(error ) {    if(error) console.log(error)    console.log("Server listening on PORT 3000")});
Run index.js file using below command:  
node index.js
Output: 
Server listening on PORT 3000
Element Present
[]    // No age is greater than 155
Reference:https://mongoosejs.com/docs/api/query.html#query_Query-elemMatch 
Mongoose
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Express.js express.Router() Function
JWT Authentication with Node.js
Express.js req.params Property
Mongoose Populate() Method
Difference between npm i and npm ci in Node.js
Roadmap to Become a Web Developer in 2022
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Convert a string to an integer in JavaScript
Split First name and Last name using JavaScript?

Let’s say the following is our string with name −
var studentFullName="John Smith";
Use split() to split the first name and last name. Following is the code −
var studentFullName="John Smith";
var details=[]
var details=studentFullName.split(' ');
console.log("StudentFirstName="+details[0])
console.log("StudentLastName="+details[1]);
To run the above program, you need to use the following command −
node fileName.js.
Here, my file name is demo163.js. This will produce the following output −
PS C:\Users\Amit\JavaScript-code> node demo163.js
StudentFirstName=John
StudentLastName=Smith
PLSQL | LTRIM Function - GeeksforGeeks

24 Sep, 2019
The PLSQL LTRIM function is used for removing all specified characters from the left-hand side of a string. The PLSQL LTRIM function accepts two parameters which are input_string and trim_string.
If the user does not specify trim_string, it defaults to a single blank.
If char is a character literal, then you must enclose it in single quotes.
Oracle Database begins scanning char from its first character and removes all characters that appear in trim_string until reaching a character not in trim_string and then returns the result.
Syntax:
LTRIM( input_string [, trim_string] )
Parameters Used:
input_string – It is used to specify the string whose characters need to be trimmed from the left hand side.
trim_string – It is an optional parameter which is used to specify the string that will be removed from the left-hand side of string1. If this parameter is omitted, the LTRIM function removes all leading spaces from input_string.
Supported Versions of Oracle/PLSQL:
Oracle 12cOracle 11gOracle 10gOracle 9iOracle 8i
Oracle 12c
Oracle 11g
Oracle 10g
Oracle 9i
Oracle 8i
Example-1:
DECLARE 
   Test_String string(25) := '    Geeksforgeeks';
   
BEGIN 
   dbms_output.put_line(LTRIM(Test_String)); 
   
END; 
Output:
Geeksforgeeks 
Example-2:
DECLARE 
   Test_String string(25) := '    Geeksforgeeks';
   
BEGIN 
   dbms_output.put_line(LTRIM(Test_String, ' ')); 
   
END; 
Output:
Geeksforgeeks 
Example-3:
DECLARE 
   Test_String string(25) := '123Geeksforgeeks';
   
BEGIN 
   dbms_output.put_line(LTRIM(Test_String, '123')); 
   
END; 
Output:
Geeksforgeeks 
Example-4:
DECLARE 
   Test_String string(25) := '123123Geeksforgeeks';
   
BEGIN 
   dbms_output.put_line(LTRIM(Test_String, '123')); 
   
END; 
Output:
Geeksforgeeks 
Example-5:
DECLARE 
   Test_String string(25) := '123Geeks123forgeeks';
   
BEGIN 
   dbms_output.put_line(LTRIM(Test_String, '123')); 
   
END; 
Output:
Geeks123forgeeks 
SQL-PL/SQL
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
CTE in SQL
SQL | Views
Difference between DELETE, DROP and TRUNCATE
How to Update Multiple Columns in Single Update Statement in SQL?
Difference between SQL and NoSQL
Difference between DDL and DML in DBMS
SQL Interview Questions
What is Temporary Table in SQL?
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
Difference between Where and Having Clause in SQL
How to use regular expressions (Regex) to filter valid emails in a Pandas series?

A regular expression is a sequence of characters that define a search pattern. In this program, we will use these regular expressions to filter valid and invalid emails.
We will define a Pandas series with different emails and check which email is valid. We will also use a python library called re which is used for regex purposes.
Step 1: Define a Pandas series of different email ids.
Step 2: Define a regex for checking validity of emails.
Step 3: Use the re.search() function in the re library for checking the validity of the email.
import pandas as pd
import re

series = pd.Series(['jimmyadams123@gmail.com', 'hellowolrd.com'])
regex = '^[a-z0-9]+[\._]?[a-z0-9]+[@]\w+[.]\w{2,3}$'
for email in series:
   if re.search(regex, email):
      print("{}: Valid Email".format(email))
   else:
      print("{} : Invalid Email".format(email))
jimmyadams123@gmail.com: Valid Email
hellowolrd.com : Invalid Email
The regex variable has the following symbols:
^: Anchor for the start of the string
[ ]: Opening and closing square brackets define a character class to match a single character
\ : Escape character
. : The dot matches any character except the newline symbol
{} : The opening and closing curly brackets are used for range definition
$ :  The dollar sign is the anchor for the end of the string
C program to compute linear regression

Write a program to implement linear regression algorithm.
User has to enter total number of values.
The solution to compute the linear regression in C programming language is as follows −
Linear regression finds the relationship between two variables by connecting a linear equation to the observed data. One variable is to be an explanatory variable, and the other is a dependent variable.
The logic with regards to linear regression is explained below −
for(i=0;i<n;i++){
   printf("enter values of x and y");
   scanf("%f%f",&x,&y);
   sumx=sumx+x;
   sumxsq=sumxsq+(x*x);
   sumy=sumy+y;
   sumxy=sumxy+(x*y);
}

d=n*sumxsq-sumx*sumx;
m=(n*sumxy-sumx*sumy)/d;
c=(sumy*sumxsq-sumx*sumxy)/d;
Finally, print m and c.
Following is the C program to compute the linear regression −
 Live Demo
#include<math.h>
#include<stdio.h>
main(){
   int n,i;
   float x,y,m,c,d;
   float sumx=0,sumxsq=0,sumy=0,sumxy=0;
   printf("enter the number of values for n:");
   scanf("%d",&n);
   for(i=0;i<n;i++){
      printf("enter values of x and y");
      scanf("%f%f",&x,&y);
      sumx=sumx+x;
      sumxsq=sumxsq+(x*x);
      sumy=sumy+y;
      sumxy=sumxy+(x*y);
   }
   d=n*sumxsq-sumx*sumx;
   m=(n*sumxy-sumx*sumy)/d;
   c=(sumy*sumxsq-sumx*sumxy)/d;
   printf("M=%f\tC=%f\n",m,c);
}
When the above program is executed, it produces the following result −
enter the number of values for n:5
enter values of x and y1 5
enter values of x and y2 6
enter values of x and y2 4
enter values of x and y3 7
enter values of x and y1 1
M=2.000000 C=1.000000
Tryit Editor v3.7

Tryit: HTML round cell borders
How to change line color in EditText

In some situations, we should change edit text bottom line color according to background color. This example demonstrate about how to change line color in EditText.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:id="@+id/parent"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".MainActivity"
   android:gravity="center"
   android:orientation="vertical">
   <EditText
      android:id="@+id/editText"
      android:hint="Bottom line color change"
      android:layout_width="wrap_content"
      android:backgroundTint="@android:color/holo_green_light"
      android:layout_height="wrap_content" >
   </EditText>
</LinearLayout>
In the above code, we have taken edit text, To change line color use the following code for edit text -
android:backgroundTint="@android:color/holo_green_light"
We can change color as per project requirement. we have taken green color for sample.
Step 3 − Add the following code to src/MainActivity.java
package com.example.andy.myapplication;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
   int view = R.layout.activity_main;
   @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(view);
   }
}
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run Eclipse Run Icon icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
In the above result, we have changed line color.
Click here to download the project code
Tryit Editor v3.7

Tryit: SVG rectangle
C# | Create HashSet from another collection - GeeksforGeeks

01 Feb, 2019
A HashSet is an unordered collection of the unique elements. It comes under System.Collections.Generic namespace. It is used in a situation where we want to prevent duplicates from being inserted in the collection. As far as performance is concerned, it is better in comparison to the list. You can create a HashSet from another collection by passing the collection as an argument while creating the object of HashSet.
Below given are some examples to understand the implementation in a better way:
Example 1:
// C# code to Create HashSet// from another collectionusing System;using System.Collections.Generic;  class GFG {      // Driver code    public static void Main()    {          // Creating a HashSet of integers        HashSet<int> mySet = new HashSet<int>();          // Inserting even numbers less than        // equal to 10 in HashSet mySet        for (int i = 0; i < 5; i++) {            mySet.Add(i * 2);        }          // Creating new HashSet mySet_new from already        // Created HashSet mySet        HashSet<int> mySet_new = new HashSet<int>(mySet);          Console.WriteLine("The elements in newly created HashSet are : ");          // Displaying the elements of newly created HashSet        foreach(int i in mySet_new)        {            Console.WriteLine(i);        }    }}
The elements in newly created HashSet are : 
0
2
4
6
8

Example 2:
// C# code to Create HashSet// from another collectionusing System;using System.Collections.Generic;  class GFG {      // Driver code    public static void Main()    {          // Creating a HashSet of strings        HashSet<string> mySet = new HashSet<string>();          // Inserting elements into HashSet mySet        mySet.Add("Delhi");        mySet.Add("Noida");        mySet.Add("Chandigarh");        mySet.Add("New York");        mySet.Add("Bangalore");          // Creating new HashSet mySet_new from already        // Created HashSet mySet        HashSet<string> mySet_new = new HashSet<string>(mySet);          Console.WriteLine("The elements in newly created HashSet are : ");          // Displaying the elements of newly created HashSet        foreach(string i in mySet_new)        {            Console.WriteLine(i);        }    }}
The elements in newly created HashSet are : 
Delhi
Noida
Chandigarh
New York
Bangalore

CSharp-Generic-HashSet
CSharp-Generic-Namespace
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Extension Method in C#
HashSet in C# with Examples
C# | Inheritance
Partial Classes in C#
C# | Generics - Introduction
Top 50 C# Interview Questions & Answers
Switch Statement in C#
C# | How to insert an element in an Array?
Convert String to Character Array in C#
Linked List Implementation in C#
Python program to extract Strings between HTML Tags - GeeksforGeeks

29 Dec, 2020
Given a String and HTML tag, extract all the strings between the specified tag.
Input :  ‘<b>Gfg</b> is <b>Best</b>. I love <b>Reading CS</b> from it.’ , tag = “br” Output : [‘Gfg’, ‘Best’, ‘Reading CS’]Explanation : All strings between “br” tag are extracted.
Input : ‘<h1>Gfg</h1> is <h1>Best</h1> I love <h1>Reading CS</h1>’  , tag = “h1” Output : [‘Gfg’, ‘Best’, ‘Reading CS’] Explanation : All strings between “h1” tag are extracted.  
Using re module this task can be performed. In this we employ, findall() function to extract all the strings by matching appropriate regex built using tag and symbols.
Python3
# importing re moduleimport re  # initializing stringtest_str = '<b>Gfg</b> is <b>Best</b>. I love <b>Reading CS</b> from it.'  # printing original stringprint("The original string is : " + str(test_str))  # initializing tagtag = "b"  # regex to extract required stringsreg_str = "<" + tag + ">(.*?)</" + tag + ">"res = re.findall(reg_str, test_str)  # printing resultprint("The Strings extracted : " + str(res))
Output:
The original string is : <b>Gfg</b> is <b>Best</b>. I love <b>Reading CS</b> from it.The Strings extracted : [‘Gfg’, ‘Best’, ‘Reading CS’]
Python Regex-programs
python-regex
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
Get Unique Values from ArrayList in Java - GeeksforGeeks

11 Dec, 2020
Let’s see how to get unique values from ArrayList. Convert ArrayList to HashSet to insert duplicate values in ArrayList but on the other hand, HashSet is not allowing to insert any duplicate value. While converting ArrayList to HashSet all the duplicate values are removed and as a result, unique values are obtained.
Example:
INPUT : ArrayList = [a, b, c, b, d, a, c]
OUTPUT: Unique = [a, b, c, d]

INPUT : ArrayList = [1, 5, 2, 4, 3, 4, 5]
OUTPUT: Unique = [1, 2, 3, 4, 5]
Approach:
Create a ArrarList.
Add elements in ArrayList.
Create HashSet and pass in HashSet constructor.
Print HashSet object.
Below is the implementation of the above approach:
Java
// Get Unique Values from ArrayList in Javaimport java.util.ArrayList;import java.util.HashSet;  public class GFG {      public static void main(String[] args)    {          // Create ArrayList        ArrayList<String> ArrList = new ArrayList<String>();          // add values in ArrayList        ArrList.add("a");        ArrList.add("b");        ArrList.add("c");        ArrList.add("b");        ArrList.add("d");        ArrList.add("a");        ArrList.add("c");          // display original ArrayList        System.out.println("Original ArrayList is : "                           + ArrList);          // convert ArrayList to HastSet.        HashSet<String> hset = new HashSet<String>(ArrList);          // display HastSet        System.out.println("ArrayList Unique Values is : "                           + hset);    }}
Original ArrayList is : [a, b, c, b, d, a, c]
ArrayList Unique Values is : [a, b, c, d]
Time Complexity: O(n), where n is the length of the original ArrayList.
Java-ArrayList
Picked
Technical Scripter 2020
Java
Java Programs
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
HashMap in Java with Examples
Interfaces in Java
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Initialize an ArrayList in Java
Initializing a List in Java
Convert a String to Character array in Java
Java Programming Examples
Convert Double to Integer in Java
How to Iterate HashMap in Java?
C# Program to check if a number is Positive, Negative, Odd, Even, Zero

Check for the following conditions −
For odd and even, check for the remainder when the number is divided by 2 −
// checking for odd/ even
if(n % 2 == 0) {
   Console.WriteLine("Even");
} else {
   Console.WriteLine("Odd");
}
For positive, negative and checking whether a number is 0 or not −
if (n < 0) {
Console.WriteLine("Negative Number!");
} else if(n == 0) {
   Console.WriteLine("Zero");
} else {
   Console.WriteLine("Positive Number!");
}
The following is the complete code:
 Live Demo
using System;
using System.Collections.Generic;

public class Demo {
   public static void Main(string[] args) {
      int n = 19;

      // checking for odd/ even
      if (n % 2 == 0) {
         Console.WriteLine("Even");
      } else {
         Console.WriteLine("Odd");
      }

      // checking for positive, negative or 0
      if (n < 0) {
         Console.WriteLine("Negative Number!");
      } else if (n == 0) {
         Console.WriteLine("Zero");
      } else {
         Console.WriteLine("Positive Number!");
      }
   }
}
Odd
Positive Number!
Create a procedure to find out the factorial of a number?

It can be created with the help of the following query −
mysql> Delimiter //
mysql> CREATE PROCEDURE fact(IN x INT)
    -> BEGIN
    -> DECLARE result INT;
    -> DECLARE i INT;
    -> SET result = 1;
    -> SET i = 1;
    -> WHILE i <= x DO
    -> SET result = result * i;
    -> SET i = i + 1;
    -> END WHILE;
    -> SELECT x AS Number, result as Factorial;
    -> END//
Query OK, 0 rows affected (0.17 sec)
Now when invoking this procedure by passing the value of which we want to get the factorial as an argument −
mysql> Delimiter ;
mysql> CALL Fact(5);
+--------+-----------+
| Number | Factorial |
+--------+-----------+
|      5 |       120 |
+--------+-----------+
1 row in set (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

mysql> CALL Fact(6);
+--------+-----------+
| Number | Factorial |
+--------+-----------+
|      6 |       720 |
+--------+-----------+
1 row in set (0.00 sec)

Query OK, 0 rows affected (0.00 sec)
Java While Loop

Loops can execute a block of code as long as a specified condition is reached.
Loops are handy because they save time, reduce errors, and they make code more readable.
The while loop loops through a block of code as long as a specified condition is true:
while (condition) {
  // code block to be executed
}

In the example below, the code in the loop will run, over and over again, as long as 
a variable (i) is less than 5:
int i = 0;
while (i < 5) {
  System.out.println(i);
  i++;
}


Try it Yourself »

Note: Do not forget to increase the variable used in the condition, otherwise 
the loop will never end!
The do/while loop is a variant of the while loop. This loop will 
execute the code block once, before checking if the condition is true, then it will
repeat the loop as long as the condition is true.
do {
  // code block to be executed
}
while (condition);

The example below uses a do/while loop. The loop will always be 
executed at least once, even if the condition is false, because the code block 
is executed before the condition is tested:
int i = 0;do {
  System.out.println(i);
  i++;
}
while (i < 5);


Try it Yourself »

Do not forget to increase the variable used in the condition, otherwise 
the loop will never end!
Print i as long as i is less than 6.
int i = 1;
 (i < 6) {
  System.out.println(i); 
  ;
}

Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
Java Program to write an array of strings to a file

Here’s our file −
FileWriter writer = new FileWriter("E:/demo.txt");
Now, consider a string array −
String arr[] = { "ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE" };
Write the above array to the file “demo.txt” −
int len = arr.length;
for (int i = 0; i < len; i++) {
   writer.write(arr[i] + "-");
}
The following is an example. Here, our file is “E:/demo.txt” −
import java.io.FileWriter;
public class Demo {
   public static void main(String[] argv) throws Exception {
      FileWriter writer = new FileWriter("E:/demo.txt");
      String arr[] = { "ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE" };
      int len = arr.length;
      for (int i = 0; i < len; i++) {
         writer.write(arr[i] + "-");
      }
      writer.close();
   }
}
The output is as follows i.e. the text in the file is −
ONE-TWO-THREE-FOUR-FIVE-SIX-SEVEN-EIGHT-NINE-
Adding and Subtracting Matrices in Python - GeeksforGeeks

30 Dec, 2020
In this article, we will discuss how to add and subtract elements of the matrix in Python. 
Example:
Suppose we have two matrices A and B.
A = [[1,2],[3,4]]
B = [[4,5],[6,7]]

then we get
A+B = [[5,7],[9,11]]
A-B = [[-3,-3],[-3,-3]]


Now let us try to implement this using Python 
1. Adding elements of the matrix
In the above code, we have used np.add() method to add elements of two matrices. If shape of two arrays are not same, that is arr1.shape != arr2.shape, they must be broadcastable to a common shape (which may be the shape of one or the other).
Python3
# importing numpy as npimport numpy as np    # creating first matrixA = np.array([[1, 2], [3, 4]])  # creating second matrixB = np.array([[4, 5], [6, 7]])  print("Printing elements of first matrix")print(A)print("Printing elements of second matrix")print(B)  # adding two matrixprint("Addition of two matrix")print(np.add(A, B))
Output:
Printing elements of first matrix
[[1 2]
 [3 4]]
Printing elements of second matrix
[[4 5]
 [6 7]]
Addition of two matrix
[[ 5  7]
 [ 9 11]]
2. Subtracting elements of matrices
In the above code, we have used np.subtract() to subtract elements of two matrices. It returns the difference of arr1 and arr2, element-wise.
Python3
# importing numpy as npimport numpy as np    # creating first matrixA = np.array([[1, 2], [3, 4]])  # creating second matrixB = np.array([[4, 5], [6, 7]])  print("Printing elements of first matrix")print(A)print("Printing elements of second matrix")print(B)  # subtracting two matrixprint("Subtraction of two matrix")print(np.subtract(A, B))
Output:
Printing elements of first matrix
[[1 2]
 [3 4]]
Printing elements of second matrix
[[4 5]
 [6 7]]
Subtraction of two matrix
[[-3 -3]
 [-3 -3]]
Python matrix-program
Python numpy-Mathematical Function
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
How to read only 5 last line of the text file in PHP?

To read only 5 last lines of the text file, the code is as follows −
$file = file("filename.txt");
for ($i = max(0, count($file)-6); $i < count($file); $i++) {
   echo $file[$i] . "\n";
}
This will produce the following output −
Given that the file has more than 5 lines of text, the last 5 lines of the text file will be displayed.
The file is opened and the number of lines in the file are counted, and beginning from the last line, 5 lines are read.
SQL – SELECT RANDOM

21 Jul, 2021
RANDOM( ) in SQL is generally used to return a random row from a table present in the database. It has many applications in real life. 
For example : 
There are a lot of employees in an organization. Suppose, if the event manager wants to mail any ten random employees then he/she can use the RANDOM( ) in SQL to get the Email Id of the ten random employees.It can also be used to display random questions during an online exam or MCQ from a pool of questions.
There are a lot of employees in an organization. Suppose, if the event manager wants to mail any ten random employees then he/she can use the RANDOM( ) in SQL to get the Email Id of the ten random employees.
It can also be used to display random questions during an online exam or MCQ from a pool of questions.
In this article, we are going to discuss how RANDOM( ) can be used using a sample table shown below.
Sample Input Table :
BASIC SQL QUERY :
1. Creating a Database
CREATE DATABASE database_name;
2. Creating a Table
CREATE TABLE Table_name(
col_1 TYPE col_1_constraint,
col_2 TYPE col_2 constraint
.....
)

col: Column name
TYPE: Data type whether an integer, variable character, etc
col_constraint: Constraints in SQL like PRIMARY KEY, NOT NULL, UNIQUE, REFERENCES, etc
3. Inserting into a Table
INSERT INTO Table_name
VALUES(val_1, val_2, val_3, ..........)

val: Values in particular column
4. View The Table
SELECT * FROM Table_name
Output :
Customer Table
SQL QUERY FOR RANDOM :
1. MYSQL
SELECT col_1,col_2, ... FROM Table_Name
ORDER BY RAND()

col_1 : Column 1
col_2 : Column 2
The above query will return the entire table for the specific columns mentioned and the rows will be random and changing position every time we run the query. To get a single row randomly, we can use the LIMIT Clause and set to only one row. ORDER BY clause in the query is used to order the row(s) randomly.
SELECT col_1,col_2, ... FROM Table_Name
ORDER BY RAND()
LIMIT 1

col_1 : Column 1
col_2 : Column 2
2. PostgreSQL and SQLite
It is exactly the same as MYSQL. Just replace RAND( ) with RANDOM( ).
SELECT col_1,col_2, ... FROM Table_Name
ORDER BY RAND()
LIMIT 1

col_1 : Column 1
col_2 : Column 2
Output :
Random Rows
RANDOM ROWS
RANDOM ROWS
RANDOM ROW
RANDOM ROW
We can observe that the above queries return the rows randomly from all the set of rows in the table. The RANDOM( ) clause is beneficial when there are humongous records in the database.
sagar0719kumar
Picked
SQL-Functions
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
Window functions in SQL
SQL | Sub queries in From Clause
What is Temporary Table in SQL?
SQL using Python
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL Query to Convert VARCHAR to INT
RANK() Function in SQL Server
SQL Query to Compare Two Dates
SQL Query to Insert Multiple Rows
Python | Split dictionary keys and values into separate lists

15 Nov, 2019
Given a dictionary, the task is to split that dictionary into keys and values into different lists. Let’s discuss the different ways we can do this.
Method #1: Using built-in functions
# Python code to demonstrate# to split dictionary# into keys and values  # initialising _dictionaryini_dict = {'a' : 'akshat', 'b' : 'bhuvan', 'c': 'chandan'}  # printing iniial_dictionaryprint("intial_dictionary", str(ini_dict))  # split dictionary into keys and valueskeys = ini_dict.keys()values = ini_dict.values()  # printing keys and values separatelyprint ("keys : ", str(keys))print ("values : ", str(values))
intial_dictionary {'a': 'akshat', 'b': 'bhuvan', 'c': 'chandan'}
keys :  dict_keys(['a', 'b', 'c'])
values :  dict_values(['akshat', 'bhuvan', 'chandan'])

 Method #2: Using zip()
# Python code to demonstrate# to split dictionary# into keys and values  # initialising _dictionaryini_dict = {'a' : 'akshat', 'b' : 'bhuvan', 'c': 'chandan'}  # printing iniial_dictionaryprint("intial_dictionary", str(ini_dict))  # split dictionary into keys and valueskeys, values = zip(*ini_dict.items())  # printing keys and values separatelyprint ("keys : ", str(keys))print ("values : ", str(values))
intial_dictionary {'a': 'akshat', 'c': 'chandan', 'b': 'bhuvan'}
keys :  ('a', 'c', 'b')
values :  ('akshat', 'chandan', 'bhuvan')

 Method #3: Using items()
# Python code to demonstrate# to split dictionary# into keys and values  # initialising _dictionaryini_dict = {'a' : 'akshat', 'b' : 'bhuvan', 'c': 'chandan'}  # printing iniial_dictionaryprint("intial_dictionary", str(ini_dict))  # split dictionary into keys and valueskeys = []values = []items = ini_dict.items()for item in items:    keys.append(item[0]), values.append(item[1])  # printing keys and values separatelyprint ("keys : ", str(keys))print ("values : ", str(values))
intial_dictionary {'b': 'bhuvan', 'c': 'chandan', 'a': 'akshat'}
keys :  ['b', 'c', 'a']
values :  ['bhuvan', 'chandan', 'akshat']

shubham_singh
Python dictionary-programs
python-dict
Python
Python Programs
python-dict
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
std::string::front() in C++with Examples

28 May, 2019
This function returns a direct reference to the first character of the string. This shall only be used on non-empty strings.This can be used to access the first character of the string as well as to insert a character at the start of the string. Length of the string remains same after inserting a character, first character gets replaced by the new one.
Syntax
string str ("GeeksforGeeks");

Accessing first character
char first_char = str.front();

Inserting character at start of string
str.front() = '#';

Parameter: This function takes no parameter
Return value: A reference to the first character in the string
Exception: If the string is empty it shows undefined behavior.
Below examples illustrate the use of the above method:
Program 1:
// C++ program to demonstrate// the use of the above method  #include <iostream>  // for std::string::front#include <string>  using namespace std;  int main(){    string str("GeeksforGeeks");      // Accessing first character of string    char first_char = str.front();      cout << "First character of string = "         << first_char << endl;      // Inserting a character at    // the start of string    str.front() = '#';      cout << "New string = " << str << endl;      return 0;}
First character of string = G
New string = #eeksforGeeks

Program 2: It shows undefined behavior when the string is empty.
// C++ program to demonstrate// the use of the above method  #include <iostream>  // for std::string::front#include <string>  using namespace std;  int main(){    string str(""); // Empty string      // trying to access first character    // of an empty string    char first_char = str.front();      cout << "First character of string = "         << first_char << endl;      // Inserting a character at    // the start of an empty string    str.front() = '#';      cout << "New string = " << str << endl;      return 0;}
First character of string = 
New string =

Reference: std::string::front()
CPP-Functions
cpp-string
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sorting a vector in C++
Polymorphism in C++
Friend class and function in C++
Pair in C++ Standard Template Library (STL)
std::string class in C++
Queue in C++ Standard Template Library (STL)
Unordered Sets in C++ Standard Template Library
std::find in C++
List in C++ Standard Template Library (STL)
Inline Functions in C++
OpenCV – Counting the number of black and white pixels in the image

22 Jan, 2021
In this article, we will discuss counting the number of black pixels and white pixels in the image using OpenCV and NumPy. 
Prerequisites:
OpenCV
NumPy
The image we are using for the demonstration is shown below:
To display OpenCV provides the imshow() method for displaying the image we have recently read.
NumPy provides a function sum() that returns the sum of all array elements in the NumPy array. This sum() function can be used to count the number of pixels on the basis of the required criteria.
Now, a bit of knowledge of the pixel patterns comes into the picture. As we know that each pixel in a coloured image ranges from [0-255] all-inclusive, the pixel value for the black color being 0 and that for the white color is 255. This gives us a certain fixed condition of differentiation for the black and white pixels respectively from the other color pixels respectively.
This condition can be written in the NumPy as:
number_of_white_pix = np.sum(img == 255)      # extracting only white pixels 
number_of_black_pix = np.sum(img == 0)          # extracting only black pixels 
The first line says to extract and count all pixels from cv2 image object “img” whose pixel value is 255 i.e. white pixels. Similarly, the second line says to extract and count all pixels from cv2 image object “img” whose pixel value is 0 i.e. black pixels.
The condition inside sum() extracts only those pixels from the image which follow that condition and assigns them value True (1) and rest of the pixels are assigned False (0). Thus, the sum of all True (1s) gives us the count of those pixels that are satisfying the given condition within the parenthesis.
Code: Python implementation to count the number of black and white pixels in the image using OpenCV
Python3
# importing librariesimport cv2import numpy as np  # reading the image data from desired directoryimg = cv2.imread("chess5.png")cv2.imshow('Image',img)  # counting the number of pixelsnumber_of_white_pix = np.sum(img == 255)number_of_black_pix = np.sum(img == 0)  print('Number of white pixels:', number_of_white_pix)print('Number of black pixels:', number_of_black_pix)
Output:
Image to Process
Count of black and white pixels from the above image
Thus, we can infer from the above results that the image can be processed to retrieve the pixels of any desired color with the help of their color code or obtain the pixels based on any other condition as required.
https://numpy.org/doc/stable/reference/generated/numpy.sum.html
https://note.nkmk.me/en/python-numpy-count
Image-Processing
OpenCV
Picked
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Convert integer to string in Python
Python | os.path.join() method
Remove Outliers from Data Set in R

14 Sep, 2021
In this article, we will be looking at the approach to remove the Outliers from the data set using the in-built functions in the R programming language.
Outliers are data points that don’t fit the pattern of the rest of the data set. The best way to detect the outliers in the given data set is to plot the boxplot of the data set and the point located outside the box in the boxplot are all the outliers in the data set. In this approach to remove the outliers from the given data set, the user needs to just plot the boxplot of the given data set using the simple boxplot() function, and if found the presence of the outliers in the given data the user needs to call the boxplot.stats() function which is a base function of the R language, and pass the required parameters into this function, which will further lead to the removal of the outliers present in the given data sets.
boxplot.stats() function is typically called by another function to gather the statistics necessary for producing box plots but may be invoked separately.
Syntax: boxplot.stats(x, coef = 1.5, do.conf = TRUE, do.out = TRUE)
Parameters:
x: a numeric vector for which the boxplot will be constructed.
coef: determines how far the plot ‘whiskers’ extend out from the box.
do.conf, do.out: logicals; if FALSE, the conf or out component respectively will be empty in the result.
Let us first look at a regular plot without removing the outliers.
Example: Initial plot
R
gfg<-rnorm(500)  gfg[1:10]<-c(-4,2,5,6,4,1,-5,8,9,-6)  boxplot(gfg)
Output:
Now let us again visualize the above plot but this time without outliers by applying the given approach.
Example: Removing Outliers Using boxplot.stats() Function-
R
gfg<-rnorm(500)  gfg[1:10]<-c(-4,2,5,6,4,1,-5,8,9,-6)  gfg <- gfg[!gfg %in% boxplot.stats(gfg)$out]     boxplot(gfg)
Output:
Picked
R Data-science
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Split Column Into Multiple Columns in R DataFrame?
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 import an Excel File into R ?
Logistic Regression in R Programming
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
R - if statement
Extract First or Last n Characters from String in R
Python 3 - Number log10() Method

The log10() method returns base-10 logarithm of x for x > 0.
Following is the syntax for log10() method −
import math

math.log10( x )

Note − This function is not accessible directly, so we need to import the math module and then we need to call this function using the math static object.
x − This is a numeric expression.
This method returns the base-10 logarithm of x for x > 0.
The following example shows the usage of the log10() method.
#!/usr/bin/python3
import math   # This will import math module

print ("math.log10(100.12) : ", math.log10(100.12))
print ("math.log10(100.72) : ", math.log10(100.72))
print ("math.log10(119) : ", math.log10(119))
print ("math.log10(math.pi) : ", math.log10(math.pi))
When we run the above program, it produces the following result −
math.log10(100.12) :  2.0005208409361854
math.log10(100.72) :  2.003115717099806
math.log10(119) :  2.0755469613925306
math.log10(math.pi) :  0.49714987269413385
PostgreSQL – Function Parameters

28 Aug, 2020
PostgreSQL has 4 types of function parameters as listed below:
IN
OUT
INOUT
VARIADIC
To better understand these function parameters let’s first define a function on which we will experiment with the above-mentioned function parameters as below:
CREATE OR REPLACE FUNCTION get_sum(
    a NUMERIC, 
    b NUMERIC) 
RETURNS NUMERIC AS $$
BEGIN
    RETURN a + b;
END; $$

LANGUAGE plpgsql;

The get_sum() function accepts two parameters: a, and b,  and returns a numeric. 
The data types of the two parameters are NUMERIC. By default, the parameter’s type of any parameter in PostgreSQL is IN parameter. You can pass the IN parameters to the function but you cannot get them back as a part of the result.
Example:
SELECT get_sum(10, 20);

Output:
The OUT parameters are defined as part of the function arguments list and are returned back as a part of the result. For better understanding let’s define a function as below:
CREATE OR REPLACE FUNCTION hi_lo(
    a NUMERIC, 
    b NUMERIC,
    c NUMERIC, 
        OUT hi NUMERIC,
    OUT lo NUMERIC)
AS $$
BEGIN
    hi := GREATEST(a, b, c);
    lo := LEAST(a, b, c);
END; $$

LANGUAGE plpgsql;

The hi_lo function accepts 5 parameters:
Three IN parameters: a, b, c.
Two OUT parameters: hi (high) and lo (low).
Inside the function, we get the greatest and least numbers of three IN parameters using GREATEST and LEAST built-in functions. Because we use the OUT parameters, we don’t need to have a RETURN statement. The OUT parameters are useful in a function that needs to return multiple values without the need of defining a custom type.
Example :
SELECT hi_lo(10, 20, 30);

Output:
The INOUT parameter is the combination IN and OUT parameters. It means that the caller can pass a value to the function. The function then changes the argument and passes the value back as a part of the result.
The following square function accepts a number and returns the square of that number.
CREATE OR REPLACE FUNCTION square(
    INOUT a NUMERIC)
AS $$
BEGIN
    a := a * a;
END; $$
LANGUAGE plpgsql;

Example:
SELECT square(4);

Output:
A function can accept a variable number of arguments with one condition that all the arguments have the same data type. The arguments are passed to the function as an array.
Example:
CREATE OR REPLACE FUNCTION sum_avg(
    VARIADIC list NUMERIC[],
    OUT total NUMERIC, 
        OUT average NUMERIC)
AS $$
BEGIN
   SELECT INTO total SUM(list[i])
   FROM generate_subscripts(list, 1) g(i);

   SELECT INTO average AVG(list[i])
   FROM generate_subscripts(list, 1) g(i);
    
END; $$
LANGUAGE plpgsql;

The sum_avg() function accepts a list of numbers, calculates the total and average, and returns both values.
SELECT * FROM sum_avg(10, 20, 30);

Output:
PostgreSQL-function
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PostgreSQL - LIMIT with OFFSET clause
PostgreSQL - REPLACE Function
PostgreSQL - DROP INDEX
PostgreSQL - INSERT
PostgreSQL - Copy Table
PostgreSQL - TIME Data Type
PostgreSQL - ROW_NUMBER Function
PostgreSQL - Identity Column
PostgreSQL - CREATE SCHEMA
PostgreSQL - EXISTS Operator
Timer in C++ using system calls

05 Jul, 2021
The task is to create timer without using any graphics or animation. The timer will be made using system calls wherever necessary. Timer in this context means a stopwatch with up-counting of time.The timer is created in Linux. Following system calls of Linux are used: sleep() : It will make the program sleep for number of seconds provided as arguments to the function. system() : It is used to execute a system command by passing the command as argument to this function. 
Below is the implementation for creating timer using System Calls:  
CPP
// CPP program to create a timer#include <iomanip>#include <iostream>#include <stdlib.h>#include <unistd.h>using namespace std; // hours, minutes, seconds of timerint hours = 0;int minutes = 0;int seconds = 0; // function to display the timervoid displayClock(){    // system call to clear the screen    system("clear");     cout << setfill(' ') << setw(55) << "         TIMER         \n";    cout << setfill(' ') << setw(55) << " --------------------------\n";    cout << setfill(' ') << setw(29);    cout << "| " << setfill('0') << setw(2) << hours << " hrs | ";    cout << setfill('0') << setw(2) << minutes << " min | ";    cout << setfill('0') << setw(2) << seconds << " sec |" << endl;    cout << setfill(' ') << setw(55) << " --------------------------\n";} void timer(){    // infinite loop because timer will keep    // counting. To kill the process press    // Ctrl+D. If it does not work ask    // ubuntu for other ways.    while (true) {                 // display the timer        displayClock();         // sleep system call to sleep        // for 1 second        sleep(1);         // increment seconds        seconds++;         // if seconds reaches 60        if (seconds == 60) {                     // increment minutes            minutes++;             // if minutes reaches 60            if (minutes == 60) {                         // increment hours                hours++;                minutes = 0;            }            seconds = 0;        }    }} // Driver Codeint main(){    // start timer from 00:00:00    timer();    return 0;}
Output:  
Note: This can be made to run on Windows with a bit of modifications. Modifications required: 1. Use “cls” in place of “clear” in system() call. 2. Use ‘S’ in sleep() function in place of lower case ‘s’ in sleep() function. 3. Include windows.h header file.Making these changes code should run perfectly fine on Windows. 
clintra
kapoorsagar226
C++
Linux-Unix
Technical Scripter
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE CS 2010 | Question 22 - GeeksforGeeks

28 Jun, 2021
What is the appropriate pairing of items in the two columns listing various activities encountered in a software life cycle?
P. Requirements Capture     1.Module Development and Integration
Q. Design             2.Domain Analysis
R. Implementation     3.Structural and Behavioral Modeling
S. Maintenance             4.Performance Tuning
(A) P-3, Q-2, R-4, S-1(B) P-2, Q-3, R-1, S-4(C) P-3, Q-2, R-1, S-4(D) P-2, Q-3, R-4, S-1Answer: (B)Explanation: Module Development and Integration is clearly implementation workPerformance Tuning is clearly maintenance workDomain Analysis is clearly Requirements CaptureQuiz of this Question
GATE-CS-2010
GATE-GATE CS 2010
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-IT-2004 | Question 66
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 2010 | Question 24
GATE | GATE CS 2011 | Question 65
GATE | GATE-CS-2004 | Question 3
GATE | GATE-CS-2006 | Question 49
GATE | GATE CS 2019 | Question 27
GATE | GATE CS 2012 | Question 54
GATE | GATE CS 2021 | Set 1 | Question 47
Convert.ToBoolean Method in C#

The Convert.ToBoolean method is used to convert a specified value to an equivalent Boolean value.
The following is our double type.
double doubleNum = 329.34;
To convert it to Boolean, use the Convert.ToBoolean() method.
bool boolNum;
boolNum = System.Convert.ToBoolean(doubleNum);
Let us see another example.
 Live Demo
using System;
public class Demo {
   public static void Main() {
      double doubleNum = 3.4;
      bool boolNum;
      // Double to bool
      boolNum = System.Convert.ToBoolean(doubleNum);
      System.Console.WriteLine("{0} as a Boolean = {1}.", doubleNum, boolNum);
   }
}
3.4 as a Boolean = True.