code-rag-bench/online-tutorials huggingface dataset:
JavaScript Array pop() Method

01 Nov, 2021
Below is the example of Array pop() method.
Example:<script>    function func() {        var arr = ['GFG', 'gfg', 'g4g', 'GeeksforGeeks'];              // Popping the last element from the array         document.write(arr.pop());          }    func();</script>                    
<script>    function func() {        var arr = ['GFG', 'gfg', 'g4g', 'GeeksforGeeks'];              // Popping the last element from the array         document.write(arr.pop());          }    func();</script>                    
Output:GeeksforGeeks
GeeksforGeeks
The arr.pop() method is used to remove the last element of the array and also returns the removed element. This function decreases the length of the array by 1.
Syntax:
arr.pop()
Parameters: This method does not accept any parameter.
Return value This method returns the removed element array. If the array is empty, then this function returns undefined.
Below examples illustrate the JavaScript Array pop() method:
Example 1: In this example the pop() method removes the last element from the array, which is 4 and returns it.var arr = [34, 234, 567, 4];
var popped = arr.pop();
print(popped);
print(arr);
Output:4
34,234,567

var arr = [34, 234, 567, 4];
var popped = arr.pop();
print(popped);
print(arr);

Output:
4
34,234,567

Example 2: In this example the function pop() tries to extract the last element of the array but since the array is empty therefore it returns undefined as the answer.var arr = [];
var popped = arr.pop();
print(popped);
Output:undefined
var arr = [];
var popped = arr.pop();
print(popped);

Output:
undefined
More example codes for the above method are as follows:
Program 1:
<script>function func() {    var arr = [34, 234, 567, 4];      // Popping the last element from the array     var popped = arr.pop();    document.write(popped);    document.write("<br>");    document.write(arr);}func();</script>
Output:
4
34,234,567

Program 2:
<script>function func() {      var arr = [];      // popping the last element    var popped = arr.pop();    document.write(popped);}func();</script>
Output:
undefined
Supported Browsers: The browsers supported by JavaScript Array pop() method are listed below:
Google Chrome 1.0 and above
Microsoft Edge 12 and above
Mozilla Firefox 1.0 and above
Safari 1 and above
Opera 4 and above
ysachin2314
javascript-array
JavaScript-Methods
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Compression

27 Jul, 2021
In this article, we will discuss the overview of Data Compression and will discuss its method illustration, and also will cover the overview part entropy. Let’s discuss it one by one. 
Overview :One important area of research is data compression. It deals with the art and science of storing information in a compact form. One would have noticed that many compression packages are used to compress files. Compression reduces the cost of storage, increases the speed of algorithms, and reduces the transmission cost. Compression is achieved by removing redundancy, that is repetition of unnecessary data. Coding redundancy refers to the redundant data caused due to suboptimal coding techniques.
Method illustration :
To illustrate this method let’s assume that there are six symbols, and binary code is used to assign a unique address to each of these symbols, as shown in the following table
Binary code requires at least three bits to encode six symbols. It can also be observed that binary codes 110 and 111 are not used at all. This clearly shows that binary code is not efficient, and hence an efficient code is required to assign a unique address. 
An efficient code is one that uses a minimum number of bits for representing any information. The disadvantage of binary code is that it is fixed code; a Huffman code is better, as it is a variable code. 
Coding techniques are related to the concepts of entropy and information content, which are studied as a subject called information theory. Information theory also deals with uncertainty present in a message is called the information content. The information content is given as 
                                 log2 (1/pi) or -log2 pi . 
Entropy :
Entropy is defined as a measure of orderliness that is present in the information. It is given as follows:
                                    H= - ∑ pi log2 pi
Entropy is a positive quantity and specifies the minimum number of bits necessary to encode information. Thus, coding redundancy is given as the difference between the average number of bits used for coding and entropy. 
coding redundancy = Average number of bits - Entropy
By removing redundancy, any information can be stored in a compact manner. This is the basis of data compression.
Computer Networks
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Wireless Application Protocol
Mobile Internet Protocol (or Mobile IP)
GSM in Wireless Communication
Secure Socket Layer (SSL)
Introduction of Mobile Ad hoc Network (MANET)
Difference between MANET and VANET
Difference between FDMA, TDMA and CDMA
Advanced Encryption Standard (AES)
Dynamic Host Configuration Protocol (DHCP)
Difference between Virus, Worm and Trojan Horse
How to empty a C# list?

To empty a C# list, use the Clear() method.
Firstly, set a list and add elements −
List<string> myList = new List<string>()
{
   "one",
   "two",
   "three",
   "four",
   "five",
   "six"
};
Now, let us empty the list −
myList.Clear();
 Live Demo
using System;
using System.Collections.Generic;
public class Program {
   public static void Main() {
      List<string> myList = new List<string>() {
         "one",
         "two",
         "three",
         "four",
         "five",
         "six"
      };
      foreach(string str in myList) {
         Console.WriteLine(str);
      }
      Console.WriteLine("Elements in the list = "+myList.Count);
      // this makes a list empty
      myList.Clear();
      Console.WriteLine("Elements in the list after using Clear() = "+myList.Count);
   }
}
one
two
three
four
five
six
Elements in the list = 6
Elements in the list after using Clear() = 0
Tryit Editor v3.7

CSS Image Reflection
Tryit: Image reflection to the right
Next.js - Dynamic Routing

In Next.js, we can create routes dynamically. In this example, we'll create pages on the fly and their routing.
Step 1. Define [id].js file − [id].js represents the dynamic page where id will be relative path. Define this file in pages/post directory.
Step 1. Define [id].js file − [id].js represents the dynamic page where id will be relative path. Define this file in pages/post directory.
Step 2. Define lib/posts.js − posts.js represents the ids and contents. lib directory is to be created in root directory.
Step 2. Define lib/posts.js − posts.js represents the ids and contents. lib directory is to be created in root directory.
Update [id].js file with getStaticPaths() method which sets the paths and getStaticProps() method to get the contents based on id.
import Link from 'next/link'
import Head from 'next/head'
import Container from '../../components/container'

import { getAllPostIds, getPostData } from '../../lib/posts'

export default function Post({ postData }) {
   return (
      <Container>
         {postData.id}
         <br />
         {postData.title}
         <br />
         {postData.date}
      </Container>
   )
}
export async function getStaticPaths() {
   const paths = getAllPostIds()
   return {
      paths,
      fallback: false
   }
}

export async function getStaticProps({ params }) {
   const postData = getPostData(params.id)
      return {
      props: {
         postData
      }
   }
}
posts.js contains getAllPostIds() to get the ids and getPostData() to get corresponding contents.
export function getPostData(id) {
   const postOne = {
      title: 'One',
      id: 1,
      date: '7/12/2020'
   }

   const postTwo = {
      title: 'Two',
      id: 2,
      date: '7/12/2020'
   }
   if(id == 'one'){
      return postOne;
   }else if(id == 'two'){
      return postTwo;
   }  
}

export function getAllPostIds() {
   return [{
      params: {
         id: 'one'
      }
   },
   {
      params: {
         id: 'two'
      }
   }
];
}
Run the following command to start the server −.
npm run dev
> nextjs@1.0.0 dev \Node\nextjs
> next

ready - started server on http://localhost:3000
event - compiled successfully
event - build page: /
wait  - compiling...
event - compiled successfully
event - build page: /next/dist/pages/_error
wait  - compiling...
event - compiled successfully

Open localhost:3000/posts/one in a browser and you will see the following output.
Open localhost:3000/posts/two in a browser and you will see the following output.
 Print
 Add Notes
 Bookmark this page
Java Program to generate random numbers string

At first, create a character array −
static char num[] = { '0', '1', '2', '3', '4', '5' };
Now, let’s say you want to a string with length. Create a StringBuilder and use append() to create random numbers string out of it −
int len = 5;
StringBuilder strBuilder = new StringBuilder();
for (int i = 0; i < len; i++) {
   strBuilder.append(randomNum());
}
Above, we created a randomNum() function that returns the random numbers string −
public static char randomNum() {
   return num[(int) Math.floor(Math.random() * 5)];
}
 Live Demo
public class Demo {
   static char num[] = { '0', '1', '2', '3', '4', '5' };
   public static char randomNum() {
      return num[(int) Math.floor(Math.random() * 5)];
   }
   public static void main(String[] args) {
      int len = 5;
      StringBuilder strBuilder = new StringBuilder();
      for (int i = 0; i < len; i++) {
         strBuilder.append(randomNum());
      }
      System.out.println("Random numbers string = "+strBuilder.toString());
   }
}
Random numbers string = 23024
How to implement ActionEvent using method reference in JavaFX?

The javafx.event package provides a framework for Java FX events. The Event class serves as the base class for JavaFX events and associated with each event is an event source, an event target, and an event type. An ActionEvent widely used when a button is pressed.
In the below program, we can implement an ActionEvent for a button by using method reference.
import javafx.application.*;
import javafx.beans.property.*;
import javafx.event.*;
import javafx.scene.*;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.stage.*;
import javafx.scene.effect.*;

public class MethodReferenceJavaFXTest extends Application {
   private Label label;
   public static void main(String[] args) {
      launch(args);
   }
   @Override
   public void start(Stage primaryStage) {
      Pane root = new StackPane();
      label = new Label("Method Reference");
      Button clickMe = new Button("Click Me");
      clickMe.setOnAction(this::handleClickMe);    // method reference
      root.getChildren().addAll(label, clickMe);

      primaryStage.setTitle("Method Reference Test");
      primaryStage.setScene(new Scene(root, 300, 200));
      primaryStage.show();
   }
   private void handleClickMe(ActionEvent event) {
      if(label.getEffect() == null) {
         label.setEffect(new BoxBlur());
      } else {
         label.setEffect(null);
      }
   }
}
Find records with a specific last digit in column with MySQL

For this, use the RIGHT() method to fetch records with a specific last digit. Let us first create a table −
mysql> create table DemoTable823(Value varchar(100));
Query OK, 0 rows affected (0.54 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable823 values('9847826');
Query OK, 1 row affected (0.52 sec)
mysql> insert into DemoTable823 values('84747464');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable823 values('9899889883');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable823 values('123456');
Query OK, 1 row affected (0.10 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable823;
This will produce the following output −
+------------+
| Value      |
+------------+
| 9847826    |
| 84747464   |
| 9899889883 |
| 123456     |
+------------+
4 rows in set (0.00 sec)
Following is the query to find records with a specific last digit −
mysql> select *from DemoTable823 where right(Value,1)='6';
This will produce the following output −
+---------+
| Value   |
+---------+
| 9847826 |
| 123456  |
+---------+
2 rows in set (0.00 sec)
Post and Pre incremented of arrays in C language

Explaining the array post and pre incremented concept with the help of C program.
Increment operator (++) −
It is used to increment the value of a variable by 1
It is used to increment the value of a variable by 1
There two types of increment operators − pre increment and post increment.
There two types of increment operators − pre increment and post increment.
Increment operator is placed before the operand in preincrement and the value is first incremented and then operation is performed on it.
Increment operator is placed before the operand in preincrement and the value is first incremented and then operation is performed on it.
eg: z = ++a; a= a+1
z=a
Increment operator is placed after the operand in post increment and the value is incremented after the operation is performed.
Increment operator is placed after the operand in post increment and the value is incremented after the operation is performed.
eg: z = a++; z=a
a= a+1
Let’s consider an example to access particular elements in memory locations by using pre- and post-increment.
Declare an array of size 5 and do compile time initialization. After that try to assign a pre incremented value to ‘a’ variable.
a=++arr[1] // arr[1]=arr[1]+1
a=arr[1]
b=arr[1]++// b=arr[1]
arr[1]+1
 Live Demo
#include<stdio.h>
int main(){
   int a, b, c;
   int arr[5] = {1, 2, 3, 25, 7};
   a = ++arr[1];
   b = arr[1]++;
   c = arr[a++];
   printf("%d--%d--%d", a, b, c);
   return 0;
}
4--3--25
here, a = ++arr[1]; i.e a = 3 //arr[2];
b = arr[1]++; i.e b = 3 //arr[2];
c = arr[a++]; i.e c = 25 //arr[4];
printf("%d--%d--%d",a, b, c);
printf("%d--%d--%d",4, 3, 25);
Thus 4--3--25 is outputted
Consider another example to know more about pre- and post-incremented of array.
 Live Demo
#include<stdio.h>
int main(){
   int a, b, c;
   int arr[5] = {1, 2, 3, 25, 7};
   a = ++arr[3];
   b = arr[3]++;
   c = arr[a++];
   printf("%d--%d--%d", a, b, c);
   return 0;
}
27--26—0
C# - if Statement

An if statement consists of a boolean expression followed by one or more statements.
The syntax of an if statement in C# is −
if(boolean_expression) {
   /* statement(s) will execute if the boolean expression is true */
}

If the boolean expression evaluates to true, then the block of code inside the if statement is executed. If  boolean expression evaluates to false, then the first set of code after the end of the if statement(after the closing curly brace) is executed.
using System;

namespace DecisionMaking {
   class Program {
      static void Main(string[] args) {
         /* local variable definition */
         int a = 10;
        
         /* check the boolean condition using if statement */
         if (a < 20) {
            /* if condition is true then print the following */
            Console.WriteLine("a is less than 20");
         }
         Console.WriteLine("value of a is : {0}", a);
         Console.ReadLine();
      }
   }
}
When the above code is compiled and executed, it produces the following result −
a is less than 20;
value of a is : 10


    119 Lectures 
     23.5 hours 

 Raja Biswas

    37 Lectures 
     13 hours 

 Trevoir Williams

    16 Lectures 
     1 hours 

 Peter Jepson

    159 Lectures 
     21.5 hours 

 Ebenezer Ogbu

    193 Lectures 
     17 hours 

 Arnold Higuit

    24 Lectures 
     2.5 hours 

 Eric Frick
 Print
 Add Notes
 Bookmark this page
Java Math IEEEremainder() method with Examples - GeeksforGeeks

16 Apr, 2018
The java.lang.Math.IEEEremainder() method computes the remainder operation on two arguments as prescribed by the IEEE 754 standard.The remainder value is mathematically equal to f1 – f2 x n, where n is the mathematical integer closest to the exact mathematical value of the quotient f1/f2, and if two mathematical integers are equally close to f1/f2, then n is the integer that is even.Note :
If the remainder is zero, its sign is the same as the sign of the first argument.
If either argument is NaN, or the first argument is infinite, or the second argument is positive zero or negative zero, then the result is NaN.
If the first argument is finite and the second argument is infinite, then the result is the same as the first argument.
Syntax:
public static double IEEEremainder(double dividend, double divisor)
Parameter:
dividend : the dividend.
divisor : the divisor.
Return :
This method returns the remainder when dividend is divided by divisor.

Example 1: To show working of java.lang.Math.IEEEremainder() method.
// Java program to demonstrate working// of java.lang.Math.IEEEremainder() methodimport java.lang.Math;  class Gfg {      // driver code    public static void main(String args[])    {        double did1 = 31.34;        double dis1 = 2.2;        System.out.println(Math.IEEEremainder(did1, dis1));          double did2 = -21.0;        double dis2 = 7.0;          // Sign of did2 is negative, Output is negative zero        System.out.println(Math.IEEEremainder(did2, dis2));          double did3 = 1.0 / 0;        double dis3 = 0.0;          // First argument is infinity and Second argument is zero        // Output NaN        System.out.println(Math.IEEEremainder(did3, dis3));          double did4 = -2.34;        double dis4 = 1.0 / 0;          // First argument finite and Second argument is infinity        // Output first argument        System.out.println(Math.IEEEremainder(did4, dis4));    }}
Output:
0.5399999999999974
-0.0
NaN
-2.34

Java-lang package
java-math
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
HashMap in Java with Examples
Stream In Java
Interfaces in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Singleton Class in Java
Multidimensional Arrays in Java
Set in Java
Multithreading in Java
Performance metrics for image steganography - GeeksforGeeks

28 Oct, 2021
Overview :Various methods are used to evaluate the quality of image steganography. Each of these methods assesses a different aspect of the result obtained after steganography. Some of the well-known methods are Mean Square Error(MSE), Peak Signal to Noise Ratio(PSNR), Structured Similarity Index Measure(SSIM), Payload Capacity.
Payload capacity : Payload capacity refers to the measure of the volume of information present within the cover image. This measure is important in a steganographic system as the communication overhead depends on the maximum payload capacity. It is measured in Bits Per Pixel(BPP).
BPP = NUMBER OF SECRET BITS EMBEDDED/ TOTAL NUMBER OF PIXELS
Mean Square Error(MSE): Mean Square Error is the averaged value of the square of the pixel-by-pixel difference between the original image and stego-image. It gives us a measure of the error produced in the cover image due to the data embedding process.
MSE=(mxn)-1∑mi=1 ∑ni=1I[I(i,j)-k(I,j)]2
Description –A lower value of MSE indicates a good quality embedding.
m,n = Dimensions of the image
I   = Original Image
K   = stego-image
Peak Signal to Noise Ratio(PSNR) : PSNR is another popular way to measure the degree of distortion in the cover image due to embedding.  It is the ratio between the maximum possible value of a signal and the power of distortion noise(MSE). It is measured in dB’s. A higher value of PSNR indicates a better quality embedding.
PSNR = 10xlog(MAX2/MSE)
Description –
MAX = 255 for a 8-bit grayscale image
Structured Similarity Index Measurement(SSIM): SSIM is a metric of comparison to check the similarity between the cover image and stego-image. It measures the perceptual difference between the two images. 
SSIM=(2μxμy + c1)(2σxy +c2)/((μx)2+(μy)2 +c1)((σx)2 +(σy)2 + c2)
Description –
c1 = (k1l)2
c2 = (k2l)2

μx  and μy  are the mean intensity values of images x and y. 

(σx)2  is the variance of x, 
(σy)2  is the variance of y 
(σxy)2 is the covariance of x and y. 

c1 and c2 are the two stabilizing parameters, 
L is the dynamic range of pixel values (2#bits per pixel - 1)  
the contents k1=0.01 and k2=0.03.
SSIM value close to 1 indicates good quality.
saurabh1990aror
Image-Processing
Computer Networks
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Advanced Encryption Standard (AES)
Intrusion Detection System (IDS)
Introduction and IPv4 Datagram Header
Secure Socket Layer (SSL)
Cryptography and its Types
Multiple Access Protocols in Computer Network
Congestion Control in Computer Networks
Routing Information Protocol (RIP)
Architecture of Internet of Things (IoT)
Block Cipher modes of Operation
SQL Query to Find Number of Employees According to Gender Whose DOB is Between a Given Range - GeeksforGeeks

19 Apr, 2021
Query in SQL is like a statement that performs a task. Here, we need to write a query that will find the number of employees according to gender whose DOB is in the given range.
We will first create a database named “geeks” then we will create a table “department” in that database.
Use the below SQL statement to create a database called geeks:
CREATE DATABASE geeks;
USE geeks;
We have the following department table in our geeks database :
CREATE TABLE department(
    ID int,
    NAME Varchar(20),
    Gender Varchar(5),
    DateOfBirth Date);
You can use the below statement to query the description of the created table:
EXEC sp_columns department;
The date data type uses the format ‘YYYY-MM-DD‘. Use the below statement to add data to the department table:
INSERT INTO department VALUES (1,'Neha','F','1994-06-03');
INSERT INTO department VALUES (2,'Harsh','M','1996-03-12');
INSERT INTO department VALUES (3,'Harsh','M','1995-05-01');
INSERT INTO department VALUES (4,'Rupali','F',1996-11-11');
INSERT INTO department VALUES (5,'Rohan','M','1992-03-08');
To verify the contents of the table use the below statement:
SELECT * FROM department
Get the number of employees according to their gender whose DOB is between a given range. Here, we will assume the DOB range to be from 1995-01-01 to 1996-12-31. 
Now we will use the below syntax to query for the number of employees according to gender whose DOB is between a given range:
Syntax:
SELECT column_name1, count(column_name1) FROM table_name 
WHERE column_name2 between value1 and value2 GROUP BY column_name1;
So the query for our table goes as shown below:
SELECT Gender,count(Gender) FROM department 
WHERE DateOfBirth between '1995-01-01' and '1996-12-31'
GROUP BY gender;
Output:
Picked
SQL-Query
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?
SQL | Subquery
How to Create a Table With Multiple Foreign Keys in SQL?
What is Temporary Table in SQL?
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL Query to Convert VARCHAR to INT
SQL using Python
How to Write a SQL Query For a Specific Date Range and Date Time?
How to Select Data Between Two Dates and Times in SQL Server?
SQL Query to Compare Two Dates
UGC-NET | UGC-NET CS 2017 Nov - III | Question 25 - GeeksforGeeks

19 Mar, 2018
Suppose we want to download text documents at the rate of 100 pages per second. Assume that a page consists of an average of 24 lines with 80 characters in each line. What is the required bit rate of the channel?
(A) 192 kbps(B) 512 kbps(C) 1.248 Mbps(D) 1.536 MbpsAnswer: (D)Explanation: We have 100 pages, each page is having 24 line and in each line there are 80 character and each character is of 8 bits.Now we have to calculate no of bits can be downloaded:ie.
 Downloading rate = 100 pages 
= 100 pages *24 line * 80 character * 8 bits
= 1536000 bits per second
ie 1.536 Mbps.

So, option (D) is correct.Quiz of this Question
UGC-NET
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
UGC-NET | UGC NET CS 2015 Dec - II | Question 36
UGC-NET | UGC NET CS 2017 Jan - III | Question 63
UGC-NET | UGC NET CS 2015 Jun - III | Question 32
UGC-NET | UGC NET CS 2014 Dec - II | Question 2
UGC-NET | UGC NET CS 2018 July - II | Question 33
UGC-NET | UGC-NET CS 2017 Dec 2 | Question 48
UGC-NET | UGC NET CS 2015 Dec - II | Question 29
UGC-NET | UGC NET CS 2017 Jan - II | Question 21
NTA UGC NET 2021 - Computer Science and Applications (087)
UGC-NET | UGC NET CS 2017 Jan - III | Question 49
How to implement a Stack using list in C++ STL - GeeksforGeeks

14 Jul, 2021
In this article, we will discuss how to implement a Stack using list in C++ STL.
Stack is a linear data structure which follows. LIFO(Last In First Out) or FILO(First In Last Out). It mainly supports 4 major operations:1. Push: Push an element into the stack.2. Pop: Removes the element by following the LIFO order.3. Top: Returns the element present at the top of the stack.4. Empty: Returns whether the stack is empty or not. 
Below is the implementation of the above approach:
C++
// C++ implementation of stack// using list STL#include <bits/stdc++.h>using namespace std;  template <typename T>// templating it so that any data type can be used  class Stack {public:    list<T> l;    int cs = 0;    // current size of the stack      // pushing an element into the stack    void push(T d)    {        cs++;        // increasing the current size of the stack        l.push_front(d);    }      // popping an element from the stack    void pop()    {        if (cs <= 0) {            // cannot pop us stack does not contain an            // elements            cout << "Stack empty" << endl;        }        else {            // decreasing the current size of the stack            cs--;            l.pop_front();        }    }      // if current size is 0 then stack is empty    bool empty() { return cs == 0; }      // getting the element present at the top of the stack    T top() { return l.front(); }    int size()    {        // getting the size of the stack        return cs;    }      // printing the elements of the stack    void print()    {        for (auto x: l) {            cout << x << endl;        }    }};int main(){    Stack<int> s;    s.push(10); // pushing into the stack    s.push(20);    s.push(30);    s.push(40);    cout << "Current size of the stack is " << s.size()         << endl;    cout << "The top element of the stack is " << s.top()         << endl;    s.pop(); // popping from the stack    cout << "The top element after 1 pop operation is "         << s.top()         << endl; // printing the top of the stack    s.pop(); // popping    cout << "The top element after 2 pop operations is "         << s.top() << endl;    cout << "Size of the stack after 2 pop operations is "         << s.size() << endl;    return 0;}
Current size of the stack is 4
The top element of the stack is 40
The top element after 1 pop operation is 30
The top element after 2 pop operations is 20
Size of the stack after 2 pop operations is 2

Time Complexity: O(1) for both push and pop operations in the stack.Auxiliary Space: O(N)
cpp-list
STL
C++
Stack
Stack
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Polymorphism in C++
Sorting a vector in C++
Friend class and function in C++
Pair in C++ Standard Template Library (STL)
Stack Data Structure (Introduction and Program)
Stack Class in Java
Stack in Python
Check for Balanced Brackets in an expression (well-formedness) using Stack
Stack | Set 2 (Infix to Postfix)
Tryit Editor v3.6 - Show C++

using namespace std;
​
int main() {
  int x;
  cout << "Type a number: "; // Type a number and press enter
  cin >> x; // Get user input from the keyboard
  cout << "Your number is: " << x;
Solve the Sherlock and Array problem in JavaScript

Watson gives Sherlock an array A of length N. Then he asks him to determine if there exists an
element in the array such that the sum of the elements on its left is equal to the sum of the
elements on its right.
We have to write this function, it should take in an array of Numbers, and any such number
exists in the array, it should return its index, otherwise it should return -1. So, let’s write the code
for this function −
const arr = [1, 2, 3, 4, 5, 7, 3];
const arr2 = [4, 6, 3, 4, 5, 2, 1];
const isSherlockArray = arr => {
   let sum = arr.reduce((acc, val) => acc+val);
   let leftSum = 0;
   for(let i = 0; i < arr.length; i++){
      sum -= arr[i];
      if(sum === leftSum){
         return i;
      };
      leftSum += arr[i];
   };
   return -1;
};
console.log(isSherlockArray(arr));
console.log(isSherlockArray(arr2));
The output in the console will be −
4
-1
Powershell - Rename Folder

Rename-Item cmdlet is used to rename a folder by passing the path of the folder to be renamed and target name.
In this example, we'll rename a folder D:\Temp\Test to D:\Temp\Test1
Type the following command in PowerShell ISE Console
Rename-Item D:\temp\Test D:\temp\Test1
You can see the Test directory as Test1 directory now. There should not be another folder with same name already in the temp directory otherwise PowerShell command will fail.

    15 Lectures 
     3.5 hours 

 Fabrice Chrzanowski

    35 Lectures 
     2.5 hours 

 Vijay Saini

    145 Lectures 
     12.5 hours 

 Fettah Ben
 Print
 Add Notes
 Bookmark this page
How to move a column from other position to first position in an R data frame?

A column’s position in an R data frame is crucial specially when we are dealing with a large data set. As the first column appears first, it becomes necessary that we should have columns of the data frame in an order that helps us to look at the important columns easily. For this purpose, we might want to change the position of columns. To change the position of a column to first position we can use single square brackets.
Consider the below data frame −
> set.seed(99)
> x1<-rnorm(20)
> x2<-rpois(20,10)
> x3<-rpois(20,5)
> x4<-runif(20,1,5)
> x5<-sample(1:5,20,replace=TRUE)
> x6<-LETTERS[1:20]
> df<-data.frame(x1,x2,x3,x4,x5,x6)
> df
x1 x2 x3 x4 x5 x6
1 0.2139625022 13 3 3.750865 3 A
2 0.4796581346 12 2 2.381080 2 B
3 0.0878287050 9 4 3.360354 3 C
4 0.4438585075 8 2 1.559041 3 D
5 -0.3628379205 10 7 1.631011 3 E
6 0.1226740295 11 2 2.877371 1 F
7 -0.8638451881 12 7 4.636257 3 G
8 0.4896242667 8 3 2.198420 4 H
9 -0.3641169125 5 5 4.987447 2 I
10 -1.2942420067 9 3 3.608834 2 J
11 -0.7457690454 8 3 2.349861 1 K
12 0.9215503620 11 9 1.992435 2 L
13 0.7500543504 13 5 1.754099 5 M
14 -2.5085540159 14 4 1.908080 2 N
15 -3.0409340953 13 1 2.406410 1 O
16 0.0002658005 11 2 2.741166 1 P
17 -0.3940189942 9 7 4.956848 4 Q
18 -1.7450276608 16 6 2.818134 5 R
19 0.4986314508 10 2 3.686916 2 S
20 0.2709537888 4 6 2.313132 4 T
Suppose we want to change the position of column 6 (x6) to position 1, then it can be done as shown below −
> df<-df[,c(6,1,2,3,4,5)]
> df
x6 x1 x2 x3 x4 x5
1 A 0.2139625022 13 3 3.750865 3
2 B 0.4796581346 12 2 2.381080 2
3 C 0.0878287050 9 4 3.360354 3
4 D 0.4438585075 8 2 1.559041 3
5 E -0.3628379205 10 7 1.631011 3
6 F 0.1226740295 11 2 2.877371 1
7 G -0.8638451881 12 7 4.636257 3
8 H 0.4896242667 8 3 2.198420 4
9 I -0.3641169125 5 5 4.987447 2
10 J -1.2942420067 9 3 3.608834 2
11 K -0.7457690454 8 3 2.349861 1
12 L 0.9215503620 11 9 1.992435 2
13 M 0.7500543504 13 5 1.754099 5
14 N -2.5085540159 14 4 1.908080 2
15 O -3.0409340953 13 1 2.406410 1
16 P 0.0002658005 11 2 2.741166 1
17 Q -0.3940189942 9 7 4.956848 4
18 R -1.7450276608 16 6 2.818134 5
19 S 0.4986314508 10 2 3.686916 2
20 T 0.2709537888 4 6 2.313132 4
In the same way, we can make more changes in the positions as shown below −
> df<-df[,c(6,2,3,5,1,4)]
> df
x5 x1 x2 x4 x6 x3
1 3 0.2139625022 13 3.750865 A 3
2 2 0.4796581346 12 2.381080 B 2
3 3 0.0878287050 9 3.360354 C 4
4 3 0.4438585075 8 1.559041 D 2
5 3 -0.3628379205 10 1.631011 E 7
6 1 0.1226740295 11 2.877371 F 2
7 3 -0.8638451881 12 4.636257 G 7
8 4 0.4896242667 8 2.198420 H 3
9 2 -0.3641169125 5 4.987447 I 5
10 2 -1.2942420067 9 3.608834 J 3
11 1 -0.7457690454 8 2.349861 K 3
12 2 0.9215503620 11 1.992435 L 9
13 5 0.7500543504 13 1.754099 M 5
14 2 -2.5085540159 14 1.908080 N 4
15 1 -3.0409340953 13 2.406410 O 1
16 1 0.0002658005 11 2.741166 P 2
17 4 -0.3940189942 9 4.956848 Q 7
18 5 -1.7450276608 16 2.818134 R 6
19 2 0.4986314508 10 3.686916 S 2
20 4 0.2709537888 4 2.313132 T 6
How to get services based on multiple conditional parameters in PowerShell?

To filter out services with both start-type “Automatic” and Status “stopped” we need to use the -AND comparison operator. Here, services will be displayed only when both conditions are matching.
Get-Service | where{($_.StartType -eq "Automatic") -and ($_.Status -eq "Stopped")} |
Select Name, StartType, Status
Name       StartType  Status
----       ---------  ------
gpsvc      Automatic Stopped
gupdate    Automatic Stopped
MapsBroker Automatic Stopped
To get services with start-type manual or disabled we will use -OR operator.
Get-Service | where{($_.StartType -eq "Manual") -or ($_.StartType -eq "Disabled")} |
Sort-Object Starttype | Select Name, StartType, Status
LxpSvc                                                    Manual Stopped
lmhosts                                                   Manual Running
KtmRm                                                     Manual Stopped
IpxlatCfgSvc                                              Manual Stopped
FontCache3.0.0.0                                          Manual Running
KeyIso                                                    Manual Running
klvssbridge64_20.0                                        Manual Stopped
UevAgentService                                         Disabled Stopped
tzautoupdate                                            Disabled Stopped
NetTcpPortSharing                                       Disabled Stopped
ssh-agent                                               Disabled Stopped
shpamsvc                                                Disabled Stopped
RemoteRegistry                                          Disabled Stopped
AppVClient                                              Disabled Stopped
svcdemo                                                 Disabled Stopped
Splunk - Calculated Fields

Many times, we will need to make some calculations on the fields that are already available in the Splunk events. We also want to store the result of these calculations as a new field to be referred later by various searches. This is made possible by using the concept of calculated fields in Splunk search.
A simplest example is to show the first three characters of a week day instead of the complete day name. We need to apply certain Splunk function to achieve this manipulation of the field and store the new result under a new field name.
The Web_application log file has two fields named bytes and date_wday. The value in the bytes field is the number of bytes. We want to display this value as GB. This will require the field to be divided by 1024 to get the GB value. We need to apply this calculation to the bytes field.
Similarly, the date_wday displays complete name of the week day. But we need to display only the first three characters.
The existing values in these two fields is shown in the image below −
To create calculated field, we use the eval function. This function stores the result of the calculation in a new field. We are going to apply the below two calculations −
# divide the bytes with 1024 and store it as a field named byte_in_GB
Eval byte_in_GB = (bytes/1024)

# Extract the first 3 characters of the name of the day.
Eval short_day = substr(date_wday,1,3)
We add new fields created above to the list of fields we display as part of the search result. To do this, we choose All fields options and tick check mark against the name of these new fields as shown in below image −
After choosing the fields above, we are able to see the calculated fields in the search result as shown below. The search query displays the calculated fields as shown below −
 Print
 Add Notes
 Bookmark this page
Display two different columns from two different tables with ORDER BY?

For this, you can use UNION along with the ORDER BY clause. Let us first create a table −
mysql> create table DemoTable1
(
   Amount int
);
Query OK, 0 rows affected (0.63 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1 values(234);
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable1 values(567);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable1 values(134);
Query OK, 1 row affected (0.43 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable1;
This will produce the following output −
+--------+
| Amount |
+--------+
|    234 |
|    567 |
|    134 |
+--------+
3 rows in set (0.00 sec)
Here is the query to create the second table −
mysql> create table DemoTable2
(
   Price int
);
Query OK, 0 rows affected (0.73 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable2 values(134);
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable2 values(775);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable2 values(121);
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable2 values(882);
Query OK, 1 row affected (0.09 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable2;
This will produce the following output −
+-------+
| Price |
+-------+
|   134 |
|   775 |
|   121 |
|   882 |
+-------+
4 rows in set (0.00 sec)
Following is the query to display two different columns from two different tables with ORDER BY −
mysql> select distinct Amount from DemoTable1
   UNION
   select distinct Price from DemoTable2
   order by Amount;
This will produce the following output −
+--------+
| Amount |
+--------+
|    121 |
|    134 |
|    234 |
|    567 |
|    775 |
|    882 |
+--------+
6 rows in set (0.00 sec)
Check if email address valid or not in Python

08 Aug, 2021
Prerequisite: Regex in Python
Given a string, write a Python program to check if the string is a valid email address or not. An email is a string (a subset of ASCII characters) separated into two parts by @ symbol, a “personal_info” and a domain, that is personal_info@domain.
Examples: 
Input:  ankitrai326@gmail.com
Output: Valid Email

Input: my.ownsite@ourearth.org
Output: Valid Email

Input: ankitrai326.com
Output: Invalid Email 
In this program, we are using the search() method of re module. so let’s see the description of it.re.search() : This method either returns None (if the pattern doesn’t match), or re.MatchObject contains information about the matching part of the string. This method stops after the first match, so this is best suited for testing a regular expression more than extracting data. 
Let’s see the Python program to validate an Email : 
Python3
# Python program to validate an Email # import re module # re module provides support# for regular expressionsimport re # Make a regular expression# for validating an Emailregex = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b' # Define a function for# for validating an Email  def check(email):     # pass the regular expression    # and the string into the fullmatch() method    if(re.fullmatch(regex, email)):        print("Valid Email")     else:        print("Invalid Email")  # Driver Codeif __name__ == '__main__':     # Enter the email    email = "ankitrai326@gmail.com"     # calling run function    check(email)     email = "my.ownsite@our-earth.org"    check(email)     email = "ankitrai326.com"    check(email)
Valid Email
Valid Email
Invalid Email
 
nagarjunarpa01
1kxezxl2vey1kouem4mpf6i5l9cpb5n9c5r7sryp
ritiedu7
atulsilori
armanschwarz
Python Regex-programs
python-regex
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Closures in Golang

23 Mar, 2020
Go language provides a special feature known as an anonymous function. An anonymous function can form a closure. A closure is a special type of anonymous function that references variables declared outside of the function itself. It is similar to accessing global variables which are available before the declaration of the function.
Example:
// Golang program to illustrate how// to create a Closurepackage main  import "fmt"  func main() {          // Declaring the variable    GFG := 0      // Assigning an anonymous      // function to a variable     counter := func() int {       GFG += 1       return GFG    }      fmt.Println(counter())    fmt.Println(counter())          }
Output:
1
2

Explanation: The variable GFG was not passed as a parameter to the anonymous function but the function has access to it. In this example, there is a slight problem as any other function which will be defined in the main has access to the global variable GFG and it can change it without calling counter function. Thus closure also provides another aspect which is data isolation.
// Golang program to illustrate how// to create data isolationpackage main  import "fmt"  // newCounter function to // isolate global variablefunc newCounter() func() int {    GFG := 0    return func() int {      GFG += 1      return GFG  }}func main() {    // newCounter function is    // assigned to a variable    counter := newCounter()      // invoke counter    fmt.Println(counter())    // invoke counter    fmt.Println(counter())          }
Output:
1
2

Explanation: The closure references the variable GFG even after the newCounter() function has finished running but no other code outside of the newCounter() function has access to this variable. This is how data persistency is maintained between function calls while also isolating the data from other code.
Picked
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to print % using printf()?

28 May, 2017
Asked by Tanuj
Here is the standard prototype of printf function in C.
          int printf(const char *format, ...);

The format string is composed of zero or more directives: ordinary characters (not %), which are copied unchanged to the output stream; and conversion specifications, each of argument (and it is an error if insufficiently many arguments are given).
The character % is followed by one of the following characters.
The flag characterThe field widthThe precisionThe length modifierThe conversion specifier:
See http://swoolley.org/man.cgi/3/printf for details of all the above characters. The main thing to note in the standard is the below line about conversion specifier.
A `%' is written. No argument is converted. The complete conversion specification is`%%'.

So we can print “%” using “%%”
/* Program to print %*/#include<stdio.h>/* Program to print %*/int main(){   printf("%%");   getchar();   return 0;}
We can also print “%” using below.
printf("%c", '%');printf("%s", "%");
C-Input and Output Quiz
c-puzzle
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | sympy.det() method

29 Jun, 2019
With the help of sympy.det() method, we can find the determinant of a matrix by using sympy.det() method.
Syntax : sympy.det()Return : Return determinant of a matrix.
Example #1 :In this example, we can see that by using sympy.det() method, we are able to find the determinant of a matrix.
# import sympyfrom sympy import *  # Use sympy.det() methodmat = Matrix([[1, 0, 1], [2, -1, 3], [4, 3, 2]])d = mat.det()   print(d)
Output :
-1
Example #2 :
# import sympyfrom sympy import *  # Use sympy.det() methodmat = Matrix([[1, 5, 1], [12, -1, 31], [4, 33, 2]])d = mat.det()   print(d)
Output :
-125
SymPy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python OOPs Concepts
How to iterate through Excel rows in Python?
Python Classes and Objects
Introduction To PYTHON
Decorators in Python
Styling Django Forms with django-crispy-forms

23 Oct, 2020
Django by default doesn’t provide any Django form styling method due to which it takes a lot of effort and precious time to beautifully style a form. django-crispy-forms solves this problem for us. It will let you control the rendering behavior of your Django forms in a very elegant and DRY way.
django : django install
django-crispy-forms
pip install django-crispy-forms


Configuring Django settings:
Add ‘crispy_forms’ to the INSTALLED_APPS in settings.py,
and also add 
CRISPY_TEMPLATE_PACK = 'bootstrap4'


after INSTALLED_APPS.
Till now we have configured settings needed for django-crispy-forms.
Using django-crispy-forms in Django templates:
First, we need to load django-crispy-forms tags in our django template.
For loading django-crispy-forms tags, add
{%load crispy_forms_tags %} 


on the top of your django template
Now to style any form with django-crispy-forms , replace
{{ form }}


with
{{ form|crispy }}


Bingo, you have successfully styled your form with django-crispy-forms.
Now you can see changes in your Django form by running server
python manage.py runserver


Example of Signup page styled using django-crispy-forms
Django-forms
Python Django
Python
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
HTML | <iframe> sandbox Attribute

17 Jun, 2022
The sandbox attribute permits an additional set of restrictions for the content within the iframe.When the sandbox attribute exists, and it will:  
treat the content as being from a singular origin
It blocks form submission
It blocks script execution
It disables APIs
It also preventing links from targeting other browsing contexts
It stop the content to navigate its top-level browsing context
block automatically triggered features (such as automatically playing a video or automatically focusing a form control)
The value of the sandbox attribute will either be simply sandboxed (then all restrictions are applied) or a space-separated list of pre-defined values which will take away the actual restrictions. 
Syntax:  
<iframe sandbox="value">
Attribute Values 
no-values: applies all restriction
allow-forms: Re-enables form submission
allow-pointer-lock: Re-enables APIs
allow-popups: Re-enables popups
allow-same-origin: It allows the content of iframe to be treated as being from same origin
allow-scripts: Re-enables scripts
allow-top-navigation: It Allows the content of iframe to navigate its top-level browsing context
Example:  
html
<!DOCTYPE html><html> <head>    <title>        HTML Iframe sandbox Attribute    </title></head> <body>    <h1>GeeksforGeeks</h1>     <h2>HTML IFrame sandbox Attribute</h2>          <br>    <br>     <iframe id="GFGFrame"            src="https://ide.geeksforgeeks.org/tryit.php"            width="400"            height="200"            sandbox>    </iframe></body> </html>
Output:  
Supported Browsers:The browsers supported by HTML IFrame sandbox Attribute are listed below 
Google Chrome 4.0 and above
Edge 12.0 and above
Firefox 17.0 and above
Internet Explorer 10.0 and above
Opera 15.0 and above
Safari 5.0 and above
hritikbhatnagar2182
simmytarika5
satyamm09
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
Design a Tribute Page using HTML & CSS
Types of CSS (Cascading Style Sheet)
How to Insert Form Data into Database using PHP ?
HTTP headers | Content-Type
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array