code-rag-bench/online-tutorials huggingface dataset:
MongoDB NOR operator ( $nor ) - GeeksforGeeks

22 Apr, 2020
MongoDB provides different types of logical query operators and $nor operator is one of them. This operator is used to perform logical NOR operation on the array of one or more expressions and select or retrieve only those documents that do not match all the given expression in the array. You can use this operator in methods like find(), update(), etc. according to your requirements.
Syntax:
{ $nor: [ { Expression1 }, { Expression2 }, ...  { ExpressionN } ] }
In the following examples, we are working with:
Database: GeeksforGeeksCollection: contributorDocument: three documents that contain the details of the contributors in the form of field-value pairs.
In this example, we are retrieving only those employee’s documents whose salary is not 3000 and whose branch is not ECE.
db.contributor.find({$nor: [{salary: 3000}, {branch: "ECE"}]}).pretty()
In this example, we are retrieving only those employee’s documents whose age is not 24 and whose state is not AP.
db.contributor.find({$nor: [{"personal.age": 24},                            {"personal.state": "AP"}]}).pretty()
In this example, we are retrieving only those employee’s documents that does not match the given array.
db.contributor.find({$nor: [{language: {$in: ["Java", "C++"]}}]}).pretty()
MongoDB
Advanced Computer Subject
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Copying Files to and from Docker Containers
Markov Decision Process
Fuzzy Logic | Introduction
Q-Learning in Python
An introduction to Machine Learning
Principal Component Analysis with Python
Basics of API Testing Using Postman
ML | What is Machine Learning ?
OpenCV - Overview
Getting Started with System Design
How to create Shopping Cart Button in ReactJS? - GeeksforGeeks

21 Mar, 2022
We can create a Shopping Cart-like button with the feature of adding items count and decreasing item count in ReactJS using the following approach. Material UI for React has this component available for us, and it is very easy to integrate. 
Creating React Application And Installing Module:
Step 1: Create a React application using the following command.
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command.
cd foldername
Step 3: After creating the ReactJS application, Install the material-ui modules using the following command.
npm install @material-ui/core
npm install @material-ui/icons
Project Structure: It will look like the following.
Project Structure
Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
App.js
import React from "react";import ButtonGroup from "@material-ui/core/ButtonGroup";import Badge from "@material-ui/core/Badge";import ShoppingCartIcon from "@material-ui/icons/ShoppingCart";import Button from "@material-ui/core/Button";import AddIcon from "@material-ui/icons/Add";import RemoveIcon from "@material-ui/icons/Remove";  export default function App() {  const [itemCount, setItemCount] = React.useState(1);    return (    <div style={{ display: "block", padding: 30 }}>      <h4>How to create ShoppingCart Button in ReactJS?</h4>      <div>        <Badge color="secondary" badgeContent={itemCount}>          <ShoppingCartIcon />{" "}        </Badge>        <ButtonGroup>          <Button            onClick={() => {              setItemCount(Math.max(itemCount - 1, 0));            }}          >            {" "}            <RemoveIcon fontSize="small" />          </Button>          <Button            onClick={() => {              setItemCount(itemCount + 1);            }}          >            {" "}            <AddIcon fontSize="small" />          </Button>        </ButtonGroup>      </div>    </div>  );}
Step to Run Application: Run the application using the following command from the root directory of the project.
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output.
Reference: https://material-ui.com/components/badges
Material-UI
React-Questions
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ReactJS useNavigate() Hook
How to set background images in ReactJS ?
Axios in React: A Guide for Beginners
How to create a table in ReactJS ?
How to navigate on path by button click in react router ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
jQuery UI Dialog focus Event - GeeksforGeeks

02 Dec, 2021
The Dialog box is the way to inform the user about something. It is a nice way to popup on the user window to show the information that will happen in the next or any kind of information the developer wants to clarify to the user should know. jQueryUI dialog method is used to create a basic dialog window inside the page. It has a title bar and a content area and can be moved, resized, and closed with the ‘X’ icon by default. The focus event is triggered when the dialog box gains focus.
Syntax:
$(".selector").dialog (
   focused: function( event, ui ) {
       console.log('focused')
   }, 
CDN Link: First, add jQuery Mobile scripts needed for your project.
<link href = “https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css”    rel =”stylesheet”><script src = “https://code.jquery.com/jquery-1.10.2.js”></script><script src = “https://code.jquery.com/ui/1.10.4/jquery-ui.js”></script>
Example 1:
‘Open Dialog’ button will trigger the click function (#gfg) that will further open the ‘textarea’ in a dialog (#gfg2).
focus( event, ui ) : Triggers box gains focus. There is callback function attached to this focus.event : Type -> Eventui : Type -> Objectcallback function : function( event, ui ) { console.log(‘focused’)}
ui : Type -> Object
callback function : function( event, ui ) { console.log(‘focused’)}
HTML
<!DOCTYPE html><html lang="en">  <head>    <meta charset="utf-8" />    <link href="https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css"      rel="stylesheet"/>    <script src="https://code.jquery.com/jquery-1.10.2.js">    </script>    <script src="https://code.jquery.com/ui/1.10.4/jquery-ui.js">    </script>    <script type="text/javascript">      $(function () {        $("#gfg2").dialog({          autoOpen: false,          focus: function (event, ui) {            console.log("focused");          },        });        $("#gfg").click(function () {          $("#gfg2").dialog("open");        });      });    </script>  </head>  <body>    <div id="gfg2" title="GeeksforGeeks">      <textarea>jQuery UI | focus(event, ui) Event</textarea>    </div>    <button id="gfg">Open Dialog</button>  </body></html>
Output:
Reference:https://api.jqueryui.com/1.9/dialog/#event-focus
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
jQuery-UI
HTML
JQuery
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
HTML Cheat Sheet - A Basic Guide to HTML
Design a web page using HTML and CSS
Form validation using jQuery
Angular File Upload
JQuery | Set the value of an input text field
Form validation using jQuery
How to change selected value of a drop-down list using jQuery?
How to change the background color after clicking the button in JavaScript ?
How to fetch data from JSON file and display in HTML table using jQuery ?
Difference between WCF and Web Service - GeeksforGeeks

03 Jun, 2021
WCF (Windows Communication Foundation): WCF, as the name suggests, is a unified .NET framework that is used to develop service-oriented applications. It allows you to develop applications that can communicate using different communication mechanisms. It is founded for other Microsoft Distributed Technologies and considered the future of distributed computing.  Because of its flexibility, it makes the development of endpoints much easier. It supports various programming languages and platforms. It is SOAP-based and returns data in XML form. It can be hosted in different scenarios, and such scenarios include various services such as WAS, IIS, Managed Windows, etc. The following code will be used to build a service in WCF:  
[ServiceContract]  
public interface ITest  
{    
 [OperationContract]    
 string ShowMessage(string strMsg);  
}  
public class Service: ITest  
{    
 public string ShowMessage(string strMsg)    
Web Service: Web Service, as the name suggests, is a client-server application that allows communication between client and server applications. It is basically a software module specially designed to execute a certain set of tasks. This service is specially used to make application platforms and technology independent. There are two types of web services include the SOAP web services and RESTful web services.  Following code will be used to build a service in Web service: 
[WebService]  
public class Service: System.Web.Services.WebService  
{  
 [WebMethod]  
 public string Test(string strMsg)    
    {    return strMsg; 
    }  
}  
WCF  
Web Service 
Difference Between
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
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
Difference between Compile-time and Run-time Polymorphism in Java
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Pure Functions

29 May, 2017
A function is called pure function if it always returns the same result for same argument values and it has no side effects like modifying an argument (or global variable) or outputting something. The only result of calling a pure function is the return value. Examples of pure functions are strlen(), pow(), sqrt() etc. Examples of impure functions are printf(), rand(), time(), etc.
If a function is known as pure to compiler then Loop optimization and subexpression elimination can be applied to it. In GCC, we can mark functions as pure using the “pure” attribute.
__attribute__ ((pure)) return-type fun-name(arguments1, ...)
{
    /* function body */
}

Following is an example pure function that returns square of a passed integer.
__attribute__ _((pure)) int my_square(int val){    return val*val;}
Consider the below example
for (len = 0; len < strlen(str); ++len)    printf("%c", toupper(str[len]));
If “strlen()” function is not marked as pure function then compiler will invoke the “strlen()” function with each iteration of the loop, and if function is marked as pure function then compiler knows that value of “strlen()” function will be same for each call, that’s why compiler optimizes the for loop and generates code like following.
int len = strlen(str);  for (i = 0; i < len; ++i)    printf("%c", toupper((str[i]));
Let us write our own pure function to calculate string length.
__attribute__ ((pure)) size_t my_strlen(const char *str){    const char *ptr = str;    while (*ptr)       ++ptr;      return (ptr – str);}
Marking function as pure says that the hypothetical function “my_strlen()” is safe to call fewer times than the program says.
This article is compiled by “Narendra Kangralkar” and reviewed by GeeksforGeeks team. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Articles
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Docker - COPY Instruction
Time complexities of different data structures
SQL | DROP, TRUNCATE
Difference Between Object And Class
Implementation of LinkedList in Javascript
std::sort() in C++ STL
Bitwise Operators in C/C++
Arrays in C/C++
Substring in C++
Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()
Python MongoDB – Find

20 Jun, 2022
MongoDB is a cross-platform document-oriented database program and the most popular NoSQL database program. The term NoSQL means non-relational. MongoDB stores the data in the form of key-value pairs. It is an Open Source, Document Database which provides high performance and scalability along with data modeling and data management of huge sets of data in an enterprise application. MongoDB also provides the feature of Auto-Scaling. It uses JSON-like documents, which makes the database very flexible and scalable.
In MongoDB, there are 2 functions that are used to find the data from the collection or the database.
find_one()
find()
In MongoDB, to select data from the collection we use find_one() method. It returns the first occurred information in the selection and brings backs as an output. find_one() method accepts an optional parameter filter that specifies the query to be performed and returns the first occurrence of information from the database. 
Example 1: Find the first document from the student’s a collection/database. Let’s suppose the database looks like as follows:
 
Python3
# Python program to demonstrate# find_one()  import pymongo  mystudent = pymongo.MongoClient('localhost', 27017) # Name of the databasemydb = mystudent["gfg"] # Name of the collectionmycol = mydb["names"] x = mycol.find_one() print(x)
Output : 
find() method is used to select data from the database. It returns all the occurrences of the information stored in the collection. It has 2 types of parameters, The first parameter of the find() method is a query object. In the below example we will use an empty Query object, which will select all information from the collection. Note: It works the same as SELECT* without any parameter. 
Example: 
Python3
import pymongo  # establishing connection# to the databasemy_client = pymongo.MongoClient('localhost', 27017) # Name of the databasemydb = my_client["gfg"] # Name of the collectionmynew = mydb["names"] for x in mycol.find():    print(x)
Output :  The second parameter to the find() method is that you can specify the field to include in the result. The second parameter passed in the find() method is of object type describing the field. Thus, this parameter is optional. If omitted then all the fields from the collection/database will be displayed in the result. To include the field in the result the value of the parameter passed should be 1, if the value is 0 then it will be excluded from the result. 
Example: Return only the names and address, not the id: 
Output: 
saurabh1990aror
khushb99
Python-mongoDB
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Get the first key in dictionary

18 May, 2020
Many times, while working with Python, we can have a situation in which we require to get the initial key of the dictionary. There can be many specific uses of it, either for checking the indexing and many more of these kinds. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using list() + keys()
The combination of the above methods can be used to perform this particular task. In this, we just convert the entire dictionaries’ keys extracted by keys() into a list and just access the first key. Just one thing you have to keep in mind while using this i.e it’s complexity. It will first convert the whole dictionary to list by iterating over each item and then extract its first element. Using this method complexity would be O(n).
# Python3 code to demonstrate working of# Getting first key in dictionary# Using keys() + list()  # initializing dictionarytest_dict = {'Gfg' : 1, 'is' : 2, 'best' : 3}  # printing original dictionaryprint("The original dictionary is : " + str(test_dict))  # Using keys() + list()# Getting first key in dictionaryres = list(test_dict.keys())[0]  # printing initial keyprint("The first key of dictionary is : " + str(res))
The original dictionary is : {'best': 3, 'Gfg': 1, 'is': 2}
The first key of dictionary is : best

 
Method #2 : Using next() + iter()This task can also be performed using these functions. In this, we just take the first next key using next() and iter function is used to get the iterable conversion of dictionary items. So if you want only the first key then this method is more efficient. Its complexity would be O(1).
# Python3 code to demonstrate working of# Getting first key in dictionary# Using next() + iter()  # initializing dictionarytest_dict = {'Gfg' : 1, 'is' : 2, 'best' : 3}  # printing original dictionaryprint("The original dictionary is : " + str(test_dict))  # Using next() + iter()# Getting first key in dictionaryres = next(iter(test_dict))  # printing initial keyprint("The first key of dictionary is : " + str(res))
The original dictionary is : {'best': 3, 'Gfg': 1, 'is': 2}
The first key of dictionary is : best

ApoorvaSingh1
Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Enumerate() in Python
Different ways to create Pandas Dataframe
Read a file line by line in Python
How to Install PIP on Windows ?
Python program to convert a list to string
Defaultdict in Python
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python program to check whether a number is Prime or not
Matplotlib.ticker.FuncFormatter class in Python

07 Oct, 2021
Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. 
The matplotlib.ticker.FuncFormatter class uses a user defined function for formatting. This user defined function must take two values as inputs for a tick value x and a position pos.  
Syntax: class matplotlib.ticker.FuncFormatter(func)Parameter:  
func: The user defined function for formatting of the plot.  
Example 1:  
Python3
import matplotlib.pyplot as pltimport matplotlib.ticker as tickimport numpy as np  x = np.linspace(0, 10, 1000)y = 0.000001 * np.sin(10 * x) fig = plt.figure()ax = fig.add_subplot(111) ax.plot(x, y) def y_fmt(x, y):    return '{:2.2e}'.format(x).replace('e', 'x10^') ax.yaxis.set_major_formatter(tick.FuncFormatter(y_fmt)) plt.show()
Output:  
Example 2:  
Python3
import matplotlib.pyplot as pltfrom matplotlib.ticker import FuncFormatter  fig, ax = plt.subplots()ax.axis([0.01, 10000, 1, 1000000])ax.loglog() for axis in [ax.xaxis, ax.yaxis]:    formatter = FuncFormatter(lambda y, _: '{:.16g}'.format(y))    axis.set_major_formatter(formatter) plt.show()
Output:  
 
gabaa406
Python-matplotlib
Python
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to input a comma separated string in C++?

23 Mar, 2021
Given an input string which is comma-separated instead of space, the task is to parse this input string in C++.First, let us understand what difference does it create if the input string is comma-separated. Taking input a whitespace-separated stringTaking input a whitespace-separated string in C++ is very easy. The program to do so is:
C++
#include <bits/stdc++.h>using namespace std; int main(){    string str;     // Get the string    getline(cin, str);     // Print the words    cout << str;}
1 2 3 4 5 6
Output: 
1
2
3
4
5
6
 
Why can’t we use the above code for comma-separated input string? The above code works fine for a whitespace-separated input string, but for a comma-separated input string, it won’t work as expected, because the program will take complete input as a single word in the string.
1, 2, 3, 4, 5, 6
Output: 
1, 2, 3, 4, 5, 6
 
How to input a comma separated string? Now inorder to input a comma separated string, following approach can be used: 
Get the string to be taken as input in stringstreamTake each character of the string one by one from the streamCheck if this character is a comma (‘, ‘).If yes, then ignore that character.Else, Insert this character in the vector which stores the words
Get the string to be taken as input in stringstream
Take each character of the string one by one from the stream
Check if this character is a comma (‘, ‘).
If yes, then ignore that character.
Else, Insert this character in the vector which stores the words
Below is the implementation of the above approach:
CPP
// C++ program to input// a comma separated string #include <bits/stdc++.h>using namespace std; int main(){    // Get the string    string str = "11,21,31,41,51,61";     vector<int> v;     // Get the string to be taken    // as input in stringstream    stringstream ss(str);     // Parse the string    for (int i; ss >> i;) {        v.push_back(i);        if (ss.peek() == ',')            ss.ignore();    }     // Print the words    for (size_t i = 0; i < v.size(); i++)        cout << v[i] << endl;}
11
21
31
41
51
61
 
laxmanprabha96
C++
C++ Programs
Strings
Strings
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
JavaScript Grouping operator

08 Oct, 2021
Below is the example of the Grouping operator.  
Example:  
jscript
<script>    function gfg() {     // 3 * (2 + 3)    let value1= 3 * (2 + 3);         // (3 + 2) * 3    let value2= (3 + 2) * 3;    document.write(value1 + "</br>" + value2);    }    gfg();</script>                   
 
Output:  
15
15
The Grouping operator consists of a pair of parentheses around an expression or sub-expression to override the normal operator precedence so that expressions with lower precedence can be evaluated before an expression with higher priority. This operator can only contain expressions. The parameter list is passed to function within this operator which will treat it as an expression.Syntax:  
( )
This ( ) operator controls the precedence of evaluation in expressionsBelow examples illustrates the Grouping operator in JavaScript: Example 1: Function as a statement and exception. In the below code JavaScript considers a function as a statement if it is not preceded by any other statement. But applying a grouping operator that has the highest precedence over any other operator considers the function as an expression and hence it gets fully evaluated.  
JavaScript
<script>    function(x){ return x };    // SyntaxError: Function statements    // require a function name.      // function as expression    (function(x){ return x });    // This will run without any exception.</script>                   
Example 2: With and without grouping operator.  
jscript
<script>    function gfg() {    // 5 * 5 + 5    // 25+5    // 30    let value= 5 * 5 + 5 ;    document.write("Without grouping operator: " + value);     // 5 * (5 + 5)    // 5*10    // 50    let value1= 5 * (5 + 5);    document.write("</br>With grouping operator: "+ value1);    }    gfg();</script>                   
Output:  
Without grouping operator: 30
With grouping operator: 50
Supported Browser:
Chrome 1 and above
Edge 12 and above
Firefox 1 and above
Internet Explorer 3 and above
Opera 3 and above
Safari 1 and above
ysachin2314
javascript-operators
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Node.js zlib.deflate() Method

11 Oct, 2021
The zlib.deflate() method is an inbuilt application programming interface of the Zlib module which is used to compress a chunk of data.
Syntax:
zlib.deflate( buffer, options, callback )
Parameters: This method accept three parameters as mentioned above and described below:
buffer: It can be of type Buffer, TypedArray, DataView, ArrayBuffer, and string.
options: It is an optional parameter that holds the zlib options.
callback: It holds the callback function.
Return Value: It returns the chunk of data after compression.
Below examples illustrate the use of zlib.deflate() method in Node.js:
Example 1:
// Node.js program to demonstrate the     // deflate() method  // Including zlib moduleconst zlib = require("zlib");  // Declaring input and assigning// it a value stringvar input = "Geeks";  // Calling deflate methodzlib.deflate(input, (err, buffer) => {    if (!err) {      console.log(buffer.toString('base64'));  }   else {    console.log(err);  }});console.log("Data Compressed...");
Output:
Data Compressed...
eJxzT03NLgYABXQB8A==

Example 2:
// Node.js program to demonstrate the     // deflate() method  // Including zlib moduleconst zlib = require("zlib");  // Declaring input and assigning// it a value stringvar input = "Geeks";  // Calling deflate methodzlib.deflate(input, (err, buffer) => {    if (!err) {      console.log(buffer.toString('bas64'));  }   else {    console.log(err);  }});console.log("Data Compressed...");
Output:
Data Compressed...
buffer.js:631
  throw new ERR_UNKNOWN_ENCODING(encoding);
  ^

TypeError [ERR_UNKNOWN_ENCODING]: Unknown encoding: bas64
    at stringSlice (buffer.js:631:9)    
    at Buffer.toString (buffer.js:667:10)    
    at Deflate.zlib.deflate [as cb] 
(/home/runner/BeautifulMiserlySourcecode/index.js:17:24)
    at Deflate.zlibBufferOnEnd (zlib.js:133:10)
    at Deflate.emit (events.js:203:15)
    at Deflate.EventEmitter.emit (domain.js:448:20)
    at endReadableNT (_stream_readable.js:1143:12)
    at process._tickCallback (internal/process/next_tick.js:63:19)

Here, an error occurs in encoding the data so, error is thrown.
Reference: https://nodejs.org/api/zlib.html#zlib_zlib_deflate_buffer_options_callback
Node.js-Zlib-module
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Throw Keyword in Scala

23 May, 2022
The throw keyword in Scala is used to explicitly throw an exception from a method or any block of code.In scala, throw keyword is used to throw exception explicitly and catch it. It can also be used to throw custom exceptions. Exception handling in java and scala are very similar. Except that scala treats all types of exceptions as runtime exceptions only, therefore it doesn’t force us to handle them instead uses pattern matching in catch block. throw is an expression that has a result type nothing in scala. If the result wont actually evaluate to anything we can use it in place of any other expression . 
Important things to remember: 
Throw expression has a return type of Nothing.
Throw is the keyword used to throw an exception, whereas throws is the keyword used to declare exception.
Catch block uses pattern matching to handle exceptions
Syntax:
 throw exception object
Example:
 throw new ArithmeticException("divide by 0") 
Example: 
val x = if (n % 10 == 0) 5 else throw new RuntimeException(“n must be a multiple of 10”)
Explanation: If n is a multiple of 10 then 5 is assigned to x, but if n is not a multiple of 10 then an exception is thrown before x can be initialised to anything at all. Because of which, we can say throw has a value of any kind. In scala, throwing an exception is the same as Java. we create an exception object and then we throw it with the throw keyword: 
Example: 
Scala
// Scala program of throw keyword // Creating objectobject Main{    // Define function    def validate(article:Int)=    {         // Using throw keyword        if(article < 20)             throw new ArithmeticException("You are not eligible for internship")         else println("You are eligible for internship")     }          // Main method    def main(args: Array[String])    {            validate(22)    }}
Output:
You are eligible for internship
In above code, if we have article less than 20 than we get no output. When an error occurs, a scala method can throw an exception instead of returning normally. In the below example, there we observe a single exception that is thrown from a function. 
Scala
// Scala program of throw keyword // Creating objectobject GFG{    // Main method    def main(args: Array[String])    {         try    {        func();             }    catch    {        case ex: Exception => println("Exception caught in main: " + ex);             }    }         // Defining function    def func()    {        // Using throw exception        throw new Exception("Exception thrown from func");             }}
Output:
Exception caught in main: java.lang.Exception: Exception thrown from func
simmytarika5
Picked
Scala
scala-exception
Scala-Keyword
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Calculate Quantiles by Group in R? - GeeksforGeeks

23 Dec, 2021
In this article, we will discuss how to calculate quantiles by the group in R programming language.
To obtain the required quartiles, quantile() function is used.
Syntax:
quantile( data, probs)
Parameters:
data: data whose percentiles are to be calculated
probs: percentile value
To group data, we use dplyr module. This module contains a function called group_by() in which the column to be grouped by has to be passed.
Syntax:
group_by(column_name)
To find quantiles of the grouped data we will call summarize method with quantiles() function.
Syntax:
summarize( function )
Example 1: Calculate Quantiles by group by summarizing one quartile with probability 0.5
R
# import librarylibrary(dplyr) # create dataframedf<-data.frame(x=c(2,13,5,36,12,50),               y=c('a','b','c','c','c','b')) # create groups# calculate quantiles by groupdf %>% group_by(y) %>%  summarize(res=quantile(x,probs=0.5))
Output:
Example 2: Calculate quantiles by group by summarizing three quartiles with probability 0.25, 0.5, and 0.75.
R
# import librarylibrary(dplyr) # create dataframedf<-data.frame(x=c(2,13,5,36,12,50),               y=c('a','b','c','c','c','b')) # create groups# find quantilesdf %>% group_by(y) %>%  summarize(first=quantile(x,probs=0.25),            second=quantile(x,probs=0.5),            third=quantile(x,probs=0.75))
Output:
simranarora5sos
Picked
R Dplyr
R-Statistics
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
How to import an Excel File into R ?
Time Series Analysis in R
How to filter R dataframe by multiple conditions?
Replace Specific Characters in String in R
R - if statement
Major Kernel Functions in Support Vector Machine (SVM) - GeeksforGeeks

07 Feb, 2022
Kernel Function is a method used to take data as input and transform it into the required form of processing data. “Kernel” is used due to a set of mathematical functions used in Support Vector Machine providing the window to manipulate the data. So, Kernel Function generally transforms the training set of data so that a non-linear decision surface is able to transform to a linear equation in a higher number of dimension spaces. Basically, It returns the inner product between two points in a standard feature dimension. Standard Kernel Function Equation :  Major Kernel Functions :- For Implementing Kernel Functions, first of all, we have to install the “scikit-learn” library using the command prompt terminal:  
    pip install scikit-learn
Gaussian Kernel: It is used to perform transformation when there is no prior knowledge about data.
 
Gaussian Kernel Radial Basis Function (RBF): Same as above kernel function, adding radial basis method to improve the transformation.
 
Gaussian Kernel Graph
Code: 
python3
from sklearn.svm import SVCclassifier = SVC(kernel ='rbf', random_state = 0) # training set in x, y axisclassifier.fit(x_train, y_train)
Sigmoid Kernel: this function is equivalent to a two-layer, perceptron model of the neural network, which is used as an activation function for artificial neurons.
 
Sigmoid Kernel Graph
Code:  
python3
from sklearn.svm import SVCclassifier = SVC(kernel ='sigmoid')classifier.fit(x_train, y_train) # training set in x, y axis
Polynomial Kernel: It represents the similarity of vectors in the training set of data in a feature space over polynomials of the original variables used in the kernel.
 
Polynomial Kernel Graph
Code:
python3
from sklearn.svm import SVCclassifier = SVC(kernel ='poly', degree = 4)classifier.fit(x_train, y_train) # training set in x, y axis
Linear Kernel: used when data is linearly separable.
Code: 
python3
from sklearn.svm import SVCclassifier = SVC(kernel ='linear')classifier.fit(x_train, y_train) # training set in x, y axis
punamsingh628700
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Decision Tree
Search Algorithms in AI
Python | Decision tree implementation
Decision Tree Introduction with example
Reinforcement learning
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
ES6 - Loops

At times, certain instructions require repeated execution. Loops are an ideal way to do the same. A loop represents a set of instructions that must be repeated. In a loop’s context, a repetition is termed as an iteration.
The following figure illustrates the classification of loops −
A loop whose number of iterations are definite/fixed is termed as a definite loop. The ‘for loop’ is an implementation of a definite loop.
for (initial_count_value; termination-condition; step) { 
   //statements
}   

The for loop executes the code block for a specified number of times.
The for...in loop is used to loop through an object's properties.
The for...of loop is used to iterate iterables instead of object literals.
An indefinite loop is used when the number of iterations in a loop is indeterminate or unknown.
Indefinite loops can be implemented using −
The while loop executes the instructions each time the condition specified evaluates to true.
The do...while loop is similar to the while loop except that the do...while loop doesn’t evaluate the condition for the first time the loop executes.
The break statement is used to take the control out of a construct.
The continue statement skips the subsequent statements in the current iteration and takes the control back to the beginning of the loop.
A label is simply an identifier followed by a colon (:) that is applied to a statement or a block of code. A label can be used with break and continue to control the flow more precisely.
Line breaks are not allowed between the ‘continue’ or ‘break’ statement and its label name. Also, there should not be any other statement in between a label name and an associated loop
A label can be used with break and continue to control the flow more precisely.
Line breaks are not allowed between the ‘continue’ or ‘break’ statement and its label name.

    32 Lectures 
     3.5 hours 

 Sharad Kumar

    40 Lectures 
     5 hours 

 Richa Maheshwari

    16 Lectures 
     1 hours 

 Anadi Sharma

    50 Lectures 
     6.5 hours 

 Gowthami Swarna

    14 Lectures 
     1 hours 

 Deepti Trivedi

    31 Lectures 
     1.5 hours 

 Shweta
 Print
 Add Notes
 Bookmark this page
How can a particular group of test cases get executed in TestNG?

We can run a particular set of test cases by including a group of test cases
in the execution.
Testng xml files with groups.
<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name = "Tutorialspoint Test">
   <test name = "Regression Cycle 1">
      <groups>
         <run>
            <include name = "Smoke"/>
         </run>
      </groups>
      <classes>
         <class name = "TestParam" />
      </classes>
   </test>
</suite>
To run a group of test cases from the set of test cases, we have to define <groups > in the testng xml file. Here the testNG xml contains group Smoke to be included in execution.
@Test(groups={"Smoke"})
public void Payment(){
   System.out.println(“Payment is successful”);
}
In the Java class file only the test method with group as Smoke will be run out of the entire regression suite.
Resolve java.sql.SQLException: No suitable driver found for localhost test?

You will get this type of exception whenever your JDBC URL is not accepted by any of the loaded JDBC drivers by the method acceptsURL. You need to mention the MySQL JDBC driver which is as follows −
The MySQL JDBC url is as follows −
jdbc:mysql://localhost:3306/test?useSSL=false
The prototype of acceptsURL is as follows −
boolean acceptsURL(String url) throws SQLException
The acceptsURL returns boolean that means if the JDBC driver understands the database URL it returns true otherwise false. It takes one parameter of type String which is a database URL.
The entire database URL connection is as follows. The syntax −
con = DriverManager.
getConnection("jdbc:mysql://localhost:3306/yourDatabaseName?useSSL=false", "yourUserName", " yourPassword");
The Java code is as follows −
import java.sql.Connection;
import java.sql.DriverManager;
public class AvoidSQLException {
   public static void main(String[]args){
      Connection con = null;
      try {
         con = DriverManager.
         getConnection("jdbc:mysql://localhost:3306/sample?useSSL=false", "root", "123456");
         System.out.println("Connection is successful !!!!!");
      } catch(Exception e) {
         e.printStackTrace();
      }
   }
}
The snapshot of code is as follows −
The following is the output −
Connection is successful !!!!!
The snapshot of the sample code is as follows −
C Program to count trailing and leading zeros in a binary number

To begin with, let us understand what are trailing zeros in a binary number.
The position of zeros after first one from the least significant bit (LSB) is called as trailing zeros in binary number.
104 is decimal number
Binary number of 104 is: (MSB) 1101000(LSB)
Here,
MSB refers to Most Significant Bit.
LSB refers to Least Significant Bit.
From LSB after the first bit set, there are three zero.
The number of trailing zeros is three.
Following is the program to count number of trailing zeros for a given number −
 Live Demo
#include<stdio.h>
#include<stdlib.h>
int main(){
   int number, i, trail = 0, size;
   printf("Enter a number\n");
   scanf("%d",&number);
   size = sizeof(number) * 8;
   for(i = 0; i < size; i++){
      if((number >> i) & 1) {
         break;
      }
      trail++;
   }
   printf("Number of trailing ZERO is = %d", trail);
   return 0;
}
When the above program is executed, it produces the following result −
Enter a number
24
Number of trailing ZERO is = 3
If the position of zero before bit is set to one, they are termed as leading zeros.
94 is decimal number.
Binary number of 94 is: (MSB) .....001011110(LSB)
Number of Leading ZERO is = 25
Given below is the program to count number of leading zeros for a given number.
 Live Demo
#include<stdio.h>
#include<stdlib.h>
int main(){
   int number, i, lead = 0, Msb,size;
   printf("Enter a number\n");
   scanf("%d",&number);
   size = sizeof(number) * 8;
   Msb=1<<(size-1);
   for(i = 0; i < size; i++){
      if((number << i) & Msb) {
         break;
      }
      lead++;
   }
   printf("Number of Leading ZERO is = %d", lead);
   return 0;
}
When the above program is executed, it produces the following result −
Enter a number
94
Number of Leading ZERO is = 25
Custom list split in Python

Data analytics throws complex scenarios where the data need to be wrangled to moved around. In this context let’s see how we can take a big list and split it into many sublists as per the requirement. In this article we will explore the approaches to achieve this.
In this approach we use list dicing to get the elements from the point at which the splitting has to happen. Then we use zip and for loop to create the sublists using a for loop.
 Live Demo
Alist = ['Mon', 'Tue', 'Wed', 6, 7, 'Thu', 'Fri', 11, 21, 4]

# The indexes to split at
split_points = [2, 5, 8]

# Given list
print("Given list : " + str(Alist))

# SPlit at
print("The points of splitting : ",split_points)

#Perform the split
split_list = [Alist[i: j] for i, j in zip([0] +
split_points, split_points + [None])]

# printing result
print("The split lists are : ", split_list)

Running the above code gives us the following result −
Given list : ['Mon', 'Tue', 'Wed', 6, 7, 'Thu', 'Fri', 11, 21, 4]
The points of splitting : [2, 5, 8]
The split lists are : [['Mon', 'Tue'], ['Wed', 6, 7], ['Thu', 'Fri', 11], [21, 4]]
The chain function makes an iterator that returns elements from the first iterable until it is exhausted. So it marks the points where the splitting happens. Then we use the zip function to package the result of splitting into sublists.
 Live Demo
from itertools import chain
Alist = ['Mon', 'Tue', 'Wed', 6, 7, 'Thu', 'Fri', 11, 21, 4]

# The indexes to split at
split_points = [2, 5, 8]

# Given list
print("Given list : ", str(Alist))

# Split at
print("The points of splitting : ",split_points)

# to perform custom list split
sublists = zip(chain([0], split_points), chain(split_points, [None]))
split_list = list(Alist[i : j] for i, j in sublists)

# printing result
print("The split lists are : ", split_list)

Running the above code gives us the following result −
Given list : ['Mon', 'Tue', 'Wed', 6, 7, 'Thu', 'Fri', 11, 21, 4]
The points of splitting : [2, 5, 8]
The split lists are : [['Mon', 'Tue'], ['Wed', 6, 7], ['Thu', 'Fri', 11], [21, 4]]
When to use yield instead of return in Python?

In short, whenever control reach the return statement in your program, the execution of the program is terminated and the remaining statements will not executed.
However, in case of yield, whenever control reach the yield statement in your program, the execution of your program is paused and later we can continue other statements in function.
Let’s understand both the statements in detail.
Using yield statement in a function makes the function a generator function which can be used in a loop. When the function is running and the yield statement exeucutes, the value after the yield is passed back to the loop that called it. The next time the loop iterates, the function starts immediately after the yield statements.
def func():
   yield 1
   yield 2
   yield 3

for num in func():
   print(num * num)
1
4
9
In above program, the loop that invokes the function will complete when the func function completes – either meets the end of the function (func()) or a return statement.
However, any new loop that uses the same generator function will execute the function from the start again.
A return statement,
Used to stop the execution of a function and optionally return a value to the caller. A function which has a return (but not a yield) cannot be used in a loop (unlike the yield above).
Used to stop the execution of a function and optionally return a value to the caller. A function which has a return (but not a yield) cannot be used in a loop (unlike the yield above).
If a function which has previously executed is called again, the function begins execution from the start (unlike the yield above).
If a function which has previously executed is called again, the function begins execution from the start (unlike the yield above).
It is recommended to use yield when we want to iterate over a sequence however, because of resource constraints or simply don’t want to store the entire sequence in memory. For other cases we can think of using return statement.
Let’s look at another program using yield statement to generate square of integer number.
def Square():
   i = 1;
   # An Infinite loop to generate squares
   while True:
      yield i*i
      i += 1 # Next execution resumes from this point
for num in Square():
   if num > 100:
      break
   print(num)
1
4
9
16
25
36
49
64
81
100
The yield statement is generally not used in the try clause of a try .... finally block because there’s no guarantee that the generator will ever be resumed, hence no guarantee that the finally block will ever get executed.
How to get the square root of 2 in JavaScript?

To get the square root of 2, use the JavaScript Math SQRT2 property. It returns the square root of 2 which is approximately 1.414.
You can try to run the following code to get the square root of 2 in JavaScript −
<html>
   <head>
      <title>JavaScript Math SQRT2 Property</title>
   </head>
   <body>
      <script>
         var property_value = Math.SQRT2
         document.write("Property Value: " + property_value);
      </script>
   </body>
</html>
fread() function in C++ program

Given the task is to show the working of fread() in C++. In this article we will also look into the different parameters which are passed to fread() and what this function returns.
fread() is an inbuilt function of C++ which reads a block of data from the stream. This function counts the number of objects each with the size of “size” bytes from the stream and stores them in buffer memory, then position pointer advanced by the total amount of bytes read. The amount of bytes read if successful will be size *count.
fread(void *buffer, size_t size, size_t count, FILE *file_stream);
This function will require all 4 parameters. Let’s understand the parameters.
buffer − This is a pointer of a buffer memory block where the bytes read from stream are stored.
buffer − This is a pointer of a buffer memory block where the bytes read from stream are stored.
size − It defines the size of each element to be read in bytes. (size_t is unsigned int).
size − It defines the size of each element to be read in bytes. (size_t is unsigned int).
count − The number of elements to be read.\
count − The number of elements to be read.\
file_stream − Pointer of the file stream from which we want to read the bytes.
file_stream − Pointer of the file stream from which we want to read the bytes.
The number of elements successfully read is returned.
If any reading error occurs or it reaches end-of-file the number of elements returned will vary from the count variable.
#include <bits/stdc++.h>
#include <cstdio>
using namespace std;
int main() {
   FILE* file_stream;
   char buf[100];
   file_stream = fopen("tp.txt", "r");
   while (!feof(file_stream)) //will read the file {
      // will read the contents of the file.
      fread(buf, sizeof(buf), 1, file_stream);
      cout << buf;
   }
   return 0;
}
Assuming the tp.txt file have the following content
tutorialspoint
Contribution
anything here
If we run the above code it will generate the following output −
tutorialspoint
Contribution
anything here
Let’s take example and check the output when the count is zero and the size is zero.
 Live Demo
#include <iostream>
#include <cstdio>
using namespace std; int main() {
   FILE *fp;
   char buffer[100];
   int retVal;
   fp = fopen("tpempty.txt","rb");
   retVal = fread(buffer,sizeof(buffer),0,fp);
   cout << "The count = 0, then return value = " << retVal << endl;
   retVal = fread(buffer,0,1,fp);
   cout << "The size = 0, then value = " << retVal << endl;
   return 0;
}
If we run the above code it will generate the following output −
The count = 0, then return value = 0
The size = 0, then value = 0
MySQL new user access denied even after giving privileges?

After creating a user and giving all privileges to the user, you need to FLUSH PRIVILEGES to set up and want the new settings to work correctly.
The syntax is as follows −
FLUSH PRIVILEGES;
Here is the query to create a new user which has the name ‘Bob’ in my case. The query to create a new user is as follows −
mysql> CREATE USER 'Bob'@'%' IDENTIFIED BY '123456';
Query OK, 0 rows affected (0.56 sec)
Now given all privileges to user Bob −
mysql> GRANT ALL PRIVILEGES ON *.* TO 'Bob'@'%' WITH GRANT OPTION;
Query OK, 0 rows affected (0.23 sec)
Now flush the privileges. The query is as follows −
mysql> FLUSH PRIVILEGES;
Query OK, 0 rows affected (0.14 sec)
Now here I am using user Bob with password 123456. The snapshot is as follows −