code-rag-bench/online-tutorials huggingface dataset:
Creating a Path Graph Using Networkx in Python - GeeksforGeeks

29 Apr, 2021
A path graph is a connected graph denoted by Pn if it contains n nodes. Nodes are connected in form of a straight line in a path graph. Here we will discuss how networkx module can be used to generate one using its inbuilt path_graph() function.
The number of nodes in a path graph(Pn) is N.
The number of edges in a path graph(Pn) is N-1.
The diameter of the path graph(Pn) i.e maximum distance between any pair of vertices is N-1 which is between 1st and last node.
The chromatic number of Path Graph is 2.
Nodes are assigned labels from 0 to N-1
Terminal vertices have degree 1 and every other vertex has degree 2.
A path graph is a connected graph.
Path graph contains no cycle in it.
Although the path graph is connected but the removal of any edge will make it unconnected as no cycle is there in Path Graph.
It is a Planar Graph.
We will use the networkx module for realizing a Path graph. It comes with an inbuilt function networkx.path_graph() and can be illustrated using the networkx.draw() method. This method is straightforward method of creating a desired path graph using appropriate parameters. 
Syntax:  path_graph(n, create_using=None)
Parameter:
n: Number of nodes we want in path graph.
create_using: We can simply pass None or pass nx.DiGraph() as a value to this argument sending nx.Digraph() will lead to creation of a directed path graph.
Approach:
Import module
Create path graph object using path_graph() function as mentioned above.
Pass appropriate parameters to the functions
Display plot
Program:
Python3
# import required moduleimport networkx as nx # create objectG = nx.path_graph(5, create_using=nx.DiGraph()) # illustrate graphnx.draw(G, node_color='green')
Output:
simmytarika5
Graph
Python
Graph
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Topological Sorting
Bellman–Ford Algorithm | DP-23
Detect Cycle in a Directed Graph
Floyd Warshall Algorithm | DP-16
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
int(5) vs. int(10) in MySQL?

The value in the parentheses is used to display only the width and sets the zerofill. The width is 5 for int(5), whereas 10 for int(10). Let us see another example with a different width value set for int.
Let us first create a table. Here, we have set the int to int(11) and int(13). The following is the query to create a table −
mysql> create table intVsIntAnyThingDemo
−> (
−> Number1 int(11) unsigned zerofill,
−> Number int(13) unsigned zerofill
−> );
Query OK, 0 rows affected (1.17 sec)
Now you can insert record in the table with the help of insert command. The query is as follows −
mysql> insert into intVsIntAnyThingDemo values(12345,6789);
Query OK, 1 row affected (0.44 sec)

mysql> insert into intVsIntAnyThingDemo values(3,2);
Query OK, 1 row affected (0.20 sec)

mysql> insert into intVsIntAnyThingDemo values(12,89);
Query OK, 1 row affected (0.15 sec)

mysql> insert into intVsIntAnyThingDemo values(123,6789);
Query OK, 1 row affected (0.17 sec)

mysql> insert into intVsIntAnyThingDemo values(1234,6789);
Query OK, 1 row affected (0.14 sec)
Display all records with the help of select statement. The query is as follows −
mysql> select *from intVsIntAnyThingDemo;
The following is the output displaying zero fill for the total width set for int −
+-------------+---------------+
| Number1     | Number        |
+-------------+---------------+
| 00000012345 | 0000000006789 |
| 00000000003 | 0000000000002 |
| 00000000012 | 0000000000089 |
| 00000000123 | 0000000006789 |
| 00000001234 | 0000000006789 |
+-------------+---------------+
5 rows in set (0.00 sec)
R Tutorial

R is a programming language.
R is often used for statistical computing and graphical presentation to analyze 
  and visualize data.
With our "Try it Yourself" editor, you can edit R code and view the result.
How to output some text, and how to do a simple calculation in R:
Result:
How you can use R to easily create a graph with 
numbers from 1 to 10 on both the x and y axis:
Result:
We recommend reading this tutorial, in the sequence listed in the left menu.
Insert the missing part of the code below to output "Hello World".
Hello World

Start the Exercise
Learn by examples! This tutorial supplements all explanations with clarifying examples.

See All R Examples
Learn by taking a quiz! This quiz will give you a signal of how much you know about R.
Take the R Quiz
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
How to put data of any size in the EEPROM using Arduino?

Arduino Uno has 1 kB of EEPROM storage. EEPROM is a type of non-volatile memory, i.e., its contents are preserved even after power-down. Therefore, it can be used to store data that you want to be unchanged across power cycles. Configurations or settings are examples of such data.
In this article, we will see how to put data of any size (not just a byte) in the EEPROM. We will be walking through an inbuilt example in Arduino. The EEPROM examples can be accessed from: File → Examples → EEPROM.
We will look at the eeprom_put example. The main function of interest is EEPROM.put(). It takes two arguments, the starting address from which to start writing/ updating data, and the data to be written (which can be of a primitive type, like float, or a custom struct). Examples of other primitive data types are short, int, long, char, double, etc. The .put() function behaves like the .update() function, i.e., it writes to the EEPROM only if the new value to be written is different from the existing value stored in that memory location.
We begin with the inclusion of the library.
#include <EEPROM.h>
Next, we a struct is defined, which contains two floats, and a character array.
struct MyObject {
   float field1;
   byte field2;
   char name[10];
};
Within the Setup, we first initialize Serial. Next, we initialize a float, and write it to the beginning of the EEPROM (address = 0). We then advance the address variable by the size of the float (using the sizeof() function), and store a struct (using the structure defined earlier).
void setup() {

   Serial.begin(9600);
   while (!Serial) {
      ; // wait for serial port to connect. Needed for native USB port only
   }

   float f = 123.456f; //Variable to store in EEPROM.
   int eeAddress = 0; // Location we want the data to be put.

   // One simple call, with the address first and the object second.
   EEPROM.put(eeAddress, f);

   Serial.println("Written float data type!");

   /** Put is designed for use with custom structures also. **/

   // Data to store.
   MyObject customVar = {
      3.14f,
      65,
      "Working!"
   };

   eeAddress += sizeof(float); // Move address to the next byte after float 'f'.

   EEPROM.put(eeAddress, customVar);
   Serial.print("Written custom data type! \n\nView the example sketch eeprom_get to see how you can retrieve the values!");
}
Nothing happens in the loop.
void loop() {
   /* Empty loop */
}
This example is a precursor to the eeprom_get example. In other words, the eeprom_get example will assume that you've run this eeprom_put example on your Arduino once.
QlikView - Master Calendar

In QlikView, many times we need to create a calendar reference object, which can be linked to any data set present in QlikView's memory. For example, you have a table that captures the sales amount and sales date but does not store the weekday or quarter, which corresponds to that date. In such a scenario, we create a Master Calendar which will supply the additional date fields like Quarter, Day etc. as required by any data set.
Let us consider the following CSV data files, which are used as input for further illustrations.
SalesDate,SalesVolume
3/28/2012,3152
3/30/2012,2458
3/31/2012,4105
4/8/2012,6245
4/10/2012,5816
4/11/2012,3522

We load the above input data using the script editor, which is invoked by pressing Control+E. Choose the option Table Files and browse for the Input file.
Next, we load the above data to QlikView's memory and create a Table Box by using the menu Layout → New Sheet Objects → Table Box where we choose all the available fields to be displayed as shown below.
Next, we create the Master Calendar by writing the following script in the script editor. Here we use the table DailySales as a resident table from which we capture the Maximum and Minimum dates. We load each of the dates within this range using the second load statement above the resident load. Finally, we have a third load statement, which extracts the year, quarter, month etc. from the SalesDate values.
After creation of the complete load script along with the master calendar, we create a table box to view the data using the menu Layout → New Sheet Objects → Table Box
The final output shows the table showing the Quarter and Month values, which are created using the Sales data and Master Calendar.

    70 Lectures 
     5 hours 

 Arthur Fong
 Print
 Add Notes
 Bookmark this page
Primitive root of a prime number n modulo n in C++

In this problem, we are given a prime number N. our task is to print the primitive root of prime number N modulo N.
Primitive root of prime number N is an integer x lying between [1, n-1] such that all values of xk (mod n) where k lies in [0, n-2] are unique.
Let’s take an example to understand the problem,
Input: 13
Output: 2
To solve this problem, we have to use mathematical function called Euler’s Totient Function.
Euler’s Totient Function is the count of numbers from 1 to n which are relatively prime to the number n.
A number i is relatively prime if GCD (i, n) = 1.
In solution, if the multiplicative order of x modulo n is equal to Euler’s Totient Function, then the number is primitive root otherwise not. We will check for all relative primes.
Note: Euler’s Totient Function of a prime number n=n-1
The below code will show the implementation of our solution,
 Live Demo
#include<bits/stdc++.h>
using namespace std;
bool isPrimeNumber(int n) {
   if (n <= 1) return false;
   if (n <= 3) return true;
   if (n%2 == 0 || n%3 == 0) return false;
   for (int i=5; i*i<=n; i=i+6)
      if (n%i == 0 || n%(i+2) == 0)
         return false;
   return true;
}
int power(int x, unsigned int y, int p) {
   int res = 1;
   x = x % p;
   while (y > 0){
      if (y & 1)
      res = (res*x) % p;
      y = y >> 1;
      x = (x*x) % p;
   }
   return res;
}
void GeneratePrimes(unordered_set<int> &s, int n) {
   while (n%2 == 0){
      s.insert(2);
      n = n/2;
   }
   for (int i = 3; i <= sqrt(n); i = i+2){
      while (n%i == 0){
         s.insert(i);
         n = n/i;
      }
   }
   if (n > 2)
   s.insert(n);
}
int findPrimitiveRoot(int n) {
   unordered_set<int> s;
   if (isPrimeNumber(n)==false)
   return -1;
   int ETF = n-1;
   GeneratePrimes(s, ETF);
   for (int r=2; r<=ETF; r++){
      bool flag = false;
      for (auto it = s.begin(); it != s.end(); it++){
         if (power(r, ETF/(*it), n) == 1){
            flag = true;
            break;
         }
      }
      if (flag == false)
      return r;
   }
   return -1;
}
int main() {
   int n= 13;
   cout<<" Smallest primitive root of "<<n<<" is "<<findPrimitiveRoot(n);
   return 0;
}
Smallest primitive root of 13 is 2
Program to find Circumference of a Circle in C++

In this tutorial, we will be discussing a program to find circumference of a circle.
For this we will be provided with the radius of the circle. Our task is to calculate and print the circumference of that circle.
 Live Demo
#include<bits/stdc++.h>
using namespace std;
#define PI 3.1415
double circumference(double r){
   double cir = 2*PI*r;
   return cir;
}
int main(){
   double r = 5;
   cout << "Circumference : " << circumference(r);
   return 0;
}
Circumference : 31.415
Java - isUpperCase() Method

This method determines whether the specified char value is uppercase.
boolean isUpperCase(char ch)

Here is the detail of parameters −
ch − Primitive character type.
ch − Primitive character type.
This method returns true, if the passed character is really an uppercase.
public class Test {

   public static void main(String args[]) {
      System.out.println(Character.isUpperCase('c'));
      System.out.println(Character.isUpperCase('C'));
      System.out.println(Character.isUpperCase('\n'));
      System.out.println(Character.isUpperCase('\t'));
   }
}
This will produce the following result −
false
true
false
false


    16 Lectures 
     2 hours 

 Malhar Lathkar

    19 Lectures 
     5 hours 

 Malhar Lathkar

    25 Lectures 
     2.5 hours 

 Anadi Sharma

    126 Lectures 
     7 hours 

  Tushar Kale

    119 Lectures 
     17.5 hours 

 Monica Mittal

    76 Lectures 
     7 hours 

 Arnab Chakraborty
 Print
 Add Notes
 Bookmark this page
Kotlin For Loop

Often when you work with arrays, you need to loop through all of the 
elements.
To loop through array elements, use the for 
loop together with the in operator:
Output all elements in the cars array:
val cars = arrayOf("Volvo", "BMW", "Ford", "Mazda")
for (x in cars) {
  println(x)
}

You can loop through all kinds of arrays. In the example above, we used an array of strings. 
In the example below, we loop through an array of integers:
val nums = arrayOf(1, 5, 10, 15, 20)
for (x in nums) {
  println(x)
}
Unlike Java and other programming languages, there is no traditional for loop 
in Kotlin.
In Kotlin, the for loop is used to loop through arrays, ranges, and other 
things that contains a 
countable number of values.
You will learn more about ranges in the next chapter - which 
will create a range of values.
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.
Instruction type ORA R in 8085 Microprocessor

In 8085 Instruction set, ORA is a mnemonic, which stands for “OR Accumulator” and “R” stands for any of the following registers, or memory location M pointed by HL pair.
R = A, B, C, D, E, H, L, or M

This instruction is used to OR contents of R with the Accumulator. The result of OR operation will be stored back in the Accumulator. As R can have any of the eight values, there are eight opcodes for this type of instruction. It occupies only 1-Byte in memory.
Let us consider the instruction ORA E as an example instruction of this category. As it is a 1-Byte instruction so it will occupy a single Byte in the memory. Let us consider that the initial contents of Accumulator and E register are ABH and CDH. The result of execution of this instruction has been shown in the following tracing table.
(E)
(A)
(F)
The internal calculation has been done as shown below −
(A) ABH ---> 1010 1011
(E) CDH ---> 1100 1101
            ---------
        ORA E ---> 1110 1111 (EFH)

The timing diagram against this instruction ORA E execution is as follows −
Summary − So this instruction ORA E requires 1-Byte, 1-Machine Cycle (Opcode Fetch) and 4 T-States for execution as shown in the timing diagram.
How to read file content into istringstream in C++?

Here is a C++ program to read file content into isstringstream in C++.
#include <fstream>
#include <sstream>
#include<iostream>
using namespace std;
int main() {
   ifstream is("a.txt", ios::binary );
   // get length of file:
   is.seekg (0, std::ios::end);
   long length = is.tellg();
   is.seekg (0, std::ios::beg);
   // allocate memory:
   char *buffer = new char [length];
   // read data as a block:
   is.read (buffer,length);
   // create string stream of memory contents
   istringstream iss( string( buffer ) );
   cout<<buffer;
   // delete temporary buffer
   delete [] buffer;
   // close filestream
   is.close();
}
hi tutorialspoint
Write an example program on structure using C language

The structure is a collection of different datatype variables, grouped together under a single name Syntax.
The general form of structure declaration is as follows −
datatype member1;
struct tagname{
   datatype member2;
   datatype member n;
};
Here, struct - keyword
         tagname - specifies name of structure
         member1, member2 - specifies the data items that makeup structure.
struct book{
   int pages;
   char author [30];
   float price;
};
There are three ways of declaring structure variables. They are as follows −
1) struct book{
   int pages;
   char author[30];
   float price;
}b;
2) struct{
   int pages;
   char author[30];
   float price;
}b;
3) struct book{
   int pages;
   char author[30];
   float price;
};
struct book b;
The link between a member and a structure variable is established using the member operator (or) dot operator.
The link between a member and a structure variable is established using the member operator (or) dot operator.
Initialization can be done in the following ways −
Initialization can be done in the following ways −
struct book{
   int pages;
   char author[30];
   float price;
} b = {100, “balu", 325.75};
struct book{
   int pages;
   char author[30];
   float price;
};
struct book b = {100, “balu", 325.75};
struct book{
   int pages;
   char author[30];
   float price;
} ;
struct book b;
   b. pages = 100;
   strcpy (b.author, “balu");
   b.price = 325.75;
struct book{
   int pages;
   char author[30];
   float price;
} ;
struct book b;
   scanf (“%d", &b.pages);
   scanf (“%s", b.author);
   scanf (“%f", &b. price);
We can print the contents of either of the above structures in the main method as shown below −
main ( ){
   struct book b;
   clrscr ( );
   printf ( "enter no of pages, author, price of book");
   scanf ("%d%s%f", &b.pages, b.author, &b.price);
   printf("Details of book are");
   printf("pages =%d, author = %s, price = %f", b.pages, b.author, b.price);
   getch();
}
Following is another example of structures −
 Live Demo
#include<stdio.h>
struct aaa{
   struct aaa *prev;
   int i;
   struct aaa *next;
};
main(){
   struct aaa abc,def,ghi,jkl;
   int x=100;
   abc.i=0;
   abc.prev=&jkl;
   abc.next=&def;
   def.i=1;
   def.prev=&abc;
   def.next=&ghi;
   ghi.i=2;ghi.prev=&def;
   ghi.next=&jkl;
   jkl.i=3;
   jkl.prev=&ghi;
   jkl.next=&abc;
   x=abc.next->next->prev->next->i;
   printf("%d",x);
}
2
How to find the sum of column values of an R dataframe? - GeeksforGeeks

30 May, 2021
In this article, we are going to find the sum of the column values of a dataframe in R with the use of sum() function.
Syntax:
sum(dataframe$column_name)
A dataframe can be created with the use of data.frame() function that is pre-defined in the R library. This function accepts the elements and the number of rows and columns that are required for the dataframe to be created.
Following is an R Program for the creation of dataframe:
R
# R Program to create a dataframe  # Creating a Data Framedf<-data.frame(row1 = 0:2, row2 = 3:5, row3 = 6:8)print(df)
Output:
  row1 row2 row3
1    0    3    6
2    1    4    7
3    2    5    8
R language provides an in-built function sum() to compute the mean of a dataframe. Following is an R program for the implementation of sum().
R
# Computing sum of column values  # Using sum() functionsum(df$row1)sum(df$row2)
Output:
3
12
Example 2:
R
# R program to illustrate dataframe Roll_num = c(01, 02, 03)Age = c(22, 25, 45)Marks = c(70, 80, 90)    # To create dataframe use data.frame command and # then pass each of the vectors  # we have created as arguments # to the function data.frame() df = data.frame(Roll_num, Age, Marks) print(df)  # Computing Sum using sum() functionsum(df$Roll_num)sum(df$Age)sum(df$Marks)
Output:
6
92
240
Example 3:
R
# R program to illustrate dataframe ID = c(01, 02, 03)Age = c(25, 30, 70)Salary = c(70000, 85000, 40000)    # To create dataframe use data.frame command and # then pass each of the vectors  # we have created as arguments # to the function data.frame() df = data.frame(ID, Age, Salary)   # Computing total salarycat("Total Salary =", sum(df$Salary))
Output:
195000
Picked
R DataFrame-Programs
R-DataFrame
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
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 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?
Replace Specific Characters in String in R
Convert Matrix to Dataframe in R
Calculate n + nn + nnn + ... + n(m times) in Python program

We are going to write a program that calculates the following series in Python. Examine the example inputs and outputs for the program that we are going to write.
Input:
34
3 + 33 + 333 + 3333
Output:
3702
Input:
5 5 5 + 55 + 555 + 5555 + 55555
Output:
61725
So, we will have two numbers, and we have to calculate the sum of the series generated as above. Follow the below steps to achieve the output.
1. Initialize the number let's say n and m.
2. Initialize a variable with the value n let's say change.
3. Intialize a variable s to zero.
4. Write a loop which iterates m times.
   4.1. Add change to the s.
   4.2. Update the value of change to get next number in the series.
5. Print the sum at the end of the program.
You have to create a general formula to generate numbers in the series. Try to get it as your own. If you stuck at the logic, see the code below.
## intializing n and m
n, m = 3, 4
## initializing change variable to n
change = n
## initializing sum to 0
s = 0
## loop
for i in range(m):
   ## adding change to s
   s += change
   ## updating the value of change
   change = change * 10 + n
## printing the s
print(s)
If you run the above program, you will get the following output.
3702
Let's see another example with different values as we discussed in the examples.
## intializing n and m
n, m = 5, 5
## initializing change variable to n
change = n
## initializing sum to 0
s = 0
## loop
for i in range(m):
   ## adding change to s
   s += change
   ## updating the value of change
   change = change * 10 + n
## printing the s
print(s)
If you run the above program, you will get the following output.
61725
If you have any doubts regarding the tutorial, mention them in the comment section.
How to install Python on Linux? - GeeksforGeeks

22 Jan, 2020
Prerequisite: Python Language Introduction Before we start with how to install Python3 on Linux, let’s first go through the basic introduction to Python. Python is a widely-used general-purpose, high-level programming language. Python is a programming language that lets you work quickly and integrate systems more efficiently. There are two major Python versions- Python 2 and Python 3. Both are quite different.
Python is a lot easier to code and learn. Python programs can be written on any plain text editor like notepad, notepad++, or anything of that sort. One can also use an online IDE for writing Python codes or can even install one on their system to make it more feasible to write these codes because IDEs provide a lot of features like intuitive code editor, debugger, compiler, etc.To begin with, writing Python Codes and performing various intriguing and useful operations, one must have Python installed on their System. This can be done by following the step by step instructions provided below:
Most of the Linux OS has Python pre-installed. To check if your device is pre-installed with Python or not, just go to terminal using Ctrl+Alt+T
Now run the following command:For Python2
python --version

For Python3.x
python3.x --version

If Python is already installed, it will generate a message with the Python version available.
Before starting with the installation process, you need to download it. For that all versions of Python for Linux are available on python.org.
Download the required version and follow the further instructions for the installation process.
Beginning the installation.
For almost every Linux system, the following command could be used to install Python directly:
$ sudo apt-get install python3.8

Getting Started:
Assigning DiskSpace:
Fetching and Installing Packages:
Getting through the installation process:
Finished Installation:
To verify the installation enter the following commands in your Terminal.
python3.8

Let’s consider a simple Hello World Program.
# Python program to print# Hello World  print("Hello World")
python-basics
Python
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
Enumerate() in Python
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
sum() function in Python
Displaying content of a HashMap in Java

Let us first create a HashMap and add elements −
HashMap hm = new HashMap();
hm.put("Wallet", new Integer(700));
hm.put("Belt", new Integer(600));
To display the content, just print the HashMap object −
System.out.println("Map = "+hm);
The following is an example to display content of a HashMap −
 Live Demo
import java.util.*;
public class Demo {
   public static void main(String args[]) {
      // Create hash map
      HashMap hm = new HashMap();
      hm.put("Wallet", new Integer(700));
      hm.put("Belt", new Integer(600));
      System.out.println("Map = "+hm);
   }
}
Map = {Belt=600, Wallet=700}
C# Regex. Matches Method

The method matches instances of a pattern and is used to extract value based on a pattern.
Let us see hoe to check for a valid URL.
For that, pass the regex expression in the Matches method.
MatchCollection mc = Regex.Matches(text, expr);
Above, the expr is our expression that we have set to check for valid URL.
"^(http|http(s)?://)?([\w-]+\.)+[\w-]+[.com|.in|.org]+(\[\?%&=]*)?”
The text we have set to check is a URL i.e.
https://demo.com
Let us see the complete code.
 Live Demo
using System;
using System.Text.RegularExpressions;
namespace Demo {
   class Program {
      private static void showMatch(string text, string expr) {
         MatchCollection mc = Regex.Matches(text, expr);
         foreach (Match m in mc) {
            Console.WriteLine(m);
         }
      }
      static void Main(string[] args) {
         string str = "https://demo.com";
         Console.WriteLine("Matching URL...");
         showMatch(str, @"^(http|http(s)?://)?([\w-]+\.)+[\w-]+[.com|.in|.org]+(\[\?%&=]*)?");
         Console.ReadKey();
      }
   }
}
Matching URL...
https://demo.com
How to implement Inheritance in Typescript ?

14 Jul, 2021
Inheritance is a major pillar of object-oriented programming languages and inheritance is used to create a new class from the existing one. The newly created class is known as the Derived class and the class from which the derived class inherited is known as the Base class. An inherited derived class acquires the properties and behaviors of the base class. TypeScript supports single inheritance and multilevel inheritance. We can not implement hybrid and multiple inheritances using TypeScript. The inheritance uses class-based inheritance and it can be implemented using extends keywords in typescript. In this article, we will see how inheritance is implemented in TypeScript.
Syntax:
class baseClassName {
}
class derivedClassName extends baseClassName {
}
Single Inheritance in TypeScript: In single inheritance, the properties and behaviour of the base class can be inherited into at most one derived class. It used to add new functionality to the already implemented class.
Example: In this example, we are creating a Person as a base class and using single inheritance implementing Teacher as a Derived class. 
 
Javascript
// Base classclass Person {  Name: string;  constructor(name: string) {    this.Name = name;  }}// Deriving Teacher classclass Teacher extends Person {  Payment: number;  constructor(name: string, payment: number) {    super(name);    this.Payment = payment;  }  display(): void {    console.log("Teacher's Name: " + this.Name);    console.log("Teacher's Payment " + this.Payment);  }}// Create Objectlet obj = new Teacher("GeeksforGeeks", 8500000);obj.display();
Output:
Teacher's Name: GeeksforGeeks 
Teacher's Payment 8500000
2.Multilevel Inheritance:
In multilevel inheritance, the derived class acts as the base class for another derived class. The newly created derived class acquires the properties and behavior of other base classes.
Example: In this example, we are creating a Vehicle as a base class and a Car as a subclass which deriving the new class called carModel and the class carModel acquires all features of the Vehicle as well as Car class.
Javascript
// Base classclass Vehicle {  Type(): void {    console.log("Car");  }}  // Inherites from Vehicleclass Car extends Vehicle {  Brand(): void {    console.log("ABC");  }}  // Inherites all properties of // Vehicle and Car classclass carModel extends Car {  Model(): void {    console.log("ABC2021");  }}  // Object creationlet obj = new carModel();obj.Type();obj.Brand();obj.Model();
Output:
Car  
ABC
ABC2021
Picked
TypeScript
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Count Variable Numbers of Arguments in C?

28 May, 2017
C supports variable numbers of arguments. But there is no language provided way for finding out total number of arguments passed. User has to handle this in one of the following ways:1) By passing first argument as count of arguments.2) By passing last argument as NULL (or 0).3) Using some printf (or scanf) like mechanism where first argument has placeholders for rest of the arguments.
Following is an example that uses first argument arg_count to hold count of other arguments.
#include <stdarg.h>#include <stdio.h>  // this function returns minimum of integer numbers passed.  First // argument is count of numbers.int min(int arg_count, ...){  int i;  int min, a;      // va_list is a type to hold information about variable arguments  va_list ap;     // va_start must be called before accessing variable argument list  va_start(ap, arg_count);        // Now arguments can be accessed one by one using va_arg macro  // Initialize min as first argument in list     min = va_arg(ap, int);       // traverse rest of the arguments to find out minimum  for(i = 2; i <= arg_count; i++) {    if((a = va_arg(ap, int)) < min)      min = a;  }       //va_end should be executed before the function returns whenever  // va_start has been previously used in that function   va_end(ap);       return min;}  int main(){   int count = 5;        // Find minimum of 5 numbers: (12, 67, 6, 7, 100)   printf("Minimum value is %d", min(count, 12, 67, 6, 7, 100));   getchar();   return 0;}
Output:Minimum value is 6
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
C-Functions
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference Between Algorithm and Flowchart - GeeksforGeeks

21 May, 2020
Algorithm:
The word Algorithm means “a process or set of rules to be followed in calculations or other problem-solving operations”. Therefore Algorithm refers to a set of rules/instructions that step-by-step define how a work is to be executed upon inorder to get the expected results.
Let’s take a look at an example for a better understanding. As a programmer, we are all aware of the Linear Search program. (Linear Search)
Algorithm of linear search :
1. Start from the leftmost element of arr[] and 
one by one compare x with each element of arr[]. 
2. If x matches with an element, return the index. 
3. If x doesn’t match with any of elements, return -1. 

Here, we can see how the steps of a linear search program are explained in a simple, English language.
Flowchart:
A flowchart is a graphical representation of an algorithm. Programmers often use it as a program-planning tool to solve a problem. It makes use of symbols which are connected among them to indicate the flow of information and processing.The process of drawing a flowchart for an algorithm is known as “flowcharting”.
Example: Draw a flowchart to input two numbers from the user and display the largest of two numbers
Let’s see the difference between algorithm and flow chart:-
pp_pankaj
Data Structures
Difference Between
Data Structures
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
SDE SHEET - A Complete Guide for SDE Preparation
Top 50 Array Coding Problems for Interviews
DSA Sheet by Love Babbar
Doubly Linked List | Set 1 (Introduction and Insertion)
Implementing a Linked List in Java using Class
Difference between BFS and DFS
Class method vs Static method in Python
Differences between TCP and UDP
Stack vs Heap Memory Allocation
Difference between Process and Thread
How to remove numbers from string in Python – Pandas?

25 Feb, 2021
In this article, let’s see how to remove numbers from string in Pandas. Currently, we will be using only the .csv file for demonstration purposes, but the process is the same for other types of files. The function read_csv() is used to read CSV files.
Syntax:
 for the method ‘replace()’:
str.replace(old, new)
Here str. replace() will return a string in which the parameter ‘old’ will be replaced by the parameter ‘new’. Now let us see through coding how to remove numbers from strings in the pandas data frame.
Example 1:
Python3
# codeimport pandas as pd    # creating dataframedf = pd.DataFrame.from_dict({'Name': ['May21', 'James',                                      'Adi22', 'Hello',                                      'Girl90'],                                                            'Age': [25, 15, 20, 33, 42],                                                                                           'Income': [21321, 12311, 25000,                                        32454, 65465]})  # removing numbers from strings of speciafied # column, here 'Name'df['Name'] = df['Name'].str.replace('\d+', '')  # display output with numbers removed from # required stringsprint(df)
Output:
Example 2:
Python3
# codeimport pandas as pd    # creating dataframedf = pd.DataFrame.from_dict({'Name': ['rohan21', 'Jelly',                                      'Alok22', 'Hey65',                                      'boy92'],                                                            'Age': [24, 25, 10, 73, 92],                                                            'Income': [28421, 14611, 28200,                                        45454, 66565]})  # removing numbers from strings of speciafied # column, here 'Name'df['Name'] = df['Name'].str.replace('\d+', '')  # display output with numbers removed from # required stringsprint(df)
Output:
Picked
Python pandas-dataFrame
Python-pandas
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function
UGC-NET | UGC NET CS 2015 Dec – II | Question 29

02 May, 2018
A system has four processes and five allocatable resources. The current allocation and maximum needs are as follows:
            Allocated    Maximum           Available
Process A    1 0 2 1 1    1 1 2 1 3    0 0 x 1 1
Process B    2 0 1 1 0    2 2 2 1 0    
Process C    1 1 0 1 0    2 1 3 1 0    
Process D    1 1 1 1 0    1 1 2 2 1    
The smallest value of x for which the above system in safe state is __________.
(A) 1(B) 3(C) 2(D) Not safe for any value of x.Answer: (D)Explanation:
            Allocated    Maximum           Available      Need 
Process A    1 0 2 1 1    1 1 2 1 3    0 0 x 1 1    0 1 0 0 2 
Process B    2 0 1 1 0    2 2 2 1 0                 0 2 1 0 0
Process C    1 1 0 1 0    2 1 3 1 0                 1 0 3 0 0
Process D    1 1 1 1 0    1 1 2 2 1                 0 0 1 1 1 
The smallest value of x for which the above system in safe state is __________.
For x = 1 process D will execute and free 1 1 2 2 1 instances. Now none of the other process will execute.let x = 2 then process D will execute and free 1 1 3 2 1 instances. Now process C will execute and free 2 2 3 3 1 instances. With these free instances process B will execute, but process A will not execute because 5 resources needs 2 instances which will never be satisfied. That’s why system is not in safe state.So, option (D) is correct.Quiz of this Question
UGC-NET
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
What is AbstractList Class in Java?

The AbstractList class provides an implementation of the List interface.
Programmer needs to extend this class and provide implementations for the get(int) and size() methods.
Programmer must override the set(int, E) method. If the list is variable-size the programmer must override the add(int, E) and remove(int) methods.
The following is the syntax:
public abstract class AbstractList<E>
extends AbstractCollection<E>
implements List<E>
To work with the AbstractList class, import the following package:
import java.util.AbstractList;
The following is an example to implement AbstractList class:
 Live Demo
import java.util.LinkedList;
import java.util.AbstractList;
public class Demo {
   public static void main(String[] args) {
      AbstractList<Integer> myList = new LinkedList<Integer>();
      myList.add(50);
      myList.add(100);
      myList.add(150);
      myList.add(200);
      myList.add(250);
      myList.add(300);
      myList.add(350);
      myList.add(400);
      System.out.println("Elements in the AbstractList class = " + myList);
   }
}
Elements in the AbstractList class = [50, 100, 150, 200, 250, 300, 350, 400]
Python | Program to convert String to a List

07 Jul, 2022
In this program, we will try to convert a given string to a list, where spaces or any other special characters, according to the users choice, are encountered. To do this we use the split() method in string.
string.split("delimiter")
Examples:
Input : "Geeks for Geeks"
Output : ['Geeks', 'for', 'Geeks']

Input : "Geeks-for-Geeks"
Output : ['Geeks', 'for', 'Geeks']
Method#1: Using split() method
The split method is used to split the strings and store them in the list. The built-in method returns a list of the words in the string, using the “delimiter” as the delimiter string. If a delimiter is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace.
Python3
# Python code to convert string to list  def Convert(string):    li = list(string.split(" "))    return li  # Driver code    str1 = "Geeks for Geeks"print(Convert(str1))
Output:
['Geeks', 'for', 'Geeks']
Example 2: 
Python3
# Python code to convert string to listdef Convert(string):    li = list(string.split("-"))    return li  # Driver code    str1 = "Geeks-for-Geeks"print(Convert(str1))
Output:
['Geeks', 'for', 'Geeks']
Method#2 : Using string slicing:
Python3
# Python code to convert string to list character-wisedef Convert(string):    list1=[]    list1[:0]=string    return list1# Driver codestr1="ABCD"print(Convert(str1))
Output:
['A','B','C','D']
Method#3 : Using re.findall() method This task can be performed using regular expression. We can used the pattern to matched all the alphabet and make list with all the matched elements. 
Python3
# Python code to convert string to list character-wise# Using re.findall methodimport re  # Function which uses re.findall method to convert string to list character wise def Convert(string):    return re.findall('[a-zA-Z]', string)      # Driver codestr1="ABCD"print("List of character is : ",Convert(str1))
Output:
List of character is :  ['A', 'B', 'C', 'D']
sagarbaisoya1
satyam00so
sagartomar9927
Python list-programs
Python string-programs
python-list
python-string
Python
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Convert integer to string in Python
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Difference between char and nchar : MS SQL Server Datatypes

14 Sep, 2020
A database has a vast collection of data stored in an organized format. A database might contain a variety of data values stored in it. To avoid confusions, the data values are assigned a name based on its type. These are called datatypes. Datatypes help the users distinguish between different categories of data. MS SQL Server supports a wide range of datatypes for the users to be able to easily identify various categories of data and to use it accordingly.
1. Char :A character is a string of words dentod by single quotation marks. Character is shortened to char in MS SQL Server. It is a datatype that stores only non-unicode data. Non-unicode data is a format that doesn’t support the unicode standards. It takes 1 byte of data and the maximum storage capacity is of 8000 bytes.
Syntax –
column_name char(number _of_bytes);

2. n-char :A n-char is also a string of words that can store unicode data. nchar stands for national character. It takes up two bytes to store the data and can store upto 4000 chars. Unicode data refers to a universal coding standard for letters and other data. Each one is uniquely identified by designating a numeric value.
Syntax –
column_name nchar(number_of_bytes);

Difference between char and nchar : MS SQL Server Datatypes :
Syntax :
col_name char(n); 
*n is the number of bytes.
Syntax :
col_name nchar(n); 
*n is the number of bytes.
SQL-Server
Difference Between
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Java Program to Check If a Number is Spy number or not

04 Jan, 2021
A number is said to be a Spy number if the sum of all the digits is equal to the product of all digits. For performing the task we need to reverse through the number which will take log(N) time.
  Example:
Input : 22
Output:  Given number is a SPY number.
Explanation: Sum of the number is 4 (2 + 2)
             Product of the number is as 4 (2 * 2) 
Input : 1241
Output:  Given number is not a SPY number.
Approach:
Calculate the sum of digits of the input Number.Calculate the product of digits of the input Number.If the sum of digits equals the product of digits then the number is Spy number otherwise not.
Calculate the sum of digits of the input Number.
Calculate the product of digits of the input Number.
If the sum of digits equals the product of digits then the number is Spy number otherwise not.
Below is the implementation of the above approach:
Java
// Java Program to Check If a Number is Spy number or notimport java.io.*;  class GFG {    public static void main(String[] args)    {        int product = 1, sum = 0, ld;        int n = 22;          // calculate sum and product of the number here.        while (n > 0) {            ld = n % 10;            sum = sum + ld;            product = product * ld;            n = n / 10;        }          // compare the sum and product.        if (sum == product)            System.out.println(                "Given number is spy number");        else            System.out.println(                "Given number is not spy number");    }}
Given number is spy number

Complexity: O(log(n))
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
List Interface in Java with Examples
Strings in Java
Different ways of Reading a text file in Java
Reverse an array in Java
How to remove an element from ArrayList in Java?
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
Traverse Through a HashMap in Java
Extends vs Implements in Java
Send SMS with REST Using Python

14 Sep, 2021
In this article, we are going to see how we can send SMS with REST using Python. The requests library can be used to make REST requests using Python to send SMS. 
You need to first create a REST API KEY for sending SMS using Python Script. We have used Fast2SMS for creating API KEY.
You can go on the website and create an account after which you can have your own API KEY.
Create a Python File and copy the below code, Replace “API_KEY_OF_YOURS” with your API KEY, and in the numbers parameter, enter the number on which you want to send SMS, you can enter multiple numbers.
Following are the parameters used in GET API:
authorization –  true, Provide “YOUR_API_KEY”. Sign up for API Key
message – true, Message “text” to be sent
language – false, Default language is “english”. API will detect “unicode” messages automatically.
route – true, For Quick SMS use “q”
numbers – true, You can send multiple mobile numbers separated by commas like: “XXXXXXXX98, YYYYYYYY89”
flash – false, This field is optional, it will use “0” as a default value or you can set it to “1” for sending a flash message.
Python
import requests  url = "https://www.fast2sms.com/dev/bulkV2"  querystring = {    "authorization": "API_KEY_OF_YOURS",    "message": "This is test Message sent from \         Python Script using REST API.",    "language": "english",    "route": "q",    "numbers": "XXXXXXXX98, YYYYYYYY89"}  headers = {    'cache-control': "no-cache"}try:    response = requests.request("GET", url,                                headers = headers,                                params = querystring)          print("SMS Successfully Sent")except:    print("Oops! Something wrong")
Output:
SMS Successfully Sent
Message sent using REST in Python
Picked
Python-requests
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function