code-rag-bench/online-tutorials huggingface dataset:
short keyword in C#

22 Jun, 2020
Keywords are the words in a language that are used for some internal process or represent some predefined actions. short is a keyword that is used to declare a variable which can store a signed integer value from the range -32, 768 to 32, 767. It is an alias of System.Int16.
Syntax:
short variable_name = value;
short keyword occupies 2 bytes (16 bits) space in the memory.
Example:
Input: num: 2

Output: num: 2
        Size of a short variable: 2

Input: num = 20200

Output: num: 20200
        Type of num: System.Int16
        Size of a short variable: 2

Example 1:
// C# program for short keywordusing System;using System.Text;  class Prog {      static void Main(string[] args)    {        // variable declaration        short num = 2;          // to print value        Console.WriteLine("num: " + num);          // to print size        Console.WriteLine("Size of a short variable: " + sizeof(short));    }}
Output:
num: 2
Size of a short variable: 2

Example 2:
// C# program for short keywordusing System;using System.Text;  namespace Test {  class Prog {      static void Main(string[] args)    {        // variable declaration        short num = 20200;          // to print value        Console.WriteLine("num: " + num);          // to print type of variable        Console.WriteLine("Type of num: " + num.GetType());          // to print size        Console.WriteLine("Size of a short variable: " + sizeof(short));          // to print minimum & maximum value of short        Console.WriteLine("Min value of short: " + short.MinValue);        Console.WriteLine("Max value of short: " + short.MaxValue);          // hit ENTER to exit        Console.ReadLine();    }}}
Output:
num: 20200
Type of num: System.Int16
Size of a short variable: 2
Min value of short: -32768
Max value of short: 32767

CSharp-keyword
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# | Multiple inheritance using interfaces
Differences Between .NET Core and .NET Framework
Extension Method in C#
C# | List Class
HashSet in C# with Examples
C# | .NET Framework (Basic Architecture and Component Stack)
Switch Statement in C#
Lambda Expressions in C#
Partial Classes in C#
Hello World in C#
Choose Specific Columns of a Data Frame in R Programming – select() Function

19 Jun, 2020
select() function in R Language is used to choose whether a column of the data frame is selected or not.
Syntax: select(x, expr)
Parameters:x: Data frameexpr: condition for selection
Example 1:
# R program to select specific columns  # Loading library library(dplyr)    # Create a data framed <- data.frame( name = c("Abhi", "Bhavesh", "Chaman", "Dimri"),                   age = c(7, 5, 9, 16),                   ht = c(46, NA, NA, 69),                  school = c("yes", "yes", "no", "no") )     # startswith() function to print only ht data select(d, starts_with("ht"))     # -startswith() function to # print everything except ht data select(d, -starts_with("ht")) 
Output:
  ht
1 46
2 NA
3 NA
4 69
     name age school
1    Abhi   7    yes
2 Bhavesh   5    yes
3  Chaman   9     no
4   Dimri  16     no

Example 2:
# R program to select specific columns  # Loading library library(dplyr)    # Create a data framed <- data.frame( name = c("Abhi", "Bhavesh", "Chaman", "Dimri"),                   age = c(7, 5, 9, 16),                   ht = c(46, NA, NA, 69),                  school = c("yes", "yes", "no", "no") )     # Printing column 1 to 2 select(d, 1:2)     # Printing data of column heading containing 'a' select(d, contains("a"))     # Printing data of column heading which matches 'na' select(d, matches("na")) 
Output:
     name age
1    Abhi   7
2 Bhavesh   5
3  Chaman   9
4   Dimri  16
     name age
1    Abhi   7
2 Bhavesh   5
3  Chaman   9
4   Dimri  16
     name
1    Abhi
2 Bhavesh
3  Chaman
4   Dimri

R DataFrame-Function
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 Split Column Into Multiple Columns in R DataFrame?
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to filter R DataFrame by values in a column?
R - if statement
Logistic Regression in R Programming
Replace Specific Characters in String in R
How to import an Excel File into R ?
Joining of Dataframes in R Programming
Scala Float floor() method with example

29 Oct, 2019
The floor() method is utilized to returns a float number which is less than or equal to the given float number.
Method Definition: (Float_Number).floor
Return Type: It returns a float number which is less than or equal to the given float number.
Example #1:
// Scala program of Float floor()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {              // Applying floor method        val result = (5.4).floor                  // Displays output        println(result)          }} 
5.0

Example #2:
// Scala program of Float floor()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {              // Applying floor method        val result = (-3.8).floor                  // Displays output        println(result)          }} 
-4.0

Scala
Scala-Method
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Naive Pattern Searching

Naïve pattern searching is the simplest method among other pattern searching algorithms. It checks for all character of the main string to the pattern. This algorithm is helpful for smaller texts. It does not need any pre-processing phases. We can find substring by checking once for the string. It also does not occupy extra space to perform the operation.
The time complexity of Naïve Pattern Search method is O(m*n). The m is the size of pattern and n is the size of the main string.
Input:
Main String: “ABAAABCDBBABCDDEBCABC”, pattern: “ABC”
Output:
Pattern found at position: 4
Pattern found at position: 10
Pattern found at position: 18
naivePatternSearch(pattern, text)
Input − The text and the pattern
Output − location, where patterns are present in the text
Begin
   patLen := pattern Size
   strLen := string size

   for i := 0 to (strLen - patLen), do
      for j := 0 to patLen, do
         if text[i+j] ≠ pattern[j], then
            break the loop
      done

      if j == patLen, then
         display the position i, as there pattern found
   done
End
#include<iostream>
using namespace std;

void naivePatternSearch(string mainString, string pattern, int array[], int *index) {
   int patLen = pattern.size();
   int strLen = mainString.size();

   for(int i = 0; i<=(strLen - patLen); i++) {
      int j;
      for(j = 0; j<patLen; j++) {      //check for each character of pattern if it is matched
         if(mainString[i+j] != pattern[j])
            break;
      }

      if(j == patLen) {     //the pattern is found
         (*index)++;
         array[(*index)] = i;
      }
   }
}

int main() {
   string mainString = "ABAAABCDBBABCDDEBCABC";
   string pattern = "ABC";
   int locArray[mainString.size()];
   int index = -1;
   naivePatternSearch(mainString, pattern, locArray, &index);

   for(int i = 0; i <= index; i++) {
      cout << "Pattern found at position: " << locArray[i]<<endl;
   }
}
Pattern found at position: 4
Pattern found at position: 10
Pattern found at position: 18
How to import java.lang.String class in Java?

To import any package in the current class you need to use the import keyword as
import packagename;
Live Demo
import java.lang.String;
public class Sample {
   public static void main(String args[]) {
      String s = new String("Hello");
      System.out.println(s);
   }
}
Hello
What are undefined reference/unresolved external symbol errors in C++?

As the name suggests, a symbol you declared was not defined by you. This may occur due to many cases. Let's have a look at three of them −
You forgot to define the declared name. For example, you declared a function in a file and used it somewhere. But you did not provide its definition. Code −
You forgot to define the declared name. For example, you declared a function in a file and used it somewhere. But you did not provide its definition. Code −
#include<iostream>
void foo();
int main() {
   foo(); // Declared but not defined
}
You defined it but did not use the qualified name. Say you created a class with a method and defined that method but forgot using scope resolution to link that function to that definition and used that function somewhere. For example,
You defined it but did not use the qualified name. Say you created a class with a method and defined that method but forgot using scope resolution to link that function to that definition and used that function somewhere. For example,
#include<iostream>
class A {
   void foo();
};
void foo() { } // should have used A::foo
int main() {
   A a;
   a.foo(); // Not defined!
}
You did not include dependencies in incorrect order. The linker tries to link in the order you specify to it. So in case you use a method before its definition, it will likely give this error.
You did not include dependencies in incorrect order. The linker tries to link in the order you specify to it. So in case you use a method before its definition, it will likely give this error.
Creating an exhaustive list of conditions that can cause this error is not possible. But you can refer to this post for a very well-curated list of likely reasons − https://stackoverflow.com/questions/12573816/what-is-an-undefined-reference-unresolved-external-symbol-error-and-how-do-i-fix
Example of a nested table in HTML

The following is an example of a nested table in HTML:
<!DOCTYPE html>
<html>
   <head>
      <meta charset="utf-8">
      <title>Example</title>
   </head>
   <body>
      <table>
         <tbody>
            <tr>
               <td>
                  <table>
                     <tbody>
                        <tr>
                           <td>My</td>
                           <td>Table</td>
                        </tr>
                     </tbody>
                  </table>
               </td>
            </tr>
         </tbody>
      </table>
   </body>
</html>
Bootstrap .btn class

Use the .btn class in Bootstrap to add a button to the web page.
You can try to run the following code to implement a .btn class
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>Bootstrap Example</title>
      <meta name = "viewport" content = "width=device-width, initial-scale = 1">
      <link rel = "stylesheet" href = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <script src = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
   </head>
   <body>
      <!-- Standard button -->
      <button type = "button" class = "btn btn-default"> Result</button>
   </body>
</html>
dl-horizontal class in Bootstrap

In definition list, each list item can consist of both the <dt> and the <dd> elements. <dt> stands for definition term, and like a dictionary, this is the term (or phrase) that is being defined. Subsequently, the <dd> is the definition of the <dt>. You can make terms and descriptions in <dl> line up side-by-side using class dl-horizontal.
You can try to run the following code to implement the dl-horizontal class:
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>Bootstrap lists</title>
      <meta name = "viewport" content = "width=device-width, initial-scale = 1">
      <link rel = "stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <script src = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
   </head>
   <body>
      <h1>Lists</h1>
      <h2>Fruits (Ordered List)</h2>
      <ol>
         <li>Kiwi</li>
         <li>Apple</li>
         <li>Mango</li>
      </ol>
      <h2>Vegetables (UnOrdered List)</h2>
      <ul>
         <li>Tomato</li>
         <li>Brinjal</li>
         <li>Broccoli</li>
      </ul>
      <h2>Horizontal Definition List</h2>
      <dl class = "dl-horizontal">
         <dt>Description 1</dt>
         <dd>Item 1</dd>
         <dt>Description 2</dt>
         <dd>Item 2</dd>
      </dl>
   </body>
</html>
JavaScript Number - toFixed()

This method formats a number with a specific number of digits to the right of the decimal.
Its syntax is as follows −
number.toFixed( [digits] )

digits − The number of digits to appear after the decimal point.
A string representation of number that does not use exponential notation and has the exact number of digits after the decimal place.
Try the following example.
<html>
   <head>
      <title>JavaScript toFixed() Method</title>
   </head>
   
   <body>      
      <script type = "text/javascript">
         var num = 177.1234;
         document.write("num.toFixed() is : " + num.toFixed()); 
         document.write("<br />"); 
      
         document.write("num.toFixed(6) is : " + num.toFixed(6)); 
         document.write("<br />"); 
      
         document.write("num.toFixed(1) is : " + num.toFixed(1)); 
         document.write("<br />"); 
      
         document.write("(1.23e+20).toFixed(2) is:" + (1.23e+20).toFixed(2)); 
         document.write("<br />"); 
      
         document.write("(1.23e-10).toFixed(2) is : " + (1.23e-10).toFixed(2)); 
      </script>   
   </body>
</html>
num.toFixed() is : 177
num.toFixed(6) is : 177.123400
num.toFixed(1) is : 177.1
(1.23e+20).toFixed(2) is:123000000000000000000.00
(1.23e-10).toFixed(2) is : 0.00 


    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
Check if a key is present in a C++ map or unordered_map

In C++ the Maps and unordered maps are hash tables. They use some keys and their respective key values. Here we will see how to check whether a given key is present in the hash table or not. The code will be like below −
 Live Demo
#include<iostream>
#include<map>
using namespace std;
string isPresent(map<string, int> m, string key) {
   if (m.find(key) == m.end())
   return "Not Present";
   return "Present";
}
int main() {
   map<string, int> my_map;
   my_map["first"] = 4;
   my_map["second"] = 6;
   my_map["third"] = 6;
   string check1 = "fifth", check2 = "third";
   cout << check1 << ": " << isPresent(my_map, check1) << endl;
   cout << check2 << ": " << isPresent(my_map, check2);
}
fifth: Not Present
third: Present
Python | sympy.isprime() method

25 Aug, 2021
In simpy module, we can test whether a given number n is prime or not using sympy.isprime() function. For n < 2^64 the answer is definitive; larger n values have a small probability of actually being pseudoprimes. 
Note that Negative numbers (e.g. -13) are not considered as prime number.
Syntax:  sympy.isprime()
Parameter:  n; number to be tested
Return:  bool value result 
Code #1:  
Python3
# Python program to check prime number# using sympy.isprime() method # importing sympy modulefrom sympy import * # calling isprime function on different numbersisprime(30)isprime(13)isprime(2)
Output: 
False
True
True
Code #2:  
Python3
# Python program to check prime number# using sympy.isprime() method # importing sympy moduleimport sympy.ntheory as nt # calling isprime function on different numbersnt.isprime(30)nt.isprime(13)nt.isprime(2)
Output: 
False
True
True
 
anikakapoor
SymPy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
What are static members of a Java class?

In Java, static members are those which belongs to the class and you can access these members without instantiating the class.
The static keyword can be used with methods, fields, classes (inner/nested), blocks.
Static Methods − You can create a static method by using the keyword static. Static methods can access only static fields, methods. To access static methods there is no need to instantiate the class, you can do it just using the class name as −
 Live Demo
public class MyClass {
   public static void sample(){
      System.out.println("Hello");
   }
   public static void main(String args[]){
      MyClass.sample();
   }
}
Hello

Static Fields − You can create a static field by using the keyword static. The static fields have the same value in all the instances of the class. These are created and initialized when the class is loaded for the first time. Just like static methods you can access static fields using the class name (without instantiation).
 Live Demo
public class MyClass {
   public static int data = 20;
   public static void main(String args[]){
      System.out.println(MyClass.data);
   }
   Java Arrays with Answers
   27
}
20

Static Blocks − These are a block of codes with a static keyword. In general, these are used to initialize the static members. JVM executes static blocks before the main method at the time of class loading.
 Live Demo
public class MyClass {
   static{
      System.out.println("Hello this is a static block");
   }
   public static void main(String args[]){
      System.out.println("This is main method");
   }
}
Hello this is a static block
This is main method
Java - String Buffer delete() Method

This method removes the characters in a substring of this StringBuffer. The substring begins at the specified start and extends to the character at index end - 1 or to the end of the StringBuffer if no such character exists.
If start is equal to end, no changes are made.
Here is the syntax of this method −
public StringBuffer delete(int start, int end)

Here is the detail of parameters −
start − The beginning index, inclusive.
start − The beginning index, inclusive.
end − The ending index, exclusive.
end − The ending index, exclusive.
This method returns the StringBuffer object.
public class Test {

   public static void main(String args[]) {
      StringBuffer sb = new StringBuffer("abcdefghijk");
      sb.delete(3, 7); 
      System.out.println(sb); 
   }  
}
This will produce the following result −
abchijk


    16 Lectures 
     2 hours 

 Malhar Lathkar

    19 Lectures 
     5 hours 

 Malhar Lathkar

    25 Lectures 
     2.5 hours 

 Anadi Sharma

    126 Lectures 
     7 hours 

  Tushar Kale

    119 Lectures 
     17.5 hours 

 Monica Mittal

    76 Lectures 
     7 hours 

 Arnab Chakraborty
 Print
 Add Notes
 Bookmark this page
JavaScript String - slice() Method

This method extracts a section of a string and returns a new string.
The syntax for slice() method is −
string.slice( beginslice [, endSlice] );

beginSlice − The zero-based index at which to begin extraction.
beginSlice − The zero-based index at which to begin extraction.
endSlice − The zero-based index at which to end extraction. If omitted, slice extracts to the end of the string.
endSlice − The zero-based index at which to end extraction. If omitted, slice extracts to the end of the string.
If successful, slice returns the index of the regular expression inside the string. Otherwise, it returns -1.
Try the following example.
<html>
   <head>
      <title>JavaScript String slice() Method</title>
   </head>
   
   <body>   
      <script type = "text/javascript">
         var str = "Apples are round, and apples are juicy.";
         var sliced = str.slice(3, -2);         
         document.write( sliced );
      </script>      
   </body>
</html>
les are round, and apples are juic


    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 to Insert an Image in HTML?

04 Aug, 2021
We can use different fonts and lists in an HTML document. Similarly, we can add graphics to make the document look more attractive. Web browsers support a number of graphic formats. Some of the most widely used formats are:
Graphics Interchange Format(GIF): GIF is the best format displaying images designed with a graphics program. This format uses a maximum of 256 colors and a combination of these to create more colors.
Joint Photographic Expert Group(JPEG): JPEG is the best format for photographs as it contains 1 million colors.
Portable Network Graphics(PNG): The format is best for images with transparency or the low color count.
Use of <img>Tag
The <img> tag specifies an image to be displayed in an HTML document. It is an element as it does not have an OFF tag.
The image tag has the following attributes in the table:
Specifies the alternative text for an image. This is displayed when the graphics feature is turned off in the browser or while 
The image is being downloaded. In some browsers, the ALT text is displayed as a tooltip for the image. 
The following HTML code will help you understand the <img>tag better. The resulting web page is shown in the output.
HTML
<!DOCTYPE html><html>    <style>        image{border:4px solid orange; width: 120px;height: 100px;}        h1{text-transform:uppercase}    </style><head>    <title>        HTML frame scrolling Attribute    </title></head><body>    <h1>INSERTING IMAGE</h1>    <img src="5.png" alt="image is not available"></body></html>
Output:
HTML
<!DOCTYPE html><html><head>    <title>        HTML frame scrolling Attribute    </title></head><body>    <h1>INSERTING IMAGE</h1>    <img src="5.png" alt="image is not available" width="120px" height="100px"></body></html>
Output:
Supported browsers are:
Google Chrome
Internet Explorer
Firefox
Opera
Safari
simmytarika5
Picked
class 7
School Learning
School Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Flora and Fauna of Ladakh
Akbar's Policies
Working of the Government in India
Equality in Indian Democracy
Components of Environment
Libraries in Python
What are Different Output Devices?
Generations of Computers - Computer Fundamentals
GeeksforGeeks School
Reading Rows from a CSV File in Python
How to create a Scatter Plot with several colors in Matplotlib?

07 Feb, 2022
Matplotlib is a plotting library for creating static, animated, and interactive visualizations in Python. Matplotlib can be used in Python scripts, the Python and IPython shell, web application servers, and various graphical user interface toolkits like Tkinter, awxPython, etc.
In-order to create a scatter plot with several colors in matplotlib, we can use the various methods:
Method #1: Using the parameter marker color i.e. c
The possible values for marker color are:
A single color format string.
A 2-D array in which the rows are RGB or RGBA.
Example:
Using the c parameter to depict scatter plot with different colors.
Python3
# import required moduleimport matplotlib.pyplot as plt # first data pointx = [1, 2, 3, 4]y = [4, 1, 3, 6] # depict first scatted plotplt.scatter(x, y, c='green') # second data pointx = [5, 6, 7, 8]y = [1, 3, 5, 2] # depict second scatted plotplt.scatter(x, y, c='red') # depict illustrationplt.show()
Output:
Method #2: Using the colormap
Colormap instances are used to convert data values (floats) from the interval [0, 1] to the RGBA color.
Example 1:
Using the colormap to depict scatter plot with RGB colors.
Python3
# import required modulesimport matplotlib.pyplot as pltimport numpy # assign data pointsa = numpy.array([[9, 1, 2, 7, 5, 8, 3, 4, 6],                 [4, 2, 3, 7, 9, 1, 6, 5, 8]]) # assign categoriescategories = numpy.array([0, 1, 2, 0, 1, 2, 0, 1, 2]) # use colormapcolormap = numpy.array(['r', 'g', 'b']) # depict illustrationplt.scatter(a[0], a[1], s=100, c=colormap[categories])plt.show()
Output:
Example 2:
Here, we manually assign the colormap using color codes.
Python3
# import required modulesimport matplotlib.pyplot as pltimport numpy # assign data pointsa = numpy.array([[1, 2, 3, 4, 5, 6, 7, 8, 9],                 [9, 8, 7, 6, 5, 4, 3, 2, 1]]) # assign categoriescategories = numpy.array([0, 1, 1, 0, 0, 1, 1, 0, 1]) # assign colors using color codescolor1 = (0.69411766529083252, 0.3490196168422699,          0.15686275064945221, 1.0)color2 = (0.65098041296005249, 0.80784314870834351,          0.89019608497619629, 1.0) # assign colormapcolormap = numpy.array([color1, color2]) # depict illustrationplt.scatter(a[0], a[1], s=500, c=colormap[categories])plt.show()
Output:
anikakapoor
kk9826225
Python-matplotlib
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Iterate over a list in Python
How to iterate through Excel rows in Python?
Python map() function
Read JSON file using Python
Enumerate() in Python
Adding new column to existing DataFrame in Pandas
Python Dictionary
How to get column names in Pandas dataframe
Deque in Python
Stack in Python
Thread hardware_concurrency() function in C++

30 Oct, 2018
Thread::hardware_concurrency is an in-built function in C++ std::thread. It is an observer function which means it observes a state and then returns the corresponding output. This function returns the number of concurrent threads supported by the available hardware implementation. This value might not always be accurate.
Syntax:
thread::hardware_concurrency()
Parameters: This function does not accept any parameters.
Return Value: It returns a non-negative integer denoting the number of concurrent threads supported by the system. If the value is either not computable or not well defined it returns 0.
Below program demonstrate the use of std::thread::joinable()
Note: On the online IDE this program will show error. To compile this, use the flag “-pthread” on g++ compilers compilation with the help of command “g++ –std=c++14 -pthread file.cpp”.
// C++ program to demonstrate the use of// std::thread::hardware_concurrency()  #include <chrono>#include <iostream>#include <thread>using namespace std;  int main(){    unsigned int con_threads;      // calculating number of concurrent threads    // supported in the hardware implementation    con_threads = thread::hardware_concurrency();      cout << "Number of concurrent threads supported are: "         << con_threads << endl;      return 0;}
Possible Output
Number of concurrent threads supported are: 4
cpp-multithreading
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sorting a vector in C++
Polymorphism in C++
Friend class and function in C++
Pair in C++ Standard Template Library (STL)
std::string class in C++
Queue in C++ Standard Template Library (STL)
Unordered Sets in C++ Standard Template Library
std::find in C++
List in C++ Standard Template Library (STL)
Inline Functions in C++
JavaScript Logical AND assignment (&&=) Operator

25 Feb, 2021
This operator is represented by x &&= y, and it is called the logical AND assignment operator. It assigns the value of y into x only if x is a truthy value.
We use this operator x &&= y like this. Now break this expression into two parts, x && (x = y).  If the value of x is truth, then the statement (x = y) executes and the value of y gets stored into x but if the value of x is a falsy value then the statement (x = y) does not get executed.
Syntax :
x &&= y
is equivalent to 
x && (x = y)
Example:
Javascript
<script>  let name = {    firstName: "Ram",    lastName: "",  };    console.log(name.firstName);    // Changing the value using logical  // AND assignment operator  name.firstName &&= "Shyam";    // Here the value changed because  // name.firstName is truthy  console.log(name.firstName);    console.log(name.lastName);    // Changing the value using logical   // AND assignment operator  name.lastName &&= "Kumar";    // Here the value remains unchanged   // because name.lastName is falsy  console.log(name.lastName);</script>
Output :
"Ram"
"Shyam"
""
""
Example 2:
HTML
<!DOCTYPE html><html>  <body>  <h1>Hello Geeksforgeeks</h1>  <p id="print_arr"></p>    <script>            let arr = [1, 2, "apple", null, undefined, []]              // Replace each truthy values with "gfg"              arr.forEach((item, index)=>{        arr[index] &&= "gfg"    })      document.getElementById("print_arr").innerText = arr.toString();    //console.log(arr)  </script>    </body></html>
Output :
Supported Browsers:
Chrome 85
Edge 85
Firefox 79
Safari 14
javascript-operators
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
Remove elements from a JavaScript Array
JavaScript String includes() Method
Implementation of LinkedList in Javascript
DOM (Document Object Model)
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 create footer to stay at the bottom of a Web page?
How to set the default value for an HTML <select> element ?
Java Constructors

A constructor in Java is a special method that is used to initialize objects. 
The constructor is called when an object of a class is created. It can be used to 
set initial values for object attributes:
Create a constructor:
// Create a Main class
public class Main {
  int x;  // Create a class attribute

  // Create a class constructor for the Main class
  public Main() {
    x = 5;  // Set the initial value for the class attribute x
  }

  public static void main(String[] args) {
    Main myObj = new Main(); // Create an object of class Main (This will call the constructor)
    System.out.println(myObj.x); // Print the value of x
  }
}

// Outputs 5
 


Try it Yourself »

Note that the constructor name must match the class name, and it cannot have a 
return type (like void). 
Also note that the constructor is called when the object is created.
All classes have constructors by default: if you do not create a class constructor 
yourself, Java creates one for you. However, then you are not able to set initial values for object attributes.
Constructors can also take parameters, which is used to initialize 
attributes.
The following example adds an int y parameter 
to the constructor. 
Inside the constructor we set x to y (x=y). When we call 
the constructor, we pass a parameter to the constructor (5), which will set the value of 
x to 5:
public class Main {
  int x;

  public Main(int y) {
    x = y;
  }

  public static void main(String[] args) {
    Main myObj = new Main(5);
    System.out.println(myObj.x);
  }
}

// Outputs 5
 


Try it Yourself »

You can have as many parameters as you want:
public class Main {
  int modelYear;
  String modelName;

  public Main(int year, String name) {
    modelYear = year;
    modelName = name;
  }

  public static void main(String[] args) {
    Main myCar = new Main(1969, "Mustang");
    System.out.println(myCar.modelYear + " " + myCar.modelName);
  }
}

// Outputs 1969 Mustang
 


Try it Yourself »

We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
How to find left position of element in horizontal scroll container using jQuery?

To find the left position of element in horizontal scroll container using jQuery, use the animate() function with the scrollLeft() function.
You can try to run the following code to learn how to find left position of an element in horizontal scroll container:
Live Demo
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
   
   var scrollArea = $('#box');
   var toScroll = $('#box .myclass');

   function myScroll() {
     toScroll.each(function() {
        var self = $(this);
        $(this).css('cursor', 'pointer');
        $(this).on('click', function () {
            var leftOffset = self.offset().left - scrollArea.offset().left +    scrollArea.scrollLeft();
            scrollArea.animate({ scrollLeft: leftOffset });
            alert(leftOffset);
        });    
     });
   };
 myScroll();
});
</script>
<style>
#box {
    width: 250px;
    height: 300px;
    margin-left: 20px;
    border: 1px solid black;
    overflow-x: scroll;
    white-space: nowrap;
}
.myclass {
    width: 250px;
    height: 100px;
    margin: 35px;
    display: inline-block;
    background: -webkit-linear-gradient(left, red , blue);
    background: -o-linear-gradient(right, red, blue);
    background: -moz-linear-gradient(right, red, blue);
    background: linear-gradient(to right, red , blue);
}
</style>
</head>
<body>
    <p>Get left position of element.</p>
<div id="box">
    <div class="myclass">First (Click Me)</div>
    <div class="myclass">Second (Click Me)</div>
    <div class="myclass">Third (Click Me)</div>
</div>

</body>
</html>
Topological Sorting

The topological sorting for a directed acyclic graph is the linear ordering of vertices. For every edge U-V of a directed graph, the vertex u will come before vertex v in the ordering.
As we know that the source vertex will come after the destination vertex, so we need to use a stack to store previous elements. After completing all nodes, we can simply display them from the stack.
Input:
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 1 0 0
0 1 0 0 0 0
1 1 0 0 0 0
1 0 1 0 0 0

Output:
Nodes after topological sorted order: 5 4 2 3 1 0
topoSort(u, visited, stack)
Input − The start vertex u, An array to keep track of which node is visited or not. A stack to store nodes.Output − Sorting the vertices in topological sequence in the stack.
Begin
   mark u as visited
   for all vertices v which is adjacent with u, do
      if v is not visited, then
         topoSort(c, visited, stack)
   done

   push u into a stack
End
performTopologicalSorting(Graph)
Input − The given directed acyclic graph.Output − Sequence of nodes.
Begin
   initially mark all nodes as unvisited
   for all nodes v of the graph, do
      if v is not visited, then
         topoSort(i, visited, stack)
   done
   pop and print all elements from the stack
End.
#include<iostream>
#include<stack>
#define NODE 6
using namespace std;

int graph[NODE][NODE] = {
   {0, 0, 0, 0, 0, 0},
   {0, 0, 0, 0, 0, 0},
   {0, 0, 0, 1, 0, 0},
   {0, 1, 0, 0, 0, 0},
   {1, 1, 0, 0, 0, 0},
   {1, 0, 1, 0, 0, 0}
};

void topoSort(int u, bool visited[], stack<int>&stk) {
   visited[u] = true;                //set as the node v is visited

   for(int v = 0; v<NODE; v++) {
      if(graph[u][v]) {             //for allvertices v adjacent to u
         if(!visited[v])
            topoSort(v, visited, stk);
      }
   }
   stk.push(u);     //push starting vertex into the stack
}

void performTopologicalSort() {
   stack<int> stk;
   bool vis[NODE];

   for(int i = 0; i<NODE; i++)
      vis[i] = false;     //initially all nodes are unvisited

   for(int i = 0; i<NODE; i++)
      if(!vis[i])     //when node is not visited
         topoSort(i, vis, stk);

   while(!stk.empty()) {
      cout << stk.top() << " ";
      stk.pop();
   }
}

main() {
   cout << "Nodes after topological sorted order: ";
   performTopologicalSort();
}
Nodes after topological sorted order: 5 4 2 3 1 0
3Sum Closest in C++

Suppose we have an array nums with n integers and one target. We have to find three integers in nums such that the sum is closest to the target. We will return the sum of the three integers. We can take one assumption that each input would have exactly one solution. So if the given array is like [-1,2,1,-4] and the target is 1, then the triplet will be [-1,2,1] this has the closest sum, that is 2.
To solve this, we will follow these steps −
Sort the array nums, ans := 0, diff := Infinity, n := size of nums
for i in range 0 to n – 1left := i + 1, right := n – 1while left < righttemp := nums[left] + nums[right] + nums[i]if |target – temp| < diff, then ans := temp and diff := |target – temp|if temp = target, then return temp, otherwise when temp > target, then decrease right by 1, else increase left by 1
left := i + 1, right := n – 1
while left < righttemp := nums[left] + nums[right] + nums[i]if |target – temp| < diff, then ans := temp and diff := |target – temp|if temp = target, then return temp, otherwise when temp > target, then decrease right by 1, else increase left by 1
temp := nums[left] + nums[right] + nums[i]
if |target – temp| < diff, then ans := temp and diff := |target – temp|
if temp = target, then return temp, otherwise when temp > target, then decrease right by 1, else increase left by 1
return ans
Let us see the following implementation to get better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   int threeSumClosest(vector<int>& nums, int target) {
      sort(nums.begin(), nums.end());
      int ans = 0;
      int diff = INT_MAX;
      int n = nums.size();
      for(int i = 0; i < n; i++){
         int left = i + 1;
         int right = n - 1;
         while(left < right){
            int temp = nums[left] + nums[right] + nums[i];
            if(abs(target - temp) < diff){
               ans = temp;
               diff = abs(target - temp);
            }
            if(temp == target)return temp;
            else if(temp > target) right--;
            else left++;
         }
      }
      return ans;
   }
};
main(){
   Solution ob;
   vector<int> v = {-1,2,1,-4};
   cout << ob.threeSumClosest(v, 1);
}
[-1,2,1,-4]
1
2
How to insert a Python tuple in a MySQL database?

Assuming that MySQL database named as test is present on server and a table named employee is also created. The table has five fields fname, lname, age, gender, and salary.
A tuple object containing data of a record is defined as
t1=('Mac', 'Mohan', 20, 'M', 2000)
To establish interface between MySQL  and Python 3, you need to install PyMySQL module. Then you can set up the connection using following statements
import PyMySQL
# Open database connection
db = PyMySQL.connect("localhost","root","","test" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
Next step is to set up the insert query using data in the tuple
sql="insert into employee values(%s,%s,%d,%s,%d)" %t1
Now this query is executed using execute() method of cursor object
cursor.execute(sql)
If you check contents of employee table, it will show new record added in it.
How to concatenate fields in MySQL?

To concatenate fields in MySQL, you can use GROUP_CONCAT() along with GROUP BY. Let us first create a table −
mysql> create table DemoTable
   (
   StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   StudentName varchar(30),
   StudentScore int
   );
Query OK, 0 rows affected (0.51 sec)
Insert records in the table using insert command −
mysql> insert into DemoTable( StudentName,StudentScore) values('Bob',80);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable( StudentName,StudentScore) values('Bob',80);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable( StudentName,StudentScore) values('Chris',90);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable( StudentName,StudentScore) values('Chris',70);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable( StudentName,StudentScore) values('Bob',50);
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable( StudentName,StudentScore) values('David',60);
Query OK, 1 row affected (0.23 sec)
mysql> insert into DemoTable( StudentName,StudentScore) values('Chris',99);
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable( StudentName,StudentScore) values('David',88);
Query OK, 1 row affected (0.18 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable;
This will produce the following output −
+-----------+-------------+--------------+
| StudentId | StudentName | StudentScore |
+-----------+-------------+--------------+
| 1         | Bob         | 80           |
| 2         | Bob         | 80           |
| 3         | Chris       | 90           |
| 4         | Chris       | 70           |
| 5         | Bob         | 50           |
| 6         | David       | 60           |
| 7         | Chris       | 99           |
| 8         | David       | 88           |
+-----------+-------------+--------------+
8 rows in set (0.00 sec)
Following is the query to concatenate fields in MySQL −
mysql> select
StudentName, group_concat(StudentScore separator ',') as Score
from DemoTable
group by StudentName;
This will produce the following output −
+-------------+----------+
| StudentName | Score    |
+-------------+----------+
| Bob         | 80,80,50 |
| Chris       | 90,70,99 |
| David       | 60,88    |
+-------------+----------+
3 rows in set (0.24 sec)
C# program to check for a string that contains all vowels

To check for all vowels, firstly set the condition to check −
string res = str.Where(chk =< "aeiouAEIOU".Contains(chk)).Distinct();
Above, we have used the string −
string str = "the quick brown fox jumps over the lazy dog";
Now, using the Any() method checks whether the string has any vowels or not −
if(!res.Any())
Console.WriteLine("No vowels!");
Loop through the string to get the vowels −
 Live Demo
using System;
using System.Linq;

public class Program {
   public static void Main() {
      string str = "the quick brown fox jumps over the lazy dog";
      var res = str.Where(chk =< "aeiouAEIOU".Contains(chk)).Distinct();

      if(!res.Any())
      Console.WriteLine("No vowels!");

      foreach(var vowel in res)
      Console.WriteLine("Your phrase contains vowel = {0}", vowel);
   }
}
Your phrase contains vowel = e
Your phrase contains vowel = u
Your phrase contains vowel = i
Your phrase contains vowel = o
Your phrase contains vowel = a
Kill Process in C++

Suppose we have n processes, here each process has a unique id called PID or process id and its PPID (parent process id) is also there.
Each process only has one parent process, but may have one or more child processes.
This is just like a tree structure. Only one process has the PPID = 0, which means this process has no parent process. All the PIDs will be unique positive integers.
We will use two list of integers to represent a list of processes, where the first list contains PID for each process and the second list contains the corresponding PPID. So, if we have two lists, and a PID representing a process we want to kill, then we have to find a list of PIDs of processes that will be killed in the end. And we should assume that when a process is killed, all its children processes will be killed.
So, if the input is like pid = [1, 3, 10, 5] ppid = [3, 0, 5, 3] kill = 5, then the output will be [5,10],
Kill 5 will also kill 10.
To solve this, we will follow these steps −
Define one map child
Define one map child
n := size of pid
n := size of pid
Define an array ret
Define an array ret
for initialize i := 0, when i < n, update (increase i by 1), do −u := ppid[i]v := pid[i]insert v at the end of child[u]
for initialize i := 0, when i < n, update (increase i by 1), do −
u := ppid[i]
u := ppid[i]
v := pid[i]
v := pid[i]
insert v at the end of child[u]
insert v at the end of child[u]
Define one queue q
Define one queue q
insert kill into q
insert kill into q
while (not q is empty), do −curr := first element of qdelete element from qinsert curr at the end of retfor initialize i := 0, when i < size of child[curr], update (increase i by 1), do −insert child[curr, i] into q
while (not q is empty), do −
curr := first element of q
curr := first element of q
delete element from q
delete element from q
insert curr at the end of ret
insert curr at the end of ret
for initialize i := 0, when i < size of child[curr], update (increase i by 1), do −insert child[curr, i] into q
for initialize i := 0, when i < size of child[curr], update (increase i by 1), do −
insert child[curr, i] into q
insert child[curr, i] into q
return ret
return ret
Let us see the following implementation to get a better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<auto> v){
   cout << "[";
   for(int i = 0; i<v.size(); i++){
      cout << v[i] << ", ";
   }
   cout << "]"<<endl;
}
class Solution {
public:
   vector<int> killProcess(vector<int>& pid, vector<int>& ppid, int kill) {
      map<int, vector<int> > child;
      int n = pid.size();
      vector<int> ret;
      for (int i = 0; i < n; i++) {
         int u = ppid[i];
         int v = pid[i];
         child[u].push_back(v);
      }
      queue<int> q;
      q.push(kill);
      while (!q.empty()) {
         int curr = q.front();
         q.pop();
         ret.push_back(curr);
         for (int i = 0; i < child[curr].size(); i++) {
            q.push(child[curr][i]);
         }
      }
      return ret;
   }
};
main(){
   Solution ob;
   vector<int> v = {1,3,10,5}, v1 = {3,0,5,3};
   print_vector(ob.killProcess(v, v1, 5));
}
{1,3,10,5},{3,0,5,3},5
[5, 10, ]
Functional Programming - Polymorphism

Polymorphism, in terms of programming, means reusing a single code multiple times. More specifically, it is the ability of a program to process objects differently depending on their data type or class.
Polymorphism is of two types −
Compile-time Polymorphism − This type of polymorphism can be achieved using method overloading.
Compile-time Polymorphism − This type of polymorphism can be achieved using method overloading.
Run-time Polymorphism − This type of polymorphism can be achieved using method overriding and virtual functions.
Run-time Polymorphism − This type of polymorphism can be achieved using method overriding and virtual functions.
Polymorphism offers the following advantages −
It helps the programmer to reuse the codes, i.e., classes once written, tested and implemented can be reused as required. Saves a lot of time.
It helps the programmer to reuse the codes, i.e., classes once written, tested and implemented can be reused as required. Saves a lot of time.
Single variable can be used to store multiple data types.
Single variable can be used to store multiple data types.
Easy to debug the codes.
Easy to debug the codes.
Polymorphic data-types can be implemented using generic pointers that store a byte address only, without the type of data stored at that memory address. For example,
function1(void *p, void *q) 

where p and q are generic pointers which can hold int, float (or any other) value as an argument.
The following program shows how to use polymorphic functions in C++, which is an object oriented programming language.
#include <iostream> 
Using namespace std: 

class A {  
   public: 
   void show() {    
      cout << "A class method is called/n"; 
   } 
}; 

class B:public A { 
   public: 
   void show() {   
      cout << "B class method is called/n"; 
   } 
};  

int main() {   
   A x;        // Base class object 
   B y;        // Derived class object 
   x.show();   // A class method is called 
   y.show();   // B class method is called 
   return 0; 
} 
It will produce the following output −
A class method is called 
B class method is called 

The following program shows how to use polymorphic functions in Python, which is a functional programming language.
class A(object): 
   def show(self): 
      print "A class method is called" 
  
class B(A): 
   def show(self): 
      print "B class method is called" 
  
def checkmethod(clasmethod): 
   clasmethod.show()  

AObj = A() 
BObj = B() 
  
checkmethod(AObj) 
checkmethod(BObj) 
It will produce the following output −
A class method is called 
B class method is called 


    32 Lectures 
     3.5 hours 

 Pavan Lalwani

    11 Lectures 
     1 hours 

 Prof. Paul Cline, Ed.D

    72 Lectures 
     10.5 hours 

 Arun Ammasai

    51 Lectures 
     2 hours 

 Skillbakerystudios

    43 Lectures 
     4 hours 

 Mohammad Nauman

    8 Lectures 
     1 hours 

 Santharam Sivalenka
 Print
 Add Notes
 Bookmark this page