code-rag-bench/online-tutorials huggingface dataset:
Python - Plotting Combined charts in excel sheet using XlsxWriter module

lsxWriter is a Python library using which one can perform multiple operations on excel files like creating, writing, arithmetic operations and plotting graphs.
# import xlsxwriter module
import xlsxwriter
# Workbook() takes one, non-optional, argument which is the filename #that we want to create.
workbook = xlsxwriter.Workbook('chart_combined.xlsx')
# The workbook object is then used to add new worksheet via the #add_worksheet() method.
worksheet = workbook.add_worksheet()
# Create a new Format object to formats cells in worksheets using #add_format() method .
# here we create bold format object .
bold = workbook.add_format({'bold': True})
# Add the worksheet data that the charts will refer to.
headings = ['Number', 'Batch 1', 'Batch 2']
data = [
   [2, 3, 4, 5, 6, 7],
   [10, 40, 50, 20, 10, 50],
   [30, 60, 70, 50, 40, 30],
]
# Write a row of data starting from 'A1' with bold format .
worksheet.write_row('A1', headings, bold)
# Write a column of data starting from 'A2', 'B2', 'C2' respectively .
worksheet.write_column('A2', data[0])
worksheet.write_column('B2', data[1])
worksheet.write_column('C2', data[2])  
# Create a chart object that can be added to a worksheet using #add_chart() method.
#here we create a column chart object.This will use as the primary #chart.
column_chart1 = workbook.add_chart({'type': 'column'})
# Add a data series to a chart using add_series method.
# Configure the first series.
# = Sheet1 !$A$1 is equivalent to ['Sheet1', 0, 0].
# note : spaces is not inserted in b/w = and Sheet1, Sheet1 and !
# if space is inserted it throws warning.
column_chart1.add_series({
   'name':       '= Sheet1 !$B$1',
   'categories': '= Sheet1 !$A$2:$A$7',
   'values':     '= Sheet1 !$B$2:$B$7',
})
# Create a new line chart.This will use as the secondary chart.
line_chart1 = workbook.add_chart({'type': 'line'})
# Configure the data series for the secondary chart.
line_chart1.add_series({
   'name':       '= Sheet1 !$C$1',
   'categories': '= Sheet1 !$A$2:$A$7',
   'values':     '= Sheet1 !$C$2:$C$7',
})
# Combine both column and line chatrs together.
column_chart1.combine(line_chart1)
# Add a chart title  
column_chart1.set_title({ 'name': 'Combined chart - same Y axis'})
# Add x-axis label
column_chart1.set_x_axis({'name': 'Test number'})
# Add y-axis label
column_chart1.set_y_axis({'name': 'Sample length (mm)'})
# add chart to the worksheet with given offset values at the top-left #corner of a chart is anchored to cell D2
worksheet.insert_chart('D2', column_chart1, {'x_offset': 25, 'y_offset': 10})
# Finally, close the Excel file via the close() method.  
workbook.close()
is_pod template in C++

In this article we will be discussing the working, syntax and examples of std::is_pod template in C++ STL.
is_ pod is a template which comes under <type_traits> header file. This template is used to check whether the given type T is a POD(plain-old-data) type or not.
Plain old data(POD) types are those types which are also in old C language. POD types also include scalar types. POD class type is that class type which is both, trivial (which can be initialised statically) and standard layout (which is a simple data structure like struct and union).
template <class T> is_pod;
The template can have only parameter of type T, and check whether the given type is a Plain Old Data type or not.
It returns a Boolean value, true if the given type is a Plain Old Data, and false if the given type is not a Plain Old Data.
Input: class final_abc{ final_abc(); };
   is_pod<final_abc>::value;
Output: False

Input: is_pod<int>::value;
Output: True
 Live Demo
#include <iostream>
#include <type_traits>
using namespace std;
struct TP_1 {
   int var_1;
};
struct TP_2 {
   int var_2;
   private:
   int var_3;
};
struct TP_3 {
   virtual void dummy();
};
int main() {
   cout << boolalpha;
   cout << "checking for is_pod:";
   cout << "\nTP_1: " << is_pod<TP_1>::value;
   cout << "\nTP_2: " << is_pod<TP_2>::value;
   cout << "\nTP_3: " << is_pod<TP_3>::value;
   return 0;
}
If we run the above code it will generate the following output −
checking for is_pod:
TP_1: true
TP_2: false
TP_3: false
 Live Demo
#include <iostream>
#include <type_traits>
using namespace std;
class TP_1 {
   int var_1;
};
class TP_2 {
   int var_2;
   private:
   int var_3;
};
class TP_3 {
   virtual void dummy();
};
int main() {
   cout << boolalpha;
   cout << "checking for is_pod:";
   cout << "\nTP_1: " << is_pod<TP_1>::value;
   cout << "\nTP_2: " << is_pod<TP_2>::value;
   cout << "\nTP_3: " << is_pod<TP_3>::value;
   return 0;
}
If we run the above code it will generate the following output −
checking for is_pod:
TP_1: true
TP_2: true
TP_3: false
How to create a JavaFX Basic Application?

To create a basic JavaFX application follow the steps given below −
To create a JavaFX application, you need to instantiate the Application class and implement its abstract method start(). In this method, we will write the code for
the JavaFX Application.
Create a Java class and inherit the Application class of the package
javafx.application and implement the start() method of this class as follows.
public class JavafxSample extends Application {
   public void start(Stage primaryStage) throws Exception {
   }
}
A group node is a collective node that contains a list of children nodes. Whenever the group node is rendered, all its child nodes are rendered in order.
In the start() method create a group object by instantiating the javafx.scene.Group class −
Group root = new Group();
A scene graph is a data structure similar to tree, in modern graphical applications it is a collection of nodes. In a JavaFX application the javafx.scene.Scene class holds all the contents of a scene graph.
Instantiate the javafx.scene class, to its constructor, pass the Group object (root), created in the previous step.
Scene scene = new Scene(root,600, 300);
A stage is the top most container of a JavaFX application and it provides a window for the application it is represented by the javafx.stage.Stage class. An object of this is passed as a parameter to the start() method.
Add the Scene object prepared in the previous step to the stage using the setScene() method.
Method.primaryStage.setScene(scene);
Display the contents of the scene using the method named show() of the Stage class as follows.
primaryStage.show();
Launch the JavaFX application by calling the static method launch() of the Application class from the main method as follows.
public static void main(String args[]){
   launch(args);
}
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class BasicApplication extends Application {
   public void start(Stage stage) {
      //Instantiating the group class
      Group root = new Group();
      //Instantiating the Scene class
      Scene scene = new Scene(root, 595, 300, Color.BEIGE);
      //Setting the scene to the Stage
      stage.setScene(scene);
      //Setting Title to the stage
      stage.setTitle("JavFX Basic Application");
      //Displaying the contents of the stage
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}
Java Program to get the difference between two time zones by seconds

Here are the two timezones −
ZoneId zone1 = ZoneId.of("America/Panama");
ZoneId zone2 = ZoneId.of("Asia/Taipei");
Set the date −
LocalDateTime dateTime = LocalDateTime.of(2019, 04, 11, 10, 5);
Now, set the first timezone −
ZonedDateTime panamaDateTime = ZonedDateTime.of(dateTime, zone1);
Set the second timezone −
ZonedDateTime taipeiDateTime = panamaDateTime.withZoneSameInstant(zone2);
Get the timezone differences in seconds −
taipeiDateTime.getOffset().getTotalSeconds()
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
public class Demo {
   public static void main(String[] args) {
      ZoneId zone1 = ZoneId.of("America/Panama");
      ZoneId zone2 = ZoneId.of("Asia/Taipei");
      LocalDateTime dateTime = LocalDateTime.of(2019, 04, 11, 10, 5);
      ZonedDateTime panamaDateTime = ZonedDateTime.of(dateTime, zone1);
      ZonedDateTime taipeiDateTime = panamaDateTime.withZoneSameInstant(zone2);
      System.out.println("Difference between two time zones in seconds = "+taipeiDateTime.getOffset().getTotalSeconds());
   }
}
Difference between two time zones in seconds = 28800
How to read a number of characters from a text file using Python?

To read a file’s contents, you can call f.read(size), which reads some quantity of data and returns it as a string. size is an optional numeric argument. When size is omitted or negative, the entire contents of the file will be read and returned. Otherwise, at most size bytes are read and returned. If the end of the file has been reached, f.read() will return an empty string ("").
So if you want to read 10 ASCII characters, you can simply pass 10 as the argument.
>>> f = open('my_file', 'r')
>>> print(f.read(10))
Hello worl
>>> f.close()
HBase - Create Table

You can create a table using the create command, here you must specify the table name and the Column Family name. The syntax to create a table in HBase shell is shown below.
create ‘<table name>’,’<column family>’ 

Given below is a sample schema of a table named emp. It has two column families: “personal data” and “professional data”.
You can create this table in HBase shell as shown below.
hbase(main):002:0> create 'emp', 'personal data', 'professional data'

And it will give you the following output.
0 row(s) in 1.1300 seconds
=> Hbase::Table - emp

You can verify whether the table is created using the list command as shown below. Here you can observe the created emp table.
hbase(main):002:0> list
TABLE 
emp
2 row(s) in 0.0340 seconds

You can create a table in HBase using the createTable() method of HBaseAdmin class. This class belongs to the org.apache.hadoop.hbase.client package. Given below are the steps to create a table in HBase using java API.
This class requires the Configuration object as a parameter, therefore initially instantiate the Configuration class and pass this instance to HBaseAdmin.
Configuration conf = HBaseConfiguration.create();
HBaseAdmin admin = new HBaseAdmin(conf);

HTableDescriptor is a class that belongs to the org.apache.hadoop.hbase class. This class is like a container of table names and column families.
//creating table descriptor
HTableDescriptor table = new HTableDescriptor(toBytes("Table name"));

//creating column family descriptor
HColumnDescriptor family = new HColumnDescriptor(toBytes("column family"));

//adding coloumn family to HTable
table.addFamily(family);

Using the createTable() method of HBaseAdmin class, you can execute the created table in Admin mode.
admin.createTable(table);

Given below is the complete program to create a table via admin.
import java.io.IOException;

import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.client.HBaseAdmin;
import org.apache.hadoop.hbase.TableName;

import org.apache.hadoop.conf.Configuration;

public class CreateTable {
      
   public static void main(String[] args) throws IOException {

      // Instantiating configuration class
      Configuration con = HBaseConfiguration.create();

      // Instantiating HbaseAdmin class
      HBaseAdmin admin = new HBaseAdmin(con);

      // Instantiating table descriptor class
      HTableDescriptor tableDescriptor = new
      HTableDescriptor(TableName.valueOf("emp"));

      // Adding column families to table descriptor
      tableDescriptor.addFamily(new HColumnDescriptor("personal"));
      tableDescriptor.addFamily(new HColumnDescriptor("professional"));

      // Execute the table through admin
      admin.createTable(tableDescriptor);
      System.out.println(" Table created ");
   }
}
Compile and execute the above program as shown below.
$javac CreateTable.java
$java CreateTable

The following should be the output:
Table created

 Print
 Add Notes
 Bookmark this page
C++ Program to find the sum of a Series 1/1! + 2/2! + 3/3! + 4/4! +.......+ n/n! - GeeksforGeeks

05 Dec, 2018
You have been given a series 1/1! + 2/2! + 3/3! + 4/4! +.......+ n/n!, find out the sum of the series till nth term.
Examples:
Input :n = 5
Output : 2.70833

Input :n = 7
Output : 2.71806

/*CPP program to print the sum of series */#include <bits/stdc++.h>using namespace std;  /*function to calculate sum of given series*/double sumOfSeries(double num){    double res = 0, fact = 1;    for (int i = 1; i <= num; i++) {        /*fact variable store factorial of the i.*/        fact = fact * i;          res = res + (i / fact);    }    return (res);}  /*Driver Function*/int main(){    double n = 5;    cout << "Sum: " << sumOfSeries(n);    return 0;}
Sum: 2.70833

Please refer complete article on Program to find the sum of a Series 1/1! + 2/2! + 3/3! + 4/4! +.......+ n/n! for more details!
C++ Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Passing a function as a parameter in C++
Const keyword in C++
Program to implement Singly Linked List in C++ using class
cout in C++
Dynamic _Cast in C++
isdigit() function in C/C++ with Examples
Why it is important to write "using namespace std" in C++ program?
Different ways to print elements of vector
Setting up Sublime Text for C++ Competitive Programming Environment
Program to count Number of connected components in an undirected graph
Depth-first search traversal in Javascript

DFS visits the child vertices before visiting the sibling vertices; that is, it traverses the depth of any particular path before exploring its breadth. A stack (often the program's call stack via recursion) is generally used when implementing the algorithm.
Following is how a DFS works −
Visit the adjacent unvisited vertex. Mark it as visited. Display it. Push it in a stack.
If no adjacent vertex is found, pop up a vertex from the stack. (It will pop up all the vertices from the stack, which do not have adjacent vertices.)
Repeat Rule 1 and Rule 2 until the stack is empty.
Let us look at an illustration of how DFS traversal works.
As C does not have any unvisited adjacent node so we keep popping the stack until we find a node that has an unvisited adjacent node. In this case, there's none and we keep popping until the stack is empty. Let us look at how we can implement this in JavaScript.
DFS(node) {
   // Create a Stack and add our initial node in it
   let s = new Stack(this.nodes.length);
   let explored = new Set();
   s.push(node);

   // Mark the first node as explored
   explored.add(node);

   // We'll continue till our Stack gets empty
   while (!s.isEmpty()) {
      let t = s.pop();

   // Log every element that comes out of the Stack
      console.log(t);

   // 1. In the edges object, we search for nodes this node is directly connected to.
   // 2. We filter out the nodes that have already been explored.
   // 3. Then we mark each unexplored node as explored and push it to the Stack.
   this.edges[t]
   .filter(n => !explored.has(n))
   .forEach(n => {
      explored.add(n);
      s.push(n);
      });
   }
}
Well, that was easy. We really just swapped the queue out for the stack and voila, we have DFS. That is really the only difference between the 2. DFS can also be implemented using recursion. But that is best avoided in this case as a bigger graph means we need extra memory just to keep track of the call stack.
You can test this using −
let g = new Graph();
g.addNode("A");
g.addNode("B");
g.addNode("C");
g.addNode("D");
g.addNode("E");
g.addNode("F");
g.addNode("G");

g.addEdge("A", "C");
g.addEdge("A", "B");
g.addEdge("A", "D");
g.addEdge("D", "E");
g.addEdge("E", "F");
g.addEdge("B", "G");

g.DFS("A");
This will give the output.
A
D
E
F
B
G
C
Java program to implement binary search

Binary search is a fast search algorithm with run-time complexity of Ο(log n). This search algorithm works on the principle of divide and conquer. For this algorithm to work properly, the data collection should be in the sorted form.
The binary search looks for a particular item by comparing the middle most item of the collection. If a match occurs, then the index of the item is returned. If the middle item is greater than the item, then the item is searched in the sub-array to the left of the middle item. Otherwise, the item is searched for in the sub-array to the right of the middle item. This process continues on the sub-array as well until the size of the subarray reduces to zero.
Live Demo
public class BinarySearch {
   public static void main(String args[]){
      int array[] = {10, 20, 25, 57, 63, 96};
      int size = array.length;
      int low = 0;
      int high = size-1;
      int value = 25;
      int mid = 0;
      mid = low +(high-low)/2;

      while(low<=high){
         if(array[mid] == value){
            System.out.println(mid);
            break;
         }
         else if(array[mid]<value)
         low = mid+1;
         else high = mid - 1;
      }
      mid = (low+high)/2;
   }
}
2
Scala - Higher-Order Functions

Scala allows the definition of higher-order functions. These are functions that take other functions as parameters, or whose result is a function.
Try the following example program, apply() function takes another function f and a value v and applies function f to v.
object Demo {
   def main(args: Array[String]) {
      println( apply( layout, 10) )
   }

   def apply(f: Int => String, v: Int) = f(v)

   def layout[A](x: A) = "[" + x.toString() + "]"
}
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
\>scalac Demo.scala
\>scala Demo

[10]


    82 Lectures 
     7 hours 

 Arnab Chakraborty

    23 Lectures 
     1.5 hours 

 Mukund Kumar Mishra

    52 Lectures 
     1.5 hours 

 Bigdata Engineer

    76 Lectures 
     5.5 hours 

 Bigdata Engineer

    69 Lectures 
     7.5 hours 

 Bigdata Engineer

    46 Lectures 
     4.5 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
Count minimum number of “move-to-front” moves to sort an array in C++

We are given with an array of numbers between 1 to n. The goal here is to find the no. of ‘move
to front’ operations required to sort the given array. The array has no repetition. The ‘move to
front’ operation picks an element and places at first position, here at index 0.
We will traverse the array from end, if element is at the correct position then no move else move
is required. For elements from 1 to n, the correct position in the array of element arr[i] should be
at index i+1. arr[0] should be 1, arr[1] should be 2 and.......arr[n-1] should be n.
Arr[]= { 4,3,2,1 }
Minimum move-to-front operations: 3
Pull 3, 3,4,2,1 count=1
Pull 2, 2,3,4,1 count=2
Pull 1, 1,2,3,4 count=3
Arr[]= { 6,1,2,5,4,3 }
Minimum move-to-front operations: 5
Pull 5, 5,6,1,2,4,3 count=1
Pull 4, 4,5,6,1,2,3 count=2
Pull 3, ,4,5,6,1,2 count=3
Pull 2, 2,3,4,5,6,1 count=4
Pull 1, 1,2,3,4,5,6 count=5
Integer array Arr[] stores the numbers 1 to n.
Integer array Arr[] stores the numbers 1 to n.
Integer variable size stores the length of array Arr[]
Integer variable size stores the length of array Arr[]
Function movetoFront(int arr[], int n) takes an array and its length as input and returns
the minimum number of ‘move-to-front’ operations required to sort that given array.
Function movetoFront(int arr[], int n) takes an array and its length as input and returns
the minimum number of ‘move-to-front’ operations required to sort that given array.
Count variable is initialized with size of array as all elements can be moved in case of
decreasing order array.
Count variable is initialized with size of array as all elements can be moved in case of
decreasing order array.
Start traversing from the last index and moving towards the front, if element value is the
same as count, (for sorted elements between 1 to n, n is last, n-1 is second last and so on)
then decrement count as that element is at the correct position.
Start traversing from the last index and moving towards the front, if element value is the
same as count, (for sorted elements between 1 to n, n is last, n-1 is second last and so on)
then decrement count as that element is at the correct position.
In this way at the end of the loop, count has the desired result.
In this way at the end of the loop, count has the desired result.
 Live Demo
#include <bits/stdc++.h>
using namespace std;
// Calculate minimum number of moves to arrange array
// in increasing order.
int movetoFront(int arr[], int n){
   //take count as all elements are correctly placed
   int count = n;
   // Traverse array from end
   for (int i=n-1; i >= 0; i--){
      // If current item is at its correct position,
         //decrement the count
      //range is 1 to n so every arr[i] should have value i+1
      //1 at 0 index, 2 at 1 index........
      if (arr[i] == count)
         count--;
   }
   return count;
}
int main(){
   int Arr[] = {5, 3, 4, 7, 2, 6, 1};
   int size = 7;
   cout <<"Minimum 'move-to-front' to sort array:"<< movetoFront(Arr, size);
   return 0;
}
Minimum 'move-to-front' to sort array:6
C library function - memcmp()

The C library function int memcmp(const void *str1, const void *str2, size_t n)) compares the first n bytes of memory area str1 and memory area str2.
Following is the declaration for memcmp() function.
int memcmp(const void *str1, const void *str2, size_t n)
str1 − This is the pointer to a block of memory.
str1 − This is the pointer to a block of memory.
str2 − This is the pointer to a block of memory.
str2 − This is the pointer to a block of memory.
n − This is the number of bytes to be compared.
n − This is the number of bytes to be compared.
if Return value < 0 then it indicates str1 is less than str2.
if Return value < 0 then it indicates str1 is less than str2.
if Return value > 0 then it indicates str2 is less than str1.
if Return value > 0 then it indicates str2 is less than str1.
if Return value = 0 then it indicates str1 is equal to str2.
if Return value = 0 then it indicates str1 is equal to str2.
The following example shows the usage of memcmp() function.
#include <stdio.h>
#include <string.h>

int main () {
   char str1[15];
   char str2[15];
   int ret;

   memcpy(str1, "abcdef", 6);
   memcpy(str2, "ABCDEF", 6);

   ret = memcmp(str1, str2, 5);

   if(ret > 0) {
      printf("str2 is less than str1");
   } else if(ret < 0) {
      printf("str1 is less than str2");
   } else {
      printf("str1 is equal to str2");
   }
   
   return(0);
}
Let us compile and run the above program that will produce the following result −
str2 is less than str1


    12 Lectures 
     2 hours 

 Nishant Malik

    12 Lectures 
     2.5 hours 

 Nishant Malik

    48 Lectures 
     6.5 hours 

 Asif Hussain

    12 Lectures 
     2 hours 

 Richa Maheshwari

    20 Lectures 
     3.5 hours 

 Vandana Annavaram

    44 Lectures 
     1 hours 

 Amit Diwan
 Print
 Add Notes
 Bookmark this page
Difference between Entity and Object - GeeksforGeeks

04 May, 2020
A database is a organized collection of logical related data stored in a software named Database Management Systems (DBMS). Before inserting the data into the system, it needs to be in the form of a model for appropriate understanding of the database. Many models were introduced and Entity-Relationship model is one among them. It is a graphical representation of the data which gives the whole view of the data. There are basic building units of this E-R model where entity and object are among them.
1. Entity:An entity is a real time object that is different from others. An entity can defined using its attributes. They are a part of entity. Entities can be represented in pictorial form. Collection of similar entities is an entity set.
Example: 
A computer, car, place, software 
2. Object:An entity that contains both attributes and actions is its object. It is defined by its life span, name and object identifier. Every object has two components: State and Behavior.
Example: 
views, indices, sequences 
Differences between entity and object are:
DBMS
Difference Between
GATE CS
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SQL Interview Questions
SQL Trigger | Student Database
CTE in SQL
Difference between Clustered and Non-clustered index
Data Preprocessing in Data Mining
Difference between BFS and DFS
Class method vs Static method in Python
Differences between TCP and UDP
Difference between var, let and const keywords in JavaScript
Differences between IPv4 and IPv6
Java Program to Print Multiplication Table for Any Number - GeeksforGeeks

19 Jan, 2021

Given a number n as input, we need to print its table, where N>0.
Example
Input 1 :- N = 7
Output  :- 
     7 * 1 = 7
    7 * 2 = 14
    7 * 3 = 21
    7 * 4 = 28
    7 * 5 = 35
    7 * 6 = 42
    7 * 7 = 49
    7 * 8 = 56
    7 * 9 = 63
    7 * 10 = 70
Two ways are shown to Print Multiplication Table for any Number:

Using for loop for printing the multiplication table upto 10.
Using while loop for printing the multiplication table upto the given range.

Using for loop for printing the multiplication table upto 10.
Using while loop for printing the multiplication table upto the given range.
Method 1: Generating Multiplication Table using for loop upto 10
Java
 

 
 










// Java Program to print the multiplication table of the 
// number N. 
  
class GFG { 
    public static void main(String[] args) 
    { 
        // number n for which we have to print the 
        // multiplication table. 
        int N = 7; 
  
        // looping from 1 to 10 to print the multiplication 
        // table of the number. 
        // using for loop 
        for (int i = 1; i <= 10; i++) { 
            // printing the N*i,ie ith multiple of N. 
            System.out.println(N + " * " + i + " = "
                               + N * i); 
        } 
    } 
}






7 * 1 = 7
7 * 2 = 14
7 * 3 = 21
7 * 4 = 28
7 * 5 = 35
7 * 6 = 42
7 * 7 = 49
7 * 8 = 56
7 * 9 = 63
7 * 10 = 70
Method 2:- Generating Multiplication Table using while loop upto any given range
Java
 

 
 










// Java Program to print the multiplication table of 
// number N using while loop 
  
class GFG { 
    public static void main(String[] args) 
    { 
        // number n for which we have to print the 
        // multiplication table. 
        int N = 7; 
  
        int range = 18; 
  
        // looping from 1 to range to print the 
        // multiplication table of the number. 
        int i = 1; 
  
        // using while loop 
        while (i <= range) { 
  
            // printing the N*i,ie ith multiple of N. 
            System.out.println(N + " * " + i + " = "
                               + N * i); 
            i++; 
        } 
    } 
}






7 * 1 = 7
7 * 2 = 14
7 * 3 = 21
7 * 4 = 28
7 * 5 = 35
7 * 6 = 42
7 * 7 = 49
7 * 8 = 56
7 * 9 = 63
7 * 10 = 70
7 * 11 = 77
7 * 12 = 84
7 * 13 = 91
7 * 14 = 98
7 * 15 = 105
7 * 16 = 112
7 * 17 = 119
7 * 18 = 126

Picked


Technical Scripter 2020


Java


Java Programs


Technical Scripter

Writing code in comment? 
                                    Please use ide.geeksforgeeks.org, 
                                    generate link and share the link here.
                                
Stream In Java
Exceptions in Java
Constructors in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?
Iterate through List in Java
SAP ABAP - Report Programming

A report is a presentation of data in an organized structure. Many database management systems include a report writer that enables you to design and generate reports. SAP applications support report creation.
A classical report is created by using the output data in the WRITE statement inside a loop. They do not contain any sub-reports. SAP also provides some standard reports such as RSCLTCOP that is used to copy tables across clients and RSPARAM that is used to display instance parameters.
These reports consist of only one screen as an output. We can use various events such as INITIALIZATON & TOP-OF-PAGE to create a classical report, and each event has its own importance during the creation of a classical report. Each of these events is associated to a specific user action and is triggered only when the user performs that action.
Following is a table describing the events and descriptions −
INITIALIZATON
Triggered before displaying the selection screen.
AT SELECTION-SCREEN
Triggered after processing of the user input on the selection screen. This event verifies the user input prior to the execution of a program. After processing the user input, the selection screen remains in the active mode.
START-OF-SELECTION
Triggered only after the processing of the selection screen is over; that is, when the user clicks the Execute icon on the selection screen.
END-OF-SELECTION
Triggered after the last statement in the START-OF-SELECTON event is executed.
TOP-OF-PAGE
Triggered by the first WRITE statement to display the data on a new page.
END-OF-PAGE
Triggered to display the text at the end of a page in a report. Note, that this event is the last event while creating a report, and should be combined with the LINE-COUNT clause of the REPORT statement.
Let's create a classical report. We will display the information stored in the standard database MARA (contains general material data) by using a sequence of statements in ABAP editor.
REPORT ZREPORT2 
LINE-SIZE 75 
LINE-COUNT 30(3) 
NO STANDARD PAGE HEADING. 
Tables: MARA. 
TYPES: Begin of itab, 

MATNR TYPE MARA-MATNR, 
MBRSH TYPE MARA-MBRSH, 
MEINS TYPE MARA-MEINS, 
MTART TYPE MARA-MTART, 

End of itab. 

DATA: wa_ma TYPE itab,
      it_ma TYPE STANDARD TABLE OF itab.
		
SELECT-OPTIONS: MATS FOR MARA-MATNR OBLIGATORY. 
INITIALIZATION. 
MATS-LOW = '1'. 
MATS-HIGH = '500'. 

APPEND MATS. 
AT SELECTION-SCREEN. .
IF MATS-LOW = ' '. 
MESSAGE I000(ZKMESSAGE). 
ELSEIF MATS-HIGH = ' '. 
MESSAGE I001(ZKMESSAGE). 
ENDIF. 

TOP-OF-PAGE. 
WRITE:/ 'CLASSICAL REPORT CONTAINING GENERAL MATERIAL DATA  
FROM THE TABLE MARA' COLOR 7. 
ULINE. 
WRITE:/ 'MATERIAL' COLOR 1, 

24 'INDUSTRY' COLOR 2, 
38 'UNITS' COLOR 3, 
53 'MATERIAL TYPE' COLOR 4. 
ULINE. 
END-OF-PAGE. 

START-OF-SELECTION. 
SELECT MATNR MBRSH MEINS MTART FROM MARA  
INTO TABLE it_ma WHERE MATNR IN MATS. 
LOOP AT it_ma into wa_ma. 
WRITE:/  wa_ma-MATNR, 

25 wa_ma-MBRSH, 
40 wa_ma-MEINS, 
55 wa_ma-MTART. 
ENDLOOP. 
END-OF-SELECTION. 

ULINE. 
WRITE:/ 'CLASSICAL REPORT HAS BEEN CREATED' COLOR 7.
ULINE. 
SKIP. 
The above code produces the following output containing the general material data from the standard table MARA −
How to add a header to a CSV file in Python?

11 Dec, 2020
A CSV file contains a tabular sort of data where each row contains comma-separated values. The columns may contain values belonging to different data structures. Python provides a wide range of methods and modules to carry out the interconversion of the CSV file to a pandas data frame and vice versa. A header of the CSV file is an array of values assigned to each of the columns. It acts as a row header for the data. Initially, the CSV file is converted to a data frame and then a header is added to the data frame. The contents of the data frame are again stored back into the CSV file. 
In this article, we are going to add a header to a CSV file in Python.
Method #1: Using header argument in to_csv() method.
Initially, create a header in the form of a list, and then add that header to the CSV file using to_csv() method.
The following CSV file gfg.csv is used for the operation:
Python3
# importing python packageimport pandas as pd  # read contents of csv filefile = pd.read_csv("gfg.csv")print("\nOriginal file:")print(file)  # adding headerheaderList = ['id', 'name', 'profession']  # converting data frame to csvfile.to_csv("gfg2.csv", header=headerList, index=False)  # display modified csv filefile2 = pd.read_csv("gfg2.csv")print('\nModified file:')print(file2)
Output: 
The CSV file gfg2.csv is created:
Method #2: Using DictWriter() method
Another approach of using DictWriter() can be used to append a header to the contents of a CSV file. The fieldnames attribute can be used to specify the header of the CSV file and the delimiter argument separates the values by the delimiter given in csv module is needed to carry out the addition of header. The writeheader() method is then invoked on csvwriter object, without passing any arguments.
Python3
# import required modulesimport pandas as pdimport csv  # assign header columnsheaderList = ['col1', 'col2', 'col3', 'col4']  # open CSV file and assign headerwith open("gfg3.csv", 'w') as file:    dw = csv.DictWriter(file, delimiter=',',                         fieldnames=headerList)    dw.writeheader()  # display csv filefileContent = pd.read_csv("gfg3.csv")fileContent
Output:
The new CSV file gfg3.csv created is:
Note: This method is only applicable to empty CSV files.
python-csv
Python-pandas
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
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Python | datetime.timedelta() function
fmt.Printf() Function in Golang With Examples

05 Mar, 2021
In Go language, fmt package implements formatted I/O with functions analogous to C’s printf() and scanf() function. The fmt.Printf() function in Go language formats according to a format specifier and writes to standard output. Moreover, this function is defined under the fmt package. Here, you need to import the “fmt” package in order to use these functions.
Syntax: 
func Printf(format string, a ...interface{}) (n int, err error)
Parameters: This function accepts two parameters which are illustrated below: 
format string: This contains some strings along with some verbs.
a ...interface{}: This contains specified constant variables.
Return Value: It returns the number of bytes written and any write error encountered.
Conversion Characters:
Example 1:
Go
// Golang program to illustrate the usage of// fmt.Printf() function // Including the main packagepackage main // Importing fmtimport (    "fmt") // Calling mainfunc main() {     // Declaring some const variables    const name, dept = "GeeksforGeeks", "CS"     // Calling Printf() function    fmt.Printf("%s is a %s Portal.\n", name, dept)     // It is conventional not to worry about any    // error returned by Printf. }
Output: 
GeeksforGeeks is a CS portal.
Example 2:
Go
// Golang program to illustrate the usage of// fmt.Printf() function // Including the main packagepackage main // Importing fmtimport (    "fmt") // Calling mainfunc main() {     // Declaring some const variables    const num1, num2, num3 = 5, 10, 15     // Calling Printf() function    fmt.Printf("%d + %d = %d\n", num1, num2, num3)     // It is conventional not to worry about any    // error returned by Printf. }
Output: 
5 + 10 = 15
Example 3:
Go
// Golang program to illustrate the usage of// fmt.Printf() function // Including the main packagepackage main // Importing fmtimport (    "fmt") // Calling mainfunc main(){     var str = "Geeksforgeeks"      fmt.Printf("The string is %s \n", str)    var num1 int = 21      fmt.Printf("The decimal value is %d \n", num1)    var num2 float32 = 7.786      fmt.Printf("The floating point is %g \n", num2)    var num3 int = 14      fmt.Printf("The binary value of num3 is %b \n", num3)    var num4 = 4 + 1i    fmt.Printf("Scientific Notation of num4 : %e \n", num4)}
Output:
The string is Geeksforgeeks  
The decimal value is 21  
The floating point is 7.786  
The binary value of num3 is 1110  
Scientific Notation of num4 : (4.000000e+00+1.000000e+00i)
yuvraj_chandra
Golang-fmt
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Pandas Series.isna()

12 Feb, 2019
Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index.
Pandas Series.isna() function detect missing values in the given series object. It return a boolean same-sized object indicating if the values are NA. Missing values gets mapped to True and non-missing value gets mapped to False.
Syntax: Series.isna()
Parameter : None
Returns : boolean
Example #1: Use Series.isna() function to detect missing values in the given series object.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series([10, 25, 3, 25, 24, 6])  # Create the Indexindex_ = ['Coca Cola', 'Sprite', 'Coke', 'Fanta', 'Dew', 'ThumbsUp']  # set the indexsr.index = index_  # Print the seriesprint(sr)
Output :Now we will use Series.isna() function to detect all the missing values in the given series object.
# detect missing valuesresult = sr.isna()  # Print the resultprint(result)
Output :As we can see in the output, the Series.isna() function has returned an object containing boolean values. All values have been mapped to False because there is no missing value in the given series object. Example #2 : Use Series.isna() function to detect missing values in the given series object.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series([11, 21, 8, 18, 65, None, 32, 10, 5, 24, None])  # Create the Indexindex_ = pd.date_range('2010-10-09', periods = 11, freq ='M')  # set the indexsr.index = index_  # Print the seriesprint(sr)
Output :
Now we will use Series.isna() function to detect all the missing values in the given series object.
# detect missing valuesresult = sr.isna()  # Print the resultprint(result)
Output :As we can see in the output, the Series.isna() function has returned an object containing boolean values. All missing values have been mapped to True.
Python pandas-series
Python pandas-series-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Iterate over a list in Python
Python Classes and Objects
Convert integer to string in Python
How to convert CSV into array in R?

02 Jul, 2021
In this article, we are going to see how to convert CSV into an array in R Programming Language. If we load this file into any environment like python, R language .etc, the data will be displayed in rows and columns format, let us convert CSV file into an array. Each and every column in the CSV will be converted into array of multiple dimensions.
Method 1 : Using loop.
Here we will use loop to convert all the columns in to the array. 
R
setwd("C:/Users/KRISHNA KARTHIKEYA/Documents") df = read.csv("item.csv") lst1 = list() for(i in 1:ncol(df)) {       lst1[[i]] <- df[ , i]   } names(lst1) = colnames(df) arr = array(unlist(lst1),            dim = c(5, 5, 3))print(arr)
Output:
Explanation :
In the first step we changed the directory using setwd() function to where the csv file is located.
In the next step we have imported a CSV file into R environment using read.csv() function.
Then created a empty list.
Using for loop extracted every element by column wise and passed to list() function.
Converted list to array using array() by passing list variable as parameter. In the array() function we have used unlist() function. The unlist() function is used to convert list to vector. So, the unlist() with list variable is passed to array().
Finally, printed the array variable.
Method 2: Extract every column into separate variable and pass to array() function.
R
setwd('C:/Users/KRISHNA KARTHIKEYA/Documents') df = read.csv('item.csv')a = df$idb = df$itemc = df$quantityd = df$pricee = df$boughtf = df$forenoong = df$afternoonarr = array(c(a, b, c, d, e, f, g),            dim = c(5, 3 ,2))print(arr)
Output:
Explanation :
In the first step we changed the directory using setwd() function to where the csv file is located.
In the next step we have imported a CSV file into R environment using read.csv() function.
Using $ operator we have extracted every column into separate variable.
Pass all the column variables to array( ) and give dimensions using dim attribute.
Finally, printed the array variable.
sweetyty
R-CSV
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Filter data by multiple conditions in R using Dplyr
Printing Output of an R Program
Group by function in R using Dplyr
How to Replace specific values in column in R DataFrame ?
How to filter R DataFrame by values in a column?
R Programming Language - Introduction
Loops in R (for, while, repeat)
How to change Row Names of DataFrame in R ?
Creating a Data Frame from Vectors in R Programming
Change Color of Bars in Barchart using ggplot2 in R
Get Time Zone of a Given Location using Python

17 May, 2022
In this article, we are going to see how to get the time zone from a given location. The Timezonefinder module is able to find the timezone of any point on earth (coordinates) offline. Before starting we need to install this module.
timezonefinder: This module does not built in with Python. To install this type the below command in the terminal.
timezonefinder: This module does not built in with Python. To install this type the below command in the terminal.
pip install timezonefinder

 Geopy: .geopy makes it easy for Python developers to locate the coordinates of addresses, cities, countries, and landmarks across the world. To install the Geopy module, run the following command in your terminal.
pip install geopy

Let’s understand this module with Step by step:
Step 1: import TimezoneFinder module
Python3
from timezonefinder import TimezoneFinder
Step 2:  make an object of TimezoneFinder.
Python3
# object creationobj = TimezoneFinder()
Step 3: Pass the latitude and longitude in a timezone_at() method and it return the time zone of a given location.
Python3
# pass the longitude and latitude# in timezone_at and# it return time zone latitude = 25.6093239longitude = 85.1235252obj.timezone_at(lng=latitude, lat=longitude)
Output:
'Asia/Kolkata'

Now let write a script to get timezone with a specific location.
Approach:
Import the module
Initialize Nominatim API to get location from the input string.
Get  latitude and longitude with geolocator.geocode() function.
Pass the latitude and longitude in a timezone_at() method and it returns the time zone of a given location.
Code:
Python3
# importing modulefrom geopy.geocoders import Nominatimfrom timezonefinder import TimezoneFinder  # initialize Nominatim APIgeolocator = Nominatim(user_agent="geoapiExercises")  # input as a geeklad = "Dhaka"print("Location address:", lad)  # getting Latitude and Longitudelocation = geolocator.geocode(lad)  print("Latitude and Longitude of the said address:")print((location.latitude, location.longitude))  # pass the Latitude and Longitude# into a timezone_at# and it return timezoneobj = TimezoneFinder()  # returns 'Europe/Berlin'result = obj.timezone_at(lng=location.longitude, lat=location.latitude)print("Time Zone : ", result)
Output:
Location address: Dhaka
Latitude and Longitude of the said address:
(23.810651, 90.4126466)
Time Zone :  Asia/Dhaka

rkbhola5
Python-projects
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
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
NLP | Chunking and chinking with RegEx

27 Sep, 2021
Chunk extraction or partial parsing is a process of meaningful extracting short phrases from the sentence (tagged with Part-of-Speech). Chunks are made up of words and the kinds of words are defined using the part-of-speech tags. One can even define a pattern or words that can’t be a part of chuck and such words are known as chinks. A ChunkRule class specifies what words or patterns to include and exclude in a chunk. 
Defining Chunk patterns : Chuck patterns are normal regular expressions which are modified and designed to match the part-of-speech tag designed to match sequences of part-of-speech tags. Angle brackets are used to specify an individual tag for example – to match a noun tag. One can define multiple tags in the same way. 
Code #1 : Converting chunks to RegEx Pattern. 
Python3
# Laading Libraryfrom nltk.chunk.regexp import tag_pattern2re_pattern # Chunk Pattern to RegEx Patternprint("Chunk Pattern : ", tag_pattern2re_pattern('<DT>?<NN.*>+'))
Output : 
Chunk Pattern :  ()?(<(NN[^\{\}]*)>)+
Curly Braces are used to specify a chunk like {} and to specify the chink pattern one can just flip the braces }{. For a particular phrase type, these rules (chunk and a chink pattern) can be combined into grammar.
Code #2 : Parsing the sentence with RegExParser.  
Python3
from nltk.chunk import RegexpParser # Introducing the Patternchunker = RegexpParser(r'''NP:{<DT><NN.*><.*>*<NN.*>}}<VB.*>{''') chunker.parse([('the', 'DT'), ('book', 'NN'), (    'has', 'VBZ'), ('many', 'JJ'), ('chapters', 'NNS')])
Output : 
Tree('S', [Tree('NP', [('the', 'DT'), ('book', 'NN')]), ('has', 'VBZ'), 
Tree('NP', [('many', 'JJ'), ('chapters', 'NNS')])])
 
sumitgumber28
anikakapoor
Natural-language-processing
Python-nltk
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Linear Regression
Reinforcement learning
Supervised and Unsupervised learning
Search Algorithms in AI
Decision Tree Introduction with example
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe