code-rag-bench/online-tutorials huggingface dataset:
C++ | Inheritance | Question 1 - GeeksforGeeks

28 Jun, 2021
#include<iostream>   using namespace std;class Base1 { public:     Base1()     { cout << " Base1's constructor called" << endl;  }};   class Base2 { public:     Base2()     { cout << "Base2's constructor called" << endl;  }};   class Derived: public Base1, public Base2 {   public:     Derived()     {  cout << "Derived's constructor called" << endl;  }};   int main(){   Derived d;   return 0;}
(A) Compiler Dependent(B) Base1′s constructor calledBase2′s constructor calledDerived’s constructor called(C) Base2′s constructor calledBase1′s constructor calledDerived’s constructor called(D) Compiler ErrorAnswer: (B)Explanation: When a class inherits from multiple classes, constructors of base classes are called in the same order as they are specified in inheritance.Quiz of this Question
C++-Inheritance
Inheritance
C Language
C++ Quiz
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Function Pointer in C
Substring in C++
fork() in C
std::string class in C++
Enumeration (or enum) in C
C++ | new and delete | Question 4
C++ | new and delete | Question 1
C++ | References | Question 4
C++ | Virtual Functions | Question 12
C++ | Virtual Functions | Question 2
Lex program to find the Length of a String

30 Apr, 2019
Problem: Write a Lex program to find the Length of a String
Explanation:FLEX (Fast Lexical Analyzer Generator) is a computer program that generates lexical analyzers and was written by Mike Lesk and Eric Schmidt. Lex reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in the C programming language.
Examples:
Input: geeksforgeeks
Output: length of given string is : 13

Input: geeks
Output: length of given string is : 5 
Implementation:
/*lex program to find the length of a string*/  %{  #include<stdio.h>   int  length;%}  /* Rules Section*/%%  [a-z A-Z 0-9]+ {length=yyleng; }%%  int main() {  yylex();  printf("length of given string is : %d", length);  return 0; }
Output:
Lex program
C Programs
Compiler Design
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Lodash _.difference() Function

12 May, 2021
The _.difference() function is used to remove a single element or the array of elements from the original array. This function works pretty much same as the core function of JavaScript i.e filter.
Syntax :
_.difference(array, [values]);
Parameters: This function accept two parameters as mentioned above and described below:
array: It is the array from which different elements are to be removed.
values: It is the array of values that are to be removed from the original array.
Note: 
We can use single value or the array of values. But if only single Integer is given then it will not effect the original array.
Please install the library before going further using npm install lodash.
Below examples illustrate the _.difference() function in Lodash:
Example 1: When array of values is given. 
Javascript
// Requiring the lodash librarylet lodash = require("lodash"); // Original arraylet array = ["a", 2, 3]; // Values to be removed from// the original arraylet values = [2, 3]let newArray = lodash.difference(array, values);console.log("Before: ", array); // Printing arrayconsole.log("After: ", newArray);
Output:
Example 2: When an empty array is given, there will be no change in the origin a array.
Javascript
// Requiring the lodash librarylet lodash = require("lodash"); // Original arraylet array = ["a", 2, 3]; // Values to be removed from// the original arraylet values = []let newArray = lodash.difference(array, values);console.log("Before: ", array); // Printing arrayconsole.log("After: ", newArray);
Output:
Note: This function returns the original array if the value array is single value, empty array or object of arrays.
simmytarika5
JavaScript-Lodash
JavaScript
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
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Hide or show elements in HTML using display property
Difference Between PUT and PATCH Request
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Nested printf (printf inside printf) in C

13 Dec, 2018
Predict the output of the following C program with a printf inside printf.
#include<stdio.h>   int main(){   int x = 1987;   printf("%d", printf("%d", printf("%d", x)));   return(0);}
Output :
198741

Explanation :1. Firstly, the innermost printf is executed which results in printing 1987
2. This printf returns total number of digits in 1987 i.e 4. printf() returns number of characters successfully printed on screen. The whole statement reduces to :
printf("%d", printf("%d", 4));
3. The second printf then prints 4 and returns the total number of digits in 4 i.e 1 (4 is single digit number ).
4. Finally, the whole statement simply reduces to :
printf("%d", 1);
5. It simply prints 1 and output will be :
Output:
198741

So, when multiple printf’s appear inside another printf, the inner printf prints its output and returns length of the string printed on the screen to the outer printf.
This article is contributed by Rishav Raj. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@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.
C-Input and Output Quiz
c-input-output
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SimpleDateFormat(“hh:mm:ss a”) in Java

The following format displays time from −
hh:mm:ss
The following format displays time with AM/ PM marker −
hh:mm:ss a
Here, we are using the SimpleDateFormat class to display date and time. Let us set it for the format we want i.e time and AM/PM Marker −
Format f = new SimpleDateFormat("hh:mm:ss a");
String strResult = f.format(new Date());
System.out.println("Time = "+strResult);
The following is an example −
 Live Demo
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Calendar;
public class Demo {
   public static void main(String[] args) throws Exception {
      // displaying current date and time
      Calendar cal = Calendar.getInstance();
      SimpleDateFormat simpleformat = new SimpleDateFormat("dd/MMMM/yyyy hh:mm:s zzzz");
      System.out.println("Today's date = "+simpleformat.format(cal.getTime()));
      // current time
      Format f = new SimpleDateFormat("hh:mm:ss a");
      String strResult = f.format(new Date());
      System.out.println("Time = "+strResult);
      // displaying hour
      f = new SimpleDateFormat("H");
      String strHour = f.format(new Date());
      System.out.println("Current Hour = "+strHour);
      // displaying minutes
      f = new SimpleDateFormat("mm");
      String strMinute = f.format(new Date());
      System.out.println("Current Minutes = "+strMinute);
      // displaying seconds
      f = new SimpleDateFormat("ss");
      String strSeconds = f.format(new Date());
      System.out.println("Current Seconds = "+strSeconds);
   }
}
Today's date = 26/November/2018 08:27:34 Coordinated Universal Time
Time = 08:27:34 AM
Current Hour = 8
Current Minutes = 27
Current Seconds = 34
Initialize Matrix in Python

In this article, we will learn about how we can initialize matrix using two dimensional list in Python 3.x. Or earlier.
Let’s see the intuitive way to initialize a matrix that only python language offers. Here we take advantage of List comprehension. we initialise the inner list and then extend to multiple rows using the list comprehension.
# input the number of rows
N = 3
# input the number of columns
M = 3
# initializing the matrix
res = [ [ i*j for i in range(N) ] for j in range(M) ]

# printing the matrix on screen row by row in a single line
print("Inline representation:")
[ [ print(res[i][j] ,end =" ") for i in range(N) ] for j in range(M) ]
print("")
# printing in multiple lines
print("Multiline representation")
for i in range(N):
   for j in range(M):
      print(res[i][j] ,end =" ")
   print("")
Inline representation:
0 0 0 0 1 2 0 2 4
Multiline representation
0 0 0
0 1 2
0 2 4
Now let's see the general way which can be implemented in any language. This is the standard way of creating a matrix or multidimensional-array
# input the number of rows
N = 3
# input the number of columns
M = 3
lis=[[0,0,0],[0,0,0],[0,0,0]]
# initializing the matrix
for i in range(N):
   for j in range(M):
      lis[i][j]=i
# multiline representation
for i in range(N):
   for j in range(M):
      print(lis[i][j],end=" ")
   print("")
0 0 0
0 1 2
0 2 4
In this article, we learned how to implement logic gates in Python 3.x. Or
earlier. We also learned about two universal gates i.e. NAND and NOR gates.
PHP | Sum of digits of a number

09 Mar, 2018
This is a simple PHP program where we need to calculate the sum of all digits of a number.Examples:
Input : 711 
Output : 9

Input : 14785
Output : 25

In this program, we will try to accept a number in the form of a string and then iterate through the length of the string. While iterating we will extract the digit from each position and then add them to the previously extracted digit, thus getting the sum.
<?php// PHP program to calculate the sum of digitsfunction sum($num) {    $sum = 0;    for ($i = 0; $i < strlen($num); $i++){        $sum += $num[$i];    }    return $sum;}  // Driver Code$num = "711";echo sum($num);?>
Output:
9

PHP-basics
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to Upload Image into Database and Display it using PHP ?
How to check whether an array is empty using PHP?
PHP | Converting string to Date and DateTime
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Animate Bootstrap progress bar

Follow the below given steps to create an animated progress bar:
Add a <div> with a class of .progress and .progress-striped. Also, add class .active to .progress-striped.
Next, inside the above <div>, add an empty <div> with a class of .progress-bar.
Add a style attribute with the width expressed as a percentage. Say for example, style = "60%"; indicates that the progress bar was at 60%.
You can try to run the following code to create animated progress bar −
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>Bootstrap Example</title>
      <link href = "/bootstrap/css/bootstrap.min.css" rel = "stylesheet">
      <script src = "/scripts/jquery.min.js"></script>
      <script src = "/bootstrap/js/bootstrap.min.js"></script>
   </head>
   <body>
      <h2>Progress Bar</h2>
      <h3>Normal Progress Bar</h3>
      <div class = "progress progress-striped">
         <div class = "progress-bar progress-bar-success" role = "progressbar"
            aria-valuenow = "45" aria-valuemin = "0" aria-valuemax = "100" style = "width: 45%;">
            <span class = "sr-only">45%Complete (success)</span>
         </div>
      </div>

      <h3>Animated Progress Bar</h3>
      <div class = "progress progress-striped active">
         <div class = "progress-bar progress-bar-success" role = "progressbar"
            aria-valuenow = "60" aria-valuemin = "0" aria-valuemax = "100" style = "width: 40%;">
            <span class = "sr-only">40% Complete</span>
         </div>
      </div>
   </body>
</html>
Difference between the Constructors and Methods - GeeksforGeeks

14 May, 2019
Java is a pure OOPS concept based programming language. Hence in Java, all the variables, data and the statements must be present in classes. These classes consist of both constructors and methods. Methods and Constructors are different from each other in a lot of ways.
Constructors:Constructors are used to initialize the object’s state. Like methods, a constructor also contains collection of statements(i.e. instructions) that are executed at time of Object creation. Each time an object is created using new() keyword at least one constructor (it could be default constructor) is invoked to assign initial values to the data members of the same class.
Example:
// Java Program to illustrate constructor  import java.io.*;  class Geek {    int num;    String name;      // This would be invoked while an object    // of that class created.    Geek()    {        System.out.println("Constructor called");    }}  class GFG {    public static void main(String[] args)    {        // this would invoke default constructor.        Geek geek1 = new Geek();          // Default constructor provides the default        // values to the object like 0, null        System.out.println(geek1.name);        System.out.println(geek1.num);    }}
Constructor called
null
0

Methods:A method is a collection of statements that perform some specific task and return the result to the caller. A method can perform some specific task without returning anything. Methods allow us to reuse the code without retyping the code. In Java, every method must be part of some class which is different from languages like C, C++, and Python.
Example:
// Java Program to illustrate methods  import java.io.*;  class Addition {      int sum = 0;      public int addTwoInt(int a, int b)    {          // Adding two integer value.        sum = a + b;          // Returning summation of two values.        return sum;    }}  class GFG {    public static void main(String[] args)    {          // Creating an instance of Addition class        Addition add = new Addition();          // Calling addTwoInt() method        // to add two integer        // using instance created        // in above step.        int s = add.addTwoInt(1, 2);          System.out.println("Sum of two "                           + "integer values: "                           + s);    }}
Sum of two integer values: 3

Differences between Constructors and Methods:
Akanksha_Rai
Java-Constructors
Java-Functions
Java-Object Oriented
Picked
Difference Between
Java
Java
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 Process and Thread
Stack vs Heap Memory Allocation
Difference Between Method Overloading and Method Overriding in Java
Differences between JDK, JRE and JVM
For-each loop in Java
Reverse a string in Java
Arrays.sort() in Java with examples
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
DateTime.ToOADate() Method in C# - GeeksforGeeks

13 Feb, 2019
This method is used to convert the value of this instance to the equivalent OLE Automation date.
Syntax: public double ToOADate ();
Return Value: This method returns a double-precision floating-point number that contains an OLE Automation date equivalent to the value of this instance.
Exception:OverflowException: If the value of this instance cannot be represented as an OLE Automation Date.
Below programs illustrate the use of DateTime.ToOADate() Method
Example 1:
// C# program to demonstrate the// DateTime.ToOADate() Methodusing System;using System.Globalization;  class GFG {      // Main Method    public static void Main()    {        try {              // creating object of DateTime            DateTime date = new DateTime(2011, 1,                                     1, 4, 0, 15);              // Converts the value of this instance to            // the equivalent OLE Automation date.            // using ToOADate() method;            double value = date.ToOADate();              // Display the time            Console.WriteLine("OLE Automation date is {0}", value);        }          catch (OverflowException e) {            Console.Write("Exception Thrown: ");            Console.Write("{0}", e.GetType(), e.Message);        }    }}
OLE Automation date is 40544.1668402778

Example 2: For OverflowException
// C# program to demonstrate the// DateTime.ToOADate() Methodusing System;using System.Globalization;  class GFG {      // Main Method    public static void Main()    {        try {              // creating object of DateTime            DateTime date = new DateTime(0099, 1,                                         1, 4, 0, 15);              // Converts the value of this instance             // to the equivalent OLE Automation date.            // using ToOADate() method;            double value = date.ToOADate();              // Display the time            Console.WriteLine("OLE Automation date is {0}", value);        }          catch (OverflowException e)        {            Console.Write("Exception Thrown: ");            Console.Write("{0}", e.GetType(), e.Message);        }    }}
Exception Thrown: System.OverflowException

Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.datetime.tooadate?view=netframework-4.7.2
CSharp DateTime Struct
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Destructors in C#
Extension Method in C#
HashSet in C# with Examples
Top 50 C# Interview Questions & Answers
C# | How to insert an element in an Array?
Partial Classes in C#
C# | Inheritance
C# | List Class
Difference between Hashtable and Dictionary in C#
Lambda Expressions in C#
Django REST Framework Installation - GeeksforGeeks

05 Oct, 2021
Django REST Framework can be installed via pip package similar to Django installation. Since Django REST Framework is a wrapper over default Django Framework, to install it, Django should be installed already. Now to install rest framework follow the below process.
Python
Pip
DjangoHow to install Django REST FrameworkTo install Django REST Framework on Windows, Linux or any operating system, one would need pip package. To check how to install pip on your operating system, checkoout – PIP Installation – Windows || Linux.Now, run a simple command,pip install djangorestframeworkWait and relax, REST framework would be installed shortly.Install Django REST Framework using Source codeOne can install Django REST Framework, using source code directly, install git command line utlity first, thengit clone https://github.com/encode/django-rest-frameworkafter cloning, it add it to bin directory where django is installed.Add rest_framework to INSTALLED_APPSFor Django REST Framework to work on top of Django, you need to add rest_framework in INSTALLED_APPS, in settings.py.INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework'
)
Bingo..!! Django REST Framework is successfully installed, one case use it in any app of Django.My Personal Notes
arrow_drop_upSave
To install Django REST Framework on Windows, Linux or any operating system, one would need pip package. To check how to install pip on your operating system, checkoout – PIP Installation – Windows || Linux.Now, run a simple command,
pip install djangorestframework
Wait and relax, REST framework would be installed shortly.
One can install Django REST Framework, using source code directly, install git command line utlity first, then
git clone https://github.com/encode/django-rest-framework
after cloning, it add it to bin directory where django is installed.
For Django REST Framework to work on top of Django, you need to add rest_framework in INSTALLED_APPS, in settings.py.
INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework'
)

Bingo..!! Django REST Framework is successfully installed, one case use it in any app of Django.
nidhi_biet
Django-REST
how-to-install
Python Django
Installation Guide
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install FFmpeg on Windows?
How to Install Anaconda on Windows?
How to Install and Run Apache Kafka on Windows?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Install Jupyter Notebook on MacOS?
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
get_property() element method - Selenium Python - GeeksforGeeks

27 Apr, 2020
Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout – Navigating links using get method – Selenium Python. Just being able to go to places isn’t terribly useful. What we’d really like to do is to interact with the pages, or, more specifically, the HTML elements within a page. There are multiple strategies to find an element using Selenium, checkout – Locating Strategies
This article revolves around how to use get_property method in Selenium. get_property method is used to get properties of an element, such as getting text_length property of anchor tag. This method will first try to return the value of a property with the given name. If a property with that name doesn’t exist, it returns the value of the property with the same name.Args:name – Name of the property to retrieve.
element.get_property("property name")
Example –
<a href="https://www.geeksforgeeks.org/" id="link" />Text Here</a>
To find an element one needs to use one of the locating strategies, For example,
element = driver.find_element_by_id("link")
element = driver.find_element_by_xpath("//a[@id='link']")
Also, to find multiple elements, we can use –
elements = driver.find_elements_by_id("link")
Now one can get property of this field with
text_length = element.get_property("text_length")
Let’s use https://www.geeksforgeeks.org/ to illustrate this method in Selenium Python . Here we get href property of courses tab in navigation bar at geeksforgeeks.Program –
# import webdriverfrom selenium import webdriver  # create webdriver objectdriver = webdriver.Firefox()  # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/")  # get element element = driver.find_element_by_link_text("Courses")  # get text_length propertyprint(element.get_property('href'))
Output-
Terminal Output –
Python-selenium
selenium
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Python Program to Convert Decimal to Hexadecimal - GeeksforGeeks

14 Sep, 2021
In this article, we will learn how to convert a decimal value(base 10) to a hexadecimal value (base 16) in Python. 
hex() function is one of the built-in functions in Python3, which is used to convert an integer number into its corresponding hexadecimal form.
Syntax : hex(x) 
Parameters : 
x – an integer number (int object)
Returns :  Returns hexadecimal string.
Errors and Exceptions :
TypeError :  Returns TypeError when anything other than
             integer type constants are passed as parameters.   
Code :
Python3
# Python3 program to illustrate# hex() function  print("The hexadecimal form of 69 is "      + hex(69))
Output:
The hexadecimal form of 69 is 0x45
The conventional method for converting decimal to hexadecimal is to divide it by 16 until it equals zero. The hexadecimal version of the given decimal number is the sequence of remainders from last to first in hexadecimal form. To convert remainders to hexadecimal form, use the following conversion table:
Code :
Python3
# Conversion table of remainders to# hexadecimal equivalentconversion_table = {0: '0', 1: '1', 2: '2', 3: '3', 4: '4',                    5: '5', 6: '6', 7: '7',                    8: '8', 9: '9', 10: 'A', 11: 'B', 12: 'C',                    13: 'D', 14: 'E', 15: 'F'}    # function which converts decimal value# to hexadecimal valuedef decimalToHexadecimal(decimal):    hexadecimal = ''    while(decimal > 0):        remainder = decimal % 16        hexadecimal = conversion_table[remainder] + hexadecimal        decimal = decimal // 16      return hexadecimal    decimal_number = 69print("The hexadecimal form of", decimal_number,      "is", decimalToHexadecimal(decimal_number))
Output:
The hexadecimal form of 69 is 45
The idea is similar to that used in the iterative approach.
Code :
Python3
# Conversion table of remainders to# hexadecimal equivalentconversion_table = {0: '0', 1: '1', 2: '2', 3: '3',                    4: '4', 5: '5', 6: '6', 7: '7',                    8: '8', 9: '9', 10: 'A', 11: 'B',                    12: 'C', 13: 'D', 14: 'E', 15: 'F'}    # function which converts decimal value# to hexadecimal valuedef decimalToHexadecimal(decimal):    if(decimal <= 0):        return ''    remainder = decimal % 16    return decimalToHexadecimal(decimal//16) + conversion_table[remainder]    decimal_number = 69print("The hexadecimal form of", decimal_number,      "is", decimalToHexadecimal(decimal_number))
Output:
The hexadecimal form of 69 is 45
Blogathon-2021
Numbers
Picked
Blogathon
Python
Python Programs
Numbers
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Create a Table With Multiple Foreign Keys in SQL?
How to Import JSON Data into SQL Server?
Stratified Sampling in Pandas
How to pass data into table from a form using React Components
SQL Query to Convert Datetime to Date
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
AngularJS | angular.toJson() Function - GeeksforGeeks

12 Apr, 2019
The angular.toJson() Function in AngularJS is used to serialize the javascript object into a JSON – formatted string. It takes the javascript object and returns JSON string.
Syntax:
angular.toJson(object)
Example:
<!DOCTYPE html><html>  <head>    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js">    </script>    <title>      angular.toJson()  </title></head>  <body ng-app="app"       style="text-align:center">    <h1 style="color:green">      GeeksforGeeks  </h1>    <h2>      angular.toJson()  </h2>    <div ng-controller="geek">        <button ng-click="showAlert()">          Click it!</button>    </div>    <script>        var app = angular.module("app", []);        app.controller('geek', ['$scope',                         function($scope) {                                         $scope.showAlert = function() {                var string = {                    'Name': 'Quick sort',                    'Type': 'sorting'                };                alert(angular.toJson(string));            }        }]);    </script></body>  </html>
Output:Before Click:After Click:
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Differences between Functional Components and Class Components in React
How to create footer to stay at the bottom of a Web page?
How to calculate the number of days between two dates in javascript?
Insertion sort in Java.

Following is the required program.
Live Demo
public class Tester {
   public static void insertionSort(int array[]) {  
      int n = array.length;  
      for (int j = 1; j < n; j++) {  
         int key = array[j];  
         int i = j-1;  
         while ( (i > -1) &amp;&amp; ( array [i] > key ) ){  
            array [i+1] = array [i];  
            i--;  
         }  
         array[i+1] = key;  
      }  
   }
   public static void main(String a[]){    
      int arr[] = {21,60,32,01,41,34,5};  
      System.out.println("Before Insertion Sort");    
      for(int i:arr){    
         System.out.print(i+" ");    
      }    
      System.out.println();    
      insertionSort(arr); //sorting array using insertion sort    
      System.out.println("After Insertion Sort");    
      for(int i:arr){    
         System.out.print(i+" ");    
      }    
   }  
}
Before Insertion Sort
21 60 32 1 41 34 5
After Insertion Sort
1 5 21 32 34 41 60
How to compress a file in Java?

The DeflaterOutputStream class of Java is used to compress the given data and stream it out to the destination.
The write() method of this class accepts the data (in integer and byte format), compresses it and, writes it to the destination of the current DeflaterOutputStream object. To compress a file using this method &Minus;
Create a FileInputStream object, by passing the path of the file to be compressed in String format, as a parameter to its constructor.
Create a FileOutputStream object, by passing the path of the output file, in String format, as a parameter to its constructor.
Create a DeflaterOutputStream object, by passing the above created FileOutputStream object, as a parameter to its constructor.
Then, read the contents of the input file and write using the write() method of the DeflaterOutputStream class.
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.DeflaterOutputStream;
public class CompressingFiles {
   public static void main(String args[]) throws IOException {
      //Instantiating the FileInputStream
      String inputPath = "D:\\ExampleDirectory\\logo.jpg";
      FileInputStream inputStream = new FileInputStream(inputPath);
      //Instantiating the FileOutputStream
      String outputPath = "D:\\ExampleDirectory\\compressedLogo.txt";
      FileOutputStream outputStream = new FileOutputStream(outputPath);
      //Instantiating the DeflaterOutputStream
      DeflaterOutputStream compresser = new DeflaterOutputStream(outputStream);
      int contents;
      while ((contents=inputStream.read())!=-1){
         compresser.write(contents);
      }
      compresser.close();
      System.out.println("File compressed.......");
   }
}
File compressed.......
How to set the alignment of the JLabel content along the Y axis in the bottom with Java

Set the alignment of the label’s content along the Y axis on the bottom, use the setVerticalAlignment() method and set the location. Let us first set a label component. We have set the label background color as well so that we can check the alignment of the label’s content properly  −
JLabel label = new JLabel("Project Name");
label.setPreferredSize(new Dimension(190, 100));
label.setOpaque(true);
label.setBackground(Color.GREEN);
label.setForeground(Color.WHITE);
Now, we will align the label content along the Y axis on the bottom by seeting location as BOTTOM −
label.setVerticalAlignment(JLabel.BOTTOM);
The following is an example to set the alignment of the label content along the Y axis in the bottom −
package my;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextArea;
import javax.swing.WindowConstants;
public class SwingDemo {
   public static void main(String[] args) {
      JFrame frame = new JFrame("Frame");
      frame.setLayout(new FlowLayout());
      JLabel label = new JLabel("Project Name");
      label.setPreferredSize(new Dimension(190, 100));
      label.setOpaque(true);
      label.setBackground(Color.GREEN);
      label.setForeground(Color.WHITE);
      Font font = new Font("Serif", Font.BOLD, 18);
      label.setFont(font);
      label.setVerticalAlignment(JLabel.BOTTOM);
      JTextArea text = new JTextArea();
      text.setText("Amit Learning Application");
      font = new Font("Serif", Font.BOLD, 13);
      text.setFont(font);
      frame.add(label);
      frame.add(text);
      frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
      frame.setSize(500, 300);
      frame.setVisible(true);
   }
}
How to declare numbers in JavaScript?

JavaScript is untyped language. This means that a JavaScript variable can hold a value of any data type. To declare variables in JavaScript, you need to use the var keyword. Whether it is a number or string, use the var keyword for declaration.
Here’s how you can declare numbers in JavaScript −
var points = 100;
var rank = 5;
You can try to run the following code to learn how to declare number in JavaScript −
<html>
   <body>
      <script>
         <!--
            var age = 20;
            if( age > 18 ){
               document.write("<b>Qualifies for driving</b>");
            }
          //-->
       </script>
   </body>
</html>
Difference between title() and wm_title() methods in Tkinter class

Tkinter has a definite class hierarchy which contains many functions and built-in methods. As we create applications, we use these functions to build the structure of components.The wm class stands for "window manager" that is a mixin class that provides many builtin functions and methods.
The method wm_title() is used to change the title of the tkinter window. However, alternatively, we can also use the win.title() method. Generally, wm class provides many methods that let us communicate with the window services.
# Import the required libraries
from tkinter import *

# Create an instance of tkinter frame or window
win = Tk()

# Set the size of the window
win.geometry("700x350")
win.wm_title("This is the Title")

# Add A label widget
Label(win, text="Welcome to TutorialsPoint✨ \n" "You are browsing the best resource for Online Education.", font=('Aerial 18 italic')).place(x=50, y=150)

win.mainloop()
Run the above code to display a window that will contain some Label text widget.
C++ Program to Generate All Possible Subsets with Exactly k Elements in Each Subset

This is a C++ program to generate all possible subsets with exactly k elements in each subset.
Begin
   function PossibleSubSet(char a[], int reqLen, int s, int currLen, bool check[], int l):
   If currLen > reqLen
   Return
   Else if currLen = reqLen
      Then print the new generated sequence.
   If s = l
      Then return no further element is left.
      For every index there are two options:
         either proceed with a start as ‘true’ and recursively call PossibleSubSet()
         with incremented value of ‘currLen’ and ‘s’.
         Or proceed with a start as ‘false’ and recursively call PossibleSubSet()
         with only incremented value of ‘s’.
End
#include<iostream>
using namespace std;
void PossibleSubSet(char a[], int reqLen, int s, int currLen, bool check[], int l)
//print the all possible combination of given array set
{
   if(currLen > reqLen)
   return;
   else if (currLen == reqLen) {
      cout<<"\t";
      for (int i = 0; i < l; i++) {
         if (check[i] == true) {
            cout<<a[i]<<" ";
         }
      }
      cout<<"\n";
      return;
   }
   if (s == l) {
      return;
   }
   check[s] = true;
   PossibleSubSet(a, reqLen, s + 1, currLen + 1, check, l);
   //recursively call PossibleSubSet() with incremented value of ‘currLen’ and ‘s’.
   check[s] = false;
   PossibleSubSet(a, reqLen, s + 1, currLen, check, l);
   //recursively call PossibleSubSet() with only incremented value of ‘s’.
}
int main() {
   int i,n,m;
   bool check[n];
   cout<<"Enter the number of elements: ";
   cin>>n;
   char a[n];
   cout<<"\n";
   for(i = 0; i < n; i++) {
      cout<<"Enter "<<i+1<<" element: ";
      cin>>a[i];
      check[i] = false;
   }
   cout<<"\nEnter the length of the subsets required: ";
   cin>>m;
   cout<<"\nThe possible combination of length "<<m<<" for the given array set:\n";
   PossibleSubSet(a, m, 0, 0, check, n);
   return 0;
}
Enter the number of elements: 7
Enter 1 element: 7
Enter 2 element: 6
Enter 3 element: 5
Enter 4 element: 4
Enter 5 element: 3
Enter 6 element: 2
Enter 7 element: 1
Enter the length of the subsets required: 6
The possible combination of length 6 for the given array set:
7 6 5 4 3 2
7 6 5 4 3 1
7 6 5 4 2 1
7 6 5 3 2 1
7 6 4 3 2 1
7 5 4 3 2 1
6 5 4 3 2 1
Add a method to a JavaScript object constructor?

Adding a method to an object constructor is unlike adding a method to a normal object. We cannot add a method as it is the case with a normal object. To make a method in an object constructor it has to be added inside the object constructor.
In the following example, the method is added inside the constructor, therefore, we have got a legitimate value.
Live Demo
<html>
<body>
<script>
   function Business(name, property, age, designation) {
      this.Name = name;
      this.prop = property;
      this.age = age;
      this.designation = designation;
      this.name = function() {
         return this.Name
      };
   }
   var person1 = new Business("Trump", "$28.05billion", "73", "President");
   document.write(person1.name());
</script>
</body>
</html>
Trump
How to determine database type (name) for a given JDBC connection?

One way to get the name of the underlying database you have connected with is by invoking the getDatabaseProductName() method of the DatabaseMetaData interface. This method returns the name of the underlying database in String format.
Therefore, to retrieve the name of your current database using Java code −
Retrieve the DatabaseMetaData object of the current Connection using the getMetaData() method.
//Retrieving the meta data object
DatabaseMetaData metaData = con.getMetaData();
Then, get the product name of the underlying database you have connected to using the getDatabaseProductName() method of the DatabaseMetaData interface as −
//retrieving the name of the database
String product_name = metaData.getDatabaseProductName();
Following JDBC program establishes connection with the database, retrieves and prints the name of the underlying database.
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DatabaseMetaData_getDatabaseProductName {
   public static void main(String args[]) throws SQLException {
      //Registering the Driver
      DriverManager.registerDriver(new com.mysql.jdbc.Driver());
      //Getting the connection
      String mysqlUrl = "jdbc:mysql://localhost/mydatabase";
      Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
      System.out.println("Connection established......");
      //Retrieving the meta data object
      DatabaseMetaData metaData = con.getMetaData();
      //retrieving the name of the database
      String product_name = metaData.getDatabaseProductName();
      System.out.println("Name of the underlying database: "+product_name);
   }
}
Connection established......
Name of the underlying database: MySQL
How to Add Live Camera Preview to UIView in Swift?

To add a live camera preview to our default UIView in swift we can either use AVFoundation framework of iOS SDK or native UIImagePickerController(). In this example we’ll be using ImagePicker as our aim is to present camera preview on the UIView and Imagepicker is suitable for that task. AVFoundation can be used when we need a lot of customization on our camera or different types of custom actions.
To show a camera preview on the UIView we need to perform the following steps.
Create a UIImagePickerController object.
Create a UIImagePickerController object.
Conform our class to UIImagePickerControllerDelegate and UINavigationControllerDelegate.
Conform our class to UIImagePickerControllerDelegate and UINavigationControllerDelegate.
Assign delegates to the object we created in step one.
Assign delegates to the object we created in step one.
Add the object we created as a child
Add the object we created as a child
Add the child's view as a subView to our UIView.
Add the child's view as a subView to our UIView.
To achieve the same we’ll use the code below
override func viewDidLoad() {
   super.viewDidLoad()
   // Do any additional setup after loading the view, typically from a nib
   let imgPicker = UIImagePickerController()
   if UIImagePickerController.isCameraDeviceAvailable( UIImagePickerController.CameraDevice.front) {
      imgPicker.delegate = self
      imgPicker.sourceType = .camera

      addChild(imgPicker)
      self.view.addSubview(imgPicker.view)
      imgPicker.view.frame = self.view.bounds
      imgPicker.allowsEditing = false
      imgPicker.showsCameraControls = false
      imgPicker.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
   }
}
For this example we have not written any function and we directly created objects here, but it’s always a good choice to use lazy variables in situations where we might not need to use some variable.
This code will not work on a simulator as it makes use of camera. When I run the above code on an iPhone 7+, below is the result that’s produced.
Tryit Editor v3.7

Tryit: Using the animation-direction property
How can I select the row with the highest ID in MySQL?

You can select the row with highest ID in MySQL with the help of ORDER BY with LIMIT OFFSET
The syntax is as follows −
select *from yourTableName order by yourColumnName desc limit 1 offset 0;
To understand the above syntax, let us create a table. The query to create a table is as follows −
mysql> create table HighestIdOrderBy
   −> (
   −> EmployeeId int,
   −> EmployeeName varchar(200)
   −> );
Query OK, 0 rows affected (0.58 sec)
Insert records in the table with the help of insert command. The query is as follows −
mysql> insert into HighestIdOrderBy values(200,'David');
Query OK, 1 row affected (0.20 sec)

mysql> insert into HighestIdOrderBy values(1000,'Bob');
Query OK, 1 row affected (0.18 sec)

mysql> insert into HighestIdOrderBy values(600,'John');
Query OK, 1 row affected (0.16 sec)

mysql> insert into HighestIdOrderBy values(300,'Johnson');
Query OK, 1 row affected (0.18 sec)

mysql> insert into HighestIdOrderBy values(100,'Carol');
Query OK, 1 row affected (0.12 sec)
Display all records from the table with select statement. The query is as follows −
mysql> select *from HighestIdOrderBy;
The following is the output −
+------------+--------------+
| EmployeeId | EmployeeName |
+------------+--------------+
|        200 | David        |
|       1000 | Bob          |
|        600 | John         |
|        300 | Johnson      |
|        100 | Carol       |
+------------+--------------+
5 rows in set (0.00 sec)
Here is the query to select maximum id from MySQL table. The query is as follows −
mysql> select *from HighestIdOrderBy order by EmployeeId desc limit 1 offset 0;
The following is the output −
+------------+--------------+
| EmployeeId | EmployeeName |
+------------+--------------+
|       1000 | Bob          |
+------------+--------------+
1 row in set (0.00 sec)
PHP - Function ereg_replace()

string ereg_replace (string pattern, string replacement, string originalstring);

The ereg_replace() function searches for string specified by pattern and replaces pattern with replacement if found. The ereg_replace() function operates under the same premises as ereg(), except that the functionality is extended to finding and replacing pattern instead of simply locating it.
Like ereg(), ereg_replace() is case sensitive.
After the replacement has occurred, the modified string will be returned.
After the replacement has occurred, the modified string will be returned.
If no matches are found, the string will remain unchanged.
If no matches are found, the string will remain unchanged.
Following is the piece of code, copy and paste this code into a file and verify the result.
<?php
   $copy_date = "Copyright 1999";
   $copy_date = ereg_replace("([0-9]+)", "2000", $copy_date);
   
   print $copy_date;
?>
This will produce the following result −

    45 Lectures 
     9 hours 

 Malhar Lathkar

    34 Lectures 
     4 hours 

 Syed Raza

    84 Lectures 
     5.5 hours 

 Frahaan Hussain

    17 Lectures 
     1 hours 

 Nivedita Jain

    100 Lectures 
     34 hours 

 Azaz Patel

    43 Lectures 
     5.5 hours 

 Vijay Kumar Parvatha Reddy
 Print
 Add Notes
 Bookmark this page
What is a recursive method call in C#?

Recursive method call in C# is called Recursion. Let us see an example to calculate power of a number using recursion.
Here, if the power is not equal to 0, then the function call occurs which is eventually recursion −
if (p!=0) {
   return (n * power(n, p - 1));
}
Above, n is the number itself and the power reduces on every iteration as shown below −
using System;
using System.IO;

public class Demo {
   public static void Main(string[] args) {
      int n = 5;
      int p = 2;
      long res;
      res = power(n, p);
      Console.WriteLine(res);
   }

   static long power (int n, int p) {
      if (p!=0) {
         return (n * power(n, p - 1));
      }
      return 1;
   }
}
C/C++ Program for Odd-Even Sort / Brick Sort - GeeksforGeeks

18 Apr, 2022
This is basically a variation of bubble-sort. This algorithm is divided into two phases- Odd and Even Phase. The algorithm runs until the array elements are sorted and in each iteration two phases occurs- Odd and Even Phases. In the odd phase, we perform a bubble sort on odd indexed elements and in the even phase, we perform a bubble sort on even indexed elements. 
CPP
// A C++ Program to implement Odd-Even / Brick Sort#include <bits/stdc++.h>using namespace std; // A function to sort the algorithm using Odd Even sortvoid oddEvenSort(int arr[], int n){    bool isSorted = false; // Initially array is unsorted     while (!isSorted) {        isSorted = true;         // Perform Bubble sort on odd indexed element        for (int i = 1; i <= n - 2; i = i + 2) {            if (arr[i] > arr[i + 1]) {                swap(arr[i], arr[i + 1]);                isSorted = false;            }        }         // Perform Bubble sort on even indexed element        for (int i = 0; i <= n - 2; i = i + 2) {            if (arr[i] > arr[i + 1]) {                swap(arr[i], arr[i + 1]);                isSorted = false;            }        }    }     return;} // A utility function to print an array of size nvoid printArray(int arr[], int n){    for (int i = 0; i < n; i++)        cout << arr[i] << " ";    cout << "\n";} // Driver program to test above functions.int main(){    int arr[] = { 34, 2, 10, -9 };    int n = sizeof(arr) / sizeof(arr[0]);     oddEvenSort(arr, n);    printArray(arr, n);     return (0);}
-9 2 10 34
Please refer complete article on Odd-Even Sort / Brick Sort for more details!
C Programs
C++ Programs
Sorting
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C Program to read contents of Whole File
Producer Consumer Problem in C
C program to find the length of a string
Exit codes in C/C++ with Examples
Difference between break and continue statement in C
C++ Program for QuickSort
C++ program for hashing with chaining
Sorting a Map by value in C++ STL
cin in C++
delete keyword in C++