code-rag-bench/online-tutorials huggingface dataset:
Difference between const char* p, char * const p, and const char * const p in C

In C programming language, *p represents the value stored in a pointer and p represents the address of the value, is referred as a pointer.
const char* and char const* says that the pointer can point to a constant char and value of char pointed by this pointer cannot be changed. But we can change the value of pointer as it is not constant and it can point to another constant char.
char* const says that the pointer can point to a char and value of char pointed by this pointer can be changed. But we cannot change the value of pointer as it is now constant and it cannot point to another char.
const char* const says that the pointer can point to a constant char and value of int pointed by this pointer cannot be changed. And we cannot change the value of pointer as well it is now constant and it cannot point to another constant char.
Thumb rule is to naming syntax from right to left.
// constant pointer to constant char
const char * const
// constant pointer to char
char * const
// pointer to constant char
const char *
Uncomment the commented errorneous codes and see the error.
 Live Demo
#include <stdio.h>
int main() {
   //Example: char const*
   //Note: char const* is same as const char*
   const char p = 'A';
   // q is a pointer to const char
   char const* q = &p;
   //Invalid asssignment
   // value of p cannot be changed
   // error: assignment of read-only location '*q'
   //*q = 'B';
   const char r = 'C';
   //q can point to another const char
   q = &r;
   printf("%c\n", *q);
   //Example: char* const
   char u = 'D';
   char * const t = &u;
   //You can change the value
   *t = 'E';
   printf("%c", *t);
   // Invalid asssignment
   // t cannot be changed
   // error: assignment of read-only variable 't'
   //t = &r;
   //Example: char const* const
   char const* const s = &p;
   // Invalid asssignment
   // value of s cannot be changed
   // error: assignment of read-only location '*s'
   // *s = 'D';
   // Invalid asssignment
   // s cannot be changed
   // error: assignment of read-only variable 's'
   // s = &r;
   return 0;
}
C
E
MongoDB aggregation to combine or merge fields and then count?

To combine or merge fields and then perform count, use $group along with $sum and $sort. Let us create a collection with documents −
> db.demo647.insertOne({"Subject":"MySQL"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e9c86316c954c74be91e6ee")
}
> db.demo647.insertOne({"Subject":"MongoDB"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e9c86356c954c74be91e6ef")
}
> db.demo647.insertOne({"Subject":"MySQL"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e9c86376c954c74be91e6f0")
}
> db.demo647.insertOne({"Subject":"SQL Server"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e9c86406c954c74be91e6f1")
}
> db.demo647.insertOne({"Subject":"MongoDB"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e9c86436c954c74be91e6f2")
}
> db.demo647.insertOne({"Subject":"PL/SQL"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e9c864b6c954c74be91e6f3")
}
> db.demo647.insertOne({"Subject":"MongoDB"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e9c86c16c954c74be91e6f4")
}
Display all documents from a collection with the help of find() method −
> db.demo647.find();
This will produce the following output −
{ "_id" : ObjectId("5e9c86316c954c74be91e6ee"), "Subject" : "MySQL" }
{ "_id" : ObjectId("5e9c86356c954c74be91e6ef"), "Subject" : "MongoDB" }
{ "_id" : ObjectId("5e9c86376c954c74be91e6f0"), "Subject" : "MySQL" }
{ "_id" : ObjectId("5e9c86406c954c74be91e6f1"), "Subject" : "SQL Server" }
{ "_id" : ObjectId("5e9c86436c954c74be91e6f2"), "Subject" : "MongoDB" }
{ "_id" : ObjectId("5e9c864b6c954c74be91e6f3"), "Subject" : "PL/SQL" }
{ "_id" : ObjectId("5e9c86c16c954c74be91e6f4"), "Subject" : "MongoDB" }
Following is the query to combine or merge fields then count −
> db.demo647.aggregate([ { "$group": { "_id": "$Subject", "COUNT": { "$sum": 1 } } }, { "$sort": { "COUNT": -1 } }, { "$limit": 2 } ] );
This will produce the following output −
{ "_id" : "MongoDB", "COUNT" : 3 }
{ "_id" : "MySQL", "COUNT" : 2 }
Nagios - Hosts and Services

Nagios is the most popular tool which is used to monitor hosts and services running in your IT infrastructure. Hosts and service configurations are the building blocks of Nagios Core.
Host is just like a computer; it can be a physical device or virtual.
Host is just like a computer; it can be a physical device or virtual.
Services are those which are used by Nagios to check something about a host.
Services are those which are used by Nagios to check something about a host.
You can create a host file inside the server directory of Nagios and mention the host and service definitions. For example −
sudo gedit /usr/local/nagios/etc/servers/ubuntu_host.cfg

define host {
   use linux-server
   host_name ubuntu_host
   alias Ubuntu Host
   address 192.168.1.10
   register 1
}
define service {
   host_name ubuntu_host
   service_description PING
   check_command check_ping!100.0,20%!500.0,60%
   max_check_attempts 2
   check_interval 2
   retry_interval 2
   check_period 24x7
   check_freshness 1
   contact_groups admins
   notification_interval 2
   notification_period 24x7
   notifications_enabled 1
   register 1
}
The above definitions add a host called ubuntu_host and defines the services which will run on this host. When you restart the Nagios, this host will start getting monitored by Nagios and the specified services will run.
There are many more services in Nagios which can be used to monitor pretty much anything on the running host.
 Print
 Add Notes
 Bookmark this page
How to compare date strings in Python?

Python date implementations support all the comparision operators. So, if you are using the datetime module to create and handle date objects, you can simply use the <, >, <=, >=, etc. operators on the dates. This makes it very easy to compare and check dates for validations, etc.
from datetime import datetime
from datetime import timedelta
today = datetime.today()
yesterday = today - timedelta(days=1)
print(today < yesterday)
print(today > yesterday)
print(today == yesterday)
This will give the output −
False
True
False
Adding labels to histogram bars in Matplotlib - GeeksforGeeks

24 Feb, 2021
In this article, we are going to discuss how to add labels to histogram bars in matplotlib. Histograms are used to display continuous data using bars. It looks similar to the bar graph. It shows the count or frequency of element that falls under the category mentioned in that range it means, taller the graph, higher the frequency of that range. To display the histogram and its labels we are going to use matplotlib.
Approach:
We import matplotlib and numpy library.
Create a dataset using numpy library so that we can plot it.
Create a histogram using matplotlib library.
To give labels use set_xlabel() and set_ylabel() functions.
We add label to each bar in histogram and for that, we loop over each bar and use text() function to add text over it. We also calculate height and width of each bar so that our label don’t coincide with each other.
Use show() function to display the histogram.
Below is the code Implementation:
Python
from matplotlib import pyplot as pltimport numpy as np  # Creating datasetmarks = np.array([70, 50, 40, 90, 55, 85, 74, 66, 33, 11, 45, 36, 89])  # Creating histogramfig, ax = plt.subplots(1, 1)ax.hist(marks)  # Set titleax.set_title("Title")  # adding labelsax.set_xlabel('x-label')ax.set_ylabel('y-label')  # Make some labels.rects = ax.patcheslabels = ["label%d" % i for i in range(len(rects))]  for rect, label in zip(rects, labels):    height = rect.get_height()    ax.text(rect.get_x() + rect.get_width() / 2, height+0.01, label,            ha='center', va='bottom')  # Show plotplt.show()
Output:
Explanation:
In the above code first, we created an array using np.array(). After that, we created a histogram using hist() function. To give labels we used  set_xlabel() and set_ylabel() functions. To give title to our graph we used the set_title() function.  We also added labels to each bar and for that first we used the get_height function to get height then, we used for loop to loop over each bar and add text over it using text() function. We used label variable to store the names of variables. Finally, to display histogram we used show() function.  
Picked
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Defaultdict in Python
Python | Get unique values from a list
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
Generate random characters and numbers in JavaScript?

At first, set the characters and numbers −
var storedCharacters =
'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
To generate randomly, use Math.random(). Following is the code −
function generateRandom3Characters(size) {
   var generatedOutput= '';
   var storedCharacters =
   '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
   var totalCharacterSize = storedCharacters.length;
   for ( var index = 0; index < size; index++ ) {
      generatedOutput+=storedCharacters.charAt(Math.floor(Math.random() *
      totalCharacterSize));
   }
   return generatedOutput;
}
console.log(generateRandom3Characters(3));
To run the above program, you need to use the following command −
node fileName.js.
Here, my file name is demo136.js. This will produce the following output −
PS C:\Users\Amit\JavaScript-code> node demo136.js
lq4
PyQt5 QListWidget | Python - GeeksforGeeks

17 Dec, 2019
In PyQt, QListWidget is a convenience class that provides a list view with a classic item-based interface for adding and removing items. QListWidget uses an internal model to manage each QListWidgetItem in the list.
Syntax:
listWidget = QListWidget()

There are two ways to add items to the list.
They can be constructed with the list widget as their parent widget.QListWidgetItem("Geeks", listWidget)
QListWidgetItem("For", listWidget)
QListWidgetItem("Geeks", listWidget)
They can be constructed with no parent widget and added to the list later.listWidgetItem = QListWidgetItem("GeeksForGeeks")
listWidget.addItem(listWidgetItem)

They can be constructed with the list widget as their parent widget.QListWidgetItem("Geeks", listWidget)
QListWidgetItem("For", listWidget)
QListWidgetItem("Geeks", listWidget)

QListWidgetItem("Geeks", listWidget)
QListWidgetItem("For", listWidget)
QListWidgetItem("Geeks", listWidget)

They can be constructed with no parent widget and added to the list later.listWidgetItem = QListWidgetItem("GeeksForGeeks")
listWidget.addItem(listWidgetItem)

listWidgetItem = QListWidgetItem("GeeksForGeeks")
listWidget.addItem(listWidgetItem)

Some of the most frequently used methods in QListWidget:
addItem() : To add QListWidgetItem object in list
addItems() : To add multiple QListWidgetItem objects
insertItem() : It adds item at specified position
clear() : To delete all the items present in the list
count() : To count number of items present in the list
Below is the code –
import sysfrom PyQt5.QtWidgets import QApplication, QWidget, QListWidget, QVBoxLayout, QListWidgetItem    class Ui_MainWindow(QWidget):    def __init__(self, parent = None):        super(Ui_MainWindow, self).__init__(parent)    if __name__ == '__main__':    app = QApplication(sys.argv)    window = QWidget()    listWidget = QListWidget()    window.setWindowTitle("Demo for QListWidget")      QListWidgetItem("Geeks", listWidget)    QListWidgetItem("For", listWidget)    QListWidgetItem("Geeks", listWidget)      listWidgetItem = QListWidgetItem("GeeksForGeeks")    listWidget.addItem(listWidgetItem)          window_layout = QVBoxLayout(window)    window_layout.addWidget(listWidget)    window.setLayout(window_layout)      window.show()      sys.exit(app.exec_())
Output :
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Enumerate() in Python
Read a file line by line in Python
Defaultdict in Python
Different ways to create Pandas Dataframe
sum() function in Python
Iterate over a list in Python
How to Install PIP on Windows ?
Deque in Python
Python String | replace()
TypeScript - String Length Property

Returns the length of the string.
var uname = new String("Hello World") 
console.log(uname) 
console.log("Length "+uname.length)  // returns the total number of characters 
                                     // including whitespace

On compiling, it will generate the same code in JavaScript.
Its output is as follows −
Hello World 
Length 11


    45 Lectures 
     4 hours 

 Antonio Papa

    41 Lectures 
     7 hours 

 Haider Malik

    60 Lectures 
     2.5 hours 

 Skillbakerystudios

    77 Lectures 
     8 hours 

 Sean Bradley

    77 Lectures 
     3.5 hours 

 TELCOMA Global

    19 Lectures 
     3 hours 

 Christopher Frewin
 Print
 Add Notes
 Bookmark this page
How to make two plots side-by-side using Python?

Using subplot(row, col, index) method, we can split a figure in row*col parts, and can plot the figure at the index position. In the following program, we will create two diagrams in a single figure.
Creating x, y1, y2 points using numpy.
Creating x, y1, y2 points using numpy.
With nrows = 1, ncols = 2, index = 1, add subplot to the current figure, using the subplot() method.
With nrows = 1, ncols = 2, index = 1, add subplot to the current figure, using the subplot() method.
Plot the line using x and y1 points, using the plot() method.
Plot the line using x and y1 points, using the plot() method.
Set up the title, label for X and Y axes for Figure 1, using plt.title(), plt.xlabel() and plt.ylabel() methods.
Set up the title, label for X and Y axes for Figure 1, using plt.title(), plt.xlabel() and plt.ylabel() methods.
With nrows = 1, ncols = 2, index = 2, add subplot to the current figure, using the subplot() method.
With nrows = 1, ncols = 2, index = 2, add subplot to the current figure, using the subplot() method.
Plot the line using x and y2 points, using the plot() method.
Plot the line using x and y2 points, using the plot() method.
Set up the title, label for X and Y axes for Figure 2, using plt.title(), plt.xlabel() and plt.ylabel() methods.
Set up the title, label for X and Y axes for Figure 2, using plt.title(), plt.xlabel() and plt.ylabel() methods.
To show the figure, use the plt.show() method.
To show the figure, use the plt.show() method.
from matplotlib import pyplot as plt
import numpy as np

xPoints = np.array([2, 4, 6, 8, 10, 12, 14, 16, 18, 20])
y1Points = np.array([12, 14, 16, 18, 10, 12, 14, 16, 18, 120])
y2Points = np.array([12, 7, 6, 5, 4, 3, 2, 2, 1, 12])

plt.subplot(1, 2, 1) # row 1, col 2 index 1
plt.plot(xPoints, y1Points)
plt.title("My first plot!")
plt.xlabel('X-axis ')
plt.ylabel('Y-axis ')

plt.subplot(1, 2, 2) # index 2
plt.plot(xPoints, y2Points)
plt.title("My second plot!")
plt.xlabel('X-axis ')
plt.ylabel('Y-axis ')

plt.show()
Java Math

The Java Math class has many methods that allows you to perform mathematical tasks on numbers.
The Math.max(x,y) method can be used to find the highest value of x and
y:
Math.max(5, 10);


Try it Yourself »

The Math.min(x,y) method can be used to find the lowest value of x 
and y:
Math.min(5, 10);


Try it Yourself »

The Math.sqrt(x) method returns the square root of x:
Math.sqrt(64);


Try it Yourself »

The Math.abs(x) method returns the absolute (positive) value of x:
Math.abs(-4.7);


Try it Yourself »

Math.random() returns a random number between 0.0 (inclusive), and 1.0 (exclusive):
Math.random();


Try it Yourself »

To get more control over the random number, e.g. you only want a random 
number between 0 and 100, you can use the following formula:
int randomNum = (int)(Math.random() * 101);  // 0 to 100

Try it Yourself »

For a complete reference of Math methods, go to our Java Math Methods Reference.
Use the correct method to find the highest value of x and y.
int x = 5;
int y = 10;
Math.(x, y);

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.
What is a virtual base class in C++?

The virtual base class is used when a derived class has multiple copies of the base class.
#include <iostream>
using namespace std;
class B {
   public: int b;
};

class D1 : public B {
   public: int d1;
};

class D2 : public B {
   public: int d2;
};

class D3 : public D1, public D2 {
   public: int d3;
};

int main() {
   D3 obj;

   obj.b = 40; //Statement 1, error will occur
   obj.b = 30; //statement 2, error will occur
   obj.d1 = 60;
   obj.d2 = 70;
   obj.d3 = 80;

   cout<< "\n B : "<< obj.b
   cout<< "\n D1 : "<< obj.d1;
   cout<< "\n D2: "<< obj.d2;
   cout<< "\n D3: "<< obj.d3;
}
In the above example, both D1 & D2 inherit B, they both have a single copy of B. However, D3 inherit both D1 & D2, therefore D3 have two copies of B, one from D1 and another from D2.
Statement 1 and 2 in above example will generate error, as compiler can't differentiate between two copies of b in D3.
To remove multiple copies of B from D3, we must inherit B in D1 and D3 as virtual class.
So, above example using virtual base class will be −
 Live Demo
#include<iostream>
using namespace std;
class B {
   public: int b;
};

class D1 : virtual public B {
   public: int d1;
};

class D2 : virtual public B {
   public: int d2;
};

class D3 : public D1, public D2 {
   public: int d3;
};

int main() {
   D3 obj;

   obj.b = 40; // statement 3
   obj.b = 30; // statement 4

   obj.d1 = 60;
   obj.d2 = 70;
   obj.d3 = 80;

   cout<< "\n B : "<< obj.b;
   cout<< "\n D1 : "<< obj.d1;
   cout<< "\n D2 : "<< obj.d2;
   cout<< "\n D3 : "<< obj.d3;
}
B : 30
D1 : 60
D2 : 70
D3 : 80
Now, D3 have only one copy of B and statement 4 will overwrite the value of b, given in statement 3.
Kth Smallest Element in a BST in Python

Suppose we have a binary search tree. We have to find the Kth smallest element in that BST. So if the tree is like −
So if we want to find 3rd smallest element, then k = 3, and result will be 7.
To solve this, we will follow these steps −
create one empty list called nodes
call solve(root, nodes)
return k – 1th element of nodes
the solve method is created, this takes root and nodes array, this will work as follows −
if root is null, then return
solve(left of root, nodes)
add value of root into the nodes array
solve(right of root, nodes)
Let us see the following implementation to get better understanding −
 Live Demo
class TreeNode:
   def __init__(self, data, left = None, right = None):
      self.data = data
      self.left = left
      self.right = right
def insert(temp,data):
   que = []
   que.append(temp)
   while (len(que)):
      temp = que[0]
      que.pop(0)
      if (not temp.left):
         temp.left = TreeNode(data)
         break
      else:
         que.append(temp.left)
      if (not temp.right):
         temp.right = TreeNode(data)
         break
      else:
         que.append(temp.right)
def make_tree(elements):
   Tree = TreeNode(elements[0])
   for element in elements[1:]:
      insert(Tree, element)
   return Tree
class Solution(object):
   def kthSmallest(self, root, k):
      nodes = []
      self.solve(root,nodes)
      return nodes[k-1]
   def solve(self, root,nodes):
      if root == None:
         return
      self.solve(root.left,nodes)
      nodes.append(root.data)
      self.solve(root.right,nodes)
ob1 = Solution()
tree = make_tree([10,5,15,2,7,13])
print(ob1.kthSmallest(tree, 3))
[10,5,15,2,7,13]
3
7
Python Identity Operators Example

Identity operators compare the memory locations of two objects. There are two Identity operators as explained below −
#!/usr/bin/python

a = 20
b = 20

if ( a is b ):
   print "Line 1 - a and b have same identity"
else:
   print "Line 1 - a and b do not have same identity"

if ( id(a) == id(b) ):
   print "Line 2 - a and b have same identity"
else:
   print "Line 2 - a and b do not have same identity"

b = 30
if ( a is b ):
   print "Line 3 - a and b have same identity"
else:
   print "Line 3 - a and b do not have same identity"

if ( a is not b ):
   print "Line 4 - a and b do not have same identity"
else:
   print "Line 4 - a and b have same identity"

When you execute the above program it produces the following result −
Line 1 - a and b have same identity
Line 2 - a and b have same identity
Line 3 - a and b do not have same identity
Line 4 - a and b do not have same identity


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
Creating SVG Image using PyCairo - GeeksforGeeks

12 Nov, 2020
In this article we will see how we can create SVG file using PyCairo in Python. 
SVG : An SVG file is a graphics file that uses a two-dimensional graphic vector format that defines images using an XML-based text format. As a standard format for showing vector graphics on the web, SVG files are developed.
PyCairo : It is a Python module providing bindings for the cairo graphics library.This library is used for creating SVG i.e vector files in python. In order to install the pycairo module we will use the command given below  
Installation:
pip install pycairo

Opening SVG file : The easiest and quickest way to open an SVG file to view it (read only) is with a modern web browser like Chrome, Firefox, Edge, or Internet Explorer—nearly all of them should provide some sort of rendering support for the SVG format.  
Steps-by-step Approach: 1. Import the cairo module. 2. Create an SVG surface and add context to it. 3. For creating a small face add two rectangles for eyes. 4. Add a curve line for the smile. 5. Set the color and width of the context.  
Below is the complete program based on the above approach:
Python3
# importing pycairoimport cairo  # creating a SVG surface# here geek is file name & 700, 700 is dimensionwith cairo.SVGSurface("geek.svg", 700, 700) as surface:      # creating a cairo context object    context = cairo.Context(surface)      # creating a rectangle(square) for left eye    context.rectangle(100, 100, 100, 100)      # creating a rectangle(square) for right eye    context.rectangle(500, 100, 100, 100)      # creating position for the curves    x, y, x1, y1 = 0.1, 0.5, 0.4, 0.9    x2, y2, x3, y3 = 0.4, 0.1, 0.9, 0.6      # setting scale of the context    context.scale(700, 700)      # setting line width of the context    context.set_line_width(0.04)      # move the context to x,y position    context.move_to(x, y)      # draw the curve for smile    context.curve_to(x1, y1, x2, y2, x3, y3)      # setting color of the context    context.set_source_rgba(0.4, 1, 0.4, 1)      # stroke out the color and width property    context.stroke()    # printing message when file is savedprint("File Saved")
Output:  
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Python program to convert a list to string
Reading and Writing to text files in Python
sum() function in Python
Writing data to a file using BufferedWriter class in Java

The BufferedWriter class of Java is used to write a stream of characters to the specified destination (character-output stream). It initially stores all the characters in a buffer and pushes the contents of the buffer to the destination, making the writing of characters, arrays and Strings efficient.
You can specify the required size of the buffer at the time of instantiating this class.
In the following Java program, we are trying to print a line on the console (Standard Output Stream). Here we are invoking the write() method by passing the required String.
 Live Demo
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
public class BufferedWriterExample {
   public static void main(String args[]) throws IOException {
      //Instantiating the OutputStreamWriter class
      OutputStreamWriter out = new OutputStreamWriter(System.out);
      //Instantiating the BufferedWriter
      BufferedWriter writer = new BufferedWriter(out);
      //Writing data to the console
      writer.write("Hello welcome to Tutorialspoint");
      writer.flush();
   }
}
Hello welcome to Tutorialspoint
What is C unconditional jump statements?

C programming language allows jumping from one statement to another. It also supports break, continue, return and go to jump statements.
It is a keyword which is used to terminate the loop (or) exit from the block.
The control jumps to next statement after the loop (or) block.
break is used with for, while, do-while and switch statement.
When break is used in nested loops then, only the innermost loop is terminated.
The syntax for break statement is as follows −
Following is the C program for break statement −
 Live Demo
#include<stdio.h>
main( ){
   int i;
   for (i=1; i<=5; i++){
      printf ("%d", i);
      if (i==3)
      break;
   }
}
When the above program is executed, it produces the following output −
1 2 3
The syntax for the continue statement is as follows −
Following is the C program for the continue statement −
#include<stdio.h>
main( ){
   int i;
   for (i=1; i<=5; i++){
      if (i==2)
      continue;
      printf("%d", i)
   }
}
When the above program is executed, it produces the following output −
1 2 3 4 5
It terminates the execution of function and returns the control of calling function
The syntax for return statement is as follows −
return[expression/value];
Following is the C program for the return statement −
 Live Demo
#include<stdio.h>
main(){
   int a,b,c;
   printf("enter a and b value:");
   scanf("%d%d",&a,&b);
   c=a*b;
   return(c);
}
When the above program is executed, it produces the following output −
enter a and b value:2 4
Process returned 8 (0x8)
It is used after the normal sequence of program execution by transferring the control to some other part of program.
The syntax for the goto statement is as follows −
Following is the C program for the goto statement −
 Live Demo
#include<stdio.h>
main( ) {
   printf("Hello");
   goto l1;
   printf("How are");
   l1: printf("you");
}
When the above program is executed, it produces the following output −
Hello you
Java Examples - Multiple exception (divided by zero)

How to use handle multiple exceptions (devided by zero) ?
This example shows how to handle multiple exceptions while deviding by zero ?
public class Main {
   public static void main (String args[]) {
      int array[] = {20,20,40};
      int num1 = 15, num2 = 0;
      int result = 0;
      try {
         result = num1/num2;
         System.out.println("The result is" +result);
         
         for(int i = 2; i >= 0; i--) {
            System.out.println("The value of array is" +array[i]);
         }
      } catch (ArrayIndexOutOfBoundsException e) {
         System.out.println("Error. Array is out of Bounds"+e);
      } catch (ArithmeticException e) {
         System.out.println ("Can't be divided by Zero"+e);
      }
   }
}
The above code sample will produce the following result.
Can't be divided by Zerojava.lang.ArithmeticException: / by zero

The following is an another example to use handle multiple exceptions in Java.
public class JavaApplication4 { 
   public static void main(String args[]) { 
      try { 
         int a[] = new int[5];
         a[5] = 30/0;  
      }  
      catch(ArithmeticException e){System.out.println("task1 is completed");}  
      catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed");}  
      catch(Exception e){System.out.println("common task completed");}
      System.out.println("rest of the code...");  
   }  
} 
The above code sample will produce the following result.
task1 is completed
rest of the code...

 Print
 Add Notes
 Bookmark this page
How do I insert a NULL value in MySQL?

To insert a NULL value, you can use UPDATE command. Following is the syntax −
UPDATE yourTableName SET yourColumnName=NULL;
Let us first create a table −
mysql> create table insertNullValue
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> ClientName varchar(100),
   -> ClientCountryName varchar(20)
   -> );
Query OK, 0 rows affected (0.54 sec)
Following is the query to insert some records in the table using insert command −
mysql> insert into insertNullValue(ClientName,ClientCountryName) values('Larry','US');
Query OK, 1 row affected (0.19 sec)

mysql> insert into insertNullValue(ClientName,ClientCountryName) values('David','AUS');
Query OK, 1 row affected (0.09 sec)

mysql> insert into insertNullValue(ClientName,ClientCountryName) values('Bob','UK');
Query OK, 1 row affected (0.17 sec)
Following is the query to display all records from the table using select statement −
mysql> select * from insertNullValue;
This will produce the following output −
+----+------------+-------------------+
| Id | ClientName | ClientCountryName |
+----+------------+-------------------+
| 1  | Larry      | US                |
| 2  | David      | AUS               |
| 3  | Bob        | UK                |
+----+------------+-------------------+
3 rows in set (0.00 sec)
Following is the query to insert NULL value for a column −
mysql> update insertNullValue set ClientCountryName=NULL;
Query OK, 3 rows affected (0.19 sec)
Rows matched: 3 Changed: 3 Warnings: 0
Let us check the NULL value is inserted for the column ‘ClientCountryName’ or not. Following is the query −
mysql> select * from insertNullValue;
This will produce the following output displaying the NULL values −
+----+------------+-------------------+
| Id | ClientName | ClientCountryName |
+----+------------+-------------------+
| 1  | Larry      | NULL              |
| 2  | David      | NULL              |
| 3  | Bob        | NULL              |
+----+------------+-------------------+
3 rows in set (0.00 sec)
Java Examples - Display hour and minute

How to display hour and minute (current time)?
This example demonstrates how to display the hour and minute of that moment by using Calender.getInstance() of Calender class.
import java.util.Calendar;
import java.util.Formatter;

public class MainClass{
   public static void main(String args[]) {
      Formatter fmt = new Formatter();
      Calendar cal = Calendar.getInstance();
      fmt = new Formatter();
      fmt.format("%tl:%tM", cal, cal);
      System.out.println(fmt);
   }
}
The above code sample will produce the following result. The result will change depending upon the current system time.
09:12

The following is an another sample example of Hour and minute
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class HelloWorld { 
   public static void main(String[] args) { 
      Calendar now = Calendar.getInstance();
      System.out.println(now.get(Calendar.HOUR_OF_DAY) + ":" + now.get(Calendar.MINUTE));
   }
}
The above code sample will produce the following result. The result will change depending upon the current system time.
5:31

 Print
 Add Notes
 Bookmark this page
How to count the number of documents in a MongoDB collection?

Following is the syntax to count the number of documents in a MongoDB collection
let anyVariableName= db.getCollection(‘yourCollectionName’);
yourVariableName.count();
Let us first create a collection with documents
> db.countNumberOfDocumentsDemo.insertOne({"CustomerName":"Bob"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9a5e2015e86fd1496b38a1")
}
>db.countNumberOfDocumentsDemo.insertOne({"CustomerName":"Ramit","CustomerAge":23});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9a5e3515e86fd1496b38a2")
}
>db.countNumberOfDocumentsDemo.insertOne({"CustomerName":"Adam","CustomerAge":27,"CustomerCountryName":"US"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9a5e4c15e86fd1496b38a3")
}
Following is the query to display all documents from a collection with the help of find() method
> db.countNumberOfDocumentsDemo.find().pretty();
This will produce the following output
{ "_id" : ObjectId("5c9a5e2015e86fd1496b38a1"), "CustomerName" : "Bob" }
{
   "_id" : ObjectId("5c9a5e3515e86fd1496b38a2"),
   "CustomerName" : "Ramit",
   "CustomerAge" : 23
}
{
   "_id" : ObjectId("5c9a5e4c15e86fd1496b38a3"),
   "CustomerName" : "Adam",
   "CustomerAge" : 27,
   "CustomerCountryName" : "US"
}
Following is the query to count the number of documents in a MongoDB collection,
> let myCollectionName = db.getCollection('countNumberOfDocumentsDemo');
> myCollectionName.count();
This will produce the following output
3
How to eliminate repeated lines in a python function?

Let us name the given text file as bar.txt
We use file handling methods in python to remove duplicate lines in python text file or function. The text file or function has to be in the same directory as the python program file. Following code is one way of removing duplicates in a text file bar.txt and the output is stored in foo.txt. These files should be in the same directory as the python script file, else it won’t work.
The file bar.txt is as follows
A cow is an animal.
A cow is an animal.
A buffalo too is an animal.
Lion is the king of jungle.
The code below removes the duplicate lines in bar.txt and stores in foo.txt
# This program opens file bar.txt and removes duplicate lines and writes the
# contents to foo.txt file.
lines_seen = set()  # holds lines already seen
outfile = open('foo.txt', "w")
infile = open('bar.txt', "r")
print "The file bar.txt is as follows"
for line in infile:
    print line
    if line not in lines_seen:  # not a duplicate
        outfile.write(line)
        lines_seen.add(line)
outfile.close()
print "The file foo.txt is as follows"
for line in open('foo.txt', "r"):
    print line

The file foo.txt is as follows
A cow is an animal.
A buffalo too is an animal.
Lion is the king of jungle.
How to make Marquee text in Android?

This example demonstrate about how to make Marquee text in Android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version = "1.0" encoding = "utf-8"?>
<RelativeLayout
   xmlns:android = "http://schemas.android.com/apk/res/android"
   xmlns:tools = "http://schemas.android.com/tools"
   android:layout_width = "match_parent"
   android:gravity = "center"
   android:layout_height = "match_parent">
   <TextView
      android:id = "@+id/text"
      android:textSize = "20dp"
      android:textAlignment = "center"
      android:layout_width = "match_parent"
      android:ellipsize = "marquee"
      android:fadingEdge = "horizontal"
      android:marqueeRepeatLimit = "marquee_forever"
      android:scrollHorizontally = "true"
      android:textColor = "#ff4500"
      android:text = "Simple application that shows how to use marquee, with a long text"
      android:layout_height = "wrap_content"
      android:singleLine = "true" />
</RelativeLayout>
In the above code, we have taken text view and ellipsize property as marquee as shown below -
android:ellipsize = "marquee"
android:fadingEdge = "horizontal"
android:marqueeRepeatLimit = "marquee_forever"
android:scrollHorizontally = "true"
android:singleLine = "true"
Step 3 − Add the following code to src/MainActivity.java
package com.example.andy.myapplication;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      TextView txt = findViewById(R.id.text);
      txt.setSelected(true);
   }
}
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run   icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
In the above result, text view will scroll from right to left with scroll animation.
Click here to download the project code
How can I convert an array to an object by splitting strings? JavaScript

Let’s say, we have an array of strings in which each value each element has a dash (-), left to
which we have our key and right to which we have our value. Our job is to split these strings and
form an object out of this array.
Here is the sample array −
const arr = ["name-Rakesh", "age-23", "city-New Delhi", "jobType-remote",
"language-English"];
So, let’s write the code, it will loop over the array splitting each string and feeding it into the new
object
The full code will be −
const arr = ["name-Rakesh", "age-23", "city-New Delhi", "jobType-remote",
"language-English"];
const obj = {};
arr.forEach(string => {
   const [key, value] = string.split("-");
   obj[key] = value;
});
console.log(obj);
The console output for this code will be −
{
   name: 'Rakesh',
   age: '23',
   city: 'New Delhi',
   jobType: 'remote',
   language: 'English'
}
Sort list elements in descending order in C#

The following is our list with elements −
IList<Employee> emp = new List<Employee>() {
   new Employee() { EmployeeRank = 4, EmpName = "Amit", EmpMarks = 90 } ,
   new Employee() { EmployeeRank = 05, EmpName = "Raman", EmpMarks = 95 }
};
Now use orderby and descending to sort elements in descending order.
var res = from str in emp orderby str.EmpName descending select str;
 Live Demo
using System;
using System.Linq;
using System.Collections.Generic;
public class Demo {
   public static void Main() {
      IList<Employee> emp = new List<Employee>() {
         new Employee() { EmployeeRank = 4, EmpName = "Amit", EmpMarks = 90 } ,
         new Employee() { EmployeeRank = 05, EmpName = "Raman", EmpMarks = 95 }
      };
      var res = from str in emp orderby str.EmpName descending select str;
      Console.WriteLine("Student List (Descending Order):");
      foreach (var list in res)
      Console.WriteLine(list.EmpName);
   }
}

public class Employee {
   public int EmployeeRank { get; set; }
   public string EmpName { get; set; }
   public int EmpMarks { get; set; }
}
Student List (Descending Order):
Raman
Amit
Create a Pie Chart using Recharts in ReactJS - GeeksforGeeks

27 Jul, 2021
Introduction: Rechart JS is a library that is used for creating charts for React JS. This library is used for building Line charts, Bar charts, Pie charts, etc, with the help of React and D3 (Data-Driven Documents).  
To create Pie Chart using Recharts, we create a dataset which contains actual data. Then we define the slices using pie element with data property which will have the data of the dataset created and with datakey property which is the property name with a value for the slices.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command.npx create-react-app foldername
Step 1: Create a React application using the following command.
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command.cd foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command.
cd foldername
Step 3: After creating the ReactJS application, Install the required modules using the following command.npm install --save recharts
Step 3: After creating the ReactJS application, Install the required modules using the following command.
npm install --save recharts
Project Structure: It will look like the following.
Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
App.js
import React from 'react';import { PieChart, Pie} from 'recharts';    const App = () => {  // Sample dataconst data = [  {name: 'Geeksforgeeks', students: 400},  {name: 'Technical scripter', students: 700},  {name: 'Geek-i-knack', students: 200},  {name: 'Geek-o-mania', students: 1000}];    return (        <PieChart width={700} height={700}>          <Pie data={data} dataKey="students" outerRadius={250} fill="green" />        </PieChart>);}  export default App;
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
Output
React-Questions
Recharts
JavaScript
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
Remove elements from a JavaScript Array
How to get character array from string in JavaScript?
How to filter object array based on attributes?
How to fetch data from an API in ReactJS ?
How to redirect to another page in ReactJS ?
How to pass data from child component to its parent in ReactJS ?
How to pass data from one component to other component in ReactJS ?
ReactJS Functional Components
VB.Net - Nested Loops

VB.Net allows using one loop inside another loop. Following section shows few examples to illustrate the concept.
The syntax for a nested For loop statement in VB.Net  is as follows −
For counter1 [ As datatype1 ] = start1 To end1 [ Step step1 ]
   For counter2 [ As datatype2 ] = start2 To end2 [ Step step2 ]
      ...
   Next [ counter2 ]
Next [ counter 1]

The syntax for a nested While loop statement in VB.Net is as follows −
While condition1
   While condition2
      ...
   End While
End While

The syntax for a nested Do...While loop statement in VB.Net is as follows −
Do { While | Until } condition1
   Do { While | Until } condition2
      ...
   Loop
Loop

A final note on loop nesting is that you can put any type of loop inside of any other type of loop. For example, a for loop can be inside a while loop or vice versa.
The following program uses a nested for loop to find the prime numbers from 2 to 100 −
Module loops
   Sub Main()
      ' local variable definition 
      Dim i, j As Integer
      For i = 2 To 100
         For j = 2 To i
            ' if factor found, not prime
            If ((i Mod j) = 0) Then
               Exit For
            End If
         Next j
            If (j > (i \ j)) Then
               Console.WriteLine("{0} is prime", i)
            End If
         Next i
      Console.ReadLine()
   End Sub
End Module
When the above code is compiled and executed, it produces the following result −
2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
23 is prime
29 is prime
31 is prime
37 is prime
41 is prime
43 is prime
47 is prime
53 is prime
59 is prime
61 is prime
67 is prime
71 is prime
73 is prime
79 is prime
83 is prime
89 is prime
97 is prime


    63 Lectures 
     4 hours 

 Frahaan Hussain

    103 Lectures 
     12 hours 

 Arnold Higuit

    60 Lectures 
     9.5 hours 

 Arnold Higuit

    97 Lectures 
     9 hours 

 Arnold Higuit
 Print
 Add Notes
 Bookmark this page
Get greatest repetitive item in array JavaScript

We have an array of Number / String literals that contains some values (some are repetitive as
well). Our job is to write a function that returns the element from the array which appears for the
greatest number of times in the array.
For example − if the input array is −
const input = ['a', 'v', 'k', 'f', 'a', 'f', 's', 'd', 'd', 'f', 'a', 'j',
'a'];
Then the output should be −
'a'
because 'a' gets repeated for the maximum number of times
Therefore, let’s write the code for this. We will use a Map() to keep track of all the elements we
encounter and their count, and at last return the element with maximum count like this −
const input = ['m', 'a', 'v', 'k', 'f', 'a', 'f', 's', 'd', 'd', 'f', 'a',
'j', 'a'];
const findMaximum = arr => {
   const map = arr.reduce((acc, val) => {
      let count = acc.get(val);
      if(count){
         acc.set(val, ++count);
      } else {
         acc.set(val, 1);
      };
      return acc;
   }, new Map());
   return Array.from(map).reduce((acc, val) => {
      if(val[1] > acc[1]){
         return val;
      };
      return acc;
   }, [0, 0])[0];
};
console.log(findMaximum(input));
The output in the console will be −
a
What are final classes in Java?

The final modifier for finalizing the implementations of classes, methods, and variables.
The main purpose of using a class being declared as final is to prevent the class from being subclassed. If a class is marked as final then no class can inherit any feature from the final class.
You cannot extend a final class. If you try it gives you a compile time error.
final class Super {
   private int data = 30;
}
public class Sub extends Super{
   public static void main(String args[]){
   }
}
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
   at newJavaExamples.Sub.main(Sub.java:9)
Evaluate and Quote an Expression in R Programming - bquote() Function - GeeksforGeeks

16 Jun, 2020
bquote() function in R Language is used to quote the arguments passed to it, except the values which are wrapped in ‘.()‘. It evaluates the wrapped values and quotes the result.
Syntax: bquote(expr)
Parameters:expr: language object
Example 1:
# R program to quote an expression  # Assigning value to variablex <- 10  # Calling bquote() Functionbquote(x == x)bquote(x == 10)bquote(x == .(x))bquote(x == .(x * 2))
Output:
x == x
x == 10
x == 10
x == 20

Example 2:
# R program to quote an expression  # Assigning value to variablez <- 10  # Calling bquote() Functionbquote(function(x, y = .(z)) x + y)  # Plotting a graph with the default valueplot(1:10, z+(1:10), main = bquote(z == .(z)))
Output:
function(x, y = 10) x + y

R String-Functions
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
R - if statement
How to import an Excel File into R ?
Plot mean and standard deviation using ggplot2 in R
How to filter R dataframe by multiple conditions?