code-rag-bench/online-tutorials huggingface dataset:
Barbell Graph Using Python networkx - GeeksforGeeks

03 Jan, 2021
Prerequisite: networkx
There are many kinds of definitions of the barbell graphs. The most commonly used one is an n-barbell graph which is a simple graph obtained by connecting two copies of a complete graph with n nodes. In this article, we are going to see how to use a barbell graph using python.
Examples of n-barbell graph:
Example 1:
If N=3 Nodes then the graph will be shown as figures:
Example 2:
If N=4 Nodes then the graph will be shown as figures:
1.Total number of nodes(In n-barbell graph):
The Total number of Nodes = 2*N
2.Total number of edges(In n-barbell graph):
Total number of edges = 2*number of edgesin complete graph + 1
=2*(n*(n-1)/2)+1 = n*(n-1) + 1
Properties:
The barbell graph contains cycles in it.The barbell graph is connected every two nodes have a path between them.It has a bridge between 2 complete graphs.Bridge may and may not have nodes in it.
The barbell graph contains cycles in it.
The barbell graph is connected every two nodes have a path between them.
It has a bridge between 2 complete graphs.
Bridge may and may not have nodes in it.
Barbell Graphs using Python:
It is realized in python using the barbell_graph(n, m) function of the networkx library and matplotlib library.
networkx library  Library in python used for realizing and analyzing different kinds of graphs(data structure) in python. For installation use this command:
pip install networkx
matplotlib library: Library in python used for realizing and analyzing different kinds of functions in python. For installation use this command:
pip install matplotlib
barbell_graph(n, m): It returns a Barbell Graph with two complete graphs of n nodes which are connected via m node bridge in between.
Approach:
Import networkx and matplotlib libraries.
Create a networkx graph object G using nx.barbell_graph(n, m) function as mentioned above.
Use nx.draw_networkx(G) function to print the graph.
Example 1:
Python
# import moduleimport networkx as nx  import matplotlib.pyplot as plt   # graph createdres = nx.barbell_graph(4, 2) nx.draw_networkx(res)
Barbell Graph in Python
Explanation: 
As we passed (4,2) as parameter’s to nx.barbell_graph() function is assigned a graph with 4 node clusters joined by a bridge of 2 nodes. And finally, we got the output as a view of graph G using the draw_networkx(G) function. 
Example 2:
Python3
import networkx as nx  import matplotlib.pyplot as plt  res = nx.barbell_graph(4, 0) nx.draw_networkx(res)
Output:
Graph
Python
Graph
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Floyd Warshall Algorithm | DP-16
Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph)
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Check whether a given graph is Bipartite or not
Ford-Fulkerson Algorithm for Maximum Flow Problem
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 Program to Find the Product of two Numbers Using Recursion

When it is required to find the product of two numbers using recursion technique, a simple if condition and recursion is used.
The recursion computes output of small bits of the bigger problem, and combines these bits to give the solution to the bigger problem.
Below is a demonstration for the same −
 Live Demo
def compute_product(val_1,val_2):
   if(val_1<val_2):
      return compute_product(val_2,val_1)
   elif(val_2!=0):
      return(val_1+compute_product(val_1,val_2-1))
   else:
      return 0
val_1 = int(input("Enter the first number... "))
val_2 = int(input("Enter the second number... "))
print("The computed product is: ")
print(compute_product(val_1,val_2))
Enter the first number... 112
Enter the second number... 3
The computed product is:
336
A method named ‘compute_product’ is defined, that takes two numeric values as paramters.
If the first value is less than second value, then the function is called again by swapping these parameters.
If the second value is 0, the function is called by passing first value, and subtracting ‘1’ from second value, and adding the first value to the result of the function.
Otherwise the function returns 0.
Outside the function, two numbers value are entered by the user.
The method is called by passing these two values.
The output is displayed on the console.
Animate CSS outline

To implement animation on outline property with CSS, you can try to run the following code:
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <style>
         div {
            width: 550px;
            height: 350px;
            outline: 1px solid blue;
            animation: myanim 3s infinite;
         }
         @keyframes myanim {
            50% {
               outline: 10px dashed orange;
            }
         }
      </style>
   </head>
   <body>
      <h1>CSS outline property</h1>
      <div> </div>
   </body>
</html>
Select records from MySQL NOW() -1 Day?

To get records from NOW()-1 Day, you can use the following syntax −
select *from yourTableName where yourColumnName >=now()-interval 1 day;
To understand the above syntax, let us first create a table. The query to create a table.
mysql> create table GetRecordsFromNow
   −> (
   −> YourDateTime datetime
   −> );
Query OK, 0 rows affected (1.76 sec)
Now insert some dates into the fields. The query to insert records are as follows −
mysql> insert into GetRecordsFromNow values(date_add(now(),interval 3 day));
Query OK, 1 row affected (0.28 sec)

mysql> insert into GetRecordsFromNow values(date_add(now(),interval -1 day));
Query OK, 1 row affected (0.11 sec)

mysql> insert into GetRecordsFromNow values(date_add(now(),interval -2 day));
Query OK, 1 row affected (0.14 sec)

mysql> insert into GetRecordsFromNow values(date_add(now(),interval -3 day));
Query OK, 1 row affected (0.09 sec)

mysql> insert into GetRecordsFromNow values(date_add(now(),interval -1 day));
Query OK, 1 row affected (0.08 sec)
Display all records with the help of select statement. The query is as follows −
mysql> select *from GetRecordsFromNow;
The following is the output −
+---------------------+
| YourDateTime        |
+---------------------+
| 2018-12-07 22:30:18 |
| 2018-12-03 22:30:31 |
| 2018-12-02 22:30:41 |
| 2018-12-01 22:30:56 |
| 2018-12-03 22:31:04 |
+---------------------+
5 rows in set (0.00 sec)
The following is the query to display records from now() -1 day −
mysql> select *from GetRecordsFromNow where YourDateTime >= now()-interval 1 day;
The following is the output −
+---------------------+
| YourDateTime        |
+---------------------+
| 2018-12-07 22:30:18 |
+---------------------+
1 row in set (0.04 sec)
PHP Object Serialization

A string representation of any object in the form of byte-stream is obtained by serialze() function in PHP. All property variables of object are contained in the string and methods are not saved. This string can be stored in any file.
To retrieve the object from the byte stream, there is unserialize() function. Definition of corresponding class must be available before calling unserialize()function.
First let us serialize an object of following class and store the string in a file.
<?php
class test1{
   private $name;
   function __construct($arg){
      $this->name=$arg;
   }
}
$obj1=new test1("Kiran");
$str=serialize($obj1);
$fd=fopen("obj.txt","w");
fwrite($fd, $str);
fclose($fd);
?>
In current folder, obj.txt is created. To unserialize, following code reconstructs object from the byte stream read from the given file
<?php
class test1{
   private $name;
   function __construct($arg){
      $this->name=$arg;
   }
   function getname(){
      return $this->name;
   }
}
$filename="obj.txt";
$fd=fopen("obj.txt","r");
$str=fread($fd, filesize($filename));
$obj=unserialize($str);
echo "name: ' . $obj->getname();
?>
Above code now returns name following output
name: Kiran
Java abstract Keyword

❮ Java Keywords

An abstract method belongs to an abstract class, and it does not have a body. 
The body is provided by the subclass:
// Code from filename: Main.java
// abstract classabstract class Main {
  public String fname = "John";
  public int age = 24;
  public abstract void study(); // abstract method
}

// Subclass (inherit from Main)
class Student extends Main {
  public int graduationYear = 2018;
  public void study() { // the body of the abstract method is provided here
    System.out.println("Studying all day long");
  }
}
// End code from filename: Main.java

// Code from filename: Second.java
class Second {
  public static void main(String[] args) {
    // create an object of the Student class (which inherits attributes and methods from Main)
    Student myObj = new Student();

    System.out.println("Name: " + myObj.fname);
    System.out.println("Age: " + myObj.age);
    System.out.println("Graduation Year: " + myObj.graduationYear);
    myObj.study(); // call abstract method
  }
}


Try it Yourself »

The abstract keyword is a non-access modifier, used for classes and methods.
Class: An abstract class is a restricted class that cannot be used to create objects (to access it, it must be inherited from another class).
Method: An abstract method can only be used in an abstract class, and it does not have a body. The body is provided by the subclass (inherited from).
Read more about modifiers in our Java Modifiers Tutorial.

❮ Java Keywords

We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
Define the number of columns in CSS Grid Layout

Use the grid-template-columns property to define the number of columns in CSS Grid Layout.
You can try to run the following code to set a number of columns. Here, 3 column grid is set:
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <style>
         .container {
            display: grid;
            background-color: yellow;
            grid-template-columns: auto auto auto;
            padding: 20px;
            grid-gap: 20px;
         }
         .container > div {
            background-color: blue;
            border: 2px solid gray;
            padding: 35px;
            font-size: 30px;
            text-align: center;
         }
      </style>
   </head>
   <body>
      <h1>Game Board</h1>
      <div class = "container">
         <div class = "ele1">1</div>
         <div class = "ele2">2</div>
         <div class = "ele3">3</div>
         <div class = "ele4">4</div>
         <div class = "ele5">5</div>
         <div class = "ele6">6</div>
      </div>
   </body>
</html>
Side by Side Line charts in R - GeeksforGeeks

21 Jul, 2021
In this article, we will discuss how to make side by side line chart in R Programming Language. 
Here we will use par() function to divide frames into grids.
Syntax: par(mfrow, mar, mgp, las)
Parameters:
mfrow: A numeric vector of length 2, which sets the rows and column in which frame has to be divided.
mar: A numeric vector of length 4, which sets the margin sizes in the following order: bottom, left, top, and right.
mgp: A numeric vector of length 3, which sets the axis label locations relative to the edge of the inner plot window.
las: A numeric value indicating the orientation of the tick mark labels and any other text added to a plot after its initialization.
Here, by changing row and column values, we can draw graphs in them. For drawing side-by-side plots we will keep row as 1 and column as the no. of plots required.
R
# Define data-set columnsx1 <- c(31,13,25,31,16)x2 <- c(12,23,43,12,22,45,32)   # set the plotting area into a 1*2 arraypar(mfrow = c(1, 2))      # Draw the two line chart using above datasetsplot(x1, type="o", col="green")plot(x2, type="o", col="blue")
Output:
Here we will use gridExtra contains a function called arrange() that is used to arrange plots as desired.
Syntax: grid.arrange(plot, nrow, ncol)
Parameter:
plot: ggplot2 plot which we want to arrange
nrow: Number of rows
ncol: Number of columns
Here, by changing nrow and ncol values, we can draw graphs in them. For drawing side-by-side plots we will keep nrow as 1 and ncol as the no. of plots required.
R
# Define data-set columnsx1 <- c(31,13,25,31,16)x2 <- c(12,23,43,12,22,45,32) x3 <- c(234,123,210)  label1 <- c('geek','geek-i-knack',            'technical-scipter',            'content-writer','problem-setter')  label2 <- c('sun','mon','tue',            'wed','thur','fri','sat')   label3 <- c('solved','attempted','unsolved')  # Create data frame using above data columndata1 <- data.frame(x1,label1)data2 <- data.frame(x2,label2)data3 <- data.frame(x3,label3)  # set the plotting area into a 1*3 arraypar(mfrow = c(1, 3))  # import library ggplot2 and gridExtralibrary(ggplot2)library(gridExtra)  # Draw the three line# chart using above datasetsplot1<-ggplot(data1,              aes(x=label1, y=x1, group=1)) +geom_line()+ geom_point()plot2<-ggplot(data2, aes(x=label2, y=x2, group=1)) +geom_line(linetype = "dashed")+ geom_point()  plot3<-ggplot(data3, aes(x=label3, y=x3, group=1)) +geom_line(color="green")+ geom_point()  # Use grid.arrange to put plots in columnsgrid.arrange(plot1, plot2, plot3, ncol=3)
Output:
Picked
R-Charts
R-Graphs
R-plots
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Change Color of Bars in Barchart using ggplot2 in R
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
How to filter R dataframe by multiple conditions?
R - if statement
Replace Specific Characters in String in R
How to import an Excel File into R ?
Filter multiple values on a string column in R using Dplyr
MySQL query to replace a column value

Let us first create a table −
mysql> create table DemoTable
(
   StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   Score int
);
Query OK, 0 rows affected (0.45 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable(Score) values(56);
Query OK, 1 row affected (0.24 sec)
mysql> insert into DemoTable(Score) values(78);
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable(Score) values(34);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable(Score) values(55);
Query OK, 1 row affected (0.37 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+-----------+-------+
| StudentId | Score |
+-----------+-------+
|         1 |    56 |
|         2 |    78 |
|         3 |    34 |
|         4 |    55 |
+-----------+-------+
4 rows in set (0.00 sec)
Following is the query to replace column value −
mysql> update DemoTable
   set Score=95 where StudentId=3;
Query OK, 1 row affected (0.12 sec)
Rows matched : 1 Changed : 1 Warnings : 0
Let us check the table records once again −
mysql> select *from DemoTable;
This will produce the following output −
+-----------+-------+
| StudentId | Score |
+-----------+-------+
|         1 |    56 |
|         2 |    78 |
|         3 |    95 |
|         4 |    55 |
+-----------+-------+
4 rows in set (0.00 sec)
Python | Check for None Tuple - GeeksforGeeks

21 Nov, 2019
Sometimes, while working with Python records, we can have a problem in which we need to filter out all the tuples which contains just None values. This can have possible application in Data Science domain. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using all() + generator expressionThe combination of above functionalities can be used to perform this particular task. In this we feed the logic of finding None using generator expression and checking for each element is handled by all().
# Python3 code to demonstrate working of# Check for None Tuple# using all() + generator expression  # initialize tupletest_tup = (None, None, None, None, None)  # printing original tupleprint("The original tuple : " + str(test_tup))  # Check for None Tuple# using all() + generator expressionres = all(ele is None for ele in test_tup)  # printing resultprint("Does tuple contain all None elements ? : " + str(res))
The original tuple : (None, None, None, None, None)
Does tuple contain all None elements ? : True

 
Method #2 : Using len() + count()The combination of above functions can be used to perform this task. In this, we just count the occurrences of None and equate to list length to check if all elements are None.
# Python3 code to demonstrate working of# Check for None Tuple# using len() + count()  # initialize tupletest_tup = (None, None, None, None, None)  # printing original tupleprint("The original tuple : " + str(test_tup))  # Check for None Tuple# using len() + count()res = len(test_tup) == test_tup.count(None)  # printing resultprint("Does tuple contain all None elements ? : " + str(res))
The original tuple : (None, None, None, None, None)
Does tuple contain all None elements ? : True

Python tuple-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Defaultdict in Python
Python | Split string into list of characters
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Weighted Job Scheduling

A list of different jobs is given, with the starting time, the ending time and profit of that job are also provided for those jobs. Our task is to find a subset of jobs, where the profit is maximum and no jobs are overlapping each other.
In this algorithm, we use a table to store the results of sub-problems and using the results of subproblems, the whole problem can be solved in a bottom-up manner.
The time complexity of this algorithm is O(n^2), but we can change it to O(n Log n) by using a binary search method to search con-conflicting jobs.
Input:
The start time, finish time and profit of some jobs as matrix form. And number of jobs. Here 4 jobs are present.
3   5  25
1   2  50
6  15  75
2 100 100

Output:
The maximum profit 150.
The job sequence is job 2, job 4, or job 2, job 1, job 3. for both cases the max profit is 150 here.
findMaxProfit(jobList, n)
Input: The job list and number of jobs.
Output: Maximum profit from the jobs.
Begin
   sort job list according to their ending time
   define table to store results
   table[0] := jobList[0].profit

   for i := 1 to n-1, do
      addProfit := jobList[i].profit
      nonConflict := find jobs which is not conflicting with others
      if any non-conflicting job found, then
         addProfit := addProfit + table[nonConflict]
      if addProfit > table[i - 1], then
         table[i] := addProfit
      else
         table[i] := table[i-1]
   done
   result := table[n-1]
   return result
End
#include <iostream>
#include <algorithm>
using namespace std;

struct Job {
   int start, end, profit;
};

bool comp(Job job1, Job job2) {
   return (job1.end < job2.end);
}

int nonConflictJob(Job jobList[], int i) {       //non conflicting job of jobList[i]
   for (int j=i-1; j>=0; j--) {
      if (jobList[j].end <= jobList[i-1].start)
         return j;
   }
   return -1;
}

int findMaxProfit(Job jobList[], int n) {
   sort(jobList, jobList+n, comp);           //sort jobs based on the ending time

   int *table = new int[n];       //create jon table
   table[0] = jobList[0].profit;

   for (int i=1; i<n; i++) {
      // Find profit including the current job
      int addProfit = jobList[i].profit;
      int l = nonConflictJob(jobList, i);
      if (l != -1)
         addProfit += table[l];
      table[i] = (addProfit>table[i-1])?addProfit:table[i-1];       //find maximum
   }

   int result = table[n-1];
   delete[] table;                 //clear table from memory
   return result;
}

int main() {
   Job jobList[] = {
      {3, 5, 25},
      {1, 2, 50},
      {6, 15, 75},
      {2, 100, 100}
   };

   int n = 4;
   cout << "The maximum profit: " << findMaxProfit(jobList, n);
   return 0;
}
The maximum profit: 150
Return Vowels in a string in JavaScript

We are required to write a JavaScript function that takes in a string that might contain some alphabets. The function should count and return the number of vowels that exists in the string.
Following is the code −
const str = 'this is a string';
const countVowels = (str = '') => {
   str = str.toLowerCase();
   const legend = 'aeiou';
   let count = 0;
   for(let i = 0; i < str.length; i++){
      const el = str[i];
      if(!legend.includes(el)){
         continue;
      };
      count++;
   };
   return count;
};
console.log(countVowels(str));
Following is the output on console −
4
How to fill NA values with previous values in an R data frame column?

To fill NA values with next and previous values, we can use na.locf function of zoo package with fromLast = TRUE. This is the situation of a column as shown below −
x
0
NA
NA
1
1
NA
0
1
The output after filling NA values with next and previous values will be −
x
0
0
0
1
1
1
0
1
Consider the below data frame −
 Live Demo
x1<-sample(c(NA,rpois(2,1)),20,replace=TRUE)
x2<-sample(c(NA,rpois(2,5)),20,replace=TRUE)
df1<-data.frame(x1,x2)
df1
   x1  x2
1  0    1
2  NA   6
3  NA   NA
4  1    6
5  1    NA
6  NA   NA
7  0    6
8  1    1
9  NA   6
10 1    NA
11 1    6
12 NA   NA
13 NA   6
14 1    NA
15 1    1
16 NA   6
17 NA   6
18 NA   NA
19 1    NA
20 1    6
Loading zoo package and replacing NA values with previous values in df1 −
library(zoo)
na.locf(na.locf(df1),fromLast=TRUE)
   x1 x2
1  0  1
2  0  6
3  0  6
4  1  6
5  1  6
6  1  6
7  0  6
8  1  1
9  1  6
10 1  6
11 1  6
12 1  6
13 1  6
14 1  6
15 1  1
16 1  6
17 1  6
18 1  6
19 1  6
20 1  6
 Live Demo
y1<-sample(c(NA,rnorm(2)),20,replace=TRUE)
y2<-sample(c(NA,rnorm(2)),20,replace=TRUE)
df2<-data.frame(y1,y2)
df2
        y1       y2
1  -0.4569616   NA
2   NA         -1.014162
3   NA         -1.014162
4  -0.4569616  -1.014162
5  -0.4569616  NA
6   0.2828478  1.282601
7  -0.4569616  NA
8   0.2828478  NA
9   0.2828478  -1.014162
10  NA          1.282601
11  0.2828478  -1.014162
12 -0.4569616   1.282601
13  0.2828478  -1.014162
14  NA         -1.014162
15  0.2828478  -1.014162
16  NA         NA
17 -0.4569616  NA
18 -0.4569616  -1.014162
19  0.2828478  -1.014162
20  NA         -1.014162
Replacing NA values with previous values in df2 −
na.locf(na.locf(df2),fromLast=TRUE)
        y1         y2
2  -0.4569616   -1.014162
3  -0.4569616   -1.014162
4  -0.4569616   -1.014162
5  -0.4569616   -1.014162
6   0.2828478    1.282601
7  -0.4569616    1.282601
8   0.2828478    1.282601
9   0.2828478   -1.014162
10  0.2828478    1.282601
11  0.2828478   -1.014162
12 -0.4569616    1.282601
13  0.2828478   -1.014162
14  0.2828478   -1.014162
15  0.2828478   -1.014162
16  0.2828478   -1.014162
17 -0.4569616   -1.014162
18 -0.4569616   -1.014162
19  0.2828478   -1.014162
20  0.2828478   -1.014162
Fetch a specific column value (name) in MySQL

To fetch a specific column value, use LIKE clause. Let us first create a table −
mysql> create table DemoTable1809
     (
     Name varchar(20)
     );
Query OK, 0 rows affected (0.00 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1809 values('John');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1809 values('David');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1809 values('Mike');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1809 values('Johnson');
Query OK, 1 row affected (0.00 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1809;
This will produce the following output −
+---------+
| Name    |
+---------+
| John    |
| David   |
| Mike    |
| Johnson |
+---------+
4 rows in set (0.00 sec)
Here is the query to fetch a specific value
mysql> select * from DemoTable1809 where Name LIKE 'Johnson%';
This will produce the following output −
+---------+
| Name    |
+---------+
| Johnson |
+---------+
1 row in set (0.00 sec)
Angular forms NgModelGroup Directive - GeeksforGeeks

04 Jul, 2021
In this article, we are going to see what is NgModelGroup in Angular 10 and how to use it. The NgModelGroup is used to create a top-level form group Instance, and it binds the form to the given form value.
Syntax:
<div ngModelGroup="name"></div>
NgModule: Module used by NgModelGroup is:
FormsModule
Selectors:
[ngModelGroup]
 
Approach: 
Create an Angular app to be use.d
In app.component.ts make an object that contains value for the input.
In app.component.html use ngModelGroup to get values.
Serve the angular app using ng serve to see the output.
Example:
app.component.ts
import { Component, Inject } from '@angular/core';    @Component({    selector: 'app-root',    templateUrl: './app.component.html',    styleUrls: [ './app.component.css' ]  })  export class AppComponent  {    gfg:any;    setValue() {    this.gfg = {first: 'Geeky', email: 'abc@gfg.com'};  }}
app.component.html
<br><form #f="ngForm">  <div ngModelGroup="gfg" #nameCtrl="ngModelGroup">    Name: <input name="first" [ngModel]="gfg.first" >    Email: <input name="email" [ngModel]="gfg.email" >  </div> </form><br><br>  <button (click)="setValue()">Set value</button>
Output:
Reference: https://angular.io/api/forms/NgModelGroup
Angular10
AngularJS-Directives
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Angular PrimeNG Dropdown Component
How to make a Bootstrap Modal Popup in Angular 9/8 ?
Angular 10 (blur) Event
How to create module with Routing in Angular 9 ?
How to setup 404 page in angular routing ?
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
MySQL - Create Database

You would need special privileges to create or to delete a MySQL database. So assuming you have access to the root user, you can create any database using the mysql mysqladmin binary.
Here is a simple example to create a database called TUTORIALS −
[root@host]# mysqladmin -u root -p create TUTORIALS
Enter password:******

This will create a MySQL database called TUTORIALS.
PHP uses mysqli query() or mysql_query() function to create or delete a MySQL database. This function takes two parameters and returns TRUE on success or FALSE on failure.
$mysqli->query($sql,$resultmode)

$sql
Required - SQL query to create a MySQL database.
$resultmode
Optional - Either the constant MYSQLI_USE_RESULT or MYSQLI_STORE_RESULT depending on the desired behavior. By default, MYSQLI_STORE_RESULT is used.
Try the following example to create a database −
Copy and paste the following example as mysql_example.php −
<html>
   <head><title>Creating MySQL Database</title></head>
   <body>
      <?php
         $dbhost = 'localhost';
         $dbuser = 'root';
         $dbpass = 'root@123';
         $mysqli = new mysqli($dbhost, $dbuser, $dbpass);
         
         if($mysqli->connect_errno ) {
            printf("Connect failed: %s<br />", $mysqli->connect_error);
            exit();
         }
         printf('Connected successfully.<br />');

         if ($mysqli->query("CREATE DATABASE TUTORIALS")) {
            printf("Database TUTORIALS created successfully.<br />");
         }
         if ($mysqli->errno) {
            printf("Could not create database: %s<br />", $mysqli->error);
         }
         $mysqli->close();
      ?>
   </body>
</html>
Access the mysql_example.php deployed on apache web server and verify the output.
Connected successfully.
Database TUTORIALS created successfully.


    31 Lectures 
     6 hours 

 Eduonix Learning Solutions

    84 Lectures 
     5.5 hours 

 Frahaan Hussain

    6 Lectures 
     3.5 hours 

 DATAhill Solutions Srinivas Reddy

    60 Lectures 
     10 hours 

 Vijay Kumar Parvatha Reddy

    10 Lectures 
     1 hours 

 Harshit Srivastava

    25 Lectures 
     4 hours 

 Trevoir Williams
 Print
 Add Notes
 Bookmark this page
Create a Pandas Dataframe by appending one row at a time

To create a Pandas DataFrame by appending one row at a time, we can iterate in a range and add multiple columns data in it.
Create a two-dimensional, size-mutable, potentially heterogeneous tabular data, df.
Create a two-dimensional, size-mutable, potentially heterogeneous tabular data, df.
Print the input DataFrame.
Print the input DataFrame.
Iterate in a range of 10.
Iterate in a range of 10.
Assign values at different index with numbers.
Assign values at different index with numbers.
Print the created DataFrame.
Print the created DataFrame.
 Live Demo
import pandas as pd
import random

df = pd.DataFrame(
   {
      "x": [],
      "y": [],
      "z": []
   }
)
print "Input DataFrame:\n", df

for i in range(10):
   df.loc[i] = [i, random.randint(1, 10), random.randint(1, 10)]

print "After appending row at a time: \n", df
Input DataFrame:
Empty DataFrame
Columns: [x, y, z]
Index: []

After appending row at a time:
     x    y    z
0  0.0   9.0   3.0
1  1.0   2.0   1.0
2  2.0   5.0   5.0
3  3.0   7.0   1.0
4  4.0   2.0  10.0
5  5.0   5.0   4.0
6  6.0   1.0   3.0
7  7.0   4.0   2.0
8  8.0   2.0   2.0
9  9.0  10.0   8.0
How to iterate over a C# tuple?

Firstly, declare a tuple and add values −
Tuple <int, string> tuple = new Tuple<int, string>(100, "Tom");
With C#, to iterate over a tuple, you can go for individual elements −
tuple.Item1 // first item
tuple.Item2 // second item
To display the complete tuple, just use:
// display entire tuple
Console.WriteLine(tuple);
Let us see the complete code −
using System;
using System.Threading;

namespace Demo {
   class Program {

      static void Main(string[] args) {

         Tuple <int, string> tuple = new Tuple<int, string>(100, "Tom");

         if (tuple.Item1 == 100) {
            Console.WriteLine(tuple.Item1);
         }
         if (tuple.Item2 == "Tom") {
            Console.WriteLine(tuple.Item2);
         }

         // display entire tuple
         Console.WriteLine(tuple);
      }
   }
}
Docker - Working of Kubernetes

In this chapter, we will see how to install Kubenetes via kubeadm. This is a tool which helps in the installation of Kubernetes. Let’s go step by step and learn how to install Kubernetes.
Step 1 − Ensure that the Ubuntu server version you are working on is 16.04.
Step 2 − Ensure that you generate a ssh key which can be used for ssh login. You can do this using the following command.
ssh-keygen 

This will generate a key in your home folder as shown below.
Step 3 − Next, depending on the version of Ubuntu you have, you will need to add the relevant site to the docker.list for the apt package manager, so that it will be able to detect the Kubernetes packages from the kubernetes site and download them accordingly.
We can do it using the following commands.
curl -s https://packages.cloud.google.com/apt/doc/apt-key.gpg | apt-key add -  
echo "deb http://apt.kubernetes.io/ kubernetes-xenial main” | sudo tee /etc/apt/sources.list.d/docker.list

Step 4 − We then issue an apt-get update to ensure all packages are downloaded on the Ubuntu server.
Step 5 − Install the Docker package as detailed in the earlier chapters.
Step 6 − Now it’s time to install kubernetes by installing the following packages −
apt-get install –y kubelet kubeadm kubectl kubernetes-cni

Step 7 − Once all kubernetes packages are downloaded, it’s time to start the kubernetes controller using the following command −
kubeadm init 

Once done, you will get a successful message that the master is up and running and nodes can now join the cluster.

    70 Lectures 
     12 hours 

 Anshul Chauhan

    41 Lectures 
     5 hours 

 AR Shankar

    31 Lectures 
     3 hours 

 Abhilash Nelson

    15 Lectures 
     2 hours 

 Harshit Srivastava, Pranjal Srivastava

    33 Lectures 
     4 hours 

 Mumshad Mannambeth

    13 Lectures 
     53 mins

 Musab Zayadneh
 Print
 Add Notes
 Bookmark this page
Cycle Sort

Cycle Sort is an in-place sorting algorithm. It is also a comparison based sort and efficient for any other in-place sorting technique. It finds the minimum number of memory write to perform the sorting tasks.
Time Complexity: O(n^2)
Space Complexity: O(1)
Input:
A list of unsorted data: 23 63 98 74 20 14 36 45 99 78
Output:
Array before Sorting: 23 63 98 74 20 14 36 45 99 78
Array after Sorting: 14 20 23 36 45 63 74 78 98 99
cycleSort(array, size)
Input − An array of data, and the total number in the array
Output − The sorted Array
Begin
   for start := 0 to n – 2 do
      key := array[start]
      location := start
      for i := start + 1 to n-1 do
         if array[i] < key then
            location:=location +1
      done

      if location = start then
         ignore lower part, go for next iteration
      while key = array[location] do
         location := location +1
      done

      if location ≠ start then
         swap array[location] with key
      while location ≠ start do
         location := start
         for i := start + 1 to n-1 do
            if array[i] < key then
               location:=location +1
         done

         while key = array[location]
            location := location +1
         if key ≠ array[location]
            swap array[location] and key
      done
   done
End
#include<iostream>
using namespace std;

void swapping(int &a, int &b) {     //swap the content of a and b
   int temp;
   temp = a;
   a = b;
   b = temp;
}

void display(int *array, int size) {
   for(int i = 0; i<size; i++)
      cout << array[i] << " ";
   cout << endl;
}

void cycleSort(int *array, int n) {
   for(int start = 0; start<n-1; start++) {    //put array element in the correct place
      int key = array[start];
      int location = start;

      for(int i = start+1; i<n; i++) { //count smaller element in the right side of key
         if(array[i] < key)
            location++;
      }

      if(location == start) //when it is in correct place go for next iteration
         continue;
      while(key == array[location]) //if same data is found increase location
         location++;
      if(location != start)
         swapping(array[location], key);

      while(location != start) {
         location = start;

         for(int i = start+1; i<n; i++) { //location to put element
            if(array[i] < key)
               location++;
         }

         while(key == array[location]) //if same data is found increase location
            location++;
         if(key != array[location])
            swapping(key, array[location]);
      }
   }
}

int main() {
   int n;
   cout << "Enter the number of elements: ";
   cin >> n;
   int arr[n]; //create an array with given number of elements
   cout << "Enter elements:" << endl;

   for(int i = 0; i<n; i++) {
      cin >> arr[i];
   }

   cout << "Array before Sorting: ";
   display(arr, n);
   cycleSort(arr, n);
   cout << "Array after Sorting: ";
   display(arr, n);
}
Enter the number of elements: 10
Enter elements:
23 63 98 74 20 14 36 45 99 78
Array before Sorting: 23 63 98 74 20 14 36 45 99 78
Array after Sorting: 14 20 23 36 45 63 74 78 98 99
C++ Stack Library - top() Function

The C++ function std::stack::top() returns top element of the stack. This is the element which is removed after performing pop operation.
Following is the declaration for std::stack::top() function form std::stack header.
value_type& top();
const value_type& top() const;

reference& top();
const_reference& top() const;

None
Returns the top element of the stack.
Depends upon underlying container.
Constant i.e. O(1)
The following example shows the usage of std::stack::top() function.
#include <iostream>
#include <stack>

using namespace std;

int main(void) {
   stack<int> s;

   for (int i = 0; i < 5; ++i)
      s.emplace(i + 1);

   while (!s.empty()) {
      cout << s.top() << endl;
      s.pop();
   }

   return 0;
}
Let us compile and run the above program, this will produce the following result −
Stack contents are
5
4
3
2
1

 Print
 Add Notes
 Bookmark this page
Functions in C - GeeksQuiz

21 Oct, 2021
In C, parameters are always  
Passed by value 
Passed by reference 
Non-pointer variables are passed by value and pointers are passed by reference 
Passed by value result 
In C, function parameters are always passed by value. Pass-by-reference is simulated in C by explicitly passing pointer values. 
Which of the following is true about return type of functions in C? 
Functions can return any type 
Functions can return any type except array and functions 
Functions can return any type except array, functions and union 
Functions can return any type except array, functions, function pointer and union 
In C, functions can return any type except arrays and functions. We can get around this limitation by returning pointer to array or pointer to function. 
struct
{
   char *name;
   int (*funcptr)();
}
symtab[] = {
   "func", func,
   "anotherfunc", anotherfunc,
};
int fun(int n);

int main()
{
    // ptr is a pointer to function fun()
    int (*ptr)(int ) = fun;

    // fun() called using pointer 
    (*ptr)(3);
    return 0;
}

int fun(int n)
{
  for(;n > 0; n--)
    printf("GeeksQuiz ");
}

extern int sum(int x, int y, int z)
{
    return (x + y + z);
}
static int sum(int x, int y, int z)
{
    return (x + y + z);
}
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Comments
Old Comments
Must Do Coding Questions for Product Based Companies
How to set background images in ReactJS ?
Microsoft Interview Experience for Internship (Via Engage)
Difference between var, let and const keywords in JavaScript
Array of Objects in C++ with Examples
How to Alter Multiple Columns at Once in SQL Server?
How to Replace Values in Column Based on Condition in Pandas?
How to Fix: SyntaxError: positional argument follows keyword argument in Python
C Program to read contents of Whole File
How to Replace Values in a List in Python?
Collectors.joining() method in Java 8

The joining() method of the Collectors class in Java 8 returns a Collector that concatenates the input elements into a String, in encounter order.
The syntax is as follows −
public static Collector<CharSequence,?,String> joining()
Here, CharSequence is a readable sequence of char values, whereas String class represents character strings.
To work with Collectors class in Java, import the following package −
import java.util.stream.Collectors;
The following is an example to implement Collectors.joining() method in Java 8 −
 Live Demo
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.Arrays;
import java.util.List;

public class Demo {
   public static void main(String[] args) {
      List<Character> list = Arrays.asList('D', 'e', 'm', 'o');
      String str = list.stream().map(String::valueOf).collect(Collectors.joining());
      System.out.println("Concatenated = "+str);
   }
}
Concatenated = Demo
Microprocessor - 8086 Addressing Modes

The different ways in which a source operand is denoted in an instruction is known as addressing modes. There are 8 different addressing modes in 8086 programming −
The addressing mode in which the data operand is a part of the instruction itself is known as immediate addressing mode.
MOV CX, 4929 H, ADD AX, 2387 H,  MOV AL, FFH 

It means that the register is the source of an operand for an instruction.
MOV CX, AX   ; copies the contents of the 16-bit AX register into  
             ; the 16-bit CX register),  
ADD BX, AX 

The addressing mode in which the effective address of the memory location is written directly in the instruction.
MOV AX, [1592H], MOV AL, [0300H]

This addressing mode allows data to be addressed at any memory location through an offset address held in any of the following registers: BP, BX, DI & SI.
MOV AX, [BX]  ; Suppose the register BX contains 4895H, then the contents  
              ; 4895H are moved to AX 
ADD CX, {BX} 

In this addressing mode, the offset address of the operand is given by the sum of contents of the BX/BP registers and 8-bit/16-bit displacement.
MOV DX, [BX+04], ADD CL, [BX+08]

In this addressing mode, the operands offset address is found by adding the contents of SI or DI register and 8-bit/16-bit displacements.
MOV BX, [SI+16], ADD AL, [DI+16] 

In this addressing mode, the offset address of the operand is computed by summing the base register to the contents of an Index register.
ADD CX, [AX+SI], MOV AX, [AX+DI] 

In this addressing mode, the operands offset is computed by adding the base register contents. An Index registers contents and 8 or 16-bit displacement.
MOV AX, [BX+DI+08], ADD CX, [BX+SI+16] 


    50 Lectures 
     6.5 hours 

 Gowthami Swarna
 Print
 Add Notes
 Bookmark this page
How to throw an exception from a static block in Java? 


A static block is a set of statements, which will be executed by the JVM before the execution of the main() method. At the time of class loading if we want to perform any activity we have to define that activity inside a static block because this block executes at the time of class loading.
A static block can throw only a RunTimeException, or there should be a try and catch block to catch a checked exception.
A static block occurs when a class is loaded by a class loader. The code can either come in the form of a static block or as a call to a static method for initializing a static data member.
In both cases, checked exceptions are not allowed by the compiler. When an unchecked exception occurs, it is wrapped by the ExceptionInInitializerError, which is then thrown in the context of the thread that triggered the class loading.
Trying to throw a checked exception from a static block is also not possible. We can have a try and catch block in a static block where a checked exception may be thrown from the try block but we have to resolve it within the catch block. We can’t propagate it further using a throw keyword.
Live Demo
public class StaticBlockException {
   static int i, j;
   static {
      System.out.println("In the static block");
      try {
         i = 0;
         j = 10/i;
      } catch(Exception e){
         System.out.println("Exception while initializing" + e.getMessage());
         throw new RuntimeException(e.getMessage());
      }
   }
   public static void main(String args[]) {
      StaticBlockException sbe = new StaticBlockException();
      System.out.println("In the main() method");
      System.out.println("Value of i is : "+i);
      System.out.println("Value of j is : "+ j);
   }
}
In the static block
Exception while initializing/ by zero
Exception in thread "main" java.lang.ExceptionInInitializerError
Caused by: java.lang.RuntimeException: / by zero
        at StaticBlockException.(StaticBlockException.java:10)
Program to add two binary strings in C++

Given two strings with binary number, we have to find the result obtained by adding those two binary strings and return the result as a binary string.
Binary numbers are those numbers which are expressed either as 0 or 1. While adding 2 binary numbers there is binary addition rule which is to be taken care of.
0+0 → 0
0+1 → 1
1+0 → 1
1+1 → 0, carry 1
Input 
str1 = {“11”}, str2 = {“1”}
Output 
“100”
Input 
str1 = {“110”}, str2 = {“1”}
Output 
“111”
Traverse both the string from last
Traverse both the string from last
Add the binary of two numbers
Add the binary of two numbers
If there are two 1’s then make it zero and carry 1.
If there are two 1’s then make it zero and carry 1.
Return the result.
Return the result.
Start
Step 1→ declare function to add two strings
   string add(string a, string b)
      set string result = ""
      set int temp = 0
      set int size_a = a.size() – 1
      set int size_b = b.size() – 1
      While (size_a >= 0 || size_b >= 0 || temp == 1)
         Set temp += ((size_a >= 0)? a[size_a] - '0': 0)
         Set temp += ((size_b >= 0)? b[size_b] - '0': 0)
         Calculate result = char(temp % 2 + '0') + result
         Set temp /= 2
         Set size_a—
         Set size_b—
      End
      return result
Step 2→ In main()
   Declare string a = "10101", b="11100"
   Call add(a, b)
Stop
 Live Demo
#include<bits/stdc++.h>
using namespace std;
//function to add two strings
string add(string a, string b){
   string result = "";
   int temp = 0;
   int size_a = a.size() - 1;
   int size_b = b.size() - 1;
   while (size_a >= 0 || size_b >= 0 || temp == 1){
      temp += ((size_a >= 0)? a[size_a] - '0': 0);
      temp += ((size_b >= 0)? b[size_b] - '0': 0);
      result = char(temp % 2 + '0') + result;
      temp /= 2;
      size_a--; size_b--;
   }
   return result;
}
int main(){
   string a = "10101", b="11100";
   cout<<"sum of strings are : "<<add(a, b);
   return 0;
}
If run the above code it will generate the following output −
sum of strings are : 110001
\mkern - Tex Command

\mkern - gives horizontal space.
{ \mkern <dimen>}
\mkern command is used to create horizontal space.

ab

ab


a\mkern18mu b

ab


a\mkern18pt b

ab



ab

ab


ab
a\mkern18mu b

ab


a\mkern18mu b
a\mkern18pt b

ab


a\mkern18pt b

    14 Lectures 
     52 mins

 Ashraf Said

    11 Lectures 
     1 hours 

 Ashraf Said

    9 Lectures 
     1 hours 

 Emenwa Global, Ejike IfeanyiChukwu

    29 Lectures 
     2.5 hours 

 Mohammad Nauman

    14 Lectures 
     1 hours 

 Daniel Stern

    15 Lectures 
     47 mins

 Nishant Kumar
 Print
 Add Notes
 Bookmark this page
Tracking bird migration using Python-3

In some Research works, Researchers uses GPS modules to track the animal behavior. They can track how they are travelling to different places in different time of a year etc.
In this example we use that kind of dataset to get an idea, how Birds are moving in different places. In this dataset there are the location details from GPS module are stored. The complete dataset is in CSV form. In that file, there are different fields. The first one is Bird Id, then date_time, Latitude, longitude and speed.
For this Task, we need some modules that can be used in Python codes.
We are using matplotlib, pandas, and cartopy modules. To install them into the Anaconda, please follow these commands. These will install some other important modules when it needs.
conda install -c conda-forge matplotlib
conda install -c anaconda pandas
conda install -c scitools/label/archive cartopy

At first we will plot the location using the latitude and longitude values. There are two birds in the dataset, so using two different colors, we can visualize the tracking locations
import pandas as pd
from matplotlib import pyplot as plt
df = pd.read_csv('bird_tracking.csv')
cr = df.groupby('bird_id').groups
cr_groups = df.groupby('bird_id')
group_list = []
for group in cr:
   group_list.append(group)
plt.figure(figsize=(7, 7))
#Create graph from dataset using the first group of cranes
for group in group_list:
   x,y = cr_groups.get_group(group).longitude, cr_groups.get_group(group).latitude
   plt.plot(x,y, marker='o', markersize=2)
plt.show()
Now we can plot this tracking results on the actual Geographical Map to visualize the exact way, which is used by those birds.
import pandas as pd
import cartopy.crs as ccrs
import cartopy.feature as cfeature
import matplotlib.pyplot as plt
df = pd.read_csv("bird_tracking.csv")
bird_id = pd.unique(birddata.bird_id)
# Setup the projection to display the details into map
projection = ccrs.Mercator()
plt.figure(figsize=(7,7))
axes = plt.axes(projection=projection)
axes.set_extent((-30.0, 25.0, 50.0, 10.0))
axes.add_feature(cfeature.LAND)
axes.add_feature(cfeature.OCEAN)
axes.add_feature(cfeature.COASTLINE)
axes.add_feature(cfeature.BORDERS, linestyle=':')
for id in bird_id:
   index = df['bird_id'] == id
   x = df.longitude[index]
   y = df.latitude[index]
   axes.plot(x,y,'.', transform=ccrs.Geodetic(), label=id)
plt.legend(loc="lower left")
plt.show()