code-rag-bench/online-tutorials huggingface dataset:
Difference Between Go-Back-N and Selective Repeat Protocol - GeeksforGeeks

29 Jul, 2020
Both Go-Back-N Protocol and Selective Repeat Protocol are the types of sliding window protocols.The main difference between these two protocols is that after finding the suspect or damage in sent frames go-back-n protocol re-transmits all the frames whereas selective repeat protocol re-transmits only that frame which is damaged.
Now, we shall see the difference between them:
N/(1+2*a)
N/(1+2*a)
ankitagarwal10
absh2702
Computer Networks
Difference Between
GATE CS
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
RSA Algorithm in Cryptography
TCP Server-Client implementation in C
Differences between TCP and UDP
Data encryption standard (DES) | Set 1
Types of Network Topology
Difference between BFS and DFS
Class method vs Static method in Python
Differences between TCP and UDP
Difference between var, let and const keywords in JavaScript
Differences between Black Box Testing vs White Box Testing
How to split a data frame in R into multiple parts randomly?

When a data frame is large, we can split it into multiple parts randomly. This might be required when we want to analyze the data partially. We can do this with the help of split function and sample function to select the values randomly.
Consider the trees data in base R −
> str(trees)
'data.frame': 31 obs. of 3 variables:
$ Girth : num 8.3 8.6 8.8 10.5 10.7 10.8 11 11 11.1 11.2 ...
$ Height: num 70 65 63 72 81 83 66 75 80 75 ...
$ Volume: num 10.3 10.3 10.2 16.4 18.8 19.7 15.6 18.2 22.6 19.9 ...
Splitting the trees data in three parts −
> split(trees, sample(rep(1:3,times=c(10,10,11))))
$`1`
 Girth Height Volume
 2  8.6 65 10.3
 3  8.8 63 10.2
10 11.2 75 19.9
12 11.4 76 21.0
13 11.4 76 21.4
16 12.9 74 22.2
21 14.0 78 34.5
22 14.2 80 31.7
25 16.3 77 42.6
26 17.3 81 55.4
$`2`
Girth Height Volume
 5 10.7 81 18.8
 6 10.8 83 19.7
 8 11.0 75 18.2
11 11.3 79 24.2
14 11.7 69 21.3
17 12.9 85 33.8
20 13.8 64 24.9
28 17.9 80 58.3
29 18.0 80 51.5
30 18.0 80 51.0
$`3`
Girth Height Volume
1 8.3 70 10.3
4 10.5 72 16.4
7 11.0 66 15.6
9 11.1 80 22.6
15 12.0 75 19.1
18 13.3 86 27.4
19 13.7 71 25.7
23 14.5 74 36.3
24 16.0 72 38.3
27 17.5 82 55.7
31 20.6 87 77.0
Consider the women data in base R −
> str(women)
'data.frame': 15 obs. of 2 variables:
$ height: num 58 59 60 61 62 63 64 65 66 67 ...
$ weight: num 115 117 120 123 126 129 132 135 139 142 ...
Splitting the women data in two parts −
> split(women, sample(rep(1:2,times=c(10,5))))
$`1`
height weight
 2 59 117
 4 61 123
 5 62 126
 6 63 129
 7 64 132
 9 66 139
11 68 146
12 69 150
14 71 159
15 72 164
$`2`
height weight
1 58 115
3 60 120
8 65 135
10 67 142
13 70 154
Uri.CheckHostName(String) Method in C#

The Uri.CheckHostName() method in C# is used to determine whether the specified hostname is a valid DNS name.
Following is the syntax −
public static UriHostNameType CheckHostName (string host_name);
Let us now see an example to implement the Uri.CheckHostName() method −
using System;
public class Demo {
   public static void Main(){
      string strURI = "http://localhost";
      Console.WriteLine("URI = "+strURI);
      UriHostNameType res = Uri.CheckHostName(strURI);
      Console.WriteLine("Host type = "+res);
   }
}
This will produce the following output −
URI = http://localhost
Host type = Unknown
Let us now see another example to implement the Uri.CheckHostName() method −
using System;
public class Demo {
   public static void Main(){
      string strURI = "www.tutorialspoint.com";
      Console.WriteLine("URI = "+strURI);
      UriHostNameType res = Uri.CheckHostName(strURI);
      Console.WriteLine("Host type = "+res);
   }
}
This will produce the following output −
URI = www.tutorialspoint.com
Host type = Dns
Difference between %d and %i format specifier in C language.

In C programming language, %d and %i are format specifiers as where %d specifies the type of variable as decimal and %i specifies the type as integer. In usage terms, there is no difference in printf() function output while printing a number using %d or %i but using scanf the difference occurs. scanf() function detects base using %i but assumes base 10 using %d.
 Live Demo
#include <stdio.h>
int main() {
   int num1 ,num2;
   int num3, num4;
   scanf("%i%d",&num1 , &num2);
   printf("%i\t%d\n",num1, num2);
   num3 = 010;
   num4 = 010;
   printf("%i\t%d",num3, num4);
   return 0;
}
32767-498932064
8 8
Here 010 is an octal number. scanf read the number as 10 using %d and read the number as 8 using %i. printf is good in both case to read the number as octal.
How to get the index and values of series in Pandas?

A pandas Series holds labeled data, by using these labels we can access series elements and we can do manipulations on our data. However, in some situations, we need to get all labels and values separately.
Labels can be called indexes and data present in a series called values. If you want to get labels and values individually. Then we can use the index and values attributes of the Series object.
Let’s take an example and see how these attributes will work.
import pandas as pd

# creating a series
s = pd.Series({97:'a', 98:'b', 99:'c', 100:'d', 101:'e', 102:'f'})
print(s)

# Getting values and index data
index = s.index
values = s.values

print('\n')
# displaying outputs
print(index)
print(values)
Created a pandas Series using a python dictionary with integer keys and string values pairs. And index and values are the series attributes that will return a ndarray of indexes and values.
The s.index and s.values will return an ndarray and those arrays are stored in index and values variables respectively. And at the end, we print the results by using the print function.
97    a
98    b
99    c
100   d
101   e
102   f
dtype: object


Int64Index([97, 98, 99, 100, 101, 102], dtype='int64')
array(['a', 'b', 'c', 'd', 'e', 'f'], dtype=object)
This block of output has a pandas Series which is created by using a python dictionary, the created series is having labeled data. and the second block the above output is representing values and index data in a ndarray format.
We can see data type each output in the above block, here values are object dtype and indexes are int64 dtype.
import pandas as pd

# creating a series
s = pd.Series([-2.3, np.nan, 9, 6.5, -5, -8, np.nan])
print(s)

# Getting values and index data
index = s.index
values = s.values

print('\n')
# displaying outputs
print(index)
print(values)
In the following example we have created a pandas Series using a python list and without index representation.
0   -2.3
1    NaN
2    9.0
3    6.5
4   -5.0
5   -8.0
6    NaN
dtype: float64


RangeIndex(start=0, stop=7, step=1)
[-2.3 nan 9. 6.5 -5. -8. nan]


The s.index attribute will return an ndarray normally, but in this case we haven’t specified any index values at the time of series creation. Due to this we can see the index values as RangeIndex format.
Python Pandas – Merge DataFrame with one-to-many relation

To merge Pandas DataFrame, use the merge() function. The one-to-many relation is implemented on both the DataFrames by setting under the “validate” parameter of the merge() function i.e. −
validate = “one-to-many”
or
validate = “1:m”
The one-to-many relation checks if merge keys are unique in left dataset.
At first, let us create our 1st DataFrame −
dataFrame1 = pd.DataFrame(
   {
      "Car": ['BMW', 'Lexus', 'Audi', 'Mustang', 'Bentley', 'Jaguar'],"Units": [100, 150, 110, 80, 110, 90]
   }
)
Now, let us create our 2nd DataFrame −
dataFrame2 = pd.DataFrame(
   {
      "Car": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],"Reg_Price": [7000, 1500, 5000, 8000, 9000, 6000]
   }
)
Following is the code −
import pandas as pd

# Create DataFrame1
dataFrame1 = pd.DataFrame(
   {
      "Car": ['BMW', 'Lexus', 'Audi', 'Mustang', 'Bentley', 'Jaguar'],"Units": [100, 150, 110, 80, 110, 90]
   }
)

print("DataFrame1 ...\n",dataFrame1)

# Create DataFrame2
dataFrame2 = pd.DataFrame(
   {
      "Car": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],"Reg_Price": [7000, 1500, 5000, 8000, 9000, 6000]

   }
)

print("\nDataFrame2 ...\n",dataFrame2)

# merge DataFrames with "one-to-many" in "validate" parameter
mergedRes = pd.merge(dataFrame1, dataFrame2, validate ="one_to_many")
print("\nMerged dataframe with one-to-many relation...\n", mergedRes)
This will produce the following output −
DataFrame1 ...
       Car   Units
0      BMW     100
1    Lexus     150
2     Audi     110
3  Mustang      80
4  Bentley     110
5   Jaguar      90
DataFrame2 ...
        Car   Reg_Price
0       BMW        7000
1     Lexus        1500
2     Tesla        5000
3   Mustang        8000
4  Mercedes        9000
5    Jaguar        6000
Merged dataframe with one-to-many realtion ...
       Car   Units   Reg_Price
0      BMW     100        7000
1    Lexus     150        1500
2  Mustang      80        8000
3   Jaguar      90        6000
C++ | Constructors | Question 1 - GeeksforGeeks

04 Jan, 2013
Which of the followings is/are automatically added to every class, if we do not write our own.(A) Copy Constructor(B) Assignment Operator(C) A constructor without any parameter(D) All of the aboveAnswer: (D)
 
Explanation: In C++, if we do not write our own, then compiler automatically creates a default constructor, a copy constructor and a assignment operator for every class.
C++ Quiz
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C++ | Constructors | Question 17
C++ | Exception Handling | Question 7
C++ | Exception Handling | Question 6
How to find Size of std::forward_list in C++ STL
C++ | Operator Overloading | Question 10
C++ | Operator Overloading | Question 7
C++ | Inheritance | Question 12
C++ | Constructors | Question 16
C++ | Exception Handling | Question 5
C++ | Misc C++ | Question 5
How to make a cylinder in React using reactthree-fiber

In this article, we will see how to create a basic cylinder-like shape in React using react-three-fiber. Three.js is a cross-browser JavaScript library and application programming interface used to create and display animated 3D computer graphics in a web browser using WebGL.
First download the react-three-fiber package −
npm i --save @react-three/fiber three
threejs and react-three/fiber will be used to add webGL renderer to the website. Three-fiber will be used to connect threejs and React.
Add the following lines of code in App.js −
import React, { useEffect, useRef } from "react";
import { Canvas, useFrame } from "@react-three/fiber";
import * as THREE from "three";
function Cylinder() {
   const myref = useRef();

   useFrame(() => (myref.current.rotation.x = myref.current.rotation.y += 0.01));

   return (
      <mesh ref={myref}>
         <cylinderBufferGeometry attach="geometry" args={[2, 2, 2]} />
         <meshBasicMaterial attach="material" color="hotpink" />
      </mesh>
   );
}

export default function App() {
   return (
      <Canvas>
         <ambientLight />
         <Cylinder />
      </Canvas>
   );
}
Here we simply created cylinder geometry and mesh for coloring. Always use a separate function to make a shape and then render it inside canvas. The Cylinder function takes 3 arguments: top radius, bottom radius, and height.
<mesh> is used to create the threeJS object, and inside it, we made a box using CylinderGeometry which is used to define the size, shape, and other structural properties. We used meshStandardMaterial to design our geometrical structure.
<mesh> is used to combine the structure and the design together. We created a functional component inside which we made a reference. Then we made a Frame which is required to change the position of our mesh object or cylinder. Then we added the frame to reference and gave reference to mesh.
We used the position argument to position the object. <AmbientLight> is used to make the color visible; in its absence, the <Cylinder> will look completely black.
On execution, it will produce the following output −
Your browser does not support HTML5 video.
Various Types of Keys in DBMS

The different types of keys in DBMS are −
Candidate Key - The candidate keys in a table are defined as the set of keys that is minimal and can uniquely identify any data row in the table.
Primary Key - The primary key is selected from one of the candidate keys and becomes the identifying key of a table. It can uniquely identify any data row of the table.
Super Key - Super Key is the superset of primary key. The super key contains a set of attributes, including the primary key, which can uniquely identify any data row in the table.
Composite Key -  If any single attribute of a table is not capable of being the key i.e it cannot identify a row uniquely, then we combine two or more attributes to form a key. This is known as a composite key.
Secondary Key - Only one of the candidate keys is selected as the primary key. The rest of them are known as secondary keys.
Foreign Key - A foreign key is an attribute value in a table that acts as the primary key in another table. Hence, the foreign key is useful in linking together two tables. Data should be entered in the foreign key column with great care, as wrongly entered data can invalidate the relationship between the two tables.
An example to explain the different keys is −
<STUDENT>
<SUBJECT>
<ENROLL>
The Super Keys in <Student> table are −
{Student_Number}
{Student_Phone}
{Student_Number,Student_Name}
{Student_Number,Student_Phone}
{Student_Number,Subject_Number}
{Student_Phone,Student_Name}
{Student_Phone,Subject_Number}
{Student_Number,Student_Name,Student_Phone}
{Student_Number,Student_Phone,Subject_Number}
{Student_Number,Student_Name,Subject_Number}
{Student_Phone,Student_Name,Subject_Number}
The Super Keys in <Subject> table are −
{Subject_Number}
{Subject_Number,Subject_Name}
{Subject_Number,Subject_Instructor}
{Subject_Number,Subject_Name,Subject_Instructor}
{Subject_Name,Subject_Instructor}
The Super Key in <Enroll> table is −
{Student_Number,Subject_Number}
The Candidate Key in <Student> table is {Student_Number} or {Student_Phone}
The Candidate Key in <Subject> table is {Subject_Number} or {Subject_Name,Subject_Instructor}
The Candidate Key in <Student> table is {Student_Number, Subject_Number}
The Primary Key in <Student> table is {Student_Number}
The Primary Key in <Subject> table is {Subject_Number}
The Primary Key in <Enroll> table is {Student_Number, Subject_Number}
The Composite Key in <Enroll> table is {Student_Number, Subject_Number}
The Secondary Key in <Student> table is {Student_Phone}
The Secondary Key in <Subject> table is {Subject_Name,Subject_Instructor}
{Subject_Number} is the Foreign Key of <Student> table and Primary key of <Subject> table.
C - Basic Syntax

You have seen the basic structure of a C program, so it will be easy to understand other basic building blocks of the C programming language.
A C program consists of various tokens and a token is either a keyword, an identifier, a constant, a string literal, or a symbol. For example, the following C statement consists of five tokens −
printf("Hello, World! \n");
The individual tokens are −
printf
(
   "Hello, World! \n"
)
;
In a C program, the semicolon is a statement terminator. That is, each individual statement must be ended with a semicolon. It indicates the end of one logical entity.
Given below are two different statements −
printf("Hello, World! \n");
return 0;
Comments are like helping text in your C program and they are ignored by the compiler. They start with /* and terminate with the characters */ as shown below −
/* my first program in C */

You cannot have comments within comments and they do not occur within a string or character literals.
A C identifier is a name used to identify a variable, function, or any other user-defined item. An identifier starts with a letter A to Z, a to z, or an underscore '_' followed by zero or more letters, underscores, and digits (0 to 9).
C does not allow punctuation characters such as @, $, and % within identifiers. C is a case-sensitive programming language. Thus, Manpower and manpower are two different identifiers in C. Here are some examples of acceptable identifiers −
mohd       zara    abc   move_name  a_123
myname50   _temp   j     a23b9      retVal

The following list shows the reserved words in C. These reserved words may not be used as constants or variables or any other identifier names.
A line containing only whitespace, possibly with a comment, is known as a blank line, and a C compiler totally ignores it.
Whitespace is the term used in C to describe blanks, tabs, newline characters and comments. Whitespace separates one part of a statement from another and enables the compiler to identify where one element in a statement, such as int, ends and the next element begins. Therefore, in the following statement −
int age;
there must be at least one whitespace character (usually a space) between int and age for the compiler to be able to distinguish them. On the other hand, in the following statement −
fruit = apples + oranges;   // get the total fruit
no whitespace characters are necessary between fruit and =, or between = and apples, although you are free to include some if you wish to increase readability.
 Print
 Add Notes
 Bookmark this page
How to clear the contents of a Tkinter Text widget?

Tkinter Text Widget is used to add the text writer in an application. It has many attributes and properties which are used to extend the functionality of a text editor. In order to delete the input content, we can use the delete("start", "end") method.
#Import the tkinter library
from tkinter import *

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

#Set the geometry
win.geometry("600x250")

#Define a function to clear the input text
def clearToTextInput():
   my_text.delete("1.0","end")

#Create a text widget
my_text=Text(win, height=10)
my_text.pack()

#Create a Button
btn=Button(win,height=1,width=10, text="Clear",command=clearToTextInput)
btn.pack()

#Display the window without pressing key
win.mainloop()
Running the above code will create a text widget and a button that can be used to clear the Input text.
Now Click on the “Clear” button, it will clear the input text.
Non static blocks in Java.

A static block is a block of code with a static keyword. In general, these are used to initialize the static members. JVM executes static blocks before the main method at the time of class loading.
 Live Demo
public class MyClass {
   static{
      System.out.println("Hello this is a static block");
   }
   public static void main(String args[]){
      System.out.println("This is main method");
   }
}
Hello this is a static block
This is main method
Similar to static blocks, Java also provides instance initialization blocks which are used to initialize instance variables, as an alternative to constructors.
Whenever you define an initialization block Java copies its code to the constructors. Therefore you can also use these to share code between the constructors of a class.
 Live Demo
public class Student {
   String name;
   int age;
   {
      name = "Krishna";
      age = 25;
   }
   public static void main(String args[]){
      Student std = new Student();
      System.out.println(std.age);
      System.out.println(std.name);
   }
}
25
Krishna
In a class, you can also have multiple initialization blocks.
 Live Demo
public class Student {
   String name;
   int age;
   {
      name = "Krishna";
      age = 25;
   }
   {
      System.out.println("Initialization block");
   }
   public static void main(String args[]){
      Student std = new Student();
      System.out.println(std.age);
      System.out.println(std.name);
   }
}
Initialization block
25
Krishna
You can also define an instance initialization block in the parent class.
public class Student extends Demo {
   String name;
   int age;
   {
      System.out.println("Initialization block of the sub class");
      name = "Krishna";
      age = 25;
   }
   public static void main(String args[]){
      Student std = new Student();
      System.out.println(std.age);
      System.out.println(std.name);
   }
}
Initialization block of the super class
Initialization block of the sub class
25
Krishna
JSF - Add Data to DataTable

In this section, we'll showcase adding a row to a dataTable.
Let us create a test JSF application to test the above functionality.
<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns = "http://www.w3.org/1999/xhtml"   
xmlns:h = "http://java.sun.com/jsf/html"
xmlns:f = "http://java.sun.com/jsf/core">
   
   <h:head>
      <title>JSF tutorial</title>		
      <h:outputStylesheet library = "css" name = "styles.css"  /> 	
   </h:head>
   
   <h:body> 
      <h2>DataTable Example</h2>
      
      <h:form>
         <h:dataTable value = "#{userData.employees}" var = "employee"
            styleClass = "employeeTable"
            headerClass = "employeeTableHeader"
            rowClasses = "employeeTableOddRow,employeeTableEvenRow">
            
            <h:column>    				
               <f:facet name = "header">Name</f:facet>    				
               #{employee.name}
            </h:column>
            
            <h:column>
               <f:facet name = "header">Department</f:facet>
               #{employee.department}
            </h:column>
            
            <h:column>
               <f:facet name = "header">Age</f:facet>
               #{employee.age}
            </h:column>
            
            <h:column>
               <f:facet name = "header">Salary</f:facet>
               #{employee.salary}
            </h:column>
         </h:dataTable>
         <h3>Add Employee</h3>
         <hr/>
         
         <table>
            <tr>
               <td>Name :</td>
               <td><h:inputText size = "10" value = "#{userData.name}" /></td>
            </tr>
            
            <tr>
               <td>Department :</td>
               <td><h:inputText size = "20" value = "#{userData.dept}" /></td>
            </tr>
            
            <tr>
               <td>Age :</td>
               <td><h:inputText size = "5" value = "#{userData.age}" /></td>
            </tr>
            
            <tr>
               <td>Salary :</td>
               <td><h:inputText size = "5" value = "#{userData.salary}" /></td>
            </tr>
            
            <tr>
               <td> </td>
               <td><h:commandButton value = "Add Employee" 
                  action = "#{userData.addEmployee}" /></td>
            </tr>
         </table>	  
      </h:form>
   
   </h:body>
</html>
Once you are ready with all the changes done, let us compile and run the application as we did in JSF - First Application chapter. If everything is fine with your application, this will produce the following result.
Add values to Add Employee Form and click Add Employee button. See the following result.

    37 Lectures 
     3.5 hours 

 Chaand Sheikh
 Print
 Add Notes
 Bookmark this page
How to select a directory and store the location using Tkinter in Python?

We are familiar with dialog boxes and interacted with them in many types of applications. Such types of dialogs are useful in creating an application where user interaction is a prime need. We can use the dialog boxes to ask the user to select different types of files and then perform certain operations such as reading the file, writing to the file, etc. The dialog boxes can be created by using the filedialog Module in Python.
In this example, we will create an application that will ask the user to select a file from the local directory and then will display the location of the directory with the help of Labels.
#Import the Tkinter library
from tkinter import *
from tkinter import ttk
from tkinter import filedialog
#Create an instance of Tkinter frame
win= Tk()
#Define the geometry
win.geometry("750x250")
def select_file():
   path= filedialog.askopenfilename(title="Select a File", filetype=(('text files''*.txt'),('all files','*.*')))
   Label(win, text=path, font=13).pack()
#Create a label and a Button to Open the dialog
Label(win, text="Click the Button to Select a File", font=('Aerial 18 bold')).pack(pady=20)
button= ttk.Button(win, text="Select", command= select_file)
button.pack(ipadx=5, pady=15)
win.mainloop()
Running the above code will display a window that contains a button to select the file from the directory and display the file location on the window.
Now, select any file from the local directory and then, it will display the location of the file in a Label widget.
How to initialize memory with a new operator in C++?

The new operator in C++ is defined for allocating memory and not initializing. If you want to allocate an array of type int with the new operator, and you want to initialize them all to the default value(ie 0 in case of ints), you can use the following syntax −
new int[10]();
Note that you simply must use the empty parentheses - you can't, for example, use (0) or the other expression that is why this is only helpful for default initialization.
There are other methods of initializing the same memory using fill_n, memset, etc which you can use to initialize objects to non default values. 
#include<iostream>
int main() {
   int myArray[10];
   
   // Initialize to 0 using memset
   memset( myArray, 0, 10 * sizeof( int ));    
   
   // Using a loop assigns the value 1 to each element
   std::fill_n(array, n, 1);    
}
Java Arithmetic Operator Examples

The following program is a simple example which demonstrates the arithmetic operators. Copy and paste the following Java program into Test.java file, and compile and run this program −
Online Demo
public class Test {
   public static void main(String args[]) {
      int a = 10;
      int b = 20;
      int c = 25;
      int d = 25;

      System.out.println("a + b = " + (a + b) );
      System.out.println("a - b = " + (a - b) );
      System.out.println("a * b = " + (a * b) );
      System.out.println("b / a = " + (b / a) );
      System.out.println("b % a = " + (b % a) );
      System.out.println("c % a = " + (c % a) );
      System.out.println("a++   = " +  (a++) );
      System.out.println("b--   = " +  (a--) );

      // Check the difference in d++ and ++d
      System.out.println("d++   = " +  (d++) );
      System.out.println("++d   = " +  (++d) );
   }
}
This will produce the following result −
a + b = 30
a - b = -10
a * b = 200
b / a = 2
b % a = 0
c % a = 5
a++   = 10
b--   = 11
d++   = 25
++d   = 27
Impala - Union Clause

You can combine the results of two queries using the Union clause of Impala.
Following is the syntax of the Union clause in Impala.
query1 union query2;

Assume we have a table named customers in the database my_db and its contents are as follows −
[quickstart.cloudera:21000] > select * from customers; 
Query: select * from customers 
+----+----------+-----+-----------+--------+ 
| id | name     | age | address   | salary | 
+----+----------+-----+-----------+--------+ 
| 1  | Ramesh   | 32  | Ahmedabad | 20000  | 
| 9  | robert   | 23  | banglore  | 28000  | 
| 2  | Khilan   | 25  | Delhi     | 15000  | 
| 4  | Chaitali | 25  | Mumbai    | 35000  | 
| 7  | ram      | 25  | chennai   | 23000  | 
| 6  | Komal    | 22  | MP        | 32000  | 
| 8  | ram      | 22  | vizag     | 31000  | 
| 5  | Hardik   | 27  | Bhopal    | 40000  | 
| 3  | kaushik  | 23  | Kota      | 30000  | 
+----+----------+-----+-----------+--------+ 
Fetched 9 row(s) in 0.59s

In the same way, suppose we have another table named employee and its contents are as follows −
[quickstart.cloudera:21000] > select * from employee; 
Query: select * from employee 
+----+---------+-----+---------+--------+ 
| id | name    | age | address | salary | 
+----+---------+-----+---------+--------+ 
| 3  | mahesh  | 54  | Chennai | 55000  | 
| 2  | ramesh  | 44  | Chennai | 50000  | 
| 4  | Rupesh  | 64  | Delhi   | 60000  | 
| 1  | subhash | 34  | Delhi   | 40000  | 
+----+---------+-----+---------+--------+ 
Fetched 4 row(s) in 0.59s

Following is an example of the union clause in Impala. In this example, we arrange the records in both tables in the order of their id’s and limit their number by 3 using two separate queries and joining these queries using the UNION clause.
[quickstart.cloudera:21000] > select * from customers order by id limit 3
 union select * from employee order by id limit 3;

On executing, the above query gives the following output.
Query: select * from customers order by id limit 3 union select 
   * from employee order by id limit 3 
+----+---------+-----+-----------+--------+ 
| id | name    | age | address   | salary | 
+----+---------+-----+-----------+--------+ 
| 2  | Khilan  | 25  | Delhi     | 15000  |
| 3  | mahesh  | 54  | Chennai   | 55000  | 
| 1  | subhash | 34  | Delhi     | 40000  | 
| 2  | ramesh  | 44  | Chennai   | 50000  | 
| 3  | kaushik | 23  | Kota      | 30000  | 
| 1  | Ramesh  | 32  | Ahmedabad | 20000  | 
+----+---------+-----+-----------+--------+ 
Fetched 6 row(s) in 3.11s

 Print
 Add Notes
 Bookmark this page
Plotting a cumulative graph of Python datetimes in Matplotlib

To plot a cumulative graph of python datetimes, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Set the figure size and adjust the padding between and around the subplots.
Make a Pandas dataframe with some college data, where one key for time difference and another key for number students have admissioned in the subsequent year.
Make a Pandas dataframe with some college data, where one key for time difference and another key for number students have admissioned in the subsequent year.
Plot the dataframe using plot() method where kind='bar', i.e., class by name.
Plot the dataframe using plot() method where kind='bar', i.e., class by name.
To display the figure, use show() method.
To display the figure, use show() method.
import pandas as pd
from matplotlib import pyplot as plt

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

college_student_data = {'durations': [1, 2, 2.5, 3, 4.5, 5, 5.5, 6, 6.5, 7], 'admissions': [5, 50, 150, 3380, 760, 340, 115, 80, 40, 10]}
df = pd.DataFrame(data=college_student_data)

df.plot(kind='bar', x='durations', y='admissions', legend=False, color='red', rot=0,)

plt.show()
How to print a line on the console using C#?

To display a line, Console.Write() is used in C#.
Console displays the result on the console. I have first set a string.
string str = "Tom Hanks is an actor";
Now displaying the above line.
Console.WriteLine(str);
The following is the complete code −
 Live Demo
using System;
namespace Program {
   public class Demo {
      public static void Main(String[] args) {
         string str = "Tom Hanks is an actor";
         Console.WriteLine("Displaying a line below");
         Console.WriteLine(str);
         Console.ReadLine();
      }
   }
}
Displaying a line below
Tom Hanks is an actor
How to import external libraries in JShell in Java 9?

JShell is an interactive tool to learn Java language and prototyping Java code. JShell does the work by evaluating the commands that user types into it. This tool works on the principle of REPL (Read-Evaluate-Print-Loop).
By default, JShell automatically imports a few useful java packages when the JShell session is started. We can type the command /imports to get a list of all these imports.
jshell> /imports
| import java.io.*
| import java.math.*
| import java.net.*
| import java.nio.file.*
| import java.util.*
| import java.util.concurrent.*
| import java.util.function.*
| import java.util.prefs.*
| import java.util.regex.*
| import java.util.stream.*
| import javax.mail.internet.InternetAddress
We can also import external libraries in JShell by using the below steps:
If we want to create an InternetAddress object that resides in the javax.mail.internet package, then we need to import that package in JShell.
jshell> import javax.mail.internet.InternetAddress
| Error:
| package javax.mail.internet does not exist
| import javax.mail.internet.InternetAddress;
| ^---------------------------------^
In the above, just importing the class doesn't work because the package is unknown to the classpath. We need to add jars or class files to classpath by using the command: "/env –class-path <jars, class files>"
jshell> /env --class-path \Users\user\mail-1.4.7.jar
| Setting new options and restoring state.

jshell> import javax.mail.internet.InternetAddress
Finally, we can create an InternetAddress object by using below
jshell> InternetAddress from = new InternetAddress("a@a")
from ==> a@a
How to plot a time series array, with confidence intervals displayed in Python? (Matplotlib)

To plot a time series array, with confidence intervals displayed in Python, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Get the time series array.
Initialize a variable, n_steps, to get the mean and standard deviation.
Get the under and above lines for confidence intervals.
Plot the mean line using plot() method.
Use fill_between() method to get the confidence interval.
To display the figure, use show() method.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

time_series_array = np.sin(np.linspace
                           (-np.pi, np.pi, 400)) + np.random.rand((400))
n_steps = 15

time_series_df = pd.DataFrame(time_series_array)

line = time_series_df.rolling(n_steps).mean()

line_deviation = 2 * time_series_df.rolling(n_steps).std()

under_line = (line - line_deviation)[0]

over_line = (line + line_deviation)[0]

plt.plot(line, linewidth=2)

plt.fill_between(line_deviation.index, under_line,
                  over_line, color='red', alpha=.3)

plt.show()
Kubernetes - Kubectl

Kubectl is the command line utility to interact with Kubernetes API. It is an interface which is used to communicate and manage pods in Kubernetes cluster.
One needs to set up kubectl to local in order to interact with Kubernetes cluster.
Download the executable to the local workstation using the curl command.
$ curl -O https://storage.googleapis.com/kubernetesrelease/
release/v1.5.2/bin/linux/amd64/kubectl

$ curl -O https://storage.googleapis.com/kubernetesrelease/
release/v1.5.2/bin/darwin/amd64/kubectl

After download is complete, move the binaries in the path of the system.
$ chmod +x kubectl
$ mv kubectl /usr/local/bin/kubectl

Following are the steps to perform the configuration operation.
$ kubectl config set-cluster default-cluster --server = https://${MASTER_HOST} --
certificate-authority = ${CA_CERT}

$ kubectl config set-credentials default-admin --certificateauthority = ${
CA_CERT} --client-key = ${ADMIN_KEY} --clientcertificate = ${
ADMIN_CERT}

$ kubectl config set-context default-system --cluster = default-cluster --
user = default-admin
$ kubectl config use-context default-system

Replace ${MASTER_HOST} with the master node address or name used in the previous steps.
Replace ${MASTER_HOST} with the master node address or name used in the previous steps.
Replace ${CA_CERT} with the absolute path to the ca.pem created in the previous steps.
Replace ${CA_CERT} with the absolute path to the ca.pem created in the previous steps.
Replace ${ADMIN_KEY} with the absolute path to the admin-key.pem created in the previous steps.
Replace ${ADMIN_KEY} with the absolute path to the admin-key.pem created in the previous steps.
Replace ${ADMIN_CERT} with the absolute path to the admin.pem created in the previous steps.
Replace ${ADMIN_CERT} with the absolute path to the admin.pem created in the previous steps.
To verify if the kubectl is working fine or not, check if the Kubernetes client is set up correctly.
$ kubectl get nodes

NAME       LABELS                                     STATUS
Vipin.com  Kubernetes.io/hostname = vipin.mishra.com    Ready


    41 Lectures 
     5 hours 

 AR Shankar

    15 Lectures 
     2 hours 

 Harshit Srivastava, Pranjal Srivastava

    18 Lectures 
     1.5 hours 

 Nigel Poulton

    25 Lectures 
     1.5 hours 

 Pranjal Srivastava

    18 Lectures 
     1 hours 

 Pranjal Srivastava

    26 Lectures 
     1.5 hours 

 Pranjal Srivastava
 Print
 Add Notes
 Bookmark this page
What is the use of update command in SQL?

Update command is a data manipulation command which is used to edit the records of a table. It may be used to update a single row based on a condition, all rows or set of rows based on the condition given by the user.
It is used along with the SET clause, operationally, a WHERE clause may be used to match conditions −
An example is given below for the use of update command −
update table student set name=’sneha’ where branch=’CSE’;
Given below is another example of the usage of update command −
create table employee(ename varchar(30),department varchar(20));
insert into employee values('pinky','CSE');
insert into employee values('priya','ECE');
insert into employee values('hari','EEE');
select * from employee;
update employee set ename='sneha' where department='CSE';
select * from employee;
You will get the following output −
pinky|CSE
priya|ECE
hari|EEE
sneha|CSE
priya|ECE
hari|EEE
Given below is an example to update table employee set age=age+1:
create table employee(ename varchar(30),department varchar(20), age number(30));
insert into employee values('ram','projectmanager',40);
insert into employee values('priya','assistant director',45);
insert into employee values('hari','developer',46);
select * from employee;
update employee set age=age+2;
select * from employee;
You will get the following output −
ram|projectmanager|40
priya|assistant director|45
hari|developer|46
ram|projectmanager|42
priya|assistant director|47
hari|developer|48
Given below is an example to update table salary set −
Here,
bonus=bonus+5000
basic=basic+(0.2*bonus)
create table employee(ename varchar(30),department varchar(20), age number(30), salary number(20));
insert into employee values('ram','projectmanager',40,50000);
insert into employee values('priya','assistant director',45,45000);
insert into employee values('hari','developer',46,30000);
select * from employee;

update employee set age=age+2,
   salary= salary+5000;

select * from employee;
You will get the following output −
ram  |projectmanager    |40|50000
priya|assistant director|45|45000
hari |developer         |46|30000
ram  |projectmanager    |42|55000
priya|assistant director|47|50000
hari |developer         |48|35000
Input type DateTime Value format with HTML

Use input type=”datetype”. The datetime input type is used in HTML using the <input type="datetime-local">. Using this, allow the users to select date and time. A date time picker popup is visible whenever input field is clicked.
<!DOCTYPE html>
<html>
   <head>
      <title>HTML input datetime</title>
   </head>
   <body>
      <form action = "" method = "get">
         Details:<br><br>
         Student Name<br><input type = "name" name = "sname"><br>
         Exam Date and Time<br><input type = "datetime-local" name = "datetime"><br>
         <input type = "submit" value = "Submit">
      </form>
   </body>
</html>
JSTL - Core <c:forEach>, <c:forTokens> Tag

These tags exist as a good alternative to embedding a Java for, while, or do-while loop via a scriptlet. The <c:forEach> tag is a commonly used tag because it iterates over a collection of objects. The <c:forTokens> tag is used to break a string into tokens and iterate through each of the tokens.
The <c:forEach> tag has the following attributes −
The <c:forTokens> tag has similar attributes as that of the <c:forEach> tag except one additional attribute delims which specifies sharacters to use as delimiters.
<%@ taglib uri = "http://java.sun.com/jsp/jstl/core" prefix = "c" %>

<html>
   <head>
      <title><c:forEach> Tag Example</title>
   </head>

   <body>
      <c:forEach var = "i" begin = "1" end = "5">
         Item <c:out value = "${i}"/><p>
      </c:forEach>
   </body>
</html>
The above code will generate the following result −
Item 1
Item 2
Item 3
Item 4
Item 5

<%@ taglib uri = "http://java.sun.com/jsp/jstl/core" prefix = "c" %>

<html>
   <head>
      <title><c:forTokens> Tag Example</title>
   </head>

   <body>
      <c:forTokens items = "Zara,nuha,roshy" delims = "," var = "name">
         <c:out value = "${name}"/><p>
      </c:forTokens>
   </body>
</html>
The above code will generate the following result −
Zara
nuha
roshy


    108 Lectures 
     11 hours 

 Chaand Sheikh

    517 Lectures 
     57 hours 

 Chaand Sheikh

    41 Lectures 
     4.5 hours 

 Karthikeya T

    42 Lectures 
     5.5 hours 

 TELCOMA Global

    15 Lectures 
     3 hours 

 TELCOMA Global

    44 Lectures 
     15 hours 

 Uplatz
 Print
 Add Notes
 Bookmark this page
How to use enums in C++?

Enumeration is a user defined datatype in C/C++ language. It is used to assign names to the integral constants which makes a program easy to read and maintain. The keyword “enum” is used to declare an enumeration.
The following is the syntax of enums.
enum enum_name{const1, const2, ....... };
Here,
enum_name − Any name given by user.
const1, const2 − These are values of type flag.
The enum keyword is also used to define the variables of enum type. There are two ways to define the variables of enum type as follows −
enum colors{red, black};
enum suit{heart, diamond=8, spade=3, club};
The following is an example of enums.
 Live Demo
#include <iostream>
using namespace std;
enum colors{red=5, black};
enum suit{heart, diamond=8, spade=3, club};
int main() {
   cout <<"The value of enum color : "<<red<<","<<black;
   cout <<"\nThe default value of enum suit : "<<heart<<","<<diamond<<","<<spade<<","<<club;
   return 0;
}
The value of enum color : 5,6
The default value of enum suit : 0,8,3,4
In the above program, two enums are declared as color and suit outside the main() function.
enum colors{red=5, black};
enum suit{heart, diamond=8, spade=3, club};
In the main() function, the values of enum elements are printed.
cout <<"The value of enum color : "<<red<<","<<black;
cout <<"\nThe default value of enum suit : "<<heart<<","<<diamond<<","<<spade<<","<<club;
Handling POST, PUT, PATCH and DELETE Requests

In this chapter, we will understand how to use the POST method using requests library and also pass parameters to the URL.
For PUT request, the Requests library has requests.post() method, the example of it is shown below −
myurl = 'https://postman-echo.com/post'
myparams = {'name': 'ABC', 'email':'xyz@gmail.com'}
res = requests.post(myurl, data=myparams)
print(res.text)
E:\prequests>python makeRequest.py
{"args":{},"data":"","files":{},"form":{"name":"ABC","email":"xyz@gmail.com"},
"headers":{"x-forwarded-proto":"https","host":"postman-echo.com","content-
length":"30","accept":"*/*","accept-encoding":"gzip,deflate","content-
type":"application/x-www-form-urlencoded","user-agent":"python-
requests/2.22.0","x-forwarded-
port":"443"},"json":{"name":"ABC","email":"xyz@gmail.com"},
"url":"https://postman-echo.com/post"}

In the example shown above, you can pass the form data as key-value pair to the data param inside requests.post(). We will also see how to work with PUT, PATCH and DELETE in requests module.
For PUT request, the Requests library has requests.put() method, the example of it is shown below.
import requests
myurl = 'https://postman-echo.com/put'
myparams = {'name': 'ABC', 'email':'xyz@gmail.com'}
res = requests.put(myurl, data=myparams)
print(res.text)
E:\prequests>python makeRequest.py
{"args":{},"data":"","files":{},"form":{"name":"ABC","email":"xyz@gmail.com"},
"headers":{"x-forwarded-proto":"https","host":"postman-echo.com","content-
length":
"30","accept":"*/*","accept-encoding":"gzip, deflate","content-
type":"applicatio
n/x-www-form-urlencoded","user-agent":"python-requests/2.22.0","x-forwarded-
port
":"443"},"json":{"name":"ABC","email":"xyz@gmail.com"},
"url":"https://postman-echo.com/put"}

For the PATCH request, the Requests library has requests.patch() method, the example of it is shown below.
import requests
myurl = https://postman-echo.com/patch'
res = requests.patch(myurl, data="testing patch")
print(res.text)
E:\prequests>python makeRequest.py
{"args":{},"data":{},"files":{},"form":{},"headers":{"x-forwarded-
proto":"https"
,"host":"postman-echo.com","content-length":"13","accept":"*/*","accept-
encoding
":"gzip, deflate","user-agent":"python-requests/2.22.0","x-forwarded-
port":"443"
},"json":null,"url":"https://postman-echo.com/patch"}

For the DELETE request, the Requests library has requests.delete() method, the example of it is shown below.
import requests
myurl = 'https://postman-echo.com/delete'
res = requests.delete(myurl, data="testing delete")
print(res.text)
E:\prequests>python makeRequest.py
{"args":{},"data":{},"files":{},"form":{},"headers":{"x-forwarded-
proto":"https"
,"host":"postman-echo.com","content-length":"14","accept":"*/*","accept-
encoding
":"gzip, deflate","user-agent":"python-requests/2.22.0","x-forwarded-
port":"443"
},"json":null,"url":"https://postman-echo.com/delete"}

 Print
 Add Notes
 Bookmark this page
How to clear the Entry widget after a button is pressed in Tkinter?

Tkinter Entry widgets are used to display a single line text that is generally taken in the form of user Input. We can clear the content of Entry widget by defining a method delete(0, END) which aims to clear all the content in the range. The method can be invoked by defining a function which can be used by creating a Button Object.
In this example, we have created an entry widget and a button that can be used to clear all the content from the widget.
#Import the required libraries
from tkinter import *

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

#Set the geometry of frame
win.geometry("650x250")

#Define a function to clear the Entry Widget Content
def clear_text():
   text.delete(0, END)

#Create a entry widget
text= Entry(win, width=40)
text.pack()

#Create a button to clear the Entry Widget
Button(win,text="Clear", command=clear_text, font=('Helvetica bold',10)).pack(pady=5)

win.mainloop()
Running the above code will display a window that contains an entry widget and a Button which can be used to clear the text written in the entry field.
Now click on the “Clear” Button to clear the Entry widget.