code-rag-bench/online-tutorials huggingface dataset:
Console.Read() Method in C#

28 Feb, 2019
Console.Read() Method is used to read the next character from the standard input stream. This method basically blocks its return when the user types some input characters. As soon as the user press ENTER key it terminates.
Syntax: public static int Read ();
Return Value: It returns the next character from the input stream, or a negative one (-1) if there are currently no more characters to be read.
Exception: This method will give IOException if an I/O error occurred.
Below programs illustrate the use of above-discussed method:
Example 1:
// C# program to illustrate the use// of Console.Read Methodusing System;  namespace GFG {  class Program {      static void Main(string[] args)    {                  int x;        Console.WriteLine("Enter your Character to get Decimal number");          // using the method        x = Console.Read();        Console.WriteLine(x);    }}}
Output:
Example 2:
// C# program to illustrate the use// of Console.Read Methodusing System;  namespace GFG {  class Program {      static void Main(string[] args)    {        // Write to console window.          int x;        Console.WriteLine("Enter your Character to get Decimal number");        x = Console.Read();        Console.WriteLine(x);          // Converting the decimal into character.        Console.WriteLine(Convert.ToChar(x));    }}}
Output:
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.console.read?view=netframework-4.7.2
CSharp-Console-Class
CSharp-method
Picked
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to .NET Framework
C# | Delegates
C# | Multiple inheritance using interfaces
Differences Between .NET Core and .NET Framework
C# | Data Types
C# | Constructors
C# | String.IndexOf( ) Method | Set - 1
C# | Class and Object
Extension Method in C#
Difference between Ref and Out keywords in C#
How to convert JSON Array to normal Java Array?

The get method of the JSONArray class returns the element at a particular index. Using this method, you can get the elements of the JSONArray object and populate the array with them.
import java.util.Arrays;
import org.json.JSONArray;

public class JsonToArray {
   public static void main(String args[]) throws Exception {
      String [] myArray = {"JavaFX", "HBase", "JOGL", "WebGL"};
      JSONArray jsArray = new JSONArray();
      for (int i = 0; i < myArray.length; i++) {
         jsArray.put(myArray[i]);
     }
     System.out.println(jsArray);
     String[] array = new String[myArray.length];
     for (int i = 0; i < myArray.length; i++) {
        array[i] = (String)jsArray.get(i);
     }
     System.out.println("Contents of the array :: "+Arrays.toString(array));
   }
}
["JavaFX","HBase","JOGL","WebGL"]
Contents of the array :: [JavaFX, HBase, JOGL, WebGL]
How to find the sum of squared values of an R data frame column?

To find the sum of squared values of an R data frame column, we can simply square the column with ^ sign and take the sum using sum function. For example, if we have a data frame called df that contains a column say V then the sum of squared values of V can be found by using the command sum(df$V^2).
Consider the below data frame −
 Live Demo
ID<-1:20
x<-rpois(20,5)
df1<-data.frame(ID,x)
df1
  ID  x
1  1  3
2  2  9
3  3  7
4  4  4
5  5  6
6  6  4
7  7  7
8  8  4
9  9  8
10 10 5
11 11 6
12 12 7
13 13 7
14 14 7
15 15 5
16 16 4
17 17 4
18 18 5
19 19 4
20 20 5
Finding the sum of squared values in column x of df1 −
sum(df1$x^2)
[1] 667
 Live Demo
S.No<-LETTERS[1:20]
y<-rnorm(20,5,1)
df2<-data.frame(S.No,y)
df2
   S.No y
1  A    4.398238
2  B    5.543076
3  C    3.089420
4  D    7.313162
5  E    6.389394
6  F    5.718104
7  G    4.999203
8  H    5.835729
9  I    5.078716
10 J    3.507107
11 K    5.712762
12 L    2.778876
13 M    4.379454
14 N    5.487530
15 O    6.192156
16 P    5.065865
17 Q    4.984204
18 R    4.925256
19 S    4.522911
20 T    4.957369
Finding the sum of squared values in column y of df2 −
sum(df2$y^2)
[1] 531.5479
break command in Linux with examples - GeeksforGeeks

15 May, 2019
break command is used to terminate the execution of for loop, while loop and until loop. It can also take one parameter i.e.[N]. Here n is the number of nested loops to break. The default number is 1.
Syntax:
break [n]

Example 1: Using break statement in for loop
Example 2: Using break statement in while loop
Example 3: Using break statement in until loop
break –help : It displays help information.
linux-command
Linux-Shell-Commands
Picked
Technical Scripter 2018
Linux-Unix
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
tar command in Linux with examples
curl command in Linux with Examples
UDP Server-Client implementation in C
Conditional Statements | Shell Script
Cat command in Linux with examples
Tail command in Linux with examples
touch command in Linux with Examples
Mutex lock for Linux Thread Synchronization
echo command in Linux with Examples
tee command in Linux with examples
How to create new Mongodb database using Node.js ? - GeeksforGeeks

20 Nov, 2020
mongodb module: This Module is used to performing CRUD(Create Read Update Read) Operations in MongoDb using Node.js. We cannot make a database only. We have to make a new Collection to see the database. The connect() method is used for connecting the MongoDb server with the Node.js project.
Please refer this link for connect() method.
Installing module:
npm install mongodb

Starting MongoDB server:
mongod --dbpath=data --bind_ip 127.0.0.1

Data is the directory name where server is located. 127.0.0.1 ip address where server will be running.
Data is the directory name where server is located. 
127.0.0.1 ip address where server will be running.
Project Structure:
Filename index.js
Javascript
const MongoClient = require('mongodb');  // server locationconst url = 'mongodb://localhost:27017';MongoClient.connect(url).then((client) => {      console.log('Database created');          // database name    const db = client.db("GFGNodejs");          // collection name    db.createCollection("GFGNEW");})
Output:
Mongodb Database:
Node.js-Misc
Technical Scripter 2020
MongoDB
Node.js
Technical Scripter
Web Technologies
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to connect MongoDB with ReactJS ?
MongoDB - limit() Method
MongoDB - FindOne() Method
Create user and add role in MongoDB
MongoDB updateOne() Method - db.Collection.updateOne()
Installation of Node.js on Linux
Node.js fs.readFileSync() Method
How to update Node.js and NPM to next version ?
Node.js fs.readFile() Method
Node.js fs.writeFile() Method
Python os.read() Method

Python method read() reads at most n bytes from file desciptor fd, return a string containing the bytes read. If the end of file referred to by fd has been reached, an empty string is returned.
Following is the syntax for read() method −
os.read(fd,n)

fd − This is the file descriptor of the file.
fd − This is the file descriptor of the file.
n − These are n bytes from file descriptor fd.
n − These are n bytes from file descriptor fd.
This method returns a string containing the bytes read.
The following example shows the usage of read() method.
# !/usr/bin/python

import os, sys
# Open a file
fd = os.open("f1.txt",os.O_RDWR)
	
# Reading text
ret = os.read(fd,12)
print ret

# Close opened file
os.close(fd)
print "Closed the file successfully!!"
Let us compile and run the above program, this will print the contents of file f1.txt −
This is test
Closed the file successfully!!


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
Python String lstrip() method - GeeksforGeeks

19 Aug, 2021
Python String lstrip() method returns a copy of the string with leading characters removed (based on the string argument passed). If no argument is passed, it removes leading spaces.
Syntax: 
string.lstrip(characters)
Parameters: 
characters [optional]: A set of characters to remove as leading characters.
Returns: 
Returns a copy of the string with leading characters stripped.
Python3
# Python3 program to demonstrate the use of  # lstrip() method using default parameter    # string which is to be stripped string = "   geeksforgeeks"    # Removes spaces from left. print(string.lstrip())
Output:
geeksforgeeks
Python3
# Python3 program to demonstrate the use of  # lstrip() method using optional parameters    # string which is to be stripped string = "++++x...y!!z* geeksforgeeks"  # Removes given set of characters from left. print(string.lstrip("+.!*xyz"))
Output: 
geeksforgeeks
Python3
# string which is to be stripped string = "geeks for geeks"  # Argument doesn't contain leading 'g' # So, no characters are removed print(string.lstrip('ge'))
Output: 
ks for geeks
There is a runtime error when we try to strip anything except a string. 
Python3
# Python3 program to demonstrate the use of # strip() method error   string = " geeks for geeks "list =[1, 2, 3]   # prints the error message print(list.lstrip())
Output: 
print(list.lstrip()) 
AttributeError: 'list' object has no attribute 'lstrip'
YangSu1
AmiyaRanjanRout
python-string
Python-string-functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python Dictionary
Taking input in Python
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
How to create a Dictionary in PowerShell?

To create a dictionary in the PowerShell we need to use the class Dictionary from the .Net namespace System.Collections.Generic. It has TKey and TValue. Its basic syntax is
Dictionary<TKey,TValue>
To learn more about this .Net namespace check the link below.
https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2?view=net-5.0
To create a dictionary we will first create the object for the dictionary object class with the datatypes. In the below example, we need to add the Country name and the country code. So we need String and Int.
$countrydata = New-Object System.Collections.Generic.Dictionary"[String,Int]"
Once we check the type of the $countrydata variable, it should be the dictionary. For example,
PS C:\> $Countrydata.GetType() | ft -AutoSize
IsPublic IsSerial Name         BaseType
-------- -------- ----         --------
True     True     Dictionary`2 System.Object
Let’s check which methods are available.
PS C:\> $Countrydata | Get-Member -MemberType Method | Select Name, Membertype
Name              MemberType
----              ----------
Add                   Method
Clear                 Method
Contains              Method
ContainsKey           Method
ContainsValue         Method
CopyTo                Method
EnsureCapacity        Method
Equals                Method
GetEnumerator         Method
GetHashCode           Method
GetObjectData         Method
GetType               Method
OnDeserialization     Method
Remove                Method
ToString              Method
TrimExcess            Method
TryAdd                Method
TryGetValue           Method
So we can use Add() method to insert the members.
PS C:\> $Countrydata.Add("India",91)
PS C:\> $Countrydata.Add("Algeria",213)
Once you check the value, its output should be in the Key-Value pair.
PS C:\> $Countrydata
Key     Value
---     -----
India      91
Algeria   213
Generally, PowerShell programmers don’t use the directory because of its uncommon syntax and tend to use the Hashtable because can be easily created.
GATE | GATE-CS-2015 (Set 1) | Question 21 - GeeksforGeeks

28 Jun, 2021
The output of the following C program is __________.
void f1 (int a, int b){  int c;  c=a; a=b; b=c;}void f2 (int *a, int *b){  int c;  c=*a; *a=*b;*b=c;}int main(){  int a=4, b=5, c=6;  f1(a, b);  f2(&b, &c);  printf (“%d”, c-a-b);  return 0;}
(A) -5(B) -4(C) 5(D) 3Answer: (A)Explanation: The function call to to f1(a, b) won’t have any effect as the values are passed by value.
The function call f2(&b, &c) swaps values of b and c. So b becomes 6 and c becomes 5. Value of c-a-b becomes 5-4-6 which is -5.Quiz of this Question
GATE-CS-2015 (Set 1)
GATE-GATE-CS-2015 (Set 1)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-IT-2004 | Question 71
GATE | GATE CS 2011 | Question 7
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2016 (Set 1) | Question 65
GATE | GATE-CS-2014-(Set-3) | Question 38
GATE | GATE CS 2018 | Question 37
GATE | GATE-IT-2004 | Question 83
GATE | GATE-CS-2016 (Set 1) | Question 63
GATE | GATE-CS-2007 | Question 64
GATE | GATE-CS-2014-(Set-2) | Question 65
How to Implement a Strategy Pattern using Enum in Java? - GeeksforGeeks

22 Feb, 2021
The strategy design pattern is intended to provide a way to choose from a variety of interchangeable strategies. Classic implementation includes an architecture to be implemented by each technique and offers a concrete implementation for execution. The method is chosen from an interface reference, and the execution method is called.
The classic implementation of the Strategy design pattern:
The strategy interface must be implemented by all strategies.
public interface Strategy {
  public void execute();
}
All strategies must implement the strategy interface two classes showing the implementation of the Strategy interface and created an execute method.
public class StrategyA implements Strategy {
 @Override
 public void execute(){
   System.out.print("Executing strategy A");
 }
}
public class StrategyB implements Strategy {
 @Override
 public void execute() {
   System.out.print("Executing strategy B");
 }
}
The main class will select the strategy and execute the execute method of the strategy we chose.
public class GFG {

 private Strategy strategy;

 public void setStrategy(Strategy strategy){
   this.strategy = strategy;
 }

 public void executeStrategy(){
   this.strategy.execute();
 }
}
An example of using the Strategy.
public class UseStrategy {

public static void main(String[] args){

Context context = new Context();

context.setStrategy(new StrategyA());
context.executeStrategy();

context.setStrategy(new StrategyB());
context.executeStrategy();
}
}
Enum implementation of the Strategy design pattern:
It will have two classes: an enum class and a class that uses it. All the magic happens in the enum, where the concrete implementation of the strategy is done to define each enum constant.
Java
// Java program to Implement a Strategy Pattern using Enum  enum Strategy {    STRATEGY_A {    @Override    void execute() {      System.out.println("Executing strategy A");    }  },      STRATEGY_B {    @Override    void execute() {      System.out.println("Executing strategy B");    }  };    abstract void execute();}     class UseStrategy {    public static void main(String[] args)  {    UseStrategy useStrategy = new UseStrategy();    useStrategy.perform(Strategy.STRATEGY_A);    useStrategy.perform(Strategy.STRATEGY_B);  }    private void perform(Strategy strategy) {    strategy.execute();  }}
Executing strategy A
Executing strategy B
Java-Enumeration
Java-Pattern
Picked
How To
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install FFmpeg on Windows?
How to Set Git Username and Password in GitBash?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Install Jupyter Notebook on MacOS?
How to Check the OS Version in Linux?
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Arrays.sort() in Java with examples
Reverse a string in Java
Dot notation in JavaScript

The dot notation is used to access the object properties in JavaScript. Following is the code
to implement dot notation −
 Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result {
      font-size: 20px;
      font-weight: 500;
      color: blueviolet;
   }
</style>
</head>
<body>
<h1>Dot notation in JavaScript.</h1>
<div class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to access the student1 object properties using dot notation</h3>
<script>
   let resEle = document.querySelector(".result");
   let BtnEle = document.querySelector(".Btn");
   function Student(name, age, standard) {
      this.name = name;
      this.age = age;
      this.standard = standard;
   }
   let student = new Student("Rohan", 18, 12);
   BtnEle.addEventListener("click", () => {
      resEle.innerHTML = "student1.name = " + student1.name + "<br>";
      resEle.innerHTML += "student1.age = " + student1.age + "<br>";
      resEle.innerHTML += "student1.standard = " + student1.standard + "<br>";
   });
</script>
</body>
</html>
On clicking the ‘CLICK HERE’ button −
Redis - Server Slaveof Command

Redis SLAVEOF command can change the replication settings of a slave on the fly. If a Redis server is already acting as a slave, the command SLAVEOF NO ONE will turn off the replication, turning the Redis server into a MASTER. In the proper form SLAVEOF hostname port will make the server a slave of another server listening at the specified hostname and port. If a server is already a slave of some master, SLAVEOF hostname port will stop the replication against the old server and start the synchronization against the new one, discarding the old dataset.
Simple string reply.
Following is the basic syntax of Redis SLAVEOF command.
redis 127.0.0.1:6379> SLAVEOF host port


    22 Lectures 
     40 mins

 Skillbakerystudios
 Print
 Add Notes
 Bookmark this page
Tryit Editor v3.7

Tryit: A navigation menu
pause method - Action Chains in Selenium Python - GeeksforGeeks

15 May, 2020
Selenium’s Python Module is built to perform automated testing with Python. ActionChains are a way to automate low-level interactions such as mouse movements, mouse button actions, keypress, and context menu interactions. This is useful for doing more complex actions like hover over and drag and drop. Action chain methods are used by advanced scripts where we need to drag an element, click an element, double click, etc.This article revolves around pause method on Action Chains in Python Selenium. pause method is used to pause all inputs for the specified duration in seconds. Pause method is highly important and useful in case one is executing some command that takes some javascript to load or a similar situation where there is a time gap between two operations.
Syntax –
pause(seconds)
pause(1024)

To demonstrate, pause method of Action Chains in Selenium Python. Let’ s visit https://www.geeksforgeeks.org/ and operate on an element.
Program –
# import webdriverfrom selenium import webdriver  # import Action chains from selenium.webdriver.common.action_chains import ActionChains  # create webdriver objectdriver = webdriver.Firefox()  # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/")  # get element element = driver.find_element_by_link_text("Courses")  # create action chain objectaction = ActionChains(driver)  # click the itemaction.click(on_element = element)  # action.pause(1000)  # click the itemaction.click(on_element = element)  # perform the operationaction.perform()
Output –
Python-selenium
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()
AngularJS | ng-keypress Directive - GeeksforGeeks

26 Mar, 2019
The ng-keypress Directive in AngluarJS is used to apply custom behavior on a keypress event. It is supported by <input>, <select> and <textarea> element.
Syntax:
<element ng-keypress="expression"> Contents... </element>
Where expression tells what to do when key is pressed.
Example: This example uses ng-keypress Directive to display key value.
<!DOCTYPE html><html>      <head>    <title>ng-keypress Directive</title>          <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js">    </script>          <script type="text/javascript">        var app = angular.module('app', []);        app.controller('geek', function ($scope) {            $scope.getkeys = function (event) {                $scope.keyval = event.keyCode;            }        });    </script></head>  <body style="text-align:center">    <div ng-app="app" ng-controller="geek">        <h1 style="color:green">            GeeksforGeeks        </h1>                  <h2>ng-keypress Directive</h2>                  Enter Text: <input type="text"                ng-keypress="getkeys($event)" >                  <br><br>                  <span style="color:Red">            Key Code: {{keyval}}        </span>    </div></body>  </html>
Output:
AngularJS-Directives
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Angular PrimeNG Dropdown Component
Angular PrimeNG Calendar Component
Angular 10 (blur) Event
How to make a Bootstrap Modal Popup in Angular 9/8 ?
Angular PrimeNG Messages Component
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Horizontal Boxplots with Seaborn in Python - GeeksforGeeks

12 Nov, 2020
Prerequisite: seaborn
The Boxplots are used to visualize the distribution of data which is useful when a comparison of data is required. Sometimes, Boxplot is also known as a box-and-whisker plot. The box shows the quartiles of dataset and whiskers extend to show rest of the distribution. In this article, we are going to implement the Horizontal boxplot with seaborn using python.
Seaborn uses the boxplot() method to draw a boxplot. We can turn the boxplot into a horizontal boxplot by two methods first, we need to switch x and y attributes and pass it to the boxplot( ) method, and the other is to use the orient=”h” option and pass it to the boxplot() method.
Method 1: Switching x and y attribute
Python3
# import library & datasetimport seaborn as sns    df = sns.load_dataset('iris')  # Just switch x and ysns.boxplot(y=df["species"], x=df["sepal_length"])
Output:
Horizontal Boxplot
Method 2: Using orient = h
Python3
# import library & datasetimport seaborn as sns    tips = sns.load_dataset("tips")ax = sns.boxplot(data=tips, orient="h", palette="Set2")
Output :
Horizontal Boxplot
Python-Seaborn
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python Dictionary
Taking input in Python
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
C++ Array Library - empty() Function

The C++ function std::array::empty() tests whether size of array is zero or not.
Following is the declaration for std::array::empty() function form std::array header.
constexpr bool empty() noexcept;
None
Returns true if array size is 0 otherwise false.
This member function never throws exception.
Constant i.e. O(1)
In below example size of arr1 is 0 that is why it will be treated as empty
array and member function will return true value for arr1.
#include <iostream>
#include <array>

using namespace std;

int main(void) {
   
   /* array size is zero, it will be treated as empty array */
   array<int, 0> arr1;   
   array<int, 10> arr2;

   if (arr1.empty())
      cout << "arr1 is empty" << endl;
   else
      cout << "arr1 is not empty" << endl;

   if (arr2.empty())
      cout << "arr2 is empty" << endl;
   else
      cout << "arr2 is not empty" << endl;
}
Let us compile and run the above program, this will produce the following result −
arr1 is empty
arr2 is not empty

 Print
 Add Notes
 Bookmark this page
Implementing Counting Sort using map in C++ - GeeksforGeeks

09 Sep, 2019
Counting Sort is one of the best sorting algorithms which can sort in O(n) time complexity but the disadvantage with the counting sort is it’s space complexity, for a small collection of values, it will also require a huge amount of unused space.
So, we need two things to overcome this:
A data structure which occupies the space for input elements only and not for all the elements other than inputs.The stored elements must be in sorted order because if it’s unsorted then storing them will be of no use.
A data structure which occupies the space for input elements only and not for all the elements other than inputs.
The stored elements must be in sorted order because if it’s unsorted then storing them will be of no use.
So Map in C++ satisfies both the condition. Thus we can achieve this through a map.
Examples:
Input: arr[] = {1, 4, 3, 5, 1}Output: 1 1 3 4 5
Input: arr[] = {1, -1, -3, 8, -3}Output: -3 -3 -1 1 8
Below is the implementation of Counting Sort using map in C++:
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std;  // Function to sort the array using counting sortvoid countingSort(vector<int> arr, int n){      // Map to store the frequency    // of the array elements    map<int, int> freqMap;    for (auto i = arr.begin(); i != arr.end(); i++) {        freqMap[*i]++;    }      int i = 0;      // For every element of the map    for (auto it : freqMap) {          // Value of the element        int val = it.first;          // Its frequency        int freq = it.second;        for (int j = 0; j < freq; j++)            arr[i++] = val;    }      // Print the sorted array    for (auto i = arr.begin(); i != arr.end(); i++) {        cout << *i << " ";    }}  // Driver codeint main(){    vector<int> arr = { 1, 4, 3, 5, 1 };    int n = arr.size();      countingSort(arr, n);      return 0;}
1 1 3 4 5

counting-sort
cpp-map
Algorithms
Sorting
Sorting
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
DSA Sheet by Love Babbar
Quadratic Probing in Hashing
Difference between Informed and Uninformed Search in AI
K means Clustering - Introduction
SCAN (Elevator) Disk Scheduling Algorithms
Write a Python program to separate a series of alphabets and digits and convert them to a dataframe

Assume you have a series and the result for separating alphabets and digits and store it in dataframe as,
series is:
0    abx123
1    bcd25
2    cxy30
dtype: object
Dataframe is
   0   1
0 abx 123
1 bcd 25
2 cxy 30
To solve this, we will follow the below approach,
Define a series.
Define a series.
Apple series extract method inside use regular expression pattern to separate alphabets and digits then store it in a dataframe −
Apple series extract method inside use regular expression pattern to separate alphabets and digits then store it in a dataframe −
series.str.extract(r'(\w+[a-z])(\d+)')
Let’s see the below implementation to get a better understanding −
import pandas as pd
series = pd.Series(['abx123', 'bcd25', 'cxy30'])
print("series is:\n",series)
df = series.str.extract(r'(\w+[a-z])(\d+)')
print("Dataframe is\n:" ,df)
series is:
0    abx123
1    bcd25
2    cxy30
dtype: object
Dataframe is
:  0   1
0 abx 123
1 bcd 25
2 cxy 30
Program for Christmas Tree in C

Here we will see one interesting problem. In this problem, we will see how to print Christmas tree randomly. So the tree will be flickering like Christmas tree lights.
To print a Christmas tree, we will print pyramids of various sizes just one beneath another. For the decorative leaves a random character is printed from a given list of characters. The height and randomness is adjustable.
Here after generating a tree, the whole screen is cleared, then generate again, that’s why this is looking like flickering tree.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#define REFRESH_RATE 40000
#define RANDOM_NESS 5 // The higer value indicates less random
void clear_screen() {
   system("@cls||clear");
}
void display_random_leaf() {
   char type_of_leaves[5] = { '.', '*', '+', 'o', 'O' }; //these are the leaf types
   int temp = rand() % RANDOM_NESS;
   if (temp == 1)
      printf("%c ", type_of_leaves[rand() % 5]); //if temp is 1, then use other leaves
   else
      printf("%c ", type_of_leaves[1]); //otherwise print *
}
void tree_triangle(int f, int n, int toth) {
   int i, j, k = 2 * toth - 2;
   for (i = 0; i < f - 1; i++)
      k--;
   for (i = f - 1; i < n; i++) { //i will point the number of rows
      for (j = 0; j < k; j++) // Used to put spaces
      printf(" ");
         k = k - 1;
      for (j = 0; j <= i; j++)
         display_random_leaf();
      printf("\n");
   }
}
void display_tree(int h) {
   int start = 1, end = 0, diff = 3;
   while (end < h + 1) {
      end = start + diff;
      tree_triangle(start, end, h);
      diff++;
      start = end - 2;
   }
}
void display_log(int n) { //print the log of the tree
   int i, j, k = 2 * n - 4;
   for (i = 1; i <= 6; i++) {
      for (j = 0; j < k; j++)
         printf(" ");
      for (j = 1; j <= 6; j++)
         printf("#");
      printf("\n");
   }
}
main() {
   srand(time(NULL));
   int ht = 15;
   while (1) {
      clear_screen();
      display_tree(ht);
      display_log(ht);
      usleep(REFRESH_RATE); //use sleep before replacing
   }
}
Construct ∈-NFA of Regular Language L = {ab,ba}

The ε transitions in Non-deterministic finite automata (NFA) are used to move from one state to another without having any symbol from input set Σ
ε-NFA is defined in five tuple representation
{Q, q0, Σ, δ, F}
Where,
δ − Q × (Σ∪ε)→2Q
δ − Q × (Σ∪ε)→2Q
Q − Finite set of states
Q − Finite set of states
Σ − Finite set of the input symbol
Σ − Finite set of the input symbol
q0 − Initial state
q0 − Initial state
F − Final state
F − Final state
δ − Transition function
δ − Transition function
NFA and NFA with epsilon both are almost the same; the only difference is their transition function.
NFA transition function is as follows −
δ − Q X Σ→ 2Q
NFA with ε- transition functions is as follows −
δ: Q × (Σ∪ε)→2Q
Construct NFA with epsilon for a given language L= {ab, ba}.
Follow the steps given below −
Step 1 − NFA with epsilon for (a+b) is given below −
It accepts either a or b as an input, and both go to the final state.
Step 2 − NFA with epsilon for ab is as follows −
Concatenating a and b with epsilon, and a must followed by b then only it can reach the final state.
Step 3 − NFA with epsilon for ba is as follows −
Concatenating b and a with epsilon, and b must follow by a then only it can reach the final state.
Step 4 − Now the final NFA with epsilon for the language L={ab, ba}.
The language consists of strings ab or ba, it can be written as (ab + ba). So the final ε-NFA having two paths, one path is for ab and another path is for ba both goes to the final state.
In the above steps we individually construct the structures for ab and ba. Now, add those two structures to get our result.
Java Examples - New File Creation

How to create a new file ?
This example demonstrates the way of creating a new file by using File() constructor and file.createNewFile() method of File class.
import java.io.File;
import java.io.IOException;

public class Main {
   public static void main(String[] args) {
      try {
         File file = new File("C:/myfile.txt");
         
         if(file.createNewFile())System.out.println("Success!");
         else System.out.println ("Error, file already exists.");
      }
      catch(IOException ioe) {
         ioe.printStackTrace();
      }
   }
}
The above code sample will produce the following result (if "myfile.txt does not exist before)
Success!

The following is an another sample example of File create
import java.io.IOException;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;

import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

import java.util.Arrays;
import java.util.List;

public class JavaApplication1 { 
   public static void main(String[] args) throws IOException {
      createFileUsingFileClass();
      createFileUsingFileOutputStreamClass();
      createFileIn_NIO();
      // TODO code application logic here
   } 
   private static void createFileUsingFileClass() throws IOException { 
      File file = new File("c://testFile1.txt");
      
      //Create the file
      if (file.createNewFile()) { 
         System.out.println("File is created!");
      } else {
         System.out.println("File already exists.");
      } 
      
      //Write Content
      FileWriter writer = new FileWriter(file);
      writer.write("Test data");
      writer.close();
   } 
   private static void createFileUsingFileOutputStreamClass() throws IOException { 
      String data = "Test data";
      FileOutputStream out = new FileOutputStream("c://testFile2.txt");
      out.write(data.getBytes());
      out.close();
   } 
   private static void createFileIn_NIO()  throws IOException { 
      String data = "Test data";
      Files.write(Paths.get("c://testFile3.txt"), data.getBytes());
      List<String> lines = Arrays.asList("1st line", "2nd line");
      Files.write(Paths.get(
         "file6.txt"), lines, StandardCharsets.UTF_8, 
         StandardOpenOption.CREATE, StandardOpenOption.APPEND);
   }
}
 Print
 Add Notes
 Bookmark this page
Tagged Template Literals in JavaScript

Template literals also allow us to create tagged template literals. The tagged literal is just like a function definition and allows us to parse template literals. The tagged literal doesn’t contain the parenthesis and the tag function gets the array of string values as first argument.The rest of the arguments are then passed to the other related parameters.
Following is the code to implement tagged template literals in JavaScript −
 Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result {
      font-size: 20px;
      font-weight: 500;
      color: blueviolet;
   }
</style>
</head>
<body>
<h1>Tagged Template Literals in JavaScript</h1>
<div class="result"></div>
<br />
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to pass the template string using tagged template literal to sampleTag() function</h3>
<script>
   let resEle = document.querySelector(".result");
   let BtnEle = document.querySelector(".Btn");
   function sampleTag(strings, name, age, rollNo) {
      let section;
      if (rollNo > 50) {
         section = "A";
      } else {
         section = "B";
      }
      return `${name} roll no: ${rollNo} age :${age} is in section ${section}`;
   }
   let name = "Rohan",
   age = 16,
   rollNo = 22;
   BtnEle.addEventListener("click", () => {
      resEle.innerHTML = sampleTag`${name} aged ${age} and roll no ${rollNo} is new in
      the school`;
   });
</script>
</body>
</html>
On clicking the ‘CLICK HERE’ button −
How to get the local Administrators group members using PowerShell?

To get the local Administrators group members using PowerShell, you need to use the GetLocalGroupMember command. This command is available in PowerShell version 5.1 onwards and the module for it is Microsoft.PowerShell.LocalAccounts. This module is not available in the 32-bit PowerShell version but on a 64-bit system.
In the below example, we need to retrieve the Local Administrators group members,
Get-LocalGroupMember -Group "Administrators"
ObjectClass    Name          PrincipalSource
-----------    ----          ---------------
User          LABDOMAIN\delta
Group         LABDOMAIN\Domain Admins
User          TEST1-WIN2K12\Administrator
User          TEST1-WIN2K12\LocalAdmin
Name Property shows the members of the local administrator groups. To retrieve the local Administrators group members from the remote servers, we need to use the Invoke-Command method.
Invoke-Command -ComputerName Test1-Win2k16 -ScriptBlock{Get-LocalGroupMember -
Name 'Administrators'}
ObjectClass    Name                         PrincipalSource          PSComputerName
-----------    ----                         ---------------          --------------
User           LABDOMAIN\Delta              ActiveDirectory          Test1-Win2k16
Group          LABDOMAIN\Domain             Admins ActiveDirectory   Test1-Win2k16
User           TEST1-WIN2K16\Administrator  Local                    Test1-Win2k16
User           TEST1-WIN2K16\LocalAdmin     Local                    Test1-Win2k16
User           TEST1-WIN2K16\Localuser      Local                    Test1-Win2k16
You can also filter the specific user as shown below.
Invoke-Command -ComputerName Test1-Win2k16 -ScriptBlock{Get-LocalGroupMember -
Name 'Administrators' | where{$_.Name -like "*Alpha*"}}
ObjectClass    Name                PrincipalSource PSComputerName
-----------    ----                --------------- --------------
User           LABDOMAIN\alpha     ActiveDirectory Test1-Win2k16
In the earlier PowerShell version, this command wasn’t supported. You can also retrieve the output using cmd.
net localgroup administrators
Alias name    administrators
Comment       Administrators have complete and unrestricted access to the comput
er/domain
Members
-------------------------------------------------------------------------------
Administrator
Delta
Domain Admins
Enterprise Admins
The command completed successfully.
To get only the members, we will store the output in the variable and operate.
$members = net localgroup administrators
$members[6..($members.Length-3)]
Administrator
Delta
Domain Admins
Enterprise Admins
To run this command on the remote computer,
Invoke-Command -ComputerName Test1-Win2k16 -ScriptBlock{
   $members = Invoke-Expression -command "Net Localgroup Administrators"
   $members[6..($members.Length-3)]
}
Administrator
LABDOMAIN\Delta
LABDOMAIN\Domain Admins
LocalAdmin
Similarly, you can use any local group name instead of the Administrators group.
PyQt5 QDockWidget – Setting Features of it - GeeksforGeeks

28 Jul, 2020
In this article we will see how we can set features to the QDockWidget. QDockWidget provides the concept of dock widgets, also know as tool palettes or utility windows. Dock windows are secondary windows placed in the dock widget area around the central widget in a QMainWindow(original window).
There are many features already enabled for the dock, also there are feature like movable, closable, flotable, horizontal title bar or there is an option of setting all features or setting no features.
In order to do this we will use setFeatures method with the dock widget object.
Syntax : dock.setFeatures(QDockWidget.DockWidgetClosable)
Argument : It takes feature as argument
Return : It returns None
Below is the implementation
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys    class Window(QMainWindow):      def __init__(self):        super().__init__()          # setting title        self.setWindowTitle("Python ")          # setting geometry        self.setGeometry(100, 100, 500, 400)          # calling method        self.UiComponents()          # showing all the widgets        self.show()      # method for components    def UiComponents(self):          # creating dock widget        dock = QDockWidget("GeeksforGeeks", self)          # push button        push = QPushButton("Press", self)          # setting widget to the dock        dock.setWidget(push)          # setting feature to the dock        dock.setFeatures(QDockWidget.DockWidgetClosable)          # setting geometry tot he dock widget        dock.setGeometry(100, 0, 200, 30)            # creating a label        label = QLabel("GeeksforGeeks", self)          # setting geometry to the label        label.setGeometry(100, 200, 300, 80)          # making label multi line        label.setWordWrap(True)      # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output :
Python PyQt-QDockWidget
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Create a Pandas DataFrame from Lists
Box Plot in Python using Matplotlib
Python Dictionary
Bar Plot in Matplotlib
Enumerate() in Python
Python | Get dictionary keys as a list
Python | Convert set into a list
Ways to filter Pandas DataFrame by column values
Graph Plotting in Python | Set 1
Python - Call function from another file
HTML | onselect Event Attribute - GeeksforGeeks

03 Aug, 2021
The onselect event attribute works when some text has been selected in an element. It is the part of event attribute. It is supported by many HTML elements such as <input type = “file”>, <input type = “password”>, <input type = “text”>, and <textarea>.
Supported Tags: 
<input type=”file”>
 <input type=”password”>
 <input type=”text”> 
 <textarea>
Syntax: 
<element onselect = "script">
Example: 
HTML
<!DOCTYPE html><html>    <head>        <title>onselect event attribute</title>        <style>            h1 {            color:green;            }            body {                text-align:center;            }        </style>        <script>            function Geeks() {                alert("Text selected!");            }        </script>    </head>    <body>        <h1>GeeksforGeeks</h1>        <h2>onselect event attribute</h2>        Text Box: <input type="text" value="GeeksforGeeks: A computer        science portal for geeks" onselect="Geeks()">    </body></html>                   </html>
Output: 
Supported Browsers: The browser supported by onselect attribute are listed below: 
Apple Safari
Google Chrome
Firefox
Opera
Internet Explorer
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
arorakashish0911
hritikbhatnagar2182
HTML-Attributes
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to create footer to stay at the bottom of a Web page?
How to update Node.js and NPM to next version ?
CSS to put icon inside an input element in a form
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
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 ?
perform method - Action Chains in Selenium Python - GeeksforGeeks

15 May, 2020
Selenium’s Python Module is built to perform automated testing with Python. ActionChains are a way to automate low-level interactions such as mouse movements, mouse button actions, keypress, and context menu interactions. This is useful for doing more complex actions like hover over and drag and drop. Action chain methods are used by advanced scripts where we need to drag an element, click an element, double click, etc.This article revolves around perform method on Action Chains in Python Selenium. perform method is used to perform all stored operations in action instance of ActionChains class.
Syntax –
perform()
Example –
<input type ="text" name ="passwd" id ="passwd-id" />
To find an element one needs to use one of the locating strategies, For example,
element = driver.find_element_by_id("passwd-id")element = driver.find_element_by_name("passwd")
Now one can use perform method as an Action chain as below –
action.click(on_element=element)
action.perform()

To demonstrate, perform method of Action Chains in Selenium Python. Let’ s visit https://www.geeksforgeeks.org/ and operate on an element.
Program –
# import webdriverfrom selenium import webdriver  # import Action chains from selenium.webdriver.common.action_chains import ActionChains  # create webdriver objectdriver = webdriver.Firefox()  # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/")  # get element element = driver.find_element_by_link_text("Courses")  # create action chain objectaction = ActionChains(driver)  # click the itemaction.click(on_element = element)  # perform the operationaction.perform()
Output –
Python-selenium
selenium
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
*args and **kwargs in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python
Check if element exists in list in Python
sum() function in Python
Priority Queue of Vectors in C++ STL with Examples - GeeksforGeeks

17 Mar, 2020
Priority Queue in STL Priority queues are a type of container adapters, specifically designed such that the first element of the queue is the greatest of all elements in the queue and elements are in non increasing order(hence we can see that each element of the queue has a priority{fixed order})
Vector in STL Vector is same as dynamic arrays with the ability to resize itself automatically when an element is inserted or deleted, with their storage being handled automatically by the container. Vector elements are placed in contiguous storage so that they can be accessed and traversed using iterators.
Priority Queue of Vectors in STL: Priority Queue of Vectors can be very efficient in designing complex data structures.
Syntax:
priority_queue<vector<datatype>> pq;

For example: Consider a simple problem where we have to print the maximum vector that is in the queue.
// C++ program to demonstrate// use of priority queue for vectors  #include <bits/stdc++.h>using namespace std;  priority_queue<vector<int> > pq;  // Prints maximum vectorvoid Print_Maximum_Vector(vector<int> Vec){    for (int i = 0; i < Vec.size(); i++) {        cout << Vec[i] << " ";    }    cout << endl;    return;}  // Driver codeint main(){    // Initializing some vectors    vector<int> data_1{ 10, 20, 30, 40 };    vector<int> data_2{ 10, 20, 35, 40 };    vector<int> data_3{ 30, 25, 10, 50 };    vector<int> data_4{ 20, 10, 30, 40 };    vector<int> data_5{ 5, 10, 30, 40 };      // Inserting vectors into priority queue    pq.push(data_1);    pq.push(data_2);      // printing the maximum vector till now    Print_Maximum_Vector(pq.top());      // Inserting vectors into priority queue    pq.push(data_3);      // printing the maximum vector till now    Print_Maximum_Vector(pq.top());      // Inserting vectors into priority queue    pq.push(data_4);    pq.push(data_5);      // printing the maximum vector till now    Print_Maximum_Vector(pq.top());      return 0;}
10 20 35 40 
30 25 10 50 
30 25 10 50

cpp-priority-queue
cpp-vector
C++ Programs
Queue
Queue
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Passing a function as a parameter in C++
Program to implement Singly Linked List in C++ using class
Const keyword in C++
cout in C++
Dynamic _Cast in C++
Breadth First Search or BFS for a Graph
Level Order Binary Tree Traversal
Queue Interface In Java
Queue in Python
Queue | Set 1 (Introduction and Array Implementation)