code-rag-bench/online-tutorials huggingface dataset:
Evaluating Model Performance

To evaluate the model performance, we call evaluate method as follows −
loss_and_metrics = model.evaluate(X_test, Y_test, verbose=2)
To evaluate the model performance, we call evaluate method as follows −
loss_and_metrics = model.evaluate(X_test, Y_test, verbose=2)

We will print the loss and accuracy using the following two statements −
print("Test Loss", loss_and_metrics[0])
print("Test Accuracy", loss_and_metrics[1])

When you run the above statements, you would see the following output −
Test Loss 0.08041584826191042
Test Accuracy 0.9837

This shows a test accuracy of 98%, which should be acceptable to us. What it means to us that in 2% of the cases, the handwritten digits would not be classified correctly. We will also plot accuracy and loss metrics to see how the model performs on the test data.
We use the recorded history during our training to get a plot of accuracy metrics. The following code will plot the accuracy on each epoch. We pick up the training data accuracy (“acc”) and the validation data accuracy (“val_acc”) for plotting.
plot.subplot(2,1,1)
plot.plot(history.history['acc'])
plot.plot(history.history['val_acc'])
plot.title('model accuracy')
plot.ylabel('accuracy')
plot.xlabel('epoch')
plot.legend(['train', 'test'], loc='lower right')
The output plot is shown below −
As you can see in the diagram, the accuracy increases rapidly in the first two epochs, indicating that the network is learning fast. Afterwards, the curve flattens indicating that not too many epochs are required to train the model further. Generally, if the training data accuracy (“acc”) keeps improving while the validation data accuracy (“val_acc”) gets worse, you are encountering overfitting. It indicates that the model is starting to memorize the data.
We will also plot the loss metrics to check our model’s performance.
Again, we plot the loss on both the training (“loss”) and test (“val_loss”) data. This is done using the following code −
plot.subplot(2,1,2)
plot.plot(history.history['loss'])
plot.plot(history.history['val_loss'])
plot.title('model loss')
plot.ylabel('loss')
plot.xlabel('epoch')
plot.legend(['train', 'test'], loc='upper right')
The output of this code is shown below −
As you can see in the diagram, the loss on the training set decreases rapidly for the first two epochs. For the test set, the loss does not decrease at the same rate as the training set, but remains almost flat for multiple epochs. This means our model is generalizing well to unseen data.
Now, we will use our trained model to predict the digits in our test data.

    87 Lectures 
     11 hours 

 Abhilash Nelson

    106 Lectures 
     13.5 hours 

 Abhilash Nelson

    28 Lectures 
     4 hours 

 Abhilash Nelson

    58 Lectures 
     8 hours 

 Soumyadeep Dey

    59 Lectures 
     2.5 hours 

 Mike West

    128 Lectures 
     5.5 hours 

 TELCOMA Global
 Print
 Add Notes
 Bookmark this page
Describe pass by value and pass by reference in JavaScript?

In pass by value, a function is called by directly passing the value of the variable as the argument. Changing the argument inside the function doesn’t affect the variable passed from outside the function. Javascript always pass by value so changing the value of the variable never changes the underlying primitive (String or number).
In the following example, variable 'a' has assigned value 1. But inside function 'change' it got assigned with value 2. Since javascript is always a pass by value, the displayed output will be '1' but not '2'.
Live Demo
<html>
<body>
<script>
   let a = 1;
   let change = (val) => {
      val = 2
   }
   change(a);
   document.write(a);
</script>
</body>
</html>
1
There are some instances that address is passed instead of arguments to call a function. At that time, changing the value inside the function affect the variable passed from outside the function. This is called a pass by reference. In javascript mostly arrays and objects follow pass by reference.
In the following example an object named 'a' is declared outside the function 'change'. Here one should heed that variable 'a' got mutated but not assigned with value 2, as shown in example 2. A pass by reference takes place when mutation has occurred.   
Live Demo
<html>
<body>
<script>
   let a = {num:1};
   let change = (val) => {
      val.num = 2
   }
   change(a);
  document.write(JSON.stringify(a));
</script>
</body>
</html>
{"num":2}
In the following example instead of mutation, variable 'a' got assigned with value 2. So pass by value takes place and there will be no affect on outside variable.
Live Demo
<html>
<body>
<script>
   let a = {num : 1};
   let change = (val) => {
      val = {num :2};
   }
   change(a);
   document.write(JSON.stringify(a));
</script>
</body>
</html>
{"num":1}
PyQt5 - Different border color to lineedit part on mouse hover (for non editable Combobox) - GeeksforGeeks

06 May, 2020
In this article we will see how we can set different border color to the line edit part of the combo box when mouse hover over the line edit part, line edit is the part of combo box which displays the selected item, it is editable by nature. In order to set and access the line edit object we use setLineEdit and lineEdit method respectively.
Note : When we create line edit object it make the combo box editable.
In order to do this we have to do the following :
1. Create a combo box2. Add item to the combo box3. Create a QLineEdit object4. Set border to the QLineEdit object5. Set border with different color when mouse hover over it6. Make line edit object non-editable(read-only)7. Add QLineEdit object to the combo box
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 a check-able combo box object        self.combo_box = QComboBox(self)          # setting geometry of combo box        self.combo_box.setGeometry(200, 150, 150, 80)          # geek list        geek_list = ["Sayian", "Super Sayian", "Super Sayian 2", "Super Sayian B"]          # adding list of items to combo box        self.combo_box.addItems(geek_list)          # creating line edit object        line_edit = QLineEdit()          # setting border to the line edit part        # set different border color when mouse hover over it        line_edit.setStyleSheet("QLineEdit"                                "{"                                "border : 5px solid black;"                                "}"                                "QLineEdit::hover"                                "{"                                "border-color : red green blue yellow"                                "}")          # making line edit object read only        line_edit.setReadOnly(True)          # adding line edit object to the combo box        self.combo_box.setLineEdit(line_edit)  # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output :
Python PyQt5-ComboBox
Python PyQt5-ComboBox-stylesheet
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Python program to convert a list to string
Reading and Writing to text files in Python
Program to find lexicographically smallest subsequence of size k in Python

Suppose we have a list of numbers called nums and another value k, we have to find the lexicographically smallest subsequence of size k.
So, if the input is like nums = [2, 3, 1, 10, 3, 4] k = 3, then the output will be [1, 3, 4]
To solve this, we will follow these steps −
l := size of nums, r := k - 1
out := a new list
for j in range 0 to k, domn := nums[complement of r]for i in range r to l, doif mn >= nums[complement of i], thenmn := nums[complement of i]l := ir := r - 1
mn := nums[complement of r]
for i in range r to l, doif mn >= nums[complement of i], thenmn := nums[complement of i]l := i
if mn >= nums[complement of i], thenmn := nums[complement of i]l := i
mn := nums[complement of i]
l := i
r := r - 1
insert mn at the end of out
return out
Let us see the following implementation to get better understanding −
 Live Demo
class Solution:
   def solve(self, nums, k):
      l, r = len(nums), k - 1
      out = []
      for j in range(k):
         mn = nums[~r]
         for i in range(r, l):
            if mn >= nums[~i]:
               mn = nums[~i]
               l = i
         r -= 1
         out.append(mn)
   return out
ob = Solution()
nums = [2, 3, 1, 10, 3, 4]
k = 3
print(ob.solve(nums, k))
[2, 3, 1, 10, 3, 4], 3
[1, 3, 4]
queue::front() and queue::back() in C++ STL

In this article we will be discussing the working, syntax and examples of queue::front() and queue::back() functions in C++ STL.
Queue is a simple sequence or data structure defined in the C++ STL which does insertion and deletion of the data in FIFO(First In First Out) fashion. The data in a queue is stored in continuous manner. The elements are inserted at the end and removed from the starting of the queue. In C++ STL there is already a predefined template of queue, which inserts and removes the data in the similar fashion of a queue.
queue::front() is an inbuilt function in C++ STL which is declared in  header file. queue::front() returns a reference to the first element which is inserted in the queue container associated with it. Also in other words we can state that front() directly refers to the element which is oldest in a queue container.
Like in the above given figure, head i.e. 1 is the first element which has been entered in the queue and tail i.e. -4 is the last or the most recent element which is entered in the queue
myqueue.front();
This function accepts no parameter
This function returns a reference to the element which is first inserted in the queue container.
Input: queue<int> myqueue = {10, 20, 30, 40};
      myqueue.front();
Output:
      Front element of the queue = 10
 Live Demo
#include <iostream>
#include <queue>
using namespace std;
int main(){
   queue<int> Queue;
   Queue.push(10);
   Queue.push(20);
   Queue.push(30);
   Queue.push(40);
   Queue.push(40);
      cout<<"Element in front of a queue is: "<<Queue.front();
   return 0;
}
If we run the above code it will generate the following output −
Element in front of a queue is: 10
queue::back() is an inbuilt function in C++ STL which is declared in  header file. queue::back() returns a reference to the last element which is inserted in the queue container associated with it. Also in other words we can state that back() directly refers to the element which is newest in a queue container.
myqueue.back();
This function accepts no parameter
This function returns a reference to the element which is last inserted in the queue container.
Input: queue<int> myqueue = {10, 20 30, 40};
      myqueue.back();
Output:
      Back element of the queue = 40
 Live Demo
#include <iostream>
#include <queue>
using namespace std;
int main(){
   queue<int> Queue;
   Queue.push(10);
   Queue.push(20);
   Queue.push(30);
   Queue.push(40);
   Queue.push(50);
      cout<<"Elements at the back of the queue is: "<<Queue.back();
   return 0;
}
If we run the above code it will generate the following output −
Elements at the back of the queue is: 50
Clojure - Maps get

Returns the value mapped to key, not-found or nil if key is not present.
Following is the syntax.
(get hmap key)

Parameters − ‘hmap’ is the map of hash keys and values. ‘key’ is the key for which the value needs to be returned.
Return Value − Returns the value of the key passed to the get function.
Following is an example of get in Clojure.
(ns clojure.examples.example
   (:gen-class))
(defn example []
   (def demokeys (hash-map "z" "1" "b" "2" "a" "3"))
   (println demokeys)
   (println (get demokeys "b")))
(example)
The above code produces the following output.
{z 1, b 2, a 3}
2

 Print
 Add Notes
 Bookmark this page
.NET Core - Adding References to Library

In this chapter, we will discuss how to add references to your library. Adding references to library is like adding references to your other projects, like console project and UWP project.
You can now see that the PCL project has some references by default. You can also add other references as per your application need.
In the PCL library, you can also see the project.json file.
{ 
   "supports": {}, 
   "dependencies": { 
      "NETStandard.Library": "1.6.0", 
      "Microsoft.NETCore.Portable.Compatibility": "1.0.1" 
   }, 
   "frameworks": { 
      "netstandard1.3": {} 
   } 
}
One method of adding references to your library is by typing it directly in the project.json file. As you can see that we have added some references under the dependencies section as shown in the following code.
{ 
   "supports": {}, 
   "dependencies": { 
      "NETStandard.Library": "1.6.0", 
      "Microsoft.NETCore.Portable.Compatibility": "1.0.1", 
      "System.Runtime.Serialization.Json": "4.0.3", 
      "Microsoft.EntityFrameworkCore": "1.1.0" 
   }, 
   "frameworks": { 
      "netstandard1.3": {} 
   } 
} 
Let us now save this file and you will see that references are added to your library now.
The other method of adding references to your library is the NuGet Package Manager. Let us now right-click on the StringLibrary (Portable) project and select Mange NuGet Packages...
On the Browse tab, you can search any NuGet package; let us say we want to add “System.Runtime.Serialization.Primitives” package.
Click the Install button, which will display the following screen.
Now, click the OK button.
Finally, click the I Accept button to start installation of this NuGet package. Once installation is finished, then you will see that the “System.Runtime.Serialization.Primitives” NuGet package is added to your library.
 Print
 Add Notes
 Bookmark this page
Python - Chunks and Chinks

Chunking is the process of grouping similar words together based on the nature of the word. In the below example we define a grammar by which the chunk must be generated. The grammar suggests the sequence of the phrases like nouns and adjectives etc. which will be followed when creating the chunks. The pictorial output of chunks is shown below.
import nltk

sentence = [("The", "DT"), ("small", "JJ"), ("red", "JJ"),("flower", "NN"), 
("flew", "VBD"), ("through", "IN"),  ("the", "DT"), ("window", "NN")]
grammar = "NP: {?*}" 
cp = nltk.RegexpParser(grammar)
result = cp.parse(sentence) 
print(result)
result.draw()

When we run the above program we get the following output −
Changing the grammar, we get a different output as shown below. 
import nltk

sentence = [("The", "DT"), ("small", "JJ"), ("red", "JJ"),("flower", "NN"),
 ("flew", "VBD"), ("through", "IN"),  ("the", "DT"), ("window", "NN")]

grammar = "NP: {?*}" 

chunkprofile = nltk.RegexpParser(grammar)
result = chunkprofile.parse(sentence) 
print(result)
result.draw()

When we run the above program we get the following output −
Chinking is the process of removing a sequence of tokens from a chunk. If the sequence of tokens appears in the middle of the chunk, these tokens are removed, leaving two chunks where they were already present. 
 
import nltk

sentence = [("The", "DT"), ("small", "JJ"), ("red", "JJ"),("flower", "NN"), ("flew", "VBD"), ("through", "IN"),  ("the", "DT"), ("window", "NN")]

grammar = r"""
  NP:
    {<.*>+}         # Chunk everything
    }+{      # Chink sequences of JJ and NN
  """
chunkprofile = nltk.RegexpParser(grammar)
result = chunkprofile.parse(sentence) 
print(result)
result.draw()
When we run the above program, we get the following output −
As you can see the parts meeting the criteria in grammar are left out from the Noun phrases as separate chunks. This process of extracting text not in the required chunk is called chinking.

    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
Math.Abs() Method in C#

The Math.Abs() method in C# is used to return the absolute value of a specified number in C#. This specified number can be decimal, double, 16-bit signed integer, etc.
Let us now see an example to implement the Math.abs() method to return the absolute value of double number −
using System;
class Demo {
   public static void Main(){
      Double val1 = 30.40;
      Double val2 = Double.MinValue;
      Double val3 = Double.MaxValue;
      Console.WriteLine("Absolute value of {0} : {1}", val1, Math.Abs(val1));
      Console.WriteLine("Absolute value of {0} : {1}", val2, Math.Abs(val2));
      Console.WriteLine("Absolute value of {0} : {1}", val3, Math.Abs(val3));
   }
}
This will produce the following output −
Absolute value of 30.4 : 30.4
Absolute value of -1.79769313486232E+308 : 1.79769313486232E+308
Absolute value of 1.79769313486232E+308 : 1.79769313486232E+308
Let us now see another example to implement the Math.abs() method to return the absolute value of 16-bit signed integer −
using System;
class Demo {
   public static void Main(){
      short val1 = -300;
      short val2 = Int16.MaxValue;
      short val3 = 0;
      Console.WriteLine("Absolute value of {0} : {1}", val1, Math.Abs(val1));
      Console.WriteLine("Absolute value of {0} : {1}" val2, Math.Abs(val2));
      Console.WriteLine("Absolute value of {0} : {1}", val3, Math.Abs(val3));
   }
}
This will produce the following output −
Absolute value of -300 : 300
Absolute value of 32767 : 32767
Absolute value of 0 : 0
MongoDB - Projection

In MongoDB, projection means selecting only the necessary data rather than selecting whole of the data of a document. If a document has 5 fields and you need to show only 3, then select only 3 fields from them.
MongoDB's find() method, explained in MongoDB Query Document accepts second optional parameter that is list of fields that you want to retrieve. In MongoDB, when you execute find() method, then it displays all fields of a document. To limit this, you need to set a list of fields with value 1 or 0. 1 is used to show the field while 0 is used to hide the fields.
The basic syntax of find() method with projection is as follows −
>db.COLLECTION_NAME.find({},{KEY:1})

Consider the collection mycol has the following data −
{_id : ObjectId("507f191e810c19729de860e1"), title: "MongoDB Overview"},
{_id : ObjectId("507f191e810c19729de860e2"), title: "NoSQL Overview"},
{_id : ObjectId("507f191e810c19729de860e3"), title: "Tutorials Point Overview"}
Following example will display the title of the document while querying the document.
>db.mycol.find({},{"title":1,_id:0})
{"title":"MongoDB Overview"}
{"title":"NoSQL Overview"}
{"title":"Tutorials Point Overview"}
>
Please note _id field is always displayed while executing find() method, if you don't want this field, then you need to set it as 0.

    44 Lectures 
     3 hours 

 Arnab Chakraborty

    54 Lectures 
     5.5 hours 

 Eduonix Learning Solutions

    44 Lectures 
     4.5 hours 

 Kaushik Roy Chowdhury

    40 Lectures 
     2.5 hours 

 University Code

    26 Lectures 
     8 hours 

 Bassir Jafarzadeh

    70 Lectures 
     2.5 hours 

 Skillbakerystudios
 Print
 Add Notes
 Bookmark this page
Teradata - SubQueries

A subquery returns records from one table based on the values from another table. It is a SELECT query within another query. The SELECT query called as inner query is executed first and the result is used by the outer query. Some of its salient features are −
A query can have multiple subqueries and subqueries may contain another subquery.
A query can have multiple subqueries and subqueries may contain another subquery.
Subqueries doesn't return duplicate records.
Subqueries doesn't return duplicate records.
If subquery returns only one value, you can use = operator to use it with the outer query. If it returns multiple values you can use IN or NOT IN.
If subquery returns only one value, you can use = operator to use it with the outer query. If it returns multiple values you can use IN or NOT IN.
Following is the generic syntax of subqueries.
SELECT col1, col2, col3,... 
FROM  
Outer Table 
WHERE col1 OPERATOR ( Inner SELECT Query);

Consider the following Salary table.
The following query identifies the employee number with highest salary. The inner SELECT performs the aggregation function to return the maximum NetPay value and the outer SELECT query uses this value to return the employee record with this value.
SELECT EmployeeNo, NetPay 
FROM Salary 
WHERE NetPay =  
(SELECT MAX(NetPay)  
FROM Salary);
When this query is executed, it produces the following output.
*** Query completed. One row found. 2 columns returned. 
*** Total elapsed time was 1 second.  
 EmployeeNo     NetPay 
-----------  ----------- 
    103         83000 

 Print
 Add Notes
 Bookmark this page
Difference between normal links and active links - GeeksforGeeks

10 Oct, 2021
Websites are designed to point you to different resources. You can move from one website to another through links. Links help you to get information from different resources. Links are established in simple HTML web pages through <a> tag.Links are categorized into three types. Typically a Link is displayed in three different colors based on the usage.
Normal links (Unvisited links)
Visited links
Active links
Example 1: The following example shows the basic example for Normal Link ( Unvisited Link ). If you want to create a link to go to “https://www.geeksforgeeks.org/“, you can get the normal link through this code. The default color is blue color and underlined but you can apply your own custom styling according to the application’s need.
HTML
<!DOCTYPE html><html>  <body>    <h2>This is a Link</h2>    <h1>        Welcome to        <a href="https://www.geeksforgeeks.org/">            GeeksforGeeks        </a>    </h1></body>  </html>
Output:                        
Visited Link: In example 1, If you click on the link shown above and again go back to the link page, you can now see the link is in purple color and underlined. It shows that the user has visited this link before. You can do your own custom styling using CSS :visited selector. In the above output, notice the visited link after going back from the home page.
Active Link: In example 1, If you left or right-click any one of the links Visited or Unvisited, it will turn into Red and Underline. Active Links shows that the browser is in the process to load a new resource.  You can do your own custom styling using CSS :active selector. In the above output, notice the active link on right-click of the link.
The <a> tag is supported in almost all browsers. So, these are the 3 types of links with their different usages and default stylings. This helps the user to navigate through different resources. 
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
HTML-Questions
HTML-Tags
Picked
Difference Between
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Difference between Prim's and Kruskal's algorithm for MST
Difference between Internal and External fragmentation
Differences and Applications of List, Tuple, Set and Dictionary in Python
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to set the default value for an HTML <select> element ?
How to update Node.js and NPM to next version ?
How to set input type date in dd-mm-yyyy format using HTML ?
C++ Program to Convert Binary Number to Decimal and vice-versa

In a computer system, the binary number is expressed in the binary numeral system while the decimal number is in the decimal numeral system. The binary number is in base 2 while the decimal number is in base 10.
Examples of decimal numbers and their corresponding binary numbers are as follows −
A program that converts the binary numbers into decimal and the decimal numbers into binary is as follows.
 Live Demo
#include <iostream>
using namespace std;
void DecimalToBinary(int n) {
   int binaryNumber[100], num=n;
   int i = 0;
   while (n > 0) {
      binaryNumber[i] = n % 2;
      n = n / 2;
      i++;
   }
   cout<<"Binary form of "<<num<<" is ";
   for (int j = i - 1; j >= 0; j--)
      cout << binaryNumber[j];
   cout<<endl;
}
int BinaryToDecimal(int n) {
   int decimalNumber = 0;
   int base = 1;
   int temp = n;
   while (temp) {
      int lastDigit = temp % 10;
      temp = temp/10;
      decimalNumber += lastDigit*base;
      base = base*2;
   }
   cout<<"Decimal form of "<<n<<" is "<<decimalNumber<<endl;;
}
int main() {
   DecimalToBinary(23);
   BinaryToDecimal(10101);
   return 0;
}
Binary form of 23 is 10111
Decimal form of 10101 is 21
In the program given above, there are two functions DecimalToBinary and BinaryToDecimal. These convert the number from decimal to binary and binary to decimal respectively.
In the DecimalToBinary function, the binary value of the decimal number n is stored in the array binaryNumber[]. A while loop is used and the result of the n modulus 2 operation is stored in binaryNumber[] for each iteration of the loop. This is shown using the following code snippet.
while (n > 0) {
   binaryNumber[i] = n % 2;
   n = n / 2;
   i++;
}
After this, the binary number is displayed using a for loop. This is shown as follows.
cout<<"Binary form of "<<num<<" is ";
for (int j = i - 1; j >= 0; j--)
cout << binaryNumber[j];
In the function, BinaryToDecimal(), a while loop is used to convert the binary number into decimal number. The LastDigit contains the last bit of the temp variable. The base contains the base value such as 2, 4, 6, 8 etc. The DecimalNumber contains the sum of the previous DecimalNumber value and the product of the LastDigit and base.
All this is demonstrated using the following code snippet −
while (temp) {
   int lastDigit = temp % 10;
   temp = temp/10;
   decimalNumber += lastDigit*base;
   base = base*2;
}
In the main() function, the DecimalToBinary() and BinaryToDecimal() functions are called. This is shown as follows.
DecimalToBinary(23);
BinaryToDecimal(10101);
C library macro - va_arg()

The C library macro type va_arg(va_list ap, type) retrieves the next argument in the parameter list of the function with type. This does not determine whether the retrieved argument is the last argument passed to the function.
Following is the declaration for va_arg() macro.
type va_arg(va_list ap, type)
ap − This is the object of type va_list with information about the additional arguments and their retrieval state. This object should be initialized by an initial call to va_start before the first call to va_arg.
ap − This is the object of type va_list with information about the additional arguments and their retrieval state. This object should be initialized by an initial call to va_start before the first call to va_arg.
type − This is a type name. This type name is used as the type of the expression, this macro expands to.
type − This is a type name. This type name is used as the type of the expression, this macro expands to.
This macro returns the next additional argument as an expression of type type.
The following example shows the usage of va_arg() macro.
#include <stdarg.h>
#include <stdio.h>

int sum(int, ...);

int main () {
   printf("Sum of 15 and 56 = %d\n",  sum(2, 15, 56) );
   return 0;
}

int sum(int num_args, ...) {
   int val = 0;
   va_list ap;
   int i;

   va_start(ap, num_args);
   for(i = 0; i < num_args; i++) {
      val += va_arg(ap, int);
   }
   va_end(ap);
 
   return val;
}
Let us compile and run the above program to produce the following result −
Sum of 15 and 56 = 71


    12 Lectures 
     2 hours 

 Nishant Malik

    12 Lectures 
     2.5 hours 

 Nishant Malik

    48 Lectures 
     6.5 hours 

 Asif Hussain

    12 Lectures 
     2 hours 

 Richa Maheshwari

    20 Lectures 
     3.5 hours 

 Vandana Annavaram

    44 Lectures 
     1 hours 

 Amit Diwan
 Print
 Add Notes
 Bookmark this page
How to convert an integer to string with padding zero in C#?

There are several ways to convert an integer to a string in C#.
PadLeft − Returns a new string of a specified length in which the beginning of the current string is padded with spaces or with a specified Unicode character
ToString − Returns a string that represents the current object.
String Interpolation − The $ special character identifies a string literal as an interpolated string. This feature is available starting with C# 6.
Example using string padding−
 Live Demo
using System;
namespace DemoApplication{
   class Program{
      public static void Main(){
         int number = 5;
         Console.WriteLine("Number: {0}", number);
         var numberString = number.ToString().PadLeft(4, '0');
         Console.WriteLine("Padded String: {0}", numberString);
         Console.ReadLine();
      }
   }
}
The output of the above code is
Number: 5
Padded String: 0005
Example using explicit form −
 Live Demo
using System;
namespace DemoApplication{
   class Program{
      public static void Main(){
         int number = 5;
         Console.WriteLine("Number: {0}", number);
         var numberString = number.ToString("0000");
         Console.WriteLine("Padded String: {0}", numberString);
         Console.ReadLine();
      }
   }
}
The output of the above code is
Number: 5
Padded String: 0005
Example using short form format specifier −
 Live Demo
using System;
namespace DemoApplication{
   class Program{
      public static void Main(){
         int number = 5;
         Console.WriteLine("Number: {0}", number);
         var numberString = number.ToString("D4");
         Console.WriteLine("Padded String: {0}", numberString);
         Console.ReadLine();
      }
   }
}
The output of the above code is
Number: 5
Padded String: 0005
Example using string interpolation−
 Live Demo
using System;
namespace DemoApplication{
   class Program{
      public static void Main(){
         int number = 5;
         Console.WriteLine("Number: {0}", number);
         var numberString = $"{number:0000}";
         Console.WriteLine("Padded String: {0}", numberString);
         Console.ReadLine();
      }
   }
}
The output of the above code is
Number: 5
Padded String: 0005
How to use an enum with switch case in Java?


Enumeration (enum) in Java is a datatype which stores a set of constant values. You can use enumerations to store fixed values such as days in a week, months in a year etc.
enum Days {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}
You can also define an enumeration with custom values to the constants declared. But you need to have an instance variable, a constructor and getter method to return values.
Let us create an enum with 5 constants representing models of 5 different scoters with their prices as values, as shown below −
enum Scoters {
   //Constants with values
   ACTIVA125(80000), ACTIVA5G(70000), ACCESS125(75000), VESPA(90000), TVSJUPITER(75000);
   //Instance variable
   private int price;
   //Constructor to initialize the instance variable
   Scoters(int price) {
      this.price = price;
   }
   //Static method to display the price
   public static void getPrice(int model){
      Scoters constants[] = Scoters.values();
      System.out.println("Price of: "+constants[model]+" is "+constants[model].price);
   }
}
Following Java program retrieves the prices of all the vehicles using switch case.
public class EnumExample {
   Scoters sc;

   public EnumExample(Scoters sc) {
      this.sc = sc;
   }

   public void displayPrice() {
      switch (sc) {
         case Activa125:
            Scoters.getPrice(0);
            break;
         case Activa5G:
            Scoters.getPrice(1);
            break;
         case Access125:
            Scoters.getPrice(2);
            break;
         case Vespa:
            Scoters.getPrice(3);
            break;
         case TVSJupiter:
            Scoters.getPrice(4);
            break;
         default:
            System.out.println("Model not found");
            break;
      }
   }
   public static void main(String args[]) {
      EnumExample activa125 = new EnumExample(Scoters.ACTIVA125);
      activa125.displayPrice();
      EnumExample activa5G = new EnumExample(Scoters.ACTIVA5G);
      activa5G.displayPrice();
      EnumExample access125 = new EnumExample(Scoters.ACCESS125);
      access125.displayPrice();
      EnumExample vespa = new EnumExample(Scoters.VESPA);
      vespa.displayPrice();
      EnumExample tvsJupiter = new EnumExample(Scoters.TVSJUPITER);
      tvsJupiter.displayPrice();
   }
}
Price of: ACTIVA125 is 80000
Price of: ACTIVA5G is 70000
Price of: ACCESS125 is 75000
Price of: VESPA is 90000
Price of: TVSJUPITER is 75000
java.lang.Math.atan2() in Java

20 Jun, 2021
atan2() is an inbuilt method in Java that is used to return the theta component from the polar coordinate. The atan2() method returns a numeric value between –and representing the angle of a (x, y) point and the positive x-axis. It is the counterclockwise angle, measured in radian, between the positive X-axis, and the point (x, y). Syntax :  
Math.atan2(double y, double x)
where, x and y are X and Y coordinates in double data type.
Returns : It returns a double value. The double value is from polar coordinate (r, theta). Example: Program demonstrating the atan2() method  
Java
// Java program for implementation of// atan2() methodimport java.util.*;class GFG {     // Driver Code    public static void main(String args[])    {         // X and Y coordinates        double x = 90.0;        double y = 15.0;         // theta value from polar coordinate (r, theta)        double theta = Math.atan2(y, x);         System.out.println(theta);    }}
0.16514867741462683

mmarsland
Java-lang package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to check pointer or interface is nil or not in Golang?

10 May, 2020
In Golang, nil check is frequently seen in GoLang code especially for error check. In most cases, nil check is straight forward, but in interface case, it’s a bit different and special care needs to be taken.
Here the task is to check pointer or interface is nil or not in Golang, you can check with the following:
Example 1: In this example, the pointer is checked whether it is a nil pointer or not.
// Go program to illustrate how to// check pointer is nil or not  package main  import (    "fmt")  type Temp struct {}  func main() {    var pnt *Temp // pointer    var x = "123"    var pnt1 *string = &x      fmt.Printf("pnt is a nil pointer: %v\n", pnt == nil)    fmt.Printf("pnt1 is a nil pointer: %v\n", pnt1 == nil)}
Output:
pnt is a nil pointer: true
pnt1 is a nil pointer: false

Example 2: In this example, the interface is checked whether it is a nil interface or not.
// Go program to illustrate how to// check interface is nil or not  package main  import (    "fmt")  // Creating an interfacetype tank interface {      // Methods    Tarea() float64    Volume() float64}  type myvalue struct {    radius float64    height float64}  // Implementing methods of// the tank interfacefunc (m myvalue) Tarea() float64 {      return 2*m.radius*m.height +        2*3.14*m.radius*m.radius}  func (m myvalue) Volume() float64 {      return 3.14 * m.radius * m.radius * m.height}  func main() {      var t tank    fmt.Printf("t is a nil interface: %v\n", t == nil)      t = myvalue{10, 14}      fmt.Printf("t is a nil interface: %v\n", t == nil)  }
Output:
t is a nil interface: true
t is a nil interface: false

Example 3: In this example, the interface holding a nil pointer is checked whether it is a nil interface or not.
// Go program to illustrate how to// check interface holding a nil// pointer is nil or not  package main  import (    "fmt")  type Temp struct {}  func main() {      // taking a pointer    var val *Temp      // taking a interface    var val2 interface{}      // val2 is a non-nil interface    // holding a nil pointer (val)    val2 = val      fmt.Printf("val2 is a nil interface: %v\n", val2 == nil)      fmt.Printf("val2 is a interface holding a nil"+            " pointer: %v\n", val2 == (*Temp)(nil))}
Output:
val2 is a nil interface: false
val2 is a interface holding a nil pointer: true

Golang-Interfaces
Golang-Pointers
Golang-Program
Picked
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
CMSmap – Open Source CMS Scanner

14 Sep, 2021
CMSmap is a Python open source CMS scanner that automates the method of detecting security flaws of the foremost popular CMSs. The main purpose of this tool is to integrate common vulnerabilities for different types of CMSs into a single tool. at the instant, there’s support for WordPress, Joomla, Drupal, and Moodle. CMSmap tool is freely available on GitHub. CMSmap tool supports multiple target domain scanning and saves the results in text file format. CMSmap tool has the ability to set custom user-agent and header. CMSmap tool Support for SSL encryption. CMSmap tool supports Verbose mode for debugging purposes.
Note: Make Sure You have Python Installed on your System, as this is a python-based tool. Click to check the Installation process: Python Installation Steps on Linux
Step 1: Use the following command to install the tool in your Kali Linux operating system.
git clone https://github.com/Dionach/CMSmap.git
Step 2: Now use the following command to move into the directory of the tool. You have to move in the directory in order to run the tool.
cd CMSmap 
Step 3: You are in the directory of the CMSmap. Now run the following command to complete the installation.
sudo python3 setup.py install
Step 4: All the dependencies have been installed in your Kali Linux operating system. Now use the following command to run the tool and check the help section.
python3 cmsmap .py -h
Example 1: Simple Scan (Single Target)
python3 cmsmap.py https://geeksforgeeks.org
In this Example, We are performing simple scanning on the target domain geeksforgeeks.org.
We have got the details of CMS and the theme applied to the domain.
The tool has identified the WordPress usernames on geeksforgeeks.org.
Example 2: Force scan WordPress
python3 cmsmap.py https://geeksforgeeks.org -f W -F --noedb -d
In this Example, We are performing a Force scan of WordPress CMS on geeksforgeeks.org.
Example 3: Scan multiple targets listed in a given file
python3 cmsmap.py -i targets.txt -o output.txt -f D
In this Example, We are scanning multiple target domains specified in the targets.txt file.
Example 4: Verbose Mode
python3 cmsmap.py https://geeksforgeeks.org -v
In this Example, We are displaying the scan results in a more detailed way. We have used the -v tag for enabling the verbose mode.
Kali-Linux
Linux-Tools
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Docker - COPY Instruction
scp command in Linux with Examples
chown command in Linux with Examples
SED command in Linux | Set 2
mv command in Linux with examples
nohup Command in Linux with Examples
chmod command in Linux with examples
Introduction to Linux Operating System
Array Basics in Shell Scripting | Set 1
Basic Operators in Shell Scripting
Union process in DFA

20 Nov, 2019
Prerequisite – Designing finite automataLet’s understand the Union process in Deterministic Finite Automata (DFA) with the help of below example.
Designing a DFA for the set of string over {a, b} such that string of the language start and end with different symbols. There two desired language will be formed:
L1 = {ab, aab, aabab, .......}
L2 = {ba, bba, bbaba, .......} 
L1= {starts with a and ends with b } and L2= {starts with b and ends with a}.Then L= L1 ∪ L2 or L=L1 + L2
State Transition Diagram for the language L1:This DFA accepts all the string starting with a and ending with b. Here, State A is initial state and state C is final state.
State Transition Diagram for the language L2:This DFA accepts all the string starting with b and ending with a. Here, State A is initial state and state C is final state.
Now, Taking the union of L1 and L2 language which gives the final result of the language which starts and end with different elements.State Transition Diagram of L1 ∪ L2:Thus as we see that L1 and L2 have been combined through union process and this final DFA accept all the language containing strings starting and ending with a different symbols.Note: From above example we can also infer that regular languages are closed under union(i.e Union of two regular languages is also regular).
VaibhavRai3
HasanBadran
GATE CS
Theory of Computation & Automata
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Mutual exclusion in distributed system
Three address code in Compiler
S - attributed and L - attributed SDTs in Syntax directed translation
Types of Operating Systems
Code Optimization in Compiler Design
Difference between DFA and NFA
Boyer-Moore Majority Voting Algorithm
Variation of Turing Machine
Design 101 sequence detector (Mealy machine)
Post Correspondence Problem
Python | Merge, Join and Concatenate DataFrames using Panda

19 Jun, 2018
A dataframe is a two-dimensional data structure having multiple rows and columns. In a dataframe, the data is aligned in the form of rows and columns only. A dataframe can perform arithmetic as well as conditional operations. It has mutable size.
Below is the implementation using Numpy and Pandas.
Modules needed:
import numpy as np
import pandas as pd

 
# Python program to concatenate# dataframes using Panda  # Creating first dataframedf1 = pd.DataFrame({'A': ['A0', 'A1', 'A2', 'A3'],                    'B': ['B0', 'B1', 'B2', 'B3'],                    'C': ['C0', 'C1', 'C2', 'C3'],                    'D': ['D0', 'D1', 'D2', 'D3']},                    index = [0, 1, 2, 3])  # Creating second dataframedf2 = pd.DataFrame({'A': ['A4', 'A5', 'A6', 'A7'],                    'B': ['B4', 'B5', 'B6', 'B7'],                    'C': ['C4', 'C5', 'C6', 'C7'],                    'D': ['D4', 'D5', 'D6', 'D7']},                    index = [4, 5, 6, 7])  # Creating third dataframedf3 = pd.DataFrame({'A': ['A8', 'A9', 'A10', 'A11'],                    'B': ['B8', 'B9', 'B10', 'B11'],                    'C': ['C8', 'C9', 'C10', 'C11'],                    'D': ['D8', 'D9', 'D10', 'D11']},                    index = [8, 9, 10, 11])  # Concatenating the dataframespd.concat([df1, df2, df3])
Output:
Code #2 : DataFrames MergePandas provides a single function, merge(), as the entry point for all standard database join operations between DataFrame objects.
# Python program to merge# dataframes using Panda  # Dataframe createdleft = pd.DataFrame({'Key': ['K0', 'K1', 'K2', 'K3'],                    'A': ['A0', 'A1', 'A2', 'A3'],                    'B': ['B0', 'B1', 'B2', 'B3']})  right = pd.DataFrame({'Key': ['K0', 'K1', 'K2', 'K3'],                      'C': ['C0', 'C1', 'C2', 'C3'],                      'D': ['D0', 'D1', 'D2', 'D3']})                        # Merging the dataframes                      pd.merge(left, right, how ='inner', on ='Key')
Output:
 Code #3 : DataFrames Join
# Python program to join# dataframes using Panda  left = pd.DataFrame({'A': ['A0', 'A1', 'A2', 'A3'],                    'B': ['B0', 'B1', 'B2', 'B3']},                    index = ['K0', 'K1', 'K2', 'K3'])  right = pd.DataFrame({'C': ['C0', 'C1', 'C2', 'C3'],                      'D': ['D0', 'D1', 'D2', 'D3']},                      index = ['K0', 'K1', 'K2', 'K3'])                        # Joining the dataframes                      left.join(right)
Output:
python-modules
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
map emplace() in C++ STL

22 Mar, 2022
The map::emplace() is a built-in function in C++ STL which inserts the key and its element in the map container. It effectively increases the container size by one. If the same key is emplaced more than once, the map stores the first element only as the map is a container which does not store multiple keys of the same value. Syntax:  
map_name.emplace(key, element)
Parameters: The function accepts two mandatory parameters which are described below:  
key – specifies the key to be inserted in the multimap container.
element – specifies the element to the key which is to be inserted in the map container.
Return Value: The function returns a pair consisting of an iterator and a bool value. (Iterator of the position it inserted/found the key,Bool value indicating the success/failure of the insertion.)  
CPP
// C++ program for the illustration of// map::emplace() function#include <bits/stdc++.h>using namespace std; int main(){     // initialize container    map<int, int> mp;     // insert elements in random order    mp.emplace(2, 30);    mp.emplace(1, 40);    mp.emplace(2, 20);    mp.emplace(1, 50);    mp.emplace(4, 50);     // prints the elements    cout << "\nThe map is : \n";    cout << "KEY\tELEMENT\n";    for (auto itr = mp.begin(); itr != mp.end(); itr++)        cout << itr->first << "\t" << itr->second << endl;     return 0;}
The map is : 
KEY    ELEMENT
1    40
2    30
4    50
 
avishekmukhopadhyay76
CPP-Functions
cpp-map
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Bitwise Operators in C/C++
vector erase() and clear() in C++
Inheritance in C++
Priority Queue in C++ Standard Template Library (STL)
Substring in C++
The C++ Standard Template Library (STL)
Object Oriented Programming in C++
C++ Classes and Objects
Sorting a vector in C++
2D Vector In C++ With User Defined Size
GATE | GATE CS 2012 | Question 65

22 Jul, 2021
Consider the 3 processes, P1, P2 and P3 shown in the table.
Process           Arrival time         Time Units Required
   P1                0                         5
   P2                1                         7
   P3                3                         4
The completion order of the 3 processes under the policies FCFS and RR2 (round robin scheduling with CPU quantum of 2 time units) are(A)
FCFS: P1, P2, P3
 RR2: P1, P2, P3
(B)
 FCFS: P1, P3, P2
 RR2: P1, P3, P2
(C)
FCFS: P1, P2, P3
 RR2: P1, P3, P2
(D)
FCFS: P1, P3, P2 
RR2: P1, P2, P3
Answer: (C)Explanation:
FCFS is clear.  

In RR, time slot is of 2 units.  

Processes are assigned in following order
p1, p2, p1, p3, p2, p1, p3, p2, p2

This question involves the concept of ready queue. At t=2, p2 starts and p1 is sent to the ready queue and at t=3 p3 arrives so then the job p3 is queued in ready queue after p1. So at t=4, again p1 is executed then p3 is executed for first time at t=6.
Watch GeeksforGeeks Video Explanation :
CPU Scheduling GATE Previous Year Questions Part-II with Viomesh Singh - YouTubeGeeksforGeeks GATE Computer Science17.5K subscribersCPU Scheduling GATE Previous Year Questions Part-II with Viomesh SinghWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:002:16 / 49:57•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=maVQoJuMAlM" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question
GATE-CS-2012
GATE-GATE CS 2012
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.