code-rag-bench/online-tutorials huggingface dataset:
An Insertion Sort time complexity question - GeeksforGeeks

28 Jun, 2021
Question : How much time Insertion sort takes to sort an array of size n in below form?
arr[] = 2, 1, 4, 3, 6, 5,....i, i-1, .....n, n-1
Answer : At first look, it seems like Insertion Sort would take O(n2) time, but it actually takes O(n) time
How? Let us take a closer look at below code.
/* Function to sort an array using insertion sort*/
void insertionSort(int arr[], int n)
{
   for (int i = 1; i = 0 && arr[j] > key)
       {
           arr[j+1] = arr[j];
           j = j-1;
       }
       arr[j+1] = key;
   }
}

If we analyze the input carefully we see that every element is only one position away from its position in sorted array. The outer for loop will run till ‘n’ and the inner while loop would take “constant” steps of 1 swap and 2 comparisons. Since, while loop takes constant time and for loop runs for ‘n’ element, so overall complexity is O(n)
Alternate Answer : Another way to look at this is, time taken by Insertion Sort is proportional to number of inversions in an array. In above example type, number of inversions is n/2, so overall time complexity is O(n)
This article is contributed by Uddalak Bhaduri. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Sorting
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Sort an array of 0s, 1s and 2s
k largest(or smallest) elements in an array
Python Program for Bubble Sort
Merge two sorted arrays
Count Inversions in an array | Set 1 (Using Merge Sort)
Bucket Sort
Python List sort() method
Python Program for QuickSort
C++ Program for QuickSort
Merge Sort for Linked Lists
LISP - Case Construct

The case construct implements multiple test-action clauses like the cond construct. However, it evaluates a key form and allows multiple action clauses based on the evaluation of that key form.
The syntax for case macro is −
The template for CASE is
(case  (keyform)
((key1)   (action1   action2 ...) )
((key2)   (action1   action2 ...) )
...
((keyn)   (action1   action2 ...) ))

Create a new source code file named main.lisp and type the following code in it.
(setq day 4)
(case day
(1 (format t "~% Monday"))
(2 (format t "~% Tuesday"))
(3 (format t "~% Wednesday"))
(4 (format t "~% Thursday"))
(5 (format t "~% Friday"))
(6 (format t "~% Saturday"))
(7 (format t "~% Sunday")))
When you click the Execute button, or type Ctrl+E, LISP executes it immediately and the result returned is −
Thursday


    79 Lectures 
     7 hours 

 Arnold Higuit
 Print
 Add Notes
 Bookmark this page
C# TimeSpan Max value

Timespan shows the length of time.
To get the maximum value of TimeSpan, use the following property.
TimeSpan.MaxValue
 Live Demo
using System;
using System.Linq;
public class Demo {
   public static void Main() {
      Console.WriteLine(TimeSpan.MaxValue);
   }
}
10675199.02:48:05.4775807
Generating OTP in Java

Generate OTP is now a requirement on most of the website now-a-days. In case of additional authentication, system generates a OTP password adhering to OTP policy of the company. Following example generates a unique OTP adhering to following conditions −
It should contain at least one number.
Length should be 4 characters.
import java.util.Random;

public class Tester {
   public static void main(String[] args) {

      System.out.println(generateOTP(4));
   }

   private static char[] generateOTP(int length) {
      String numbers = "1234567890";
      Random random = new Random();
      char[] otp = new char[length];

      for(int i = 0; i< length ; i++) {
         otp[i] = numbers.charAt(random.nextInt(numbers.length()));
      }
      return otp;
   }
}
6674
Sizeof operator in C

The sizeof operator is the most common operator in C. It is a compile-time unary operator and used to compute the size of its operand. It returns the size of a variable. It can be applied to any data type, float type, pointer type variables.
When sizeof() is used with the data types, it simply returns the amount of memory allocated to that data type. The output can be different on different machines like a 32-bit system can show different output while a 64-bit system can show different of same data types.
Here is an example in C language,
 Live Demo
#include <stdio.h>
int main() {
int a = 16;
   printf("Size of variable a : %d\n",sizeof(a));
   printf("Size of int data type : %d\n",sizeof(int));
   printf("Size of char data type : %d\n",sizeof(char));
   printf("Size of float data type : %d\n",sizeof(float));
   printf("Size of double data type : %d\n",sizeof(double));
   return 0;
}
Size of variable a : 4
Size of int data type : 4
Size of char data type : 1
Size of float data type : 4
Size of double data type : 8
When the sizeof() is used with an expression, it returns the size of the expression. Here is an example.
 Live Demo
#include <stdio.h>
int main() {
   char a = 'S';
   double b = 4.65;
   printf("Size of variable a : %d\n",sizeof(a));
   printf("Size of an expression : %d\n",sizeof(a+b));
   int s = (int)(a+b);
   printf("Size of explicitly converted expression : %d\n",sizeof(s));
   return 0;
}
Size of variable a : 1
Size of an expression : 8
Size of explicitly converted expression : 4
MongoDB - Overview

MongoDB is a cross-platform, document oriented database that provides, high performance, high availability, and easy scalability. MongoDB works on concept of collection and document.
Database is a physical container for collections. Each database gets its own set of files on the file system. A single MongoDB server typically has multiple databases.
Collection is a group of MongoDB documents. It is the equivalent of an RDBMS table. A collection exists within a single database. Collections do not enforce a schema. Documents within a collection can have different fields. Typically, all documents in a collection are of similar or related purpose.
A document is a set of key-value pairs. Documents have dynamic schema. Dynamic schema means that documents in the same collection do not need to have the same set of fields or structure, and common fields in a collection's documents may hold different types of data.
The following table shows the relationship of RDBMS terminology with MongoDB.
Following example shows the document structure of a blog site, which is simply a comma separated key value pair.
{
   _id: ObjectId(7df78ad8902c)
   title: 'MongoDB Overview', 
   description: 'MongoDB is no sql database',
   by: 'tutorials point',
   url: 'http://www.tutorialspoint.com',
   tags: ['mongodb', 'database', 'NoSQL'],
   likes: 100, 
   comments: [	
      {
         user:'user1',
         message: 'My first comment',
         dateCreated: new Date(2011,1,20,2,15),
         like: 0 
      },
      {
         user:'user2',
         message: 'My second comments',
         dateCreated: new Date(2011,1,25,7,45),
         like: 5
      }
   ]
}
_id is a 12 bytes hexadecimal number which assures the uniqueness of every document. You can provide _id while inserting the document. If you don’t provide then MongoDB provides a unique id for every document. These 12 bytes first 4 bytes for the current timestamp, next 3 bytes for machine id, next 2 bytes for process id of MongoDB server and remaining 3 bytes are simple incremental VALUE.

    44 Lectures 
     3 hours 

 Arnab Chakraborty

    54 Lectures 
     5.5 hours 

 Eduonix Learning Solutions

    44 Lectures 
     4.5 hours 

 Kaushik Roy Chowdhury

    40 Lectures 
     2.5 hours 

 University Code

    26 Lectures 
     8 hours 

 Bassir Jafarzadeh

    70 Lectures 
     2.5 hours 

 Skillbakerystudios
 Print
 Add Notes
 Bookmark this page
Java Program to find the sum of a Series 1/1! + 2/2! + 3/3! + 4/4! +.......+ n/n!

Following is the Java program to find the sum of the series −
1/1! + 2/2! + 3/3! + 4/4! +.......+ n/n!
 Live Demo
import java.io.*;
import java.lang.*;
public class Demo{
   public static double pattern_sum(double val){
      double residual = 0, factorial_val = 1;
      for (int i = 1; i <= val; i++){
         factorial_val = factorial_val * i;
         residual = residual + (i / factorial_val);
      }
      return (residual);
   }
   public static void main(String[] args){
      double val = 6;
      System.out.println("The sum of the series is : " + pattern_sum(val));
   }
}
The sum of the series is : 2.7166666666666663
A class named Demo contains a function named ‘pattern_sum’. This function takes a double valued
number as parameter, and iterates through the value and calculates the series value of (1/1! + 2/2! +
..) and so on. In the main function, the value is defined and the function ‘pattern_sum’ is called by
passing this value. The output is displayed on the console.
What is parameter binding in C# ASP.NET WebAPI?

Binding is a process to set values for the parameters when Web API calls a controller
action method.
Web API methods with the different types of the parameters and how to customize
the binding process.
If the parameter is a simple type like int, bool, double, etc., Web API tries to get the value from the URI (Either from route data or from the Query String)
if the parameter is a complex type like Customer, Employee, etc., then the Web API
Framework tries to get the value from the request body.
We can change this default behavior of the parameter binding process by using
[FromBody] and [FromUri] attributes.
FromUri −
If the parameter is of simple type, then web Api tries to get the value from the URI
.NET Primitive type like double,DateTime,GUID string any type which can e
converted from the String type
public Student Get(int id){}
If the parameter of type Complex type, then Web Api will try to bind the values from
the message body.
Public Student Post(Employee employee){}
To force Web API to read a complex type from the URI, add the [FromUri] attribute
to the parameter
Use [FromUri] attribute to force Web Api to get the value of Complex type from
QueryString.
public Student Get([FromUri] Employee employee)
public HttpResponseMessage Get([FromUri] Employee employee) { ... }
Use [FromBody] attribute to get the value of Primitive type from the request body,
opposite to the default values
No, multiple FormBody is not allowed in a single action.
To force Web API to read a simple type from the request body, add the [FromBody]
In this example, Web API will use a media-type formatter to read the value of name
from the request body
public Student Post([FromBody] string name]){...}
public HttpResponseMessage Post([FromBody] string name) { ... }
Python – Pandas Dataframe.rename()

It's quite simple to rename a DataFrame column name in Pandas. All that you need to do is to use the rename() method and pass the column name that you want to change and the new column name. Let's take an example and see how it's done.
Create a two-dimensional, size-mutable, potentially heterogeneous tabular data, df.
Print the input DataFrame, df.
Use rename() method to rename the column name. Here, we will rename the column "x" with its new name "new_x".
Print the DataFrame with the renamed column.
import pandas as pd

df = pd.DataFrame(
   {
      "x": [5, 2, 7, 0],
      "y": [4, 7, 5, 1],
      "z": [9, 3, 5, 1]
   }
)

print "Input DataFrame is:\n", df
df = df.rename(columns={"x": "new_x"})
print "After renaming, the DataFrame is:\n", df
Input DataFrame is:
   x  y  z
0  5  4  9
1  2  7  3
2  7  5  5
3  0  1  1

After renaming, the DataFrame is:
   new_x  y  z
0      5  4  9
1      2  7  3
2      7  5  5
3      0  1  1
SQL - ORDER BY Clause

The SQL ORDER BY clause is used to sort the data in ascending or descending order, based on one or more columns. Some databases sort the query results in an ascending order by default.
The basic syntax of the ORDER BY clause is as follows −
SELECT column-list 
FROM table_name 
[WHERE condition] 
[ORDER BY column1, column2, .. columnN] [ASC | DESC];

You can use more than one column in the ORDER BY clause. Make sure whatever column you are using to sort that column should be in the column-list.
Consider the CUSTOMERS table having the following records −
+----+----------+-----+-----------+----------+
| ID | NAME     | AGE | ADDRESS   | SALARY   |
+----+----------+-----+-----------+----------+
|  1 | Ramesh   |  32 | Ahmedabad |  2000.00 |
|  2 | Khilan   |  25 | Delhi     |  1500.00 |
|  3 | kaushik  |  23 | Kota      |  2000.00 |
|  4 | Chaitali |  25 | Mumbai    |  6500.00 |
|  5 | Hardik   |  27 | Bhopal    |  8500.00 |
|  6 | Komal    |  22 | MP        |  4500.00 |
|  7 | Muffy    |  24 | Indore    | 10000.00 |
+----+----------+-----+-----------+----------+

The following code block has an example, which would sort the result in an ascending order by the NAME and the SALARY −
SQL> SELECT * FROM CUSTOMERS
   ORDER BY NAME, SALARY;
This would produce the following result −
+----+----------+-----+-----------+----------+
| ID | NAME     | AGE | ADDRESS   | SALARY   |
+----+----------+-----+-----------+----------+
|  4 | Chaitali |  25 | Mumbai    |  6500.00 |
|  5 | Hardik   |  27 | Bhopal    |  8500.00 |
|  3 | kaushik  |  23 | Kota      |  2000.00 |
|  2 | Khilan   |  25 | Delhi     |  1500.00 |
|  6 | Komal    |  22 | MP        |  4500.00 |
|  7 | Muffy    |  24 | Indore    | 10000.00 |
|  1 | Ramesh   |  32 | Ahmedabad |  2000.00 |
+----+----------+-----+-----------+----------+

The following code block has an example, which would sort the result in the descending order by NAME.
SQL> SELECT * FROM CUSTOMERS
   ORDER BY NAME DESC;
This would produce the following result −
+----+----------+-----+-----------+----------+
| ID | NAME     | AGE | ADDRESS   | SALARY   |
+----+----------+-----+-----------+----------+
|  1 | Ramesh   |  32 | Ahmedabad |  2000.00 |
|  7 | Muffy    |  24 | Indore    | 10000.00 |
|  6 | Komal    |  22 | MP        |  4500.00 |
|  2 | Khilan   |  25 | Delhi     |  1500.00 |
|  3 | kaushik  |  23 | Kota      |  2000.00 |
|  5 | Hardik   |  27 | Bhopal    |  8500.00 |
|  4 | Chaitali |  25 | Mumbai    |  6500.00 |
+----+----------+-----+-----------+----------+


    42 Lectures 
     5 hours 

 Anadi Sharma

    14 Lectures 
     2 hours 

 Anadi Sharma

    44 Lectures 
     4.5 hours 

 Anadi Sharma

    94 Lectures 
     7 hours 

 Abhishek And Pukhraj

    80 Lectures 
     6.5 hours 

 Oracle Master Training | 150,000+ Students Worldwide

    31 Lectures 
     6 hours 

 Eduonix Learning Solutions
 Print
 Add Notes
 Bookmark this page
Java Regex - Capturing Groups

Capturing groups are a way to treat multiple characters as a single unit. They are created by placing the characters to be grouped inside a set of parentheses. For example, the regular expression (dog) creates a single group containing the letters "d", "o", and "g".
Capturing groups are numbered by counting their opening parentheses from the left to the right. In the expression ((A)(B(C))), for example, there are four such groups −
((A)(B(C)))
(A)
(B(C))
(C)
To find out how many groups are present in the expression, call the groupCount method on a matcher object. The groupCount method returns an int showing the number of capturing groups present in the matcher's pattern.
There is also a special group, group 0, which always represents the entire expression. This group is not included in the total reported by groupCount.
Following example illustrates how to find a digit string from the given alphanumeric string −
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexMatches {
   public static void main( String args[] ) {
      // String to be scanned to find the pattern.
      String line = "This order was placed for QT3000! OK?";
      String pattern = "(.*)(\\d+)(.*)";

      // Create a Pattern object
      Pattern r = Pattern.compile(pattern);

      // Now create matcher object.
      Matcher m = r.matcher(line);
      
      if (m.find( )) {
         System.out.println("Found value: " + m.group(0) );
         System.out.println("Found value: " + m.group(1) );
         System.out.println("Found value: " + m.group(2) );
      } else {
         System.out.println("NO MATCH");
      }
   }
}
This will produce the following result −
Found value: This order was placed for QT3000! OK?
Found value: This order was placed for QT300
Found value: 0

 Print
 Add Notes
 Bookmark this page
C library function - qsort()

The C library function void qsort(void *base, size_t nitems, size_t size, int (*compar)(const void *, const void*)) sorts an array.
Following is the declaration for qsort() function.
void qsort(void *base, size_t nitems, size_t size, int (*compar)(const void *, const void*))
base − This is the pointer to the first element of the array to be sorted.
base − This is the pointer to the first element of the array to be sorted.
nitems − This is the number of elements in the array pointed by base.
nitems − This is the number of elements in the array pointed by base.
size − This is the size in bytes of each element in the array.
size − This is the size in bytes of each element in the array.
compar − This is the function that compares two elements.
compar − This is the function that compares two elements.
This function does not return any value.
The following example shows the usage of qsort() function.
#include <stdio.h>
#include <stdlib.h>

int values[] = { 88, 56, 100, 2, 25 };

int cmpfunc (const void * a, const void * b) {
   return ( *(int*)a - *(int*)b );
}

int main () {
   int n;

   printf("Before sorting the list is: \n");
   for( n = 0 ; n < 5; n++ ) {
      printf("%d ", values[n]);
   }

   qsort(values, 5, sizeof(int), cmpfunc);

   printf("\nAfter sorting the list is: \n");
   for( n = 0 ; n < 5; n++ ) {   
      printf("%d ", values[n]);
   }
  
   return(0);
}
Let us compile and run the above program that will produce the following result −
Before sorting the list is: 
88 56 100 2 25 
After sorting the list is: 
2 25 56 88 100


    12 Lectures 
     2 hours 

 Nishant Malik

    12 Lectures 
     2.5 hours 

 Nishant Malik

    48 Lectures 
     6.5 hours 

 Asif Hussain

    12 Lectures 
     2 hours 

 Richa Maheshwari

    20 Lectures 
     3.5 hours 

 Vandana Annavaram

    44 Lectures 
     1 hours 

 Amit Diwan
 Print
 Add Notes
 Bookmark this page
How to link pages using absolute URL in HTML?

To link pages using absolute URL in HTML, use the <a> tag with href attribute. Absolute URL is used to link an external website. For example https://www.qries.com/questions.php
Everything inside <a>...</a> tag becomes a hyperlink. Some of the attributes of <a> tag are listed below,
You can try the following code to link pages using absolute URL in HTML −
<!DOCTYPE html>
<html>
   <head>
      <title>HTML Absolute links</title>
   </head>
   <body>
      <h1>Qries</h1>
      <p>
         With <a href="https://www.qries.com/questions.php">Qries</a>,
         get information about different topics such as games, government, education,
         geology, sports, etc.
      </p>
   </body>
</html>
Apache Pig - ToDate()

This function is used to generate a DateTime object according to the given parameters.
The syntax of ToDate() function can be any of the following −
grunt> ToDate(milliseconds)
  
grunt> ToDate(iosstring) 
  
grunt> ToDate(userstring, format)
  
grunt> ToDate(userstring, format, timezone)

Assume that there is a file named date.txt in the HDFS directory /pig_data/. This file contains the date-of-birth details of a particular person, id, date, and time.
date.txt
001,1989/09/26 09:00:00
002,1980/06/20 10:22:00
003,1990/12/19 03:11:44 

And, we have loaded this file into Pig with a relation named date_data as shown below.
grunt> date_data = LOAD 'hdfs://localhost:9000/pig_data/date.txt' USING PigStorage(',')
   as (id:int,date:chararray);
Following is an example of the ToDate() function. Here we are converting the DateTime object corresponding to the date-of-birth of every employee.
grunt> todate_data = foreach date_data generate ToDate(date,'yyyy/MM/dd HH:mm:ss')
   as (date_time:DateTime >);
The result (DateTime object of every employee) of the statement will be stored in the relation named todate_data. Verify the content of this relation using the Dump operator as shown below.
grunt> Dump todate_data;
  
(1989-09-26T09:00:00.000+05:30)
(1980-06-20T10:22:00.000+05:30)
(1990-12-19T03:11:44.000+05:30)


    46 Lectures 
     3.5 hours 

 Arnab Chakraborty

    23 Lectures 
     1.5 hours 

 Mukund Kumar Mishra

    16 Lectures 
     1 hours 

 Nilay Mehta

    52 Lectures 
     1.5 hours 

 Bigdata Engineer

    14 Lectures 
     1 hours 

 Bigdata Engineer

    23 Lectures 
     1 hours 

 Bigdata Engineer
 Print
 Add Notes
 Bookmark this page
How To Calculate the Mean and Standard Deviation — Normalizing Datasets in Pytorch | by Jorrit Willaert | Towards Data Science

The normalization of a dataset is mostly seen as a rather mundane task, although it strongly influences the performance of a neural network. With unnormalized data, numerical ranges of features may vary strongly. Take for example a machine learning application where housing prices are predicted from several inputs (surface area, age, ...). Surface areas will typically range from 100 to 500m2, while the age is more likely between 0 and 25. If this raw data is inputted in our machine learning model, slow convergence will occur.
As illustrated left, the steepest gradient is searched, which is somewhat in the correct direction but also possesses quite a large oscillation part. This can be explained by reasoning about the learning rate. A relatively large learning rate is required for the surface area feature since its range is quite large. However, this large learning rate is too large for the age. The optimizer overshoots each step, which results in oscillation and hence slow convergence.
The data can be normalized by subtracting the mean (μ) of each feature and a division by the standard deviation (σ). This way, each feature has a mean of 0 and a standard deviation of 1. This results in faster convergence.
In machine vision, each image channel is normalized this way.
First, some imports are required.
I will use the CIFAR dataset with its color images as an example. However, the same code works on the MNIST dataset with grayscale images as well.
The training examples are downloaded and transformed to tensors, after which the loader fetches batches of 64 images.
The mean has to be calculated over all the images, their height, and their width, however, not over the channels. In the case of colored images, an output tensor of size 3 is expected.
The standard deviation can be calculated with the following formula:
E[X2] represents the mean of the squared data, while (E[X])2 represents the square of the mean of the data.
Finally, the mean and standard deviation are calculated for the CIFAR dataset.
Mean: tensor([0.4914, 0.4822, 0.4465])Standard deviation: tensor([0.2471, 0.2435, 0.2616])
The dataloader has to incorporate these normalization values in order to use them in the training process. Therefore, besides the ToTensor() transform, normalization with the obtained values follows.
Note that since the network is trained on normalized images, every image (be it while validating or inferencing) must be normalized with the same obtained values.
Data normalization is an important step in the training process of a neural network. By normalizing the data to a uniform mean of 0 and a standard deviation of 1, faster convergence is achieved.
If you have any questions, please don’t hesitate to contact me!
Change the color of "tab header" in ttk.Notebook (tkinter)

Tabs are very useful for a multipurpose GUI application. It helps to isolate the several tasks or processes within the application in the form of tabs. Tabs are very useful for processing multiple tasks at a time. With the help of Tkinter Notebook widget, we can create Tabs in our tkinter application.
To configure the property or style of the tabs, we must have to use a ttk themed widget. The ttk themed widget helps to style any widget present in the application. To configure the background color of the tab, you can use ttk 'default' theme along with passing 'TNotebook.Tab' as the style parameter in configuration.
# Import the required libraries
from tkinter import *
from tkinter import ttk

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

# Set the size of the tkinter window
win.geometry("700x350")

# Create an instance of ttk style
s = ttk.Style()
s.theme_use('default')
s.configure('TNotebook.Tab', background="green3")
s.map("TNotebook", background= [("selected", "green3")])

# Create a Notebook widget
nb = ttk.Notebook(win)

# Add a frame for adding a new tab
f1= ttk.Frame(nb, width= 400, height=180)

# Adding the Tab Name
nb.add(f1, text= 'Tkinter-1')
f2 = ttk.Frame(nb, width= 400, height=180)
nb.add(f2, text= "Tkinter-2")

nb.pack(expand= True, fill=BOTH, padx= 5, pady=5)
win.mainloop()
Executing the above code will display customized tabs in the window. You can modify the color of the tab by adding the color name in the configuration.
What are the methods used to provide effects in jQuery?

jQuery effect methods are used to create custom animation effects. The following are some of the methods used to provide effects in jQuery −
Let’s see an example to work with jQuery method animate(), which animates any element.
You can try to run the following code to learn how to use the jQuery method to animate() to animate a button −
Live Demo
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
 $(document).ready(function(){
    $("#button1").click(function(){
      $("#shape").animate({width: "300px"});
    });
    $("#button2").click(function(){
      $("#shape").animate({width: "150px"});
    });
 });
</script>
</head>
<body>

<button id="button1">Increase width</button>
<button id="button2">Original width</button>

<div id="shape" style="background:rgb(73,159,255);height:150px;width:150px;margin:30px;"></div>

</body>
</html>
Write a C# program to calculate a factorial using recursion

Factorial of a number is what we are finding using a recursive function checkFact () in the below example −
If the value is 1, it returns 1 since Factorial is 1 −
if (n == 1)
return 1;
If not, then the recursive function will be called for the following iterations if you want the value of 5!
Interation1:
5 * checkFact (5 - 1);

Interation2:
4 * checkFact (4 - 1);

Interation3:
3 * checkFact (3 - 1);

Interation4:
4 * checkFact (2 - 1);
To calculate a factorial using recursion, you can try to run the following code which shows what is done above −
 Live Demo
using System;

namespace Demo {

   class Factorial {

      public int checkFact(int n) {
         if (n == 1)
         return 1;
         else
         return n * checkFact(n - 1);
      }

      static void Main(string[] args) {

         int value = 9;
         int ret;

         Factorial fact = new Factorial();
         ret = fact.checkFact(value);
         Console.WriteLine("Value is : {0}", ret );
         Console.ReadLine();
      }
   }
}
Value is : 362880
JavaScript input type=submit is not working?

To make it work, you can use onclick with input type = “submit”.
Following is the code −
<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>Document</title>
</head>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<body>
   <form action="#">
      <label for="firstName">First Name:</label>
      <input type="text" id="fName" name="firstName" placeholder="Enter your First Name" />
      <button type="submit" onclick="submitForm(event)">Submit</button>
   </form>
<span id="result"></span>
</body>
<script>
   var firstName = null;
   function submitForm(evnt) {
      evnt.preventDefault();
      firstName = document.getElementById("fName").value;
      document.getElementById("result").innerHTML = "The First Name is=" + firstName;
   }
</script>
</html>
To run the above program, save the file name anyName.html(index.html). Right click on the file
and select the option “Open with live server” in VS Code editor.
This will produce the following output −
Now enter some value into the text box and enter the Submit button.
This will produce the following output −
Now enter the Submit button. This will produce the following output −
Find and Replace Pattern in Python

Suppose we have a list of words and a pattern, and we have to find which words in words matches the pattern. Here a word matches the pattern if there exists a permutation of letters p so that after replacing every letter x in the pattern with p(x), we get the target word. We have to find a list of the words in words that match the given pattern.
So for example, if the input is like ["abc","deq","mee","aqq","dkd","ccc"] and pattern is “abb”, then the output will be [“mee”, “aqq”], here mee and aqq are matching the style of the pattern “abb”. but “ccc” is not a pattern, because this is not a permutation.
To solve this, we will follow these steps −
define one convert() method. This will take word as input, this will act like −
counter := 1, s := empty string
s := s + string equivalent of counter
for i in range 1 to length of word – 1j := i – 1while j>=0if word[j] is word[i], then breakdecrease j by 1if j > -1, then s := s + s[j], otherwise increase counter by 1 and s := s + counter value as string
j := i – 1
while j>=0if word[j] is word[i], then breakdecrease j by 1
if word[j] is word[i], then break
decrease j by 1
if j > -1, then s := s + s[j], otherwise increase counter by 1 and s := s + counter value as string
return s
the actual method will be like
make one array word_num, and this is empty, make another empty array res
for each element i in words −insert convert(i) into word_num
insert convert(i) into word_num
pattern := convert(pattern)
for i in range 0 to length of words – 1if words_num[i] = pattern, then insert words[i] into res
if words_num[i] = pattern, then insert words[i] into res
return res
Let us see the following implementation to get better understanding −
 Live Demo
class Solution(object):
   def findAndReplacePattern(self, words, pattern):
      words_num = []
      result = []
      for i in words:
         words_num.append(self.convert(i))
      pattern = self.convert(pattern)
      for i in range(len(words)):
         if words_num[i] == pattern:
            result.append(words[i])
      return result
   def convert(self,word):
      counter = 1
      s = ""
      s+=str(counter)
      for i in range(1,len(word)):
         j= i -1
         while j>=0:
            if word[j] == word[i]:
               break
            j-=1
         if j >-1:
            s+=s[j]
         else:
            counter+=1
            s+=str(counter)
      return s
ob = Solution()
print(ob.findAndReplacePattern(["abc","deq","mee","aqq","dkd","ccc"],"abb"))
["abc","deq","mee","aqq","dkd","ccc"]
"abb"
['mee', 'aqq']
Console flush() method in Java with Examples - GeeksforGeeks

12 Jun, 2020
The flush() method of Console class in Java is used to flush the console and to force any buffered output to be written immediately.
Syntax:
public void flush()

Specified By: This method is specified by flush() method of Flushable interface.
Parameters: This method does not accept any parameter.
Return value: This method does not return any value.
Exceptions: This method does not any throw exception.
Note: System.console() returns null in an online IDE.
Below programs illustrate flush() method in Console class in IO package:
Program 1:
// Java program to illustrate// Console flush() method  import java.io.*;  public class GFG {    public static void main(String[] args)    {        // Create the console object        Console cnsl            = System.console();          if (cnsl == null) {            System.out.println(                "No console available");            return;        }        String str = cnsl.readLine(            "Enter string : ");          System.out.println(            "You entered : " + str);          // Revoke flush() method        cnsl.flush();    }}
Program 2:
// Java program to illustrate// Console flush() method  import java.io.*;  public class GFG {    public static void main(String[] args)    {        // Create the console object        Console cnsl            = System.console();          if (cnsl == null) {            System.out.println(                "No console available");            return;        }        String str = cnsl.readLine(            "Enter string : ");          System.out.println(            "You entered : " + str);          // Revoke flush() method        cnsl.flush();    }}
References:https://docs.oracle.com/javase/10/docs/api/java/io/Console.html#flush()
Java-Functions
Java-IO package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Interfaces in Java
How to iterate any Map in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Singleton Class in Java
Multithreading in Java
Python os.lseek() Method

Python method lseek() sets the current position of file descriptor fd to the given position pos, modified by how.
Following is the syntax for lseek() method −
os.lseek(fd, pos, how)

fd − This is the file descriptor, which needs to be processed.
fd − This is the file descriptor, which needs to be processed.
pos − This is the position in the file with respect to given parameter how. You give os.SEEK_SET or 0 to set the position relative to the beginning of the file, os.SEEK_CUR or 1 to set it relative to the current position; os.SEEK_END or 2 to set it relative to the end of the file.
pos − This is the position in the file with respect to given parameter how. You give os.SEEK_SET or 0 to set the position relative to the beginning of the file, os.SEEK_CUR or 1 to set it relative to the current position; os.SEEK_END or 2 to set it relative to the end of the file.
how − This is the reference point with-in the file. os.SEEK_SET or 0 means beginning of the file, os.SEEK_CUR or 1 means the current position and os.SEEK_END or 2 means end of the file.
how − This is the reference point with-in the file. os.SEEK_SET or 0 means beginning of the file, os.SEEK_CUR or 1 means the current position and os.SEEK_END or 2 means end of the file.
This method does not return any value.
The following example shows the usage of lseek() method.
#!/usr/bin/python

import os, sys

# Open a file
fd = os.open( "foo.txt", os.O_RDWR|os.O_CREAT )

# Write one string
os.write(fd, "This is test")

# Now you can use fsync() method.
# Infact here you would not be able to see its effect.
os.fsync(fd)

# Now read this file from the beginning
os.lseek(fd, 0, 0)
str = os.read(fd, 100)
print "Read String is : ", str

# Close opened file
os.close( fd )

print "Closed the file successfully!!"
When we run above program, it produces following result −
Read String is :  This is test
Closed the file successfully!!


    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
Angular Highcharts - Basic Bar Chart

Following is an example of a Bar Chart.
We have already seen the configurations used to draw a chart in Highcharts Configuration Syntax chapter. Now, let us see an example of a basic bar chart. We will also understand additional configuration. We have changed the type attribute in chart.
Configure the chart type to be 'bar' based. chart.type decides the series type for the chart. Here, the default value is "line".
var chart = {
   type: 'bar'
};
app.component.ts
import { Component } from '@angular/core';
import * as Highcharts from 'highcharts';
@Component({
   selector: 'app-root',
   templateUrl: './app.component.html',
   styleUrls: ['./app.component.css']
})
export class AppComponent {
   highcharts = Highcharts;
   chartOptions = {   
      chart: {
         type: 'bar'
      },
      title: {
         text: 'Historic World Population by Region'
      },
      subtitle : {
         text: 'Source: Wikipedia.org'  
      },
      legend : {
         layout: 'vertical',
         align: 'left',
         verticalAlign: 'top',
         x: 250,
         y: 100,
         floating: true,
         borderWidth: 1,
        
         backgroundColor: (
            (Highcharts.theme && Highcharts.theme.legendBackgroundColor) || 
              '#FFFFFF'), shadow: true
         },
         xAxis:{
            categories: ['Africa', 'America', 'Asia', 'Europe', 'Oceania'], title: {
            text: null
         } 
      },
      yAxis : {
         min: 0, title: {
            text: 'Population (millions)', align: 'high'
         },
         labels: {
            overflow: 'justify'
         }
      },
      tooltip : {
         valueSuffix: ' millions'
      },
      plotOptions : {
         bar: {
            dataLabels: {
               enabled: true
            }
         }
      },
      credits:{
         enabled: false
      },
      series: [
         {
            name: 'Year 1800',
            data: [107, 31, 635, 203, 2]
         }, 
         {
            name: 'Year 1900',
            data: [133, 156, 947, 408, 6]
         }, 
         {
            name: 'Year 2008',
            data: [973, 914, 4054, 732, 34]      
         }
      ]
   };
}
Verify the result.

    16 Lectures 
     1.5 hours 

 Anadi Sharma

    28 Lectures 
     2.5 hours 

 Anadi Sharma

    11 Lectures 
     7.5 hours 

 SHIVPRASAD KOIRALA

    16 Lectures 
     2.5 hours 

 Frahaan Hussain

    69 Lectures 
     5 hours 

 Senol Atac

    53 Lectures 
     3.5 hours 

 Senol Atac
 Print
 Add Notes
 Bookmark this page
How to create a JavaFX slider?

JavaFX provides a class known as Slider, this represents a slider component that displays a continuous range of values. This contains a track on which the numerical values are displayed. Along the track, there is a thumb pointing to the numbers. You can provide the maximum, minimum and initial values of the slider. 
To create a slider you need to instantiate the Slider class, set the required properties and, add it to the scene.
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Slider;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;         
public class SliderExample extends Application {
   public void start(Stage stage) {      
      //Setting the slider
      Slider slider = new Slider(0, 500, 0);      
      slider.setShowTickLabels(true);
      slider.setShowTickMarks(true);
      slider.setMajorTickUnit(100);
      slider.setBlockIncrement(50);     
      //Creating a VBox
      VBox vbox = new VBox();
      vbox.setPadding(new Insets(50, 50, 50, 50 ));
      vbox.setSpacing(150);
      vbox.getChildren().addAll(slider);      
      //Preparing the scene
      Scene scene = new Scene(vbox, 595, 150); 
      stage.setTitle("Slider Example");
      stage.setScene(scene);
      stage.show();
   }     
   public static void main(String args[]){
      launch(args);
   }
}
Output:
What are the different categories of functions in C Programming?

Depending on whether arguments are present or not and whether a value is returned or not, functions are categorized into −
Functions without arguments and without return values
Functions without arguments and without return values
Functions without arguments and with return values
Functions without arguments and with return values
Functions with arguments and without return values
Functions with arguments and without return values
Functions with arguments and with return values
Functions with arguments and with return values
#include<stdio.h>
main (){
   void sum ();
   clrscr ();
   sum ();
   getch ();
}
void sum (){
   int a,b,c;
   printf("enter 2 numbers:\n");
   scanf ("%d%d", &a, &b);
   c = a+b;
   printf("sum = %d",c);
}
Enter 2 numbers:
3
5
Sum=8
#include<stdio.h>
main (){
   int sum ();
   int c;
   c= sum ();
   printf(“sum = %d”,c);
   getch ();
}
int sum (){
   int a,b,c;
   printf(“enter 2 numbers”);
   scanf (“%d%d”, &a, &b);
   c = a+b;
   return c;
}
Enter two numbers 10 20
30
#include<stdio.h>
main (){
   void sum (int, int );
   int a,b;
   printf("enter 2 numbers");
   scanf("%d%d", &a,&b);
   sum (a,b);
   getch ();
}
void sum ( int a, int b){
   int c;
   c= a+b;
   printf (“sum=%d”, c);
}
Enter two numbers 10 20
Sum=30
#include<stdio.h>
main (){
   int sum ( int,int);
   int a,b,c;
   printf("enter 2 numbers");
   scanf("%d%d", &a,&b);
   c= sum (a,b);
   printf ("sum=%d", c);
   getch ();
}
int sum ( int a, int b ){
   int c;
   c= a+b;
   return c;
}
Enter two numbers 10 20
Sum=30
What is the best data type to store money values in MySQL?

We can store the money values in MySQL in decimal(value1,value2). Here, value1 is the total
range including value2. The value2 specifies the number of digits after the decimal point. To
understand this concept, the steps are given below.
First a table is created using the create command.
mysql> CREATE table MoneyDemo
-> (
-> Id int,
-> Money decimal(10,2)
-> );
Query OK, 0 rows affected (0.46 sec)
As can be seen from the above command, the decimal value has 10 digits only and also 2 digits
only after the decimal point.
After creating the table, some records are inserted with the help of the insert command. This is
given as follows −
mysql> INSERT into MoneyDemo values(1,98777445.50);
Query OK, 1 row affected (0.13 sec)

mysql> INSERT into MoneyDemo values(2,12345678.00);
Query OK, 1 row affected (0.18 sec)

mysql> INSERT into MoneyDemo values(3,88888888.50);
Query OK, 1 row affected (0.20 sec)
If more than 10 digits are inserted in the above commands, an error message will be generated.
This can be seen below −
mysql> INSERT into MoneyDemo values(3,8888888888.50);
ERROR 1264 (22003): Out of range value for column 'Money' at row 1
All the records in the table can be displayed with the help of the select statement. The query for
this is given below −
mysql> SELECT * from MoneyDemo;

The output obtained is as follows
+------+-------------+
| Id   | Money       |
+------+-------------+
| 1    | 98777445.50 |
| 2    | 12345678.00 |
| 3    | 88888888.50 |
+------+-------------+
3 rows in set (0.00 sec)
DSA using Java - Linear Search

Linear search is a very simple search algorithm. In this type of search, a sequential search is made over all items one by one. Every items is checked and if a match founds then that particular item is returned otherwise search continues till the end of the data collection. 
Linear Search ( A: array of item, n: total no. of items ,x: item to be searched)
Step 1: Set i to 1
Step 2: if i > n then go to step 7
Step 3: if A[i] = x then go to step 6
Step 4: Set i to i + 1
Step 5: Go to Step 2
Step 6: Print Element x Found at index i and go to step 8
Step 7: Print element not found
Step 8: Exit
package com.tutorialspoint.simplesearch;

import java.util.Arrays;

public class LinearSearchDemo {

public static void main(String args[]){
      // array of items on which linear search will be conducted. 
      int[] sourceArray = {1,2,3,4,6,7,9,11,12,14,15,
                           16,17,19,33,34,43,45,55,66,76,88};
      System.out.println("Input Array: " +Arrays.toString(sourceArray));
      printline(50);
      //find location of 1
      int location = find(sourceArray, 55);

      // if element was found 
      if(location != -1)
         System.out.println("Element found at location: " +(location+1));
      else
         System.out.println("Element not found.");

   }

   // this method makes a linear search. 
   public static int find(int[] intArray, int data){
      int comparisons = 0;
      int index= -1;

      // navigate through all items 
      for(int i=0;i<intArray.length;i++){
         // count the comparisons made 
         comparisons++;
         // if data found, break the loop 
         if(data == intArray[i]){
            index = i;
            break;
         }
      }
      System.out.println("Total comparisons made: " + comparisons);
      return index;
   }
   
   public static void printline(int count){
      for(int i=0;i <count-1;i++){
         System.out.print("=");
      }
         System.out.println("=");
   }
}

If we compile and run the above program then it would produce following result −
Input Array: [1, 2, 3, 4, 6, 7, 9, 11, 12, 14, 15, 16, 17, 19, 33, 34, 43, 45, 55, 66, 76, 88]
==================================================
Total comparisons made: 19
Element found at location: 19

 Print
 Add Notes
 Bookmark this page
How to add a rank column in base R of a data frame?

Ranking of a variable has many objectives such as defining order based on hierarchy but in data science, we use it mainly for analyzing non-parametric data. The ranking of a variable in an R data frame can be done by using rank function. For example, if we have a data frame df that contains column x then rank of values in x can be found as rank(df$x).
 Live Demo
Consider the below data frame:
x1<-sample(c("A","B","C"),20,replace=TRUE)
y1<-rpois(20,2)
df1<-data.frame(x1,y1)
df1
  x1 y1
1  A 4
2  A 0
3  A 2
4  B 1
5  A 0
6  C 6
7  A 4
8  C 0
9  C 4
10 B 1
11 A 2
12 B 2
13 B 2
14 B 3
15 C 0
16 B 1
17 C 3
18 C 4
19 C 2
20 C 2
Creating a column with Ranks of values in y1 −
df1$Rank<-rank(df1$y1)
df1
   x1 y1 Rank
1  A 4 17.5
2  A 0 2.5
3  A 2 10.5
4  B 1 6.0
5  A 0 2.5
6  C 6 20.0
7  A 4 17.5
8  C 0 2.5
9  C 4 17.5
10 B 1 6.0
11 A 2 10.5
12 B 2 10.5
13 B 2 10.5
14 B 3 14.5
15 C 0 2.5
16 B 1 6.0
17 C 3 14.5
18 C 4 17.5
19 C 2 10.5
20 C 2 10.5
 Live Demo
x2<-sample(c("F1","F2","F3","F4"),20,replace=TRUE)
y2<-sample(0:9,20,replace=TRUE)
df2<-data.frame(x2,y2)
df2
  x2 y2
1  F1 3
2  F1 4
3  F3 3
4  F4 1
5  F4 2
6  F2 9
7  F4 5
8  F1 1
9  F2 8
10 F2 1
11 F2 3
12 F4 0
13 F1 7
14 F4 5
15 F3 3
16 F2 9
17 F4 6
18 F4 6
19 F4 9
20 F2 9
Creating a column with Ranks of values in y2 −
df2$Rank<-rank(df2$y2)
df2
   x2 y2 Rank
1  F1 3 7.5
2  F1 4 10.0
3  F3 3 7.5
4  F4 1 3.0
5  F4 2 5.0
6  F2 9 18.5
7  F4 5 11.5
8  F1 1 3.0
9  F2 8 16.0
10 F2 1 3.0
11 F2 3 7.5
12 F4 0 1.0
13 F1 7 15.0
14 F4 5 11.5
15 F3 3 7.5
16 F2 9 18.5
17 F4 6 13.5
18 F4 6 13.5
19 F4 9 18.5
20 F2 9 18.5