code-rag-bench/online-tutorials huggingface dataset:
Which packages contain Wrapper class in Java?

Java provides certain classes called wrapper classes in the java.lang package. The objects of these classes wrap primitive datatypes within them. Following is the list of primitive data types and their respective classes −
Wrapper classes in Java belong to the java.lang package, Therefore there is no need to import any package explicitly while working with them.
The following Java example accepts various primitive variables from the user and creates their respective wrapper classes.
 Live Demo
import java.util.Scanner;
public class WrapperClassesExample {
   public static void main(String args[]){
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter an integer value: ");
      int i = sc.nextInt();
      //Wrapper class of an integer
      Integer obj1 = new Integer(i);
      System.out.println("Enter a long value: ");
      long l = sc.nextLong();
      //Wrapper class of a long
      Long obj2 = new Long(l);
      System.out.println("Enter a float value: ");
      float f = sc.nextFloat();
      //Wrapper class of a float
      Float obj3 = new Float(f);
      System.out.println("Enter a double value: ");
      double d = sc.nextDouble();
      //Wrapper class of a double
      Double obj4 = new Double(d);
      System.out.println("Enter a boolean value: ");
      boolean bool = sc.nextBoolean();
      //Wrapper class of a boolean
      Boolean obj5 = new Boolean(bool);
      System.out.println("Enter a char value: ");
      char ch = sc.next().toCharArray()[0];
      //Wrapper class of a boolean
      Character obj6 = new Character(ch);
      System.out.println("Enter a byte value: ");
      byte by = sc.nextByte();
      //Wrapper class of a boolean
      Byte obj7 = new Byte(by);
      System.out.println("Enter a short value: ");
      short sh = sc.nextShort();
      //Wrapper class of a boolean
      Short obj8 = new Short(sh);
   }
}
Enter an integer value:
254
Enter a long value:
4444445455454
Enter a float value:
12.324
Enter a double value:
1236.22325
Enter a boolean value:
true
Enter a char value:
c
Enter a byte value:
125
Enter a short value:
14233
Python dictionary items() Method

Python dictionary  method items() returns a list of dict's (key, value) tuple pairs
Following is the syntax for items() method −
dict.items()

NA
NA
This method returns a list of tuple pairs.
The following example shows the usage of items() method.
#!/usr/bin/python

dict = {'Name': 'Zara', 'Age': 7}
print "Value : %s" %  dict.items()
When we run above program, it produces following result −
Value : [('Age', 7), ('Name', 'Zara')]


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
Node.js – forEach() Method

The forEach() method in Node.js is used for iterating over a set of given array items. One can iterate over all the values of the array one-by-one using the forEach array loop.
arrayName.forEach(function)
function − The function takes input for the method that will be executed.
arrayName − Array that will be iterated.
Create a file "forEach.js" and copy the following code snippet. After creating the file, use the command "node forEach.js" to run this code.
 Live Demo
// forEach() Demo Example

// Defining a vehicle array
const vehicleArray = ['bike', 'car', 'bus'];

// Iterating over the array and printing
vehicleArray.forEach(element => {
   console.log(element);
});
C:\home\node>> node forEach.js
bike
car
bus
 Live Demo
// forEach() Demo Example

// Defining a vehicle array
const array = [1,2,3,4,5,6,7,8,9];

var sum=0;

// Iterating over the array and printing
array.forEach(element => {
   sum += element;
});

console.log(sum);
C:\home\node>> node forEach.js
45
PostgreSQL - COUNT() Function - GeeksforGeeks

01 Jun, 2020
The COUNT() function is an aggregate function that enables users to get the number of rows that match a particular requirement of a query.Depending upon the user requirements the COUNT() function can have the following syntaxes:
Syntax: COUNT(*)
Returns: All rows including NULL and Duplicates

Syntax: COUNT(column)
Returns:  All rows except NULL.

Syntax: COUNT(DISTINCT column)
Returns: All rows without NULL and Duplicates
The COUNT() function is used with the SELECT statement.
For examples we will be using the sample database (ie, dvdrental).Example 1:In this example we will use the COUNT(*) function to get the number of transactions in the payment table using the command below:
SELECT
   COUNT(*)
FROM
   payment;
Output:
Example 2:In this example we will query for the distinct amounts which customers paid, using the COUNT(DISTINCT column) function as shown below:
SELECT
    COUNT (DISTINCT amount)
FROM
    payment;
Output:
Example 3:Here we will be using the COUNT() function to get the details of customers who have made more than 40 payments:
SELECT
    customer_id,
    COUNT (customer_id)
FROM
    payment
GROUP BY
    customer_id
HAVING
    COUNT (customer_id) > 40;
Output:
postgreSQL-aggregate-functions
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
PostgreSQL - Change Column Type
PostgreSQL - Psql commands
PostgreSQL - Function Returning A Table
PostgreSQL - For Loops
PostgreSQL - Create Auto-increment Column using SERIAL
PostgreSQL - ARRAY_AGG() Function
PostgreSQL - DROP INDEX
PostgreSQL - Interval Data Type
PostgreSQL - Cursor
How to use PostgreSQL Database in Django?
Data compression in SAP HANA

In SAP HANA, there are various methods and algorithms that you can use to store data in Column based structure- Dictionary Compressed, Run Length Compressed and many more.
In Dictionary Compressed, cells are stored in form of numbers in tables and numeral cells are always performance optimized as compared to characters.
In Run length compressed, it saves the multiplier with cell value in numerical format and multiplier shows repetitive value in the table.
Compression is calculated using Compression factor. Compression factor refers to the ratio of the uncompressed data size to the compressed data size in SAP HANA.
In SAP HANA, Compression is performed and calculations are done as part of the delta merge operation. If you create an empty column table, no compression is applied initially as the database cannot know which method is most appropriate. As you start to insert data into the table and the delta merge operation starts being executed at regular intervals, data compression is automatically (re)evaluated and optimized.
Automatic compression optimization is ensured by the parameter active in the optimize_compression section of the index server.ini configuration file. This parameter must have the value yes.
To find compression details, you need to first load the table into memory. You can also load a table using SQL command. Open the SQL console and execute the following statement −
LOAD <table_name>
UNLOAD <table_name>
Note that when you load a table, it loads the complete data and also delta storage into the main memory of SAP HANA system.
To perform data compression, run the following SQL command to check data compression properties.
SELECT SCHEMA_NAME, TABLE_NAME, COLUMN_NAME, COMPRESSION_TYPE, LOADED from
PUBLIC.M_CS_COLUMNS where SCHEMA_NAME = '<your_schema>' and TABLE_NAME = '<your_table>
How can we implement auto-complete JComboBox in Java?


A JComboBox is a subclass of JComponent class and it is a combination of a text field and a drop-down list from which the user can choose a value. A JComboBox can generate an ActionListener, ChangeListener, and ItemListener interfaces when the user actions on a combo box.
We can implement auto-complete JComboBox when the user types an input value from a keyboard by using customization of a combo box (AutoCompleteComboBox) by extending the JComboBox class.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.plaf.basic.*;
public class AutoCompleteComboBoxTest extends JFrame {
   private JComboBox comboBox;
   public AutoCompleteComboBoxTest() {
      setTitle("AutoCompleteComboBox");
      String[] countries = new String[] {"india", "australia", "newzealand", "england", "germany",
"france", "ireland", "southafrica", "bangladesh", "holland", "america"};
      comboBox = new AutoCompleteComboBox(countries);
      add(comboBox, BorderLayout.NORTH);
      setSize(400, 300);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setLocationRelativeTo(null);
      setVisible(true);
   }
   public static void main(String []args) {
      new AutoCompleteComboBoxTest();
   }
}
 // Implementtion of AutoCompleteComboBox
class AutoCompleteComboBox extends JComboBox {
   public int caretPos = 0;
   public JTextField tfield = null;
   public AutoCompleteComboBox(final Object countries[]) {
      super(countries);
      setEditor(new BasicComboBoxEditor());
      setEditable(true);
   }
   public void setSelectedIndex(int index) {
      super.setSelectedIndex(index);
      tfield.setText(getItemAt(index).toString());
      tfield.setSelectionEnd(caretPos + tfield.getText().length());
      tfield.moveCaretPosition(caretPos);
   }
   public void setEditor(ComboBoxEditor editor) {
      super.setEditor(editor);
      if(editor.getEditorComponent() instanceof JTextField) {
         tfield = (JTextField) editor.getEditorComponent();
         tfield.addKeyListener(new KeyAdapter() {
            public void keyReleased(KeyEvent ke) {
               char key = ke.getKeyChar();
               if (!(Character.isLetterOrDigit(key) || Character.isSpaceChar(key) )) return;
               caretPos = tfield.getCaretPosition();
               String text="";
               try {
                  text = tfield.getText(0, caretPos);
               } catch (javax.swing.text.BadLocationException e) {
                  e.printStackTrace();
               }
               for (int i=0; i < getItemCount(); i++) {
                  String element = (String) getItemAt(i);
                  if (element.startsWith(text)) {
                     setSelectedIndex(i);
                     return;
                  }
               }
            }
         });
      }
   }
}
C++ Program for GCD of more than two (or array) numbers?

The common divisor of two numbers are the numbers that are divisors of both of them.
For example, the divisors of 12 are 1, 2, 3, 4, 6, 12. The divisors of 18 are 1, 2, 3, 6, 9, 18. Thus, the common divisors of 12 and 18 are 1, 2, 3, 6. The greatest among these is, perhaps unsurprisingly, called the of 12 and 18. The usual mathematical notation for the greatest common divisor of two integers a and b are denoted by (a, b). Hence, (12, 18) = 6.
The greatest common divisor is important for many reasons. For example, it can be used to calculate the of two numbers, i.e., the smallest positive integer that is a multiple of these numbers. The least common multiple of the numbers a and b can be calculated as a*b*(a, b)
For example, the least common multiple of 12 and 18 is
12*18*(12, 18)=12*18*6
Input: 4, 10, 16, 14
Output: 2
GCD of two or more integers is the largest integer that can exactly divide both numbers (without a remainder).
#include <iostream>
using namespace std;
int gcd(int a,int b) {
   int temp;
   while(b > 0) {
      temp = b;
      b = a % b;
      a = temp;
   }
   return a;
}
int main() {
   int a[] = {4, 10, 16, 14};
   int n = 4;
   int r = a[0];
   for(int i=1; i<n; i++) {
      r = gcd(r, a[i]);
   }
   cout << r << endl;
   return 0;
}
4
Program to find Kth bit in n-th binary string using Python

Suppose we have two positive values n and k, now we can make a binary string S_n by using following rules −
S_1 = 0
S_1 = 0
S_i = S_i-1 concatenate "1" concatenate reverse(invert(S_i-1)) for i > 1
S_i = S_i-1 concatenate "1" concatenate reverse(invert(S_i-1)) for i > 1
Here reverse(x) returns the reversed string x, and invert(x) flips all the bits in x.
These are the example of four such strings
S_1 = "0"
S_1 = "0"
S_2 = "011"
S_2 = "011"
S_3 = "0111001"
S_3 = "0111001"
S_4 = "011100110110001"
S_4 = "011100110110001"
We have to find kth bit in S_n.
So, if the input is like n = 4 k = 10, then the output will be 1 because S_4 = "011100110110001",
so 10th bit is 1 (first bit is at position 1).
To solve this, we will follow these steps −
if k is same as 1, thenreturn 0 as string
if k is same as 1, then
return 0 as string
return 0 as string
otherwise,arr := an array with single element 0arr2 := an array with single element 1while k > size of arr, dotemplast := copy of arrtemp2last := copy of arr2arr := templast concatenate 1 concatenate temp2lastarr2 := templast concatenate 0 concatenate temp2last
otherwise,
arr := an array with single element 0
arr := an array with single element 0
arr2 := an array with single element 1
arr2 := an array with single element 1
while k > size of arr, dotemplast := copy of arrtemp2last := copy of arr2arr := templast concatenate 1 concatenate temp2lastarr2 := templast concatenate 0 concatenate temp2last
while k > size of arr, do
templast := copy of arr
templast := copy of arr
temp2last := copy of arr2
temp2last := copy of arr2
arr := templast concatenate 1 concatenate temp2last
arr := templast concatenate 1 concatenate temp2last
arr2 := templast concatenate 0 concatenate temp2last
arr2 := templast concatenate 0 concatenate temp2last
return k-1 th element from arr
return k-1 th element from arr
Let us see the following implementation to get better understanding −
def solve(n, k):
   if k == 1:
      return(str(0))
   else:
      arr = [0]
      arr2 = [1]
      while k > len(arr):
         templast = arr.copy()
         temp2last = arr2.copy()
         arr = templast + [1] + temp2last
         arr2 = templast + [0] + temp2last
      return(str(arr[k-1]))
n = 4
k = 10
print(solve(n, k))
4, 10
1
Object to array - JavaScript

Suppose, we have an object of key value pairs like this −
const obj = {
   name: "Vikas",
   age: 45,
   occupation: "Frontend Developer",
   address: "Tilak Nagar, New Delhi",
   experience: 23,
   salary: "98000"
};
We are required to write a function that takes in the object and returns an array of arrays with each subarray representing one key value pair
Let’s write the code for this function −
const obj = {
   name: "Vikas",
   age: 45,
   occupation: "Frontend Developer",
   address: "Tilak Nagar, New Delhi",
   experience: 23,
   salary: "98000"
};
const objectToArray = obj => {
   const keys = Object.keys(obj);
   const res = [];
   for(let i = 0; i < keys.length; i++){
      res.push([keys[i], obj[keys[i]]]);
   };
   return res;
};
console.log(objectToArray(obj));
The output in the console: −
[
   [ 'name', 'Vikas' ],
   [ 'age', 45 ],
   [ 'occupation', 'Frontend Developer' ],
   [ 'address', 'Tilak Nagar, New Delhi' ],
   [ 'experience', 23 ],
   [ 'salary', '98000' ]
]
How null is converted to String in JavaScript?

Use the String() method in JavaScript to convert to String.
You can try to run the following code to learn how to convert null to String in JavaScript.
Live Demo
<!DOCTYPE html>
<html>
   <body>
      <p>Convert null to String</p>
      <script>
         var myVal = null;
         document.write("String: " + String(myVal));
      </script>
   </body>
</html>
How to create table header in HTML?

To create table header in HTML, use the <th>...</th> tag. A table header tag is surrounded by the table row <tr>...</tr>. The <tr> tag is surrounded by the <table> tag. A table consist of a rows and columns, which can be set using one or more <tr>, <th>, and <td> elements. Use the style attribute to add CSS properties for adding a border to the table.
A table row is defined by the <tr> tag. To create table header, use the <th> tag. Just keep in mind that you can only have a single heading in a table.
You can try the following code to create table header in HTML. We’re also using the <style> tag to style the table borders
<!DOCTYPE html>
<html>
   <head>
      <style>
         table, th, td {
            border: 1px solid black;
         }
      </style>
   </head>

   <body>
      <h1>Database</h1>
      <table>
         <tr>
            <th>Database</th>
            <th>Release Year</th>
         </tr>
         <tr>
            <td>MySQL</td>
            <td>1995</td>
         </tr>
      </table>
   </body>
</html>
How to use a variable for a key in a JavaScript object literal? - GeeksforGeeks

31 Oct, 2019
In ES5 and earlier, you could not use a variable as a property name inside an object literal. The only option you had was to create the object literal, assign the variable property name with value and pass the resulting object to the animate method. ES6 defines ‘ComputedPropertyName’ as part of the grammar for object literals, which helps use a variable for a key. Object keys can be dynamically assigned in ES6 by placing an expression in square brackets.
Syntax:
var key="your_choice";
var object = {};
object[key] = "your_choice";
console.log(object);
Example 1: This shows how to use a variable for a key.
<html>  <head>    <title>        How to use a variable for a      key in a JavaScript object literal?    </title></head>  <body style="text-align:center;">    <h1 style="color:green;">  GeeksForGeeks  </h1>    <script>        var key = "Geeksforgeeks";        var object = {};        object[key] = "something";        console.log(object);    </script></body>  </html>
Output:
javascript-object
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
How to Open URL in New Tab using JavaScript ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Number of Closed Islands in C++

Suppose we have a 2D grid consists of 0s (as land) and 1s (as water). An island is a maximal 4- directionally connected group of 0s. A closed island is an island totally surrounded by 1s. We have to find the number of closed islands. So if the grid is like
So the output will be 2. There are two islands, that are completely surrounded by water.
To solve this, we will follow these steps −
Define a variable flag
Define a variable flag
Define a method called dfs, this will take the grid, i, j, n and m
Define a method called dfs, this will take the grid, i, j, n and m
if i and j are not inside the range of the grid, then set flag := false and return
if g[i,j] = 1 or g[i, j] = -1, then return
if g[i,j] = 1 or g[i, j] = -1, then return
if g[i, j] = 0, then g[i, j] = -1
if g[i, j] = 0, then g[i, j] = -1
call dfs(g, i + 1, j, n, m), dfs(g, i, j+1, n, m), dfs(g, i - 1, j, n, m), dfs(g, i, j-1, n, m)
call dfs(g, i + 1, j, n, m), dfs(g, i, j+1, n, m), dfs(g, i - 1, j, n, m), dfs(g, i, j-1, n, m)
The main method will be like −
The main method will be like −
create a dp matrix of order n x m, and fill it with -1
create a dp matrix of order n x m, and fill it with -1
for i in range 0 to n – 1for j in range 0 to m – 1if g[i, j] = 0, thenflag := truedfs(g, i, j, n, m)flag := trueans := ans + flag
for i in range 0 to n – 1
for j in range 0 to m – 1if g[i, j] = 0, thenflag := truedfs(g, i, j, n, m)flag := trueans := ans + flag
for j in range 0 to m – 1
if g[i, j] = 0, thenflag := truedfs(g, i, j, n, m)flag := trueans := ans + flag
if g[i, j] = 0, then
flag := true
flag := true
dfs(g, i, j, n, m)
dfs(g, i, j, n, m)
flag := true
flag := true
ans := ans + flag
ans := ans + flag
return ans
return ans
Let us see the following implementation to get better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   vector < vector <int> > dp;
   bool flag;
   void dfs(vector<vector<int>>& g, int i, int j, int n, int m){
      if(i>=n || j >=m || i<0 || j<0){
         flag = false;
         return ;
      }
      if(g[i][j] == 1 || g[i][j] == -1)return;
      if(g[i][j] == 0)g[i][j] = -1;
      dfs(g, i+1, j, n, m);
      dfs(g, i, j+1, n, m);
      dfs(g, i-1, j, n, m);
      dfs(g,i, j-1, n, m);
   }
   int closedIsland(vector<vector<int>>& g) {
      int ans = 0;
      int n = g.size();
      int m = g[0].size();
      dp = vector < vector <int> > (n, vector <int> (m, -1));
      for(int i = 0; i < n ; i++){
         for(int j = 0; j < m; j++){
            if(g[i][j] == 0){
               flag = true;
               dfs(g, i , j ,n ,m);
               ans += flag;
            }
         }
      }
   return ans;
   }
};
main(){
   vector<vector<int>> v =
   {{1,1,1,1,1,1,1,0},{1,0,0,0,0,1,1,0},{1,0,1,0,1,1,1,0},{1,0,0,0,0,1,0
   ,1},{1,1,1,1,1,1,1,0}};
   Solution ob;
   cout << (ob.closedIsland(v));
}
[[1,1,1,1,1,1,1,0],[1,0,0,0,0,1,1,0],[1,0,1,0,1,1,1,0],[1,0,0,0,0,1,0,1],[1,1,1,1,1,1,1,0]]
2
p5.js | lights() Function - GeeksforGeeks

13 Jan, 2022
The lights() function in p5.js is used to set the default ambient and directional light in the scene. The default ambient light used is ambientLight(128, 128, 128) and the directional light is directionalLight(128, 128, 128, 0, 0, -1). This function can be used to quickly add default lights in the scene.The lights() function has to be used in the draw() function of the code to remain persistent in the scene.Syntax:  
lights()
Parameters: This function does not accept any parameters.Below examples illustrate the lights() function in p5.js:Example 1: 
javascript
let newFont;let lightsEnable = false; function preload() {  newFont = loadFont('fonts/Montserrat.otf');} function setup() {  createCanvas(600, 300, WEBGL);  textFont(newFont, 18);   lightsEnableCheck = createCheckbox(      "Enable Default Lights", false);  lightsEnableCheck.position(20, 60);   // Toggle default light  lightsEnableCheck.changed(() => {    lightsEnable = !lightsEnable;  });} function draw() {  background("green");  text("Click on the checkbox to toggle the"     + " default lights.", -285, -125);  noStroke();  shininess(15);  specularMaterial(250);   if (lightsEnable) {     // Enable the default lights    lights();  }   sphere(80);}
Output:  
Example 2: 
javascript
let newFont;let lightsEnable = false; function preload() {  newFont = loadFont('fonts/Montserrat.otf');} function setup() {  createCanvas(600, 300, WEBGL);  textFont(newFont, 18);   lightsEnableCheck = createCheckbox(       "Enable Default Lights", false);   lightsEnableCheck.position(20, 60);   // Toggle default light  lightsEnableCheck.changed(() => {    lightsEnable = !lightsEnable;  });} function draw() {  background("green");  text("Click on the checkbox to toggle the"       + " default lights.", -285, -125);  noStroke();  shininess(15);  specularMaterial(250);   if (lightsEnable) {     // Enable the default lights    lights();  }   rotateX(millis() / 1000);  rotateY(millis() / 1000);  box(100);}
Output:  
Online editor: https://editor.p5js.org/Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/Reference: https://p5js.org/reference/#/p5/lights 
adnanirshad158
JavaScript-p5.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
How to Open URL in New Tab using JavaScript ?
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
GATE | GATE-CS-2004 | Question 48 - GeeksforGeeks

28 Jun, 2021
Consider two processes P1 and P2 accessing the shared variables X and Y protected by two binary semaphores SX and SY respectively, both initialized to 1. P and V denote the usual semaphone operators, where P decrements the semaphore value, and V increments the semaphore value. The pseudo-code of P1 and P2 is as follows :
P1 :
 While true do {
   L1 : ................
   L2 : ................
   X = X + 1;
   Y = Y - 1;
   V(SX);
   V(SY);             
 }
P2 :
 While true do {
   L3 : ................   
   L4 : ................
   Y = Y + 1;
   X = Y - 1;
   V(SY);
   V(SX);            
}
In order to avoid deadlock, the correct operators at L1, L2, L3 and L4 are respectively(A) P(SY), P(SX); P(SX), P(SY)(B) P(SX), P(SY); P(SY), P(SX)(C) P(SX), P(SX); P(SY), P(SY)(D) P(SX), P(SY); P(SX), P(SY)Answer: (D)Explanation:
Option A: In line L1 ( p(Sy) ) i.e. process p1 wants lock on Sy that is 
held by process p2 and line L3 (p(Sx)) p2 wants lock on Sx which held by p1. 
So here circular and wait condition exist means deadlock.

Option B : In line L1 ( p(Sx) ) i.e. process p1 wants lock on Sx that is held 
by process p2 and line L3 (p(Sy)) p2 wants lock on Sx which held by p1. So here 
circular and wait condition exist means deadlock.

Option C: In line L1 ( p(Sx) ) i.e. process p1 wants lock on Sx and line L3 (p(Sy)) 
p2 wants lock on Sx . But Sx and Sy can’t be released by its processes p1 and p2.

Please read the following to learn more about process synchronization and semaphores:Process Synchronization Set 1
This explanation has been contributed by Dheerendra Singh.Quiz of this Question
GATE-CS-2004
GATE-GATE-CS-2004
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-CS-2014-(Set-3) | Question 38
GATE | GATE CS 2018 | Question 37
GATE | GATE-IT-2004 | Question 83
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2016 (Set 1) | Question 65
GATE | GATE-CS-2016 (Set 1) | Question 63
GATE | GATE-IT-2004 | Question 12
GATE | GATE-CS-2007 | Question 17
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 2010 | Question 33
Filter an array containing objects based on another array containing objects in JavaScript

Suppose we have two arrays of objects like these −
const arr1 = [{id:'1',name:'A'},{id:'2',name:'B'},{id:'3',name:'C'},{id:'4',name:'D'}];
const arr2 = [{id:'1',name:'A',state:'healthy'},{id:'3',name:'C',state:'healthy'}];
We are required to write a JavaScript function that takes in two such arrays. Our function should return a new filtered version of the first array (arr1 in this case) that contains only those objects with a name property that are not contained in the second array (arr2 in this case) with the same name property.
Therefore, the output, in this case, should look like −
const output = [{id:'2',name:'B'},{id:'4',name:'D'}];
The code for this will be −
const arr1 = [{id:'1',name:'A'},{id:'2',name:'B'},{id:'3',name:'C'},{id:'4',name:'D'}];
const arr2 = [{id:'1',name:'A',state:'healthy'},{id:'3',name:'C',state:'healthy'}];
const filterByReference = (arr1, arr2) => {
   let res = [];
   res = arr1.filter(el => {
      return !arr2.find(element => {
         return element.id === el.id;
      });
   });
   return res;
}
console.log(filterByReference(arr1, arr2));
And the output in the console will be −
[ { id: '2', name: 'B' }, { id: '4', name: 'D' } ]
Check if a string contains only alphabets in Java

23 May, 2022
Given a string, the task is to write a Java program to check whether the string contains only alphabets or not. If so, then print true, otherwise false.
Examples:
Input: GeeksforGeeksOutput: trueExplanation: The given string contains only alphabets so the output is true.
Input: GeeksforGeeks2020Output: falseExplanation: The given string contains alphabets and numbers so the output is false.
Input: “”Output: falseExplanation: The given string is empty so the output is false.
Method 1: This problem can be solved using the ASCII values. Please refer this article for this approach.
Method 2: This problem can be solved using Lambda expression. Please refer this article for this approach.
Method 3: This problem can be solved using Regular Expression. Please refer this article for this approach.
Method 4: This approach uses the methods of Character class in Java
The idea is to iterate over each character of the string and check whether the specified character is a letter or not using Character.isLetter() method. 
If the character is a letter then continue, else return false. 
If we are able to iterate over the whole string, then return true.
Below is the implementation of the above approach:
Java
class GFG {     // Function to check if a string    // contains only alphabets    public static boolean onlyAlphabets(      String str, int n)    {         // Return false if the string        // has empty or null        if (str == null || str == "") {            return false;        }         // Traverse the string from        // start to end        for (int i = 0; i < n; i++) {            // Check if the specified            // character is not a letter then            // return false,            // else return true            if (!Character                .isLetter(str.charAt(i))) {                return false;            }        }        return true;    }     // Driver Code    public static void main(String args[])    {        // Given string str        String str = "GeeksforGeeks";        int len = str.length();         // Function Call        System.out.println(          onlyAlphabets(str, len));    }}
true
Time Complexity: O(N), where N is the size of the given string.
Auxiliary Space: O(1), no extra space required so it is a constant.
samim2000
Java-Character
java-lambda
java-regular-expression
Java-String-Programs
strings
Java
Strings
Strings
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Write a program to reverse an array or string
C++ Data Types
Write a program to print all permutations of a given string
Longest Common Subsequence | DP-4
Python program to check if a string is palindrome or not
Stack.Synchronized() Method in C#

04 Feb, 2019
This method(comes under System.Collections Namespace) is used to return a synchronized (thread safe) wrapper for the Stack. To guarantee the thread safety of the Stack, all operations must be done through this wrapper.
Syntax:
public static System.Collections.Stack Synchronized (System.Collections.Stack stack);
Return Value: It returns synchronized wrapper around the Stack.
Exception: This method will give ArgumentNullException if the stack is null.
Below programs illustrate the use of above-discussed method:
Example 1:
// C# code to illustrate the// Stack.Synchronized() Methodusing System;using System.Collections;  class GFG {      // Driver code    public static void Main()    {          // Creating a Stack        Stack myStack = new Stack();          // Inserting the elements into the Stack        myStack.Push("Geeks");        myStack.Push("Geeks Classes");        myStack.Push("Noida");        myStack.Push("Data Structures");        myStack.Push("GeeksforGeeks");          // Creates a synchronized        // wrapper around the Stack        Stack st = Stack.Synchronized(myStack);          // Displays the synchronization        // status of both Stack        Console.WriteLine("myStack is {0}.", myStack.IsSynchronized ?                                "Synchronized" : "Not Synchronized");          Console.WriteLine("st is {0}.", st.IsSynchronized ?                       "Synchronized" : "Not Synchronized");    }}
Output:
myStack is Not Synchronized.
st is Synchronized.

Example 2:
// C# code to illustrate the// Stack.Synchronized() Methodusing System;using System.Collections;  class GFG {      // Driver code    public static void Main()    {          // Creating a Stack        Stack myStack = new Stack();          // Inserting the elements into the Stack        myStack.Push("C");        myStack.Push("C++");        myStack.Push("Java");        myStack.Push("C#");        myStack.Push("Python");          // it will give error as        // the parameter is null        Stack sq = Stack.Synchronized(null);    }}
Runtime Error:
Unhandled Exception:System.ArgumentNullException: Value cannot be null.Parameter name: stack
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.collections.stack.synchronized?view=netframework-4.7.2
CSharp-Collections-Namespace
CSharp-Collections-Stack
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to add a new column to represent the percentage for groups in an R data frame?

In data analysis, we often need to find the percentage of values that exists in a data group. This helps us to understand which value occurs frequently and which one has low frequency. Also, plotting of percentages through pie charts can be done and that gives a better view of the data to the readers. Adding a new column as percentage for groups is not a challenge if we can use mutate function of dplyr package, here you will get the examples from that.
 Live Demo
> Group<-rep(1:2,each=5)
> Frequency<-sample(1:100,10)
> df1<-data.frame(Group,Frequency)
> df1
Group Frequency
1 1 67
2 1 58
3 1 54
4 1 13
5 1 23
6 2 91
7 2 3
8 2 95
9 2 38
10 2 48
> library(dplyr)
Finding the percentage for each group values in the group −
> df1%>%group_by(Group)%>%mutate(Percentage=paste0(round(Frequency/sum(Frequency)*100,2),"%"))
# A tibble: 10 x 3
# Groups: Group [2]
Group Frequency Percentage
 <int> <int> <chr>
1 1    67    31.16%
2 1    58    26.98%
3 1    54    25.12%
4 1    13    6.05%
5 1    23    10.7%
6 2    91    33.09%
7 2    3     1.09%
8 2    95    34.55%
9 2    38    13.82%
10 2   48    17.45%
 Live Demo
> Gender<-rep(c("Male","Female"),each=5)
> Salary<-sample(25000:50000,10)
> df2<-data.frame(Gender,Salary)
> df2
 Gender  Salary
1  Male   41734
2  Male   39035
3  Male   36161
4  Male   33437
5  Male   45123
6  Female 44492
7  Female 48456
8  Female 31569
9  Female 35110
10 Female 43630
>df2%>%group_by(Gender)%>%mutate(Percentage=paste0(round(Salary/sum(Salary)*1
00,2),"%"))
# A tibble: 10 x 3
# Groups: Gender [2]
   Gender Salary Percentage
   <fct> <int> <chr>
1  Male   41734    21.35%
2  Male   39035    19.97%
3  Male   36161    18.5%
4  Male   33437    17.1%
5  Male   45123    23.08%
6  Female 44492    21.89%
7  Female 48456    23.84%
8  Female 31569    15.53%
9  Female 35110    17.27%
10 Female 43630    21.47%
 Live Demo
> Grade<-rep(c("A","B","C","D","E"),each=2)
> Number_of_Years_in_Job<-sample(1:5,10,replace=TRUE)
> df3<-data.frame(Grade,Number_of_Years_in_Job)
> df3
   Grade Number_of_Years_in_Job
1    A       4
2    A       5
3    B       4
4    B       4
5    C       1
6    C       4
7    D       1
8    D       1
9    E       3
10   E       1
>df3%>%group_by(Grade)%>%mutate(Percentage=paste0(round(Number_of_Years_in_J
ob/sum(Number_of_Years_in_Job)*100,2),"%"))
# A tibble: 10 x 3
# Groups: Grade [5]
Grade Number_of_Years_in_Job Percentage
  <fct> <int> <chr>
1    A    4 44.44%
2    A    5 55.56%
3    B    4 50%
4    B    4 50%
5    C    1 20%
6    C    4 80%
7    D    1 50%
8    D    1 50%
9    E    3 75%
10   E    1 25%
Bootstrap 4 .d-*-flex class

Use the .d-*-flex class in Bootstrap to set a flexbox container on a screen size as shown below −
<div class="d-flex bg-primary">d-flex</div>
<span class="d-sm-flex bg-warning">d-sm-flex</span>
<span class="d-md-flex bg-info">d-md-flex</span>
<span class="d-lg-flex bg-success">d-lg-flex</span>
Above the flex is set for different screen sizes, for example,
Let us see an example of the class −
Live Demo
<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Bootstrap Example</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
  </head>

<body>

<div class="container mt-3">
  <h2>Understanding Flex</h2>
  <div class="d-flex bg-primary">d-flex</div>
  <span class="d-sm-flex bg-warning">Small Screen Size</span>
  <span class="d-md-flex bg-info"> Medium Screen Size </span>
  <span class="d-lg-flex bg-success"> Large Screen Size </span>
  <span class="d-xl-flex bg-danger"> Extra Large Screen Size </span>
</div>

</body>
</html>
std::count() in C++ STL

22 Sep, 2019
std::count() returns number of occurrences of an element in a given range. Returns the number of elements in the range [first,last) that compare equal to val.
// Returns count of occurrences of value in// range [begin, end]int count(Iterator first, Iterator last, T &val)
first, last : Input iterators to the initial and final positions of the sequence of elements.val : Value to match
Complexity It’s order of complexity O(n). Compares once each element with the particular value.
Counting occurrences in an array.
// C++ program for count in C++ STL for// array#include <bits/stdc++.h>using namespace std;  int main(){    int arr[] = { 3, 2, 1, 3, 3, 5, 3 };    int n = sizeof(arr) / sizeof(arr[0]);    cout << "Number of times 3 appears : "         << count(arr, arr + n, 3);      return 0;}
Number of times 3 appears : 4

Counting occurrences in a vector.
// C++ program for count in C++ STL for// a vector#include <bits/stdc++.h>using namespace std;  int main(){    vector<int> vect{ 3, 2, 1, 3, 3, 5, 3 };    cout << "Number of times 3 appears : "         << count(vect.begin(), vect.end(), 3);      return 0;}
Number of times 3 appears : 4

Counting occurrences in a string.
// C++ program for the count in C++ STL// for a string#include <bits/stdc++.h>using namespace std;  int main(){    string str = "geeksforgeeks";      cout << "Number of times 'e' appears : "          << count(str.begin(), str.end(), 'e');      return 0;}
Number of times 'e' appears : 4

This article is contributed by Jatin Goyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
saurved785
cpp-algorithm-library
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Calculating the completeness score using sklearn in Python

26 May, 2021
An entirely complete clustering is one where each cluster has information that directs a place toward a similar class cluster. Completeness portrays the closeness of the clustering algorithm to this (completeness_score) perfection. 
This metric is autonomous of the outright values of the labels. A permutation of the cluster label values won’t change the score value in any way.
Syntax: sklearn.metrics.completeness_score(labels_true, labels_pred)
Parameters:
labels_true:<int array, shape = [n_samples]>: It accepts the ground truth class labels to be used as a reference.
labels_pred: <array-like of shape (n_samples,)>: It accepts the cluster labels to evaluate.
Returns: completeness score between 0.0 and 1.0. 1.0 stands for perfectly completeness labeling.
Switching label_true with label_pred will return the homogeneity_score.
Example 1:
Python3
# Importing the modulesimport pandas as pd from sklearn import datasetsfrom sklearn.cluster import KMeans from sklearn.metrics import completeness_score # Loading the data digits = datasets.load_digits() # Separating the dependent and independent variables Y = digits.targetX = digits.data # Building the clustering model kmeans = KMeans(n_clusters = 2)  # Training the clustering model kmeans.fit(X)  # Storing the predicted Clustering labels labels = kmeans.predict(X)  # Evaluating the performance print(completeness_score(Y, labels))
Output:
0.8471148027985769
Example 2: Perfectly completeness:
Python3
# Importing the modulefrom sklearn.metrics.cluster import completeness_score # Evaluating the scoreCscore = completeness_score([0, 1, 0, 1],                            [1, 0, 1, 0])print(Cscore)
 Output: 
1.0 
Example 3: Non-perfect labeling that further split classes into more clusters can be perfectly completeness:
Python3
# Importing the modulefrom sklearn.metrics.cluster import completeness_score # Evaluating the scoreCscore = completeness_score([0, 1, 2, 3],                            [0, 0, 1, 1])print(Cscore)
Output:
0.9999999999999999
Example 4: Include samples from different classes don’t make for completeness labeling:
Python3
# Importing the modulefrom sklearn.metrics.cluster import completeness_score # Evaluating the scoreCscore = completeness_score([0, 0, 0, 0],                            [0, 1, 2, 3])print(Cscore)
Output:
0.0
 
sweetyty
ML-Clustering
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function
numpy.diagflat() in Python

04 Aug, 2021
numpy.diagflat (a, k = 0): Create a two-dimensional array with the array_like input as a diagonal to the new output array.
Parameters : 
a : array_like input data with diagonal  elements
strong>k : [int, optional, 0 by default]
          Diagonal we require; k>0 means diagonal  above main diagonal  or vice versa.
Returns :  
array with the array_like input as a diagonal to the new output array.
Python
# Python Program illustrating# numpy.diagflat method import numpy as geek print("diagflat use on main diagonal : \n", geek.diagflat([1, 7]), "\n") print("diagflat use on main diagonal : \n", geek.diagflat([1, 7, 6]), "\n") # Diagonal above main diagonalprint("diagflat above main diagonal : \n", geek.diagflat([1, 7, 6], 1), "\n")
Output : 
diagflat use on main diagonal  : 
 [[1 0]
 [0 7]] 

diagflat use on main diagonal  : 
 [[1 0 0]
 [0 7 0]
 [0 0 6]] 

diagflat above main diagonal  : 
 [[0 1 0 0]
 [0 0 7 0]
 [0 0 0 6]
 [0 0 0 0]] 
Note : These NumPy-Python programs won’t run on onlineID, so run them on your systems to explore them.
 This article is contributed by Mohit Gupta_OMG . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
gabaa406
Python numpy-arrayCreation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Convert list of Celsius values into Fahrenheit using NumPy array

25 Jan, 2022
Let us see how to convert a list of Celsius temperatures into Fahrenheit by converting them into NumPy array. The formula to convert Celsius to Fahrenheit is :  
feh = (9 * cel / 5 + 32)
 
Method 1 : Using the numpy.array() method.
 
python3
# importing the moduleimport numpy as np # taking the celsius  inputinp = [0, 12, 45.21, 34, 99.91] # storing the input# in numpy arraycel = np.array(inp) print(f"Celsius {cel}") # using formulaefeh = (9 * cel / 5 + 32) # printing resultsprint(f"Fahrenheit {feh}")
Output :
Celsius [ 0.   12.   45.21 34.   99.91]
Fahrenheit [ 32.     53.6   113.378  93.2   211.838]
Method 2 : Using the numpy.asarray() method.
python3
# importing the moduleimport numpy as np # taking the celsius  inputinp = [0, 12, 45.21, 34, 99.91] # storing the input# in numpy arraycel = np.asarray(inp) print(f"Celsius {cel}") # using formulaefeh = (9 * cel / 5 + 32) # printing resultsprint(f"Fahrenheit {feh}")
Output :
Celsius [ 0.   12.   45.21 34.   99.91]
Fahrenheit [ 32.     53.6   113.378  93.2   211.838]
Method 3 : Using numpy.arange().
python3
# importing the moduleimport numpy as np # taking thecelsius  inputinp = [0, 12, 45.21, 34, 99.91] # arange will not directly# convert into numpy arraycel = np.arange(5) # the above code# will give o/p as# cel = [0, 1, 2, 3, 4]cel = [i for i in inp]# thus the input(inp)# is stored in cel# using list comprehension print(f"Celsius {cel}") # applying formulae# using list comprehensionfeh = [(9 * i / 5 + 32) for i in cel] # printing resultsprint(f"Fahrenheit {feh}")
Output :
Celsius [ 0.   12.   45.21 34.   99.91]
Fahrenheit [ 32.     53.6   113.378  93.2   211.838]
clintra
Python numpy-program
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Iterate over a list in Python
Python Classes and Objects
Convert integer to string in Python
How to Build a Simple Web Server with Node.js ?

25 Jun, 2021
Introduction: Node.js is an open-source and cross-platform runtime environment for executing JavaScript code outside a browser. You need to remember that NodeJS is not a framework, and it’s not a programming language. Node.js is mostly used in server-side programming. In this article, we will discuss how to make a web server using node.js.
Creating Web Servers Using NodeJS: There are mainly two ways as follows.
Using http inbuilt moduleUsing express third party module
Using http inbuilt module
Using express third party module
Using http module: HTTP and HTTPS, these two inbuilt modules are used to create a simple server. The HTTPS module provides the feature of the encryption of communication with the help of the secure layer feature of this module. Whereas the HTTP module doesn’t provide the encryption of the data.
Project structure: It will look like this.
index.js
// Importing the http moduleconst http = require("http")  // Creating server const server = http.createServer((req, res) => {    // Sending the response    res.write("This is the response from the server")    res.end();})  // Server listening to port 3000server.listen((3000), () => {    console.log("Server is Running");})
Run index.js file using below command:
node index.js
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
Using express module: The express.js is one of the most powerful frameworks of the node.js that works on the upper layer of the http module. The main advantage of using express.js server is filtering the incoming requests by clients.
Installing module: Install the required module using the following command.
npm install express
Project structure: It will look like this.
index.js
// Importing express moduleconst express = require("express")const app = express()  // Handling GET / requestapp.use("/", (req, res, next) => {    res.send("This is the express server")})  // Handling GET /hello requestapp.get("/hello", (req, res, next) => {    res.send("This is the hello response");})  // Server setupapp.listen(3000, () => {    console.log("Server is Running")})
Run the index.js file using the below command:
node index.js
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
Node.js-Methods
NodeJS-Questions
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
JWT Authentication with Node.js
Installation of Node.js on Windows
Difference between dependencies, devDependencies and peerDependencies
Mongoose Populate() Method
Mongoose find() Function
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React