code-rag-bench/online-tutorials huggingface dataset:
Construct tree from Inorder and LevelOrder | Practice | GeeksforGeeks

Given inorder and level-order traversals of a Binary Tree, construct the Binary Tree and return the root Node. 
Input:
First line consists of T test cases. First line of every test case consists of N, denoting number of elements is respective arrays. Second and third line consists of arrays containing Inorder and Level-order traversal respectively.
Output:
Single line output, print the preOrder traversal of array.
Constraints:
1<=T<=100
1<=N<=100
Example:
Input:
2
3
1 0 2 
0 1 2 
7
3 1 4 0 5 2 6 
0 1 2 3 4 5 6 
Output:
0 1 2
0 1 3 4 2 5 6
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

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

A loop can be nested inside of another loop. Perl allows to nest all type of loops to be nested.
The syntax for a nested for loop statement in Perl is as follows −
for ( init; condition; increment ) {
   for ( init; condition; increment ) {
      statement(s);
   }
   statement(s);
}

The syntax for a nested while loop statement in Perl is as follows −
while(condition) {
   while(condition) {
      statement(s);
   }
   statement(s);
}

The syntax for a nested do...while loop statement in Perl is as follows −
do{
   statement(s);
   do{
      statement(s);
   }while( condition );

}while( condition );

The syntax for a nested until loop statement in Perl is as follows −
until(condition) {
   until(condition) {
      statement(s);
   }
   statement(s);
}

The syntax for a nested foreach loop statement in Perl is as follows −
foreach $a (@listA) {
   foreach $b (@listB) {
      statement(s);
   }
   statement(s);
}

The following program uses a nested while loop to show the usage −
#/usr/local/bin/perl
   
$a = 0;
$b = 0;

# outer while loop
while($a < 3) {
   $b = 0;
   # inner while loop
   while( $b < 3 ) {
      print "value of a = $a, b = $b\n";
      $b = $b + 1;
   }
   $a = $a + 1;
   print "Value of a = $a\n\n";
}
This would produce the following result −
value of a = 0, b = 0
value of a = 0, b = 1
value of a = 0, b = 2
Value of a = 1

value of a = 1, b = 0
value of a = 1, b = 1
value of a = 1, b = 2
Value of a = 2

value of a = 2, b = 0
value of a = 2, b = 1
value of a = 2, b = 2
Value of a = 3


    46 Lectures 
     4.5 hours 

 Devi Killada

    11 Lectures 
     1.5 hours 

 Harshit Srivastava

    30 Lectures 
     6 hours 

 TELCOMA Global

    24 Lectures 
     2 hours 

 Mohammad Nauman

    68 Lectures 
     7 hours 

 Stone River ELearning

    58 Lectures 
     6.5 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
HTML | DOM Audio Object

02 Aug, 2019
The Audio object is used for representing an HTML <audio> element.The Audio Object is a new object in HTML5.
Syntax:
For creating an <audio> element:var gfg = document.createElement("AUDIO")
var gfg = document.createElement("AUDIO")
For accessing an <audio> element:var x = document.getElementById("myAudio")
var x = document.getElementById("myAudio")
Property Values:
Audio Object Methods:
Below programs illustrate the Audio Object :Example-1: Creating a <audio> element.
<!DOCTYPE html><html>  <head>    <title>Audio Object</title>    <style>        h1 {            color: green;        }                  h2 {            font-family: Impact;        }                  body {            text-align: center;        }    </style></head>  <body>      <h1>GeeksforGeeks</h1>    <h2>Audio Object</h2>      <p>Double Click the "Create"       button to create an Audio Object.</p>      <button ondblclick="Create()">      Create  </button>      <script>        function Create() {                        // Create audio element.            var m = document.createElement(              "AUDIO");              if (m.canPlayType("audio/mpeg")) {                m.setAttribute("src", "bells.mp3");            } else {                m.setAttribute("src", "bells.ogg");            }              m.setAttribute("controls", "controls");            document.body.appendChild(m);        }    </script>  </body>  </html>
Output:
Before clicking the button:
After clicking the button:
Example-2: Accessing a <audio> element.
<!DOCTYPE html><html>  <head>    <title>Audio Object</title>    <style>        h1 {            color: green;        }                  h2 {            font-family: Impact;        }                  body {            text-align: center;        }    </style></head>  <body>      <h1>GeeksforGeeks</h1>    <h2>Audio Object</h2>      <audio id="track" controls>        <source src="bells.ogg" type="audio/ogg">        <source src="bells.mp3" type="audio/mpeg">      Your browser does not support the audio element.    </audio>      <p>Double-click the "Access Audio" button       to get the duration of the audio, in seconds.</p>       <button onclick="access()">Access Audio</button>      <p id="test"></p>      <script>        function access() {                        // Accessing audio element duration.            var m = document.getElementById(              "track").duration;            document.getElementById("test").innerHTML = m;        }    </script>  </body>  </html>
Output:
Before clicking the button:
After clicking the button:
Supported Browsers: The browser supported by HTML | DOM Audio Object are listed below:
Google Chrome
Internet Explorer
Firefox
Opera
Apple Safari
HTML-DOM
Picked
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python program to Concatenate all Elements of a List into a String

15 Jul, 2022
Given a list, the task is to write a Python program to concatenate all elements in a list into a string.
Examples:
Input:  ['hello', 'geek', 'have', 'a', 'geeky', 'day']
Output: hello geek have a geeky day
Here, we are taking a list of words, and by using the Python loop we are iterating each element and concatenating words with the help of the “+” operator.
Python3
l = [ 'hello', 'geek', 'have',     'a', 'geeky', 'day'] ans = ' 'for i in l:     # concatenating the strings  # using + operator  ans = ans+ ' '+ i   print(ans)
Output:
hello geek have a geeky day
Here, we are using list comprehension to make the items into a Python string. 
Python3
l = [ 'hello', 'geek', 'have',     'a', 'geeky', 'day'] res = " ".join([str(item) for item in l])res
Output:
'hello geek have a geeky day'
The join() is an inbuilt string function in Python used to join elements of the sequence separated by a string separator. This function joins elements of a sequence and makes it a string. 
Python3
# codel = ['hello', 'geek', 'have',   'a', '1', 'day'] # this will join all the# elements of the list with ' 'l = ' '.join(l)print(l)
Output:
hello geek have a 1 day
The map() function returns a map object(which is an iterator) of the results after applying the given function to each item of a given iterable. In map we passed the str as Datatype and list, this will iterate till the length of the list and join each element to form a string.
Python3
l = [ 'hello', 'geek', 'have',     'a', 'geeky', 'day'] res = " ".join(map(str, l))print(res)
Output:
hello geek have a geeky day
The reduce(fun,seq) function is used to apply a particular function passed in its argument to all of the list elements mentioned in the sequence passed along. This function is defined in “functools” module.
Python3
from functools import reduce l = ['hello', 'geek', 'have',     'a', 'geeky', 'day'] # Concatenate all items in list to a stringres = reduce(lambda x, y: x + ' ' + y, map(str, l))print(res)
Output:
hello geek have a geeky day
surajkumarguptaintern
Python string-programs
Technical Scripter 2020
Python
Python Programs
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Rust - Bitwise Operators

Assume variable A = 2 and B = 3.
fn main() {
   let a:i32 = 2;     // Bit presentation 10
   let b:i32 = 3;     // Bit presentation 11

   let mut result:i32;

   result = a & b;
   println!("(a & b) => {} ",result);

   result = a | b;
   println!("(a | b) => {} ",result) ;

   result = a ^ b;
   println!("(a ^ b) => {} ",result);

   result = !b;
   println!("(!b) => {} ",result);

   result = a << b;
   println!("(a << b) => {}",result);

   result = a >> b;
   println!("(a >> b) => {}",result);
}
(a & b) => 2
(a | b) => 3
(a ^ b) => 1
(!b) => -4
(a << b) => 16
(a >> b) => 0


    45 Lectures 
     4.5 hours 

 Stone River ELearning

    10 Lectures 
     33 mins

 Ken Burke
 Print
 Add Notes
 Bookmark this page
Divide numbers from two columns and display result in a new column with MySQL

Let us first create a table −
mysql> create table DemoTable719 (FirstNumber int,SecondNumber int);
Query OK, 0 rows affected (0.57 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable719 values(20,10);
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable719 values(500,50);
Query OK, 1 row affected (0.22 sec)
mysql> insert into DemoTable719 values(400,20);
Query OK, 1 row affected (0.11 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable719;
This will produce the following output −
+-------------+--------------+
| FirstNumber | SecondNumber |
+-------------+--------------+
| 20          |           10 |
| 500         |           50 |
| 400         |           20 |
+-------------+--------------+
3 rows in set (0.00 sec)
Following is the query to divide numbers from two columns and display result in a new column −
mysql> select *,FirstNumber/SecondNumber AS Result from DemoTable719;
This will produce the following output 7minus;
+-------------+--------------+---------+
| FirstNumber | SecondNumber | Result  |
+-------------+--------------+---------+
| 20          |           10 | 2.0000  |
| 500         |           50 | 10.0000 |
| 400         |           20 | 20.0000 |
+-------------+--------------+---------+
3 rows in set (0.00 sec)
SciPy - Spatial

The scipy.spatial package can compute Triangulations, Voronoi Diagrams and Convex Hulls of a set of points, by leveraging the Qhull library. Moreover, it contains KDTree implementations for nearest-neighbor point queries and utilities for distance computations in various metrics.
Let us understand what Delaunay Triangulations are and how they are used in SciPy.
In mathematics and computational geometry, a Delaunay triangulation for a given set P of discrete points in a plane is a triangulation DT(P) such that no point in P is inside the circumcircle of any triangle in DT(P).
We can the compute the same through SciPy. Let us consider the following example.
from scipy.spatial import Delaunay
points = np.array([[0, 4], [2, 1.1], [1, 3], [1, 2]])
tri = Delaunay(points)
import matplotlib.pyplot as plt
plt.triplot(points[:,0], points[:,1], tri.simplices.copy())
plt.plot(points[:,0], points[:,1], 'o')
plt.show()
The above program will generate the following output.
Let us understand what Coplanar Points are and how they are used in SciPy.
Coplanar points are three or more points that lie in the same plane. Recall that a plane is a flat surface, which extends without end in all directions. It is usually shown in math textbooks as a four-sided figure.
Let us see how we can find this using SciPy. Let us consider the following example.
from scipy.spatial import Delaunay
points = np.array([[0, 0], [0, 1], [1, 0], [1, 1], [1, 1]])
tri = Delaunay(points)
print tri.coplanar
The above program will generate the following output.
array([[4, 0, 3]], dtype = int32)

This means that point 4 resides near triangle 0 and vertex 3, but is not included in the triangulation.
Let us understand what convex hulls are and how they are used in SciPy.
In mathematics, the convex hull or convex envelope of a set of points X in the Euclidean plane or in a Euclidean space (or, more generally, in an affine space over the reals) is the smallest convex set that contains X.
Let us consider the following example to understand it in detail.
from scipy.spatial import ConvexHull
points = np.random.rand(10, 2) # 30 random points in 2-D
hull = ConvexHull(points)
import matplotlib.pyplot as plt
plt.plot(points[:,0], points[:,1], 'o')
for simplex in hull.simplices:
plt.plot(points[simplex,0], points[simplex,1], 'k-')
plt.show()
The above program will generate the following output.
 Print
 Add Notes
 Bookmark this page
Kruskal’s Minimum Spanning Tree using STL in C++

In this tutorial, we will be discussing a program to understand Kruskal’s minimum spanning tree using STL in C++.
For this, we will be provided with a connected, undirected and weighted graph. Our task is to calculate the Minimum spanning tree for the given graph.
 Live Demo
#include<bits/stdc++.h>
using namespace std;
typedef pair<int, int> iPair;
//structure for graph
struct Graph{
   int V, E;
   vector< pair<int, iPair> > edges;
   Graph(int V, int E){
      this->V = V;
      this->E = E;
   }
   void addEdge(int u, int v, int w){
      edges.push_back({w, {u, v}});
   }
   int kruskalMST();
};
struct DisjointSets{
   int *parent, *rnk;
   int n;
   DisjointSets(int n){
      this->n = n;
      parent = new int[n+1];
      rnk = new int[n+1];
   for (int i = 0; i <= n; i++){
      rnk[i] = 0;
      parent[i] = i;
   }
}
int find(int u){
   if (u != parent[u])
   parent[u] = find(parent[u]);
   return parent[u];
}
void merge(int x, int y){
   x = find(x), y = find(y);
   if (rnk[x] > rnk[y])
      parent[y] = x;
   else
      parent[x] = y;
   if (rnk[x] == rnk[y])
      rnk[y]++;
   }
};
int Graph::kruskalMST(){
   int mst_wt = 0;
   sort(edges.begin(), edges.end());
   DisjointSets ds(V);
   vector< pair<int, iPair> >::iterator it;
   for (it=edges.begin(); it!=edges.end(); it++){
      int u = it->second.first;
      int v = it->second.second;
      int set_u = ds.find(u);
      int set_v = ds.find(v);
      if (set_u != set_v){
         cout << u << " - " << v << endl;
         mst_wt += it->first;
         ds.merge(set_u, set_v);
      }
   }
   return mst_wt;
}
int main(){
   int V = 9, E = 14;
   Graph g(V, E);
   g.addEdge(0, 1, 4);
   g.addEdge(0, 7, 8);
   g.addEdge(1, 2, 8);
   g.addEdge(1, 7, 11);
   g.addEdge(2, 3, 7);
   g.addEdge(2, 8, 2);
   g.addEdge(2, 5, 4);
   g.addEdge(3, 4, 9);
   g.addEdge(3, 5, 14);
   g.addEdge(4, 5, 10);
   g.addEdge(5, 6, 2);
   g.addEdge(6, 7, 1);
   g.addEdge(6, 8, 6);
   g.addEdge(7, 8, 7);
   cout << "Edges of MST are \n";
   int mst_wt = g.kruskalMST();
   cout << "\nWeight of MST is " << mst_wt;
   return 0;
}
Edges of MST are
6 - 7
2 - 8
5 - 6
0 - 1
2 - 5
2 - 3
0 - 7
3 - 4
Weight of MST is 37
How to print content of JavaScript object?

To print the content of a JavaScript object, try to run the following code. The code prints the object, with its properties and values −
<!DOCTYPE html>
<html>
   <body>
      <script>
         function display(obj) {
            var res = '';
            for (var a in obj) {
               res += a + ': ' + obj[a] + '\n';
            }
            alert(res);
         }

         var newObject = {'Amit': 70778, 'Sachin': 87547, 'Saurav': 57535};
         display(newObject);
      </script>
   </body>
</html>
Determining Countability in TOC - GeeksforGeeks

27 Nov, 2019
Countable Set is a set having cardinality same as that of some subset of N the set of natural numbers . A countable set is the one which is listable.
Cardinality of a countable set can be a finite number. For example, B: {1, 5, 4}, |B| = 3, in this case its termed countably finite or the cardinality of countable set can be infinite. For example, A: {2, 4, 6, 8 ...}, in this case its termed countably infinite.
Common Traces for Countable Set:
Cardinality expressed in form  where , ; m may or may not be ∞
It has finite elements* only in case of countably finite sets.
It listable in terms of roaster form* an exhaustive list exists which can include every element atleast once, in case of countably infinite list first few elements followed by three dot ellipsis(...).
Set of Rational numbers is Countably Infinite:
Follow along the red line to build roaster set containing all rational numbers. Hence an exhaustive set containing every element atleast once can be build therefore set of rational numbers is countably infinite.
Uncountable Sets:A set such that its elements cannot be listed, or to put intuitively, there exists no sequence which can list every element of the set atleast once.
Example:
R : {set of real numbers is uncountable}
B : {set of all binary sequences of infinite length} 
Common Traces for Uncountable Set:
Cardinality expressed in form ;
It is power set of set with infinite elements
It is equal set to R set of real numbers
It is equal set to Q set of irrational numbers
It is non-listable set
Union Operations quick Reference:
Example-1:Let N be the set of natural numbers. Consider the following sets,
P: Set of Rational numbers (positive and negative)
Q: Set of functions from {0, 1} to N
R: Set of functions from N to {0, 1}
S: Set of finite subsets of N 
Which of the above sets are countable ?(A) Q and S only(B) P and S only(C) P and R only(D) P, Q and S only
Explanation:Please see GATE CS 2018 | Question 58
Example-2:Consider the following sets:
S1: Set of all recursively enumerable languages over the alphabet {0, 1}.
S2: Set of all syntactically valid C programs.
S3: Set of all languages over the alphabet {0, 1}.
S4: Set of all non-regular languages over the alphabet {0, 1}. 
Which of the above sets are uncountable?(A) S1 and S2(B) S3 and S4(C) S1 and S4(D) S2 and S3
Explanation:Please see GATE CS 2019 | Question 43
GATE CS
Theory of Computation & Automata
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between Clustered and Non-clustered index
Preemptive and Non-Preemptive Scheduling
Phases of a Compiler
Introduction of Process Synchronization
Differences between IPv4 and IPv6
Regular Expressions, Regular Grammar and Regular Languages
Difference between DFA and NFA
Introduction of Finite Automata
Difference between Mealy machine and Moore machine
Pumping Lemma in Theory of Computation
How to get formatted JSON in .NET using C#?

Use Namespace Newtonsoft.Json.Formatting Newtonsoft.Json.Formatting provides formatting options to Format the Json
None − No special formatting is applied. This is the default.
Indented − Causes child objects to be indented according to the Newtonsoft.Json.JsonTextWriter.Indentation and Newtonsoft.Json.JsonTextWriter.IndentChar settings.
static void Main(string[] args){
   Product product = new Product{
      Name = "Apple",
      Expiry = new DateTime(2008, 12, 28),
      Price = 3.9900M,
      Sizes = new[] { "Small", "Medium", "Large" }
   };
   string json = JsonConvert.SerializeObject(product, Formatting.Indented);
   Console.WriteLine(json);
   Product deserializedProduct = JsonConvert.DeserializeObject<Product>(json);
   Console.ReadLine();
}
class Product{
   public String[] Sizes { get; set; }
   public decimal Price { get; set; }
   public DateTime Expiry { get; set; }
   public string Name { get; set; }
}
{
   "Sizes": [
      "Small",
      "Medium",
      "Large"
   ],
   "Price": 3.9900,
   "Expiry": "2008-12-28T00:00:00",
   "Name": "Apple"
}
static class Program{
   static void Main(string[] args){
      Product product = new Product{
         Name = "Apple",
         Expiry = new DateTime(2008, 12, 28),
         Price = 3.9900M,
         Sizes = new[] { "Small", "Medium", "Large" }
      };
      string json = JsonConvert.SerializeObject(product, Formatting.None);
      Console.WriteLine(json);
      Product deserializedProduct = JsonConvert.DeserializeObject<Product>(json);
      Console.ReadLine();
   }
}
class Product{
   public String[] Sizes { get; set; }
   public decimal Price { get; set; }
   public DateTime Expiry { get; set; }
   public string Name { get; set; }
}
{"Sizes":["Small","Medium","Large"],"Price":3.9900,"Expiry":"2008-12-28T00:00:00","Name":"Apple"}
Matplotlib.axes.Axes.set() in Python - GeeksforGeeks

19 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute.
The Axes.set() function in axes module of matplotlib library is a property batch setter. Pass kwargs to set properties.
Syntax: Axes.set(self, **kwargs)
Parameters: This method does not accepts any parameters other than **kwargs.
Below examples illustrate the matplotlib.axes.Axes.set() function in matplotlib.axes:
Example 1:
# Implementation of matplotlib functionimport matplotlibimport matplotlib.pyplot as pltimport numpy as np   t = np.arange(0.0, 2, 0.001)s = 1 + np.sin(8 * np.pi * t)*0.4   fig, ax = plt.subplots()ax.plot(t, s)   ax.set(xlabel ='X-Axis', ylabel ='Y-Axis',       xlim =(0, 1.5), ylim =(0.5, 1.5),       title ='matplotlib.axes.Axes.set()\ function Example')ax.grid()   plt.show()
Output:
Example 2:
# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as pltnp.random.seed(19680801)  fig, ax = plt.subplots()  x, y, s, c = np.random.rand(4, 200)s *= 200  ax.scatter(x, y, s, c)  ax.set(xlabel ='X-Axis', ylabel ='Y-Axis',       xlim =(0, 0.5), ylim =(0, 0.5),       title ='matplotlib.axes.Axes.set()\ function Example')ax.grid()  plt.show()
Output:
Python-matplotlib
Python
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
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Highlight Pandas DataFrame's specific columns using apply() - GeeksforGeeks

17 Aug, 2020
Let us see how to highlight specific columns of a Pandas DataFrame. We can do this using the apply() function of the Styler class.
Syntax : Styler.apply(func, axis = 0, subset = None, **kwargs)
Parameters :
func : function should take a Series or DataFrame (depending on-axis), and return an object with the same shape. Must return a DataFrame with identical index and column labels when axis = None.
axis : apply to each column (axis=0 or ‘index’) or to each row (axis=1 or ‘columns’) or to the entire DataFrame at once with axis = None
subset : valid indexer to limit data to before applying the function.
**kwargs : dict pass along to func.
Returns : Styler
Let’s understand with examples:
Example 1 :
# importing pandas as pd import pandas as pd   # creating the dataframedf = pd.DataFrame({"A" : [14, 4, 5, 4, 1],                   "B" : [5, 2, 54, 3, 2],                   "C" : [20, 20, 7, 3, 8],                    "D" : [14, 3, 6, 2, 6],                   "E" : [23, 45, 64, 32, 23]})   print("Original DataFrame :")display(df)  # function definitiondef highlight_cols(x):          # copy df to new - original data is not changed    df = x.copy()          # select all values to green color    df.loc[:, :] = 'background-color: green'          # overwrite values grey color    df[['B', 'C', 'E']] = 'background-color: grey'          # return color df    return df   print("Highlighted DataFrame :")display(df.style.apply(highlight_cols, axis = None))
Output :
Example 2 :
# importing pandas as pd import pandas as pd   # creating the dataframedf = pd.DataFrame({"Name" : ["Yash", "Ankit", "Rao"],                   "Age" : [5, 2, 54]})   print("Original DataFrame :")display(df)  # function definitiondef highlight_cols(x):          # copy df to new - original data is not changed    df = x.copy()          # select all values to yellow color    df.loc[:, :] = 'background-color: yellow'          # return color df    return df   print("Highlighted DataFrame :")display(df.style.apply(highlight_cols, axis = None))
Output :
Python pandas-dataFrame
Python-pandas
Python
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
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python
AngularJS | ng-selected Directive - GeeksforGeeks

28 Mar, 2019
The ng-selected Directive in AngularJS is used to specify the selected attribute of an HTML element. It can be used to select the default value specified on an HTML element. If the expression inside the ng-selected directive returns true then the selected option value will be display otherwise not display.
Syntax:
<element ng-selected="expression"> Contents... </element> 
Example: This example uses ng-selected Directive to display the selected element.
<!DOCTYPE html><html>  <head>    <title>ng-selected Directive</title>          <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js">    </script></head>  <body ng-app style="text-align:center">          <h1 style="color:green">GeeksforGeeks</h1>    <h2>ng-selected Directive</h2>               Check to select default value:     <input type="checkbox" ng-model="sort">          <br><br>          <select name="geek" >        <option value="1" >Merge sort</option>        <option value="2" ng-selected="sort">Quick sort</option>        <option value="3">Bubble sort</option>        <option value="4">Insertion sort</option>    </select></body>  </html>                    
Output:Before checked the checkbox:After checked the checkbox:
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
Auth Guards in Angular 9/10/11
Angular PrimeNG Calendar Component
How to bundle an Angular app for production?
What is AOT and JIT Compiler in Angular ?
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 ?
How to insert spaces/tabs in text using HTML/CSS?
Comments in Shell Script - GeeksforGeeks

10 May, 2021
Comments are the useful information that the developers provide to make the reader understand the source code. It explains the logic or a part of it used in the code. Comments are usually helpful to someone maintaining or enhancing your code when you are no longer around to answer questions about it. These are often cited as a useful programming convention that does not take part in the output of the program but improves the readability of the whole program.
There are two types of comments:
Single-line commentMulti-line comment
Single-line comment
Multi-line comment
A single-line comment starts with hashtag symbol with no white spaces (#) and lasts till the end of the line. If the comment exceeds one line then put a hashtag on the next line and continue the comment.
The shell script is commented out prefixing # character for single-line comment.
Syntax
#This is a comment
Example:
#Single line comment
echo "hello world"
Output:
Multi-line comment is a piece of text enclosed in a delimiter (”) on each end of the comment. Again there should be no white space between delimiter (‘ ‘). They are useful when the comment text does not fit into one line; therefore need to span across lines. Multi-line comments or paragraphs serve as documentation for others reading your code. See the following code snippet demonstrating multi-line comment:
Syntax:
: '
This is a
Multi-line comments'
Example:
echo "multiline comments"
: '
Print some word'
Output:
meetgor
Shell Script
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TCP Server-Client implementation in C
tar command in Linux with examples
curl command in Linux with Examples
Conditional Statements | Shell Script
UDP Server-Client implementation in C
Tail command in Linux with examples
Cat command in Linux with examples
touch command in Linux with Examples
echo command in Linux with Examples
Compiling with g++
PHP | bcadd() Function - GeeksforGeeks

19 Apr, 2018
The bcadd() function in PHP is an inbuilt function and is used to add two arbitrary precision numbers. This function accepts two arbitrary precision numbers as strings and returns the addition of the two numbers after scaling the result to a specified precision.
Syntax:
string bcadd ( $num_str1, $num_str2, $scaleVal)
Parameters: This function accepts three parameters as shown in the above syntax and explained below:
$num_str1: This parameter is of string type and represents the left operand or one of the two numbers among which we want to perform the addition. This parameter is mandatory.
$num_str2: This parameter is of string type and represents the right operand or one of the two numbers among which we want to perform the addition. This parameter is mandatory.
$scaleVal: This parameter is of int type and is optional. This parameter tells the number of digits that will appear after the decimal in the result of addition. It’s default value is zero.
Return Value: This function returns the addition of the two numbers $num_str1 and $num_str2 as string.
Examples:
Input:  $num_str1 = 3, $num_str2 = 11.222
Output: 14
Since the parameter $scaleVal is not specified so
no digits after decimal is appeared in the 
result after addition.

Input:  $num_str1 = 3, $num_str2 = 11.222, $scaleVal = 4
Output: 14.2220

Below programs illustrate the bcadd() function in PHP :
Program 1:
<?php// PHP program to illustrate bcadd() function   // input numbers with arbitrary precision$num_str1 = "3";$num_str2 = "11.222";   // calculates the addition of// the two numbers when $scaleVal is// not specified$res = bcadd($num_str1, $num_str2);  echo $res;   ?>
Output:
14

Program 2:
<?php// PHP program to illustrate bcadd() function   // input numbers with arbitrary precision$num_str1 = "3";$num_str2 = "11.222";  // scale value$scaleVal = 4;   // calculates the addition of the two// numbers when $scaleVal is specified$res = bcadd($num_str1, $num_str2, $scaleVal);  echo $res;   ?>
Output:
14.2220

Reference:http://php.net/manual/en/function.bcadd.php
PHP-bc
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to fetch data from localserver database and display on HTML table using PHP ?
How to create admin login page using PHP?
PHP str_replace() Function
Different ways for passing data to view in Laravel
How to pass form variables from one page to other page in PHP ?
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 ?
How to insert spaces/tabs in text using HTML/CSS?
NLP | Filtering Insignificant Words - GeeksforGeeks

26 Feb, 2019
Many of the words used in the phrase are insignificant and hold no meaning. For example – English is a subject. Here, ‘English’ and ‘subject’ are the most significant words and ‘is’, ‘a’ are almost useless. English subject and subject English holds the same meaning even if we remove the insignificant words – (‘is’, ‘a’). Using the nltk, we can remove the insignificant words by looking at their part-of-speech tags. For that we have to decide which Part-Of-Speech tags are significant.
Code #1 : filter_insignificant() class to filter out the insignificant words
def filter_insignificant(chunk,                          tag_suffixes =['DT', 'CC']):        good = []          for word, tag in chunk:        ok = True              for suffix in tag_suffixes:        if tag.endswith(suffix):            ok = False            break          if ok:            good.append((word, tag))                  return good
filter_insignificant() checks whether that tag ends(for each tag) with the tag_suffixes by iterating over the tagged words in the chunk. The tagged word is skipped if tag ends with any of the tag_suffixes. Else if the tag is ok, the tagged word is appended to a new good chunk that is returned.
Code #2 : Using filter_insignificant() on a phrase
from transforms import filter_insignificant  print ("Significant words : \n",        filter_insignificant([('the', 'DT'),                              ('terrible', 'JJ'), ('movie', 'NN')]))
Output :
Significant words : 
[('terrible', 'JJ'), ('movie', 'NN')]

We can pass out different tag suffixes using filter_insignificant(). In the code below we are talking about pronouns and possessive words such as your, you, their and theirs are no good, but DT and CC words are ok. The tag suffixes would then be PRP and PRP$: Code #3 : Passing in our own tag suffixes using filter_insignificant()
from transforms import filter_insignificant  # choosing tag_suffixesprint ("Significant words : \n",        filter_insignificant([('your', 'PRP$'),                              ('book', 'NN'), ('is', 'VBZ'),                              ('great', 'JJ')],         tag_suffixes = ['PRP', 'PRP$']))
Output :
Significant words : 
[('book', 'NN'), ('is', 'VBZ'), ('great', 'JJ')]

Natural-language-processing
Python-nltk
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?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
Year() Function in MS Access

11 Sep, 2020
Year() : Function in Microsoft Access is used to return the year part of a given date.
Syntax :
Year (date)
Parameter : This method accepts one parameter as mentioned above and described below :
date : It is any variant, numeric expression, string expression, or any combination of these that can represent a date.
Returns : It Returns the year part of a specified date . If date contains Null, Null is returned.
Example-1 : Find Year from a specified Date :
SELECT Year(#05/17/2017#);

Output :
2017 

Example-2 : Find Year part of Today :
SELECT Year(Date());

Output :
2020

Example-3 : Find Year of Joining of the Employee :
SELECT Year(JoiningDate) FROM Employees;

Output :
1990
2004
1992

Note : There Should be JoiningDate column in Employees Database.Here, the Employees Database contains only 3 records.
DBMS-SQL
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to wrap text within Tkinter Text Box?

26 Mar, 2021
In this article, we will see that how can we wrap the text in the TKinter Text-Box using the Tkinter module Called textWrap Module. The textwrap module can be used for wrapping and formatting plain text. This module provides formatting of the text by adjusting the line breaks in the input paragraph.
Example 1:
Firstly We will import the Tkinter Library to the Code then we will declare it as a root for our Window then after declaring the size of the window we will call the function in the Tkinter called text() which will provide the Text box in that Window then declare the size of the Text Box then pack to the window or combined the textBox to the Window.
Below is the implementation:
Python3
# import tkinter module from tkinter import *          # Create Objectroot = Tk()    # Initialize tkinter window with dimensions 100x100             root.geometry('300x300')        text=Text(root,          width = 50,          height = 50,          padx = 10,           pady = 10)  # pack the text-Aera in the windowtext.pack()  root.mainloop()
Output:
Example 2:
Here We have the Problem like at the end of the box when we write something then it breaks the text to the new line. Generally to wrap the text we use the Text(wrap=word). Here is the basic idea about how we use the word=wrap
Use the wrap=WORD option. Here’s an example:
from tkinter import *
root = Tk()
t = Text(wrap=WORD)
t.pack()
root.mainloop()
Below is the implementation:
Python3
# import tkinter module from tkinter import *          # Create Objectroot = Tk()    # Initialize tkinter window with dimensions 100x100             root.geometry('300x300')        text=Text(root, width = 50, height = 50,           wrap = WORD, padx = 10, pady = 10)  # pack the text-Aera in the windowtext.pack()  root.mainloop()
Picked
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Introduction To PYTHON
Python OOPs Concepts
Python Classes and Objects
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
Python - Pytorch randn() method
sys.path in Python
Check if element exists in list in Python
Python - Pandas dataframe.append()
Python | Crop image using pillow

16 Oct, 2019
In this article, we will learn to crop an image using pillow library. Cropping an image means to select a rectangular region inside an image and removing everything outside the rectangle. To crop an image we make use of crop() method on image objects.
Syntax : IMG.crop(box_tuple)
Parameters :Image_path- Location of the imageIMG- Image to cropbox_tuple- [left, up, right, bottom] of the image to crop
Returns : An Image object which represents the cropped image.
Example 1:
# import Image modulefrom PIL import Image  # open the imageImage1 = Image.open('D:/cat.jpg')  # crop the imagecroppedIm = Image1.crop((130, 120, 200, 200))  # show the imagecroppedIm.show()
Input Image :
Output :
Example 2:
# import Image modulefrom PIL import Image  # open the imageImage1 = Image.open('D:/cat.jpg')  # crop the imagecroppedIm = Image1.crop((130, 50, 250, 150))  # show the imagecroppedIm.show()
Input Image :
Output :
nidhi_biet
Python-pil
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Enumerate() in Python
Different ways to create Pandas Dataframe
Read a file line by line in Python
How to Install PIP on Windows ?
Python String | replace()
Python OOPs Concepts
Python Classes and Objects
*args and **kwargs in Python
Introduction To PYTHON
Write an Efficient C Program to Reverse Bits of a Number

27 May, 2022
Given an unsigned integer, reverse all bits of it and return the number with reversed bits.
Input : n = 1Output : 2147483648  Explanation : On a machine with size of unsigned bit as 32. Reverse of 0....001 is 100....0.
Input : n = 2147483648Output : 1                            
Method1 – Simple: Loop through all the bits of an integer. If a bit at ith position is set in the i/p no. then set the bit at (NO_OF_BITS – 1) – i in o/p. Where NO_OF_BITS is number of bits present in the given number.  
Below is the implementation of the above approach:
c
// C code to implement the approach#include <stdio.h> // Function to reverse bits of numunsigned int reverseBits(unsigned int num){    unsigned int NO_OF_BITS = sizeof(num) * 8;    unsigned int reverse_num = 0;    int i;    for (i = 0; i < NO_OF_BITS; i++) {        if ((num & (1 << i)))            reverse_num |= 1 << ((NO_OF_BITS - 1) - i);    }    return reverse_num;} // Driver codeint main(){    unsigned int x = 2;    printf("%u", reverseBits(x));    getchar();}
1073741824
Time Complexity: O(Log n). Time complexity would be Log(num) as there are log(num) bits in a binary number “num” and we’re looping through all bits.Auxiliary space: O(1)
Method 2 – Standard: The idea is to keep putting set bits of the num in reverse_num until num becomes zero. After num becomes zero, shift the remaining bits of reverse_num. Let num is stored using 8 bits and num be 00000110. After the loop you will get reverse_num as 00000011. Now you need to left shift reverse_num 5 more times and you get the exact reverse 01100000. 
Below is the implementation of the above approach:
c
// C code to implement the approach#include <stdio.h> // Function to reverse bits of numunsigned int reverseBits(unsigned int num){    unsigned int count = sizeof(num) * 8 - 1;    unsigned int reverse_num = num;     num >>= 1;    while (num) {        reverse_num <<= 1;        reverse_num |= num & 1;        num >>= 1;        count--;    }    reverse_num <<= count;    return reverse_num;} // Driver's codeint main(){    unsigned int x = 1;    printf("%u", reverseBits(x));    getchar();}
2147483648
Time Complexity: O(logn) where n is the given numberAuxiliary space: O(1)
 Method 3 – Lookup Table: We can reverse the bits of a number in O(1) if we know the size of the number. We can implement it using look up table. Please refer Reverse bits using lookup table in O(1) time for details. 
Source : https://graphics.stanford.edu/~seander/bithacks.html
mohity
parthdhake
avtarkumar719
chandramauliguptach
Amazon
HCL
Nvidia
Qualcomm
Bit Magic
Mathematical
Amazon
Qualcomm
HCL
Nvidia
Mathematical
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to check which Azure account is logged in using PowerShell?

To check the logged-in Azure user account in the console using PowerShell, you can check the context of the Azure and for that Get-AZContext command is used.
Get-AzContext
If you are already logged in with multiple user accounts then there may be chances that there are multiple contexts available, to list all the available context, use the below command,
Get-AzContext -ListAvailable
You can choose the context using the Select-AZContext command.
How to extract each (English) word from a string using regular expression in Java?

The regular expression “[a-zA-Z]+” matches one or the English alphabet. Therefore, to extract each word in the given input string −
Compile the above expression of the compile() method of the Pattern class.
Compile the above expression of the compile() method of the Pattern class.
Get the Matcher object bypassing the required input string as a parameter to the matcher() method of the Pattern class.
Get the Matcher object bypassing the required input string as a parameter to the matcher() method of the Pattern class.
Finally, for each match get the matched characters by invoking the group() method.
Finally, for each match get the matched characters by invoking the group() method.
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class EachWordExample {
   public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter sample text: ");
      String data = sc.nextLine();
      String regex = "[a-zA-Z]+";
      //Creating a pattern object
      Pattern pattern = Pattern.compile(regex);
      //Creating a Matcher object
      Matcher matcher = pattern.matcher(data);
      System.out.println("Words in the given String: ");
      while(matcher.find()) {
         System.out.println(matcher.group()+" ");
      }
   }
}
Enter sample text:
Hello this is a sample text
Words in the given String:
Hello
this
is
a
sample
text
JavaScript RegExp - [a-z]

[a-z] matches any character from lowercase a through lowercase z.
Following example shows usage of RegExp expression.
<html>
   <head>
      <title>JavaScript RegExp</title>
   </head>
   
   <body>
      <script type = "text/javascript">
         var str = "first";
         var pattern = /[a-z]/g;

         var result = str.match(pattern);
         document.write("Test 1 - returned value : " +  result); 

         str = "Second";
         result = str.match(pattern);
         document.write("<br/>Test 2 - returned value : " +  result); 	 		 
      </script>
   </body>
</html>
Test 1 - returned value : f,i,r,s,t
Test 2 - returned value : e,c,o,n,d 


    25 Lectures 
     2.5 hours 

 Anadi Sharma

    74 Lectures 
     10 hours 

 Lets Kode It

    72 Lectures 
     4.5 hours 

 Frahaan Hussain

    70 Lectures 
     4.5 hours 

 Frahaan Hussain

    46 Lectures 
     6 hours 

 Eduonix Learning Solutions

    88 Lectures 
     14 hours 

 Eduonix Learning Solutions
 Print
 Add Notes
 Bookmark this page
java.util.regex.Matcher.replaceAll() Method 

The java.util.regex.Matcher.replaceAll(String replacement) method replaces every subsequence of the input sequence that matches the pattern with the given replacement string.
Following is the declaration for java.util.regex.Matcher.replaceAll(String replacement) method.
public String replaceAll(String replacement)

replacement − The replacement string.
replacement − The replacement string.
The string constructed by replacing each matching subsequence by the replacement string, substituting captured subsequences as needed.
The following example shows the usage of java.util.regex.Matcher.replaceAll(String replacement) method.
package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MatcherDemo {
   private static String REGEX = "dog";
   private static String INPUT = "The dog says meow " + "All dogs say meow.";
   private static String REPLACE = "cat";
   
   public static void main(String[] args) {
      Pattern pattern = Pattern.compile(REGEX);
      
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 
      INPUT = matcher.replaceAll(REPLACE);
      System.out.println(INPUT);
   }
}
Let us compile and run the above program, this will produce the following result −
The cat says meow All cats say meow.

 Print
 Add Notes
 Bookmark this page
Python program to split the even and odd elements into two different lists.

In this program we create a user input list and the elements are mixture of odd and even elements. Our task is to split these list into two list. One contains odd number of element and another is even number of elements.
Input: [1, 2, 3, 4, 5, 9, 8, 6]
Output
Even lists: [2, 4, 8, 6]
Odd lists: [1, 3, 5, 9]

Step 1 : create a user input list.
Step 2 : take two empty list one for odd and another for even.
Step 3 : then traverse each element in the main list.
Step 4 : every element is divided by 2, if remainder is 0 then it’s even number and add to the even list, otherwise its odd number and add to the odd list.

# Python code to split into even and odd lists 
# Funtion to split 
def splitevenodd(A): 
   evenlist = [] 
   oddlist = [] 
   for i in A: 
      if (i % 2 == 0): 
         evenlist.append(i) 
      else: 
         oddlist.append(i) 
   print("Even lists:", evenlist) 
   print("Odd lists:", oddlist) 
  
# Driver Code 
A=list()
n=int(input("Enter the size of the First List ::"))
print("Enter the Element of First  List ::")
for i in range(int(n)):
   k=int(input(""))
   A.append(k)
splitevenodd(A) 
Enter the size of the First List :: 8
Enter the Element of First  List ::
1
2
3
4
5
9
8
6
Even lists: [2, 4, 8, 6]
Odd lists: [1, 3, 5, 9]
Anonymous function in Dart Programming

A function without a name is known as an anonymous function. They behave in the exact same manner as a normal named function would. The only difference between the named and an anonymous function is how different they are in syntax.
Anonymous functions are used in Dart to form closures. An anonymous function contains a self-contained block of codes, also it can be passed as a parameter to another function as well.
(parameterList){
   // inner statement(s)
}
Now, let's consider a simple example of an anonymous function.
Consider the example shown below −
 Live Demo
void main() {
   var fruits = ["Apple", "Mango", "Banana", "Kiwi"];
   fruits.forEach((item) {
      print('${fruits.indexOf(item)}: $item');
   });
}
In the above example, we have an anonymous function with an untyped parameter named item.
0: Apple
1: Mango
2: Banana
3: Kiwi