code-rag-bench/online-tutorials huggingface dataset:
Add data to existing data in a MySQL Database?

You can use CONCAT() function for this. Let us first create a table −
mysql> create table DemoTable
   (
   UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   UserName varchar(100)
   );
Query OK, 0 rows affected (0.43 sec)
Insert records in the table using insert command −
mysql> insert into DemoTable(UserName) values('John');
Query OK, 1 row affected (0.24 sec)
mysql> insert into DemoTable(UserName) values('Chris');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable(UserName) values('Robert');
Query OK, 1 row affected (0.11 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+--------+----------+
| UserId | UserName |
+--------+----------+
| 1      | John     |
| 2      | Chris    |
| 3      | Robert   |
+--------+----------+
3 rows in set (0.00 sec)
Here is the query to add data to existing data in MySQL database. The UserId 1 is concatenated with the name “Smith” to the already existed name−
mysql> update DemoTable
set UserName=concat(UserName,' Smith') where UserId=1;
Query OK, 1 row affected (0.12 sec)
Rows matched: 1 Changed: 1 Warnings: 0
Let us check the table records once again −
mysql> select *from DemoTable;
This will produce the following output −
+--------+------------+
| UserId | UserName   |
+--------+------------+
| 1      | John Smith |
| 2      | Chris      |
| 3      | Robert     |
+--------+------------+
3 rows in set (0.00 sec)
Check Constraint in MS SQL Server - GeeksforGeeks

26 Aug, 2020
Check Constraint :It is used alongside relational operators to check whether a value satisfies the condition or not (boolean). If the condition is satisfied, the boolean expression sets to True otherwise False. The check constraint does not have a specific syntax. It is used along with the create table syntax.
Syntax :
Create table Marks 
name varchar2(30), 
rollnumber number primary key, 
marks int check (marks<=75)
A table named Student is created along with the condition that marks must not be greater than 75. A user inserts a few values as shown below –
Table – Marks
The values are inserted as per the conditions mentioned in the create table syntax. The user tries inserting a few more values yet errors occur as shown below –
Example-1:
Insert into Student 
values('Maya', '117', '80')
Output –The value results in an error as the value is greater than 75.Example-2:
Insert into Student 
values('Maya' '111', '74')
Output –An error is displayed. This is due to the primary key used for rollnumber. Primary key forbids the use of duplicates in a table.Check constraint in case of NULL :
Insert into Student 
values('Riya', '112', 'NULL')
Output –In SQL, NULL is used incase of unknown value. Therefore it is considered as False.
SQL-Server
DBMS
SQL
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Second Normal Form (2NF)
Introduction of Relational Algebra in DBMS
What is Temporary Table in SQL?
Types of Functional dependencies in DBMS
Difference between Where and Having Clause in SQL
SQL | DDL, DQL, DML, DCL and TCL Commands
How to find Nth highest salary from a table
SQL | ALTER (RENAME)
How to Update Multiple Columns in Single Update Statement in SQL?
What is Temporary Table in SQL?
Tryit Editor v3.6 - Show React

import React from 'react';
import ReactDOM from 'react-dom/client';

class Header extends React.Component {
  constructor(props) {
    super(props);
    this.state = {favoritecolor: "red"};
  }
  componentDidMount() {
    setTimeout(() => {
      this.setState({favoritecolor: "yellow"})
    }, 1000)
  }
  getSnapshotBeforeUpdate(prevProps, prevState) {
    document.getElementById("div1").innerHTML =
    "Before the update, the favorite was " + prevState.favoritecolor;
  }
  componentDidUpdate() {
    document.getElementById("div2").innerHTML =
    "The updated favorite is " + this.state.favoritecolor;
  }
  render() {
    return (
      <div>
      <h1>My Favorite Color is {this.state.favoritecolor}</h1>
      <div id="div1"></div>
      <div id="div2"></div>
      </div>
    );
  }
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Header />);




<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport"
      content="width=device-width, initial-scale=1" />
How to split images into different channels in OpenCV using C++?

There are three channels in an RGB image- red, green and blue. The color space where red, green and blue channels represent images is called RGB color space. In OpenCV, BGR sequence is used instead of RGB. This means the first channel is blue, the second channel is green, and the third channel is red. To split an RGB image into different channels, we need to define a matrix of 3 channels. We use 'Mat different_Channels[3]' to define a three-channel matrix.
Next, we split the loaded image using OpenCV 'split()' function. The format of this function is 'split(Source Matrix, Destination Matrix)'. This function split the images of the source matrix into the channels the image and save them in the destination matrix. This line is operating – 'split(myImage, different_Channels);'
The split function has already loaded the blue, green and red channel into the 'different_channels' matrix. Using the following lines, we loaded the images stored in different channels into new matrices.
Mat b = different_Channels[0];//loading blue channels//
Mat g = different_Channels[1];//loading green channels//
Mat r = different_Channels[2];//loading red channels//
And finally we showed each channel differently using the following lines −
imshow("Blue Channel",b);//showing Blue channel//
imshow("Green Channel",g);//showing Green channel//
imshow("Red Channel",r);//showing Red channel//
This is how we can split an images into its channels.
The following program splits an RGB image into blue, green, and red channel.
#include<iostream>
#include<opencv2/highgui/highgui.hpp>
#include<opencv2/imgproc/imgproc.hpp>
using namespace cv;
using namespace std;
int main(int argc,const char** argv) {
   Mat myImage;//declaring a matrix to load the image//
   Mat different_Channels[3];//declaring a matrix with three channels//  
   myImage= imread("RGB.png");//loading the image in myImage matrix//
   split(myImage, different_Channels);//splitting images into 3 different channels//  
   Mat b = different_Channels[0];//loading blue channels//
   Mat g = different_Channels[1];//loading green channels//
   Mat r = different_Channels[2];//loading red channels//  
   imshow("Blue Channel",b);//showing Blue channel//
   imshow("Green Channel",g);//showing Green channel//
   imshow("Red Channel",r);//showing Red channel//
   imshow("Actual_Image", myImage);//showing actual image//
   waitKey(0);//wait for key stroke
   destroyAllWindows();//closing all windows//
   return 0;
}
HTML <tt> Tag - GeeksforGeeks

17 Mar, 2022
The <tt> tag is the abbreviation of teletype text. This tag is depreciated from HTML 5. It was used for marking Keyboard input. It was mainly used for formatting purposes. This tag was used in HTML 4 (Not Supported in HTML5).Syntax: 
<tt> Contents... </tt>
Below example illustrates the <tt> tag in HTML:
Example: 
HTML
<html>       <body>        <h1>GeeksforGeeks</h1>        <h2>tt Tag</h2>                <!-- HTML tt Tag is used here-->       <tt>GfG stands for GeeksforGeeks</tt>                 <p><tt>It is a computer science portal for geeks</tt></p>      </body>   </html>                                       
Output: 
Supported Browsers: 
Google Chrome
Internet Explorer
Firefox
Opera
Safari
 
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
arorakashish0911
shubhamyadav4
HTML-Tags
HTML
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to set the default value for an HTML <select> element ?
How to update Node.js and NPM to next version ?
How to set input type date in dd-mm-yyyy format using HTML ?
Types of CSS (Cascading Style Sheet)
Hide or show elements in HTML using display property
How to Insert Form Data into Database using PHP ?
CSS to put icon inside an input element in a form
REST API (Introduction)
pandas.isna() function in Python

14 Aug, 2020
This method is used to detect missing values for an array-like object. This function takes a scalar or array-like object and indicates whether values are missing (“NaN“ in numeric arrays, “None“ or “NaN“ in object arrays, “NaT“ in datetimelike).
Syntax : pandas.isna(obj)
Argument :
obj : scalar or array-like, Object to check for null or missing values.
Below is the implementation of the above method with some examples :
Example 1 :
Python3
# importing packageimport numpyimport pandas  # string "deep" is not nan valueprint(pandas.isna("deep"))  # numpy.nan represents a nan valueprint(pandas.isna(numpy.nan))
Output :
False
True

Example 2 :
Python3
# importing packageimport numpyimport pandas  # create and view dataarray = numpy.array([[1, numpy.nan, 3],                      [4, 5, numpy.nan]])  print(array)  # numpy.nan represents a nan valueprint(pandas.isna(array))
Output :
[[ 1. nan  3.]
 [ 4.  5. nan]]
[[False  True False]
 [False False  True]]

Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
time.Time.AddDate() Function in Golang with Examples

19 Apr, 2020
In Go language, time packages supplies functionality for determining as well as viewing time. The Time.AddDate() function in Go language is used to check the time which is equivalent to adding the stated number of years, months, and days to the given “t”.For example, if the parameters of the method are like (-2, 4, 5) and the stated t is February 3, 2018 then the output will be June 8, 2016. Like Date method here also if the range of months, days or years are outside the normal range then its automatically converted to normalized range. Moreover, this function is defined under the time package. Here, you need to import “time” package in order to use these functions.
Syntax:
func (t Time) AddDate(years int, months int, days int) Time

Here, “t” is the stated time.
Return Value: It returns the result of adding stated t to the stated number of years, months, and days.
Example 1:
// Golang program to illustrate the usage of// Time.AddDate() function  // Including main packagepackage main  // Importing fmt and timeimport "fmt"import "time"  // Calling mainfunc main() {      // Declaring Time in UTC    Time := time.Date(2018, 6, 4, 0, 0, 0, 0, time.UTC)      // Calling AddDate method with all    // its parameters    t1 := Time.AddDate(1, 2, 5)    t2 := Time.AddDate(5, -2, 9)    t3 := Time.AddDate(0, 3, -3)    t4 := Time.AddDate(1, 0, 0)      // Prints output    fmt.Printf("%v\n", Time)    fmt.Printf("%v\n", t1)    fmt.Printf("%v\n", t2)    fmt.Printf("%v\n", t3)    fmt.Printf("%v\n", t4)}
Output:
2018-06-04 00:00:00 +0000 UTC
2019-08-09 00:00:00 +0000 UTC
2023-04-13 00:00:00 +0000 UTC
2018-09-01 00:00:00 +0000 UTC
2019-06-04 00:00:00 +0000 UTC

Here, the output returned is in UTC as defined above.
Example 2:
// Golang program to illustrate the usage of// Time.AddDate() function  // Including main packagepackage main  // Importing fmt and timeimport "fmt"import "time"  // Calling mainfunc main() {      // Declaring Time in UTC    Time := time.Date(2020, 15, 34, 0, 0, 0, 0, time.UTC)      // Calling AddDate method with all    // its parameters    t1 := Time.AddDate(3, 13, 35)    t2 := Time.AddDate(2, -24, 29)    t3 := Time.AddDate(4, 32, -31)    t4 := Time.AddDate(5, 10, -11)      // Prints output    fmt.Printf("%v\n", Time)    fmt.Printf("%v\n", t1)    fmt.Printf("%v\n", t2)    fmt.Printf("%v\n", t3)    fmt.Printf("%v\n", t4)}
Output:
2021-04-03 00:00:00 +0000 UTC
2025-06-07 00:00:00 +0000 UTC
2021-05-02 00:00:00 +0000 UTC
2027-11-02 00:00:00 +0000 UTC
2027-01-23 00:00:00 +0000 UTC

Here, the range used is outside the usual range but they are normalized while converted.
GoLang-time
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
strings.Replace() Function in Golang With Examples
fmt.Sprintf() Function in Golang With Examples
Arrays in Go
Golang Maps
How to Split a String in Golang?
Interfaces in Golang
Slices in Golang
Different Ways to Find the Type of Variable in Golang
How to Parse JSON in Golang?
How to convert a string in lower case in Golang?
Print first letter of each word in a string using regex

11 Dec, 2018
Given a string, extract the first letter of each word in it. “Words” are defined as contiguous strings of alphabetic characters i.e. any upper or lower case characters a-z or A-Z.
Examples:
Input : Geeks for geeks
Output :Gfg
        
Input : United Kingdom
Output : UK

Below is the Regular expression to extract the first letter of each word. It uses ‘/b'(one of boundary matchers). Please refer How to write Regular Expressions? to learn it.
\b[a-zA-Z]

// Java program to demonstrate extracting first// letter of each word using Regex  import java.util.regex.Matcher;import java.util.regex.Pattern;  public class Test {    public static void main(String[] args)     {        String s1 = "Geeks for Geeks";        String s2 = "A Computer Science Portal for Geeks";                  Pattern p = Pattern.compile("\\b[a-zA-Z]");                  Matcher m1 = p.matcher(s1);        Matcher m2 = p.matcher(s2);                  System.out.println("First letter of each word from string \"" + s1 + "\" : ");        while (m1.find())            System.out.print(m1.group());                  System.out.println();                  System.out.println("First letter of each word from string \"" + s2 + "\" : ");                  while (m2.find())             System.out.print(m2.group());                        }}
Output:
First letter of each word from string "Geeks for Geeks" : 
GfG
First letter of each word from string "A Computer Science Portal for Geeks" : 
ACSPfG

Next Article: Extracting each word from a String using Regex in Java
This article is contributed by Gaurav Miglani. 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.
java-regular-expression
Java-String-Programs
Java-Strings
Java
Java-Strings
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python sympy | Matrix.diagonalize() method

30 Dec, 2020
With the help of sympy.Matrix().diagonalize() method, we can diagonalize a matrix. diagonalize() returns a tuple , where  is diagonal and .
Syntax: Matrix().diagonalize()
Returns: Returns a tuple of matrix where the second element represents the diagonal of the matrix.
Example #1:
# import sympy from sympy import * M = Matrix([[3, -2,  4, -2],                                [5,  3, -3, -2],                                [5, -2,  2, -2],                                [5, -2, -3,  3]])  print("Matrix : {} ".format(M))   # Use sympy.diagonalize() method P, D = M.diagonalize()        print("Diagonal of a matrix : {}".format(D))  
Output:
Matrix : Matrix([[3, -2, 4, -2], [5, 3, -3, -2], [5, -2, 2, -2], [5, -2, -3, 3]])Diagonal of a matrix : Matrix([[-2, 0, 0, 0], [0, 3, 0, 0], [0, 0, 5, 0], [0, 0, 0, 5]])
Example #2:
# import sympy from sympy import * M = Matrix([[1, -3, 3], [3, -5, 3], [6, -6, 4]]) print("Matrix : {} ".format(M))   # Use sympy.diagonalize() method P, D = M.diagonalize()        print("Diagonal of a matrix : {}".format(D))
Output:
Matrix : Matrix([[1, -3, 3], [3, -5, 3], [6, -6, 4]])Diagonal of a matrix : Matrix([[-2, 0, 0], [0, -2, 0], [0, 0, 4]])
Python matrix-program
SymPy
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
Python | Decimal quantize() method

09 Sep, 2019
Decimal#quantize() : quantize() is a Decimal class method which returns a value equal to first decimal value (rounded) having the exponent of second decimal value.
Syntax: Decimal.quantize()
Parameter: Decimal values
Return: a value equal to first decimal value (rounded) having the exponent of second decimal value.
Code #1 : Example for quantize() method
# Python Program explaining # quantize() method  # loading decimal libraryfrom decimal import *    # Initializing a decimal valuea = Decimal(-1)  b = Decimal('0.142857')  # printing Decimal valuesprint ("Decimal value a : ", a)print ("Decimal value b : ", b)    # Using Decimal.quantize() methodprint ("\n\nDecimal a with quantize() method : ", a.quantize(b))  print ("Decimal b with quantize() method : ", b.quantize(b))
Output :
Decimal value a :  -1
Decimal value b :  0.142857


Decimal a with quantize() method :  -1.000000
Decimal b with quantize() method :  0.142857


Code #2 : Example for quantize() method
# Python Program explaining # quantize() method  # loading decimal libraryfrom decimal import *    # Initializing a decimal valuea = Decimal('-3.14')  b = Decimal('321e + 5')    # printing Decimal valuesprint ("Decimal value a : ", a)print ("Decimal value b : ", b)    # Using Decimal.quantize() methodprint ("\n\nDecimal a with quantize() method : ", a.quantize(b))  print ("Decimal b with quantize() method : ", b.quantize(b))
Output :
Decimal value a :  -3.14
Decimal value b :  3.21E+7


Decimal a with quantize() method :  -0E+5
Decimal b with quantize() method :  3.21E+7


Python-Functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between cout and puts() in C++ with Examples

08 Jul, 2020
Standard Output Stream(cout): The C++ cout statement is the instance of the ostream class. It is used to display output on the standard output device which is usually the display screen. The data needed to be displayed on the screen is inserted in the standard output stream (cout) using the insertion operator(<<). For more details prefer to this article.
puts(): It can be used for printing a string. It is generally less expensive, and if the string has formatting characters like ‘%’, then printf() would give unexpected results. If string str is a user input string, then use of printf() might cause security issues. For more details prefer to this article.
Differences are:
Program 1:
C++
// C++ program use of puts#include <iostream>#include <stdio.h>using namespace std;  // main codeint main(){    puts("Geeksforgeeks");    fflush(stdout);    return 0;}
Geeksforgeeks

Program 2: Below program do not require fflush to flush the output buffer, because cout has it inbuilt.
C++
// C++ program use of cout#include <iostream>using namespace std;  // main codeint main(){    cout << "Geeksforgeeks" << endl;      return 0;}
Geeksforgeeks

CPP-Functions
C++
C++ Programs
Difference Between
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sorting a vector in C++
Polymorphism in C++
Friend class and function in C++
std::string class in C++
Pair in C++ Standard Template Library (STL)
Header files in C/C++ and its uses
Sorting a Map by value in C++ STL
Program to print ASCII Value of a character
How to return multiple values from a function in C or C++?
Shallow Copy and Deep Copy in C++
Python | Send SMS using Twilio

18 Apr, 2019
As we know Python is a cool scripting language and can be used to write scripts to easify day-to-day task. Also, since python has large community support and lots of module/API available, it makes Python more versatile and popular among users.
In this article, we will see how to use Twilio API to send SMS using Python. It will be a very quick and easy guide to doing this very interesting task.
Firstly, we need to create an account in Twilio’s official website to get the id and token. This is a paid service, but you will be credited with an initial amount to get you started.
Steps to create Twilio account:
Head to Twilio’s registration page. Complete the registration by filling in with the required details.
From the console(dashboard), copy the ACCOUNT SID and AUTH TOKEN.
Install Twilio library using pip.
pip install twilio
 Below is the Python implementation:
# importing twiliofrom twilio.rest import Client  # Your Account Sid and Auth Token from twilio.com / consoleaccount_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'auth_token = 'your_auth_token'  client = Client(account_sid, auth_token)  ''' Change the value of 'from' with the number received from Twilio and the value of 'to'with the number in which you want to send message.'''message = client.messages.create(                              from_='+15017122661',                              body ='body',                              to ='+15558675310'                          )  print(message.sid)
In the above code, just replace the values of account_sid and auth_token with the values you receive from Twilio. Also, replace the body with the message which you want to send and bingo!
Exercise:Extract emails from your account and forward the subject and receivers mail address as a text message to your mobile phone. You can even filter it by limiting it to forward only important mails.
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to download and install Python Latest Version on macOS / Mac OS X

24 Oct, 2019
Python is a widely-used general-purpose, high-level programming language. This article will serve as a complete tutorial on How to download and install Python latest version on macOS / Mac OS X. Like Linux, macOS also comes with Python pre-installed on the system. It might be Python version 2 or some similar outdated version. To update to the latest version, we will use the Homebrew Package manager. It is one of the best and convenient methods to install Python on macOS.To know more about Homebrew Package manager, visit here.
Download and install Homebrew Package ManagerIf you don’t have homebrew installed on your system, follow the steps belowOpen the Terminal Application of macOS from Application -> Utilities. Bash terminal will open where you can enter commandsEnter following command in macOS terminal/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
Enter system password if prompted. This will install the Homebrew package Manager on your OS.After you see a message called “Installation Successful”. You are ready to install python version 3 on your macOS.
If you don’t have homebrew installed on your system, follow the steps belowOpen the Terminal Application of macOS from Application -> Utilities. Bash terminal will open where you can enter commandsEnter following command in macOS terminal
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

Enter system password if prompted. This will install the Homebrew package Manager on your OS.After you see a message called “Installation Successful”. You are ready to install python version 3 on your macOS.
Install Python Latest Version on macOS / macOS XTo install python simple open Terminal app from Application -> Utilitiesand enter following commandbrew install python3After command processing is complete, Python’s version 3 would be installed on your mac.To verify the installation enter following commands in your Terminal apppythonpip3Bingo..!! Python is installed on your computer. You can explore more about python here
To install python simple open Terminal app from Application -> Utilitiesand enter following command
brew install python3
After command processing is complete, Python’s version 3 would be installed on your mac.
To verify the installation enter following commands in your Terminal app
python
pip3
Bingo..!! Python is installed on your computer. You can explore more about python here
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to find specific words in an array with JavaScript?

To find specific words in an array, you can use includes(). We have the following array −
var sentence = ["My Name is John Smith. My Favourite Subject is JavaScript. I live in US. I like Hockey"];
Now, the following is an array having the words we need to search in the above “sentence” array −
var keywords = ["John", "AUS", "JavaScript", "Hockey"];
Following is the code −
var keywords = ["John", "AUS", "JavaScript", "Hockey"];
var sentence = ["My Name is John Smith. My Favourite Subject is JavaScript. I live in US. I like Hockey"];
const matched = [];
for (var index = 0; index < sentence.length; index++) {
   for (var outerIndex = 0; outerIndex < keywords.length; outerIndex++) {
      if (sentence[index].includes(keywords[outerIndex])) {
         matched.push(keywords[outerIndex]);
      }
   }
}
console.log("The matched keywords are==");
console.log(matched);
To run the above program, you need to use the following command −
node fileName.js.
Here, my file name is demo226.js.
The output is as follows −
PS C:\Users\Amit\JavaScript-code> node demo226.js
The matched keywords are==
[ 'John', 'JavaScript', 'Hockey' ]
How to remove blank (undefined) elements from JavaScript array - JavaScript

Suppose we have an array of literals like this −
const arr = [4, 6, , 45, 3, 345, , 56, 6];
We are required to write a JavaScript function that takes in one such array and remove all the undefined elements from the array in place. We are only required to remove the undefined and empty values and not all the falsy values.
Use a for loop to iterate over the array and Array.prototype.splice() to remove undefined elements in place.
Following is the code −
const arr = [4, 6, , 45, 3, 345, , 56, 6]
const eliminateUndefined = arr => {
   for(let i = 0; i < arr.length; ){
      if(typeof arr[i] !== 'undefined'){
         i++;
         continue;
      };
      arr.splice(i, 1);
   };
};
eliminateUndefined(arr);
console.log(arr);
This will produce the following output in console −
[
   4,  6, 45, 3,
 345, 56,  6
]
C++ Program to Check the Connectivity of Undirected Graph Using DFS

To check connectivity of a graph, we will try to traverse all nodes using any traversal algorithm. After completing the traversal, if there is any node, which is not visited, then the graph is not connected.
For the undirected graph, we will select one node and traverse from it.
In this case the traversal algorithm is recursive DFS traversal.
Input − Adjacency matrix of a graph
Output − The Graph is connected.
Input − The start node u and the visited node to mark which node is visited.
Output: Traverse all connected vertices.
Begin
   mark u as visited
   for all vertex v, if it is adjacent with u, do
      if v is not visited, then
         traverse(v, visited)
   done
End
Input − The graph.
Output − True if the graph is connected.
Begin
   define visited array
      for all vertices u in the graph, do
         make all nodes unvisited
         traverse(u, visited)
         if any unvisited node is still remaining, then
            return false
      done
   return true
End
 Live Demo
#include<iostream>
#define NODE 5
using namespace std;
int graph[NODE][NODE] = {{0, 1, 1, 0, 0},
{1, 0, 1, 1, 0},
{1, 1, 0, 1, 1},
{0, 1, 1, 0, 1},
{0, 0, 1, 1, 0}};
void traverse(int u, bool visited[]) {
   visited[u] = true; //mark v as visited
   for(int v = 0; v<NODE; v++) {
      if(graph[u][v]) {
         if(!visited[v])
            traverse(v, visited);
      }
   }
}
bool isConnected() {
   bool *vis = new bool[NODE];
   //for all vertex u as start point, check whether all nodes are visible or not
   for(int u; u < NODE; u++) {
      for(int i = 0; i<NODE; i++)
         vis[i] = false; //initialize as no node is visited
         traverse(u, vis);
      for(int i = 0; i<NODE; i++) {
         if(!vis[i]) //if there is a node, not visited by traversal, graph is not connected
            return false;
      }
   }
   return true;
}
int main() {
   if(isConnected())
      cout << "The Graph is connected.";
   else
      cout << "The Graph is not connected.";
}
The Graph is connected.
How to Display Data from CSV file using PHP ? - GeeksforGeeks

14 Dec, 2020
We have given the data in CSV file format and the task is to display the CSV file data into the web browser using PHP. To display the data from CSV file to web browser, we will use fgetcsv() function.
Comma Separated Value (CSV) is a text file containing data contents. It is a comma-separated value file with .csv extension, which allows data to be saved in a tabular format.
fgetcsv() Function: The fgetcsv() function is used to parse a line from an open file, checking for CSV fields.
Execution Steps:
Open XAMPP server and start apache service
Open notepad and type the PHP code and save it as code.php
Store the CSV file in the same folder. Like xampp/htdocs/gfg/a.csv
Go to browser and type http://localhost/gfg/code.php. 
 
Filename: code.php
PHP
<!DOCTYPE html><html>  <body>    <center>        <h1>DISPLAY DATA PRESENT IN CSV</h1>        <h3>Student data</h3>          <?php        echo "<html><body><center><table>\n\n";          // Open a file        $file = fopen("a.csv", "r");          // Fetching data from csv file row by row        while (($data = fgetcsv($file)) !== false) {              // HTML tag for placing in row format            echo "<tr>";            foreach ($data as $i) {                echo "<td>" . htmlspecialchars($i)                     . "</td>";            }            echo "</tr> \n";        }          // Closing the file        fclose($file);          echo "\n</table></center></body></html>";        ?>    </center></body>  </html>
Output:
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
HTML-Misc
PHP-Misc
HTML
PHP
PHP Programs
Web Technologies
Web technologies Questions
HTML
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to update Node.js and NPM to next version ?
Types of CSS (Cascading Style Sheet)
How to Insert Form Data into Database using PHP ?
CSS to put icon inside an input element in a form
REST API (Introduction)
How to Insert Form Data into Database using PHP ?
How to execute PHP code using command line ?
How to pop an alert message box using PHP ?
How to convert array to string in PHP ?
How to Upload Image into Database and Display it using PHP ?
Encryption of Transposition Cipher

In the previous chapter, we have learnt about Transposition Cipher. In this chapter, let us discuss its encryption.
The main usage of pyperclip plugin in Python programming language is to perform cross platform module for copying and pasting text to the clipboard. You can install python pyperclip module using the command as shown
pip install pyperclip

If the requirement already exists in the system, you can see the following output −
The python code for encrypting transposition cipher in which pyperclip is the main module is as shown below −
import pyperclip
def main():
   myMessage = 'Transposition Cipher'
   myKey = 10
   ciphertext = encryptMessage(myKey, myMessage)
   
   print("Cipher Text is")
   print(ciphertext + '|')
   pyperclip.copy(ciphertext)

def encryptMessage(key, message):
   ciphertext = [''] * key
   
   for col in range(key):
      position = col
      while position < len(message):
         ciphertext[col] += message[position]
			position += key
      return ''.join(ciphertext) #Cipher text
if __name__ == '__main__':
   main()
The program code for encrypting transposition cipher in which pyperclip is the main module gives the following output −
The function main() calls the encryptMessage() which includes the procedure for splitting the characters using len function and iterating them in a columnar format.
The function main() calls the encryptMessage() which includes the procedure for splitting the characters using len function and iterating them in a columnar format.
The main function is initialized at the end to get the appropriate output.
The main function is initialized at the end to get the appropriate output.

    10 Lectures 
     2 hours 

 Total Seminars

    10 Lectures 
     2 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
Stack.GetEnumerator Method in C#

04 Feb, 2019
This method returns an IEnumerator that iterates through the Stack. And it comes under the System.Collections namespace.
Syntax:
public virtual System.Collections.IEnumerator GetEnumerator ();
Below programs illustrate the use of above-discussed method:
Example 1:
// C# program to illustrate the// Stack.GetEnumerator 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");          // To get an Enumerator        // for the Stack        IEnumerator enumerator = myStack.GetEnumerator();          // If MoveNext passes the end of the        // collection, the enumerator is positioned        // after the last element in the Stack        // and MoveNext returns false.        while (enumerator.MoveNext()) {              Console.WriteLine(enumerator.Current);        }    }}
GeeksforGeeks
Data Structures
Noida
Geeks Classes
Geeks

Example 2:
// C# code to illustrate the// Stack.GetEnumerator 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(2);        myStack.Push(3);        myStack.Push(4);        myStack.Push(5);        myStack.Push(6);          // To get an Enumerator        // for the Stack        IEnumerator enumerator = myStack.GetEnumerator();          // If MoveNext passes the end of the        // collection, the enumerator is positioned        // after the last element in the Stack        // and MoveNext returns false.        while (enumerator.MoveNext()) {              Console.WriteLine(enumerator.Current);        }    }}
6
5
4
3
2

Note:
The foreach statement of the C# language hides the complexity of the enumerators. Therefore, using foreach is recommended, instead of directly manipulating the enumerator.
Enumerators can be used to read the data in the collection, but they cannot be used to modify the underlying collection.
Current returns the same object until either MoveNext or Reset is called. MoveNext sets Current to the next element.
An enumerator remains valid as long as the collection remains unchanged. If changes are made to the collection, such as adding, modifying, or deleting elements, the enumerator is irrecoverably invalidated and its behavior is undefined.
This method is an O(1) operation.
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.collections.stack.getenumerator?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 Pass Arguments to Tkinter Button Command?

11 Aug, 2021
Tkinter is the standard GUI library for Python. Tkinter is the Python interface to the Tk GUI toolkit shipped with Python. It provides a robust and platform independent windowing toolkit, that is available to Python programmers using this package. Python when combined with Tkinter provides a fast and easy way to create GUI applications. Tkinter provides a powerful object-oriented interface to the Tk GUI toolkit.
Import tkinter package.
Create a root window. Give the root window a title(using title()) and dimension(using geometry()).
Create a button using (Button()).
Use mainloop() to call the endless loop of the window.
These steps remain same for both methods, only thing that has to be changed is how to apply these two methods.
Method 1: Using lambda function
Python3
# importing tkinterimport tkinter as tk # defining function  def func(args):    print(args)  # create root windowroot = tk.Tk() # root window title and dimensionroot.title("Welcome to GeekForGeeks")root.geometry("380x400") # creating buttonbtn = tk.Button(root, text="Press", command=lambda: func("See this worked!"))btn.pack() # running the main looproot.mainloop()
Output:
using lambda
Method 2: Using partial 
Python3
# importing necessary librariesfrom functools import partialimport tkinter as tk # defining function  def function_name(func):    print(func)  # creating root windowroot = tk.Tk() # root window title and dimensionroot.title("Welcome to GeekForGeeks")root.geometry("380x400") # creating buttonbtn = tk.Button(root, text="Click Me", command=partial(    function_name, "Thanks, Geeks for Geeks !!!"))btn.pack() # running the main looproot.mainloop()
Output:
using partial
adnanirshad158
Python-tkinter
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
numpy.indices() function – Python

11 Jun, 2020
numpy.indices() function return an array representing the indices of a grid. Compute an array where the subarrays contain index values 0, 1, ... varying only along the corresponding axis.
Syntax : numpy.indices(dimensions, dtype, sparse = False)
Parameters :dimensions : [sequence of ints] The shape of the grid.dtype: [dtype, optional] Data type of the result.sparse: [boolean, optional] Return a sparse representation of the grid instead of a dense representation. Default is False.
Return : [ndarray or tuple of ndarrays]If sparse is False:Returns one array of grid indices, grid.shape = (len(dimensions), ) + tuple(dimensions).
If sparse is True:Returns a tuple of arrays, with grid[i].shape = (1, ..., 1, dimensions[i], 1, ..., 1) with dimensions[i] in the ith place
Code #1 :
# Python program explaining# numpy.indices() function       # importing numpy as geek import numpy as geek    gfg = geek.indices((2, 3))  print (gfg)
Output :
[[[0 0 0]
  [1 1 1]]

 [[0 1 2]
  [0 1 2]]]

 Code #2 :
# Python program explaining# numpy.indices() function       # importing numpy as geek import numpy as geek    grid = geek.indices((2, 3))gfg = grid[1]  print (gfg)
Output :
[[0 1 2]
 [0 1 2]]

Python numpy-ndarray
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Java and multiple inheritance

Java does not support multiple inheritance. This means that a class cannot extend more than one class. Therefore, following is illegal
public class extends Animal, Mammal{}
However, a class can implement one or more interfaces, which has helped Java get rid of the impossibility of multiple inheritance. The extends keyword is used once, and the parent interfaces are declared in a comma-separated list. For example, if the Hockey interface extended both Sports and Event, it would be declared as −
public interface Hockey extends Sports, Event
Following example demonstrates the running example.
 Live Demo
interface Event {
   public void start();
}
interface Sports {
   public void play();
}
interface Hockey extends Sports, Event{
   public void show();
}
public class Tester{
   public static void main(String[] args){
      Hockey hockey = new Hockey() {
         public void start() {
            System.out.println("Start Event");
         }
         public void play() {
            System.out.println("Play Sports.");
         }
         public void show() {
            System.out.println("Show Hockey.");
         }
      };

      hockey.start();
      hockey.play();
      hockey.show();
   }
}
Start Event
Play Sports.
Show Hockey.
Missing number in matrix | Practice | GeeksforGeeks

Given a matrix of size n x n such that it has only one 0, Find the number to be placed in place of the 0 such that sum of the numbers in every row, column and two diagonals become equal. 
Note: Diagonals should be only of the form matrix[i][i] and matrix[i][n - i - 1].
 
Example 1:
Input: matrix = {{5, 5}, {5, 0}}
Output: 5
Explanation: The matrix is
5 5
5 0
Therefore If we place 5 instead of 0, all
the element of matrix will become 5. 
Therefore row 5+5=10, column 5+5=10 and 
diagonal 5+5=10, all are equal.
Example 2:
Input: matrix = {{1, 2, 0}, {3, 1, 2}, 
{2, 3, 1}}
Output: -1
Explanation: It is not possible to insert 
an element in place of 0 so that the 
condition is satisfied.thus result is -1. 


Your Task:
You don't need to read or print anyhting. Your task is to complete the function MissingNo() which takes the matrix as input parameter and returns the number which should be placed in place of 0 such that the condition gets satisfied. If not possible return -1.
 
Expected Time Complexity: O(n * n)
Expected Space Complexity: O(2 * n)
 
Constraints:
1 <= n <= 100
1 <= elements in the matrix <= 109
-1
tolstoyl7 months ago
The first test case where your code
failed:Input:
2 
0 1 
2 1Its Correct output is:
2And Your Code's output is:
-1
This is obviously wrong, it is enough to take the sum of the first column to see it.
0
VENKTESH KUMAR1 year ago
VENKTESH KUMAR
very nice question it took 1 hr to solve the problem
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
Get the top most document from a MongoDB collection

To get the topmost document, use find() along with limit(). To fetch only a single document, consider using limit(1). Let us create a collection with documents −
> db.demo681.insertOne({_id:101,Name:"Chris"});
{ "acknowledged" : true, "insertedId" : 101 }
> db.demo681.insertOne({_id:102,Name:"Bob"});
{ "acknowledged" : true, "insertedId" : 102 }
> db.demo681.insertOne({_id:103,Name:"David"});
{ "acknowledged" : true, "insertedId" : 103 }
> db.demo681.insertOne({_id:104,Name:"Bob"});
{ "acknowledged" : true, "insertedId" : 104 }
> db.demo681.insertOne({_id:105,Name:"Sam"});
{ "acknowledged" : true, "insertedId" : 105 }
Display all documents from a collection with the help of find() method −
> db.demo681.find();
This will produce the following output −
{ "_id" : 101, "Name" : "Chris" }
{ "_id" : 102, "Name" : "Bob" }
{ "_id" : 103, "Name" : "David" }
{ "_id" : 104, "Name" : "Bob" }
{ "_id" : 105, "Name" : "Sam" }
Following is the query to get the topmost element −
> db.demo681.find().limit(1);
This will produce the following output −
{ "_id" : 101, "Name" : "Chris" }
Collect.js partition() Method - GeeksforGeeks

30 Nov, 2020
The partition() method is used to separate the collection elements according to the given callback function. The first array containing those elements that satisfy the predicate (condition) and the second array contains the remaining elements.
Syntax:
collect(array).partition(callback)
Parameters: The collect() method takes one argument that is converted into the collection and then the partition() method is applied to it. The partition() method holds the callback function as a parameter.
Return Value: This method returns the collection elements with partition.
Module Installation: Install collect.js module using the following command from the root directory of your project:
npm install collect.js
The below example illustrates the partition() method in collect.js:
Example 1: Filename: index.js
Javascript
// Requiring the moduleconst collect = require('collect.js');  // Creating collection objectconst collection = collect([1, 2, 3,     5, 6, 8, 9, 11, 17, 22]);  // Calling partition function on collectionconst [odd, even] = collection.partition(    element => element % 2 != 0);  // Printing the odd & even valuesconsole.log(odd.all());console.log(even.all());
Run the index.js file using the following command:
node index.js
Output:
[ 2, 6, 8, 22 ]
[ 1, 3, 5, 9, 11, 17 ]
Example 2: Filename: index.js
Javascript
// Requiring the moduleconst collect = require('collect.js');  // Creating collection objectconst collection = collect(['Welcome',     'Geeks', 'GFG', 'GeeksforGeeks']);  // Calling partition function on // collection objectconst [short, long] = collection.partition(    element => element.length < 6);  // Printing short valuesconsole.log(short.all());  // Printing long valuesconsole.log(long.all());
Run the index.js file using the following command:
node index.js
Output:
[ 'Geeks', 'GFG' ]
[ 'Welcome', 'GeeksforGeeks' ]
Collect.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
Difference Between PUT and PATCH Request
How to get character array from string in JavaScript?
How to remove duplicate elements from JavaScript Array ?
How to get selected value in dropdown list 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?
C++ Program to compare two string using pointers - GeeksforGeeks

04 Nov, 2018
Given two strings, compare the strings using pointers
Examples:
Input: str1 = geeks, str2 = geeks
Output: Both are equal

Input: str1 = hello, str2 = hellu
Output: Both are not equal
As their length are same but characters are different
The idea is to dereference given pointers, compare values and advance both of them.
Program:
// C++ Program to compare two strings using// Pointers#include <iostream>using namespace std;    // Method to compare two string// using pointerbool compare(char *str1, char *str2){    while (*str1 == *str2)    {        if (*str1 == '\0' && *str2 == '\0')            return true;        str1++;        str2++;    }            return false;}  int main(){    // Declare and Initialize two strings    char str1[] = "geeks";    char str2[] = "geeks";      if (compare(str1, str2) == 1)        cout << str1 << " " << str2 << " are Equal";    else        cout << str1 << " " << str2 << " are not Equal";}
geeks geeks are Equal

cpp-pointer
cpp-string
C++ Programs
Strings
Technical Scripter
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Passing a function as a parameter in C++
Const keyword in C++
Program to implement Singly Linked List in C++ using class
cout in C++
Handling the Divide by Zero Exception in C++
Reverse a string in Java
Write a program to reverse an array or string
Longest Common Subsequence | DP-4
C++ Data Types
Write a program to print all permutations of a given string