code-rag-bench/online-tutorials huggingface dataset:
AngularJS | angular.isDate() Function - GeeksforGeeks

12 Apr, 2019
The angular.isDate() function in AngularJS is used to determine the value of date is valid or not. It returns true if the reference is a date else false.
Syntax:
angular.isDate( value )
Parameters: This function accepts single parameter value which stores the date object.
Return Value: It returns true if the value passed is date else return false.
Example: This example uses angular.isDate() function to determine the value of date is valid or not.
<!DOCTYPE html><html>  <head>    <title>angular.isDate() function</title>          <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js">    </script></head>  <body ng-app="app" style="text-align:center">    <h1 style="color:green">GeeksforGeeks</h1>    <h2>angular.isDate()</h2>          <div ng-controller="geek">        <b>Date:</b> {{ date }} <br><br>            isDate: {{isDate}}     </div>          <!-- Script to uses angular.isDate() function -->    <script>        var app = angular.module("app", []);        app.controller('geek', ['$scope', function ($scope) {            $scope.date = new Date;            $scope.isDate = angular.isDate($scope.date)        }]);    </script></body>  </html>                    
Output:
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Angular File Upload
Top 10 Angular Libraries For Web Developers
Angular | keyup event
Auth Guards in Angular 9/10/11
What is AOT and JIT Compiler in Angular ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to disable right click using jQuery?

To disable right click on a page, use the jQuery bind() method.
You can try to run the following code to learn how to disable right click:
Live Demo
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
   $(document).bind("contextmenu",function(e){
      return false;
   });
});
</script>
</head>
<body>

<p>Right click is disabled on this page.</p>

</body>
</html>
Unidirectional Channel in Golang - GeeksforGeeks

18 May, 2020
As we know that a channel is a medium of communication between concurrently running goroutines so that they can send and receive data to each other. By default a channel is bidirectional but you can create a unidirectional channel also. A channel that can only receive data or a channel that can only send data is the unidirectional channel. The unidirectional channel can also create with the help of make() function as shown below:
// Only to receive data
c1:= make(<- chan bool)

// Only to send data
c2:= make(chan<-bool

Example 1:
// Go program to illustrate the concept// of the unidirectional channelpackage main  import "fmt"  // Main functionfunc main() {      // Only for receiving    mychanl1 := make(<-chan string)      // Only for sending    mychanl2 := make(chan<- string)      // Display the types of channels    fmt.Printf("%T", mychanl1)    fmt.Printf("\n%T", mychanl2)}
Output:
<-chan string
chan<- string

In Go language, you are allowed to convert a bidirectional channel into the unidirectional channel, or in other words, you can convert a bidirectional channel into a receive-only or send-only channel, but vice versa is not possible. As shown in the below program:
Example:
// Go program to illustrate how to convert// bidirectional channel into the// unidirectional channelpackage main  import "fmt"  func sending(s chan<- string) {    s <- "GeeksforGeeks"}  func main() {      // Creating a bidirectional channel    mychanl := make(chan string)      // Here, sending() function convert    // the bidirectional channel    // into send only channel    go sending(mychanl)      // Here, the channel is sent     // only inside the goroutine    // outside the goroutine the     // channel is bidirectional    // So, it print GeeksforGeeks    fmt.Println(<-mychanl)}
Output:
GeeksforGeeks
Use of Unidirectional Channel: The unidirectional channel is used to provide the type-safety of the program so, that the program gives less error. Or you can also use a unidirectional channel when you want to create a channel that can only send or receive data.
amit bhaira
Golang
Golang-Concurrency
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Different ways to concatenate two strings in Golang
time.Sleep() Function in Golang With Examples
strings.Replace() Function in Golang With Examples
strings.Contains Function in Golang with Examples
Time Formatting in Golang
fmt.Sprintf() Function in Golang With Examples
Golang Maps
How to convert a string in lower case in Golang?
Different Ways to Find the Type of Variable in Golang
Inheritance in GoLang
Print All Link Name Using Selenium In Python - GeeksforGeeks

12 Nov, 2020
Selenium is a powerful tool for controlling web browsers through programs and performing browser automation. It is functional for all browsers, works on all major OS and its scripts are written in various languages i.e Python, Java, C#, etc, we will be working with Python.
Requirements:
You need to install chromedriver and set path. Click here to download.
Note: For more information follows this link.
Step-by-step Approach:
Import required modules
Taking any URL.
using By.TAG_NAME find web link on a webpage.
then use a loop for print link name.
Implementation:
Python3
#import modulefrom selenium import webdriverfrom selenium.webdriver.common.by import By    driver = webdriver.Chrome()  # urldriver.get('https://www.youtube.com/')  # find web linkslink = driver.find_elements(By.TAG_NAME, 'a')  # print name of all linksfor i in link:    print(i.text)
Output:
Python-selenium
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
How to Get the Size of a Table in MySQL using Python? - GeeksforGeeks

26 Dec, 2020
Prerequisite: Python: MySQL Create Table
In this article, we are going to see how to get the size of a table in MySQL using Python. Python allows the integration of a wide range of database servers with applications. A database interface is required to access a database from Python. MySQL Connector-Python module is an API in python for communicating with a MySQL database. 
Approach:
Import module.
Make a connection request with the database.
Create an object for the database cursor.
Execute the following MySQL query:
SELECT  table_name AS `Table`,  round(((data_length + index_length) / 1024 / 1024), 2) `Size in MB` FROM information_schema.TABLES WHERE table_schema = ‘DataBase_name’ AND table_name = ‘Table_name’;
Example 1:
In this example we are using this database table with the following query;
Below is the implementation:
Python3
# Import required moduleimport mysql.connector  # Establish connection# to MySQL databasemydb = mysql.connector.connect(    host="localhost",    user="root",    password="root123",    database="geeks")  # Create cursor objectmycursor = mydb.cursor()  # Execute queryquery = "SELECT  table_name AS `Table`, \        round(((data_length + index_length) \        / 1024 / 1024), 2) `Size in MB` \        FROM information_schema.TABLES \        WHERE table_schema = 'Geeks' AND \        table_name = 'Persons';"  mycursor.execute(query)  # Display size of each tablemyresult = mycursor.fetchall()  for item in myresult:    print(item[0], "Size in MB: ", item[-1])
Output:
Example 2:
In this example, we are going to get all table sizes in a database.
Below is the implementation:
Python3
# Import required moduleimport mysql.connector  # Establish connection# to MySQL databasemydb = mysql.connector.connect(    host="localhost",    user="root",    password="root123",    database="geeks")  # Create cursor objectmycursor = mydb.cursor()  # Execute queryquery = "SELECT  TABLE_NAME AS `Table`, \         ROUND(((DATA_LENGTH + INDEX_LENGTH) \         / 1024 / 1024),2) AS `Size (MB)` \         FROM information_schema.TABLES WHERE \         TABLE_SCHEMA = 'Geeks' ORDER BY \         (DATA_LENGTH + INDEX_LENGTH) DESC;"  mycursor.execute(query)  # Display size of each tablemyresult = mycursor.fetchall()  for item in myresult:    print(item[0], "Size in MB: ", item[-1])
Output:
Picked
Python-mySQL
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
Python - Check for Key in Dictionary Value list - GeeksforGeeks

01 Mar, 2020
Sometimes, while working with data, we might have a problem we receive a dictionary whole key has list of dictionaries as value. In this scenario, we might need to find if a particular key exists in that. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using any()This is simple and most recommended way in which this task can be performed. In this, we just check for the key inside the values by iteration.
# Python3 code to demonstrate working of # Check for Key in Dictionary Value list# Using any()    # initializing dictionary test_dict = {'Gfg' : [{'CS' : 5}, {'GATE' : 6}], 'for' : 2, 'CS' : 3}     # printing original dictionary print("The original dictionary is : " + str(test_dict))     # initializing keykey = "GATE"    # Check for Key in Dictionary Value list# Using any()res = any(key in ele for ele in test_dict['Gfg'])    # printing result  print("Is key present in nested dictionary list ?  : " + str(res)) 
The original dictionary is : {'Gfg': [{'CS': 5}, {'GATE': 6}], 'for': 2, 'CS': 3}
Is key present in nested dictionary list ?  : True

 
Method #2 : Using list comprehension + in operatorThe combination of above functionalities can be used to perform this task. In this, we iterate through the list using comprehension and perform key flattening and store keys. Then we check for desired key using in operator.
# Python3 code to demonstrate working of # Check for Key in Dictionary Value list# Using list comprehension + in operator    # initializing dictionary test_dict = {'Gfg' : [{'CS' : 5}, {'GATE' : 6}], 'for' : 2, 'CS' : 3}     # printing original dictionary print("The original dictionary is : " + str(test_dict))     # initializing keykey = "GATE"    # Check for Key in Dictionary Value list# Using list comprehension + in operatorres = key in [sub for ele in test_dict['Gfg'] for sub in ele.keys()]    # printing result  print("Is key present in nested dictionary list ?  : " + str(res)) 
The original dictionary is : {'Gfg': [{'CS': 5}, {'GATE': 6}], 'for': 2, 'CS': 3}
Is key present in nested dictionary list ?  : True

Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Defaultdict in Python
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
Operating Systems | CPU Scheduling | Question 1 - GeeksforGeeks

03 Oct, 2019
Consider three processes (process id 0, 1, 2 respectively) with compute time bursts 2, 4 and 8 time units. All processes arrive at time zero. Consider the longest remaining time first (LRTF) scheduling algorithm. In LRTF ties are broken by giving priority to the process with the lowest process id. The average turn around time is:(A) 13 units(B) 14 units(C) 15 units(D) 16 unitsAnswer: (A)Explanation: Let the processes be p0, p1 and p2. These processes will be executed in following order.
  p2  p1  p2  p1  p2  p0  p1   p2   p0   p1   p2
0   4   5   6   7   8   9   10    11   12   13   14 

Turn around time of a process is total time between submission of the process and its completion.Turn around time of p0 = 12 (12-0)Turn around time of p1 = 13 (13-0)Turn around time of p2 = 14 (14-0)
Average turn around time is (12+13+14)/3 = 13.Quiz of this Question
cpu-scheduling
Operating Systems-CPU Scheduling
Operating Systems
Operating Systems
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Memory Management in Operating System
File Allocation Methods
Logical and Physical Address in Operating System
Difference between Internal and External fragmentation
File Access Methods in Operating System
Memory Hierarchy Design and its Characteristics
File Systems in Operating System
Process Table and Process Control Block (PCB)
States of a Process in Operating Systems
Introduction of Process Management
What are boolean operators in Python?

The logical operators and, or and not are also referred to as boolean operators. While and as well as or operator needs two operands, which may evaluate to true or false, not operator needs one operand evaluating to true or false.
Boolean and operator returns true if both operands return true.
>>> a=50
>>> b=25
>>> a>40 and b>40
False
>>> a>100 and b<50
False
>>> a==0 and b==0
False
>>> a>0 and b>0
True
Boolean or operator returns true if any one operand is true
>>> a=50
>>> b=25
>>> a>40 or b>40
True
>>> a>100 or b<50
True
>>> a==0 or b==0
False
>>> a>0 or b>0
True
The not operator returns true if its operand is a false expression and returns false if it is true.
>>> a=10
>>> a>10
False
>>> not(a>10)
True
NPDA for accepting the language L = {an bn | n>=1}

03 Jun, 2022
Prerequisite – Pushdown automata, Pushdown automata acceptance by final state 
Problem – Design a non deterministic PDA for accepting the language L = {[Tex]b^n  [/Tex]| n>=1}, i.e.,
L = {ab, aabb, aaabbb, aaaabbbb, ......} 
In each of the string, the number of a’s are followed by equal number of b’s. 
Explanation – Here, we need to maintain the order of a’s and b’s. That is, all the a’s are coming first and then all the b’s are coming. Thus, we need a stack along with the state diagram. The count of a’s and b’s is maintained by the stack. We will take 2 stack alphabets:
 = { a, z }
Where, = set of all the stack alphabet z = stack start symbol 
Approach used in the construction of PDA – As we want to design a NPDA, thus every time ‘a’ comes before ‘b’. When ‘a’ comes then push it in stack and if again ‘a’ comes then also push it. After that, when ‘b’ comes then pop one ‘a’ from the stack each time. So, at the end if the stack becomes empty then we can say that the string is accepted by the PDA. 
Stack transition functions –
(q0, a, z)  (q0, az)(q0, a, a)  (q0, aa)(q0, b, a)  (q1,  )(q1, b, a)  (q1,  )(q1, , z)  (qf, z)             
Where, q0 = Initial state qf = Final state = indicates pop operation  
So, this is our required non deterministic PDA for accepting the language L = {[Tex]b^n  [/Tex]: n>=1}.
simmytarika5
GATE CS
Theory of Computation & Automata
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Join two ArrayLists in Java

11 Dec, 2018
Given two ArrayLists in Java, the task is to join these ArrayLists.
Examples:
Input: ArrayList1: [Geeks, For, ForGeeks], ArrayList2: [GeeksForGeeks, A computer portal]Output: ArrayList: [Geeks, For, ForGeeks, GeeksForGeeks, A computer portal]
Input: ArrayList1: [G, e, e, k, s], ArrayList2: [F, o, r, G, e, e, k, s]Output: ArrayList: [G, e, e, k, s, F, o, r, G, e, e, k, s]
Approach: ArrayLists can be joined in Java with the help of Collection.addAll() method. This method is called by the destination ArrayList and the other ArrayList is passed as the parameter to this method. This method appends the second ArrayList to the end of the first ArrayList.
Syntax:
ArrayList1.addAll(ArrayList2);
Below is the implementation of the above approach:
// Java program to demonstrate// How to sort ArrayList in descending order  import java.util.*;  public class GFG {    public static void main(String args[])    {          // Get the ArrayList1        ArrayList<String>            list1 = new ArrayList<String>();          // Populate the ArrayList        list1.add("Geeks");        list1.add("For");        list1.add("ForGeeks");          // Print the ArrayList 1        System.out.println("ArrayList 1: "                           + list1);          // Get the ArrayList2        ArrayList<String>            list2 = new ArrayList<String>();          list2.add("GeeksForGeeks");        list2.add("A computer portal");          // Print the ArrayList 2        System.out.println("ArrayList 2: "                           + list2);          // Join the ArrayLists        // using Collection.addAll() method        list1.addAll(list2);          // Print the joined ArrayList        System.out.println("Joined ArrayLists: "                           + list1);    }}
Java - util package
Java-ArrayList
Java-Collections
Java-List-Programs
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Timer Objects in Python

28 Jun, 2017
Timer objects are used to represent actions that needs to be scheduled to run after a certain instant of time. These objects get scheduled to run on a separate thread that carries out the action. However, the interval that a timer is initialized with might not be the actual instant when the action was actually performed by the interpreter because it is the responsibility of the thread scheduler to actually schedule the thread corresponding to the timer object.
Timer is a sub class of Thread class defined in python. It is started by calling the start() function corresponding to the timer explicitly.
Creating a Timer object
Syntax:
threading.Timer(interval, function, args = None, kwargs = None) 
Create a timer that will run function with arguments args and keyword arguments kwargs, after interval seconds have passed. If args is None (the default) then an empty list will be used. If kwargs is None (the default) then an empty dict will be used.
# Program to demonstrate# timer objects in python  import threadingdef gfg():    print("GeeksforGeeks\n")  timer = threading.Timer(2.0, gfg)timer.start()print("Exit\n")
Output:
Exit
GeeksforGeeks
Explanation: The program above, schedules gfg() function to run after 5 seconds of interval since start() function call.
Cancelling a timer
Syntax:
timer.cancel()
Stop the timer, and cancel the execution of the timer’s action. This will only work if the timer is still in its waiting stage.
# Program to cancel the timerimport threading  def gfg():    print("GeeksforGeeks\n")  timer = threading.Timer(5.0, gfg)timer.start()print("Cancelling timer\n")timer.cancel()print("Exit\n")
Output:
Cancelling timer
Exit
This article is contributed by Mayank Kumar. 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.
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to select a value from a static dropdown in Selenium?

The various methods available under Select class in Selenium to select a
value from a static dropdown. They are as listed below −
selectByVisibleText(String args)This method is most commonly used in dropdowns. It is very simple to select an option in a dropdown and multiple selection box with this method. It takes a String parameter as argument and returns no values.Syntax −Select s = new Select(driver.findElement(By.id("<< id exp>>")));
s.selectByVisibleText("Selenium");
selectByVisibleText(String args)
This method is most commonly used in dropdowns. It is very simple to select an option in a dropdown and multiple selection box with this method. It takes a String parameter as argument and returns no values.
Syntax −
Select s = new Select(driver.findElement(By.id("<< id exp>>")));
s.selectByVisibleText("Selenium");
selectByIndex(String args)
selectByIndex(String args)
This method takes the index of the option to select in the dropdown. It takes an int parameter as argument and returns no values.
This method takes the index of the option to select in the dropdown. It takes an int parameter as argument and returns no values.
Syntax −Select s = new Select(driver.findElement(By.id("<< id exp>>")));
s.selectByIndex(1);
Syntax −
Select s = new Select(driver.findElement(By.id("<< id exp>>")));
s.selectByIndex(1);
selectByValue(String args)This method takes the value of the option to select in the dropdown. It takes a String parameter as argument and returns no values.Syntax −Select s = new Select(driver.findElement(By.id("<< id exp>>")));
s.selectByValue(“Testing”);
selectByValue(String args)
This method takes the value of the option to select in the dropdown. It takes a String parameter as argument and returns no values.
Syntax −
Select s = new Select(driver.findElement(By.id("<< id exp>>")));
s.selectByValue(“Testing”);
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import java.util.List;
import org.openqa.selenium.support.ui.Select;
public class SelectOptions{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String url = "https://www.tutorialspoint.com/tutor_connect/index.php"; driver.get(url);
      driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS);
      Select s = new Select(driver.findElement(By.xpath("//select[@name=’selType’]")));
      // select an option by value method
      s.selectByValue("name");
      Thread.sleep(1000);
      // select an option by index method
      s.selectByIndex(0);
      Thread.sleep(1000);
      // select an option by visible text method
      s.selectByVisibleText("By Subject");
      Thread.sleep(1000);
      driver.quit();
   }
}
Maximum Frequency Stack in C++

Suppose we want to implement one stack called FreqStack, Our FreqStack has two functions −
push(x), This will push an integer x onto the stack.
push(x), This will push an integer x onto the stack.
pop(), This will remove and returns the most frequent element in the stack. If there are more than one elements with same frequency, then the element closest to the top of the stack is removed and returned.
pop(), This will remove and returns the most frequent element in the stack. If there are more than one elements with same frequency, then the element closest to the top of the stack is removed and returned.
So, if the input is like push some elements like 7, 9, 7, 9, 6, 7, then perform the pop operations four times, then the output will be 7,9,7,6 respectively.
To solve this, we will follow these steps −
Define one map cnt
Define one map cnt
Define one map sts
Define one map sts
maxFreq := 0
maxFreq := 0
Define a function push(), this will take x,
Define a function push(), this will take x,
(increase cnt[x] by 1)
(increase cnt[x] by 1)
maxFreq := maximum of maxFreq and cnt[x]
maxFreq := maximum of maxFreq and cnt[x]
insert x into sts[cnt[x]]
insert x into sts[cnt[x]]
Define a function pop()
Define a function pop()
maxKey := maxFreq
maxKey := maxFreq
x := top element of sts[maxKey]
x := top element of sts[maxKey]
delete element from sts[maxKey]
delete element from sts[maxKey]
if size of sts[maxKey] is same as 0, then −delete maxKey from sts(decrease maxFreq by 1)
if size of sts[maxKey] is same as 0, then −
delete maxKey from sts
delete maxKey from sts
(decrease maxFreq by 1)
(decrease maxFreq by 1)
(decrease cnt[x] by 1)
(decrease cnt[x] by 1)
return x
return x
Let us see the following implementation to get better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
class FreqStack {
   public:
   unordered_map <int ,int > cnt;
   unordered_map <int, stack <int> >sts;
   int maxFreq = 0;
   FreqStack() {
      maxFreq = 0;
      cnt.clear();
      sts.clear();
   }
   void push(int x) {
      cnt[x]++;
      maxFreq = max(maxFreq, cnt[x]);
      sts[cnt[x]].push(x);
   }
   int pop() {
      int maxKey = maxFreq;
      int x = sts[maxKey].top();
      sts[maxKey].pop();
      if(sts[maxKey].size() == 0){
         sts.erase(maxKey);
         maxFreq--;
      }
      cnt[x]--;
      return x;
   }
};
main(){
   FreqStack ob;
   ob.push(7);
   ob.push(9);
   ob.push(7);
   ob.push(9);
   ob.push(6);
   ob.push(7);
   cout << (ob.pop()) << endl;
   cout << (ob.pop()) << endl;
   cout << (ob.pop()) << endl;
   cout << (ob.pop()) << endl;
}
push elements 7, 9, 7, 9, 6, 7, then call pop() four times.
7
9
7
6
Rexx - find

This method is used to search for the first occurrence of a string in another string.
find(string, phrase)

string − The string value that needs to be searched for.
string − The string value that needs to be searched for.
phrase − This is the value that needs to be searched for in the string.
phrase − This is the value that needs to be searched for in the string.
The method returns the word number of the first word of phrase in string.
/* Main program */ 
options arexx_bifs 
say find(' Hello World ','World') 
When we run the above program we will get the following result.
2

 Print
 Add Notes
 Bookmark this page
Playit

div#myBox {  background-color:yellow;  border: 1px solid red;  padding:0px;}
WebSockets - Closing a Connection

Close event marks the end of a communication between the server and the client. Closing a connection is possible with the help of onclose event. After marking the end of communication with the help of onclose event, no messages can be further transferred between the server and the client. Closing the event can occur due to poor connectivity as well.
The close() method stands for goodbye handshake. It terminates the connection and no data can be exchanged unless the connection opens again.
Similar to the previous example, we call the close() method when the user clicks on the second button.
var textView = document.getElementById("text-view");
var buttonStop = document.getElementById("stop-button");

buttonStop.onclick = function() {
   // Close the connection, if open.
   if (socket.readyState === WebSocket.OPEN) {
      socket.close();
   }
}
It is also possible to pass the code and reason parameters we mentioned earlier as shown below.
socket.close(1000, "Deliberate disconnection");

The following code gives a complete overview of how to close or disconnect a Web Socket connection −
<!DOCTYPE html>
<html>
   <meta charset = "utf-8" />
   <title>WebSocket Test</title>

   <script language = "javascript" type = "text/javascript">
      var wsUri = "ws://echo.websocket.org/";
      var output;
	
      function init() {
         output = document.getElementById("output");
         testWebSocket();
      }
	
      function testWebSocket() {
         websocket = new WebSocket(wsUri);
		
         websocket.onopen = function(evt) {
            onOpen(evt)
         };
		
         websocket.onclose = function(evt) {
            onClose(evt)
         };
		
         websocket.onmessage = function(evt) {
            onMessage(evt)
         };
		
         websocket.onerror = function(evt) {
            onError(evt)
         };
      }
	
      function onOpen(evt) {
         writeToScreen("CONNECTED");
         doSend("WebSocket rocks");
      }
	
      function onClose(evt) {
         writeToScreen("DISCONNECTED");
      }
	
      function onMessage(evt) {
         writeToScreen('<span style = "color: blue;">RESPONSE: ' + 
            evt.data+'</span>'); websocket.close();
      }
	
      function onError(evt) {
         writeToScreen('<span style = "color: red;">ERROR:</span> '
            + evt.data);
      } 
	
      function doSend(message) {
         writeToScreen("SENT: " + message); websocket.send(message);
      }
	
      function writeToScreen(message) {
         var pre = document.createElement("p"); 
         pre.style.wordWrap = "break-word"; 
         pre.innerHTML = message; 
         output.appendChild(pre);
      }
	
      window.addEventListener("load", init, false);
   </script>
	
   <h2>WebSocket Test</h2>
   <div id = "output"></div>
	
</html>
The output is as follows −
 Print
 Add Notes
 Bookmark this page
How to define methods in C#?

A method is a group of statements that together perform a task. Every C# program has at least one class with a method named Main.
When you define a method, you basically declare the elements of its structure. The syntax for defining a method in C# is as follows −
<Access Specifier> <Return Type> <Method Name>(Parameter List) {
   Method Body
}
Here,
Access Specifier − This determines the visibility of a variable or a method from another class.
Access Specifier − This determines the visibility of a variable or a method from another class.
Return type − A method may return a value. The return type is the data type of the value the method returns. If the method is not returning any values, then the return type is void.
Return type − A method may return a value. The return type is the data type of the value the method returns. If the method is not returning any values, then the return type is void.
Method name − Method name is a unique identifier and it is case sensitive. It cannot be same as any other identifier declared in the class.
Method name − Method name is a unique identifier and it is case sensitive. It cannot be same as any other identifier declared in the class.
Parameter list − Enclosed between parentheses, the parameters are used to pass and receive data from a method. The parameter list refers to the type, order, and number of the parameters of a method. Parameters are optional; that is, a method may contain no parameters.
Parameter list − Enclosed between parentheses, the parameters are used to pass and receive data from a method. The parameter list refers to the type, order, and number of the parameters of a method. Parameters are optional; that is, a method may contain no parameters.
Method body − This contains the set of instructions needed to complete the required activity.
Method body − This contains the set of instructions needed to complete the required activity.
The following is an example of methods showing how to find that a string has unique words or not. Here, we have created a C# method CheckUnique() −
 Live Demo
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

public class Demo {

   public bool CheckUnique(string str) {
      string one = "";
      string two = "";

      for (int i = 0; i < str.Length; i++) {
         one = str.Substring(i, 1);
         for (int j = 0; j < str.Length; j++) {
            two = str.Substring(j, 1);
            if ((one == two) && (i != j))
            return false;
         }
      }
      return true;
   }
   static void Main(string[] args) {
      Demo d = new Demo();
      bool b = d.CheckUnique("amit");
      Console.WriteLine(b);

      Console.ReadKey();
   }
}
True
Delete a node in a Doubly Linked List in C++

In this tutorial, we are going to learn how to delete a node in doubly linked list.
Let's see the steps to solve the problem.
Write struct with data, prev and next pointers.
Write struct with data, prev and next pointers.
Write a function to insert the node into the doubly linked list.
Write a function to insert the node into the doubly linked list.
Initialize the doubly linked list with dummy data.
Initialize the doubly linked list with dummy data.
Take a node to delete.
Take a node to delete.
Write a function to delete the node. Consider the following three cases while deleting the node.If the node is head node, then move the head to next node.If the node is middle node, then link the next node to the previous nodeIf the node is end node, then remove the previous node link.
Let's see the code.
Write a function to delete the node. Consider the following three cases while deleting the node.
If the node is head node, then move the head to next node.
If the node is head node, then move the head to next node.
If the node is middle node, then link the next node to the previous node
If the node is middle node, then link the next node to the previous node
If the node is end node, then remove the previous node link.
Let's see the code.
If the node is end node, then remove the previous node link.
Let's see the code.
 Live Demo
#include <bits/stdc++.h>
using namespace std;
struct Node {
   int data;
   Node *prev, *next;
};
void deleteNode(Node** head_ref, Node* del) {
   if (*head_ref == NULL || del == NULL) {
      return;
   }
   if (*head_ref == del) {
      *head_ref = del->next;
   }
   if (del->next != NULL) {
      del->next->prev = del->prev;
   }
   if (del->prev != NULL) {
      del->prev->next = del->next;
   }
   free(del);
   return;
}
void insertNode(Node** head_ref, int new_data) {
   Node* new_node = new Node();
   new_node->data = new_data;
   new_node->prev = NULL;
   new_node->next = (*head_ref);
   if ((*head_ref) != NULL) {
      (*head_ref)->prev = new_node;
   }
   (*head_ref) = new_node;
}
void printLinkedList(Node* node) {
   while (node != NULL) {
      cout << node->data << " -> ";
      node = node->next;
   }
}
int main() {
   Node* head = NULL;
   insertNode(&head, 1);
   insertNode(&head, 2);
   insertNode(&head, 3);
   insertNode(&head, 4);
   insertNode(&head, 5);
   cout << "Linked List before deletion:" << endl;
   printLinkedList(head);
   deleteNode(&head, head->next);
   cout << "\nLinked List after deletion:" << endl;
   printLinkedList(head);
   return 0;
}
If you execute the above program, then you will get the following result.
Linked List before deletion:
5 -> 4 -> 3 -> 2 -> 1 ->
Linked List after deletion:
5 -> 3 -> 2 -> 1 ->
If you have any queries in the tutorial, mention them in the comment section.
C# While Loop

Loops can execute a block of code as long as a specified condition is reached.
Loops are handy because they save time, reduce errors, and they make code more readable.
The while loop loops through a block of code as long as a specified condition is 
True:
while (condition) 
{
  // code block to be executed
}

In the example below, the code in the loop will run, over and over again, as long as 
a variable (i) is less than 5:
int i = 0;
while (i < 5) 
{
  Console.WriteLine(i);
  i++;
}


Try it Yourself »

Note: Do not forget to increase the variable used in the condition, otherwise 
the loop will never end!
The do/while loop is a variant of the while loop. This loop will 
execute the code block once, before checking if the condition is true, then it will
repeat the loop as long as the condition is true.
do 
{
  // code block to be executed
}
while (condition);

The example below uses a do/while loop. The loop will always be 
executed at least once, even if the condition is false, because the code block 
is executed before the condition is tested:
int i = 0;do 
{
  Console.WriteLine(i);
  i++;
}
while (i < 5);


Try it Yourself »

Do not forget to increase the variable used in the condition, otherwise 
the loop will never end!
Print i as long as i is less than 6.
int i = 1;
 (i  6) 
{
  Console.WriteLine(i); 
  ;
}

Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
How do I sort a two-dimensional array in C#

To sort a two-dimensional array in C#, in a nested for loop, add another for loop to check the following condition.
for (int k = 0; k < j; k++) {
   if (arr[i, k] > arr[i, k + 1]) {
      int myTemp = arr[i, k];
      arr[i, k] = arr[i, k + 1];
      arr[i, k + 1] = myTemp;
   }
}
Till the outer loop loops through, use the GetLength() method as shown below. This is done to sort the array.
for (int i = 0; i < arr.GetLength(0); i++) {
   for (int j = arr.GetLength(1) - 1; j > 0; j--) {
      for (int k = 0; k < j; k++) {
         if (arr[i, k] > arr[i, k + 1]) {
            int myTemp = arr[i, k];
            arr[i, k] = arr[i, k + 1];
            arr[i, k + 1] = myTemp;
         }
      }
   }
   Console.WriteLine();
}
C program to calculate sum of series using predefined function

The program to calculate the sum of the following expression
Sum=1-n^2/2!+n^4/4!-n^6/6!+n^8/8!-n^10/10!
User has to enter the value of n at runtime to calculate the sum of the series by using the predefined function power present in math.h library function.
It is explained below how to calculate sum of series using predefined function.
Refer an algorithm given below to calculate sum of series by using the predefined function.
Step 1 − Read the num value
Step 2 − Initialize fact = 1, sum = 1 and n =5
Step 3 − for i= 1 to n
   a. compute fact= fact*i
   b. if i %2 = 0
   c. then if i=2 or i=10 or i=6
   d. then sum+= -pow(num,i)/fact
   e. else sum+=pow(num,i)/fact
   4. print sum
Following is the C program to calculate sum of series by using the predefined function −
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main(){
   int i,n=5,num;
   long int fact=1;
   float sum=1;
   printf("Enter the n value:");
   scanf("%d", &num);
   for(i=1;i<=n;i++){
      fact=fact*i;
      if(i%2==0){
         if(i==2|i==10|i==6)
            sum+= -pow(num,i)/fact;
         else
         sum+=pow(num,i)/fact;
      }
   }
   printf("sum is %f", sum);
}
When the above program is executed, it produces the following result −
Enter the n value:10
sum is 367.666656
Create nested JSON object in PHP?

JSON structure can be created with the below code −
$json = json_encode(array(
   "client" => array(
      "build" => "1.0",
      "name" => "xxxx",
      "version" => "1.0"
   ),
   "protocolVersion" => 4,
   "data" => array(
      "distributorId" => "xxxx",
      "distributorPin" => "xxxx",
      "locale" => "en-US"
   )
));
#pragma Directive in C/C++

The preprocessor directive #pragma is used to provide the additional information to the compiler in C/C++ language. This is used by the compiler to provide some special features.
Here is the syntax of #pragma directive in C/C++ language,
#pragma token_name
The table of some of #pragma directives in C/C++ language is given as follows,
Here is an example of #pragma directive in C language,
#include<stdio.h>
int display();

#pragma startup display
#pragma exit display

int main() {
   printf("\nI am in main function");
   return 0;
}

int display() {
   printf("\nI am in display function");
   return 0;
}
C | Arrays | Question 14 - GeeksforGeeks

28 Jun, 2021
Which of the following is true about arrays in C.(A) For every type T, there can be an array of T.(B) For every type T except void and function type, there can be an array of T.(C) When an array is passed to a function, C compiler creates a copy of array.(D) 2D arrays are stored in column major formAnswer: (B)Explanation: In C, we cannot have an array of void type and function types.
For example, below program throws compiler error
int main()
{
    void arr[100];
}

But we can have array of void pointers and function pointers. The below program works fine.
int main()
{
    void *arr[100];
}

See examples of function pointers for details of array function pointers.
Quiz of this Question
Arrays
C-Arrays
C Language
C Quiz
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TCP Server-Client implementation in C
Exception Handling in C++
'this' pointer in C++
Multithreading in C
Arrow operator -> in C/C++ with Examples
Compiling a C program:- Behind the Scenes
Operator Precedence and Associativity in C
C | File Handling | Question 1
C | Arrays | Question 7
C | Misc | Question 7
How to make a new folder using askdirectory dialog in Tkinter?

To make a new folder using askdirectory dialog in Tkinter, we can take the following steps −
Import the required modules. filedialog module is required for askdirectory method. os module is required for makedirs method.
Import the required modules. filedialog module is required for askdirectory method. os module is required for makedirs method.
Create an instance of tkinter frame.
Create an instance of tkinter frame.
Set the size of the frame using win.geometry method.
Set the size of the frame using win.geometry method.
Define a user-defined method "create_subfolder". Inside the method, call filedialog.askdirectory to select a folder and save the path in a variable, source_path.
Define a user-defined method "create_subfolder". Inside the method, call filedialog.askdirectory to select a folder and save the path in a variable, source_path.
We can use askdirectory method of filedialog to open a directory. Save the path of the selected directory in a 'path' variable.
We can use askdirectory method of filedialog to open a directory. Save the path of the selected directory in a 'path' variable.
Then, use os.path.join and makedirs to create a sub-folder inside the parent directory.
Then, use os.path.join and makedirs to create a sub-folder inside the parent directory.
Create a button to call the create_subfolder method.
Create a button to call the create_subfolder method.
# Import the required libraries
from tkinter import *
from tkinter import ttk
from tkinter import filedialog
import os

# Create an instance of tkinter frame or window
win = Tk()

# Set the size of the window
win.geometry("700x350")

def create_subfolder():
   source_path = filedialog.askdirectory(title='Select the Parent Directory')
   path = os.path.join(source_path, 'Images')
   os.makedirs(path)

button1 = ttk.Button(win, text="Select a Folder", command=create_subfolder)

button1.pack(pady=5)

win.mainloop()
When we execute the above code, it will first show the following window −
Now, click the "Select a Folder" button to select a parent folder. It will automatically create a sub-folder called "Images" in the selected parent folder.
Counting number of words in text file using java


We can read words in a file using BufferedReader class of Java and splitting the read data based on space character. See the example below:
Consider the following text file in classpath.
This is Line 1
This is Line 2
This is Line 3
This is Line 4
This is Line 5
This is Line 6
This is Line 7
This is Line 8
This is Line 9
This is Line 10
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;

public class Tester {

   private static final String FILE_PATH = "data.txt";
   public static void main(String args[]) throws IOException {
      FileUtil fileUtil = new FileUtil(FILE_PATH);
      System.out.println("No. of words in file: " + fileUtil.getWordCount());
   }
}

class FileUtil {
   static BufferedReader reader = null;
   public FileUtil(String filePath) throws FileNotFoundException {
      File file = new File(filePath);
      FileInputStream fileStream = new FileInputStream(file);
      InputStreamReader input = new InputStreamReader(fileStream);
      reader = new BufferedReader(input);
   }

   public static int getWordCount() throws IOException {
      int wordCount = 0;
      String data;
      while((data = reader.readLine()) != null){

         // \\s+ regex for space delimiter
         String[] words = data.split("\\s+");
         wordCount += words.length;
      }
      return wordCount;
   }
}
This will produce the following result −
No. of words in file: 40
What is increment (++) operator in JavaScript?

The increment operator increases an integer value by one. Here’s an example where the value of a is incremented twice using the increment operator twice
Live Demo
<html>
   <body>
      <script>
         var a = 33;
         a = ++a;
         document.write("++a = ");
         result = ++a;
         document.write(result);
      </script>
   </body>
</html>
Maximum Length of a Concatenated String with Unique Characters in C++

Suppose we have an array of strings arr. The string s is a concatenation of a sub-sequence of arr which have unique characters. Find the maximum possible length of s. If the input is like [“cha”, “r”, “act”, “ers”], then the output will be 6, possible solutions are “chaers” and “acters”.
To solve this, we will follow these steps −
make one method called ok() and this will take strings s and t. This will act like below
make one map x
for i in range 0 to size of sincrease x[s[i]] by 1if x[s[i]] > 1, then return false
increase x[s[i]] by 1
if x[s[i]] > 1, then return false
for i in range 0 to size of tincrease x[t[i]] by 1if x[t[i]] > 1, then return false
increase x[t[i]] by 1
if x[t[i]] > 1, then return false
return true
the actual method will be look like below −
make an array of strings called v, and ans := 0, insert one empty string into v
for i in range 0 to size of arrn := size of vfor j in range 0 to n – 1if ok(v[j], arr[i]) is true, thent := v[j] + arr[i]insert t into vans := max of ans and size of t
n := size of v
for j in range 0 to n – 1if ok(v[j], arr[i]) is true, thent := v[j] + arr[i]insert t into vans := max of ans and size of t
if ok(v[j], arr[i]) is true, thent := v[j] + arr[i]insert t into vans := max of ans and size of t
t := v[j] + arr[i]
insert t into v
ans := max of ans and size of t
return ans
Let us see the following implementation to get better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   bool ok(string s, string t){
      map <char, int > x;
      for(int i = 0; i < s.size(); i++){
         x[s[i]]++;
         if(x[s[i]] >1)return false;
      }
      for(int i = 0; i < t.size(); i++){
         x[t[i]]++;
         if(x[t[i]]>1)return false;
      }
      return true;
   }
   int maxLength(vector<string>& arr) {
      vector <string> v;
      int ans = 0;
      v.push_back("");
      for(int i = 0; i < arr.size(); i++){
         int n = v.size();
         for(int j = 0; j < n; j++){
            if(ok(v[j],arr[i])){
               string t = v[j]+arr[i];
               v.push_back(t);
               ans = max(ans,(int)t.size());
            }
         }
      }
      return ans;
   }
};
main(){
   vector<string> v = {"cha","r","act","ers"};
   Solution ob;
   cout << (ob.maxLength(v));
}
["cha","r","act","ers"]
6
Get value from div with JavaScript resulting undefined?

Use document.getElementById().innerHTML for this. Following is the JavaScript code −
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<div class='getValueFromDiv' id='getValue' contenteditable="true" onkeyUp='display()'
style="color: red"></div>
<script>
   function display(){
      var storedValue = document.getElementById('getValue').innerHTML.value="This is the
      value";
      console.log("The value is==="+storedValue);
   }
</script>
</body>
</html>
To run the above program, save the file name anyName.html(index.html) and right click on the file and select the option open with live server in VS Code editor.
Following is the output. When you will click the mouse and place the arrow key, you will get the
following output.
The snapshot is as follows −