code-rag-bench/online-tutorials huggingface dataset:
PostgreSQL – UNIQUE Index

28 Aug, 2020
In PostgreSQL, the UNIQUE index to ensure the uniqueness of values in one or more columns. To create a UNIQUE index, you can use the following syntax:
Syntax:
CREATE UNIQUE INDEX index_name
ON table_name(column_name, [...]);

Note: Only B-tree indexes can be declared as unique indexes.
Example 1:
The following statement creates a table called employees :
CREATE TABLE employees (
    employee_id SERIAL PRIMARY KEY,
    first_name VARCHAR(255) NOT NULL,
    last_name VARCHAR(255) NOT NULL,
    email VARCHAR(255) UNIQUE
);

In this statement, the employee_id is the primary key column and email column has a unique constraint, therefore, PostgreSQL created two UNIQUE indexes, one for each column.
To show the indexes of the employees table, you use the following statement:
SELECT 
    tablename, 
    indexname, 
    indexdef 
FROM 
    pg_indexes 
WHERE 
    tablename = 'employees';

Output:
Example 2:
The following statement adds the mobile_phone column to the employees table that we created in the above example:
ALTER TABLE employees
ADD mobile_phone VARCHAR(20);

To ensure that the mobile phone numbers are distinct for all employees, you define a UNIQUE index for the mobile_phone column as follows:
CREATE UNIQUE INDEX idx_employees_mobile_phone
ON employees(mobile_phone);

Now let’s test it. First, insert a new row into the employees table:
INSERT INTO employees(first_name, last_name, email, mobile_phone)
VALUES ('Raju', 'kumar', 'raju.kumar@geeksforgeeks.org', '(408)-555-1234');

Second, attempt to insert another row with the same phone number:
INSERT INTO employees(first_name, last_name, email, mobile_phone)
VALUES ('Nikhil', 'Aggarwal', 'nikhil.aggarwal@gfg.org', '(408)-555-1234');

This should raise an error.
Output:
As we can observe the behaviour is exactly what is expected of the unique index.
postgreSQL-indexes
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PostgreSQL - Psql commands
PostgreSQL - Change Column Type
PostgreSQL - For Loops
PostgreSQL - LIMIT with OFFSET clause
PostgreSQL - Function Returning A Table
PostgreSQL - ARRAY_AGG() Function
PostgreSQL - Create Auto-increment Column using SERIAL
PostgreSQL - DROP INDEX
PostgreSQL - Copy Table
How to use PostgreSQL Database in Django?
How to insert data to MySQL having auto incremented primary key?

Whenever your column has an auto incremented primary key then there is an advantage that you do not need to give value for that column in the INSERT command. This means MySQL will give the value for that column.
To understand the above concept, let us first create a table. The query to create a table is as follows −
mysql> create table AutoIncrementedPrimary
   -> (
   -> Id int auto_increment,
   -> Name varchar(100),
   -> Age int,
   -> Primary key(Id)
   -> );
Query OK, 0 rows affected (0.56 sec)
Now insert records for the column Name and Age only, MySQL will provide the value for Id column on its own since it is set auto_increment. The query to insert record is as follows −
mysql> insert into AutoIncrementedPrimary(Name,Age) values('John',23);
Query OK, 1 row affected (0.12 sec)

mysql> insert into AutoIncrementedPrimary(Name,Age) values('Sam',24);
Query OK, 1 row affected (0.15 sec)

mysql> insert into AutoIncrementedPrimary(Name,Age) values('Carol',30);
Query OK, 1 row affected (0.13 sec)

mysql> insert into AutoIncrementedPrimary(Name,Age) values('Johnson',28);
Query OK, 1 row affected (0.16 sec)
Let us now display all records from the table using select command. The query is as follows −
mysql> select *from AutoIncrementedPrimary;
+----+---------+------+
| Id | Name    | Age  |
+----+---------+------+
|  1 | John    |   23 |
|  2 | Sam     |   24 |
|  3 | Carol   |   30 |
|  4 | Johnson |   28 |
+----+---------+------+
4 rows in set (0.00 sec)
Look at the above sample output, the column Id value is provided by MySQL.
What is the difference between public, static and void keywords in C#?

All these keywords are part of the main method of any C# program.
The Main method, which is the entry point for all C# programs states that what a class does when it executed.
using System;
class Demo {
   static void Main(string[] args) {
      Console.WriteLine("My first program in C#!");
   }
}
public − This is the access specifier that states that the method can be accesses publically.
public − This is the access specifier that states that the method can be accesses publically.
static −  Here, the object is not required to access static members.
static −  Here, the object is not required to access static members.
void − This states that the method doesn’t return any value.
void − This states that the method doesn’t return any value.
main − is As stated above, it s the entry point of a C# program i.e. this method is the method that executes first.
main − is As stated above, it s the entry point of a C# program i.e. this method is the method that executes first.
How to fire event if CSS class is changed using jQuery ? - GeeksforGeeks

29 Nov, 2021
Given an HTML document with heading and button, jQuery should fire an event when the CSS class of the button changes.
Approach: In jQuery, there is no provision to trigger an event on class change. An alternative method is to manually raise an event when you programmatically change the class using the trigger() function. The trigger() function will raise an event whenever the class of the button is changed.
HTML
<!DOCTYPE html><html lang="en">  <head>      <meta charset="UTF-8">    <meta name="viewport" content=        "width=device-width, initial-scale=1.0">      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js">    </script>      <style>        .buttonstyle {            background-color: #4CB96B;            color: white;        }          .buttonsize {            padding: 1em;            height: 70px;            width: 400px;            border: .5px solid black;            outline: none;            font-size: large;            border-radius: 10px;        }    </style></head>  <body>    <center>        <h1>            Click the button to            change its style        </h1>          <button id="classchange-btn"             class="buttonsize">            Click Me        </button>    </center>      <script>        $("#classchange-btn").click(function () {            $(this).toggleClass("buttonstyle")                    .trigger('classChanged');        });          $("#classchange-btn").on(            "classChanged", function () {            alert("Button Style Change event fired");        });    </script></body>  </html>
Initially the page looked like the following image.
On clicking the button, an alert message pops up indicating that the listener was fired and the CSS class of the button has changed.
After closing the popup, the button’s CSS class changed (notice the green background color and white text).
jQuery is an open-source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples.
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
jQuery-Questions
CSS
HTML
JQuery
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to create footer to stay at the bottom of a Web page?
Types of CSS (Cascading Style Sheet)
Create a Responsive Navbar using ReactJS
Design a web page using HTML and CSS
How to position a div at the bottom of its container using CSS?
How to set the default value for an HTML <select> element ?
Types of CSS (Cascading Style Sheet)
Hide or show elements in HTML using display property
How to Insert Form Data into Database using PHP ?
REST API (Introduction)
How to get the length of a Number in JavaScript?

Use the toString() method to covert the Number to string, then the length() method gives you length.
You can try to run the following code to learn how to get the length of a Number −
Live Demo
<!DOCTYPE html>
<html>
   <body>
      <script>
         var num1 = 344;
         var num2 = 149856;

         document.write("Length of number "+num1+" = "+ num1.toString().length);
         document.write("<br>Length of number "+num2+" = "+ num2.toString().length);
      </script>
   </body>
</html>
Length of number 344 = 3
Length of number 149856 = 6
numpy.linalg.inv()

We use numpy.linalg.inv() function to calculate the inverse of a matrix. The inverse of a matrix is such that if it is multiplied by the original matrix, it results in identity matrix.
import numpy as np 

x = np.array([[1,2],[3,4]]) 
y = np.linalg.inv(x) 
print x 
print y 
print np.dot(x,y)
It should produce the following output −
[[1 2]                                                                        
 [3 4]]                                                                       
[[-2.   1. ]                                                                  
 [ 1.5 -0.5]]                                                                 
[[  1.00000000e+00   1.11022302e-16]                                          
 [  0.00000000e+00   1.00000000e+00]]

Let us now create an inverse of matrix A in our example.
import numpy as np 
a = np.array([[1,1,1],[0,2,5],[2,5,-1]]) 

print 'Array a:” 
print a 
ainv = np.linalg.inv(a) 

print 'Inverse of a:' 
print ainv  

print 'Matrix B is:' 
b = np.array([[6],[-4],[27]]) 
print b 

print 'Compute A-1B:' 
x = np.linalg.solve(a,b) 
print x  
# this is the solution to linear equations x = 5, y = 3, z = -2
It will produce the following output −
Array a:
[[ 1 1 1]
 [ 0 2 5]
 [ 2 5 -1]]

Inverse of a:
[[ 1.28571429 -0.28571429 -0.14285714]
 [-0.47619048 0.14285714 0.23809524]
 [ 0.19047619 0.14285714 -0.0952381 ]]

Matrix B is:
[[ 6]
 [-4]
 [27]]

Compute A-1B:
[[ 5.]
 [ 3.]
 [-2.]]

The same result can be obtained by using the function −
x = np.dot(ainv,b)


    63 Lectures 
     6 hours 

 Abhilash Nelson

    19 Lectures 
     8 hours 

 DATAhill Solutions Srinivas Reddy

    12 Lectures 
     3 hours 

 DATAhill Solutions Srinivas Reddy

    10 Lectures 
     2.5 hours 

 Akbar Khan

    20 Lectures 
     2 hours 

 Pruthviraja L

    63 Lectures 
     6 hours 

 Anmol
 Print
 Add Notes
 Bookmark this page
How to insert an element into DOM using jQuery?

There may be a situation when you would like to insert new one or more DOM elements in your existing document. jQuery provides various methods to insert elements at various locations.
The after( content ) method insert content after each of the matched elements whereas the method before( content ) method inserts content before each of the matched elements.
After content
The after( content ) method inserts content after each of the matched elements.
You can try to run the following code to learn how to insert an element into DOM, with after() method:
Live Demo
<html>

   <head>
      <title>jQuery after(content) method</title>
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
       
      <script>
         $(document).ready(function() {
            $("div").click(function () {
               $(this).after('<div class = "div"></div>' );
            });
         });
      </script>
       
      <style>
         .div {
             margin:10px;
             padding:12px;
             border:2px solid #666;
             width:60px;
         }
      </style>
   </head>
   <body>
   
      <p>Click on any square below to see the result:</p>
       
      <div class = "div" style = "background-color:blue;"></div>
      <div class = "div" style = "background-color:green;"></div>
      <div class = "div" style = "background-color:red;"></div>
       
   </body>
</html>
Before content
The before( content ) method inserts content before each of the matched elements.
You can try to run the following code to learn how to insert an element into DOM, with before() method:
Live Demo
<html>

   <head>
      <title>jQuery before(content) method</title>
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
       
      <script>
         $(document).ready(function() {
            $("div").click(function () {
               $(this).before('<div class = "div"></div>' );
            });
         });
      </script>
       
      <style>
         .div {
             margin:10px;
             padding:12px;
             border:2px solid #666;
             width:60px;
         }
      </style>
   </head>
   
   <body>
   
      <p>Click on any square below to see the result:</p>
      <div class = "div" style = "background-color:blue;"></div>
      <div class = "div" style = "background-color:green;"></div>
      <div class = "div" style = "background-color:red;"></div>
       
   </body>
</html>
Sort collection by multiple fields in Kotlin

A Collection is an object where developers can group different types of related objects in one place. There are different kinds of collections present in Kotlin library such as List, Array, etc.
In this article, we will see how we can sort a collection by different properties present inside that collection. In order to do that, we will be taking the help of the following two functions provided by the Kotlin library.
sortedWith()
sortedWith()
compareBy()
compareBy()
sortedWith() is a function provided by the Kotlin library that returns a list of all the elements sorted by a specified comparator. According to official Kotlin documentation, the function definition is,
fun <T> Array<out T>.sortedWith(
   comparator: Comparator<in T>
): List<T>
sortedWith() takes a comparator as an argument and compares the custom properties of each object and sorts the same.
compareBy() is responsible for creating the comparator that we will pass to sortedWith() in order to sort the object properties. As per the Kotlin documentation, the function definition goes like this:
fun <T> compareBy(
   vararg selectors: (T) -> Comparable<*>?
): Comparator<T>
In the following example, we will create a class Student that will hold different kinds of values such as student name, their age, and corresponding GPA. We want to sort the same as a whole, not by only "age" or "GPA".
fun main()
{

   val studentA=Student("Student A",18,7.0)
   val studentB=Student("Student B",18,6.9)
   val studentC=Student("Student C",20,7.3)
   val studentD=Student("Student D",22,8.3)

   val studentsList=listOf(
      studentA,
      studentB,
      studentC,
      studentD
   );

   val sortedList=studentsList.sortedWith(
      compareBy(
         {it.age},
         {it.GPA}
      )
   )

   sortedList.forEach {
      println("name: ${it.name}, age: ${it.age}, GPA: ${it.GPA}")
   }
}

class Student(val name:String, val age:Int, val GPA: Double)
Once you execute the code, it will generate the following output −
name: Student B, age: 18, GPA: 6.9
name: Student A, age: 18, GPA: 7.0
name: Student C, age: 20, GPA: 7.3
name: Student D, age: 22, GPA: 8.3
C++ decision making statements

Decision making structures require that the programmer specify one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false.
Following is the general form of a typical decision making structure found in most of the programming languages −
C++ programming language provides following types of decision making statements.
An ‘if’ statement consists of a boolean expression followed by one or more statements.
An ‘if’ statement can be followed by an optional ‘else’ statement, which executes when the boolean expression is false.
A ‘switch’ statement allows a variable to be tested for equality against a list of values.
You can use one ‘if’ or ‘else if’ statement inside another ‘if’ or ‘else if’ statement(s).
You can use one ‘switch’ statement inside another ‘switch’ statement(s).
We have covered conditional operator “? :” in previous chapter which can be used to replace if...else statements. It has the following general form −
Exp1 ? Exp2 : Exp3;

Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the colon.
The value of a ‘?’ expression is determined like this: Exp1 is evaluated. If it is true, then Exp2 is evaluated and becomes the value of the entire ‘?’ expression. If Exp1 is false, then Exp3 is evaluated and its value becomes the value of the expression.

    154 Lectures 
     11.5 hours 

 Arnab Chakraborty

    14 Lectures 
     57 mins

 Kaushik Roy Chowdhury

    30 Lectures 
     12.5 hours 

 Frahaan Hussain

    54 Lectures 
     3.5 hours 

 Frahaan Hussain

    77 Lectures 
     5.5 hours 

 Frahaan Hussain

    12 Lectures 
     3.5 hours 

 Frahaan Hussain
 Print
 Add Notes
 Bookmark this page
Scope of Variables in Python

All variables in a program may not be accessible at all locations in that program. This depends on where you have declared a variable.
The scope of a variable determines the portion of the program where you can access a particular identifier. There are two basic scopes of variables in Python −
Global variables
Local variables
Variables that are defined inside a function body have a local scope, and those defined outside have a global scope.
This means that local variables can be accessed only inside the function in which they are declared, whereas global variables can be accessed throughout the program body by all functions. When you call a function, the variables declared inside it are brought into scope.
 Live Demo
#!/usr/bin/python
total = 0; # This is global variable.
# Function definition is here
def sum( arg1, arg2 ):
   # Add both the parameters and return them."
   total = arg1 + arg2; # Here total is local variable.
   print "Inside the function local total : ", total
   return total;
# Now you can call sum function
sum( 10, 20 );
print "Outside the function global total : ", total
When the above code is executed, it produces the following result −
Inside the function local total : 30
Outside the function global total : 0
PLSQL | DECOMPOSE Function - GeeksforGeeks

20 Sep, 2019
The DECOMPOSE Function in PLSQL is used for accepting a string and returning its Unicode string.The DECOMPOSE Function is generally the opposite of the COMPOSE function.The DECOMPOSE function is valid only for Unicode characters and it returns a Unicode string after decomposition in the same character set as the input.The results of the inputs used can vary depending on the character set of the operating system used.
Syntax:
DECOMPOSE( string )
Parameters Used:
string – It is used to specify the string that needs to be decomposed.
Return Value:The DECOMPOSE function returns a Unicode string.
Supported Versions of Oracle/PLSQL:
Oracle 12cOracle 11gOracle 10gOracle 9i
Oracle 12c
Oracle 11g
Oracle 10g
Oracle 9i
Example:
DECLARE 
   Test_String2 varchar(5) := 'â';
   Test_String varchar(20) := 'Gèèksforgèèks';
   
BEGIN 
   dbms_output.put_line(DECOMPOSE(Test_String)); 
   dbms_output.put_line(DECOMPOSE(Test_String2)); 
   
END;  
Output:
a^
Ge ́e ́ksforge ́e ́ks 
SQL-PL/SQL
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Update Multiple Columns in Single Update Statement in SQL?
What is Temporary Table in SQL?
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL using Python
SQL | Subquery
How to Write a SQL Query For a Specific Date Range and Date Time?
SQL Query to Convert VARCHAR to INT
SQL Query to Delete Duplicate Rows
SQL Query to Compare Two Dates
Window functions in SQL
source command in Linux with Examples - GeeksforGeeks

31 Jan, 2021
source is a shell built-in command which is used to read and execute the content of a file(generally set of commands), passed as an argument in the current shell script. The command after taking the content of the specified files passes it to the TCL interpreter as a text script which then gets executed. If any arguments are supplied, they become the positional parameters when filename is executed. Otherwise, the positional parameters remain unchanged. The entries in $PATH are used to find the directory containing FILENAME, however if the file is not present in $PATH it will search the file in the current directory. The source command has no option and the argument is the file only. 
Syntax: 
 
source FILENAME [arguments]

Example 1: To pass gfg.txt as an argument which is stored in the home directory and contain list of command i.e. ls, date and time. Each command enlisted in the file will be executed line by line. 
 
Example 2: To pass a path_name of a file as an argument where, /home/sc/sourcefolder/ is the file directory here. The content of the file is written below: 
 
echo ” Hello, Welcome to Geeksforgeeks” echo “current directory is:” pwd echo “Date is:” date  
 
 
rahulmeewa
linux-command
Linux-misc-commands
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
TCP Server-Client implementation in C
ZIP command in Linux with examples
tar command in Linux with examples
curl command in Linux with Examples
UDP Server-Client implementation in C
Conditional Statements | Shell Script
Cat command in Linux with examples
touch command in Linux with Examples
echo command in Linux with Examples
Compiling with g++
MongoDB Query for boolean field as “not true”

You can use $ne(not equal) operator for this. The syntax is as follows −
db.yourCollectionName.find({yourFieldName: {$ne: true}}).pretty();
To understand the above syntax, let us create a collection with the document. The query to create a collection with a document is as follows −
> db.queryForBooleanFieldsDemo.insertOne({"EmployeeName":"Larry","EmployeeAge":24,"isOldEmployee":true});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8b7f7680f10143d8431e13")
}
> db.queryForBooleanFieldsDemo.insertOne({"EmployeeName":"Mike","EmployeeAge":20,"isOldEmployee":false});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8b7f8680f10143d8431e14")
}
> db.queryForBooleanFieldsDemo.insertOne({"EmployeeName":"Sam","EmployeeAge":23,"isOldEmployee":false});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8b7f9380f10143d8431e15")
}
> db.queryForBooleanFieldsDemo.insertOne({"EmployeeName":"David","EmployeeAge":25,"isOldEmployee":true});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8b7fa280f10143d8431e16")
}
> db.queryForBooleanFieldsDemo.insertOne({"EmployeeName":"Carol","EmployeeAge":27,"isOldEmployee":true});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8b7fae80f10143d8431e17")
}
Display all documents from a collection with the help of find() method. The query is as follows −
> db.queryForBooleanFieldsDemo.find().pretty();
The following is the output −
{
   "_id" : ObjectId("5c8b7f7680f10143d8431e13"),
   "EmployeeName" : "Larry",
   "EmployeeAge" : 24,
   "isOldEmployee" : true
}
{
   "_id" : ObjectId("5c8b7f8680f10143d8431e14"),
   "EmployeeName" : "Mike",
   "EmployeeAge" : 20,
   "isOldEmployee" : false
}
{
   "_id" : ObjectId("5c8b7f9380f10143d8431e15"),
   "EmployeeName" : "Sam",
   "EmployeeAge" : 23,
   "isOldEmployee" : false
}
{
   "_id" : ObjectId("5c8b7fa280f10143d8431e16"),
   "EmployeeName" : "David",
   "EmployeeAge" : 25,
   "isOldEmployee" : true
}
{
   "_id" : ObjectId("5c8b7fae80f10143d8431e17"),
   "EmployeeName" : "Carol",
   "EmployeeAge" : 27,
   "isOldEmployee" : true
}
Here is the query for the boolean field as “not true” −
> db.queryForBooleanFieldsDemo.find({isOldEmployee: {$ne: true}}).pretty();
The following is the output −
{
   "_id" : ObjectId("5c8b7f8680f10143d8431e14"),
   "EmployeeName" : "Mike",
   "EmployeeAge" : 20,
   "isOldEmployee" : false
}
{
   "_id" : ObjectId("5c8b7f9380f10143d8431e15"),
   "EmployeeName" : "Sam",
   "EmployeeAge" : 23,
   "isOldEmployee" : false
}
How to save Pandas data into Excel multiple sheets?

To save Pandas DataFrames into multiple excel sheets, we can use the pd.ExcelWriter() method. Make sure you have the openpyxl package installed before using ExcelWriter().
Create a two-dimensional, size-mutable, potentially heterogeneous tabular data, df1.
Print the input DataFrame, df1.
Create another DataFrame, df2, and print it.
Use ExcelWriter() method to write the given formatted cells into an Excel sheet.
import pandas as pd

df1 = pd.DataFrame(
   [[5, 2], [4, 1]],
   index=["One", "Two"],
   columns=["Rank", "Subjects"]
)

df2 = pd.DataFrame(
   [[15, 21], [41, 11]],
   index=["One", "Two"],
   columns=["Rank", "Subjects"]
)

print "DataFrame 1:\n", df1
print "DataFrame 2:\n", df2

with pd.ExcelWriter('output.xlsx') as writer:
df1.to_excel(writer, sheet_name='Sheet_name_1')
df2.to_excel(writer, sheet_name='Sheet_name_2')
DataFrame 1:

     Rank  Subjects
One    5     2
Two    4     1

DataFrame 2:

     Rank Subjects
One   15    21
Two   41    11
It will also create an Excel file called "output.xlsx" in your project directory and save the DataFrame values in two different sheets.
Breadth First Search (BFS) for a Graph

The Breadth First Search (BFS) traversal is an algorithm, which is used to visit all of the nodes of a given graph. In this traversal algorithm one node is selected and then all of the adjacent nodes are visited one by one. After completing all of the adjacent vertices, it moves further to check another vertex and checks its adjacent vertices again.
To implement this algorithm, we need to use the Queue data structure. All the adjacent vertices are added into the queue when all adjacent vertices are completed, one item is removed from the queue and start traversing through that vertex again.
In Graph sometimes, we may get some cycles, so we will use an array to mark when a node is visited already or not.
Input:
The Adjacency matrix of the graph.

     A B C D E F
   A 0 1 1 1 0 0
   B 1 0 0 1 1 0
   C 1 0 0 1 0 1
   D 1 1 1 0 1 1
   E 0 1 0 1 0 1
   F 0 0 1 1 1 0

Output:
BFS Traversal: B A D E C F
bfs(vertices, start)
Input − The list of vertices, and the start vertex.
Output − Traverse all of the nodes, if the graph is connected.
Begin
   define an empty queue que
   at first mark all nodes status as unvisited
   add the start vertex into the que

   while que is not empty, do
      delete item from que and set to u
      display the vertex u

      for all vertices 1 adjacent with u, do
         if vertices[i] is unvisited, then
            mark vertices[i] as temporarily visited
            add v into the queue
         mark
      done

      mark u as completely visited
   done
End
#include<iostream>
#include<queue>
#define NODE 6
using namespace std;

typedef struct node {
   int val;
   int state;    //status
}node;

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

void bfs(node *vert, node s) {
   node u;
   int i, j;
   queue<node> que;

   for(i = 0; i<NODE; i++) {
      vert[i].state = 0;    //not visited
   }

   vert[s.val].state = 1;   //visited
   que.push(s);            //insert starting node

   while(!que.empty()) {
      u = que.front();    //delete from queue and print
      que.pop();
      cout << char(u.val+'A') << " ";

      for(i = 0; i<NODE; i++) {
         if(graph[i][u.val]) {
            //when the node is non-visited
            if(vert[i].state == 0) {
               vert[i].state = 1;
               que.push(vert[i]);
            }    
         }
      }
      u.state = 2;   //completed for node u
   }
}

int main() {
   node vertices[NODE];
   node start;
   char s;

   for(int i = 0; i<NODE; i++) {
      vertices[i].val = i;
   }

   s = 'B';   //starting vertex B
   start.val = s-'A';
   cout << "BFS Traversal: ";
   bfs(vertices, start);
   cout << endl;
}
BFS Traversal: B A D E C F
TypeScript | Array some() Method

03 Mar, 2021
The Array.some() is an inbuilt TypeScript function which is used to check for some element in the array passes the test implemented by the provided function.Syntax:
array.some(callback[, thisObject])
Parameter: This method accept two parameter as mentioned above and described below:
callback : This parameter is the Function to test for each element.
thisObject : This parameter is the Object to use as this when executing callback.
Return Value: This method returns true if some element in this array satisfies the provided testing function. Below example illustrate the  Array  some() method in TypeScriptJS:Example 1: 
TypeScript
// check for positive number function ispositive(element, index, array){    return element > 0;}  // Driver codevar arr = [ 11, 89, 23, 7, 98 ];   // check for positive number var value = arr.some(ispositive); console.log( value );
Output: 
true
Example 2: 
TypeScript
// check for even number function iseven(element, index, array) {     return (element % 2 == 0);  }   // Driver codevar arr = [ 11, 89, 23, 7, 91 ];   // check for positive number var value = arr.some(iseven); console.log( value );
Output: 
 
false
 
pratikraut0000
TypeScript
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
Difference Between PUT and PATCH Request
Roadmap to Learn JavaScript For Beginners
JavaScript | Promises
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
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 ?
Interesting Facts in C Programming

06 Jan, 2019
Below are some interesting facts about C programming:
1) The case labels of a switch statement can occur inside if-else statements.
#include <stdio.h>  int main(){    int a = 2, b = 2;    switch(a)    {    case 1:        ;          if (b==5)        {        case 2:            printf("GeeksforGeeks");        }    else case 3:    {      }    }}
Output :
GeeksforGeeks
2) arr[index] is same as index[arr]The reason for this to work is, array elements are accessed using pointer arithmetic.
// C program to demonstrate that arr[0] and// 0[arr]#include<stdio.h>int main() {    int arr[10];    arr[0] = 1;    printf("%d", 0[arr] );          return 0;    }
Output :
1
3) We can use ‘<:, :>’ in place of ‘[,]’ and ‘<%, %>’ in place of ‘{,}’
#include<stdio.h>int main()<%    int arr <:10:>;    arr<:0:> = 1;    printf("%d", arr<:0:>);      return 0;%>
Output :
1
4) Using #include in strange places.Let “a.txt” contains (“GeeksforGeeks”);
#include<stdio.h>int main(){    printf    #include "a.txt"    ;}
Output :
GeeksforGeeks
5) We can ignore input in scanf() by using an ‘*’ after ‘%’ in format specifiers
#include<stdio.h>int main(){    int a;      // Let we input 10 20, we get output as 20    // (First input is ignored)    // If we remove * from below line, we get 10.    scanf("%*d%d", &a);      printf( "%d ",  a);        return 0;     }
This article is contributed by Harsh Agarwal. 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.
C-Input and Output Quiz
c-input-output
C-Loops & Control Statements
interesting-facts
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Functions that cannot be overloaded in C++
Exception Handling in C++
Function Pointer in C
Left Shift and Right Shift Operators in C/C++
Command line arguments in C/C++
Multidimensional Arrays in C / C++
Different Methods to Reverse a String in C++
Structures in C
Switch Statement in C/C++
Program to Emulate N Dice Roller

29 Jul, 2021
In this article, we emulate N Dice roller. Given N, the task is to create a Java program which outputs N random numbers where each number is in the range 1 to 6 inclusive. Such type of emulation can be used in games and apart from that some similar variations of the problem statement can be used in several other applications.
Example1:
Enter the Number of dice: 4  
Hey Geek! You rolled: 3 2 1 6
Total: 12
Example2:
Enter the Number of dice: 2  
Hey Geek! You rolled: 1 6
Total: 7
Note: The output may change since we are using random numbers.
Approach:
Here, we use the Random object in Java to generate random integers in the range 1 to 6 inclusive and execute a loop to generate such random numbers N times.
Implementation
C++
Java
#include <cstdlib>#include <ctime>#include <iostream>using namespace std;int main(){    int numberOfDice, total = 0;     cout << "Enter the Number of dice: ";    cin >> numberOfDice;       // calling srand() with time() function for seed    // generation    srand((unsigned)time(0));    cout << "Hey Geek! You rolled: ";     for (int i = 0; i < numberOfDice ; i++)    {               // Generating the random number and storing it        // in the 'randomNumber' variable        int  randomNumber = (rand() % 6) + 1;        total +=  randomNumber;        cout <<  randomNumber << " ";    }    cout << "\n"         << "Total: " << total << "\n";    return 0;} // This code is contributed by anurag31.
import java.util.Random;import java.util.Scanner; public class Main {    public static void main(String args[])    {        System.out.print("Enter the number of dice: ");         // Initializing the Scanner object to read input        Scanner input = new Scanner(System.in);        int numberOfDice = input.nextInt();         // Initializing the Random object for        // generating random numbers        Random ranNum = new Random();         System.out.print("Hey Geek! You rolled: ");        int total = 0;        int randomNumber = 0;         for (int i = 0; i < numberOfDice; i++) {             // Generating the random number and storing it            // in the 'randomNumber' variable            randomNumber = ranNum.nextInt(6) + 1;            total = total + randomNumber;            System.out.print(randomNumber);            System.out.print(" ");        }         System.out.println("");        System.out.println("Total: " + total);        input.close();    }}
  
Output
 
 
Time Complexity: O(N)
 
Auxiliary Space: O(1)
 
 
anurag31
Picked
Java
Java Programs
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
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
Factory method design pattern in Java
Java Program to Remove Duplicate Elements From the Array
Collect.js pull() Method

30 Nov, 2020
The pull() method is used to remove an element from collection by given key and return the pulled element.
Syntax:
collect(array).pull(key)
Parameters: The collect() method takes one argument that is converted into the collection and then pull() method is applied on it. The pull() method holds the key as parameter.
Return Value: This method returns the value of given key.
Below example illustrate the pull() method in collect.js:
Example 1:
Javascript
const collect = require('collect.js');  let obj = ['Welcome', 'Geeks', 'GFG', 'GeeksforGeeks'];  const collection = collect(obj);  console.log(collection.pull(3));
Output:
GeeksforGeeks
Example 2:
Javascript
const collect = require('collect.js');  let obj = {    name: 'Rahul',    dob: '25-10-96',    section: 'A',    score: 98,};  const collection = collect(obj);  console.log(collection.pull('name'));console.log(collection.pull('dob'));
Output:
Rahul
25-10-96
Collect.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Deserializing a JSON into a JavaScript object

05 Jul, 2021
To Deserialize a JSON into a JavaScript object, here we will use a common method JSON.parse() method.
JavaScript Object Notation is used to exchange data to or from a web server or RESTFull API. The data received from a web server is always a string. In order to use that data you need to parse the data with JSON.parse() which will returns a JavaScript Object or Array of Objects.
Syntax:  
JSON.parse( string, function )
Example 1:  
html
<!DOCTYPE html><html> <head>    <title>    Deserializing a JSON into a JavaScript object        using JSON parse() Method    </title></head> <body><center>    <h1 style="color: green;">GeeksforGeeks</h1>    <h3>Deserializing a JSON into a JavaScript object</h3>    <p id="geeks"></p>           <!-- Script to parse a string and return        JavaScript object -->    <script>        var obj = JSON.parse('{"var1":"Hello", "var2":"Geeks!"}');                 document.getElementById("geeks").innerHTML                = obj.var1 + " " + obj.var2;    </script>    </center></body> </html>                    
Output:  
Example 2: Here we will use reviver function to parse a string and return the JavaScript object.  
html
<!DOCTYPE html><html> <body>    <center>        <h1 style="color:green">GeeksforGeeks</h1>        <h3>Convert a string into a date object.</h3>         <p id="geeks"></p>          <script>            var text = '{"name":" Pankaj_Singh",\                 "birth":"1996-12-14", "city":"Jhansi"}';            var obj = JSON.parse(text);            obj.birth = new Date(obj.birth);            document.getElementById("geeks").innerHTML =                             obj.name + ", " + obj.birth;        </script></center></body> </html>                   
Output:  
 
Chrome 4.0
Firefox 3.5
Opera 11.0
Internet Explorer 8.0
Safari 4.0
 
anikakapoor
JSON
Picked
JavaScript
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Convert String from Uppercase to Lowercase in R programming – tolower() method

10 May, 2020
tolower() method in R programming is used to convert the uppercase letters of string to lowercase string.
Syntax: tolower(s)
Return: Returns the lowercase string.
Example 1:
# R program to convert string# from uppercase to lowercasegfg <- "GeEks FoR GeeKs"  # Using tolower() methodanswer <- tolower(gfg)  print(answer)
Output:
[1] "geeks for geeks"

Example 2:
# R program to convert string# from uppercase to lowercase  # Given Stringgfg <- "The QuiCk bRown FoX jUmpS oVer tHe LaZy dOG"  # Using tolower() methodanswer <- tolower(gfg)  print(answer)
Output:
[1] "the quick brown fox jumps over the lazy dog"

R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | asksaveasfile() function in Tkinter

29 Nov, 2021
Python provides a variety of modules with the help of which one may develop GUI (Graphical User Interface) applications. Tkinter is one of the easiest and fastest way to develop GUI applications.
While working with files one may need to open files, do operations on files and after that to save file. asksaveasfile() is the function which is used to save user’s file (extension can be set explicitly or you can set default extensions also). This function comes under the class filedialog.
Below is the Code:
# importing all files  from tkinterfrom tkinter import * from tkinter import ttk  # import only asksaveasfile from filedialog# which is used to save file in any extensionfrom tkinter.filedialog import asksaveasfile  root = Tk()root.geometry('200x150')  # function to call when user press# the save button, a filedialog will# open and ask to save filedef save():    files = [('All Files', '*.*'),              ('Python Files', '*.py'),             ('Text Document', '*.txt')]    file = asksaveasfile(filetypes = files, defaultextension = files)  btn = ttk.Button(root, text = 'Save', command = lambda : save())btn.pack(side = TOP, pady = 20)  mainloop()
Output #1: Directory before saving any file (folder is initially empty)
Output #2: Dialogbox when user presses the save button (dialog box to save file is opened). You may see in the output Python file as default is selected.
Output #3: Directory after saving 2 Python files (one may also change the type of file)
Python-gui
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
How to Install PIP on Windows ?
Python String | replace()
Python OOPs Concepts
Python Program to find the Larger String without Using Built-in Functions

26 Nov, 2020
Given two strings. The task is to find the larger string without using built-in functions.
Examples:
Input:
GeeksforGeeks
Geeks
Output:
GeeksforGeeks

Input:
GeeksForFeeks is an good Computer Coding Website
It offers several topics
Output:
GeeksForFeeks is an good Computer Coding Website

Step-by-step Approach:
Take two strings in separate variables.
Initialize the two count variables to zero.
Use a for loop to traverse through the characters in the string and increment the count variables each time a character is encountered.
Compare the count variables of both the strings.
Print the larger string.
Exit.
Below is the complete program based on the above approach:
Python3
string1="GeeksForFeeks is an good Computer Coding Website "string2="It offers several topics"count1=0count2=0  for i in string1:      count1=count1+1for j in string2:      count2=count2+1  if(count1<count2):      print("Larger string is:")      print(string2)  elif(count1==count2):      print("Both strings are equal.")  else:      print("Larger string is:")      print(string1)
Larger string is:
GeeksForFeeks is an good Computer Coding Website 

Program Explanation :
User must enter two strings and store it in separate variables.The count variables are initialized to zero.The for loop is used to traverse through the characters in the strings.The count variables are incremented each time a character is encountered.The count variables are then compared and the larger string is printed.
User must enter two strings and store it in separate variables.
The count variables are initialized to zero.
The for loop is used to traverse through the characters in the strings.
The count variables are incremented each time a character is encountered.
The count variables are then compared and the larger string is printed.
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Split by repeating substring

22 Apr, 2020
Sometimes, while working with Python strings, we can have a problem in which we need to perform splitting. This can be of custom nature. In this, we can have a split in which we need to split by all the repetitions. This can have application in many domains. Lets discuss certain ways in which this task can be performed.
Method #1 : Using * operator + len()This is one of the way in this we can perform this task. In this, we compute the length of repeated string and then divide the list to obtain root and construct new list using * operator.
# Python3 code to demonstrate working of # Split by repeating substring# Using * operator + len()  # initializing stringtest_str = "gfggfggfggfggfggfggfggfg"  # printing original stringprint("The original string is : " + test_str)  # initializing targetK = 'gfg'  # Split by repeating substring# Using * operator + len()temp = len(test_str) // len(str(K))res = [K] * temp  # printing result print("The split string is : " + str(res)) 
The original string is : gfggfggfggfggfggfggfggfg
The split string is : ['gfg', 'gfg', 'gfg', 'gfg', 'gfg', 'gfg', 'gfg', 'gfg']

 
Method #2 : Using re.findall()This is yet another way in which this problem can be solved. In this, we use findall() to get all the substrings and split is also performed internally.
# Python3 code to demonstrate working of # Split by repeating substring# Using re.findall()import re  # initializing stringtest_str = "gfggfggfggfggfggfggfggfg"  # printing original stringprint("The original string is : " + test_str)  # initializing targetK = 'gfg'  # Split by repeating substring# Using re.findall()res = re.findall(K, test_str)  # printing result print("The split string is : " + str(res)) 
The original string is : gfggfggfggfggfggfggfggfg
The split string is : ['gfg', 'gfg', 'gfg', 'gfg', 'gfg', 'gfg', 'gfg', 'gfg']

Python string-programs
Python
Python Programs
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
Python | os.path.join() method
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Convert string dictionary to dictionary
Tuples in Julia

23 Jan, 2022
Tuples in Julia are an immutable collection of distinct values of same or different datatypes separated by commas. Tuples are more like arrays in Julia except that arrays only take values of similar datatypes. The values of a tuple can not be changed because tuples are immutable. Tuples are a heterogeneous collection of values.The sequence of values stored in a tuple can be of any type, and they are indexed by integers. Values of a tuple are syntactically separated by ‘commas’. Although it is not necessary, it is more common to define a tuple by closing the sequence of values in parentheses. This helps in understanding the Julia tuples more easily.Syntax:  
Tuple_name = (value1, value2, value3, ...)
Example:  
Python
# Julia program to define Tuples # Creating an empty tupletupl1 = ()println(isempty(tupl1)) # Creating a tuple with similar valuestupl2 = (1, 2, 4, 5)println(tupl2) # Creating a tuple with mixed valuestupl3 = (1, 2, 3, "Hello Geeks")println(tupl3)
Output:  
 
Elements of a tuple can be easily extracted with the use of square brackets([]). Loops can also be used to extract more than one element from a tuple. Also, a range of elements can also be extracted from a tuple by passing a range within square brackets just like strings.Example:  
Python
# Julia program to access elements# from a Tuple # Creating a tupletupl = ("Hello", "Geeks", 1, 2, 3, "Welcome") # Accessing tuple elementsprintln(tupl[2]) # Accessing a range of elementsprintln(tupl[1:3]) # Using for loop to iterate over tuplefor i in tupl    println(i)end
Output:  
 
Tuples allow performing various operations on them as per user needs. These operations can be like reverse, length, map, isempty, etc. 
Python
# Julia program to access elements# from a Tuple # Creating a tupletupl = ("Hello", "Geeks", 1, 2, 3, "Welcome") # Reversing tupleRev_tupl = reverse(tupl)println(Rev_tupl) # Printing Tuple lengthprintln(length(tupl)) # Using map operatorprintln(map(typeof, tupl)) # Checking if tuple is emptyprintln(isempty(tupl))
Output:  
 
adnanirshad158
Julia-dataTypes
Julia
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.