code-rag-bench/online-tutorials huggingface dataset:
is_empty template in C++ - GeeksforGeeks

19 Nov, 2018
The std::is_empty template of C++ STL is used to check whether the given type is empty or not. This method returns a boolean value showing whether the given type is empty or not.
Syntax:
template < class T > struct is_empty;

Parameters: This template contains single parameter T (Trait class) that identifies whether T is a empty type.
Return Value: This template returns a boolean value as shown below:
True: if the type is a empty.
False: if the type is not empty.
Below programs illustrate the std::is_empty template in C++ STL:
Program 1: Using Structs
// C++ program to illustrate// std::is_empty template  #include <iostream>#include <type_traits>using namespace std;  // empty structstruct GFG1 {};  // struct with local variablestruct GFG2 {    int variab;};  // Struct with global variablestruct GFG3 {    static int variab;};  // Struct with virtual destructorstruct GFG4 {    virtual ~GFG4();};  // Driver codeint main(){    cout << boolalpha;      cout << "Is GFG1 empty: "         << is_empty<GFG1>::value         << '\n';    cout << "Is GFG2 empty: "         << is_empty<GFG2>::value         << '\n';    cout << "Is GFG3 empty: "         << is_empty<GFG3>::value         << '\n';    cout << "Is GFG4 empty: "         << is_empty<GFG4>::value         << '\n';      return 0;}
Is GFG1 empty: true
Is GFG2 empty: false
Is GFG3 empty: true
Is GFG4 empty: false

Program 2: Using classes
// C++ program to illustrate// std::is_empty template  #include <iostream>#include <type_traits>using namespace std;  // empty classclass GFG1 {};  // class with local variableclass GFG2 {    int variab;};  // class with global variableclass GFG3 {    static int variab;};  // class with virtual destructorclass GFG4 {    virtual ~GFG4();};  int main(){    cout << boolalpha;    cout << "Is GFG1 empty: "         << is_empty<GFG1>::value         << '\n';    cout << "Is GFG2 empty: "         << is_empty<GFG2>::value         << '\n';    cout << "Is GFG3 empty: "         << is_empty<GFG3>::value         << '\n';    cout << "Is GFG4 empty: "         << is_empty<GFG4>::value         << '\n';      return 0;}
Is GFG1 empty: true
Is GFG2 empty: false
Is GFG3 empty: true
Is GFG4 empty: false

STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Polymorphism in C++
Sorting a vector in C++
Friend class and function in C++
std::string class in C++
Pair in C++ Standard Template Library (STL)
Queue in C++ Standard Template Library (STL)
Inline Functions in C++
Array of Strings in C++ (5 Different Ways to Create)
Convert string to char array in C++
Scala Varargs - GeeksforGeeks

28 May, 2019
Most of the programming languages provide us variable length argument mobility to a function, Scala is not a exception. it allows us to indicate that the last argument of the function is a variable length argument. it may be repeated multiple times. It allows us to indicate that last argument of a function is a variable length argument, so it may be repeated multiple times. we can pass as many argument as we want. This allows programmers to pass variable length argument lists to the function. Inside function, the type of args inside the declared are actually saved as a Array[Datatype] for example can be declared as type String* is actually Array[String].Note :- We place * on the last argument to make it variable length.Syntax : –

def Nameoffunction(args: Int *) : Int = { s foreach println. }

Below are some restrictions of varargs :
The last parameter in the list must be the repeating argument.def sum(a :Int, b :Int, args: Int *)
No default values for any parameters in the method containing the varargs.
All values must be same data type otherwise error.> sum(5, 3, 1000, 2000, 3000, "one")> error: type mismatch;found : String("one")required: Int
Inside the body args is an array, so all values are packed into an array
Example :
// Scala program of varargsobject GFG {           // Driver code    def main(args: Array[String])    {                       // Calling the function         println("Sum is: " + sum(5, 3, 1000, 2000, 3000));     }                 // declaration and definition of function     def sum(a :Int, b :Int, args: Int *) : Int =    {        var result = a + b              for(arg <- args)        {            result += arg        }              return result    }} 
Output :
Sum is: 6008
In above example we can see the last argument of the function is a variable length argument. here 1000 is variable length argument. argument arg is added to the result variable. the names argument is of type Integer.Example :
// Scala program of varargsobject GFG{     // Driver code    def main(args: Array[String])     {              // calling of function             printGeek("Geeks", "for", "geeks")      }      // declaration and definition of function    def printGeek(strings: String*)     {        strings.map(println)    }  } 
Output :
Geeks
for
geeks

In above example as we have defined it using the * syntax so it is a variable argument. the names argument is of type String.
Picked
Scala
Scala-Method
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
For Loop in Scala
Scala | flatMap Method
Scala | map() method
Scala List filter() method with example
Scala | reduce() Function
String concatenation in Scala
Type Casting in Scala
Scala Tutorial – Learn Scala with Step By Step Guide
Scala List contains() method with example
Scala String substring() method with example
PyQt5 – How to change color of the label ? - GeeksforGeeks

26 Mar, 2020
While creating a Label in PyQt5, we can see that there is no background color. In this article we will see how to add background color to the Label.
In order to add border to the Label we will use label.setStyleSheet() method, this will add the background color to the label, it is same like designing the CSS style sheet.
Syntax : label.setStyleSheet(“background-color: cyan”)
Argument : It takes string as argument.
Action performed: It changes the background color of the label.
Code :
# importing the required libraries  from PyQt5.QtWidgets import * from PyQt5.QtGui import * import sys    class Window(QMainWindow):    def __init__(self):        super().__init__()          # set the title        self.setWindowTitle("Label")          # setting  the geometry of window        self.setGeometry(0, 0, 400, 300)          # creating a label widget        # by default label will display at top left corner        self.label_1 = QLabel('Light green', self)          # moving position        self.label_1.move(100, 100)          # setting up background color        self.label_1.setStyleSheet("background-color: lightgreen")          # creating a label widget        # by default label will display at top left corner        self.label_2 = QLabel('Yellow', self)                  # moving position        self.label_2.move(100, 150)          # setting up background color and border        self.label_2.setStyleSheet("background-color: yellow;                                     border: 1px solid black;")          # show all the widgets        self.show()    # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()# start the appsys.exit(App.exec())
Output :
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
*args and **kwargs in Python
Create a Pandas DataFrame from Lists
Check if element exists in list in Python
Convert integer to string in Python
How To Convert Python Dictionary To JSON?
sum() function in Python
isupper(), islower(), lower(), upper() in Python and their applications
Python Classes and Objects
tty command in Linux with examples

19 Feb, 2021
Linux operating system represents everything in a file system, the hardware devices that we attach are also represented as a file. The terminal is also represented as a file. There a command exists called tty which displays information related to terminal. The tty command of terminal basically prints the file name of the terminal connected to standard input. tty is short of teletype, but popularly known as a terminal it allows you to interact with the system by passing on the data (you input) to the system, and displaying the output produced by the system.
Syntax:
tty [OPTION]....
Options:
-s, ––silent, ––quiet : Prints nothing, only returns an exit status.
––help : It will display the help message and exit.
––version : Prints the version information and exits.
Linux Tutorials | About the user and the terminal | GeeksforGeeks - YouTubeGeeksforGeeks532K subscribersLinux Tutorials | About the user and the terminal | GeeksforGeeksWatch 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:001:40 / 2:30•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=WnjofnvIIvg" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
linux-command
Linux-misc-commands
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sorting an array by date in JavaScript

Suppose, we have an array of objects like this −
const arr = [{id: 1, date: 'Mar 12 2012 10:00:00 AM'}, {id: 2, date: 'Mar 8 2012 08:00:00 AM'}];
We are required to write a JavaScript function that takes in one such array and sorts the array according to the date property of each object.
(Either newest first or oldest first).
The approach should be to convert these into JS Date Object and compare their timestamps to sort the array.
The code for this will be −
const arr = [{id: 1, date: 'Mar 12 2012 10:00:00 AM'}, {id: 2, date: 'Mar 8 2012 08:00:00 AM'}];
const sortByDate = arr => {
   const sorter = (a, b) => {
      return new Date(a.date).getTime() - new Date(b.date).getTime();
   }
   arr.sort(sorter);
};
sortByDate(arr);
console.log(arr);
And the output in the console will be −
[
   { id: 2, date: 'Mar 8 2012 08:00:00 AM' },
   { id: 1, date: 'Mar 12 2012 10:00:00 AM' }
]
CSS - widows

The widows property is used in paged media to control line breaks by specifying the minimum number of lines in a paragraph that should be left at the top of the page.
integer − Any length unit. Negative length values are not permitted for this property.
integer − Any length unit. Negative length values are not permitted for this property.
All the Block level elements.
object.style.widows = "5";

Here is the example to create 4 lines at the bottom and 3 lines at the top of each page −
<style type = "text/css">
   <!--
      @page{orphans:4; widows:2;}
   -->
</style>

    33 Lectures 
     2.5 hours 

 Anadi Sharma

    26 Lectures 
     2.5 hours 

 Frahaan Hussain

    44 Lectures 
     4.5 hours 

 DigiFisk (Programming Is Fun)

    21 Lectures 
     2.5 hours 

 DigiFisk (Programming Is Fun)

    51 Lectures 
     7.5 hours 

 DigiFisk (Programming Is Fun)

    52 Lectures 
     4 hours 

 DigiFisk (Programming Is Fun)
 Print
 Add Notes
 Bookmark this page
Create a block element with Bootstrap 4

To create a block element, use the .d-block Bootstrap 4 class.
Use the d-block class −
<span class="d-block bg-info">
  A block
</span>
To set blocks for difference screen sizes, use the .d-*-block −
<span class="d-md-block bg-info">
  A block for medium screen size
</span>
Let us see an example to learn how to create block element −
Live Demo
<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Bootstrap Example</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
  </head>

<body>

  <div class="container mt-3">
    <h2>Blocks</h2>
    <p>Resize the browser to check the effect</p>
    <span class="d-block bg-info">
      A block
    </span>
    <span class="d-md-block bg-info">
      A block for medium screen size
    </span>
  </div>

</body>
</html>
How can we add a JSONArray to JSONObject in Java?

The JSON is a text-based format for exchanging data. It is a lightweight component and language independent. We can also add a JSONArray to JSONObject. We need to add a few items to an ArrayList first and pass this list to the put() method of JSONArray class and finally add this array to JSONObject using the put() method. 
import org.json.*;
import java.util.*;
public class AddJSONArrayToJSONObjTest {
   public static void main(String args[]) {
      List<String> list = new ArrayList<String>();
      list.add("Raja");
      list.add("Jai");
      list.add("Adithya");
      JSONArray array = new JSONArray();
      for(int i = 0; i < list.size(); i++) {
         array.put(list.get(i));
      }
      JSONObject obj = new JSONObject();
      try {
         obj.put("Employee Names:", array);
      } catch(JSONException e) {
         e.printStackTrace();
      }
      System.out.println(obj.toString());
   }
}
{"Employee Names:":["Raja","Jai","Adithya"]}
What is the purpose of a function prototype? - GeeksforGeeks

07 Oct, 2021
The Function prototype serves the following purposes – 1) It tells the return type of the data that the function will return. 2) It tells the number of arguments passed to the function. 3) It tells the data types of each of the passed arguments. 4) Also it tells the order in which the arguments are passed to the function.Therefore essentially, the function prototype specifies the input/output interlace to the function i.e. what to give to the function and what to expect from the function.The prototype of a function is also called the signature of the function.What if one doesn’t specify the function prototype? The output of the below kinds of programs is generally asked at many places.  
c
int main(){   foo();   getchar();   return 0;}void foo(){   printf("foo called");}
If one doesn’t specify the function prototype, the behavior is specific to the C standard (either C90 or C99) that the compilers implement. Up to the C90 standard, C compilers assumed the return type of the omitted function prototype as int. And this assumption at the compiler side may lead to unspecified program behavior.Later C99 standard specified that compilers can no longer assume return type as int. Therefore, C99 became more restricted in type checking of function prototypes. But to make C99 standard backward compatible, in practice, compilers throw the warning saying that the return type is assumed as int. But they go ahead with compilation. Thus, it becomes the responsibility of programmers to make sure that the assumed function prototype and the actual function type matches.To avoid all these implementation specifics of C standards, it is best to have a function prototype. 
tanwarsinghvaibhav
C-Functions
c-puzzle
CBSE - Class 11
school-programming
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
rand() and srand() in C/C++
fork() in C
Left Shift and Right Shift Operators in C/C++
Command line arguments in C/C++
Different methods to reverse a string in C/C++
Function Pointer in C
Substring in C++
Enumeration (or enum) in C
TCP Server-Client implementation in C
Structures in C
Powershell - Create HTML File

New-Item cmdlet is used to create a html file and Set-Content cmdlet to put content into it.
In this example, we're creating a new html file named test.html
Type the following command in PowerShell ISE Console
New-Item D:\temp\test\test.html -ItemType File
You can see the test.html created in D:\temp\test directory.
In this example, we're adding content to test.html.
Type the following command in PowerShell ISE Console
Set-Content D:\temp\test\test.html '<html>Welcome to TutorialsPoint</html>'
In this example, we're reading content of test.html.
Get-Content D:\temp\test\test.html

You can see following output in PowerShell console.
<html>Welcome to TutorialsPoint</html>


    15 Lectures 
     3.5 hours 

 Fabrice Chrzanowski

    35 Lectures 
     2.5 hours 

 Vijay Saini

    145 Lectures 
     12.5 hours 

 Fettah Ben
 Print
 Add Notes
 Bookmark this page
Scikit Learn - Gaussian NaÃ ̄ve Bayes

As the name suggest, Gaussian Naïve Bayes classifier assumes that the data from each label is drawn from a simple Gaussian distribution. The Scikit-learn provides sklearn.naive_bayes.GaussianNB to implement the Gaussian Naïve Bayes algorithm for classification.
Following table consist the parameters used by sklearn.naive_bayes.GaussianNB method −
priors − arrray-like, shape(n_classes)
It represents the prior probabilities of the classes. If we specify this parameter while fitting the data, then the prior probabilities will not be justified according to the data.
Var_smoothing − float, optional, default = 1e-9
This parameter gives the portion of the largest variance of the features that is added to variance in order to stabilize calculation.
Following table consist the attributes used by sklearn.naive_bayes.GaussianNB method −
class_prior_ − array, shape(n_classes,)
It provides the probability of every class.
class_count_ − array, shape(n_classes,)
It provides the actual number of training samples observed in every class.
theta_ − array, shape (n_classes, n_features)
It gives the mean of each feature per class.
sigma_ − array, shape (n_classes, n_features)
It gives the variance of each feature per class.
epsilon_ − float
These are the absolute additive value to variance.
Following table consist the methods used by sklearn.naive_bayes.GaussianNB method −
fit(self, X, y[, sample_weight])
This method will Fit Gaussian Naive Bayes classifier according to X and y.
get_params(self[, deep])
With the help of this method we can get the parameters for this estimator.
partial_fit(self, X, y[,classes, sample_weight])
This method allows the incremental fit on a batch of samples.
predict(self, X)
This method will perform classification on an array of test vectors X.
predict_log_proba(self, X)
This method will return the log-probability estimates for the test vector X.
predict_proba(self, X)
This method will return the probability estimates for the test vector X.
score(self, X, y[, sample_weight])
With this method we can get the mean accuracy on the given test data and labels.
set_params(self, \*\*params)
This method allows us to set the parameters of this estimator.
The Python script below will use sklearn.naive_bayes.GaussianNB method to construct Gaussian Naïve Bayes Classifier from our data set −
import numpy as np
X = np.array([[-1, -1], [-2, -4], [-4, -6], [1, 2]])
Y = np.array([1, 1, 2, 2])
from sklearn.naive_bayes import GaussianNB
GNBclf = GaussianNB()
GNBclf.fit(X, Y)
GaussianNB(priors = None, var_smoothing = 1e-09)
Now, once fitted we can predict the new value by using predict() method as follows −
print((GNBclf.predict([[-0.5, 2]]))
[2]

    11 Lectures 
     2 hours 

 PARTHA MAJUMDAR
 Print
 Add Notes
 Bookmark this page
HTML Emojis - GeeksforGeeks

27 Nov, 2020
Emojis are letters (characters) from the UTF-8 (Unicode) character set. The <meta charset=”UTF-8′′> element in HTML defines the character set. Many UTF-8 characters cannot be typed on a keyboard, but they can always be displayed using numbers (called entity numbers). To let the browser understand that you are displaying a character, you must start the entity number with &# and end it with ; (semicolon). 
Syntax:
<head>
    <meta charset="UTF-8">                       
</head>

<body>
    <p>&#number;</p>

    // Take 'number' corresponding
    // to UTF-8 characters you want
    // to display.
</body>

Emojis are also characters from the UTF-8 alphabet and can be used in HTML by mentioning the corresponding emoji, decimal (dec) or hexadecimal (hex) reference in the above syntax.
Example: Represent the following emoji in a webpage.
HTML
<!DOCTYPE html><html><head>    <meta charset="UTF-8"></head>  <body>    <h1>Geeks For Geeks</h1>    <h2>HTML Emojis </h2>    <p></p>    <p></p>    <p></p></body></html>
Output:
In the above example, the decimal reference used for the following emojis are as follows
Note: Instead of decimal (dec) reference, one can also use hexadecimal(hex)  reference to display emoji in a webpage. In addition to the above syntax, one need to include ‘x’ before hexadecimal reference.
Syntax:
<p>&#xhexaDecimal;</p>

Example: In this example, we will represent ,  and  emoji in a webpage with hexadecimal(hex) reference.
HTML
<!DOCTYPE html><html>  <head>    <meta charset="UTF-8"></head>  <body>    <h1>Geeks For Geeks</h1>    <h2>HTML Emojis</h2>    <p></p>    <p></p>    <p></p></body>  </html>
Output:
With hexadecimal reference also we are getting the same output.
Note: Since Emojis are characters, they can be copied, displayed and sized just like any other character in HTML. 
Example: In this example, we will change the font size of the following emojis ,  and .
HTML
<!DOCTYPE html><html>  <head>    <meta charset="UTF-8"></head>  <body>    <h1>Geeks For Geeks</h1>    <h2>HTML Emojis with different font size </h2>    <p style="font-size:25px"> </p>    <p style="font-size:65px"></p>    <p style="font-size:75px"></p></body>  </html>
Output: The output contains the different sizes of emojis.
Similarly any emoji can be displayed in a webpage by entering the corresponding decimal or hexadecimal reference in a code.
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
HTML-Basics
HTML-Misc
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to update Node.js and NPM to next version ?
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to convert Python date to Unix timestamp?

You can use the datetime module to convert a datetime to a UTC timestamp in Python. If you already have the datetime object in UTC, you can the timestamp() to get a UTC timestamp. This function returns the time since epoch for that datetime object. If you have the datetime object in local timezone, first replace the timezone info and then fetch the time. 
from datetime import timezone
dt = datetime(2015, 10, 19)
timestamp = dt.replace(tzinfo=timezone.utc).timestamp()
print(timestamp)
This will give the output −
1445212800.0
If you're on Python 2, then you can use the total_seconds function to get the total seconds since epoch. And if you want to get rid of the timestamp, you can first subtract time from 1 Jan 1970. 
from datetime import timezone
dt = datetime(2015, 10, 19)
timestamp = (dt - datetime(1970, 1, 1)).total_seconds()
print(timestamp)
This will give the output −
1445212800.0
Python Raise Keyword

28 Nov, 2021
Python raise Keyword is used to raise exceptions or errors. The raise keyword raises an error and stops the control flow of the program. It is used to bring up the current exception in an exception handler so that it can be handled further up the call stack.
Syntax of the raise keyword :
raise  {name_of_ the_ exception_class}
The basic way to raise an error is :
raise Exception(“user text”)
Example:
In the below code, we check if an integer is even or odd. if the integer is odd an exception is raised.  a  is a variable to which we assigned a number 5, as a is odd, then if loop checks if it’s an odd integer, if it’s an odd integer then an error is raised.
Input:
Python3
a = 5  if a % 2 != 0:    raise Exception("The number shouldn't be an odd integer")
Output:
While raising an error we can also what kind of error we need to raise, and if necessary print out a text.
Syntax: 
raise TypeError
Example:
In the below code, we tried changing the string ‘apple’  assigned to s to integer and wrote a try-except clause to raise the ValueError. the raise keyword raises a value error with the message “String can’t be changed into an integer”.
Input:
Python3
s = 'apple'  try:    num = int(s)except ValueError:    raise ValueError("String can't be changed into integer")
Output:
When we use the raise keyword, there’s no compulsion to give an exception class along with it. When we do not give any exception class name with the raise keyword, it reraises the exception that last occurred.
Example:
In the above code, we tried changing the string ‘apple’ to integer and wrote a try-except clause to raise the ValueError. The code is the same as before except that we don’t provide an exception class, it reraises the exception that was last occurred.
Input:
Python3
s = 'apple'  try:    num = int(s)except:    raise
Output:
It helps us raise exceptions when we may run into situations where execution can’t proceed.
It helps us reraise an exception that is caught.
Raise allows us to throw one exception at any time.
It is useful when we want to work with input validations.
Picked
python-basics
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Latent Semantic Analysis

30 May, 2021
Latent Semantic Analysis is a natural language processing method that uses the statistical approach to identify the association among the words in a document. LSA deals with the following kind of issue:  
Example: mobile, phone, cell phone, telephone are all similar but if we pose a query like “The cell phone has been ringing” then the documents which have “cell phone” are only retrieved whereas the documents containing the mobile, phone, telephone are not retrieved.
Assumptions of LSA:
The words which are used in the same context are analogous to each other.The hidden semantic structure of the data is unclear due to the ambiguity of the words chosen.
The words which are used in the same context are analogous to each other.
The hidden semantic structure of the data is unclear due to the ambiguity of the words chosen.
Singular Value Decomposition: 
Singular Value Decomposition is the statistical method that is used to find the latent(hidden) semantic structure of words spread across the document.
Let  
C = collection of documents.  
d = number of documents.
n = number of unique words in the whole collection.
M = d X n 
The SVD decomposes the M matrix i.e word to document matrix into three matrices as follows
M = U∑VT
where
U = distribution of words across the different contexts
∑ = diagonal matrix of the association among the contexts
VT = distribution of contexts across the different documents
SVD OF n x d matrix
A very significant feature of SVD is that it allows us to truncate few contexts which are not necessarily required by us. The ∑ matrix provides us with the diagonal values which represent the significance of the context from highest to the lowest. By using these values we can reduce the dimensions and hence this can be used as a dimensionality reduction technique too.
If we select the k the largest diagonal values in ∑ a matrix we obtain  
Mk = Uk∑kVTK
where
Mk = approximated matrix of M
Uk, ∑k, VTk are the matrices containing  only the k contexts from U, ∑, VT respectively
Truncated SVD after selecting k value
Machine Learning
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Monte Carlo Tree Search (MCTS)
Introduction to Recurrent Neural Network
Markov Decision Process
Support Vector Machine Algorithm
DBSCAN Clustering in ML | Density based clustering
Normalization vs Standardization
Bagging vs Boosting in Machine Learning
Principal Component Analysis with Python
Types of Environments in AI
Intuition of Adam Optimizer
isupper() function in C Language

27 Sep, 2021
isupper() function in C programming checks whether the given character is upper case or not. isupper() function is defined in ctype.h header file.  
Syntax :  
int isupper ( int x );
Examples:  
Input: A
Output: Entered character is uppercase character
Input: a
Output: Entered character is not uppercase character
Input: 1
Output: Entered character is not uppercase character
C
// C program to demonstrate// isupper() function#include <ctype.h>#include <stdio.h>int main(){    char ch = 'A';     // checking uppercase    if (isupper(ch))        printf("\nEntered character is uppercase character");    else        printf("\nEntered character is not uppercase character");}
Output: 
Entered character is uppercase character
Application : isupper() function in C programming language is used to find out total number of uppercase present in a given sentence. Example: 
Input: GEEKSFORGEEKS
Output: Number of upper case present in the sentence is : 13
Input: GeeksFORGeeks
Output: Number of upper case present in the sentence is : 5
Input: geeksforgeeks
Output: Number of upper case present in the sentence is : 0 
C
// C program to demonstrate// isupper() function #include <ctype.h>#include <stdio.h> // called functionint ttl_upper(int i, int counter){    char ch;    char a[50] = "GeeksForGeeks";    ch = a[0];     // counting of upper case    while (ch != '\0') {        ch = a[i];        if (isupper(ch))            counter++;         i++;    }     // returning total number of upper case present in sentence    return (counter);}int main(){    int i = 0;    int counter = 0;     // calling function    counter = ttl_upper(i, counter);    printf("\nNumber of upper case present in the sentence is : %d", counter);    return 0;}
Output:  
Number of upper case present in the sentence is : 3 
varshagumber28
C-Library
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Underscore.js | _.omit() Function

27 Apr, 2020
The _.omit() function is used to return a copy of the object that filtered to omit the blacklisted keys.
Syntax:
_.omit(object, *keys)
Parameters: This function accept two parameters as mentioned above and described below:
object: This parameter holds the value of an object.
keys: It is an optional parameter. It contains the key name that value need to be omitted.
Return Value: It returns a copy of the object that filtered to omit the blacklisted keys.
Example 1:
<!DOCTYPE html><html>  <head>    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js">    </script></head>  <body>    <script type="text/javascript">          var info = {            Company: 'GeeksforGeeks',            Address: 'Noida',            Contact: '+91 9876543210'        };          console.log(_.omit(info, 'Company', 'Address'));    </script></body>  </html>
Output:
Example 2:
<!DOCTYPE html><html>  <head>    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js">    </script></head>  <body>    <script type="text/javascript">          var info = {            key1: 10,            key2: 20,            key3: 30,            key4: 40,            key5: 50        };          console.log(_.omit(info, function (value, key, info) {            return value == 10 || value == 50;        }));    </script></body>  </html>
Output:
JavaScript - Underscore.js
JavaScript
Web Technologies
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
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Hide or show elements in HTML using display property
Difference Between PUT and PATCH Request
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
How to enable back button in action bar?

This example demonstrates How to get action bar tittle in android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
   xmlns:app = "http://schemas.android.com/apk/res-auto"
   xmlns:tools = "http://schemas.android.com/tools"
   android:layout_width = "match_parent"
   android:gravity = "center"
   android:layout_height = "match_parent"
   tools:context = ".MainActivity">
   <TextView
      android:id = "@+id/text"
      android:textSize = "30sp"
      android:layout_width = "match_parent"
      android:layout_height = "match_parent" />
</LinearLayout>
In the above code, we have taken text view.
Step 3 − Add the following code to src/MainActivity.java
package com.example.myapplication;
import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
   TextView textView;
   @SuppressLint("RestrictedApi")
   @RequiresApi(api = Build.VERSION_CODES.N)
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      textView = findViewById(R.id.text);
      getSupportActionBar().setDisplayHomeAsUpEnabled(true);
      getSupportActionBar().setTitle("Home");
      getSupportActionBar().setSubtitle("sairam");
   }
}
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run  icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
Click here to download the project code
Depth First Traversal in C

We shall not see the implementation of Depth First Traversal (or Depth First Search) in C programming language. For our reference purpose, we shall follow our example and take this as our graph model −
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

#define MAX 5

struct Vertex {
   char label;
   bool visited;
};

//stack variables

int stack[MAX]; 
int top = -1; 

//graph variables

//array of vertices
struct Vertex* lstVertices[MAX];

//adjacency matrix
int adjMatrix[MAX][MAX];

//vertex count
int vertexCount = 0;

//stack functions

void push(int item) { 
   stack[++top] = item; 
} 

int pop() { 
   return stack[top--]; 
} 

int peek() {
   return stack[top];
}

bool isStackEmpty() {
   return top == -1;
}

//graph functions

//add vertex to the vertex list
void addVertex(char label) {
   struct Vertex* vertex = (struct Vertex*) malloc(sizeof(struct Vertex));
   vertex->label = label;  
   vertex->visited = false;     
   lstVertices[vertexCount++] = vertex;
}

//add edge to edge array
void addEdge(int start,int end) {
   adjMatrix[start][end] = 1;
   adjMatrix[end][start] = 1;
}

//display the vertex
void displayVertex(int vertexIndex) {
   printf("%c ",lstVertices[vertexIndex]->label);
}       

//get the adjacent unvisited vertex
int getAdjUnvisitedVertex(int vertexIndex) {
   int i;

   for(i = 0; i < vertexCount; i++) {
      if(adjMatrix[vertexIndex][i] == 1 && lstVertices[i]->visited == false) {
         return i;
      }
   }

   return -1;
}

void depthFirstSearch() {
   int i;

   //mark first node as visited
   lstVertices[0]->visited = true;

   //display the vertex
   displayVertex(0);   

   //push vertex index in stack
   push(0);

   while(!isStackEmpty()) {
      //get the unvisited vertex of vertex which is at top of the stack
      int unvisitedVertex = getAdjUnvisitedVertex(peek());

      //no adjacent vertex found
      if(unvisitedVertex == -1) {
         pop();
      } else {
         lstVertices[unvisitedVertex]->visited = true;
         displayVertex(unvisitedVertex);
         push(unvisitedVertex);
      }
   }

   //stack is empty, search is complete, reset the visited flag        
   for(i = 0;i < vertexCount;i++) {
      lstVertices[i]->visited = false;
   }        
}

int main() {
   int i, j;

   for(i = 0; i < MAX; i++)    // set adjacency {
      for(j = 0; j < MAX; j++) // matrix to 0
         adjMatrix[i][j] = 0;
   }

   addVertex('S');   // 0
   addVertex('A');   // 1
   addVertex('B');   // 2
   addVertex('C');   // 3
   addVertex('D');   // 4

   addEdge(0, 1);    // S - A
   addEdge(0, 2);    // S - B
   addEdge(0, 3);    // S - C
   addEdge(1, 4);    // A - D
   addEdge(2, 4);    // B - D
   addEdge(3, 4);    // C - D

   printf("Depth First Search: ")
   depthFirstSearch(); 

   return 0;   
}
If we compile and run the above program, it will produce the following result −
Depth First Search: S A D B C
How to plot a function defined with def in Python? (Matplotlib)

To plot a function defined with def in Python, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Create a user-defined function using, def, i.e., f(x).
Create x data points using numpy.
Plot x and f(x) using plot() method.
To display the figure, use show() method.
import numpy as np
from matplotlib import pyplot as plt

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

def f(x):
   return np.sin(x) + x + x * np.sin(x)

x = np.linspace(-10, 10, 100)

plt.plot(x, f(x), color='red')

plt.show()
GATE | GATE-CS-2016 (Set 2) | Question 43 - GeeksforGeeks

30 Sep, 2021
Consider a 3 GHz (gigahertz) processor with a three-stage pipeline and stage latencies v1, v2, and v3 such thatv1 = 3v2/4 = 2v3. If the longest pipeline stage is split into two pipeline stages of equal latency, the new frequency is _________ GHz, ignoring delays in the pipeline registers(A) 2(B) 4(C) 8(D) 16Answer: (B)Explanation: Ans is B
Consider this pipeline
(V1) --> (V2) --> (V3)
Can be written as
(V) --> (4V/3) --> (V/2)
Where given V = V1 = 3V2/4 = 2V3 
Largest stage is stage 2 with 4V/3 seconds time required. Speed of processor is limited by this stage only. In fact this is the speed of the processor.
Frequency given is 3Ghz, which means processor can execute
3 Giga clock cycle.... in 1 second
Or
1 clock cycle .....in (1/3G) secs
(G for giga)
But we know that stage latency of the largest stage in pipeline limits the time of 1 clock cycle. Hence
4V/3 = 1 clock cycle = 1/3G secs
V = 1/4G...........(1) 
Now largest stage that is stage 2 is split into equal size, so new pipeline is
(V)-->(2V/3)-->(2V/3)-->(V/2) 
Now largest stage is V secondsHence,
In V seconds do 1 clock cycle
In 1 second do 1/V clock cycles
But V = 1/4G
So in 1 second do 4 Ghz. {ANS} 
YouTubeGeeksforGeeks GATE Computer Science16.1K subscribersPipelining: Previous Year Question part-IV | COA | GeeksforGeeks GATE | Harshit NigamWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You'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.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:002:00 / 31:50•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=PmA5Ic9vc9o" 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-2016 (Set 2)
GATE-GATE-CS-2016 (Set 2)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-CS-2014-(Set-3) | Question 38
GATE | GATE CS 2018 | Question 37
GATE | GATE-IT-2004 | Question 83
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2016 (Set 1) | Question 65
GATE | GATE-CS-2016 (Set 1) | Question 63
GATE | GATE-IT-2004 | Question 12
GATE | GATE-CS-2007 | Question 17
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 2010 | Question 33
JavaScript String - replace() Method

This method finds a match between a regular expression and a string, and replaces the matched substring with a new substring.
The replacement string can include the following special replacement patterns −
The syntax to use the replace() method is as follows −
string.replace(regexp/substr, newSubStr/function[, flags]);

regexp − A RegExp object. The match is replaced by the return value of parameter #2.
regexp − A RegExp object. The match is replaced by the return value of parameter #2.
substr − A String that is to be replaced by newSubStr.
substr − A String that is to be replaced by newSubStr.
newSubStr − The String that replaces the substring received from parameter #1.
newSubStr − The String that replaces the substring received from parameter #1.
function − A function to be invoked to create the new substring.
function − A function to be invoked to create the new substring.
flags − A String containing any combination of the RegExp flags: g - global match, i - ignore case, m - match over multiple lines. This parameter is only used if the first parameter is a string.
flags − A String containing any combination of the RegExp flags: g - global match, i - ignore case, m - match over multiple lines. This parameter is only used if the first parameter is a string.
It simply returns a new changed string.
Try the following example.
<html>
   <head>
      <title>JavaScript String replace() Method</title>
   </head>
   
   <body>   
      <script type = "text/javascript">
         var re = /apples/gi;
         var str = "Apples are round, and apples are juicy.";
         var newstr = str.replace(re, "oranges");        
         document.write(newstr ); 
      </script>      
   </body>
</html>
oranges are round, and oranges are juicy.

Try the following example; it shows how to switch words in a string.
<html>
   <head>
      <title>JavaScript String replace() Method</title>
   </head>
   
   <body>     
      <script type = "text/javascript">
         var re = /(\w+)\s(\w+)/;
         var str = "zara ali";
         var newstr = str.replace(re, "$2, $1");
         document.write(newstr);
      </script>   
   </body>
</html>
ali, zara


    25 Lectures 
     2.5 hours 

 Anadi Sharma

    74 Lectures 
     10 hours 

 Lets Kode It

    72 Lectures 
     4.5 hours 

 Frahaan Hussain

    70 Lectures 
     4.5 hours 

 Frahaan Hussain

    46 Lectures 
     6 hours 

 Eduonix Learning Solutions

    88 Lectures 
     14 hours 

 Eduonix Learning Solutions
 Print
 Add Notes
 Bookmark this page
How do we specify the buffer size when opening a file in Python?

If you look at the function definition of open - open(name[, mode[, buffering]]), you'll see that it takes 3 arguments in Python 2, third one being buffering. The optional buffering argument specifies the file’s desired buffer size: 0 means unbuffered, 1 means line buffered, any other positive value means use a buffer of (approximately) that size (in bytes). A negative buffering means to use the system default, which is usually line buffered for tty devices and fully buffered for other files. If omitted, the system default is used.
For example, If you want to open a file with a buffer size of 128 bytes you can open the file like this −
>>> open('my_file', 'r+', 128)
In Python 3, the function definition of open is: open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None). buffering is an optional integer used to set the buffering policy. Pass 0 to switch buffering off (only allowed in binary mode), 1 to select line buffering (only usable in text mode), and an integer > 1 to indicate the size in bytes of a fixed-size chunk buffer. When no buffering argument is given, the default buffering policy works as follows −
Binary files are buffered in fixed-size chunks; the size of the buffer is chosen using a heuristic trying to determine the underlying device’s “block size” and falling back on io.DEFAULT_BUFFER_SIZE.
Binary files are buffered in fixed-size chunks; the size of the buffer is chosen using a heuristic trying to determine the underlying device’s “block size” and falling back on io.DEFAULT_BUFFER_SIZE.
“Interactive” text files (files for which isatty() returns True) use line buffering. Other text files use the policy described above for binary files.
“Interactive” text files (files for which isatty() returns True) use line buffering. Other text files use the policy described above for binary files.
The example for Python 3 is the same as Python 2. For example, If you want to open a file with a buffer size of 128 bytes you can open the file like this −
>>> open('my_file', 'r+', 128)
Boolean Values in Python

The truth values of an expression is stored as a python data type called bool. There are only two such values in this data type. True and False.
In the below program we find out the data types of True and False Boolean values.
 Live Demo
print(True)
print(type(True))
print(False)
print(type(False))
Running the above code gives us the following result −
True
<class 'bool'>
False
<class 'bool'>
Boolean expression is an expression that evaluates to a Boolean value. It almost always involves a comparison operator. In the below example we will see how the comparison operators can give us the Boolean values. The bool() method is used to return the truth value of an ex[resison.
Syntax: bool([x])
Returns True if X evaluates to true else false.
Without parameters it returns false.
Below we have examples which use numbers streams and Boolean values as parameters to the bool function. The results come out us true or false depending on the parameter.
 Live Demo
# Check true
a = True
print(bool(a))
# Check false
a = False
print(bool(a))
# Check 0
a = 0.0
print(bool(a))
# Check 1
a = 1.0
print(bool(a))
# Check Equality
a = 5
b = 10
print(bool( a==b))
# Check None
a = None
print(bool(a))
# Check an empty sequence
a = ()
print(bool(a))
# Check an emtpty mapping
a = {}
print(bool(a))
# Check a non empty string
a = 'Tutorialspoint'
print(bool(a))
Running the above code gives us the following result −
True
False
False
True
False
False
False
False
True