code-rag-bench/online-tutorials huggingface dataset:
Difference between Hard real time and Soft real time system - GeeksforGeeks

10 May, 2020
Real time system is defined as a system in which job has deadline, job has to finished by the deadline (strictly finished). If a result is delayed, huge loss may happen.
1. Hard Real Time System :Hard real time is a system whose operation is incorrect whose result is not produce according to time constraint.For example,
1. Air Traffic Control
2. Medical System 
2. Soft Real Time System :Soft real time system is a system whose operation is degrade if results are not produce according to the specified timing requirement.For example<
1. Multimedia Transmission and Reception
2. Computer Games 
Difference between Hard real time and Soft real time system :
Difference Between
GATE CS
Operating Systems
Operating Systems
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Difference between Process and Thread
Stack vs Heap Memory Allocation
Difference Between Method Overloading and Method Overriding in Java
Differences between JDK, JRE and JVM
Layers of OSI Model
ACID Properties in DBMS
TCP/IP Model
Page Replacement Algorithms in Operating Systems
Normal Forms in DBMS
Render ASP.NET TextBox as HTML5 Input type “Number”

To render ASP.NET TextBox as HTML5 input type “Number”, set type="number" directly on the textbox.
Let us see an example of ASP.NET TextBox −
<asp:TextBox runat="server" type="number" />
You can also use the following dynamically created the control −
TextBox tb = new TextBox();
tb.Attributes.Add("Type", "number");
Tryit Editor v3.7

Tryit: no iframe border
GATE | GATE-CS-2017 (Set 1) | Question 64 - GeeksforGeeks

31 Aug, 2021
The output of executing the following C program is ________.
# include 

int total(int v) 
{ 
   static int count = 0; 
   while (v) { 
     count += v & 1; 
     v >>= 1; 
   } 
   return count; 
} 

void main() 
{ 
   static int x = 0; 
   int i = 5; 
   for (; i> 0; i--) { 
       x = x + total(i); 
   } 
   printf (“%d\n”, x) ; 
} 

(A) 23(B) 24(C) 26(D) 27Answer: (A)Explanation: Digits : 5-0101, 4-0100, 3-0011, 2-0010, 1-0001Countof 1s : 2, 3, 5, 6, 7
Total: 2+3+5+6+7 = 23
total(i)=23
Therefore, option A is correct
Check out the running code with comments:
#include<stdio.h>  int total(int v) {    static int count = 0;    while(v)     {        count += v&1;        v >>= 1;    }          //This count can be used to see number of 1s returned    //for every number i    //printf("%d", count);    return count;}  void main() {    static int x=0;    int i=5;    for(; i>0; i--)     {        //total gets added everytime with total number        //of digits in the given number i        x = x + total(i);    }    printf("%d\n", x);}
Alternate Solution :
This solution is contributed by parul sharmaQuiz of this Question
AnasH
adnanirshad158
GATE-CS-2017 (Set 1)
GATE-GATE-CS-2017 (Set 1)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-IT-2004 | Question 66
GATE | GATE CS 2019 | Question 27
GATE | GATE-CS-2006 | Question 49
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE-CS-2004 | Question 3
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2000 | Question 43
GATE | GATE-CS-2017 (Set 2) | Question 42
GATE | Gate IT 2007 | Question 30
GATE | GATE CS 2010 | Question 24
Sum of Two Integers in Python

Suppose we have two integers a and b. Our task is to find the sum of these two integers. One constraint is that, we cannot use any operator like + or -. So if a = 5 and b = 7, the result will be 12.
To solve this, we will follow these steps −
For solving we will use the bitwise logical operators
If b = 0, then return a
otherwise, recursively use the sum function by providing an XOR b, and a AND b after left shifting the result one time
Let us see the following implementation to get a better understanding −
 Live Demo
#include <iostream>
using namespace std;
class Solution {
   public:
   int getSum(int a, int b) {
      return b == 0?a:getSum(a^b, (unsigned int)(a&b)<<1);
   }
};
main(){
   Solution ob;
   cout<<ob.getSum(5,7)<<endl;
}
a = 5
b = 7
12
Create a TreeMap in Java and add key-value pairs

A TreeMap cannot contain duplicate keys. TreeMap cannot contain the null key. However, It can have null values.
Let us first see how to create a TreeMap −
TreeMap<Integer,String> m = new TreeMap<Integer,String>();
Add some elements in the form of key-value pairs −
m.put(1,"India");
m.put(2,"US");
m.put(3,"Australia");
m.put(4,"Netherlands");
m.put(5,"Canada");
The following is an example to create a TreeMap and add key-value pairs −
 Live Demo
import java.util.*;
public class Demo {
   public static void main(String args[]) {
      TreeMap<Integer,String> m = new TreeMap<Integer,String>();
      m.put(1,"India");
      m.put(2,"US");
      m.put(3,"Australia");
      m.put(4,"Netherlands");
      m.put(5,"Canada");
      for(Map.Entry e:m.entrySet()) {
         System.out.println(e.getKey()+" "+e.getValue());
      }
   }
}
1 India
2 US
3 Australia
4 Netherlands
5 Canada
How do you get the font metrics in Java Swing?

To get the font metrics, use the FontMetrics class:
Graphics2D graphics = (Graphics2D) gp.create();
String str = getWidth() + "(Width) x (Height)" + getHeight();
FontMetrics m = graphics.getFontMetrics();
Now to display it:
int xValue = (getWidth() - m.stringWidth(str)) / 2;
int yValue = ((getHeight() - m.getHeight()) / 2) + m.getAscent();
graphics.drawString(str, xValue, yValue);
The following is an example to get the font metrics in Java Swing:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class SwingDemo {
   public static void main(String[] args) {
      JFrame frame = new JFrame("Font Metrics");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setLayout(new BorderLayout());
      frame.add(new Demo());
      frame.pack();
      frame.setVisible(true);
      System.out.println(frame.getSize());
   }
}
class Demo extends JPanel {
   @Override
   public Dimension getPreferredSize() {
      return new Dimension(500, 500);
   }
   @Override
   protected void paintComponent(Graphics gp) {
      super.paintComponent(gp);
      Graphics2D graphics = (Graphics2D) gp.create();
      String str = getWidth() + "(Width) x (Height)" + getHeight();
      FontMetrics m = graphics.getFontMetrics();
      int xValue = (getWidth() - m.stringWidth(str)) / 2;
      int yValue = ((getHeight() - m.getHeight()) / 2) + m.getAscent();
      graphics.drawString(str, xValue, yValue);
      graphics.dispose();
   }
}
Style input type button with CSS

The input type button can be a submit button or reset button. With CSS, we can style any button on a web page.
You can try to run the following code to style input type button:
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <style>
         input[type=button] {
            background-color: orange;
            border: none;
            text-decoration: none;
            color: white;
            padding: 20px 20px;
            margin: 20px 20px;
            cursor: pointer;
         }
      </style>
   </head>
   <body>
      <p>Fill the below form,</p>
      <form>
         <label for = "subject">Subject</label>
         <input type = "text" id = "subject" name = "sub"><br><br>
         <label for = "student">Student</label>
         <input type = "text" id = "student" name = "stu"><br>
         <input type = "button" value = "Button">
      </form>
   </body>
</html>
Peewee - Update Existing Records

Existing data can be modified by calling save() method on model instance as well as with update() class method.
Following example fetches a row from User table with the help of get() method and updates it by changing the value of age field.
row=User.get(User.name=="Amar")
print ("name: {} age: {}".format(row.name, row.age))
row.age=25
row.save()
The update() method of Method class generates UPDATE query. The query object’s execute() method is then invoked.
Following example uses update() method to change the age column of rows in which it is >20.
qry=User.update({User.age:25}).where(User.age>20)
print (qry.sql())
qry.execute()
The SQL query rendered by update() method is as follows −
('UPDATE "User" SET "age" = ? WHERE ("User"."age" > ?)', [25, 20])
Peewee also has a bulk_update() method to help update multiple model instance in a single query operation. The method requires model objects to be updated and list of fields to be updated.
Following example updates the age field of specified rows by new value.
rows=User.select()
rows[0].age=25
rows[2].age=23
User.bulk_update([rows[0], rows[2]], fields=[User.age])
 Print
 Add Notes
 Bookmark this page
\ldots - Tex Command

\ldots - Used to draw lower dots symbol.
{ \ldots }
\ldots command is used to draw lower dots symbol.

x_1,\ldots,x_n

x1,...,xn



x_1,\ldots,x_n

x1,...,xn


x_1,\ldots,x_n

    14 Lectures 
     52 mins

 Ashraf Said

    11 Lectures 
     1 hours 

 Ashraf Said

    9 Lectures 
     1 hours 

 Emenwa Global, Ejike IfeanyiChukwu

    29 Lectures 
     2.5 hours 

 Mohammad Nauman

    14 Lectures 
     1 hours 

 Daniel Stern

    15 Lectures 
     47 mins

 Nishant Kumar
 Print
 Add Notes
 Bookmark this page
How to get the absolute coordinates of a view in Android?

Before getting into example, we should know what is absolute coordinates. It means absolute position (x,y)of a view on window manager. This example demonstrate about how to get the absolute coordinates of a view.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version = "1.0" encoding = "utf-8"?>
<RelativeLayout
   xmlns:android = "http://schemas.android.com/apk/res/android"
   xmlns:tools = "http://schemas.android.com/tools"
   android:layout_width = "match_parent"
   android:layout_height = "match_parent"
   android:padding = "16dp"
   tools:context = ".MainActivity"
   android:background = "#dde4dd">
   <TextView
      android:id = "@+id/text"
      android:layout_marginLeft = "100dp"
      android:layout_width = "wrap_content"
      android:layout_height = "wrap_content"
      android:text = "Hello World!" />
</RelativeLayout>
In the above xml, we have given one Textview. when user click on textview, it will show the position of the view on Toast.
Step 3 − Add the following code to src/MainActivity.java
package com.example.andy.myapplication;

import android.graphics.Point;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.TextureView;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
   TextView textView;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      textView = findViewById(R.id.text);
      textView.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            int[] location = new int[2];
            textView.getLocationOnScreen(location);
            Toast.makeText(MainActivity.this,"X axis is "+location[0] +"and Y axis is "+location[1],Toast.LENGTH_LONG).show();
         }
      });
   }
   public static Point getLocationOnScreen(View view) {
      int[] location = new int[2];
      view.getLocationOnScreen(location);
      return new Point(location[0], location[1]);
   }
}
In the above code, when user click on textview, it will show absolute coordinates on the screen . Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run  icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
In the above result is initial screen, when user click on textview, it will show the result as shown below -
Click here to download the project code
Jackson Annotations - @JsonBackReference

@JsonManagedReferences and JsonBackReferences are used to display objects with parent child relationship. @JsonManagedReferences is used to refer to parent object and @JsonBackReferences is used to mark child objects.
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JacksonTester {
   public static void main(String args[]) throws IOException, ParseException {
      ObjectMapper mapper = new ObjectMapper();     
      Student student = new Student(1, "Mark");
      Book book1 = new Book(1,"Learn HTML", student);
      Book book2 = new Book(1,"Learn JAVA", student);

      student.addBook(book1);
      student.addBook(book2);

      String jsonString = mapper
         .writerWithDefaultPrettyPrinter()
         .writeValueAsString(book1);
      System.out.println(jsonString);
   }
}
class Student { 
   public int rollNo;
   public String name;

   @JsonBackReference
   public List<Book> books;

   Student(int rollNo, String name){
      this.rollNo = rollNo;
      this.name = name;
      this.books = new ArrayList<Book>();
   }
   public void addBook(Book book){
      books.add(book);
   }
}
class Book {
   public int id;
   public String name;

   Book(int id, String name, Student owner) {
      this.id = id;
      this.name = name;
      this.owner = owner;
   }

   @JsonManagedReference
   public Student owner;
}
{
   "id" : 1,
   "name" : "Learn HTML",
   "owner" : {
      "rollNo" : 1,
      "name" : "Mark"
   }
}

 Print
 Add Notes
 Bookmark this page
How to find by id in MongoDB?

To find by id in MongoDB, use the find() method as in the below syntax −
db.findByIdDemo.find({"_id" :yourObjectId});
To understand the above syntax, let us create a collection with documents −
> db.findByIdDemo.insertOne({"Value":10});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e07158925ddae1f53b621fc")
}
> db.findByIdDemo.insertOne({"Value":500});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e07158c25ddae1f53b621fd")
}
> db.findByIdDemo.insertOne({"Value":1000});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e07159125ddae1f53b621fe")
}
Following is the query to display all documents from a collection with the help of find() method −
> db.findByIdDemo.find();
This will produce the following output −
"_id" : ObjectId("5e07158925ddae1f53b621fc"), "Value" : 10 }
{ "_id" : ObjectId("5e07158c25ddae1f53b621fd"), "Value" : 500 }
{ "_id" : ObjectId("5e07159125ddae1f53b621fe"), "Value" : 1000 }
Following is the query to find by id in MongoDB −/p>
> db.findByIdDemo.find({"_id" :ObjectId("5e07158c25ddae1f53b621fd")});
This will produce the following output −
{ "_id" : ObjectId("5e07158c25ddae1f53b621fd"), "Value" : 500 }
Can you assign an Array of 100 elements to an array of 10 elements in Java?

In general, arrays are the containers that store multiple variables of the same datatype. These are of fixed size and the size is determined at the time of creation. Each element in an array is positioned by a number starting from 0.
You can access the elements of an array using name and position as −
System.out.println(myArray[3]);
//Which is 1457
In Java, arrays are treated as referenced types you can create an array using the new keyword similar to objects and populate it using the indices as −
int myArray[] = new int[7];
While creating array in this way, you must specify the size of the array.
You can also directly assign values within flower braces separating them with commas (,) as −
int myArray = {1254, 1458, 5687, 1457, 4554, 5445, 7524};
Yes, you can assign an array with 100 elements to an array of size 10 provided they are of same type.
While assigning the compiler doesn’t bother the sizes it just verifies the type of both arrays and proceeds further.
import java.util.Arrays;
public class Test {
   public static void main(String[] args) {
      int[] intArray = new int[100];
      for(int i=0; i<100; i++) {
         intArray[i] = i;
      }
      System.out.println(Arrays.toString(intArray));
   }
}
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49,
50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73,
74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95,
96, 97, 98, 99]
Recursive product of summed digits JavaScript

We have to create a function that takes in any number of arguments (Number literals), adds them together, and returns the product of digits when the answer is only 1 digit long.
For example −
If the arguments are −
16, 34, 42
We have to first add them together −
16+34+42 = 92
And then keep multiplying the digits together until we get a 1-digit number like this −
9*2 = 18
1*8 = 8
When we get the one-digit number, we have to return it from our function.
We will break this into two functions −
One function accepts a number and returns the product of its digits, we will use recursion to do so, let’s call this first function product().
One function accepts a number and returns the product of its digits, we will use recursion to do so, let’s call this first function product().
Second function recursively calls this product() function and checks if the product happens to be 1 digit, it returns the product otherwise it keeps on iterating.
Second function recursively calls this product() function and checks if the product happens to be 1 digit, it returns the product otherwise it keeps on iterating.
The code for this whole functionality will be −
const recursiveMuliSum = (...numbers) => {
   const add = (a) => a.length === 1 ? a[0] : a.reduce((acc, val) => acc+val);
   const produce = (n, p = 1) => {
      if(n){
         return produce(Math.floor(n/10), p*(n%10));
      };
      return p;
   };
   const res = produce(add(numbers));
   if(res > 9){
      return recursiveMuliSum(res);
   }
   return res;
};
console.log(recursiveMuliSum(16, 28));
console.log(recursiveMuliSum(16, 28, 44, 76, 11));
console.log(recursiveMuliSum(1, 2, 4, 6, 8));
The output in the console will be −
6
5
2
How to show all the options from a dropdown list with JavaScript?

To show all the options from a dropdown list, use the options property. The property allows you to get all the options with length property.
You can try to run the following code to get all the options from a drop-down list.
Live Demo
<!DOCTYPE html>
<html>
   <body>
      <form id="myForm">
         <select id="selectNow">
            <option>One</option>
            <option>Two</option>
            <option>Three</option>
         </select>
         <input type="button" onclick="display()" value="Click">
      </form>
      <p>Click the button to get all the options</p>
      <script>
         function display() {
            var a, i, options;
            a = document.getElementById("selectNow");
            options = "";
            for (i = 0; i < a.length; i++) {
               options = options + "<br> " + a.options[i].text;
            }
            document.write("DropDown Options: "+options);
         }
      </script>
   </body>
</html>
Boehm’s Software Maintenance Model - GeeksforGeeks

16 Jun, 2020
In 1983, Boehm proposed a model for the maintenance process which was based upon the economic models and principles. Economics model is nothing new thing, economic decisions are a major building block of many processes and Boehm’s thesis was that economics model and principles could not only improve productivity in the maintenance but it also helps to understand the process very well.
Boehm maintenance process model represented as a closed-loop cycle as shown in the below diagram.
He theorizes that it is the platform where management decisions are made that drive the process. In this stage, a set of required changes is determined by applying particular strategies and cost -benefits evaluations to a set of proposed changes. Those approved changes are accompanied by company budgets, which will largely determine the extent and type of resources expanded.
Boehm had understood that the maintenance manager’s task is one of the balancing and the pursuit of the objectives of maintenance against the constraint imposed by the environment in which maintenance work is carried out. That’s why, the maintenance process should be driven by the maintenance manager’s decisions, which are typically based on the balancing of objectives against the constraint. Boehm proposed a formula for calculating the maintenance cost as it is a part of the COCOMO Model. All the collected data from the various projects, the formula was formed in terms of effort.
Boehm used a quantity called Annual Charge Traffic (ACT), which is defined as:
The fraction of a software product’s source instruction which changes during a year either through add, delete or modify.The ACT is related to the number of change request,
ACT = KLOCadded +  KLOCdeleted /  KLOCtotal 
The annual maintenance effort (AME) in person-months is measured as:
AME = ACT * SDE
Where,ACT = Annual change traffic,SDE = Software Development effort in person-months.
Example –Annual change traffic (ACT) for a software system is 20% per year. The development effort is 700 PMs. Compute an estimate the annual maintenance effort (AME). If the lifetime of the project is 15 years, what is the total effort of the project ?
Explanation :Given,The development effort = 700PMAnnual Charge traffic (ACT) = 20%Total duration for which effort is to be calculated = 15years.
The maintenance effort is a fraction of development effort and that is assumed to be constant.
AME 
= ACT * SDE
= 0.20 * 700 
= 140PM 
Maintenance effort for 15 years,
= 15 * 140 
= 2100PM 
So, Total effort,
= 700 + 2100 
= 2800PM 
Software Engineering
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
DFD for Library Management System
What is DFD(Data Flow Diagram)?
Use Case Diagram for Library Management System
RUP and its Phases
Software Development Life Cycle (SDLC)
System Testing
Software Engineering | Black box testing
Data Dictionaries in Software Engineering
Software Engineering | Seven Principles of software testing
Software Engineering | System configuration management
C# Program for Converting Hexadecimal String to Integer - GeeksforGeeks

02 Jul, 2020
Given an hexadecimal number as input, we need to write a program to convert the given hexadecimal number into equivalent integer. To convert an hexadecimal string to integer, we have to use Convert.ToInt32() function to convert the values.
Syntax: 
Convert.ToInt32(input_string, Input_base);

Here,
input_string is the input containing hexadecimal number in string format.
input_base is the base of the input value – for a hexadecimal value it will be 16.
Examples:
Input : 56304
Output : 353028

Input : 598f
Output : 22927

If we input wrong value for eg. 672g, it shows error: Enter a hexadecimal number: System.FormatException: Additional unparsable characters are at the end of the string.
If we input number greater than 8 digit e.g. 746465789, it shows error: Enter a hexadecimal number: System.OverflowException: Arithmetic operation resulted in an overflow.
Program 1:  
C#
// C# program to convert array // of hexadecimal strings to integersusing System;using System.Text;  class Program {        static void Main(string[] args)    {        // hexadecimal number as string        string input = "56304";        int output = 0;                // converting to integer        output = Convert.ToInt32(input, 16);                // to print  the value        Console.WriteLine("Integer number: " + output);    }}
Output: 
Integer number: 353028

Program 2:  
C#
// C# program to convert array // of hexadecimal strings// to integersusing System;using System.Text;  namespace geeks {    class GFG {        static void Main(string[] args)    {        string input = "";        int output = 0;        try {                        // input string            Console.Write("Enter a hexadecimal number: ");            input = Console.ReadLine();              // converting to integer            output = Convert.ToInt32(input, 16);              Console.WriteLine("Integer number: " + output);        }        catch (Exception ex) {            Console.WriteLine(ex.ToString());        }          // hit ENTER to exit        Console.ReadLine();    }}}
Input:
598f
Output:
Enter a hexadecimal number: 
Integer number: 22927

C#
C# Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# Dictionary with examples
C# | Delegates
C# | Method Overriding
C# | Abstract Classes
Extension Method in C#
Convert String to Character Array in C#
Program to Print a New Line in C#
Getting a Month Name Using Month Number in C#
Socket Programming in C#
Program to find absolute value of a given number
Python - Word Tokenization

Word tokenization is the process of splitting a large sample of text into words. This is a requirement in natural language processing tasks where each word needs to be captured and subjected
to further analysis like classifying and counting them for a particular sentiment etc. The Natural Language Tool kit(NLTK) is a library used to achieve this. Install NLTK before proceeding with the python 
program for word tokenization. 
conda install -c anaconda nltk
Next we use the word_tokenize method to split the paragraph into individual words.
import nltk

word_data = "It originated from the idea that there are readers who prefer learning new skills from the comforts of their drawing rooms"
nltk_tokens = nltk.word_tokenize(word_data)
print (nltk_tokens)
When we execute the above code, it produces the following result.
['It', 'originated', 'from', 'the', 'idea', 'that', 'there', 'are', 'readers', 
'who', 'prefer', 'learning', 'new', 'skills', 'from', 'the',
'comforts', 'of', 'their', 'drawing', 'rooms']
We can also tokenize the sentences in a paragraph like we tokenized the words. We use the method sent_tokenize to achieve this. Below is an example.
import nltk
sentence_data = "Sun rises in the east. Sun sets in the west."
nltk_tokens = nltk.sent_tokenize(sentence_data)
print (nltk_tokens)
When we execute the above code, it produces the following result.
['Sun rises in the east.', 'Sun sets in the west.']

    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
Shell Script to Display All Words of a File in Ascending Order - GeeksforGeeks

19 Jul, 2021
Here we will see a shell script that will arrange all the words from a file in ascending order, which comes in handy when we have many words that need to be sorted in ascending order. The script helps to analyze the data easily and represent it in a much more organized manner.
Approach:
Store the value of the file into a filename variable.Store the words into a TEMP file.Sort the words using the sort command.If TEMP file exists then delete it.
Store the value of the file into a filename variable.
Store the words into a TEMP file.
Sort the words using the sort command.
If TEMP file exists then delete it.
Example: 
There is a File named : words.txt which contain the following word, 
Input: word.txt.
Word.txt contains: creature, assorted, bent.
Output: 
assorted
bent
creature
The Shell Script is given below:
# Shell Script to Display All Words of a File in Ascending Order
# echo is for printing the message
echo -n "Enter name of the file :"
# read file name  
read filename
# condition checking if the file exists
# if file do not exists the print "file does not exist"
if [ ! -f $filename ]
then
   echo "File does not exist"
else
# in for loop we are comparing the words and storing it in TEMP file
for i in $(cat $filename)
do
 echo $i >> "TEMP"
done
# printing the sorted value in ascending order
echo "***SORTED WORDS IN ASCENDING ORDER***"
echo "$(sort "TEMP")"
fi
# condition checking if the TEMP file exists
# if the TEMP file already exists then it will delete it
if [ -f "TEMP" ]
then
rm "TEMP"
fi
Input:  words.txt containing 100 words.
Output:
ruhelaa48
Picked
Shell Script
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TCP Server-Client implementation in C
curl command in Linux with Examples
Conditional Statements | Shell Script
UDP Server-Client implementation in C
Tail command in Linux with examples
Cat command in Linux with examples
touch command in Linux with Examples
Compiling with g++
echo command in Linux with Examples
ps command in Linux with Examples
Terra - OSINT Tool On Instagram - GeeksforGeeks

28 Nov, 2021
Terra is an Open Source Intelligence Tool. Terra can give you so much information about an Instagram account that is not easily visible to a normal user. Using Terra you can get various information such as location, timestamp, caption, picture, URL of the account.  Terra is a free and open-source tool available on GitHub which can be used to perform reconnaissance on Instagram account/profiles. The location parameter of the terra will give you a complete list of all the locations over where the user has tagged the location on pictures, posts, etc. Timestamp will give you the actual timestamp of all the posts of the user. Terra even gives the email address of the user if an email is used anywhere it’ll be displayed. Terra is written in python language. You must have python language installed in your kali Linux operating system. As this tool is open source so you can contribute in this tool. This tool is very useful when you want to get information about Instagram that you normally wouldn’t be able to get from just looking at the profile of the user. 
Step 1: Open your kali linux operating system and use the following command to install the tool from GitHub.
git clone https://github.com/xadhrit/terra.git
Step 2: Use the following command to move in to the directory of the tool.
cd terra
Step 3: Now install the dependences of the tool.
python3 -m pip install -r requirements.txt
Step 4: Now use the following command to run the tool.
python3 terra.py
Now we will see example to use the tool.
Example: use the terra tool to find information about a username of a Instagram account.
python3 terra.py <username of target> 
The tool found the details of given username.
Kali-Linux
Linux-Tools
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
scp command in Linux with Examples
Docker - COPY Instruction
mv command in Linux with examples
SED command in Linux | Set 2
chown command in Linux with Examples
nohup Command in Linux with Examples
Named Pipe or FIFO with example C program
Thread functions in C/C++
uniq Command in LINUX with examples
Start/Stop/Restart Services Using Systemctl in Linux
Python program to implement Half Adder

21 Aug, 2021
Prerequisite: Half Adder in Digital Logic
Given two inputs of Half Adder A, B. The task is to implement the Half Adder circuit and Print output i.e sum and carry of two inputs.
Half Adder: A half adder is a type of adder, an electronic circuit that performs the addition of numbers. The half adder is able to add two single binary digits and provide the output plus a carrying value. It has two inputs, called A and B, and two outputs S (sum) and C (carry).
Logical Expression:  
Sum = A XOR B  
Carry = A AND B 
Truth Table:
Examples:
Input : 0 1
Output: Sum=1, Carry=0
Explanation: According to logical expression Sum=A XOR B  i.e 0 XOR 1 =1 , Carry=A AND B  i.e 0 AND 1 =0
Input : 1 1
Output: Sum=0, Carry=1
Explanation: According to logical expression Sum=A XOR B  i.e 1 XOR 1 =0 , Carry=A AND B  i.e 1 AND 1 =1
Approach:
We take two inputs A and B.
XOR operation on A and B gives the value of the sum.
AND operation on A and B gives the value of Carry.
Below is the implementation.
Python3
# Function to print sum and carrydef getResult(A, B):       # Calculating value of sum    Sum = A ^ B         # Calculating value of Carry    Carry = A & B         # printing the values    print("Sum ", Sum)    print("Carry", Carry)  # Driver codeA = 0B = 1 # passing two inputs of halfadder as arguments to get result functiongetResult(A, B)
Output:
Sum  1
Carry 0
simranarora5sos
anudeep23042002
Technical Scripter 2020
Digital Electronics & Logic Design
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to memory and memory units
Analog to Digital Conversion
Latches in Digital Logic
Introduction of Sequential Circuits
Half Subtractor in Digital Logic
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
Python Dictionary
How to get column names in Pandas dataframe
SQL Query to List All Databases

15 May, 2021
SQL language is a DML in DBMS. This is used to manipulate databases and the records kept in them. A database is a collection of structured information or data stored in any computer system. So to modify these databases or to update any data contained by them, we are using DML languages like SQL, etc. We will mainly be using MS SQL SERVER for this topic.
So first let us create some of the databases which we will be using in this article to query up using SQL.
To create a database in SQL we have to use the following command:
CREATE DATABASE database_name;
This command creates a database of the given names in the SQL server and then we can add tables to this database also through SQL. We can also add tuples or rows in these tables, or we can delete the tables or update or modify them according to our needs using SQL. 
To use any particular database we should select between them which we can do as shown below:
USE database_name;
So let’s add two tables to this database using SQL.
To do that we will be using the below given commands:
CREATE TABLE [database_name.]table_name (
   pk_column data_type PRIMARY KEY,
   column_1 data_type NOT NULL,
   column_2 data_type,
   ...,
   table_constraints
);
If we do not mention the name of the database then the default USE database is selected for the creation of tables.
Below are some commands which shows how we created databases and then how we listed them and run queries on them.
There are default databases present on SQL server initially, which are of two types :
The command to see system databases are :
SELECT name, database_id, create_date  
FROM sys.databases ;  
Output:
There are mainly four types of system databases :
mastermodelmsdbtmpdb
master
model
msdb
tmpdb
Some other databases are also present in the server other than the above ones. Those can be displayed as shown below:
SELECT name FROM master.dbo.sysdatabases
Output:
Now in order to select the user-defined databases first let’s create some databases in the server.
We will be using the below-mentioned commands to add some databases to SQL server:
create database GFG;
create database GFG1;
create database GFG2;
Output:
These are the query to list the user-defined database present in the server (while we had done above):
select name  
from sys.Databases
WHERE name NOT IN ('master', 'tempdb', 'model', 'msdb');  /* removing the name of sys db*/
Output:
Hence in this way we are able to select and list all the user-defined and non-user-defined databases in the SQL server.
Picked
SQL-Query
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Replacing missing values using Pandas in Python

16 Nov, 2020
Dataset is a collection of attributes and rows. Data set can have missing data that are represented by NA in Python and in this article, we are going to replace missing values in this article
We consider this data set: Dataset
data set
In our data contains missing values in quantity, price, bought, forenoon and afternoon columns,
So, We can replace missing values in the quantity column with mean, price column with a median, Bought column with standard deviation. Forenoon column with the minimum value in that column. Afternoon column with maximum value in that column.
Approach:
Import the module
Load data set
Fill in the missing values
Verify data set
Syntax:
Mean: data=data.fillna(data.mean())
Median: data=data.fillna(data.median())
Standard Deviation: data=data.fillna(data.std())
Min: data=data.fillna(data.min())
Max: data=data.fillna(data.max())
Below is the Implementation:
Python3
# importing pandas moduleimport pandas as pd  # loading data setdata = pd.read_csv('item.csv')  # display the dataprint(data)
Output:
Then after we will proceed with Replacing missing values with mean, median, mode, standard deviation, min & max
Python3
# replacing missing values in quantity# column with mean of that columndata['quantity'] = data['quantity'].fillna(data['quantity'].mean())  # replacing missing values in price column# with median of that columndata['price'] = data['price'].fillna(data['price'].median())  # replacing missing values in bought column with# standard deviation of that columndata['bought'] = data['bought'].fillna(data['bought'].std())  # replacing missing values in forenoon  column with# minimum number of that columndata['forenoon'] = data['forenoon'].fillna(data['forenoon'].min())  # replacing missing values in afternoon  column with # maximum number of that columndata['afternoon'] = data['afternoon'].fillna(data['afternoon'].max())  print(Data)
Output:
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary keys() method

31 May, 2021
Dictionary in Python is a collection of data values which only maintains the order of insertion, used to store data values like a map, which, unlike other Data Types that hold only a single value as an element, Dictionary holds key: value pair.
keys() method in Python Dictionary, returns a view object that displays a list of all the keys in the dictionary in order of insertion. 
Syntax: dict.keys()Parameters: There are no parameters.Returns: A view object is returned that displays all the keys. This view object changes according to the changes in the dictionary.
Example #1: 
Python3
# Python program to show working# of keys in Dictionary # Dictionary with three keysDictionary1 = {'A': 'Geeks', 'B': 'For', 'C': 'Geeks'} # Printing keys of dictionaryprint(Dictionary1.keys()) # Creating empty Dictionaryempty_Dict1 = {} # Printing keys of Empty Dictionaryprint(empty_Dict1.keys())
Output: 
dict_keys(['A', 'B', 'C'])
dict_keys([])
Note: The order of these key values in the list may not always be the same.   Example #2: To show how updation of dictionary works 
Python3
# Python program to show updation# of keys in Dictionary # Dictionary with two keysDictionary1 = {'A': 'Geeks', 'B': 'For'} # Printing keys of dictionaryprint("Keys before Dictionary Updation:")keys = Dictionary1.keys()print(keys) # adding an element to the dictionaryDictionary1.update({'C':'Geeks'}) print('\nAfter dictionary is updated:')print(keys)
Output: 
Keys before Dictionary Updation:
dict_keys(['B', 'A'])

After dictionary is updated:
dict_keys(['B', 'A', 'C'])
Here, when the dictionary is updated, keys are also automatically updated to show the changes. 
Practical Application: The keys() can be used to access the elements of the dictionary as we can do for the list, without the use of keys(), no other mechanism provides means to access dictionary keys as a list by index. This is demonstrated in the example below. 
Example #3: Demonstrating the practical application of keys() 
Python3
# Python program to demonstrate# working of keys() # initializing dictionarytest_dict = { "geeks" : 7, "for" : 1, "geeks" : 2 } # accessing 2nd element using naive method# using loopj = 0for i in test_dict:    if (j == 1):        print ('2nd key using loop : ' + i)    j = j + 1 # accessing 2nd element using keys()print ('2nd key using keys() : ' + test_dict.keys()[1])
Output : 
2nd key using loop : for
TypeError: 'dict_keys' object does not support indexing 
Note: The second approach would not work because dict_keys in Python 3 does not support indexing.  
manjeet_04
Rohan_Navlakhe
michaelalanwalters
python-dict
Python-dict-functions
Python
python-dict
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# Program to Calculate the Sum of Array Elements using the LINQ Aggregate() Method - GeeksforGeeks

09 Dec, 2021
Given an array of integers, now we calculate the sum of array elements. So we use the Aggregate() method of LINQ. This method applies a function to all the elements of the source sequence and calculates a cumulative result and return value. This method is overloaded in three different ways:
Aggregate<TSource, TAccumulate, TResult>(IEnumerable<TSource>, TAccumulate, Func<TAccumulate, TSource, TAccumulate>, Func<TAccumulate, TResult>): It applies an accumulator function on the specified sequence. Here, the seed value is used to define the starting accumulator value, and the function is used to select the final result value.
Aggregate<TSource, TAccumulate>(IEnumerable<TSource>, TAccumulate, Func<TAccumulate, TSource, TAccumulate>): It applies an accumulator function on the specified sequence. Here, the specified seed value is used to define the starting accumulator value.
Aggregate<TSource>(IEnumerable<TSource>, Func<TSource, TSource, TSource>): It applies an accumulator function on the specified sequence.
Example:
Input: { 34, 27, 34, 5, 6 }
Output: Sum = 106

Input: { 3, 4, 27, 34, 15, 26, 234, 123 }
Output:  Sum = 466
Approach:
1. Create and initialize an array of integer type
2. Now find the sum of the array using the Aggregate() function.
sum = arr.Aggregate((element1,element2) => element1 + element2);
3. Display the sum of the elements of the array
Example:
C#
// C# program to finding the sum of the array elements// using Aggregate() Methodusing System;using System.Linq; class GFG{ static void Main(string[] args){         // Creating and initializing the array    // with integer values    int[] arr = { 1, 2, 3, 14, 5, 26, 7, 8, 90, 10};    int sum = 0;         // Finding the sum of the elements of arr    // using Aggregate() Method    sum = arr.Aggregate((element1, element2) => element1 + element2);         // Displaying the final output    Console.Write("Sum is : " + sum);}}
Output:
Sum is : 166
 
surinderdawra388
CSharp LINQ
Picked
C#
C# Programs
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?
Convert String to Character Array in C#
Socket Programming in C#
Program to Print a New Line in C#
Getting a Month Name Using Month Number in C#
Program to find absolute value of a given number
Pattern asPredicate() method in Java with examples

The Predicate interface of the java.util.function package can be used as a target for lambda expressions. The test method of this interface accepts a value ad validates it with the current value of the Predicate object. This method returns true in-case of a match, else false.
The asPredicate() method of the java.util.regex.Pattern class returns a Predicate object which can match a string with the regular expression using which the current Pattern object was compiled.
import java.util.Scanner;
import java.util.function.Predicate;
import java.util.regex.Pattern;
public class AsPredicateExample {
   public static void main( String args[] ) {
      //Reading string value
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter input string");
      String input = sc.nextLine();
      //Regular expression to find digits
      String regex = "[t]";
      //Compiling the regular expression
      Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
      //Converting the regular expression to predicate
      Predicate<String> predicate = pattern.asPredicate();
      //Testing the predicate with the input string
      boolean result = predicate.test(input);
      if(result) {
         System.out.println("Match found");
      } else {
         System.out.print("Match not found");
      }
   }
}
Enter input string
Tutorialspoint
Number of matches: 3
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
import java.util.function.Predicate;
import java.util.regex.Pattern;
public class AsPredicateExample {
   public static void main( String args[] ) {
      ArrayList<String> list = new ArrayList<String>();
      list.addAll(Arrays.asList("Java", "JavaFX", "Hbase", "JavaScript"));
      //Regular expression to find digits
      String regex = "[J]";
      //Compiling the regular expression
      Pattern pattern = Pattern.compile(regex);
      //Converting the regular expression to predicate
      Predicate<String> predicate = pattern.asPredicate();
      list.forEach(n -> { if (predicate.test(n)) System.out.println("Match found "+n); });
   }
}
Match found Java
Match found JavaFX
Match found JavaScript
Where is MySQL bin directory located in Windows OS?

Let’s say we installed MySQL version is 8.0 on our Windows OS. The bin directory is present at the following location −
C:\Program Files\MySQL\MySQL Server 8.0\bin
Let us check the location. The screenshot is as follows −
These are the drives −
Go to C: drive and click Program Files −
Now, click “MySQL” and open the folder −
After that, click the current MySQL version folder. For us, it is MySQL Server 8.0 −
Inside the folder, you can easily locate the bin folder as shown in the following screenshot −
What is typeof Operator in JavaScript?

The typeof operator is a unary operator that is placed before its single operand, which can be of any type. Its value is a string indicating the data type of the operand.  The typeof operator evaluates to "number", "string" or "boolean" if its operand is a number, string, or boolean value and returns true or false based on the evaluation.
Here is a list of the return values for the typeof Operator.
The following code shows how to implement typeof operator −
<html>
   <body>
      <script>
         var a = 10;
         var b = "String";
         var linebreak = "<br />";

         result = (typeof b == "string" ? "B is String" : "Bis Numeric");
         document.write("Result => ");
         document.write(result);
         document.write(linebreak);

         result = (typeof a == "string" ? "A is String" : "Ais Numeric");
         document.write("Result => ");
         document.write(result);
         document.write(linebreak);
      </script>
   </body>
</html>