code-rag-bench/online-tutorials huggingface dataset:
kbhit in C language

07 Jun, 2022
kbhit() functionality is basically stand for the Keyboard Hit. This function is deals with keyboard pressing 
kbhit() is present in conio.h and used to determine if a key has been pressed or not. To use kbhit function in your program you should include the header file “conio.h”. If a key has been pressed then it returns a non zero value otherwise returns zero. 
CPP
// C++ program to demonstrate use of kbhit()#include <iostream.h>#include <conio.h> int main(){    while (!kbhit())        printf("Press a key\n");     return 0;}
Output:
"Press a key" will keep printing on the 
console until the user presses a key on the keyboard.
Note : kbhit() is not a standard library function and should be avoided. Program to fetch the pressed key using kbhit 
CPP
// C++ program to fetch key pressed using// kbhit()#include <iostream>#include <conio.h>using namespace std;int main(){    char ch;    while (1) {         if ( kbhit() ) {             // Stores the pressed key in ch            ch = getch();             // Terminates the loop            // when escape is pressed            if (int(ch) == 27)                break;             cout << "\nKey pressed= " << ch;        }    }    return 0;}
Output:
Prints all the keys that will be pressed on
 the keyboard until the user presses Escape key
C
#include <stdio.h>// include conio.h file for kbhit function#include <conio.h>main(){    // declare variable    char ch;    printf("Enter key ESC to exit \n");    // define infinite loop for taking keys    while (1) {        if (kbhit) {            // fetch typed character into ch            ch = getch();            if ((int)ch == 27)                // when esc button is pressed, then it will exit from loop                break;            printf("You have entered : %c\n", ch);        }    }}
Output :
Enter key ESC to exit
You have entered : i
You have entered : P
You have entered : S
You have entered : w
You have entered : 7
You have entered : /
You have entered : *
You have entered : +
This article is contributed by Nishu Singh 1. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
sahivam4u
reshmapatil2772
cpp-input-output
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
D3.js - Timer API

Timer API module is used to perform the concurrent animations with synchronized timing delay. It uses requestAnimationFrame for animation. This chapter explains Timer API module in detail.
This method tells the browser that you wish to perform an animation and requests that the browser call a specified function to update an animation.
We can easily load the timer directly from d3js.org by using the following script.
<script src = "https://d3js.org/d3-timer.v1.min.js"></script>
<script>
   var timer = d3.timer(callback);
</script>
The Timer API supports the following important methods. All of these are explained in detail as follows.
This method returns the current time.
This method is used to schedule a new timer and invokes the timer until stopped. You can set a numeric delay in MS, but it is optional otherwise, it defaults to zero. If time is not specified, it is considered as d3.now().
Restart a timer with the specified callback and optional delay and time.
This method stops the timer, preventing subsequent callbacks.
It is used to stop the timer on its first callback. Callback is passed as the elapsed time.
It is invoked on a particular time delay interval. If delay is not specified, it takes the timer time.
Create a webpage “timer.html” and add the following script to it.
<!DOCTYPE html>
<html>
   <head>
      <script type = "text/javascript" src = "https://d3js.org/d3.v4.min.js"></script>
   </head>

   <body>
      <h3> Timer API </h3>
      <script>
         var timer = d3.timer(function(duration) {
            console.log(duration);
            if (duration > 150) timer.stop();
         }, 100);
      </script>
   </body>
</html>
We will see the following response on the screen.
 Print
 Add Notes
 Bookmark this page
Min Cost Path

A matrix of the different cost is given. Also, the destination cell is provided. We have to find minimum cost path to reach the destination cell from the starting cell (0, 0).
Each cell of the matrix represents the cost to traverse through that cell. 
From a cell, we cannot move anywhere, we can move either to the right or to the bottom or to the lower right diagonal cell, to reach the destination.
Input:
The cost matrix. And the destination point. In this case the destination point is (2, 2).
1 2 3
4 8 2
1 5 3

Output:
The minimum cost to reach to the destination from (0, 0). The minimum cost is 8.

minCostPath(destX, destY, cost)
Input − The (x, y) place of the destination, and the cost matrix.
Output − Minimum cost to reach a destination.
Begin
   define matrix totalCost, whose order is same as cost matrix
   totalCost[0, 0] = cost[0, 0]

   for i := 1 to destX, do
      totalCost[i, 0] := totalCost[i-1, 0] + cost[i, 0]
   done

   for j := 1 to destY, do
      totalCost[0, j] := totalCost[0, j-1] + cost[0, j]
   done

   for all places (i, j) from (1, 1) to (destX, destY), do
      totalCost[i, j] := minimum of totalCost[i-1, j-1], totalCost[i-1, j] and (totalCost[i, j-1] + cost[i,j])
   done

   return totalCost[destX, destY]
End
#include<iostream>
#define ROW 3
#define COL 3
using namespace std;

int cost[ROW][COL] = {
   {1, 2, 3},
   {4, 8, 2},
   {1, 5, 3}
};

int min(int a, int b, int c) {
   return (a<b)?((a<c)?a:c):((b<c)?b:c);
}

int minCostPath(int destX, int destY) {
   int totalCost[ROW][COL];

   totalCost[0][0] = cost[0][0];

   for (int i = 1; i <= destX; i++)
      totalCost[i][0] = totalCost[i-1][0] + cost[i][0];    //set first col of totalCost array

   for (int j = 1; j <= destY; j++)            //set first row of totalCost array
      totalCost[0][j] = totalCost[0][j-1] + cost[0][j];

   for (int i = 1; i <= destX; i++)            //for second row and column to all
      for (int j = 1; j <= destY; j++)
         totalCost[i][j] = min(totalCost[i-1][j-1], totalCost[i- 1][j], totalCost[i][j-1]) + cost[i][j];
   return totalCost[destX][destY];
}

int main() {
   cout << "Minimum Cost: "<< minCostPath(2, 2);    //destination (2, 2)
   return 0;
}
Minimum Cost: 8
Calculate the power on a BigInteger in Java

Use the BigInteger pow() method in Java to calculate the power on a BigInteger.
First, let us create some objects.
BigInteger one, two;
one = new BigInteger("5");
Perform the power operation and assign it to the second object −
// power operation
two = one.pow(3);
The following is an example −
 Live Demo
import java.math.*;
public class BigIntegerDemo {
   public static void main(String[] args) {
      BigInteger one, two;
      one = new BigInteger("5");
      System.out.println("Actual Value: " +one);
      // power operation
      two = one.pow(3);
      System.out.println("Result: " +two);
   }
}
Actual Value: 5
Negated Value: 125
Return from void functions in C++

The void functions are called void because they do not return anything. “A void function cannot return anything” this statement is not always true. From a void function, we cannot return any values, but we can return something other than values. Some of them are like below.
A void function cannot return any values. But we can use the return statement. It indicates that the function is terminated. It increases the readability of code.
 Live Demo
#include <iostream>
using namespace std;

void my_func() {
   cout << "From my_function" << endl;
   return;
}

int main() {
   my_func();
   return 0;
}
From my_function
In this approach, one void function can call another void function while it is terminating. The code will look like this.
 Live Demo
#include <iostream>
using namespace std;

void another_func() {
   cout << "From another_function" << endl;
   return;
}

void my_func() {
   cout << "From my_function" << endl;
   return another_func();
}

int main() {
   my_func();
   return 0;
}
From my_function
From another_function
React ES6 Ternary Operator

The ternary operator is a simplified conditional operator like if / else.
Syntax: condition ? <expression if true> : <expression if false>
Here is an example using if / else:
if (authenticated) {
  renderApp();
} else {
  renderLogin();
}


Try it Yourself »

Here is the same example using a ternary operator:
authenticated ? renderApp() : renderLogin();


Try it Yourself »

Complete this ternary operator statement.
blue  renderBlue()  renderRed();

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.
How to aggregate sum in MongoDB to get the total count?

To aggregate sum in MongoDB to get the total count, you can use the $sum operator. To understand the above concept, let us create a collection with the document −
> db.aggregateSumDemo.insertOne({"CustomerName":"Larry","Amount":140});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8baa0680f10143d8431e18")
}
> db.aggregateSumDemo.insertOne({"CustomerName":"Mike","Amount":160});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8baa1380f10143d8431e19")
}
> db.aggregateSumDemo.insertOne({"CustomerName":"Sam","Amount":300});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8baa1c80f10143d8431e1a")
}
> db.aggregateSumDemo.insertOne({"CustomerName":"David","Amount":500});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8baa2580f10143d8431e1b")
}
Display all documents from a collection with the help of find() method. The query is as follows −
> db.aggregateSumDemo.find().pretty();
The following is the output −
{
   "_id" : ObjectId("5c8baa0680f10143d8431e18"),
   "CustomerName" : "Larry",
   "Amount" : 140
}
{
   "_id" : ObjectId("5c8baa1380f10143d8431e19"),
   "CustomerName" : "Mike",
   "Amount" : 160
}
{
   "_id" : ObjectId("5c8baa1c80f10143d8431e1a"),
   "CustomerName" : "Sam",
   "Amount" : 300
}
{
   "_id" : ObjectId("5c8baa2580f10143d8431e1b"),
   "CustomerName" : "David",
   "Amount" : 500
}
Here is the query to get the total count.
Case 1 − The query is as follows −
> db.aggregateSumDemo.aggregate([ {
   ... $group: {
      ... _id: null,
      ... "TotalCount": {
         ... $sum:1
      ... }
   ... }
... } ] );
The following is the output −
{ "_id" : null, "TotalCount" : 4 }
Here is the query to aggregate sum in MongoDB to get the total sum.
Case 2 − The query is as follows −
> db.aggregateSumDemo.aggregate([ {
   ... $group: {
      ... _id: null,
      ... "TotalAmount": {
         ... $sum: "$Amount"
      ... }
   ... }
... } ] );
The following is the output −
{ "_id" : null, "TotalAmount" : 1100 }
C# Program to find the sum of a sequence

Firstly, set a sequence.
List<int> myList = new List<int> { 1, 2, 3, 4 ,5};
Now find the sum using the Queryable Sum() method.
myList.AsQueryable().Sum();
 Live Demo
using System;
using System.Linq;
using System.Collections.Generic;
public class Demo {
   public static void Main() {
      List<int> myList = new List<int> { 1, 2, 3, 4 ,5};
      Console.WriteLine("Sum of elements in a list...");
      foreach (int res in myList) {
         Console.WriteLine(res);
      }
      int sum = myList.AsQueryable().Sum();
      Console.WriteLine("Sum = {0}", sum);
   }
}
Sum of elements in a list...
1
2
3
4
5
Sum = 15
putchar() function in C - GeeksforGeeks

10 Jan, 2019
The putchar(int char) method in C is used to write a character, of unsigned char type, to stdout. This character is passed as the parameter to this method.
Syntax:
int putchar(int char)
Parameters: This method accepts a mandatory parameter char which is the character to be written to stdout.
Return Value: This function returns the character written on the stdout as an unsigned char. It also returns EOF when some error occurs.
Below examples illustrate the use of putchar() method:
Example 1:
// C program to demonstrate putchar() method  #include <stdio.h>  int main(){      // Get the character to be written    char ch = 'G';      // Write the Character to stdout    putchar(ch);      return (0);}
G

Example 2:
// C program to demonstrate putchar() method  #include <stdio.h>  int main(){      // Get the character to be written    char ch = '1';      // Write the Character to stdout    for (ch = '1'; ch <= '9'; ch++)        putchar(ch);      return (0);}
123456789

C-Functions
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
TCP Server-Client implementation in C
Exception Handling in C++
Multithreading in C
Arrow operator -> in C/C++ with Examples
'this' pointer in C++
How to split a string in C/C++, Python and Java?
Smart Pointers in C++ and How to Use Them
How to dynamically allocate a 2D array in C?
UDP Server-Client implementation in C
Input-output system calls in C | Create, Open, Close, Read, Write
Python | Prefix key match in dictionary - GeeksforGeeks

02 Aug, 2019
Sometimes, while working with dictionaries, we can have a problem in which we need to find the dictionary items that have some constraints on keys. One such constraint can be a prefix match on keys. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using dictionary comprehension + startswith()The combination of above two methods can be used to perform this particular task. In this, dictionary comprehension does the basic task of dictionary construction and startswith() performs the utility task of checking keys starting with specific prefix.
# Python3 code to demonstrate working of# Prefix key match in dictionary# Using dictionary comprehension + startswith()  # Initialize dictionarytest_dict = {'tough' : 1, 'to' : 2, 'do' : 3, 'todays' : 4, 'work' : 5}  # printing original dictionaryprint("The original dictionary : " +  str(test_dict))  # Initialize prefix test_pref = 'to'  # Using dictionary comprehension + startswith()# Prefix key match in dictionaryres = {key:val for key, val in test_dict.items()                    if key.startswith(test_pref)}  # printing result print("Filtered dictionary keys are : " + str(res))
The original dictionary : {‘to’: 2, ‘tough’: 1, ‘work’: 5, ‘todays’: 4, ‘do’: 3}Filtered dictionary keys are : {‘to’: 2, ‘tough’: 1, ‘todays’: 4}
 
Method #2 : Using map() + filter() + items() + startswith()This particular task can also be performed using the combination of above functions. The map function ties the filter logic of startswith() to each dictionary’s items extracted by items()
# Python3 code to demonstrate working of# Prefix key match in dictionary# Using map() + filter() + items() + startswith()  # Initialize dictionarytest_dict = {'tough' : 1, 'to' : 2, 'do' : 3, 'todays' : 4, 'work' : 5}  # printing original dictionaryprint("The original dictionary : " +  str(test_dict))  # Initialize prefix test_pref = 'to'  # Using map() + filter() + items() + startswith()# Prefix key match in dictionaryres = dict(filter(lambda item: item[0].startswith(test_pref),                                          test_dict.items()))  # printing result print("Filtered dictionary keys are : " + str(res))
The original dictionary : {‘to’: 2, ‘tough’: 1, ‘work’: 5, ‘todays’: 4, ‘do’: 3}Filtered dictionary keys are : {‘to’: 2, ‘tough’: 1, ‘todays’: 4}
Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Python program to convert a list to string
Defaultdict in Python
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
Pandas Tutorial

Pandas is a Python library.
Pandas is used to analyze data.
We have created 14 tutorial pages for you to learn more about Pandas.
Starting with a basic introduction and ends up with cleaning and plotting data:
Test your Pandas skills with a quiz test.
Start Pandas Quiz
Insert the correct Pandas method to create a Series.
pd.(mylist)

Start the Exercise
In our "Try it Yourself" editor, you can use the Pandas module, and modify the code to see the result.
Load a CSV file into a Pandas DataFrame:
Click on the "Try it Yourself" button to see how it works.
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.
PHP Tags

A PHP code script is a text file having .php extension and is stored on web server. The PHP parser on server looks for special sequence of characters <?php and ?>. These are called PHP's opening and closing tags. Statements witihn these two are interpreted by the parser. PHP script within these tags can be embedded in HTML document, so that embedded code is executed on server, leaving rest of the document to be processed by client browser's HTML parser.
<?php
//one or more PHP statements
..
..
?>
PHP allows a using a shorter representation of opening tag <? instead of cannonical usage <?php if it s enabled in php.ini file by enabling short_open_tag in php.ini file
<?
//one or more PHP statements
..
..
?>
This setting is recommended to be Off for production environment. Use of ASP style tags <%, %> and <script language="PHP"> has been discontinued since PHP 7.0
Following example shows use of PHP tags
 Live Demo
<?php
//cannonical PHP tags
echo "Hello World";
?>
This will produce following result −
Hello World
PHP supports a short echo tag <?= which is equivalent to the more verbose <?php echo.
 Live Demo
<?= "Hello World";
?>
This will produce following result −
Hello World
Example using short tags
 Live Demo
<?php
//set short_open_tag=on
echo "Hello World";
?>
This will produce following result −
Hello World
VBScript String Function

The String Function fills a string with the specified character the specified number of times.
String(number,character)

Number, a Required Parameter. An integer value, which would be repeated for the specified number of times against the character parameter.
Number, a Required Parameter. An integer value, which would be repeated for the specified number of times against the character parameter.
Character, a Required Parameter. Character value, which has to be repeated for the specified number of times.
Character, a Required Parameter. Character value, which has to be repeated for the specified number of times.
<!DOCTYPE html>
<html>
   <body>
      <script language = "vbscript" type = "text/vbscript">
         document.write("Line 1 :" & String(3,"$") & "<br />")
         document.write("Line 2 :" & String(4,"*") & "<br />")
         document.write("Line 3 :" & String(5,100) & "<br />")
         document.write("Line 4 :" & String(6,"ABCDE") & "<br />")

      </script>
   </body>
</html>
When you save it as .html and execute it in Internet Explorer, then the above script will produce the following result −
Line 1 :$$$
Line 2 :****
Line 3 :ddddd
Line 4 :AAAAAA


    63 Lectures 
     4 hours 

 Frahaan Hussain
 Print
 Add Notes
 Bookmark this page
C++ Program to Perform Graph Coloring on Bipartite Graphs

A bipartite graph is a graph in which if the graph coloring is possible using two colors i.e.; vertices in a set are colored with the same color. In this program we take a bipartite graph as input and outputs colors of each vertex after coloring the vertices.
Begin
   BFS algorithm is used to traverse all the vertices.
   Take a vertex and colour it yellow.
   Colour all its neighbour vertices as blue.
   Colour the next level vertices as yellow and so, until all vertices are coloured.
End.
#include<bits/stdc++.h>
using namespace std;
int n, e, i, j;
vector<vector<int> > g;
vector<int> color;
bool v[11101];
void c(int node,int n) {
   queue<int> q;
   if(v[node])
      return;
   color[node]=n;
   v[node]=1;
   for(i=0;i<n;i++) {
      if(!v[g[node][i]]) {
         q.push(g[node][i]);
      }
   }
   while(!q.empty()) {
      c(q.front(),(n+1)%2);
      q.pop();
   }
   return;
}
int main() {
   int a,b;
   cout<<"Enter number of vertices and edges respectively:";
   cin>>n>>e;
   cout<<"'Y' is for Yellow Colour and 'B' is for Blue Colour.";
   cout<<"\n";
   g.resize(n);
   color.resize(n);
   memset(v,0,sizeof(v));
   for(i=0;i<e;i++) {
      cout<<"\nEnter edge vertices of edge "<<i+1<<" :";
      cin>>a>>b;
      a--; b--;
      g[a].push_back(b);
      g[b].push_back(a);
   }
   c(0,1);
   for(i=0;i<n;i++) {
      if(color[i])
         cout<<i+1<<" "<<'Y'<<"\n";
      else
         cout<<i+1<<" "<<'B'<<"\n";
   }
}
Enter number of vertices and edges respectively:4 3
'Y' is for Yellow Colour and 'B' is for Blue Colour.

Enter edge vertices of edge 1 :1 2
Enter edge vertices of edge 2 :3 2
Enter edge vertices of edge 3 :4 2
1 Y
2 B
3 B
4 B
Find closest value for every element in array in C++

Here we will see how to find the closest value for every element in an array. If an element x has next element that is larger than it, and also present in the array, then that will be the greater value of that element. If the element is not present, then return -1. Suppose the array elements are [10, 5, 11, 6, 20, 12], then the greater elements are [11, 6, 12, 10, -1, 20]. As 20 has not greater value in the array, then print -1.
To solve this, we will use the set in C++ STL. The set is implemented using the binary tree approach. In binary tree always the inorder successor is the next larger element. So we can get the element in O(log n) time.
#include<iostream>
#include<set>
using namespace std;
void nearestGreatest(int arr[], int n) {
   set<int> tempSet;
   for (int i = 0; i < n; i++)
      tempSet.insert(arr[i]);
   for (int i = 0; i < n; i++) {
      auto next_greater = tempSet.upper_bound(arr[i]);
      if (next_greater == tempSet.end())
         cout << -1 << " ";
      else
         cout << *next_greater << " ";
   }
}
int main() {
   int arr[] = {10, 5, 11, 6, 20, 12};
   int n = sizeof(arr) / sizeof(arr[0]);
   nearestGreatest(arr, n);
}
11 6 12 10 -1 20
How to plot data from multiple two-column text files with legends in Matplotlib?

To plot data from multiple two-column text files with legends in matplotlib, we can take the following steps −
Import genfromtxt from pylab. It has several options to read data from a text file and plot the data.
Import genfromtxt from pylab. It has several options to read data from a text file and plot the data.
Read two text files, test.txt and test1.txt (having two columns of data), using genfromtxt and store the data in two variables, firstfiledata and secondfiledata.
Read two text files, test.txt and test1.txt (having two columns of data), using genfromtxt and store the data in two variables, firstfiledata and secondfiledata.
Plot the data using plot() method. label will be displayed as the legend.
Plot the data using plot() method. label will be displayed as the legend.
To display the figure, use show() method.
To display the figure, use show() method.
from matplotlib import pyplot as plt;
from pylab import genfromtxt;

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

firstfiledata = genfromtxt("test.txt");
secondfiledata = genfromtxt("test1.txt");
plt.plot(firstfiledata[:, 0], firstfiledata[:, 1], label="test.txt Data");
plt.plot(secondfiledata[:, 0], secondfiledata[:, 1], label="test1.txt Data");
plt.legend();
plt.show();
Suppse the two text files have the following data −
test.txt
========
1    3
2    5
3    27
4    9
5    11
6    13
7    15
8    17
9    19
test1.txt
=========
11    13
12    15
13    17
14    19
15    21
16    23
17    25
18    27
19    29
When we execute the code, it will produce the following output −
Sort multidimensional array by multiple keys in PHP

The array_multisort function can be used to sort a multidimensional array based on multiple keys −
$my_list = array(
   array('ID' => 1, 'title' => 'data one', 'event_type' => 'one'),
   array('ID' => 2, 'title' => 'data two', 'event_type' => 'zero'),
   array('ID' => 3, 'title' => 'data three', 'event_type' => 'one'),
   array('ID' => 4, 'title' => 'data four', 'event_type' => 'zero')
);
# The list of sorted columns and their data can be obtained. This will be passed to the array_multisort function.
$sort = array();
foreach($my_list as $k=>$v) {
   $sort['title'][$k] = $v['title'];
   $sort['event_type'][$k] = $v['event_type'];
}
# It is sorted by event_type in descending order and the title is sorted in ascending order.
array_multisort($sort['event_type'], SORT_DESC, $sort['title'], SORT_ASC,$my_list);
For PHP version 5.5.0 −
array_multisort(array_column($my_list, 'event_type'), SORT_DESC,
array_column($my_list, 'title'), SORT_ASC,
$my_list);
This will produce the following output −
array (
   0 =>
   array (
      'ID' => 4,
      'title' => 'data four',
      'event_type' => 'zero',
   ),
   1 =>
   array (
      'ID' => 3,
      'title' => 'data two',
      'event_type' => 'zero',
   ),
   2 =>
   array (
      'ID' => 1,
      'title' => 'data one',
      'event_type' => 'one',
   ),
   3 =>
   array (
      'ID' => 2,
      'title' => 'data three',
      'event_type' => 'one',
   ),
)
How to perform browser navigations in Selenium?

There are various navigate() methods to perform navigations in Selenium. They are as the listed below −
navigate().to(url)This is used to launch a new browser and open a particular URL as in the parameter.
navigate().to(url)
This is used to launch a new browser and open a particular URL as in the parameter.
navigate().refresh()This is used to reload a page.
navigate().refresh()
This is used to reload a page.
navigate().back()This is used to jump to the previous page as per browser history context.
navigate().back()
This is used to jump to the previous page as per browser history context.
navigate().forward()This is used to jump to the next page as per browser history context.
navigate().forward()
This is used to jump to the next page as per browser history context.
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import java.util.List;
public class BrowserNavigation {
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String url = "https://www.tutorialspoint.com/index.htm";
      // new browser will launch and navigate to the URL
      driver.navigate().to(url);
      driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS);
      // refresh the current browser
      driver.navigate().refresh();
      //Using id tagname attribute combination for css expression
      driver.findElement(By.cssSelector("input[name=’search’]")).
      sendKeys("Selenium");
      //browser will go back to the previous page
      driver.navigate().back();
      //browser will go move to the next page
      driver.navigate().forward();
      driver.close();
   }
}
XML - Character Entities

This chapter describes the XML Character Entities. Before we understand the Character Entities, let us first understand what an XML entity is.
As put by W3 Consortium the definition of an entity is as follows −
This means, entities are the placeholders in XML. These can be declared in the document prolog or in a DTD. There are different types of entities and in this chapter we will discuss Character Entity.
Both, HTML and XML, have some symbols reserved for their use, which cannot be used as content in XML code. For example, < and > signs are used for opening and closing XML tags. To display these special characters, the character entities are used.
There are few special characters or symbols which are not available to be typed directly from the keyboard. Character Entities can also be used to display those symbols/special characters.
There are three types of character entities −
Predefined Character Entities
Numbered Character Entities
Named Character Entities
They are introduced to avoid the ambiguity while using some symbols. For example, an ambiguity is observed when less than ( < ) or greater than ( > ) symbol is used with the angle tag (<>). Character entities are basically used to delimit tags in XML. Following is a list of pre-defined character entities from XML specification. These can be used to express characters without ambiguity.
Ampersand − &amp;
Ampersand − &amp;
Single quote − &apos;
Single quote − &apos;
Greater than − &gt;
Greater than − &gt;
Less than − &lt;
Less than − &lt;
Double quote − "
Double quote − "
The numeric reference is used to refer to a character entity. Numeric reference can either be in decimal or hexadecimal format. As there are thousands of numeric references available, these are a bit hard to remember. Numeric reference refers to the character by its number in the Unicode character set.
General syntax for decimal numeric reference is −
&# decimal number ;

General syntax for hexadecimal numeric reference is −
&#x Hexadecimal number ;

The following table lists some predefined character entities with their numeric values −
As it is hard to remember the numeric characters, the most preferred type of character
entity is the named character entity. Here, each entity is identified with a name.
For example −
'Aacute' represents capital  character with acute accent.
'Aacute' represents capital  character with acute accent.
'ugrave' represents the small  with grave accent.
'ugrave' represents the small  with grave accent.

    84 Lectures 
     6 hours 

 Frahaan Hussain

    29 Lectures 
     2 hours 

 YouAccel

    27 Lectures 
     1 hours 

 Jordan Stanchev

    16 Lectures 
     2 hours 

 Simon Sez IT
 Print
 Add Notes
 Bookmark this page
JavaScript | handler.get() Method - GeeksforGeeks

28 Sep, 2021
The handler.get() method in JavaScript is a trap for getting a property value.Syntax:  
const p = new Proxy(target, {
  get: function(target, property, receiver) {
  }
});
Parameters: This method accept three parameters as mentioned above and described below:  
Target: This parameter holds the target object.
Property: This parameter holds the name of the property which is to be get.
Receiver: This parameter holds the proxy or an object that inherits from the proxy.
Return value: This method returns any value.Below examples illustrate the handler.get() method in JavaScript:Example 1:  
javascript
<script>const monster1 = {  string: 'Geeksforgeeks',  num: 334}; const handler1 = {  get: function(target, prop, receiver) {    if (prop === 'string') {      return `${target.string.substr(0, 8)} ... Best portal!`;    } else {      return Reflect.get(...arguments);    }  }}; const proxy1 = new Proxy(monster1, handler1); console.log(proxy1.num);console.log(proxy1.string);console.log(proxy1.numstring); const obj = new Proxy({}, {  get: function(target, property, receiver) {    console.log('Property : ' + property);    return 56.56;  }}); console.log(obj.value);</script>
Output:  
334
"Geeksfor ... Best portal!"
undefined
"Property : value"
56.56
Example 2:  
javascript
<script>const obj = {};Object.defineProperty(obj, 'a', {  configurable: false,  enumerable: false,  value: 10,  writable: false}); const p = new Proxy(obj, {  get: function(target, property) {    return 10;  }}); console.log(p.a); var datalist = {    "vala": 32, "valb": 7 } var get = new Proxy(   datalist,  {     get: function(y, idx) {          return y[idx] * 11      }     } )    for(var z in get) {   console.log(z +" : "+ get[z]) } </script>
Output:  
10
"vala : 352"
"valb : 77"
Supported Browsers: The browsers supported by handler.get() method are listed below:  
Google Chrome 49 and above
Edge 12 and above
Firefox 18 and above
Opera 36 and above
Safari 10 and above
 
ysachin2314
javascript-functions
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
How to get character array from string in JavaScript?
How to remove duplicate elements from JavaScript Array ?
How to get selected value in dropdown list using JavaScript ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Sorting a String in C#

Firstly, set a string array.
string[] values = { "tim", "amit", "tom", "jack", "saurav"};
Use the Sort() method to sort.
Array.Sort(values);
Let us see the complete code −
 Live Demo
using System;
public class Program {
   public static void Main() {
      string[] values = { "tim", "amit", "tom", "jack", "saurav"};

      foreach (string value in values) {
         Console.Write(value);
         Console.Write(' ');
      }

      // sorting
      Array.Sort(values);
      Console.WriteLine("\nSorted...");
      foreach (string value in values) {
         Console.Write(value);
         Console.Write(' ');
      }
      Console.WriteLine();
   }
}
tim amit tom jack saurav
Sorted...
amit jack saurav tim tom
C++ Memory Library - allocator

It defines the memory models to be used by some parts of the Standard Library, and most specifically, by STL containers.
Following is the declaration for std::allocator function.
template <class T> class allocator;
template <class T> class allocator;
T − It contains information about types of elements.
In below example explains about std::allocator function.
#include <memory>
#include <iostream>
#include <string>

int main() {
   std::allocator<int> a1;
   int* a = a1.allocate(10);

   a[9] = 7;

   std::cout << a[9] << '\n';

   a1.deallocate(a, 10);

   std::allocator<std::string> a2;

   decltype(a1)::rebind<std::string>::other a2_1;

   std::allocator_traits<decltype(a1)>::rebind_alloc<std::string> a2_2;

   std::string* s = a2.allocate(2);

   a2.construct(s, "foo");
   a2.construct(s + 1, "bar");

   std::cout << s[0] << ' ' << s[1] << '\n';
 
   a2.destroy(s);
   a2.destroy(s + 1);
   a2.deallocate(s, 2);
}
Let us compile and run the above program, this will produce the following result −
7
foo bar

 Print
 Add Notes
 Bookmark this page
Get the count of a specific value in MongoDB

To get the count of a specific value in MongoDB, use aggregate(). Let us create a collection with documents −
> db.demo210.insertOne(
...   {
...      details: [
...         {
...            ClientName: "Robert"
...         },
...         {
...
...            lientName: "John Doe"
...         },
...         {
...
...            ClientName: "Robert"
...         },
...         {
...
...            ClientName: "Robert"
...         },
...         {
...
...            ClientName: "David Miller"
...         }
...      ]
...   }
...);
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3d99ab03d395bdc21346f9")
}
Display all documents from a collection with the help of find() method −
> db.demo210.find();
This will produce the following output −
{ "_id" : ObjectId("5e3d99ab03d395bdc21346f9"), "details" : [ { "ClientName" : "Robert" }, { "ClientName" : "John Doe" }, { "ClientName" : "Robert" }, { "ClientName" : "Robert" }, { "ClientName" : "David Miller" } ] }
Following is the query to get the count of a specific value −
> db.demo210.aggregate([
...   { "$match" : { "details.ClientName" : "Robert" } },
...   { "$unwind" : "$details" },
...   { "$match" : { "details.ClientName" : "Robert" } },
...   { "$group" : { "_id" : "$_id", "Size" : { "$sum" : 1 } } },
...   { "$match" : { "Size" : { "$gte" : 2 } } }
...]);
This will produce the following output −
{ "_id" : ObjectId("5e3d99ab03d395bdc21346f9"), "Size" : 3 }
Python VLC – Creating MediaPlayer object

11 Apr, 2022
In this article we will see how we can create a MediaPlayer object in the python vlc module. VLC media player is a free and open-source portable cross-platform media player software and streaming media server developed by the VideoLAN project. MediaPlayer object is the basic object in vlc module for playing the video. MediaPlayer class is the basic class it is used to play single video at a time.
In order to do this we will use MediaPlayer method Syntax : MediaPlayer(video_uri) Argument : It takes video uri as optional argument Return : It returns MediaPlayer object
Below is the implementation 
Python3
# importing vlc moduleimport vlcimport timeimport time # creating vlc media player objectmedia_player = vlc.MediaPlayer() # printing type of media player variableprint(type(media_player))
Output :
class 'vlc.MediaPlayer'
Another example 
Python3
# importing vlc moduleimport vlcimport time # creating vlc media player objectmedia_player = vlc.MediaPlayer("1.mp4") # start playing videomedia_player.play() # wait so the video can be played for 5 seconds# irrespective for length of videotime.sleep(5)
Output : 
simranarora5sos
Python vlc-library
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Neo4j Create Node

23 Aug, 2019
In the Neo4j to create node you will have to state CREATE statement. With the help of cypher language it is easy to create nodes, properties and relation between nodes. Let’s create sample node of GeeksforGeesk. You can see the table format, the actual code and the text also by selecting options. Below examples will illustrate the concept more clearly.
Example: In this example we will create a node label “GeeksforGeeks” with the “Tag” property that will tell us about the “GeeksforGeeks” that will be property value.
To create the node:$ CREATE (a:GeeksforGeeks { Tag : "A Computer Science Portal" })
The prefix a is a variable that will be anything this thing will required to refer later in any statement. After firing the Cypher query you will get something like the below picture.Output:
$ CREATE (a:GeeksforGeeks { Tag : "A Computer Science Portal" })

The prefix a is a variable that will be anything this thing will required to refer later in any statement. After firing the Cypher query you will get something like the below picture.Output:
Display node:So now you have a created node but the above query does not show you the created node to see the node you need to use RETURN statement like have to fire the below query. Here again we will create a node with 2 properties.
Display Created node:$ CREATE (a:GeksforGeeks { Tag : "A Computer Science Portal", Type : "Edutech" }) 
RETURN a
Output:Note: We return the node by using its variable name (in this case a).
$ CREATE (a:GeksforGeeks { Tag : "A Computer Science Portal", Type : "Edutech" }) 
RETURN a

Output:Note: We return the node by using its variable name (in this case a).
Creating multiple nodes:To create multiple nodes use the CREATE statement and separate the nodes by “, ” coma or you can use multiple time CREATE statement Like the below query.
Multiple nodes single Query using coma:$ CREATE (a:GeeksforGeeks { Tag: "A Computer Science Portal"}), 
(b:W3School { Tag: "We are the Learner"}) 
RETURN a, b
orCREATE (a:GeeksforGeeks { Tag: "A Computer Science Portal"}) 
CREATE (b:W3School { Tag: "We are the Learner"}) 
RETURN a, b
Output:
$ CREATE (a:GeeksforGeeks { Tag: "A Computer Science Portal"}), 
(b:W3School { Tag: "We are the Learner"}) 
RETURN a, b

or
CREATE (a:GeeksforGeeks { Tag: "A Computer Science Portal"}) 
CREATE (b:W3School { Tag: "We are the Learner"}) 
RETURN a, b

Output:
Note: Both the query will gave you same output.
DBMS
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
enum.IntEnum in Python

22 Apr, 2020
With the help of enum.IntEnum() method, we can get the enumeration based on integer value, if we compare with normal enum based class it will fail by using enum.IntEnum() method.
Syntax : enum.IntEnum
Return : IntEnum doesn’t have a written type.
Example #1 :In this example we can see that by using enum.IntEnum() method, we are able to get the enumeration based on integer value by using this method.
# import enum and IntEnumfrom enum import IntEnum  # Using enum.IntEnum class author(IntEnum):     GEEK = 1     FOR = 2     GEEKS = 3  print(author.FOR == 2)
OutPut :
True
Example #2 :
# import enum and IntEnumfrom enum import IntEnum, Enum  # Using enum.IntEnum class author(IntEnum):     GEEK = 1     FOR = 2     GEEKS = 3  class language(Enum):     Python = 1     Java = 2  print(author.GEEK == language.Python)
OutPut :
False
Python-enum
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python – Create dictionary from the list

01 Oct, 2020
Given a list. The task is to convert it to a dictionary with the values as the list element and keys as the concatenation of the given string K and value.
Examples:
Input : test_list = [“gfg”, “is”, “best”], K = “pref_” Output : {‘pref_gfg’: ‘gfg’, ‘pref_is’: ‘is’, ‘pref_best’: ‘best’} Explanation : Keys constructed after concatenating K.
Input : test_list = [“gfg”, “best”], K = “pref_” Output : {‘pref_gfg’: ‘gfg’, ‘pref_best’: ‘best’} Explanation : Keys constructed after concatenating K. 
Method #1: Using loop
This is one of the ways in which this task can be performed. In this, we perform concatenation using + operator to construct keys and values are extracted from list.
Python3
# Python3 code to demonstrate working of # Values derived Dictionary keys# Using loop  # initializing listtest_list = ["gfg", "is", "best"]   # printing original listprint("The original list is : " + str(test_list))  # initializing K K = "def_key_"  # using loop to construct new Dictionary# + operator used to concat default key and values res = dict()for ele in test_list:    res[K + str(ele)] = ele   # printing result print("The constructed Dictionary : " + str(res))
Output:
The original list is : [‘gfg’, ‘is’, ‘best’]The constructed Dictionary : {‘def_key_gfg’: ‘gfg’, ‘def_key_is’: ‘is’, ‘def_key_best’: ‘best’}
Method #2: Using dictionary comprehension
This is yet another way in which this task can be performed. In this, we construct a dictionary using one-liner using dictionary comprehension.
Python3
# Python3 code to demonstrate working of # Values derived Dictionary keys# Using dictionary comprehension  # initializing listtest_list = ["gfg", "is", "best"]   # printing original listprint("The original list is : " + str(test_list))  # initializing K K = "def_key_"  # using dictionary comprehension# + operator used to concat default key and values res = {K + str(ele) : ele for ele in test_list}  # printing result print("The constructed Dictionary : " + str(res))
Output:
The original list is : [‘gfg’, ‘is’, ‘best’]The constructed Dictionary : {‘def_key_gfg’: ‘gfg’, ‘def_key_is’: ‘is’, ‘def_key_best’: ‘best’}
Python dictionary-programs
Python list-programs
Python
Python Programs
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
Read a file line by line in Python
Python String | replace()
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
How to make a grouped boxplot graph in matplotlib?

To make a grouped boxplot graph in matplotlib, we can take the following steps −
Import matplotlib.pyplot and seaborn.
Set the figure size and adjust the padding between and around the subplots.
Load an example Seaborn dataset from the online repository.
Make a boxplot with male and female group in a single day.
To display the figure, use show() method.
import seaborn as sns
import matplotlib.pyplot as plt

# Set the figure size
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True

# Import a Seaborn dataset
data = sns.load_dataset('tips')

# Create a grouped boxplot
sns.boxplot(x=data['day'], y=data['total_bill'], hue=data['sex'])


plt.show()
It will produce the following output
CSS | var() Function - GeeksforGeeks

18 Dec, 2018
The var() function in CSS is used to insert a value for custom property.
Syntax:
var( custom_property, value )
Parameters: This function accepts two parameters which are listed below:
custom_property: It is the required parameter. The name of custom property must start with two dashes(–).
value: It is optional parameter. It is used if custom property is invalid.
Below program illustrates the var() function in CSS:
Program:
<!-- HTML code to describes var() function in CSS --><!DOCTYPE html><html>    <head>        <title>var() function</title>        <style>            :root {                --main-bg-color: Green;             }                          /* Use of var() function */            .gfg1 {                background-color: var(--main-bg-color);                padding:10px;            }            .gfg2 {                background-color: var(--main-bg-color);                padding: 5px;            }            h1 {                color:green;            }            body {                text-align:center;            }        </style>    </head>    <body>        <h1>GeeksforGeeks</h1>        <h2>var() function</h2>        <div class = "gfg1">GeeksforGeeks</div><br>        <div class = "gfg2">A computer science portal for geeks</div>    </body></html>                    
Output:
Supported Browsers: The browser supported by var() function are listed below:
Google Chrome 49.0
Edge 15.0
Firefox 31.0
Safari 9.1
Opera 36.0
CSS-Functions
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to update Node.js and NPM to next version ?
How to create footer to stay at the bottom of a Web page?
CSS to put icon inside an input element in a form
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?