code-rag-bench/online-tutorials huggingface dataset:
What is Replication in Distributed System?

17 Dec, 2021
In a distributed system data is stored is over different computers in a network. Therefore, we need to make sure that data is readily available for the users. Availability of the data is an important factor often accomplished by data replication. Replication is the practice of keeping several copies of data in different places.
The first and foremost thing is that it makes our system more stable because of node replication. It is good to have replicas of a node in a network due to following reasons:
If a node stops working, the distributed network will still work fine due to its replicas which will be there. Thus it increases the fault tolerance of the system.
It also helps in load sharing where loads on a server are shared among different replicas.
It enhances the availability of the data. If the replicas are created and data is stored near to the consumers, it would be easier and faster to fetch data.
Active Replication
Passive Replication
The request of the client goes to all the replicas.
It is to be made sure that every replica receives the client request in the same order else the system will get inconsistent.
There is no need for coordination because each copy processes the same request in the same sequence.
All replicas respond to the client’s request.
Advantages:
It is really simple. The codes in active replication are the same throughout.
It is transparent.
Even if a node fails, it will be easily handled by replicas of that node.
Disadvantages:
It increases resource consumption. The greater the number of replicas, the greater the memory needed.
It increases the time complexity. If some change is done on one replica it should also be done in all others.
The client request goes to the primary replica, also called the main replica.
There are more replicas that act as backup for the primary replica.
Primary replica informs all other backup replicas about any modification done.
The response is returned to the client by a primary replica.
Periodically primary replica sends some signal to backup replicas to let them know that it is working perfectly fine.
In case of failure of a primary replica, a backup replica becomes the primary replica.
Advantages:
The resource consumption is less as backup servers only come into play when the primary server fails.
The time complexity of this is also less as there’s no need for updating in all the nodes replicas, unlike active replication.
Disadvantages:
If some failure occurs, the response time is delayed.
Distributed System
Picked
Computer Subject
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Data Structures | Binary Search Trees | Question 8

28 Jun, 2021
The preorder traversal sequence of a binary search tree is 30, 20, 10, 15, 25, 23, 39, 35, 42. Which one of the following is the postorder traversal sequence of the same tree?(A) 10, 20, 15, 23, 25, 35, 42, 39, 30(B) 15, 10, 25, 23, 20, 42, 35, 39, 30(C) 15, 20, 10, 23, 25, 42, 35, 39, 30(D) 15, 10, 23, 25, 20, 35, 42, 39, 30Answer: (D)Explanation: The following is the constructed tree
            30
         /      \
        20       39 
       /  \     /  \
     10    25  35  42  
      \   /
      15 23

Quiz of this Question
Binary Search Trees
Data Structures
Data Structures-Binary Search Trees
Data Structures
Data Structures
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Data Structures | Array | Question 2
Data Structures | Queue | Question 2
Amazon Interview Experience for SDE-II
Data Structures | Hash | Question 5
Data Structures | Linked List | Question 16
Data Structures | Linked List | Question 4
FIFO vs LIFO approach in Programming
Data Structures | Linked List | Question 15
Data Structures | Linked List | Question 11
Bit manipulation | Swap Endianness of a number
How can I add a Boolean field to MySQL?

You can use tinyint(1) or bool or boolean. All are synonym. If you use bool or boolean datatype, then it nternally change into tinyint(1).
In PHP, the value 0 represents false and 1 represents true. Any other number except 0 is also true.
Let us check the internal representation of bool or boolean using a table. The query to create a table is as follows.
mysql> create table AddBoolDemo
-> (
-> isToggle bool
-> );
Query OK, 0 rows affected (1.24 sec)
To check the DDL of the table, the following is the query.
SHOW CREATE TABLE yourTableName;
Let us check the representation of bool which internally converts into tinyint(1). Now check for the table AddBoolDemo.
mysql> show create table AddBoolDemo\G
The following is the output.
*************************** 1. row ***************************
Table: AddBoolDemo
Create Table: CREATE TABLE `addbooldemo` (
`isToggle` tinyint(1) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
1 row in set (0.00 sec)
Add true or false or 1 or 0 literals in the table using insert command.
mysql> insert into AddBoolDemo values(true);
Query OK, 1 row affected (0.19 sec)

mysql> insert into AddBoolDemo values(false);
Query OK, 1 row affected (0.19 sec)

mysql> insert into AddBoolDemo values(1);
Query OK, 1 row affected (0.10 sec)

mysql> insert into AddBoolDemo values(0);
Query OK, 1 row affected (0.18 sec)
Display all records from the table using select statement. The query is as follows.
mysql> select *from AddBoolDemo;
The following is the output.
+----------+
| isToggle |
+----------+
| 1        |
| 0        |
| 1        |
| 0        |
+----------+
4 rows in set (0.00 sec)
How to Install Python Tensorflow in Windows?

06 Oct, 2021
Tensorflow is a free and open-source software library used to do computational mathematics to build machine learning models more profoundly deep learning models.It is a product of Google built by Google’s brain team, hence it provides a vast range of operations performance with ease that is compatible with human behavior for ML and DL. It can run on multiple CPUs and GPUs.
Computational Framework – It is a platform that provides huge computational framework at one place. In this, computation is approached as a dataflow graph.
Mobile Deployment – It is an easy way to build projects with mobile deployment
High Performance – Due to its ease and varying toolkits, it gives high-performance user experience.
Tensorflow can be downloaded from its official Website tensorflow.org and can be installed with the help of following steps: Step 1: Click on Install on top navigation bar of Tensorflow website. Step 2: Before proceeding we need to get python environment. Choose pip in the left side and go to python section and install python environment to work on it. Step 3: Python environment can be downloaded from python.org. To install python on windows refer to: How to install Python on Windows? Step 4: To install Tensorflow, we need pip for python. Usually, pip comes already installed if the python version is 3 or above. To know more about pip installation please refer: How to install pip in Windows?
For all OS users check the pip section of TensorFlow as shown in the following screenshot:Tensorflow can also be downloaded for installation on different OS: Step 5: Creating a Tensorflow virtual environment
This can be done with the use of following command:
pip install --user virtualenv
 Step 6: After setting up the virtual environment, use the following command to install Tensorflow pip package:
pip install --upgrade tensorflow 
Once installed you can import TensorFlow in your python programming environment as you choose(here python IDE as stated in step 5).
how-to-install
Tensorflow
How To
Installation Guide
Python
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Equivalent of SQL Server IDENTITY Column in MySQL?

Equivalent of Microsoft SQL Server IDENTITY column in MySQL is AUTO_INCREMENT. The IDENTITY in SQL Server acts like AUTO_INCREMENT in MySQL.
The syntax is as follows −
CREATE TABLE yourTableName
(
   yourColumnName1 dataType NOT NULL AUTO_INCREMENT,
   yourColumnName2 dataType,
   .
   .
   .
   N,
   PRIMARY KEY(yourColumnName1)
);
In MySQL, you need to use primary key if your column is auto_increment otherwise MySQL will give an error. Look at the error −
mysql> create table EquivalentOfIdentityInMySQL
   -> (
   -> ProductId int NOT NULL AUTO_INCREMENT,
   -> ProductName varchar(30)
   -> );
ERROR 1075 (42000) − Incorrect table definition; there can be only one auto column and it
must be defined as a key
To remove the above error, you need to make ProductId as primary key. The declaration of MySQL AUTO_INCREMENT is as follows with ProductId set as primary key −
mysql> create table EquivalentOfIdentityInMySQL
   -> (
   -> ProductId int NOT NULL AUTO_INCREMENT,
   -> ProductName varchar(30)
   -> ,
   -> PRIMARY KEY(ProductId)
   -> );
Query OK, 0 rows affected (0.59 sec)
If you won’t pass any value for the column ProductId, MySQL begins auto_increment from 1 and the next number increments by 1 by default. 
To check the ProductId column, let us insert some records in the table using insert command. The query is as follows −
mysql> insert into EquivalentOfIdentityInMySQL(ProductName) values('Product-1');
Query OK, 1 row affected (0.14 sec)

mysql> insert into EquivalentOfIdentityInMySQL(ProductName) values('Product-2');
Query OK, 1 row affected (0.14 sec)

mysql> insert into EquivalentOfIdentityInMySQL(ProductName) values('Product-34');
Query OK, 1 row affected (0.10 sec)
Display all records from the table using select statement. The query is as follows −
mysql> select *from EquivalentOfIdentityInMySQL;
The following is the output −
+-----------+-------------+
| ProductId | ProductName |
+-----------+-------------+
|         1 | Product-1   |
|         2 | Product-2   |
|         3 | Product-34  |
+-----------+-------------+
3 rows in set (0.00 sec)
Look at the column ProductId, we did not pass any value for this column but we are getting the number beginning from 1 and next number increments by 1.
Find Circles and Ellipses in an Image using OpenCV | Python

11 Apr, 2022
To identify circles, ellipses, or in general, any shape in which the pixels are connected we use the SimpleBlobDetector() function of OpenCV. In non-technical terms, a blob is understood as a thick liquid drop. Here, we are going to call all shapes a blob. Our task is to detect and recognize whether the blob is a circle or not.
OpenCV provides a convenient way to detect blobs and filter them based on different characteristics. There are various different parameters that control the identification process and the results. The important parameters used for this project are: 
Filter by Area – This is to avoid any identification of any small dots present in the image that can be wrongly detected as a circle. 
Filter by Circularity – This helps us to identify, shapes that are more similar to a circle. 
Circularity = . 
A true circle has a circularity of 1, a square has a circularity near 78%. 
Filter by Convexity – Concavity in general, destroys the circularity. More is the convexity, the closer it is to a close circle. 
Filter by Inertia – Objects similar to a circle has larger inertial.E.g. for a circle, this value is 1, for an ellipse it is between 0 and 1, and for a line it is 0. To filter by inertia ratio, set filterByInertia = 1, and set, 0 <= minInertiaRatio <= 1 and maxInertiaRatio (<=1 ) appropriately. 
Below is the code for identifying Circles:  
Python3
import cv2import numpy as np # Load imageimage = cv2.imread('C://gfg//images//blobs.jpg', 0) # Set our filtering parameters# Initialize parameter setting using cv2.SimpleBlobDetectorparams = cv2.SimpleBlobDetector_Params() # Set Area filtering parametersparams.filterByArea = Trueparams.minArea = 100 # Set Circularity filtering parametersparams.filterByCircularity = Trueparams.minCircularity = 0.9 # Set Convexity filtering parametersparams.filterByConvexity = Trueparams.minConvexity = 0.2     # Set inertia filtering parametersparams.filterByInertia = Trueparams.minInertiaRatio = 0.01 # Create a detector with the parametersdetector = cv2.SimpleBlobDetector_create(params)     # Detect blobskeypoints = detector.detect(image) # Draw blobs on our image as red circlesblank = np.zeros((1, 1))blobs = cv2.drawKeypoints(image, keypoints, blank, (0, 0, 255),                          cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS) number_of_blobs = len(keypoints)text = "Number of Circular Blobs: " + str(len(keypoints))cv2.putText(blobs, text, (20, 550),            cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 100, 255), 2) # Show blobscv2.imshow("Filtering Circular Blobs Only", blobs)cv2.waitKey(0)cv2.destroyAllWindows()
Output: 
 
gabaa406
arorakashish0911
Image-Processing
OpenCV
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Radix Sort

Radix sort is a non-comparative sorting algorithm. This sorting algorithm works on the integer keys by grouping digits which share the same position and value. The radix is the base of a number system. As we know that in the decimal system the radix or base is 10. So for sorting some decimal numbers, we need 10 positional boxes to store numbers.
Time Complexity: O(nk)
Space Complexity: O(n+k)
Input:
The unsorted list: 802 630 20 745 52 300 612 932 78 187
Output:
Data before Sorting: 802 630 20 745 52 300 612 932 78 187
Data after Sorting: 20 52 78 187 300 612 630 745 802 932
radixSort(array, size, maxDigit)
Input − An array of data, and the total number in the array, digit count of max number
Output − Sorted array.
Begin
   define 10 lists as pocket
   for i := 0 to max -1 do
      m = 10^i+1
      p := 10^i
      for j := 0 to n-1 do
         temp := array[j] mod m
         index := temp / p
         pocket[index].append(array[j])
      done

      count := 0
      for j := 0 to radix do
         while pocket[j] is not empty
            array[count] := get first node of pocket[j] and delete it
            count := count +1
      done
   done
End
#include<iostream>
#include<list>
#include<cmath>
using namespace std;

void display(int *array, int size) {
   for(int i = 0; i<size; i++)
      cout << array[i] << " ";
   cout << endl;
}

void radixSort(int *arr, int n, int max) {
   int i, j, m, p = 1, index, temp, count = 0;
   list<int> pocket[10]; //radix of decimal number is 10

   for(i = 0; i< max; i++) {
      m = pow(10, i+1);
      p = pow(10, i);

      for(j = 0; j<n; j++) {
         temp = arr[j]%m;
         index = temp/p;   //find index for pocket array
         pocket[index].push_back(arr[j]);
      }

      count = 0;
      for(j = 0; j<10; j++) {
         //delete from linked lists and store to array
         while(!pocket[j].empty()) {
            arr[count] = *(pocket[j].begin());
            pocket[j].erase(pocket[j].begin());
            count++;
         }
      }
   }
}

int main() {
   int n, max;
   cout << "Enter the number of elements: ";
   cin >> n;
   cout << "Enter the maximum digit of elements: ";
   cin >> max;
   int arr[n]; //create an array with given number of elements
   cout << "Enter elements:" << endl;

   for(int i = 0; i<n; i++) {
      cin >> arr[i];
   }

   cout << "Data before Sorting: ";
   display(arr, n);
   radixSort(arr, n, max);
   cout << "Data after Sorting: ";
   display(arr, n);
}
Enter the number of elements: 10
Enter the maximum digit of elements: 3
Enter elements:
802 630 20 745 52 300 612 932 78 187
Data before Sorting: 802 630 20 745 52 300 612 932 78 187
Data after Sorting: 20 52 78 187 300 612 630 745 802 932
Java Examples - Display files in a directory

How to display all the files in a directory ?
Following example shows how to display all the files contained in a directory using list method of File class.
import java.io.*;

public class Main {
   public static void main(String[] args) {
      File dir = new File("C:");
      String[] children = dir.list();
      
      if (children == null) {
         System.out.println( "Either dir does not exist or is not a directory");
      } else { 
         for (int i = 0; i< children.length; i++) {
            String filename = children[i];
            System.out.println(filename);
         }
      }
   }
}
The above code sample will produce the following result.
build
build.xml
destnfile
detnfile
filename
manifest.mf
nbproject
outfilename
src
srcfile
test

The following is an another example to display all the files in a directory.
import java.io.File;

public class ReadFiles { 
   public static File folder = new File("C:\\Apache24\\htdocs");
   static String temp = "";
   
   public static void main(String[] args) {
      System.out.println("Reading files under the folder "+ folder.getAbsolutePath());
      listFilesForFolder(folder);
   } 
   public static void listFilesForFolder(final File folder) {
      for (final File fileEntry : folder.listFiles()) {
         if (fileEntry.isDirectory()) {
            listFilesForFolder(fileEntry);
         } else {
            if (fileEntry.isFile()) {
               temp = fileEntry.getName();
               if ((temp.substring(temp.lastIndexOf('.') 
                  + 1, temp.length()).toLowerCase()).equals("txt"))System.out.println(
                  "File = " + folder.getAbsolutePath()+ "\\" + fileEntry.getName());
            } 
         } 
      } 
   }
}
The above code sample will produce the following result.
Reading files under the folder C:\Apache24\htdocs
File= C:\Apache24\htdocs\android\bkp\end.txt
File= C:\Apache24\htdocs\android\end.txt
File= C:\Apache24\htdocs\cpp_standard_library\images\code.txt
File= C:\Apache24\htdocs\java\Java - Data Structures.txt
File= C:\Apache24\htdocs\java\Java - Inheritance.txt
PyQt5 QSpinBox – Making it disabled according to user

17 May, 2020
In this article we will see how we can make spin box disabled according to the user, disabled spin box box is basically spin box which can’t be edited i.e which get disabled. Below is the representation of how disabled spin box looks like.
In order to do so we use setDisabled method.
Syntax : spin_box.setDisabled(bool)
Argument : It takes bool as argument
Return : It returns None
Implementation steps :1. Create a spin box2. Create a push button3. Add action to the push button4. Inside the action make the spin box disabled
Below is the implementation
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys  class Window(QMainWindow):      def __init__(self):        super().__init__()          # setting title        self.setWindowTitle("Python ")          # setting geometry        self.setGeometry(100, 100, 600, 400)          # calling method        self.UiComponents()          # showing all the widgets        self.show()      # method for widgets    def UiComponents(self):          # creating spin box        self.spin = QSpinBox(self)          # setting geometry to spin box        self.spin.setGeometry(100, 100, 250, 40)          # setting prefix to spin        self.spin.setPrefix("Prefix ")          # setting suffix to spin        self.spin.setSuffix(" Suffix")          # setting range to spin        self.spin.setRange(0, 99999)          # creating push button        button = QPushButton("Press", self)          # setting button geometry        button.setGeometry(100, 160, 100, 40)          # adding action to the push button        button.clicked.connect(self.push_method)      # method called by push button    def push_method(self):          # making spin box disabled        self.spin.setDisabled(True)  # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output :
Python PyQt-SpinBox
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How can I show and hide an HTML element using jQuery?

To hide and show an HTML element using jQuery, use the hide and show() methods. Here, the <p> element is hidden and shown on button click,
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(){
    $("#visible").click(function(){
        $("p").show();
    });
     $("#hidden").click(function(){
        $("p").hide();
    });
});
</script>
</head>
<body>

<p>This text  will show on clicking "Show element" button, and hide on clicking "Hide element" button.</p>

<button id="hidden">Hide element</button>
<button id="visible">Show element</button>

</body>
</html>
How to create Label widget in PyQt5 ? - GeeksforGeeks

26 Mar, 2020
While designing any GUI (Graphical User Interface) there is a need to display plain text on screen, in order to do so Label widget is used in PyQt5.
A label is a graphical control element which displays text on a form. It is usually a static control; having no interactivity. A label is generally used to identify a nearby text box or other widget. Some labels can respond to events such as mouse clicks, allowing the text of the label to be copied, but this is not standard user-interface practice.
To use Labels in PyQt5 we have to import QLabel from PyQt5.QtWidgets , below is the syntax to do so.
from PyQt5.QtWidgets import QLabel
After importing Qlabel, we can create Labels in our PyQt5 application.
Syntax :
self.label_name = QLabel(Info, self)
Here Info can be any text of string type.
Below is the Python implementation –
# importing the required libraries  from PyQt5.QtWidgets import QLabelfrom PyQt5.QtWidgets import QMainWindowfrom PyQt5.QtWidgets import QApplicationimport sys  class Window(QMainWindow):    def __init__(self):        super().__init__()          # set the title        self.setWindowTitle("Label")          # setting  the geometry of window        self.setGeometry(0, 0, 400, 300)          # creating a label widget        # by default label will display at top left corner        self.label = QLabel('This is label', self)          # show all the widgets        self.show()  # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output :
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
C++ | Inheritance | Question 10 - GeeksforGeeks

28 Jun, 2021
Output of following program?
#include <iostream>#include<string>using namespace std;  class Base{public:    virtual string print() const    {        return "This is Base class";    }};  class Derived : public Base{public:    virtual string print() const    {        return "This is Derived class";    }};  void describe(Base p){    cout << p.print() << endl;}  int main(){    Base b;    Derived d;    describe(b);    describe(d);    return 0;}
(A)
This is Derived class
This is Base class
(B)
This is Base class
This is Derived class
(C)
This is Base class
This is Base class
(D) Compiler ErrorAnswer: (C)Explanation: Note that an object of Derived is passed in describe(d), but print of Base is called. The describe function accepts a parameter of Base type.
This is a typical example of object slicing, when we assign an object of derived class to an object of base type, the derived class object is sliced off and all the data members inherited from base class are copied. Object slicing should be ovoided as there may be surprising results like above. As a side note, object slicing is not possible in Java. In Java, every non-primitive variable is actually a reference.Quiz of this Question
C++-Inheritance
Inheritance
C Language
C++ Quiz
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
fork() in C
Command line arguments in C/C++
Function Pointer in C
Substring in C++
Different methods to reverse a string in C/C++
C++ | Exception Handling | Question 3
C++ | new and delete | Question 4
C++ | Operator Overloading | Question 10
C++ | Virtual Functions | Question 2
C++ | Virtual Functions | Question 1
Bidirectional Iterators in C++

Here we will see the concept of Bidirectional iterators in C++.
The bidirectional iterators support all of the features of forward iterators, and also prefix and postfix decrement operators.
This type of iterator can access elements in both directions, like towards the end and towards the beginning.
The random access iterator is also a type of bidirectional iterator.
Bidirectional iterators have features of forward iterator, but only difference is this iterator can also be decremented.
The Bidirectional iterators has some properties. These are like below.
#include <iostream>
#include<iterator>
#include<vector>
using namespace std;
int main() {
   vector<int> vec{10, 20, 30, 40, 50, 60, 70, 80, 90, 100};
   vector<int> ::iterator it;
   vector<int> :: reverse_iterator rev_it;
   for(it = vec.begin(); it != vec.end(); it++)
      cout<<*it<<" ";
      cout<< endl;
   for(rev_it = vec.rbegin(); rev_it!= vec.rend(); rev_it++)
      cout<<*rev_it<<" ";
}
10 20 30 40 50 60 70 80 90 100
100 90 80 70 60 50 40 30 20 10
How to check missing values in R dataframe ? - GeeksforGeeks

21 Apr, 2021
In this article, we are going to see how to find out the missing values in the data frame in R Programming Language.
Step 1: Create DataFrame.
Let us first create a data frame with some missing values and then demonstrate with an example how to find the missing values.
R
data <- data.frame(x1 = c(NA, 5, 6, 8, 9),                           x2 = c(2, 4, NA, NA, 1),                         x3 = c(3,6,7,0,3),                         x4 = c("Hello", "value",                               NA, "geeksforgeeks", NA))                                                                              display(data)
Output:
We have created a data frame with some missing values (NA).
Step 2: Now to check the missing values we are using is.na() function in R and print out the number of missing items in the data frame as shown below.
Syntax: is.na()
Parameter: x: data frame
Example 1:
In this example, we have first created data with some missing values and then found the missing value in particular columns x1,×2, x3, and x4 respectively using the above function.
R
data <- data.frame(x1 = c(NA, 5, 6, 8, 9),                               x2 = c(2, 4, NA, NA, 1),                         x3 = c(3,6,7,0,3),                         x4 = c("Hello", "value",                               NA, "geeksforgeeks", NA))                                                                              data                      # to find out the missing valuewhich(is.na(data$x1))which(is.na(data$x2)) which(is.na(data$x3)) which(is.na(data$x4))
Output:
Print the variables which have missing values and the number of missing values.
Example 2: 
Let’s find the number of missing values using a different approach, here in this example, we have created data with missing values and then find the number of missing values in the data.
R
Name <- c("John", "Sunny", NA)Age <- c(31, 18, NA)number<- c("0", "1", "2")  data <- data.frame(Name, Sex, number)  display(data)
Output:
We have a data frame, and we have to find the number of missing values in this data frame.
R
Name <- c("John", "Sunny", NA)Age <- c(31, 18, NA)number<- c("0", "1", "2")  data <- data.frame(Name, Sex, number)sum(is.na(data))
Output:
Picked
R DataFrame-Programs
R-DataFrame
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Filter data by multiple conditions in R using Dplyr
Loops in R (for, while, repeat)
Change Color of Bars in Barchart using ggplot2 in R
How to change Row Names of DataFrame in R ?
How to Change Axis Scales in R Plots?
How to change Row Names of DataFrame in R ?
Remove rows with NA in one column of R DataFrame
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
How to filter R dataframe by multiple conditions?
Find missing element in a sorted array of consecutive numbers in Python

Suppose we have an array A of n unique numbers, these n elements are present in the array in ascending order, but there is one missing element. We have to find the missing element.
So, if the input is like A = [1, 2, 3, 4, 5, 6, 7, 9], then the output will be 8.
To solve this, we will follow these steps −
n := size of A
n := size of A
left := 0
left := 0
right := n - 1
right := n - 1
mid := 0
mid := 0
while right > left , domid := left +(right - left) / 2if A[mid] - mid is same as A[0], thenif A[mid + 1] - A[mid] > 1, thenreturn A[mid] + 1otherwise,left := mid + 1otherwise,if A[mid] - A[mid - 1] > 1, thenreturn A[mid] - 1otherwise,right := mid - 1
while right > left , do
mid := left +(right - left) / 2
mid := left +(right - left) / 2
if A[mid] - mid is same as A[0], thenif A[mid + 1] - A[mid] > 1, thenreturn A[mid] + 1otherwise,left := mid + 1
if A[mid] - mid is same as A[0], then
if A[mid + 1] - A[mid] > 1, thenreturn A[mid] + 1
if A[mid + 1] - A[mid] > 1, then
return A[mid] + 1
return A[mid] + 1
otherwise,left := mid + 1
otherwise,
left := mid + 1
left := mid + 1
otherwise,if A[mid] - A[mid - 1] > 1, thenreturn A[mid] - 1otherwise,right := mid - 1
otherwise,
if A[mid] - A[mid - 1] > 1, thenreturn A[mid] - 1
if A[mid] - A[mid - 1] > 1, then
return A[mid] - 1
return A[mid] - 1
otherwise,right := mid - 1
otherwise,
right := mid - 1
right := mid - 1
return -1
return -1
Let us see the following implementation to get better understanding −
 Live Demo
def search_missing_item(A):
   n = len(A)
   left, right = 0, n - 1
   mid = 0
   while (right > left):
      mid = left + (right - left) // 2
   if (A[mid] - mid == A[0]):
      if (A[mid + 1] - A[mid] > 1):
         return A[mid] + 1
      else:
         left = mid + 1
      else:
         if (A[mid] - A[mid - 1] > 1):
            return A[mid] - 1
         else:
            right = mid - 1
   return -1

A = [1, 2, 3, 4, 5, 6, 7, 9]
print(search_missing_item(A))
[1, 2, 3, 4, 5, 6, 7, 9]
8
How to merge multiple Python dictionaries?

First, put all dictionary objects in a list object.
Initialize a dictionary object to empty directory. This is intended to contain merged directory
Update it with each directory item from the list
>>> d=[{'a':1, 'b':2, 'c':3}, {'a':1, 'd':2, 'c':'foo'}, {'e':57,'c':3}]
>>> d
[{'a': 1, 'b': 2, 'c': 3}, {'a': 1, 'd': 2, 'c': 'foo'}, {'e': 57, 'c': 3}]
>>> merged={}
>>> for x in d:
    merged.update(x)

>>> merged
{'a': 1, 'b': 2, 'c': 3, 'd': 2, 'e': 57}
How to find the MAC address of the system using PowerShell?

There are several ways to find the MAC address (Physical Address) of the system using PowerShell.
Using this command, we can retrieve the MAC address of the network adapter.
We need to use Ipconfig /all to retrieve the mac address of all the adapters.
Ipconfig /all | Select-String -Pattern "Description","Physical"
Maximum triplet sum in array in C++

In this problem, we are given an array. Our task is to create a program that will find the maximum triplet sum in the array i.e. find the set of three elements whose sum is maximum.
Let’s take an example to understand the problem,
Input − array = {4, 6, 1, 2}
Output − 12
Explanation −
all triplets are :
(4, 6, 1) = 4+6+1 = 11
(4, 6, 2) = 4+6+1 = 12
(4, 1, 2) = 4+6+1 = 7
(6, 1, 2) = 4+6+1 = 9
The maximum triplet sum is 12
One simple approach to solve the problem is what we have depicted in the example, which is taking sum values for all triplet pairs and then finding the maximum of them. But this approach is not effective as with the length of all the number of triplets will become large.
In this method, we will run three loops that will find all possible sum triplets and if this triplet’s sum is larger than maxsum then we will initialize this triplet sum as maxsum.
Program to illustrate our solution,
 Live Demo
#include <iostream>
using namespace std;
int maxSum(int arr[], int n){
   int maxSum = 0;
   int i, j, k;
   for (i = 0; i < n; i++)
      for (j = i + 1; j < n; j++)
         for (k = j + 1; k < n; k++)
            if (maxSum < arr[i] + arr[j] + arr[k]) maxSum = arr[i] + arr[j] + arr[k];
   return maxSum;
}
int main(){
   int arr[] = { 3, 5, 7 ,1, 9, 0 };
   int n = sizeof(arr) / sizeof(arr[0]);
   cout<<"The maximum triplet sum of the array is "<<maxSum(arr, n);
   return 0;
}
The maximum triplet sum of the array is 21
An effective approach will be sorting the array and then finding sum of the last three elements of the array which will be the maximum sum of triplets.
Program to illustrate the solution,
 Live Demo
#include <bits/stdc++.h>
using namespace std;
int maxSum(int arr[], int n) {
   sort(arr, arr + n);
   return arr[n - 1] + arr[n - 2] + arr[n - 3];
}
int main() {
   int arr[] = { 3, 5, 9, 1, 2, 8, 7 };
   int n = sizeof(arr) / sizeof(arr[0]);
   cout<<"The maximum triplet sum of the array is "<<maxSum(arr, n);
   return 0;
}
The maximum triplet sum of the array is 24
How to add a set of frames in HTML?

Use the <frameset> tag to add a set of frames. The HTML <frameset> tag is used to divide the window into frames. 
Note − This tag is not supported in HTML5. Do not use.
The following are the attributes −
You can try to run the following code to add a set of frames using the <frameset> tag −
<!DOCTYPE html>
<html>
   <head>
      <title>HTML frameset Tag</title>
   </head>
   <frameset cols = "300, *">
      <frame src = "/html/menu.htm" name = "menu_page" />
      <frame src = "/html/main.htm" name = "main_page" />

      <noframes>
         <body>
            Your browser does not support frames.
         </body>
      </noframes>

   </frameset>
</html>
Java Examples - Array sort and insert

How to sort an array and insert an element inside it?
Following example shows how to use sort () method and user defined method insertElement ()to accomplish the task.
import java.util.Arrays;

public class MainClass {
   public static void main(String args[]) throws Exception {
      int array[] = { 2, 5, -2, 6, -3, 8, 0, -7, -9, 4 };
      Arrays.sort(array);
      printArray("Sorted array", array);
      
      int index = Arrays.binarySearch(array, 1);
      System.out.println("Didn't find 1 @ " + index);
      
      int newIndex = -index - 1;
      array = insertElement(array, 1, newIndex);
      printArray("With 1 added", array);
   }
   private static void printArray(String message, int array[]) {
      System.out.println(message + ": [length: " + array.length + "]");
      for (int i = 0; i < array.length; i++) {
         if (i != 0){
            System.out.print(", ");
         }
         System.out.print(array[i]);         
      }
      System.out.println();
   }
   private static int[] insertElement(int original[], int element, int index) {
      int length = original.length;
      int destination[] = new int[length + 1];
      System.arraycopy(original, 0, destination, 0, index);
      destination[index] = element;
      System.arraycopy(original, index, destination, index + 1, length - index);
      return destination;
   }
}
The above code sample will produce the following result.
Sorted array: [length: 10]
-9, -7, -3, -2, 0, 2, 4, 5, 6, 8
Didn't find 1 @ -6
With 1 added: [length: 11]
-9, -7, -3, -2, 0, 1, 2, 4, 5, 6, 8

 Print
 Add Notes
 Bookmark this page
Web Scraping  HTML Tables using Python  | Towards Data Science

Data has become the most valuable currency and precious commodity these days and the way you use it will differentiate you from ordinary people. You need to be smart enough to earn this data which is available everywhere around you and in this article you will be able to learn an easy way to get the tabular data from any website using a single line in python.
With data collection ‘the sooner the better’ is always the best answer — Marrisa Mayer (former CEO of Yahoo!)
There is a lot of data that is getting generated publicly every day, one of the most common types of data is HTML tables, there are are many ways to get this data into your notebook, like using urllib and BeautifulSoup but it's a lengthy and time-consuming process you can do the same task using pandas library in a single line.
read_html() method in the Pandas library is a web scraping tool that extracts all the tables on a website by just giving the required URL as a parameter to the method.
Prerequisites: Importing pandas Library
import pandas as pd
By just giving a URL as a parameter, you can get all the tables on that particular website.
pandas.read_html(URL)
Example: Reading the data from Wikipedia
#Data about Cricket World cupURL = "https://en.wikipedia.org/wiki/Cricket_World_Cup"tables = pd.read_html(URL)print("There are : ",len(tables)," tables")print("Take look at table 0")print(tables[0])
If there are many tables on a website it will be a tedious task for you to find the table you are targeting, you can’t just search for a table manually. For this, we need to add an extra parameter(match) to be included in the read_html() method to search for a required table automatically.
match attribute can take a string or a compiled regular expression as it's value
pandas.read_html(URL,match = ".+")
Example: To scrape a particular table using match as a parameter
URL = "https://en.wikipedia.org/wiki/Cricket_World_Cup"tables = pd.read_html(URL,match="Performance details")print("There are : ",len(tables)," tables")print("Take look at table 0")tables[0]
Note: The search space is reduced, this might help you to search for your required table quickly
Useful attributes  1. header    : The row to use to make as the column header.2. index_col : The column to use to create the index3. skiprows  : Number of rows to skip after parsing column integer
pandas.read_html(URL,attrs = {'html_tag' : 'value'})
we can directly target an HTML tag corresponding to the required table by inspecting the table.
how can I inspect a table?
left-click on the table and select Inspect option
After inspecting find the related tag exclusive to that table, here we can see that class:'wikitable' is a tag that identifies this table.
#By using this line of code we can hit the target table directlypandas.read_html(URL,attrs = {'class' : 'wikitable'})
After reading this article you will be able to scrape the tabular data from any website within no time.
Online PHP Formatter

Editable PHP Code
1234567891011121314151617181920212223242526272829<htm><body><?phpclass  Books{/* Member variables */var $price;var $title;/* Member functions */function setPrice($par){$this->price = $par;}function getPrice(){echo $this->price ."";}function setTitle($par){$this->title = $par;}function getTitle(){echo $this->title ." ";}}?></body></html>X
Privacy Policy
Cookies Policy
Terms of Use
Char.TryParse() Method in C#

The Char.TryParse() method in C# is used to convert the value of the specified string to its equivalent Unicode character.
public static bool TryParse (string str, out char res);
Let us now see an example to implement the Char.TryParse () method −
using System;
public class Demo {
   public static void Main(){
      bool res;
      Char ch;
      res = Char.TryParse("10", out ch);
      Console.WriteLine(res);
      Console.WriteLine(ch.ToString());
   }
}
This will produce the following output −
False
Let us now see another example −
using System;
public class Demo {
   public static void Main(){
      bool res;
      Char ch;
      res = Char.TryParse("P", out ch);
      Console.WriteLine(res);
      Console.WriteLine(ch.ToString());
   }
}
This will produce the following output −
True
P
Implementation of Queue in JavaScript

Following is the code to implement queue in JavaScript.
 Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result {
      font-size: 18px;
      font-weight: 500;
      color: blueviolet;
   }
   button {
      padding: 6px;
      margin: 4px;
   }
</style>
</head>
<body>
<h1>Implementation of queue in JavaScript.</h1>
<div class="result"></div>
<br />
<input type="text" class="enqueueVal" /><button class="enqueueBtn">
Enqueue
</button>
<button class="dequeueBtn">Dequeue</button>
<button class="Btn">Display</button>
<h3>Click on the above buttons to perform queue operations</h3>
<script>
   let resEle = document.querySelector(".result");
   let BtnEle = document.querySelector(".Btn");
   let enqueueBtnEle = document.querySelector(".enqueueBtn");
   let dequeueBtnEle = document.querySelector(".dequeueBtn");
   class Queue {
      constructor() {
         this.items = [];
         this.length = 0;
      }
   }
   Queue.prototype.enqueue = function (ele) {
      this.items[this.length] = ele;
      this.length += 1;
   };
   Queue.prototype.dequeue = function () {
      debugger;
      if (this.length === 0) {
         return "Underflow: no more elements to remove";
      }
      tempNum = this.items[0];
      this.length -= 1;
      return tempNum;
   };
   Queue.prototype.display = function () {
      debugger;
      if (this.length == 0) {
         return "Stack is empty";
      }
      for (let i = 0; i < this.length; i++) {
         resEle.innerHTML += this.items[i] + " , ";
      }
   };
   let queue1 = new Queue();
   BtnEle.addEventListener("click", () => {
      resEle.innerHTML = "";
      queue1.display();
   });
   enqueueBtnEle.addEventListener("click", () => {
      let ele = document.querySelector(".enqueueVal").value;
      resEle.innerHTML = ele + " is added to the back of the queue";
      queue1.enqueue(ele);
   });
   dequeueBtnEle.addEventListener("click", () => {
      resEle.innerHTML =
      queue1.dequeue() + " is removed from the front of queue";
   });
</script>
</body>
</html>
On entering some value and clicking on ‘Enqueue’ button −
On clicking the ‘Dequeue’ button −
On clicking the ‘Display’ button when the queue is not empty −
Connect to MySQL database from command line

Let us understand how MySQL can be connected to the database using the command-line. This is done for clients like mysql or mysqldump.
The below command invokes mysql without specifying any explicit connection parameters −
mysql
Since there are no parameter options, the default values will be applied −
The default host name is localhost.
The default host name is localhost.
The default user name is ODBC on Windows.
The default user name is ODBC on Windows.
No password is sent because neither --password nor -p has been mentioned.
No password is sent because neither --password nor -p has been mentioned.
For mysql, the first non-option argument is considered the name of the default database. Since there is no such argument, mysql selects no default database.
To specify the host name, user name and password specifically, provide appropriate options on the command line. To select a default database, add a database-name argument. Let us see this with the command −
mysql --host=localhost --user=myname --password=password mydb
mysql -h localhost -u myname -ppassword mydb
Client programs determine the type of connection that needs to be made −
If the host is not specified or it is a localhost, a connection to the local host occurs
If the host is not specified or it is a localhost, a connection to the local host occurs
Else, the connection will use TCP/IP.
Else, the connection will use TCP/IP.
To ensure that the client makes a TCP/IP connection to the local server, ‘—host’ or ‘-h’ needs to be specified, with a host name value of 127.0.0.1 (instead of localhost). Instead of this, the IP address or name of the local server can also be mentioned. The transport protocol can be explicitly mentioned using the --protocol=TCP option. Let us see with the example −
mysql --host=127.0.0.1
mysql --protocol=TCP
On Windows, MySQL client can be forced to use a named-pipe connection. This can be done by specifying the --pipe or --protocol=PIPE option. Otherwise, . (period) can also be mentioned as the host name.
Connections to remote servers will use TCP/IP. The command would connect to the server running on remote.example.com using the default port number (3306). Let us see it in action −
mysql --host=remote.example.com
To specify a port number explicitly, the --port or -P option can be used. Lets see how it can be done −
mysql --host=remote.example.com --port=13306
To cause the port number to be used, force a TCP/IP connection. It can be done using any one of the way −
mysql --port=13306 --host=127.0.0.1
(or)
mysql --port=13306 --protocol=TCP
It is possible to specify connection parameters without entering them on the command line every time a client program is invoked.
Python program to check if a string contains all unique characters

In this article, we will learn about the solution and approach to solve the given problem statement.
Given a sring input, we need to find whether a string contains all unique characters or not.
We will create an array of boolean values, where the variable flag at the index i indicates that whether character i in the alphabet is contained in the string or not.
We will create an array of boolean values, where the variable flag at the index i indicates that whether character i in the alphabet is contained in the string or not.
The second time we encounter this character we can immediately return false as string characters is no longer unique.
The second time we encounter this character we can immediately return false as string characters is no longer unique.
We can also return false if the string length exceeds the value of number of unique characters presnt in the alphabet.
We can also return false if the string length exceeds the value of number of unique characters presnt in the alphabet.
Herw we have fixed the size of string to 256 maximum
Now let’s see the implementation −
 Live Demo
def isUniqueChars(st):
   if len(st) > 256:
      return False
   # Initialization
   char_set = [False] * 128
   # in char_set
   for i in range(0, len(st)):
      # ASCII value
      val = ord(st[i])
      if char_set[val]:
         return False
      char_set[val] = True
   return True
# main
st = "tutorialspoint"
print(isUniqueChars(st))
False
All the variables are declared in the global frame as shown in the figure given below −
In this article, we learned about the approach to check if a string contains all unique characters
Java Program to convert first character uppercase in a sentence

In order to convert first character as upper case in a sentence we have to first separate each word of sentence and then make first character of each word in upper case.After which we have to again join each word separated by space to make again sentence.
Now let take each task one by one.First in order to get each word of the sentence separately we would use Scanner class of Java and implement its hasnext method to check whether our sentence has any more word or not,in case word is present then we would get that word by using next method of same class.
After getting each word of the sentence we would now convert first character of each word in upper case by using toUpperCase method of Character class and join other characters of the word by using sub string method of string class and also append space at last of each word in order to make them again in a sentence.
 Live Demo
import java.util.Scanner;
public class UpperCaseOfSentence {
   public static void main(String[] args) {
      String upper_case_line = "";
      String str = "ram is a good boy.";
      Scanner lineScan = new Scanner(str);
      while(lineScan.hasNext()) {
         String word = lineScan.next();
         upper_case_line += Character.toUpperCase(word.charAt(0)) + word.substring(1) + " ";
      }
      System.out.println(upper_case_line);
   }
}
Ram Is A Good Boy.