title stringlengths 3 221 | text stringlengths 17 477k | parsed listlengths 0 3.17k |
|---|---|---|
Calling Stored Procedure inside foreach PHP Codeigniter | The code inside the 'Model' and the 'Controller' needs to be changed to include code that is shown below −
$header = $this->model_name->call_head();
foreach($header as $item) {
$name = $item['name'];
$array['name'] = $name;
$array['data'] = $item['data'];
$child_val = $this->model_name->call_child($name);
foreach($child_val as $value) {
$array['child'] = array(
'child_name' => $value['child_name'],
'child_data' => $value['child_data']
);
}
}
public function call_head() {
$query = "CALL PROCEDURE_HEAD()";
$result = $this->db->query($query)->result_array();
$query->next_result();
$query->free_result();
return $result;
}
public function call_child($name) {
$query = "CALL PROCEDURE_CHILD($name)";
$result = $this->db->query($query)->result_array();
$query->next_result();
$query->free_result();
return $result;
} | [
{
"code": null,
"e": 1169,
"s": 1062,
"text": "The code inside the 'Model' and the 'Controller' needs to be changed to include code that is shown below −"
},
{
"code": null,
"e": 1556,
"s": 1169,
"text": "$header = $this->model_name->call_head();\nforeach($header as $item) {\n $name = $item['name'];\n $array['name'] = $name;\n $array['data'] = $item['data'];\n $child_val = $this->model_name->call_child($name);\n foreach($child_val as $value) {\n $array['child'] = array(\n 'child_name' => $value['child_name'],\n 'child_data' => $value['child_data']\n );\n }\n}"
},
{
"code": null,
"e": 1958,
"s": 1556,
"text": "public function call_head() {\n $query = \"CALL PROCEDURE_HEAD()\";\n $result = $this->db->query($query)->result_array();\n $query->next_result();\n $query->free_result();\n return $result;\n}\npublic function call_child($name) {\n $query = \"CALL PROCEDURE_CHILD($name)\";\n $result = $this->db->query($query)->result_array();\n $query->next_result();\n $query->free_result();\n return $result;\n}"
}
] |
Passing arrays to methods in C#? | To pass arrays to methods, you need to pass an array as a method argument.
int displaySum(int[] arr, int size) {
}
Now call it −
sum = d.displaySum(myArr, 5 ) ;
Live Demo
using System;
namespace Test {
class Demo {
int displaySum(int[] arr, int size) {
int i;
int sum = 0;
for (i = 0; i < size; ++i) {
sum += arr[i];
}
return sum;
}
static void Main(string[] args) {
Demo d = new Demo();
int [] myArr = new int[] {59, 34, 76, 65, 12, 99};
int sum;
sum = d.displaySum(myArr, 5 ) ;
/* output the returned value */
Console.WriteLine( "Sum: {0} ", sum );
Console.ReadKey();
}
}
}
Sum: 246 | [
{
"code": null,
"e": 1137,
"s": 1062,
"text": "To pass arrays to methods, you need to pass an array as a method argument."
},
{
"code": null,
"e": 1177,
"s": 1137,
"text": "int displaySum(int[] arr, int size) {\n}"
},
{
"code": null,
"e": 1191,
"s": 1177,
"text": "Now call it −"
},
{
"code": null,
"e": 1223,
"s": 1191,
"text": "sum = d.displaySum(myArr, 5 ) ;"
},
{
"code": null,
"e": 1234,
"s": 1223,
"text": " Live Demo"
},
{
"code": null,
"e": 1799,
"s": 1234,
"text": "using System;\n\nnamespace Test {\n class Demo {\n int displaySum(int[] arr, int size) {\n int i;\n int sum = 0;\n\n for (i = 0; i < size; ++i) {\n sum += arr[i];\n }\n\n return sum;\n }\n \n static void Main(string[] args) {\n Demo d = new Demo();\n\n int [] myArr = new int[] {59, 34, 76, 65, 12, 99};\n int sum;\n\n sum = d.displaySum(myArr, 5 ) ;\n\n /* output the returned value */\n Console.WriteLine( \"Sum: {0} \", sum );\n Console.ReadKey();\n }\n }\n}"
},
{
"code": null,
"e": 1808,
"s": 1799,
"text": "Sum: 246"
}
] |
Apache Flink - Setup/Installation | Before the start with the setup/ installation of Apache Flink, let us check whether we have Java 8 installed in our system.
We will now proceed by downloading Apache Flink.
wget http://mirrors.estointernet.in/apache/flink/flink-1.7.1/flink-1.7.1-bin-scala_2.11.tgz
Now, uncompress the tar file.
tar -xzf flink-1.7.1-bin-scala_2.11.tgz
Go to Flink's home directory.
cd flink-1.7.1/
Start the Flink Cluster.
./bin/start-cluster.sh
Open the Mozilla browser and go to the below URL, it will open the Flink Web Dashboard.
http://localhost:8081
This is how the User Interface of Apache Flink Dashboard looks like.
Now the Flink cluster is up and running.
46 Lectures
3.5 hours
Arnab Chakraborty
23 Lectures
1.5 hours
Mukund Kumar Mishra
16 Lectures
1 hours
Nilay Mehta
52 Lectures
1.5 hours
Bigdata Engineer
14 Lectures
1 hours
Bigdata Engineer
23 Lectures
1 hours
Bigdata Engineer
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2193,
"s": 2069,
"text": "Before the start with the setup/ installation of Apache Flink, let us check whether we have Java 8 installed in our system."
},
{
"code": null,
"e": 2242,
"s": 2193,
"text": "We will now proceed by downloading Apache Flink."
},
{
"code": null,
"e": 2335,
"s": 2242,
"text": "wget http://mirrors.estointernet.in/apache/flink/flink-1.7.1/flink-1.7.1-bin-scala_2.11.tgz\n"
},
{
"code": null,
"e": 2365,
"s": 2335,
"text": "Now, uncompress the tar file."
},
{
"code": null,
"e": 2406,
"s": 2365,
"text": "tar -xzf flink-1.7.1-bin-scala_2.11.tgz\n"
},
{
"code": null,
"e": 2436,
"s": 2406,
"text": "Go to Flink's home directory."
},
{
"code": null,
"e": 2453,
"s": 2436,
"text": "cd flink-1.7.1/\n"
},
{
"code": null,
"e": 2478,
"s": 2453,
"text": "Start the Flink Cluster."
},
{
"code": null,
"e": 2502,
"s": 2478,
"text": "./bin/start-cluster.sh\n"
},
{
"code": null,
"e": 2590,
"s": 2502,
"text": "Open the Mozilla browser and go to the below URL, it will open the Flink Web Dashboard."
},
{
"code": null,
"e": 2612,
"s": 2590,
"text": "http://localhost:8081"
},
{
"code": null,
"e": 2681,
"s": 2612,
"text": "This is how the User Interface of Apache Flink Dashboard looks like."
},
{
"code": null,
"e": 2722,
"s": 2681,
"text": "Now the Flink cluster is up and running."
},
{
"code": null,
"e": 2757,
"s": 2722,
"text": "\n 46 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 2776,
"s": 2757,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 2811,
"s": 2776,
"text": "\n 23 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 2832,
"s": 2811,
"text": " Mukund Kumar Mishra"
},
{
"code": null,
"e": 2865,
"s": 2832,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 2878,
"s": 2865,
"text": " Nilay Mehta"
},
{
"code": null,
"e": 2913,
"s": 2878,
"text": "\n 52 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 2931,
"s": 2913,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 2964,
"s": 2931,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 2982,
"s": 2964,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 3015,
"s": 2982,
"text": "\n 23 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3033,
"s": 3015,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 3040,
"s": 3033,
"text": " Print"
},
{
"code": null,
"e": 3051,
"s": 3040,
"text": " Add Notes"
}
] |
Animation of Tower Of Hanoi using computer graphics in C/C++ - GeeksforGeeks | 18 Apr, 2022
The task is to design the Tower of Hanoi using computer graphics in C/C++.
Tower Of Hanoi: It is a mathematical problem where there are three towers and N numbers of disks. The problem is to move all the disks from the first tower to the third tower with the following rules:
Only one disk can be moved at a time and cannot move two or more than two disks at a time.
While moving the disk user have to remember that the smaller disk will always be on top of a bigger one.
That means the bigger one will be at the bottom of the tower & the smaller one will be at the top of the tower.
Function Used:
rectangle(l, t, r, b): A function from graphics.h header file which draw a rectangle from left(l) to right(r) & from top(t) to bottom(b).
line(a1, b1, a2, b2): A function from graphics.h header file which draws a line from the point (a1, b1) to the point (a2, b2).
setfillstyle( pattern, color): A function from graphics.h header file by which we can give a pattern of drawing & also a specific color.
floodfill( a, b, c): A function from graphics.h header file by which we can color in a specific bounded area with (a, b) as the center & c as the border color.
outtextxy(int x, int y, char *string): A function from graphics.h header file by which we can print any statements where, x, y are coordinates of the point and, the third argument contains the address of the string to be displayed.
settextstyle(int font, int direction, int font_size): A function from graphics.h header file by which we can make the style of the printable text where font argument specifies the font of the text, Direction can be HORIZ_DIR (Left to right) or VERT_DIR(Bottom to top).
Approach:
Here made an animation where 3 disk Tower Of Hanoi Problem is implemented. The full process will complete in 7 phases.
Total nine functions are defined , start(), p1(), p2(), p3(), p4(), p5(), p6(), p7(), outline().
First, call start() function. There print a message ‘Beginning State’. Then implement a total of three disks using the rectangle() function. Then color it. The lower bigger one is colored with Red, the middle one is colored with Blue & the smaller top one is colored with Green. All coloring is done by setfillstyle() and floodfill() functions. At last call outline().
In outline() function implement the towers using line() function and print the number of towers also.
Then call p1() function. cleardevice() function will clear the screen. Here, move the smaller Green disk to the third tower. Then call outline() function. Also, print the message ‘1st Phase’.
Then call p2() function. cleardevice() function will clear the screen. Here, move the smaller Blue disk to the second tower. Then will also call the outline() function. Also, print the message ‘2nd Phase’.
Then will call the p3() function. cleardevice() function will clear the screen. Here, move the smaller Green disk to the second tower on the top of the Blue disk. Then will also call the outline() function. Also, print the message ‘3rd Phase’.
Then will call the p4() function. cleardevice() function will clear the screen. Here, move the bigger Red disk to the third tower. Then will also call the outline() function. Also, print the message ‘4th Phase’.
Then will call the p5() function. cleardevice() function will clear the screen. Here, move the smaller Green disk to the first tower. Then also call outline() function. Also, print the message ‘5th Phase’.
Then call p6() function. cleardevice() function will clear the screen. Here, move the smaller Blue disk to the third tower on the top of Red disk. Then will also call the outline() function. Also, print the message ‘6th Phase’.
Then will call the p7() function. cleardevice() function will clear the screen. Here, move the smaller Green disk to the third tower on the top of the Blue disk. Then will also call the outline() function. Also, print the message ‘7th Phase’. Hence animation is completed.
Below is the implementation of the above approach:
C
// C program for the above approach#include <conio.h>#include <graphics.h>#include <stdio.h> // Function for moving the Green Disk// to Third Tower On Top Of Blue Diskvoid p7(){ getch(); cleardevice(); settextstyle(8, 0, 4); outtextxy(500, 50, "7th Phase"); setfillstyle(SOLID_FILL, BLUE); rectangle(850, 500, 950, 550); floodfill(855, 545, 15); setfillstyle(SOLID_FILL, GREEN); rectangle(875, 450, 925, 500); floodfill(880, 495, 15); setfillstyle(SOLID_FILL, RED); rectangle(825, 600, 975, 550); floodfill(830, 555, 15); // Calling outline() function outline();} // Function to find the moving the Blue// Disk To Third Tower On Top Of Red Diskvoid p6(){ getch(); cleardevice(); settextstyle(8, 0, 4); outtextxy(500, 50, "6th Phase"); setfillstyle(SOLID_FILL, BLUE); rectangle(850, 500, 950, 550); floodfill(855, 545, 15); setfillstyle(SOLID_FILL, GREEN); rectangle(275, 600, 325, 550); floodfill(280, 595, 15); setfillstyle(SOLID_FILL, RED); rectangle(825, 600, 975, 550); floodfill(830, 555, 15); // Calling outline() function outline();} // Function to find the moving Green Disk// To the First Towervoid p5(){ getch(); cleardevice(); settextstyle(8, 0, 4); outtextxy(500, 50, "5th Phase"); setfillstyle(SOLID_FILL, BLUE); rectangle(550, 550, 650, 600); floodfill(555, 595, 15); setfillstyle(SOLID_FILL, GREEN); rectangle(275, 600, 325, 550); floodfill(280, 595, 15); setfillstyle(SOLID_FILL, RED); rectangle(825, 600, 975, 550); floodfill(830, 555, 15); // Calling outline() function outline();} // Moving Red Disk To Third Towervoid p4(){ getch(); cleardevice(); settextstyle(8, 0, 4); outtextxy(500, 50, "4th Phase"); setfillstyle(SOLID_FILL, BLUE); rectangle(550, 550, 650, 600); floodfill(555, 595, 15); setfillstyle(SOLID_FILL, GREEN); rectangle(575, 500, 625, 550); floodfill(580, 545, 15); setfillstyle(SOLID_FILL, RED); rectangle(825, 600, 975, 550); floodfill(830, 555, 15); // Calling outline() function outline();} // Function for moving the Green Disk// To Second Tower On Top Of Blue Diskvoid p3(){ getch(); cleardevice(); settextstyle(8, 0, 4); outtextxy(500, 50, "3rd Phase"); setfillstyle(SOLID_FILL, BLUE); rectangle(550, 550, 650, 600); floodfill(555, 595, 15); setfillstyle(SOLID_FILL, GREEN); rectangle(575, 500, 625, 550); floodfill(580, 545, 15); setfillstyle(SOLID_FILL, RED); rectangle(225, 550, 375, 600); floodfill(230, 590, 15); // Calling outline() function outline();} // Function for moving the Blue Disk// To Second Towervoid p2(){ getch(); cleardevice(); settextstyle(8, 0, 4); outtextxy(500, 50, "2nd Phase"); setfillstyle(SOLID_FILL, BLUE); rectangle(550, 550, 650, 600); floodfill(555, 595, 15); setfillstyle(SOLID_FILL, GREEN); rectangle(875, 600, 925, 550); floodfill(880, 595, 15); setfillstyle(SOLID_FILL, RED); rectangle(225, 550, 375, 600); floodfill(230, 590, 15); // Calling outline() function outline();} // Function for moving the Green Disk// To Third Towervoid p1(){ getch(); cleardevice(); settextstyle(8, 0, 4); outtextxy(500, 50, "1st Phase"); setfillstyle(SOLID_FILL, GREEN); rectangle(875, 600, 925, 550); floodfill(880, 595, 15); setfillstyle(SOLID_FILL, RED); rectangle(225, 550, 375, 600); floodfill(230, 590, 15); setfillstyle(SOLID_FILL, BLUE); rectangle(250, 500, 350, 550); floodfill(255, 545, 15); // Calling outline() function outline();} // Function to start the animationsvoid start(){ // Starting Condition cleardevice(); settextstyle(8, 0, 4); outtextxy(500, 50, "Beginning State"); // Red Coloring Of Disk setfillstyle(SOLID_FILL, RED); rectangle(225, 550, 375, 600); floodfill(230, 590, 15); // Blue Coloring Of Disk setfillstyle(SOLID_FILL, BLUE); rectangle(250, 500, 350, 550); floodfill(255, 545, 15); // Green Coloring Of Disk setfillstyle(SOLID_FILL, GREEN); rectangle(275, 450, 325, 500); floodfill(285, 495, 15); // calling outline() function outline();} // Function to print the outlines of// the animationsvoid outline(){ // Main Base line(100, 600, 1100, 600); // 1st Line line(300, 600, 300, 300); // 2nd Line line(600, 600, 600, 300); // 3rd Line line(900, 600, 900, 300); // Printing Message settextstyle(8, 0, 2); outtextxy(290, 620, "(1)"); outtextxy(590, 620, "(2)"); outtextxy(890, 620, "(3)");}// Driver Codevoid main(){ int gd = DETECT, gm; // Initialize of gdriver with // DETECT macros initgraph(&gd, &gm, "C:\\turboc3\\bgi"); // Calling start() function start(); // Calling p1() function p1(); // Calling p2() function p2(); // Calling p3() function p3(); // Calling p4() function p4(); // Calling p5() function p5(); // Calling p6() function p6(); // Calling p7() function p7(); // Holding screen for a while getch(); // Close the initialized gdriver closegraph();}
Output:
simranarora5sos
c-graphics
computer-graphics
C Language
C Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TCP Server-Client implementation in C
Multithreading in C
Exception Handling in C++
Arrow operator -> in C/C++ with Examples
'this' pointer in C++
Strings in C
Arrow operator -> in C/C++ with Examples
UDP Server-Client implementation in C
C Program to read contents of Whole File
Header files in C/C++ and its uses | [
{
"code": null,
"e": 24208,
"s": 24180,
"text": "\n18 Apr, 2022"
},
{
"code": null,
"e": 24283,
"s": 24208,
"text": "The task is to design the Tower of Hanoi using computer graphics in C/C++."
},
{
"code": null,
"e": 24484,
"s": 24283,
"text": "Tower Of Hanoi: It is a mathematical problem where there are three towers and N numbers of disks. The problem is to move all the disks from the first tower to the third tower with the following rules:"
},
{
"code": null,
"e": 24575,
"s": 24484,
"text": "Only one disk can be moved at a time and cannot move two or more than two disks at a time."
},
{
"code": null,
"e": 24680,
"s": 24575,
"text": "While moving the disk user have to remember that the smaller disk will always be on top of a bigger one."
},
{
"code": null,
"e": 24792,
"s": 24680,
"text": "That means the bigger one will be at the bottom of the tower & the smaller one will be at the top of the tower."
},
{
"code": null,
"e": 24807,
"s": 24792,
"text": "Function Used:"
},
{
"code": null,
"e": 24945,
"s": 24807,
"text": "rectangle(l, t, r, b): A function from graphics.h header file which draw a rectangle from left(l) to right(r) & from top(t) to bottom(b)."
},
{
"code": null,
"e": 25073,
"s": 24945,
"text": "line(a1, b1, a2, b2): A function from graphics.h header file which draws a line from the point (a1, b1) to the point (a2, b2)."
},
{
"code": null,
"e": 25210,
"s": 25073,
"text": "setfillstyle( pattern, color): A function from graphics.h header file by which we can give a pattern of drawing & also a specific color."
},
{
"code": null,
"e": 25370,
"s": 25210,
"text": "floodfill( a, b, c): A function from graphics.h header file by which we can color in a specific bounded area with (a, b) as the center & c as the border color."
},
{
"code": null,
"e": 25602,
"s": 25370,
"text": "outtextxy(int x, int y, char *string): A function from graphics.h header file by which we can print any statements where, x, y are coordinates of the point and, the third argument contains the address of the string to be displayed."
},
{
"code": null,
"e": 25871,
"s": 25602,
"text": "settextstyle(int font, int direction, int font_size): A function from graphics.h header file by which we can make the style of the printable text where font argument specifies the font of the text, Direction can be HORIZ_DIR (Left to right) or VERT_DIR(Bottom to top)."
},
{
"code": null,
"e": 25881,
"s": 25871,
"text": "Approach:"
},
{
"code": null,
"e": 26000,
"s": 25881,
"text": "Here made an animation where 3 disk Tower Of Hanoi Problem is implemented. The full process will complete in 7 phases."
},
{
"code": null,
"e": 26097,
"s": 26000,
"text": "Total nine functions are defined , start(), p1(), p2(), p3(), p4(), p5(), p6(), p7(), outline()."
},
{
"code": null,
"e": 26466,
"s": 26097,
"text": "First, call start() function. There print a message ‘Beginning State’. Then implement a total of three disks using the rectangle() function. Then color it. The lower bigger one is colored with Red, the middle one is colored with Blue & the smaller top one is colored with Green. All coloring is done by setfillstyle() and floodfill() functions. At last call outline()."
},
{
"code": null,
"e": 26568,
"s": 26466,
"text": "In outline() function implement the towers using line() function and print the number of towers also."
},
{
"code": null,
"e": 26760,
"s": 26568,
"text": "Then call p1() function. cleardevice() function will clear the screen. Here, move the smaller Green disk to the third tower. Then call outline() function. Also, print the message ‘1st Phase’."
},
{
"code": null,
"e": 26966,
"s": 26760,
"text": "Then call p2() function. cleardevice() function will clear the screen. Here, move the smaller Blue disk to the second tower. Then will also call the outline() function. Also, print the message ‘2nd Phase’."
},
{
"code": null,
"e": 27210,
"s": 26966,
"text": "Then will call the p3() function. cleardevice() function will clear the screen. Here, move the smaller Green disk to the second tower on the top of the Blue disk. Then will also call the outline() function. Also, print the message ‘3rd Phase’."
},
{
"code": null,
"e": 27422,
"s": 27210,
"text": "Then will call the p4() function. cleardevice() function will clear the screen. Here, move the bigger Red disk to the third tower. Then will also call the outline() function. Also, print the message ‘4th Phase’."
},
{
"code": null,
"e": 27628,
"s": 27422,
"text": "Then will call the p5() function. cleardevice() function will clear the screen. Here, move the smaller Green disk to the first tower. Then also call outline() function. Also, print the message ‘5th Phase’."
},
{
"code": null,
"e": 27856,
"s": 27628,
"text": "Then call p6() function. cleardevice() function will clear the screen. Here, move the smaller Blue disk to the third tower on the top of Red disk. Then will also call the outline() function. Also, print the message ‘6th Phase’."
},
{
"code": null,
"e": 28130,
"s": 27856,
"text": "Then will call the p7() function. cleardevice() function will clear the screen. Here, move the smaller Green disk to the third tower on the top of the Blue disk. Then will also call the outline() function. Also, print the message ‘7th Phase’. Hence animation is completed. "
},
{
"code": null,
"e": 28181,
"s": 28130,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 28183,
"s": 28181,
"text": "C"
},
{
"code": "// C program for the above approach#include <conio.h>#include <graphics.h>#include <stdio.h> // Function for moving the Green Disk// to Third Tower On Top Of Blue Diskvoid p7(){ getch(); cleardevice(); settextstyle(8, 0, 4); outtextxy(500, 50, \"7th Phase\"); setfillstyle(SOLID_FILL, BLUE); rectangle(850, 500, 950, 550); floodfill(855, 545, 15); setfillstyle(SOLID_FILL, GREEN); rectangle(875, 450, 925, 500); floodfill(880, 495, 15); setfillstyle(SOLID_FILL, RED); rectangle(825, 600, 975, 550); floodfill(830, 555, 15); // Calling outline() function outline();} // Function to find the moving the Blue// Disk To Third Tower On Top Of Red Diskvoid p6(){ getch(); cleardevice(); settextstyle(8, 0, 4); outtextxy(500, 50, \"6th Phase\"); setfillstyle(SOLID_FILL, BLUE); rectangle(850, 500, 950, 550); floodfill(855, 545, 15); setfillstyle(SOLID_FILL, GREEN); rectangle(275, 600, 325, 550); floodfill(280, 595, 15); setfillstyle(SOLID_FILL, RED); rectangle(825, 600, 975, 550); floodfill(830, 555, 15); // Calling outline() function outline();} // Function to find the moving Green Disk// To the First Towervoid p5(){ getch(); cleardevice(); settextstyle(8, 0, 4); outtextxy(500, 50, \"5th Phase\"); setfillstyle(SOLID_FILL, BLUE); rectangle(550, 550, 650, 600); floodfill(555, 595, 15); setfillstyle(SOLID_FILL, GREEN); rectangle(275, 600, 325, 550); floodfill(280, 595, 15); setfillstyle(SOLID_FILL, RED); rectangle(825, 600, 975, 550); floodfill(830, 555, 15); // Calling outline() function outline();} // Moving Red Disk To Third Towervoid p4(){ getch(); cleardevice(); settextstyle(8, 0, 4); outtextxy(500, 50, \"4th Phase\"); setfillstyle(SOLID_FILL, BLUE); rectangle(550, 550, 650, 600); floodfill(555, 595, 15); setfillstyle(SOLID_FILL, GREEN); rectangle(575, 500, 625, 550); floodfill(580, 545, 15); setfillstyle(SOLID_FILL, RED); rectangle(825, 600, 975, 550); floodfill(830, 555, 15); // Calling outline() function outline();} // Function for moving the Green Disk// To Second Tower On Top Of Blue Diskvoid p3(){ getch(); cleardevice(); settextstyle(8, 0, 4); outtextxy(500, 50, \"3rd Phase\"); setfillstyle(SOLID_FILL, BLUE); rectangle(550, 550, 650, 600); floodfill(555, 595, 15); setfillstyle(SOLID_FILL, GREEN); rectangle(575, 500, 625, 550); floodfill(580, 545, 15); setfillstyle(SOLID_FILL, RED); rectangle(225, 550, 375, 600); floodfill(230, 590, 15); // Calling outline() function outline();} // Function for moving the Blue Disk// To Second Towervoid p2(){ getch(); cleardevice(); settextstyle(8, 0, 4); outtextxy(500, 50, \"2nd Phase\"); setfillstyle(SOLID_FILL, BLUE); rectangle(550, 550, 650, 600); floodfill(555, 595, 15); setfillstyle(SOLID_FILL, GREEN); rectangle(875, 600, 925, 550); floodfill(880, 595, 15); setfillstyle(SOLID_FILL, RED); rectangle(225, 550, 375, 600); floodfill(230, 590, 15); // Calling outline() function outline();} // Function for moving the Green Disk// To Third Towervoid p1(){ getch(); cleardevice(); settextstyle(8, 0, 4); outtextxy(500, 50, \"1st Phase\"); setfillstyle(SOLID_FILL, GREEN); rectangle(875, 600, 925, 550); floodfill(880, 595, 15); setfillstyle(SOLID_FILL, RED); rectangle(225, 550, 375, 600); floodfill(230, 590, 15); setfillstyle(SOLID_FILL, BLUE); rectangle(250, 500, 350, 550); floodfill(255, 545, 15); // Calling outline() function outline();} // Function to start the animationsvoid start(){ // Starting Condition cleardevice(); settextstyle(8, 0, 4); outtextxy(500, 50, \"Beginning State\"); // Red Coloring Of Disk setfillstyle(SOLID_FILL, RED); rectangle(225, 550, 375, 600); floodfill(230, 590, 15); // Blue Coloring Of Disk setfillstyle(SOLID_FILL, BLUE); rectangle(250, 500, 350, 550); floodfill(255, 545, 15); // Green Coloring Of Disk setfillstyle(SOLID_FILL, GREEN); rectangle(275, 450, 325, 500); floodfill(285, 495, 15); // calling outline() function outline();} // Function to print the outlines of// the animationsvoid outline(){ // Main Base line(100, 600, 1100, 600); // 1st Line line(300, 600, 300, 300); // 2nd Line line(600, 600, 600, 300); // 3rd Line line(900, 600, 900, 300); // Printing Message settextstyle(8, 0, 2); outtextxy(290, 620, \"(1)\"); outtextxy(590, 620, \"(2)\"); outtextxy(890, 620, \"(3)\");}// Driver Codevoid main(){ int gd = DETECT, gm; // Initialize of gdriver with // DETECT macros initgraph(&gd, &gm, \"C:\\\\turboc3\\\\bgi\"); // Calling start() function start(); // Calling p1() function p1(); // Calling p2() function p2(); // Calling p3() function p3(); // Calling p4() function p4(); // Calling p5() function p5(); // Calling p6() function p6(); // Calling p7() function p7(); // Holding screen for a while getch(); // Close the initialized gdriver closegraph();}",
"e": 33349,
"s": 28183,
"text": null
},
{
"code": null,
"e": 33357,
"s": 33349,
"text": "Output:"
},
{
"code": null,
"e": 33373,
"s": 33357,
"text": "simranarora5sos"
},
{
"code": null,
"e": 33384,
"s": 33373,
"text": "c-graphics"
},
{
"code": null,
"e": 33402,
"s": 33384,
"text": "computer-graphics"
},
{
"code": null,
"e": 33413,
"s": 33402,
"text": "C Language"
},
{
"code": null,
"e": 33424,
"s": 33413,
"text": "C Programs"
},
{
"code": null,
"e": 33522,
"s": 33424,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33560,
"s": 33522,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 33580,
"s": 33560,
"text": "Multithreading in C"
},
{
"code": null,
"e": 33606,
"s": 33580,
"text": "Exception Handling in C++"
},
{
"code": null,
"e": 33647,
"s": 33606,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 33669,
"s": 33647,
"text": "'this' pointer in C++"
},
{
"code": null,
"e": 33682,
"s": 33669,
"text": "Strings in C"
},
{
"code": null,
"e": 33723,
"s": 33682,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 33761,
"s": 33723,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 33802,
"s": 33761,
"text": "C Program to read contents of Whole File"
}
] |
Difference between Call by Value and Call by Reference | In programming on the basis of passing parameters to a function we classified function invocation into two : Call by value and Call by reference.As name suggest in both invocations we are calling function by type of parameters in one we are passing actual value of parameter and in other we are passing the location/reference of parameter.
Following are the important differences between Call by Value and Call by Reference.
ByValue.c
#include <stdio.h>
class ByValue{
void swapByValue(int, int); /* Prototype */
int main(){
int n1 = 10, n2 = 20;
swapByValue(n1, n2);
printf("n1: %d, n2: %d\n", n1, n2);
}
void swapByValue(int a, int b){
int t;
t = a; a = b; b = t;
}
}
n1: 10, n2: 20
ByReference.c
#include <stdio.h>
class ByReference{
void swapByReference(int*, int*);
int main(){
int n1 = 10, n2 = 20;
swapByReference(&n1, &n2);
printf("n1: %d, n2: %d\n", n1, n2);
}
void swapByReference(int *a, int *b){
int t;
t = *a; *a = *b; *b = t;
}
}
n1: 20, n2: 10 | [
{
"code": null,
"e": 1402,
"s": 1062,
"text": "In programming on the basis of passing parameters to a function we classified function invocation into two : Call by value and Call by reference.As name suggest in both invocations we are calling function by type of parameters in one we are passing actual value of parameter and in other we are passing the location/reference of parameter."
},
{
"code": null,
"e": 1487,
"s": 1402,
"text": "Following are the important differences between Call by Value and Call by Reference."
},
{
"code": null,
"e": 1497,
"s": 1487,
"text": "ByValue.c"
},
{
"code": null,
"e": 1777,
"s": 1497,
"text": "#include <stdio.h>\nclass ByValue{\n void swapByValue(int, int); /* Prototype */\n int main(){\n int n1 = 10, n2 = 20;\n swapByValue(n1, n2);\n printf(\"n1: %d, n2: %d\\n\", n1, n2);\n }\n void swapByValue(int a, int b){\n int t;\n t = a; a = b; b = t;\n }\n}"
},
{
"code": null,
"e": 1792,
"s": 1777,
"text": "n1: 10, n2: 20"
},
{
"code": null,
"e": 1806,
"s": 1792,
"text": "ByReference.c"
},
{
"code": null,
"e": 2096,
"s": 1806,
"text": "#include <stdio.h>\nclass ByReference{\n void swapByReference(int*, int*);\n int main(){\n int n1 = 10, n2 = 20;\n swapByReference(&n1, &n2);\n printf(\"n1: %d, n2: %d\\n\", n1, n2);\n }\n void swapByReference(int *a, int *b){\n int t;\n t = *a; *a = *b; *b = t;\n }\n}"
},
{
"code": null,
"e": 2111,
"s": 2096,
"text": "n1: 20, n2: 10"
}
] |
GATE | GATE-CS-2017 (Set 1) | Question 49 - GeeksforGeeks | 13 Aug, 2021
Consider the following two functions
void fun1(int n){
if(n == 0) return;
printf(“%d”, n);
fun2(n-2);
printf(“%d”, n);
}
void fun2(int n){
if(n == 0) return;
printf(“%d”, n);
fun1(++n);
printf(“%d”, n);
}
The output printed when fun1 (5) is called is(A) 53423122233445(B) 53423120112233(C) 53423122132435(D) 53423120213243Answer: (A)Explanation:
This solution is contributed by parul sharma.
Alternate Solution
This solution is contributed by Sumouli Chaudhary.
YouTubeGeeksforGeeks GATE Computer Science16.2K subscribersGATE PYQs 2017 and 2018 with Shubham Agrawal | GeeksforGeeks GATE CSEWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:0014:56 / 1:11:13•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=j9Vmf5yRw-I" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question
GATE-CS-2017 (Set 1)
GATE-GATE-CS-2017 (Set 1)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE CS 2019 | Question 27
GATE | GATE-IT-2004 | Question 66
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2006 | Question 49
GATE | GATE-CS-2004 | Question 3
GATE | GATE-CS-2017 (Set 2) | Question 42
GATE | GATE CS 2010 | Question 24
GATE | GATE-CS-2000 | Question 43
GATE | GATE CS 2021 | Set 1 | Question 47 | [
{
"code": null,
"e": 24474,
"s": 24446,
"text": "\n13 Aug, 2021"
},
{
"code": null,
"e": 24511,
"s": 24474,
"text": "Consider the following two functions"
},
{
"code": null,
"e": 24733,
"s": 24511,
"text": "void fun1(int n){ \n\n if(n == 0) return; \n printf(“%d”, n); \n fun2(n-2);\n printf(“%d”, n); \n}\n\nvoid fun2(int n){ \n\n if(n == 0) return; \n printf(“%d”, n); \n fun1(++n);\n printf(“%d”, n); \n}\n"
},
{
"code": null,
"e": 24875,
"s": 24733,
"text": "The output printed when fun1 (5) is called is(A) 53423122233445(B) 53423120112233(C) 53423122132435(D) 53423120213243Answer: (A)Explanation: "
},
{
"code": null,
"e": 24921,
"s": 24875,
"text": "This solution is contributed by parul sharma."
},
{
"code": null,
"e": 24940,
"s": 24921,
"text": "Alternate Solution"
},
{
"code": null,
"e": 24991,
"s": 24940,
"text": "This solution is contributed by Sumouli Chaudhary."
},
{
"code": null,
"e": 25891,
"s": 24991,
"text": "YouTubeGeeksforGeeks GATE Computer Science16.2K subscribersGATE PYQs 2017 and 2018 with Shubham Agrawal | GeeksforGeeks GATE CSEWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:0014:56 / 1:11:13•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=j9Vmf5yRw-I\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question"
},
{
"code": null,
"e": 25912,
"s": 25891,
"text": "GATE-CS-2017 (Set 1)"
},
{
"code": null,
"e": 25938,
"s": 25912,
"text": "GATE-GATE-CS-2017 (Set 1)"
},
{
"code": null,
"e": 25943,
"s": 25938,
"text": "GATE"
},
{
"code": null,
"e": 26041,
"s": 25943,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26075,
"s": 26041,
"text": "GATE | GATE CS 2019 | Question 27"
},
{
"code": null,
"e": 26109,
"s": 26075,
"text": "GATE | GATE-IT-2004 | Question 66"
},
{
"code": null,
"e": 26151,
"s": 26109,
"text": "GATE | GATE-CS-2014-(Set-3) | Question 65"
},
{
"code": null,
"e": 26193,
"s": 26151,
"text": "GATE | GATE-CS-2016 (Set 2) | Question 48"
},
{
"code": null,
"e": 26227,
"s": 26193,
"text": "GATE | GATE-CS-2006 | Question 49"
},
{
"code": null,
"e": 26260,
"s": 26227,
"text": "GATE | GATE-CS-2004 | Question 3"
},
{
"code": null,
"e": 26302,
"s": 26260,
"text": "GATE | GATE-CS-2017 (Set 2) | Question 42"
},
{
"code": null,
"e": 26336,
"s": 26302,
"text": "GATE | GATE CS 2010 | Question 24"
},
{
"code": null,
"e": 26370,
"s": 26336,
"text": "GATE | GATE-CS-2000 | Question 43"
}
] |
VB.Net - Constants and Enumerations | The constants refer to fixed values that the program may not alter during its execution. These fixed values are also called literals.
Constants can be of any of the basic data types like an integer constant, a floating constant, a character constant, or a string literal. There are also enumeration constants as well.
The constants are treated just like regular variables except that their values cannot be modified after their definition.
An enumeration is a set of named integer constants.
In VB.Net, constants are declared using the Const statement. The Const statement is used at module, class, structure, procedure, or block level for use in place of literal values.
The syntax for the Const statement is −
[ < attributelist > ] [ accessmodifier ] [ Shadows ]
Const constantlist
Where,
attributelist − specifies the list of attributes applied to the constants; you can provide multiple attributes separated by commas. Optional.
attributelist − specifies the list of attributes applied to the constants; you can provide multiple attributes separated by commas. Optional.
accessmodifier − specifies which code can access these constants. Optional. Values can be either of the: Public, Protected, Friend, Protected Friend, or Private.
accessmodifier − specifies which code can access these constants. Optional. Values can be either of the: Public, Protected, Friend, Protected Friend, or Private.
Shadows − this makes the constant hide a programming element of identical name in a base class. Optional.
Shadows − this makes the constant hide a programming element of identical name in a base class. Optional.
Constantlist − gives the list of names of constants declared. Required.
Constantlist − gives the list of names of constants declared. Required.
Where, each constant name has the following syntax and parts −
constantname [ As datatype ] = initializer
constantname − specifies the name of the constant
constantname − specifies the name of the constant
datatype − specifies the data type of the constant
datatype − specifies the data type of the constant
initializer − specifies the value assigned to the constant
initializer − specifies the value assigned to the constant
For example,
'The following statements declare constants.'
Const maxval As Long = 4999
Public Const message As String = "HELLO"
Private Const piValue As Double = 3.1415
The following example demonstrates declaration and use of a constant value −
Module constantsNenum
Sub Main()
Const PI = 3.14149
Dim radius, area As Single
radius = 7
area = PI * radius * radius
Console.WriteLine("Area = " & Str(area))
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
Area = 153.933
VB.Net provides the following print and display constants −
vbCrLf
Carriage return/linefeed character combination.
vbCr
Carriage return character.
vbLf
Linefeed character.
vbNewLine
Newline character.
vbNullChar
Null character.
vbNullString
Not the same as a zero-length string (""); used for calling external procedures.
vbObjectError
Error number. User-defined error numbers should be greater than this value. For example: Err.Raise(Number) = vbObjectError + 1000
vbTab
Tab character.
vbBack
Backspace character.
An enumerated type is declared using the Enum statement. The Enum statement declares an enumeration and defines the values of its members. The Enum statement can be used at the module, class, structure, procedure, or block level.
The syntax for the Enum statement is as follows −
[ < attributelist > ] [ accessmodifier ] [ Shadows ]
Enum enumerationname [ As datatype ]
memberlist
End Enum
Where,
attributelist − refers to the list of attributes applied to the variable. Optional.
attributelist − refers to the list of attributes applied to the variable. Optional.
accessmodifier − specifies which code can access these enumerations. Optional. Values can be either of the: Public, Protected, Friend or Private.
accessmodifier − specifies which code can access these enumerations. Optional. Values can be either of the: Public, Protected, Friend or Private.
Shadows − this makes the enumeration hide a programming element of identical name in a base class. Optional.
Shadows − this makes the enumeration hide a programming element of identical name in a base class. Optional.
enumerationname − name of the enumeration. Required
enumerationname − name of the enumeration. Required
datatype − specifies the data type of the enumeration and all its members.
datatype − specifies the data type of the enumeration and all its members.
memberlist − specifies the list of member constants being declared in this statement. Required.
memberlist − specifies the list of member constants being declared in this statement. Required.
Each member in the memberlist has the following syntax and parts:
[< attribute list >] member name [ = initializer ]
Where,
name − specifies the name of the member. Required.
name − specifies the name of the member. Required.
initializer − value assigned to the enumeration member. Optional.
initializer − value assigned to the enumeration member. Optional.
For example,
Enum Colors
red = 1
orange = 2
yellow = 3
green = 4
azure = 5
blue = 6
violet = 7
End Enum
The following example demonstrates declaration and use of the Enum variable Colors −
Module constantsNenum
Enum Colors
red = 1
orange = 2
yellow = 3
green = 4
azure = 5
blue = 6
violet = 7
End Enum
Sub Main()
Console.WriteLine("The Color Red is : " & Colors.red)
Console.WriteLine("The Color Yellow is : " & Colors.yellow)
Console.WriteLine("The Color Blue is : " & Colors.blue)
Console.WriteLine("The Color Green is : " & Colors.green)
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
The Color Red is: 1
The Color Yellow is: 3
The Color Blue is: 6
The Color Green is: 4
63 Lectures
4 hours
Frahaan Hussain
103 Lectures
12 hours
Arnold Higuit
60 Lectures
9.5 hours
Arnold Higuit
97 Lectures
9 hours
Arnold Higuit
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2434,
"s": 2300,
"text": "The constants refer to fixed values that the program may not alter during its execution. These fixed values are also called literals."
},
{
"code": null,
"e": 2618,
"s": 2434,
"text": "Constants can be of any of the basic data types like an integer constant, a floating constant, a character constant, or a string literal. There are also enumeration constants as well."
},
{
"code": null,
"e": 2740,
"s": 2618,
"text": "The constants are treated just like regular variables except that their values cannot be modified after their definition."
},
{
"code": null,
"e": 2792,
"s": 2740,
"text": "An enumeration is a set of named integer constants."
},
{
"code": null,
"e": 2972,
"s": 2792,
"text": "In VB.Net, constants are declared using the Const statement. The Const statement is used at module, class, structure, procedure, or block level for use in place of literal values."
},
{
"code": null,
"e": 3012,
"s": 2972,
"text": "The syntax for the Const statement is −"
},
{
"code": null,
"e": 3086,
"s": 3012,
"text": "[ < attributelist > ] [ accessmodifier ] [ Shadows ] \nConst constantlist\n"
},
{
"code": null,
"e": 3093,
"s": 3086,
"text": "Where,"
},
{
"code": null,
"e": 3235,
"s": 3093,
"text": "attributelist − specifies the list of attributes applied to the constants; you can provide multiple attributes separated by commas. Optional."
},
{
"code": null,
"e": 3377,
"s": 3235,
"text": "attributelist − specifies the list of attributes applied to the constants; you can provide multiple attributes separated by commas. Optional."
},
{
"code": null,
"e": 3539,
"s": 3377,
"text": "accessmodifier − specifies which code can access these constants. Optional. Values can be either of the: Public, Protected, Friend, Protected Friend, or Private."
},
{
"code": null,
"e": 3701,
"s": 3539,
"text": "accessmodifier − specifies which code can access these constants. Optional. Values can be either of the: Public, Protected, Friend, Protected Friend, or Private."
},
{
"code": null,
"e": 3807,
"s": 3701,
"text": "Shadows − this makes the constant hide a programming element of identical name in a base class. Optional."
},
{
"code": null,
"e": 3913,
"s": 3807,
"text": "Shadows − this makes the constant hide a programming element of identical name in a base class. Optional."
},
{
"code": null,
"e": 3985,
"s": 3913,
"text": "Constantlist − gives the list of names of constants declared. Required."
},
{
"code": null,
"e": 4057,
"s": 3985,
"text": "Constantlist − gives the list of names of constants declared. Required."
},
{
"code": null,
"e": 4120,
"s": 4057,
"text": "Where, each constant name has the following syntax and parts −"
},
{
"code": null,
"e": 4164,
"s": 4120,
"text": "constantname [ As datatype ] = initializer\n"
},
{
"code": null,
"e": 4214,
"s": 4164,
"text": "constantname − specifies the name of the constant"
},
{
"code": null,
"e": 4264,
"s": 4214,
"text": "constantname − specifies the name of the constant"
},
{
"code": null,
"e": 4315,
"s": 4264,
"text": "datatype − specifies the data type of the constant"
},
{
"code": null,
"e": 4366,
"s": 4315,
"text": "datatype − specifies the data type of the constant"
},
{
"code": null,
"e": 4425,
"s": 4366,
"text": "initializer − specifies the value assigned to the constant"
},
{
"code": null,
"e": 4484,
"s": 4425,
"text": "initializer − specifies the value assigned to the constant"
},
{
"code": null,
"e": 4497,
"s": 4484,
"text": "For example,"
},
{
"code": null,
"e": 4654,
"s": 4497,
"text": "'The following statements declare constants.'\nConst maxval As Long = 4999\nPublic Const message As String = \"HELLO\" \nPrivate Const piValue As Double = 3.1415"
},
{
"code": null,
"e": 4731,
"s": 4654,
"text": "The following example demonstrates declaration and use of a constant value −"
},
{
"code": null,
"e": 4969,
"s": 4731,
"text": "Module constantsNenum\n Sub Main()\n Const PI = 3.14149\n Dim radius, area As Single\n radius = 7\n area = PI * radius * radius\n Console.WriteLine(\"Area = \" & Str(area))\n Console.ReadKey()\n End Sub\nEnd Module"
},
{
"code": null,
"e": 5050,
"s": 4969,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 5066,
"s": 5050,
"text": "Area = 153.933\n"
},
{
"code": null,
"e": 5126,
"s": 5066,
"text": "VB.Net provides the following print and display constants −"
},
{
"code": null,
"e": 5133,
"s": 5126,
"text": "vbCrLf"
},
{
"code": null,
"e": 5181,
"s": 5133,
"text": "Carriage return/linefeed character combination."
},
{
"code": null,
"e": 5186,
"s": 5181,
"text": "vbCr"
},
{
"code": null,
"e": 5213,
"s": 5186,
"text": "Carriage return character."
},
{
"code": null,
"e": 5218,
"s": 5213,
"text": "vbLf"
},
{
"code": null,
"e": 5238,
"s": 5218,
"text": "Linefeed character."
},
{
"code": null,
"e": 5248,
"s": 5238,
"text": "vbNewLine"
},
{
"code": null,
"e": 5267,
"s": 5248,
"text": "Newline character."
},
{
"code": null,
"e": 5278,
"s": 5267,
"text": "vbNullChar"
},
{
"code": null,
"e": 5294,
"s": 5278,
"text": "Null character."
},
{
"code": null,
"e": 5307,
"s": 5294,
"text": "vbNullString"
},
{
"code": null,
"e": 5388,
"s": 5307,
"text": "Not the same as a zero-length string (\"\"); used for calling external procedures."
},
{
"code": null,
"e": 5402,
"s": 5388,
"text": "vbObjectError"
},
{
"code": null,
"e": 5532,
"s": 5402,
"text": "Error number. User-defined error numbers should be greater than this value. For example: Err.Raise(Number) = vbObjectError + 1000"
},
{
"code": null,
"e": 5538,
"s": 5532,
"text": "vbTab"
},
{
"code": null,
"e": 5553,
"s": 5538,
"text": "Tab character."
},
{
"code": null,
"e": 5560,
"s": 5553,
"text": "vbBack"
},
{
"code": null,
"e": 5581,
"s": 5560,
"text": "Backspace character."
},
{
"code": null,
"e": 5811,
"s": 5581,
"text": "An enumerated type is declared using the Enum statement. The Enum statement declares an enumeration and defines the values of its members. The Enum statement can be used at the module, class, structure, procedure, or block level."
},
{
"code": null,
"e": 5861,
"s": 5811,
"text": "The syntax for the Enum statement is as follows −"
},
{
"code": null,
"e": 5978,
"s": 5861,
"text": "[ < attributelist > ] [ accessmodifier ] [ Shadows ] \nEnum enumerationname [ As datatype ] \n memberlist\nEnd Enum\n"
},
{
"code": null,
"e": 5985,
"s": 5978,
"text": "Where,"
},
{
"code": null,
"e": 6069,
"s": 5985,
"text": "attributelist − refers to the list of attributes applied to the variable. Optional."
},
{
"code": null,
"e": 6153,
"s": 6069,
"text": "attributelist − refers to the list of attributes applied to the variable. Optional."
},
{
"code": null,
"e": 6299,
"s": 6153,
"text": "accessmodifier − specifies which code can access these enumerations. Optional. Values can be either of the: Public, Protected, Friend or Private."
},
{
"code": null,
"e": 6445,
"s": 6299,
"text": "accessmodifier − specifies which code can access these enumerations. Optional. Values can be either of the: Public, Protected, Friend or Private."
},
{
"code": null,
"e": 6554,
"s": 6445,
"text": "Shadows − this makes the enumeration hide a programming element of identical name in a base class. Optional."
},
{
"code": null,
"e": 6663,
"s": 6554,
"text": "Shadows − this makes the enumeration hide a programming element of identical name in a base class. Optional."
},
{
"code": null,
"e": 6715,
"s": 6663,
"text": "enumerationname − name of the enumeration. Required"
},
{
"code": null,
"e": 6767,
"s": 6715,
"text": "enumerationname − name of the enumeration. Required"
},
{
"code": null,
"e": 6842,
"s": 6767,
"text": "datatype − specifies the data type of the enumeration and all its members."
},
{
"code": null,
"e": 6917,
"s": 6842,
"text": "datatype − specifies the data type of the enumeration and all its members."
},
{
"code": null,
"e": 7013,
"s": 6917,
"text": "memberlist − specifies the list of member constants being declared in this statement. Required."
},
{
"code": null,
"e": 7109,
"s": 7013,
"text": "memberlist − specifies the list of member constants being declared in this statement. Required."
},
{
"code": null,
"e": 7175,
"s": 7109,
"text": "Each member in the memberlist has the following syntax and parts:"
},
{
"code": null,
"e": 7227,
"s": 7175,
"text": "[< attribute list >] member name [ = initializer ]\n"
},
{
"code": null,
"e": 7234,
"s": 7227,
"text": "Where,"
},
{
"code": null,
"e": 7285,
"s": 7234,
"text": "name − specifies the name of the member. Required."
},
{
"code": null,
"e": 7336,
"s": 7285,
"text": "name − specifies the name of the member. Required."
},
{
"code": null,
"e": 7402,
"s": 7336,
"text": "initializer − value assigned to the enumeration member. Optional."
},
{
"code": null,
"e": 7468,
"s": 7402,
"text": "initializer − value assigned to the enumeration member. Optional."
},
{
"code": null,
"e": 7481,
"s": 7468,
"text": "For example,"
},
{
"code": null,
"e": 7593,
"s": 7481,
"text": "Enum Colors\n red = 1\n orange = 2\n yellow = 3\n green = 4\n azure = 5\n blue = 6\n violet = 7\nEnd Enum"
},
{
"code": null,
"e": 7678,
"s": 7593,
"text": "The following example demonstrates declaration and use of the Enum variable Colors −"
},
{
"code": null,
"e": 8155,
"s": 7678,
"text": "Module constantsNenum\n Enum Colors\n red = 1\n orange = 2\n yellow = 3\n green = 4\n azure = 5\n blue = 6\n violet = 7\n End Enum\n \n Sub Main()\n Console.WriteLine(\"The Color Red is : \" & Colors.red)\n Console.WriteLine(\"The Color Yellow is : \" & Colors.yellow)\n Console.WriteLine(\"The Color Blue is : \" & Colors.blue)\n Console.WriteLine(\"The Color Green is : \" & Colors.green)\n Console.ReadKey()\n End Sub\nEnd Module"
},
{
"code": null,
"e": 8236,
"s": 8155,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 8323,
"s": 8236,
"text": "The Color Red is: 1\nThe Color Yellow is: 3\nThe Color Blue is: 6\nThe Color Green is: 4\n"
},
{
"code": null,
"e": 8356,
"s": 8323,
"text": "\n 63 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 8373,
"s": 8356,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 8408,
"s": 8373,
"text": "\n 103 Lectures \n 12 hours \n"
},
{
"code": null,
"e": 8423,
"s": 8408,
"text": " Arnold Higuit"
},
{
"code": null,
"e": 8458,
"s": 8423,
"text": "\n 60 Lectures \n 9.5 hours \n"
},
{
"code": null,
"e": 8473,
"s": 8458,
"text": " Arnold Higuit"
},
{
"code": null,
"e": 8506,
"s": 8473,
"text": "\n 97 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 8521,
"s": 8506,
"text": " Arnold Higuit"
},
{
"code": null,
"e": 8528,
"s": 8521,
"text": " Print"
},
{
"code": null,
"e": 8539,
"s": 8528,
"text": " Add Notes"
}
] |
How to convert DB2 queries to python scripts | by Dawn Moyer | Towards Data Science | Many companies are running common data analytics tasks using python scripts. They are asking employees to convert scripts that may currently exist in SAS or other toolsets to python. One step of this process is being able to pull in the same data with the new techniques. This article is about converting DB2 queries into python scripts.
How do you convert your queries to python? It may sound overwhelming but it’s easier than you think. Once you have a template for your data source, all you need to do is change the query and output filename.
There are several ways you can do this, but I will outline an intuitive template that allows you to run a DB2 query on your local laptop/desktop.
Let’s pretend you work at a large donut company, DiscoDonuts. You have a query to you run the following query against DB2. Typically you might use a tool such as DataStudio. Pretty simple.
SELECT store_id, donut_style, date, volume, net_sales FROM donutsdb.sales_data WHERE date = '2020-08-16' WITH UR;
Now you have your manager asking you to start using python. Take a deep breath; it’s not that hard. After the code is set up, you just need to update two fields, the name of your output file and your query itself. Then you hit Run. How simple is that?
If you haven’t already, you will need to contact your IT department to have a tool (“IDE”) installed (such as PyCharm, VSCode, Jupyter Notebooks).
To connect to DB2, you will need to enter your own company’s database, hostname, and port id. Most likely, you already have this information in whatever tool you are currently using.
First, fill in the database connection information. Now you can save this template for use time and time again.
For each query you want to run, you update the output filename and the actual query itself. The query is passed to DB2 so it is in the same DB2 format you are already using.
import ibm_dbimport ibm_db_dbiimport pandas as pd# name your output file (and path if needed)output_filename = "donut_sales.csv"# enter your query between the triple quotesquery = """ SELECT store_id, donut_style, date, volume, net_sales FROM donutsdb.sales_data WHERE date = '2020-08-16' WITH UR; """# one way to do credentialingimport getpass as gp uid=input('Enter uid: ') pwd=gp.getpass('Enter password (hidden): ')# connect to your databasedb = ( "DRIVER = {IBM DB2 ODBC DRIVER - DB2COPY1};" "DATABASE=<your donut database>;" "HOSTNAME=<your db2 hostname>;" "PORT=<your db2 port ####>;" "PROTOCAL=TCPIP;" 'UID='+uid+';' 'PWD='+pwd+';')ibm_db_conn = ibm_db.connect(db, "", "")pconn = ibm_db_dbi.Connection(ibm_db_conn)#optional if you are using the accelerator #ibm_db.exec_immediate(ibm_db_conn, "SET CURRENT QUERY ACCELERATION = ALL") df = pd.read_sql(query, pconn)df.to_csv(output_filename,index=False)
Just hit Run. You will be asked to enter your credentials, your query will run on DB2, the data will be transferred back to your script and your file will be created!
The data frame created can serve as your data for further analysis within the python script if you choose.
Update your output filenameUpdate your queryHit Run!
Update your output filename
Update your query
Hit Run!
It is not that hard to transfer your DB2 SQL knowledge to python. This is a great skill to have and share with others.
* I always welcome feedback. If you have another technique, share it in the responses. There are many ways to approach a problem and I have presented just one of many. Code is ever-evolving so what works today may not work tomorrow. | [
{
"code": null,
"e": 510,
"s": 172,
"text": "Many companies are running common data analytics tasks using python scripts. They are asking employees to convert scripts that may currently exist in SAS or other toolsets to python. One step of this process is being able to pull in the same data with the new techniques. This article is about converting DB2 queries into python scripts."
},
{
"code": null,
"e": 718,
"s": 510,
"text": "How do you convert your queries to python? It may sound overwhelming but it’s easier than you think. Once you have a template for your data source, all you need to do is change the query and output filename."
},
{
"code": null,
"e": 864,
"s": 718,
"text": "There are several ways you can do this, but I will outline an intuitive template that allows you to run a DB2 query on your local laptop/desktop."
},
{
"code": null,
"e": 1053,
"s": 864,
"text": "Let’s pretend you work at a large donut company, DiscoDonuts. You have a query to you run the following query against DB2. Typically you might use a tool such as DataStudio. Pretty simple."
},
{
"code": null,
"e": 1168,
"s": 1053,
"text": "SELECT store_id, donut_style, date, volume, net_sales FROM donutsdb.sales_data WHERE date = '2020-08-16' WITH UR;"
},
{
"code": null,
"e": 1420,
"s": 1168,
"text": "Now you have your manager asking you to start using python. Take a deep breath; it’s not that hard. After the code is set up, you just need to update two fields, the name of your output file and your query itself. Then you hit Run. How simple is that?"
},
{
"code": null,
"e": 1567,
"s": 1420,
"text": "If you haven’t already, you will need to contact your IT department to have a tool (“IDE”) installed (such as PyCharm, VSCode, Jupyter Notebooks)."
},
{
"code": null,
"e": 1750,
"s": 1567,
"text": "To connect to DB2, you will need to enter your own company’s database, hostname, and port id. Most likely, you already have this information in whatever tool you are currently using."
},
{
"code": null,
"e": 1862,
"s": 1750,
"text": "First, fill in the database connection information. Now you can save this template for use time and time again."
},
{
"code": null,
"e": 2036,
"s": 1862,
"text": "For each query you want to run, you update the output filename and the actual query itself. The query is passed to DB2 so it is in the same DB2 format you are already using."
},
{
"code": null,
"e": 3056,
"s": 2036,
"text": "import ibm_dbimport ibm_db_dbiimport pandas as pd# name your output file (and path if needed)output_filename = \"donut_sales.csv\"# enter your query between the triple quotesquery = \"\"\" SELECT store_id, donut_style, date, volume, net_sales FROM donutsdb.sales_data WHERE date = '2020-08-16' WITH UR; \"\"\"# one way to do credentialingimport getpass as gp uid=input('Enter uid: ') pwd=gp.getpass('Enter password (hidden): ')# connect to your databasedb = ( \"DRIVER = {IBM DB2 ODBC DRIVER - DB2COPY1};\" \"DATABASE=<your donut database>;\" \"HOSTNAME=<your db2 hostname>;\" \"PORT=<your db2 port ####>;\" \"PROTOCAL=TCPIP;\" 'UID='+uid+';' 'PWD='+pwd+';')ibm_db_conn = ibm_db.connect(db, \"\", \"\")pconn = ibm_db_dbi.Connection(ibm_db_conn)#optional if you are using the accelerator #ibm_db.exec_immediate(ibm_db_conn, \"SET CURRENT QUERY ACCELERATION = ALL\") df = pd.read_sql(query, pconn)df.to_csv(output_filename,index=False)"
},
{
"code": null,
"e": 3223,
"s": 3056,
"text": "Just hit Run. You will be asked to enter your credentials, your query will run on DB2, the data will be transferred back to your script and your file will be created!"
},
{
"code": null,
"e": 3330,
"s": 3223,
"text": "The data frame created can serve as your data for further analysis within the python script if you choose."
},
{
"code": null,
"e": 3383,
"s": 3330,
"text": "Update your output filenameUpdate your queryHit Run!"
},
{
"code": null,
"e": 3411,
"s": 3383,
"text": "Update your output filename"
},
{
"code": null,
"e": 3429,
"s": 3411,
"text": "Update your query"
},
{
"code": null,
"e": 3438,
"s": 3429,
"text": "Hit Run!"
},
{
"code": null,
"e": 3557,
"s": 3438,
"text": "It is not that hard to transfer your DB2 SQL knowledge to python. This is a great skill to have and share with others."
}
] |
How to create vector in R with a sequence of numbers? | Creating a numeric vector is the first step towards learning R programming and there are many ways to do that but if we want to generate a sequence of number then it is a bit different thing, not totally different. We can create a vector with a sequence of numbers by using − if the sequence of numbers needs to have only the difference of 1, otherwise seq function can be used.
Live Demo
> x1<-1:50
> x1
[1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
[26] 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
Live Demo
> x2<-50:1
> x2
[1] 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26
[26] 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
Live Demo
> x3<-seq(1,100,by=5)
> x3
[1] 1 6 11 16 21 26 31 36 41 46 51 56 61 66 71 76 81 86 91 96
Live Demo
> x4<-seq(1,500,by=5)
> x4
[1] 1 6 11 16 21 26 31 36 41 46 51 56 61 66 71 76 81 86
[19] 91 96 101 106 111 116 121 126 131 136 141 146 151 156 161 166 171 176
[37] 181 186 191 196 201 206 211 216 221 226 231 236 241 246 251 256 261 266
[55] 271 276 281 286 291 296 301 306 311 316 321 326 331 336 341 346 351 356
[73] 361 366 371 376 381 386 391 396 401 406 411 416 421 426 431 436 441 446
[91] 451 456 461 466 471 476 481 486 491 496
Live Demo
> x5<-seq(5,500,by=5)
> x5
[1] 5 10 15 20 25 30 35 40 45 50 55 60 65 70 75 80 85 90
[19] 95 100 105 110 115 120 125 130 135 140 145 150 155 160 165 170 175 180
[37] 185 190 195 200 205 210 215 220 225 230 235 240 245 250 255 260 265 270
[55] 275 280 285 290 295 300 305 310 315 320 325 330 335 340 345 350 355 360
[73] 365 370 375 380 385 390 395 400 405 410 415 420 425 430 435 440 445 450
[91] 455 460 465 470 475 480 485 490 495 500
Live Demo
> x6<-seq(-500,5,by=5)
> x6
[1] -500 -495 -490 -485 -480 -475 -470 -465 -460 -455 -450 -445 -440 -435 -430
[16] -425 -420 -415 -410 -405 -400 -395 -390 -385 -380 -375 -370 -365 -360 -355
[31] -350 -345 -340 -335 -330 -325 -320 -315 -310 -305 -300 -295 -290 -285 -280
[46] -275 -270 -265 -260 -255 -250 -245 -240 -235 -230 -225 -220 -215 -210 -205
[61] -200 -195 -190 -185 -180 -175 -170 -165 -160 -155 -150 -145 -140 -135 -130
[76] -125 -120 -115 -110 -105 -100 -95 -90 -85 -80 -75 -70 -65 -60 -55
[91] -50 -45 -40 -35 -30 -25 -20 -15 -10 -5 0 5
Live Demo
> x7<-seq(-500,-1,by=5)
> x7
[1] -500 -495 -490 -485 -480 -475 -470 -465 -460 -455 -450 -445 -440 -435 -430
[16] -425 -420 -415 -410 -405 -400 -395 -390 -385 -380 -375 -370 -365 -360 -355
[31] -350 -345 -340 -335 -330 -325 -320 -315 -310 -305 -300 -295 -290 -285 -280
[46] -275 -270 -265 -260 -255 -250 -245 -240 -235 -230 -225 -220 -215 -210 -205
[61] -200 -195 -190 -185 -180 -175 -170 -165 -160 -155 -150 -145 -140 -135 -130
[76] -125 -120 -115 -110 -105 -100 -95 -90 -85 -80 -75 -70 -65 -60 -55
[91] -50 -45 -40 -35 -30 -25 -20 -15 -10 -5
Live Demo
> x8<-seq(-50,50,by=2)
> x8
[1] -50 -48 -46 -44 -42 -40 -38 -36 -34 -32 -30 -28 -26 -24 -22 -20 -18 -16 -14
[20] -12 -10 -8 -6 -4 -2 0 2 4 6 8 10 12 14 16 18 20 22 24
[39] 26 28 30 32 34 36 38 40 42 44 46 48 50
Live Demo
> x9<-seq(500,5000,by=100)
> x9
[1] 500 600 700 800 900 1000 1100 1200 1300 1400 1500 1600 1700 1800 1900
[16] 2000 2100 2200 2300 2400 2500 2600 2700 2800 2900 3000 3100 3200 3300 3400
[31] 3500 3600 3700 3800 3900 4000 4100 4200 4300 4400 4500 4600 4700 4800 4900
[46] 5000 | [
{
"code": null,
"e": 1441,
"s": 1062,
"text": "Creating a numeric vector is the first step towards learning R programming and there are many ways to do that but if we want to generate a sequence of number then it is a bit different thing, not totally different. We can create a vector with a sequence of numbers by using − if the sequence of numbers needs to have only the difference of 1, otherwise seq function can be used."
},
{
"code": null,
"e": 1452,
"s": 1441,
"text": " Live Demo"
},
{
"code": null,
"e": 1468,
"s": 1452,
"text": "> x1<-1:50\n> x1"
},
{
"code": null,
"e": 1618,
"s": 1468,
"text": "[1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25\n[26] 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50"
},
{
"code": null,
"e": 1629,
"s": 1618,
"text": " Live Demo"
},
{
"code": null,
"e": 1645,
"s": 1629,
"text": "> x2<-50:1\n> x2"
},
{
"code": null,
"e": 1795,
"s": 1645,
"text": "[1] 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26\n[26] 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1"
},
{
"code": null,
"e": 1806,
"s": 1795,
"text": " Live Demo"
},
{
"code": null,
"e": 1833,
"s": 1806,
"text": "> x3<-seq(1,100,by=5)\n> x3"
},
{
"code": null,
"e": 1895,
"s": 1833,
"text": "[1] 1 6 11 16 21 26 31 36 41 46 51 56 61 66 71 76 81 86 91 96"
},
{
"code": null,
"e": 1906,
"s": 1895,
"text": " Live Demo"
},
{
"code": null,
"e": 1933,
"s": 1906,
"text": "> x4<-seq(1,500,by=5)\n> x4"
},
{
"code": null,
"e": 2340,
"s": 1933,
"text": "[1] 1 6 11 16 21 26 31 36 41 46 51 56 61 66 71 76 81 86\n[19] 91 96 101 106 111 116 121 126 131 136 141 146 151 156 161 166 171 176\n[37] 181 186 191 196 201 206 211 216 221 226 231 236 241 246 251 256 261 266\n[55] 271 276 281 286 291 296 301 306 311 316 321 326 331 336 341 346 351 356\n[73] 361 366 371 376 381 386 391 396 401 406 411 416 421 426 431 436 441 446\n[91] 451 456 461 466 471 476 481 486 491 496"
},
{
"code": null,
"e": 2351,
"s": 2340,
"text": " Live Demo"
},
{
"code": null,
"e": 2378,
"s": 2351,
"text": "> x5<-seq(5,500,by=5)\n> x5"
},
{
"code": null,
"e": 2787,
"s": 2378,
"text": "[1] 5 10 15 20 25 30 35 40 45 50 55 60 65 70 75 80 85 90\n[19] 95 100 105 110 115 120 125 130 135 140 145 150 155 160 165 170 175 180\n[37] 185 190 195 200 205 210 215 220 225 230 235 240 245 250 255 260 265 270\n[55] 275 280 285 290 295 300 305 310 315 320 325 330 335 340 345 350 355 360\n[73] 365 370 375 380 385 390 395 400 405 410 415 420 425 430 435 440 445 450\n[91] 455 460 465 470 475 480 485 490 495 500"
},
{
"code": null,
"e": 2798,
"s": 2787,
"text": " Live Demo"
},
{
"code": null,
"e": 2826,
"s": 2798,
"text": "> x6<-seq(-500,5,by=5)\n> x6"
},
{
"code": null,
"e": 3344,
"s": 2826,
"text": "[1] -500 -495 -490 -485 -480 -475 -470 -465 -460 -455 -450 -445 -440 -435 -430\n[16] -425 -420 -415 -410 -405 -400 -395 -390 -385 -380 -375 -370 -365 -360 -355\n[31] -350 -345 -340 -335 -330 -325 -320 -315 -310 -305 -300 -295 -290 -285 -280\n[46] -275 -270 -265 -260 -255 -250 -245 -240 -235 -230 -225 -220 -215 -210 -205\n[61] -200 -195 -190 -185 -180 -175 -170 -165 -160 -155 -150 -145 -140 -135 -130\n[76] -125 -120 -115 -110 -105 -100 -95 -90 -85 -80 -75 -70 -65 -60 -55\n[91] -50 -45 -40 -35 -30 -25 -20 -15 -10 -5 0 5"
},
{
"code": null,
"e": 3355,
"s": 3344,
"text": " Live Demo"
},
{
"code": null,
"e": 3384,
"s": 3355,
"text": "> x7<-seq(-500,-1,by=5)\n> x7"
},
{
"code": null,
"e": 3898,
"s": 3384,
"text": "[1] -500 -495 -490 -485 -480 -475 -470 -465 -460 -455 -450 -445 -440 -435 -430\n[16] -425 -420 -415 -410 -405 -400 -395 -390 -385 -380 -375 -370 -365 -360 -355\n[31] -350 -345 -340 -335 -330 -325 -320 -315 -310 -305 -300 -295 -290 -285 -280\n[46] -275 -270 -265 -260 -255 -250 -245 -240 -235 -230 -225 -220 -215 -210 -205\n[61] -200 -195 -190 -185 -180 -175 -170 -165 -160 -155 -150 -145 -140 -135 -130\n[76] -125 -120 -115 -110 -105 -100 -95 -90 -85 -80 -75 -70 -65 -60 -55\n[91] -50 -45 -40 -35 -30 -25 -20 -15 -10 -5"
},
{
"code": null,
"e": 3909,
"s": 3898,
"text": " Live Demo"
},
{
"code": null,
"e": 3937,
"s": 3909,
"text": "> x8<-seq(-50,50,by=2)\n> x8"
},
{
"code": null,
"e": 4120,
"s": 3937,
"text": "[1] -50 -48 -46 -44 -42 -40 -38 -36 -34 -32 -30 -28 -26 -24 -22 -20 -18 -16 -14\n[20] -12 -10 -8 -6 -4 -2 0 2 4 6 8 10 12 14 16 18 20 22 24\n[39] 26 28 30 32 34 36 38 40 42 44 46 48 50"
},
{
"code": null,
"e": 4131,
"s": 4120,
"text": " Live Demo"
},
{
"code": null,
"e": 4163,
"s": 4131,
"text": "> x9<-seq(500,5000,by=100)\n> x9"
},
{
"code": null,
"e": 4407,
"s": 4163,
"text": "[1] 500 600 700 800 900 1000 1100 1200 1300 1400 1500 1600 1700 1800 1900\n[16] 2000 2100 2200 2300 2400 2500 2600 2700 2800 2900 3000 3100 3200 3300 3400\n[31] 3500 3600 3700 3800 3900 4000 4100 4200 4300 4400 4500 4600 4700 4800 4900\n[46] 5000"
}
] |
How to Filter a Map in Java 8 | Filter a Map in Java | Online Tutorialspoint | PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
In this tutorial, we are going to filter a Map in Java 8. We have been filtering the map in Java since over the years. But in previous versions of Java, if we want to filter a Map, we should loop the map and put a condition inside the loop based on the requirement.
Map<Integer,String> mobiles = new HashMap<>();
mobiles.put(1, "iPhone 7");
mobiles.put(2, "iPhone 6S");
mobiles.put(3, "Samsung");
mobiles.put(4, "1+");
for (Map.Entry<Integer,String> mobis : mobiles.entrySet()) {
if(mobis.getValue().equals("Samsung")){
System.out.println("Filtered Value : "+mobis.getValue());
}
}
On the above, we have filtered a samsung mobile among 4.
Now we will see how do we do filter a Map in Java 8 using Stream API.
We can filter a Map in Java 8 by converting the map.entrySet() into Stream and followed by filter() method and then finally collect it using collect() method.
String result = mobiles.entrySet().stream() // converting into Stream
.filter(map -> "Samsung".equals(map.getValue())) // Applying filter
.map(map -> map.getValue()) // apply mapping
.collect(Collectors.joining()); // collecting the data
Complete Example:
package com.onlinetutorialspoint.java8;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
public class Java8_FilterMap {
public static void main(String[] args) {
Map<Integer,String> mobiles = new HashMap<>();
mobiles.put(1, "iPhone 7");
mobiles.put(2, "iPhone 6S");
mobiles.put(3, "Samsung");
mobiles.put(4, "1+");
for (Map.Entry<Integer,String> mobis : mobiles.entrySet()) {
if(mobis.getValue().equals("Samsung")){
System.out.println("Filtered Value : "+mobis.getValue());
}
}
// Java8 Filtering
String result = mobiles.entrySet().stream()
.filter(map -> "Samsung".equals(map.getValue()))
.map(map -> map.getValue())
.collect(Collectors.joining());
System.out.println("Filtering With Value " + result);
Map<Integer, String> deptMap2 = mobiles.entrySet().stream()
.filter(map -> map.getKey() == 2)
.collect(Collectors.toMap(p -> p.getKey(), p -> p.getValue()));
System.out.println("Filtering With Key : " + deptMap2);
}
}
Output:
Java8_FilterMap
Filtered With Value Samsung
Filtered With Key : {2=iPhone 6S}
Happy Learning 🙂
Java 8 Read File Line By Line Example
How to get Stream count in Java 8
How to calculate Employees Salaries Java 8 summingInt
Java 8 foreach Example Tutorials
How to Merge Streams in Java 8
Java 8 groupingBy Example
How to sort a Map using Java8
Java 8 How to get common elements from two lists
Java 8 Stream Filter Example with Objects
How to Filter null values from Java8 Stream
User defined sorting with Java 8 Comparator
Hibernate Filter Example Xml Configuration
AngularJs lowercase Filter Example
AngularJs Currency Filter Example
AngularJs Orderby Filter Example
Java 8 Read File Line By Line Example
How to get Stream count in Java 8
How to calculate Employees Salaries Java 8 summingInt
Java 8 foreach Example Tutorials
How to Merge Streams in Java 8
Java 8 groupingBy Example
How to sort a Map using Java8
Java 8 How to get common elements from two lists
Java 8 Stream Filter Example with Objects
How to Filter null values from Java8 Stream
User defined sorting with Java 8 Comparator
Hibernate Filter Example Xml Configuration
AngularJs lowercase Filter Example
AngularJs Currency Filter Example
AngularJs Orderby Filter Example
Δ
Java8 – Install Windows
Java8 – foreach
Java8 – forEach with index
Java8 – Stream Filter Objects
Java8 – Comparator Userdefined
Java8 – GroupingBy
Java8 – SummingInt
Java8 – walk ReadFiles
Java8 – JAVA_HOME on Windows
Howto – Install Java on Mac OS
Howto – Convert Iterable to Stream
Howto – Get common elements from two Lists
Howto – Convert List to String
Howto – Concatenate Arrays using Stream
Howto – Remove duplicates from List
Howto – Filter null values from Stream
Howto – Convert List to Map
Howto – Convert Stream to List
Howto – Sort a Map
Howto – Filter a Map
Howto – Get Current UTC Time
Howto – Verify an Array contains a specific value
Howto – Convert ArrayList to Array
Howto – Read File Line By Line
Howto – Convert Date to LocalDate
Howto – Merge Streams
Howto – Resolve NullPointerException in toMap
Howto -Get Stream count
Howto – Get Min and Max values in a Stream
Howto – Convert InputStream to String | [
{
"code": null,
"e": 158,
"s": 123,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 172,
"s": 158,
"text": "Java Examples"
},
{
"code": null,
"e": 183,
"s": 172,
"text": "C Examples"
},
{
"code": null,
"e": 195,
"s": 183,
"text": "C Tutorials"
},
{
"code": null,
"e": 199,
"s": 195,
"text": "aws"
},
{
"code": null,
"e": 234,
"s": 199,
"text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC"
},
{
"code": null,
"e": 245,
"s": 234,
"text": "EXCEPTIONS"
},
{
"code": null,
"e": 257,
"s": 245,
"text": "COLLECTIONS"
},
{
"code": null,
"e": 263,
"s": 257,
"text": "SWING"
},
{
"code": null,
"e": 268,
"s": 263,
"text": "JDBC"
},
{
"code": null,
"e": 275,
"s": 268,
"text": "JAVA 8"
},
{
"code": null,
"e": 282,
"s": 275,
"text": "SPRING"
},
{
"code": null,
"e": 294,
"s": 282,
"text": "SPRING BOOT"
},
{
"code": null,
"e": 304,
"s": 294,
"text": "HIBERNATE"
},
{
"code": null,
"e": 311,
"s": 304,
"text": "PYTHON"
},
{
"code": null,
"e": 315,
"s": 311,
"text": "PHP"
},
{
"code": null,
"e": 322,
"s": 315,
"text": "JQUERY"
},
{
"code": null,
"e": 357,
"s": 322,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 371,
"s": 357,
"text": "Java Examples"
},
{
"code": null,
"e": 382,
"s": 371,
"text": "C Examples"
},
{
"code": null,
"e": 394,
"s": 382,
"text": "C Tutorials"
},
{
"code": null,
"e": 398,
"s": 394,
"text": "aws"
},
{
"code": null,
"e": 664,
"s": 398,
"text": "In this tutorial, we are going to filter a Map in Java 8. We have been filtering the map in Java since over the years. But in previous versions of Java, if we want to filter a Map, we should loop the map and put a condition inside the loop based on the requirement."
},
{
"code": null,
"e": 1068,
"s": 664,
"text": "Map<Integer,String> mobiles = new HashMap<>();\n mobiles.put(1, \"iPhone 7\");\n mobiles.put(2, \"iPhone 6S\");\n mobiles.put(3, \"Samsung\");\n mobiles.put(4, \"1+\");\n for (Map.Entry<Integer,String> mobis : mobiles.entrySet()) {\n if(mobis.getValue().equals(\"Samsung\")){\n System.out.println(\"Filtered Value : \"+mobis.getValue());\n }\n }"
},
{
"code": null,
"e": 1125,
"s": 1068,
"text": "On the above, we have filtered a samsung mobile among 4."
},
{
"code": null,
"e": 1195,
"s": 1125,
"text": "Now we will see how do we do filter a Map in Java 8 using Stream API."
},
{
"code": null,
"e": 1354,
"s": 1195,
"text": "We can filter a Map in Java 8 by converting the map.entrySet() into Stream and followed by filter() method and then finally collect it using collect() method."
},
{
"code": null,
"e": 1639,
"s": 1354,
"text": "String result = mobiles.entrySet().stream() // converting into Stream\n .filter(map -> \"Samsung\".equals(map.getValue())) // Applying filter\n .map(map -> map.getValue()) // apply mapping\n .collect(Collectors.joining()); // collecting the data\n\n"
},
{
"code": null,
"e": 1657,
"s": 1639,
"text": "Complete Example:"
},
{
"code": null,
"e": 2876,
"s": 1657,
"text": "package com.onlinetutorialspoint.java8;\n\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.stream.Collectors;\n\npublic class Java8_FilterMap {\n public static void main(String[] args) {\n Map<Integer,String> mobiles = new HashMap<>();\n mobiles.put(1, \"iPhone 7\");\n mobiles.put(2, \"iPhone 6S\");\n mobiles.put(3, \"Samsung\");\n mobiles.put(4, \"1+\");\n for (Map.Entry<Integer,String> mobis : mobiles.entrySet()) {\n if(mobis.getValue().equals(\"Samsung\")){\n System.out.println(\"Filtered Value : \"+mobis.getValue());\n }\n }\n // Java8 Filtering\n \n String result = mobiles.entrySet().stream()\n .filter(map -> \"Samsung\".equals(map.getValue()))\n .map(map -> map.getValue())\n .collect(Collectors.joining());\n\n System.out.println(\"Filtering With Value \" + result);\n \n \n Map<Integer, String> deptMap2 = mobiles.entrySet().stream()\n .filter(map -> map.getKey() == 2)\n .collect(Collectors.toMap(p -> p.getKey(), p -> p.getValue()));\n \n System.out.println(\"Filtering With Key : \" + deptMap2);\n }\n}"
},
{
"code": null,
"e": 2884,
"s": 2876,
"text": "Output:"
},
{
"code": null,
"e": 2962,
"s": 2884,
"text": "Java8_FilterMap\nFiltered With Value Samsung\nFiltered With Key : {2=iPhone 6S}"
},
{
"code": null,
"e": 2979,
"s": 2962,
"text": "Happy Learning 🙂"
},
{
"code": null,
"e": 3551,
"s": 2979,
"text": "\nJava 8 Read File Line By Line Example\nHow to get Stream count in Java 8\nHow to calculate Employees Salaries Java 8 summingInt\nJava 8 foreach Example Tutorials\nHow to Merge Streams in Java 8\nJava 8 groupingBy Example\nHow to sort a Map using Java8\nJava 8 How to get common elements from two lists\nJava 8 Stream Filter Example with Objects\nHow to Filter null values from Java8 Stream\nUser defined sorting with Java 8 Comparator\nHibernate Filter Example Xml Configuration\nAngularJs lowercase Filter Example\nAngularJs Currency Filter Example\nAngularJs Orderby Filter Example\n"
},
{
"code": null,
"e": 3589,
"s": 3551,
"text": "Java 8 Read File Line By Line Example"
},
{
"code": null,
"e": 3623,
"s": 3589,
"text": "How to get Stream count in Java 8"
},
{
"code": null,
"e": 3677,
"s": 3623,
"text": "How to calculate Employees Salaries Java 8 summingInt"
},
{
"code": null,
"e": 3710,
"s": 3677,
"text": "Java 8 foreach Example Tutorials"
},
{
"code": null,
"e": 3741,
"s": 3710,
"text": "How to Merge Streams in Java 8"
},
{
"code": null,
"e": 3767,
"s": 3741,
"text": "Java 8 groupingBy Example"
},
{
"code": null,
"e": 3797,
"s": 3767,
"text": "How to sort a Map using Java8"
},
{
"code": null,
"e": 3846,
"s": 3797,
"text": "Java 8 How to get common elements from two lists"
},
{
"code": null,
"e": 3888,
"s": 3846,
"text": "Java 8 Stream Filter Example with Objects"
},
{
"code": null,
"e": 3932,
"s": 3888,
"text": "How to Filter null values from Java8 Stream"
},
{
"code": null,
"e": 3976,
"s": 3932,
"text": "User defined sorting with Java 8 Comparator"
},
{
"code": null,
"e": 4019,
"s": 3976,
"text": "Hibernate Filter Example Xml Configuration"
},
{
"code": null,
"e": 4054,
"s": 4019,
"text": "AngularJs lowercase Filter Example"
},
{
"code": null,
"e": 4088,
"s": 4054,
"text": "AngularJs Currency Filter Example"
},
{
"code": null,
"e": 4121,
"s": 4088,
"text": "AngularJs Orderby Filter Example"
},
{
"code": null,
"e": 4127,
"s": 4125,
"text": "Δ"
},
{
"code": null,
"e": 4152,
"s": 4127,
"text": " Java8 – Install Windows"
},
{
"code": null,
"e": 4169,
"s": 4152,
"text": " Java8 – foreach"
},
{
"code": null,
"e": 4197,
"s": 4169,
"text": " Java8 – forEach with index"
},
{
"code": null,
"e": 4228,
"s": 4197,
"text": " Java8 – Stream Filter Objects"
},
{
"code": null,
"e": 4260,
"s": 4228,
"text": " Java8 – Comparator Userdefined"
},
{
"code": null,
"e": 4280,
"s": 4260,
"text": " Java8 – GroupingBy"
},
{
"code": null,
"e": 4300,
"s": 4280,
"text": " Java8 – SummingInt"
},
{
"code": null,
"e": 4324,
"s": 4300,
"text": " Java8 – walk ReadFiles"
},
{
"code": null,
"e": 4354,
"s": 4324,
"text": " Java8 – JAVA_HOME on Windows"
},
{
"code": null,
"e": 4386,
"s": 4354,
"text": " Howto – Install Java on Mac OS"
},
{
"code": null,
"e": 4422,
"s": 4386,
"text": " Howto – Convert Iterable to Stream"
},
{
"code": null,
"e": 4466,
"s": 4422,
"text": " Howto – Get common elements from two Lists"
},
{
"code": null,
"e": 4498,
"s": 4466,
"text": " Howto – Convert List to String"
},
{
"code": null,
"e": 4539,
"s": 4498,
"text": " Howto – Concatenate Arrays using Stream"
},
{
"code": null,
"e": 4576,
"s": 4539,
"text": " Howto – Remove duplicates from List"
},
{
"code": null,
"e": 4616,
"s": 4576,
"text": " Howto – Filter null values from Stream"
},
{
"code": null,
"e": 4645,
"s": 4616,
"text": " Howto – Convert List to Map"
},
{
"code": null,
"e": 4677,
"s": 4645,
"text": " Howto – Convert Stream to List"
},
{
"code": null,
"e": 4697,
"s": 4677,
"text": " Howto – Sort a Map"
},
{
"code": null,
"e": 4719,
"s": 4697,
"text": " Howto – Filter a Map"
},
{
"code": null,
"e": 4749,
"s": 4719,
"text": " Howto – Get Current UTC Time"
},
{
"code": null,
"e": 4800,
"s": 4749,
"text": " Howto – Verify an Array contains a specific value"
},
{
"code": null,
"e": 4836,
"s": 4800,
"text": " Howto – Convert ArrayList to Array"
},
{
"code": null,
"e": 4868,
"s": 4836,
"text": " Howto – Read File Line By Line"
},
{
"code": null,
"e": 4903,
"s": 4868,
"text": " Howto – Convert Date to LocalDate"
},
{
"code": null,
"e": 4926,
"s": 4903,
"text": " Howto – Merge Streams"
},
{
"code": null,
"e": 4973,
"s": 4926,
"text": " Howto – Resolve NullPointerException in toMap"
},
{
"code": null,
"e": 4998,
"s": 4973,
"text": " Howto -Get Stream count"
},
{
"code": null,
"e": 5042,
"s": 4998,
"text": " Howto – Get Min and Max values in a Stream"
}
] |
Analysis of Emotion Data: A Dataset for Emotion Recognition Tasks | by Parul Pandey | Towards Data Science | You’ll just never know...so many emotions I choose not to show you
Emotion Recognition is a common classification task. For instance, given a tweet, you create a model to classify the tweet as being either positive or negative. However, human emotions consist of myriad emotions and cannot be constrained to just these three categories. On the contrary, most of the datasets available for this purpose consist of only two polarities — positive, negative, and at times neutral.
However, recently, I came across a new dataset constructed from Twitter data that seems to fill this void. The dataset, aka emotion dataset, contains English language Twitter messages representing six basic emotions- anger, disgust, fear, joy, sadness, and surprise. In this article, we’ll get to know the background of data collection and explore it a bit.
The emotion dataset comes from the paper CARER: Contextualized Affect Representations for Emotion Recognition by Saravia et al. The authors constructed a set of hashtags to collect a separate dataset of English tweets from the Twitter API belonging to eight basic emotions, including anger, anticipation, disgust, fear, joy, sadness, surprise, and trust. The data has already been preprocessed based on the approach described in their paper. The dataset is stored as a pandas dataframe and ready to be used in an NLP pipeline. The distribution of the data and the list of hashtag examples for each emotion are provided below.
We have seen the dataset. Let’s now see how to access it. I’ll demonstrate two ways to load the dataset and use it.
The dataset is already available as a pandas dataframe. There is an accompanying notebook showing how to use it for fine-tuning a pre-trained language model for emotion classification. It can be easily accessed as follows:
Let’s look at few statistics of data.
data.head()
We can we the first five rows of the dataset containing tweets and their corresponding labels. From here, we can split the dataset into a test and a validation set and train an emotion classifier. It is also a good idea to do some exploratory text analysis to understand the data. We’ll get to that in a bit, but before that, let me show you another way to load the dataset.
Hugging face datasets library provides API to download public datasets and preprocess them easily. You can refer to this video on Huggingface datasets to get started.
We’ll first download the datasets library and import the necessary modules
!pip install datasetsfrom datasets import load_datasetemotion_dataset = load_dataset("emotion")
This creates an emotion_dataset object.
emotion_dataset
What we get is a dictionary with each key corresponding to a different split. Let’s access the training data to see its contents.
emotion_train = emotion_dataset['train']print(emotion_train[0])print(emotion_train.column_names)print(emotion_train.features)
The training dataset comprises six different classes — sadness, joy, love, anger, fear, and surprise.
Converting emotion datasets into a Pandas DataFrame
We can now easily convert the above dataset into a pandas dataframe and analyze it further.
import pandas as pdemotion_dataset.set_format(type="pandas")train = emotion_dataset["train"][:]test = emotion_dataset["test"][:]val = emotion_dataset["validation"][:]
Let’s quickly check if the conversion was successful.
train.head()
Yes, indeed! Now you know how to access datasets from the Huggingface dataset hub- another addition to your data science skill. So what do you do when you have the data? You explore it, and that is precisely what we are going to do in the next section.
We’ll start by importing the necessary libraries and visualizing the data. As we already know, the data has been preprocessed, so that is a bonus. We’ll typically look for imbalance in the dataset and length of the tweets to start with. Beyond that, feel free to dive in further.
Notebooks to follow along: Exploratory Data Analysis of the emotion dataset
The label column currently has integers. To make it more understandable, we’ll create a new column called description containing the description of each integer in the label column.
Now, let’s analyze and see how the description column looks like. I have only used the training dataset, but the process will remain the same if we wish to do it for the test dataset, too.
Examples of each emotion
Let’s look at an example of each of the emotions.
It’ll be informative to look at the distribution of the labels. This will also give us an idea of the imbalance in the dataset, if any.
train['description'].value_counts(normalize=True)
sns.countplot(train['description'],order = train['description'].value_counts(normalize=True).index)
About 33 percent of the tweets are joyful, followed by sad and angry tweets.
We can now do some statistical analysis to explore the fundamental characteristics of the text data. Some of the analyses which can be helpful are:
Text length analysis: calculating the length of the text, and
word frequency analysis: calculating the word count in the form of unigrams, bigrams, and trigrams.
train['text_length'] = train['text'].astype(str).apply(len)train['text_word_count'] = train['text'].apply(lambda x: len(str(x).split()))
Tweet length analysis
sns.distplot(train['text_length'])plt.xlim([0, 512]);plt.xlabel('Text Length');
The histogram above shows that the length of the tweet ranges from around 2 to 300 characters.
Now let’s analyze the frequency of the words per tweet per class.
sns.boxplot(x="description", y="text_word_count", data=train)
Most of the tweets have an average of 15 words. Also, all the tweets appear to have more or less the same length. Hence, the length of the tweet isn’t a powerful indicator of polarity.
An n-gram is a contiguous sequence of n items from a given sample of text or speech. It is also a good idea to look at various n-grams to understand which words mainly occur together. For instance, we look at the distribution of unigrams, bigrams, and trigrams across emotions- sadness, anger, and love.
Now that we have done some preliminary exploration of the dataset, the next is to use this dataset to create an emotion classifier. This could be a great project to add to your resume and you can also share your trained model with the community. If you want to quickly spin up a notebook to explore the data, I have also made it available on Kaggle now. | [
{
"code": null,
"e": 239,
"s": 172,
"text": "You’ll just never know...so many emotions I choose not to show you"
},
{
"code": null,
"e": 649,
"s": 239,
"text": "Emotion Recognition is a common classification task. For instance, given a tweet, you create a model to classify the tweet as being either positive or negative. However, human emotions consist of myriad emotions and cannot be constrained to just these three categories. On the contrary, most of the datasets available for this purpose consist of only two polarities — positive, negative, and at times neutral."
},
{
"code": null,
"e": 1007,
"s": 649,
"text": "However, recently, I came across a new dataset constructed from Twitter data that seems to fill this void. The dataset, aka emotion dataset, contains English language Twitter messages representing six basic emotions- anger, disgust, fear, joy, sadness, and surprise. In this article, we’ll get to know the background of data collection and explore it a bit."
},
{
"code": null,
"e": 1633,
"s": 1007,
"text": "The emotion dataset comes from the paper CARER: Contextualized Affect Representations for Emotion Recognition by Saravia et al. The authors constructed a set of hashtags to collect a separate dataset of English tweets from the Twitter API belonging to eight basic emotions, including anger, anticipation, disgust, fear, joy, sadness, surprise, and trust. The data has already been preprocessed based on the approach described in their paper. The dataset is stored as a pandas dataframe and ready to be used in an NLP pipeline. The distribution of the data and the list of hashtag examples for each emotion are provided below."
},
{
"code": null,
"e": 1749,
"s": 1633,
"text": "We have seen the dataset. Let’s now see how to access it. I’ll demonstrate two ways to load the dataset and use it."
},
{
"code": null,
"e": 1972,
"s": 1749,
"text": "The dataset is already available as a pandas dataframe. There is an accompanying notebook showing how to use it for fine-tuning a pre-trained language model for emotion classification. It can be easily accessed as follows:"
},
{
"code": null,
"e": 2010,
"s": 1972,
"text": "Let’s look at few statistics of data."
},
{
"code": null,
"e": 2022,
"s": 2010,
"text": "data.head()"
},
{
"code": null,
"e": 2397,
"s": 2022,
"text": "We can we the first five rows of the dataset containing tweets and their corresponding labels. From here, we can split the dataset into a test and a validation set and train an emotion classifier. It is also a good idea to do some exploratory text analysis to understand the data. We’ll get to that in a bit, but before that, let me show you another way to load the dataset."
},
{
"code": null,
"e": 2564,
"s": 2397,
"text": "Hugging face datasets library provides API to download public datasets and preprocess them easily. You can refer to this video on Huggingface datasets to get started."
},
{
"code": null,
"e": 2639,
"s": 2564,
"text": "We’ll first download the datasets library and import the necessary modules"
},
{
"code": null,
"e": 2735,
"s": 2639,
"text": "!pip install datasetsfrom datasets import load_datasetemotion_dataset = load_dataset(\"emotion\")"
},
{
"code": null,
"e": 2775,
"s": 2735,
"text": "This creates an emotion_dataset object."
},
{
"code": null,
"e": 2791,
"s": 2775,
"text": "emotion_dataset"
},
{
"code": null,
"e": 2921,
"s": 2791,
"text": "What we get is a dictionary with each key corresponding to a different split. Let’s access the training data to see its contents."
},
{
"code": null,
"e": 3047,
"s": 2921,
"text": "emotion_train = emotion_dataset['train']print(emotion_train[0])print(emotion_train.column_names)print(emotion_train.features)"
},
{
"code": null,
"e": 3149,
"s": 3047,
"text": "The training dataset comprises six different classes — sadness, joy, love, anger, fear, and surprise."
},
{
"code": null,
"e": 3201,
"s": 3149,
"text": "Converting emotion datasets into a Pandas DataFrame"
},
{
"code": null,
"e": 3293,
"s": 3201,
"text": "We can now easily convert the above dataset into a pandas dataframe and analyze it further."
},
{
"code": null,
"e": 3460,
"s": 3293,
"text": "import pandas as pdemotion_dataset.set_format(type=\"pandas\")train = emotion_dataset[\"train\"][:]test = emotion_dataset[\"test\"][:]val = emotion_dataset[\"validation\"][:]"
},
{
"code": null,
"e": 3514,
"s": 3460,
"text": "Let’s quickly check if the conversion was successful."
},
{
"code": null,
"e": 3527,
"s": 3514,
"text": "train.head()"
},
{
"code": null,
"e": 3780,
"s": 3527,
"text": "Yes, indeed! Now you know how to access datasets from the Huggingface dataset hub- another addition to your data science skill. So what do you do when you have the data? You explore it, and that is precisely what we are going to do in the next section."
},
{
"code": null,
"e": 4060,
"s": 3780,
"text": "We’ll start by importing the necessary libraries and visualizing the data. As we already know, the data has been preprocessed, so that is a bonus. We’ll typically look for imbalance in the dataset and length of the tweets to start with. Beyond that, feel free to dive in further."
},
{
"code": null,
"e": 4136,
"s": 4060,
"text": "Notebooks to follow along: Exploratory Data Analysis of the emotion dataset"
},
{
"code": null,
"e": 4318,
"s": 4136,
"text": "The label column currently has integers. To make it more understandable, we’ll create a new column called description containing the description of each integer in the label column."
},
{
"code": null,
"e": 4507,
"s": 4318,
"text": "Now, let’s analyze and see how the description column looks like. I have only used the training dataset, but the process will remain the same if we wish to do it for the test dataset, too."
},
{
"code": null,
"e": 4532,
"s": 4507,
"text": "Examples of each emotion"
},
{
"code": null,
"e": 4582,
"s": 4532,
"text": "Let’s look at an example of each of the emotions."
},
{
"code": null,
"e": 4718,
"s": 4582,
"text": "It’ll be informative to look at the distribution of the labels. This will also give us an idea of the imbalance in the dataset, if any."
},
{
"code": null,
"e": 4768,
"s": 4718,
"text": "train['description'].value_counts(normalize=True)"
},
{
"code": null,
"e": 4868,
"s": 4768,
"text": "sns.countplot(train['description'],order = train['description'].value_counts(normalize=True).index)"
},
{
"code": null,
"e": 4945,
"s": 4868,
"text": "About 33 percent of the tweets are joyful, followed by sad and angry tweets."
},
{
"code": null,
"e": 5093,
"s": 4945,
"text": "We can now do some statistical analysis to explore the fundamental characteristics of the text data. Some of the analyses which can be helpful are:"
},
{
"code": null,
"e": 5155,
"s": 5093,
"text": "Text length analysis: calculating the length of the text, and"
},
{
"code": null,
"e": 5255,
"s": 5155,
"text": "word frequency analysis: calculating the word count in the form of unigrams, bigrams, and trigrams."
},
{
"code": null,
"e": 5392,
"s": 5255,
"text": "train['text_length'] = train['text'].astype(str).apply(len)train['text_word_count'] = train['text'].apply(lambda x: len(str(x).split()))"
},
{
"code": null,
"e": 5414,
"s": 5392,
"text": "Tweet length analysis"
},
{
"code": null,
"e": 5494,
"s": 5414,
"text": "sns.distplot(train['text_length'])plt.xlim([0, 512]);plt.xlabel('Text Length');"
},
{
"code": null,
"e": 5589,
"s": 5494,
"text": "The histogram above shows that the length of the tweet ranges from around 2 to 300 characters."
},
{
"code": null,
"e": 5655,
"s": 5589,
"text": "Now let’s analyze the frequency of the words per tweet per class."
},
{
"code": null,
"e": 5717,
"s": 5655,
"text": "sns.boxplot(x=\"description\", y=\"text_word_count\", data=train)"
},
{
"code": null,
"e": 5902,
"s": 5717,
"text": "Most of the tweets have an average of 15 words. Also, all the tweets appear to have more or less the same length. Hence, the length of the tweet isn’t a powerful indicator of polarity."
},
{
"code": null,
"e": 6206,
"s": 5902,
"text": "An n-gram is a contiguous sequence of n items from a given sample of text or speech. It is also a good idea to look at various n-grams to understand which words mainly occur together. For instance, we look at the distribution of unigrams, bigrams, and trigrams across emotions- sadness, anger, and love."
}
] |
How to remove the hash from window.location (URL) with JavaScript without page refresh? | You can use the replaceState method on the history API to remove the hash.
The replaceState() method modifies the current history entry, replacing it with the state objects, title, and URL passed in the method parameters. This method is particularly useful when you want to update the state object or URL of the current history entry in response to some user action.
To remove the hash you can use −
history.replaceState(null, null, ' '); | [
{
"code": null,
"e": 1137,
"s": 1062,
"text": "You can use the replaceState method on the history API to remove the hash."
},
{
"code": null,
"e": 1429,
"s": 1137,
"text": "The replaceState() method modifies the current history entry, replacing it with the state objects, title, and URL passed in the method parameters. This method is particularly useful when you want to update the state object or URL of the current history entry in response to some user action."
},
{
"code": null,
"e": 1462,
"s": 1429,
"text": "To remove the hash you can use −"
},
{
"code": null,
"e": 1501,
"s": 1462,
"text": "history.replaceState(null, null, ' ');"
}
] |
How to convert a spreadsheet to Python dictionary? | The easiest way to convert a spreadsheet to Python dictionary is to use an external library like pandas. This provides very helpful features like to_dict on excel objects. You can use these like −
from pandas import *
xls = ExcelFile('my_file.xls')
data = xls.parse(xls.sheet_names[0])
print(data.to_dict())
This will give the output −
{'id': 10, 'name': "John"} | [
{
"code": null,
"e": 1259,
"s": 1062,
"text": "The easiest way to convert a spreadsheet to Python dictionary is to use an external library like pandas. This provides very helpful features like to_dict on excel objects. You can use these like −"
},
{
"code": null,
"e": 1370,
"s": 1259,
"text": "from pandas import *\nxls = ExcelFile('my_file.xls')\ndata = xls.parse(xls.sheet_names[0])\nprint(data.to_dict())"
},
{
"code": null,
"e": 1398,
"s": 1370,
"text": "This will give the output −"
},
{
"code": null,
"e": 1425,
"s": 1398,
"text": "{'id': 10, 'name': \"John\"}"
}
] |
Let’s talk about NumPy — for Data Science Beginners | by Ehi Aigiomawu | Towards Data Science | NumPy (Numerical Python) is a linear algebra library in Python. It is a very important library on which almost every data science or machine learning Python packages such as SciPy (Scientific Python), Mat−plotlib (plotting library), Scikit-learn, etc depends on to a reasonable extent.
NumPy is very useful for performing mathematical and logical operations on Arrays. It provides an abundance of useful features for operations on n-arrays and matrices in Python.
This course covers basics things to know about NumPy as a beginner in Data science. These includes how to create NumPy arrays, use broadcasting, access values, and manipulate arrays. More importantly, you will learn NumPy’s benefit over Python lists, which include: being more compact, faster access in reading and writing items, being more convenient and more efficient.
In this course, we will be using the Jupyter notebook as our editor.
Let’s Go!
If you have Anaconda, you can simply install NumPy from your terminal or command prompt using:
conda install numpy
If you do not have Anaconda on your computer, install NumPy from your terminal using:
pip install numpy
Once you have NumPy installed, launch your Jupyter notebook and get started. Let’s begin with NumPy Arrays
A NumPy array is simply a grid that contains values of the same type. NumPy Arrays come in two forms; Vectors and Matrices. Vectors are strictly one-dimensional(1-d) arrays, while Matrices are multidimensional. In some cases, Matrices can still have only one row or one column.
Let’s start by importing NumPy in your Jupyter notebook.
import numpy as np
Creating numpy arrays from python lists
Say we have a Python list:
my_list = [1, 2, 3, 4, 5]
We can simply create a NumPy array called my_numpy_list and display the result:
my_numpy_list = np.array(my_list)my_numpy_list #This line show the result of the array generated
What we have just done is casting a python list into a one-dimensional array. To get a 2-dimensional array, we have to cast a list of list as shown below.
second_list = [[1,2,3], [5,4,1], [3,6,7]]new_2d_arr = np.array(second_list)new_2d_arr #This line show the result of the array generated
We have successfully created a 2-d array that has 3 rows and 3 columns.
Creating NumPy array using arange() built-in function.
Similar to the python built-in range() function, we will create a NumPy array using arange().
my_list = np.arange(10)#ORmy_list = np.arange(0,10)
This generates 10 digits of values from index 0 to 10.
It is important to note that the arange() function can also take 3 arguments. The third argument signifies the step size of the operation. For example, to get all even numbers from 0 to 10, simply add a step size of 2 like below.
my_list = np.arange(0,11,2)
We can also generate a one-dimensional array of seven zeros.
my_zeros = np.zeros(7)
We can also generate a one-dimensional array of five ones.
my_ones = np.ones(5)
Similarly, we could generate a two-dimensional array of zeros having 3 rows and 5 columns
two_d = np.zeros((3,5))
Creating NumPy array using linspace() built-in function.
The linspace() function returns numbers evenly spaced over a specified intervals. Say we want 15 evenly spaced points from 1 to 3, we can easily use:
lin_arr = np.linspace(1, 3, 15)
This gives us a one dimensional vector.
Unlike the arange() function which takes the third argument as the number of steps, linspace() takes the third argument as the number of datapoints to be created.
Creating an identity matrix in NumPy
Identity matrices are very useful when dealing with linear algebras. Usually, is a two-dimensional square matrix. This means the number of row is equal to the number of column. One unique thing to note about identity matrix is that the diagonals are 1’s and everything else is 0. Identity matrices usually takes a single argument. Here’s how to create one.
my_matrx = np.eye(6) #6 is the number of columns/rows you want
Generating an array of random numbers in NumPy
We can generate an array of random numbers using rand(), randn() or randint() functions.
Using random.rand(), we can generate an array of random numbers of the shape we pass to it from uniform distribution over 0 to 1.
For example, say we want a one-dimensional array of 4 objects that are uniformly distributed from 0 to 1, we can do this:
my_rand = np.random.rand(4)
And if we want a two-dimensional array of 5rows and 4columns:
my_rand = np.random.rand(5, 4)my_rand
Using randn(), we can generate random samples from Standard, normal or Gaussian distribution centered around 0. For example, let’s generate 7 random numbers:
my_randn = np.random.randn(7)my_randn
When you plot the result will give us a normal distribution curve.
Similarly, to generate a two-dimensional array of 3 rows and 5 columns, do this:
np.random.randn(3,5)
Lastly, we can use the randint() function to generate an array of integers. The randint() function can take up to 3 arguments; the low(inclusive), high(exclusive) and size of the array.
np.random.randint(20) #generates a random integer exclusive of 20np.random.randint(2, 20) #generates a random integer including 2 but excluding 20np.random.randint(2, 20, 7) #generates 7 random integers including 2 but excluding 20
Converting one-dimensional array to two-dimensional
First, we generate a 1-d array of random 25 integers
arr = np.random.rand(25)
Then convert it to a 2-d array using the reshape() function
arr.reshape(5,5)
Note: The reshape() can only convert to equal number or rows and columns and must together be equal to equal to the number of elements. In the example above, arr contained 25 elements hence can only be reshaped to a 5X5 matrix.
Locating the maximum and minimum values of a NumPy Array
Using the max(), and min(), we can get the maximum or minimum values in an array.
arr_2 = np.random.randint(0, 20, 10) arr_2.max() #This gives the highest value in the array arr_2.min() #This gives the lowest value in the array
Using the argmax() and argmin() functions, we can locate the index of the maximum or minimum values in an array.
arr_2.argmax() #This shows the index of the highest value in the array arr_2.argmin() #This shows the index of the lowest value in the array
Say you have a large volume of array and you are trying to figure out the shape of that array, you want to know if it’s a one-dimensional or two-dimensional array, simply use the shape function.
arr.shape
Indexing/Selecting elements or groups of elements from a NumPy array
Indexing NumPy arrays is similar to that of Python. You simply pass in the index you want.
my_array = np.arange(0,11)my_array[8] #This gives us the value of element at index 8
To get a range of values in an array, we will use the slice notation ‘:’ just like in Python
my_array[2:6] #This returns everything from index 2 to 6(exclusive)my_array[:6] #This returns everything from index 0 to 6(exclusive)my_array[5:] #This returns everything from index 5 to the end of the array.
Similarly, we can select elements in a 2-d array using either the double bracket [][] notation or the single bracket [,] notation.
Using the double bracket notation, we will grab the value ‘60’ from the 2-d array below:
two_d_arr = np.array([[10,20,30], [40,50,60], [70,80,90]])two_d_arr[1][2] #The value 60 appears is in row index 1, and column index 2
Using the single bracket notation, we will grab the value ‘20’ from the array above:
two_d_arr[0,1]
We can also go further to grab subsections of a 2-d array using the slice notation. Let’s grab some elements in some corners of the array:
two_d_arr[:1, :2] # This returns [[10, 20]]two_d_arr[:2, 1:] # This returns ([[20, 30], [50, 60]])two_d_arr[:2, :2] #This returns ([[10, 20], [40, 50]])
We can also index an entire row or column. To grab any row, simple use it’s index number like this:
two_d_arr[0] #This grabs row 0 of the array ([10, 20, 30])two_d_arr[:2] #This grabs everything before row 2 ([[10, 20, 30], [40, 50, 60]])
We can also perform conditional and logical selections on arrays using & (AND), | (OR), <, > and == operators to compare the values in the array with the given value. Here’s how:
new_arr = np.arange(5,15)new_arr > 10 #This returns TRUE where the elements are greater than 10 [False, False, False, False, False, False, True, True, True, True]
Now we can print out the actual elements that were TRUE in the above conditional using:
bool_arr = new_arr > 10new_arr[bool_arr] #This returns elements greater than 10 [11, 12, 13, 14]new_arr[new_arr>10] #A shorter way to do what we have just done
Using a combination of conditional and Logical & (AND) operators, we can get elements that are greater than 6 but less than 10.
new_arr[(new_arr>6) & (new_arr<10)]
Our expected result is: ([7, 8, 9])
Broadcasting
Broadcasting is a quick way to change the values of a NumPy array.
my_array[0:3] = 50#Result is: [50, 50, 50, 3, 4, 5, 6, 7, 8, 9, 10]
In this example, we changed the values of the elements in index 0 to 3 from their initial values to 50.
Performing arithmetic operations on NumPy Arrays
arr = np.arange(1,11)arr * arr #Multiplies each element by itself arr - arr #Subtracts each element from itselfarr + arr #Adds each element to itselfarr / arr #Divides each element by itself
We can also perform scalar operations on an array. NumPy makes it possible through broadcasting.
arr + 50 #This adds 50 to every element in that array
Numpy also let’s you perform universal functions such as square roots, exponentials, trigonometric, etc on array.
np.sqrt(arr) #Returns the square root of each element np.exp(arr) #Returns the exponentials of each elementnp.sin(arr) #Returns the sin of each elementnp.cos(arr) #Returns the cosine of each elementnp.log(arr) #Returns the logarithm of each elementnp.sum(arr) #Returns the sum total of elements in the arraynp.std(arr) #Returns the standard deviation of in the array
We can also grab the sum of columns or rows in a 2-d array:
mat = np.arange(1,26).reshape(5,5)mat.sum() #Returns the sum of all the values in matmat.sum(axis=0) #Returns the sum of all the columns in matmat.sum(axis=1) #Returns the sum of all the rows in mat
Congratulations, we have come to the end of the NumPy tutorial!
If you completed this lesson, then you have covered a lot of grounds. Keep practicing, so that your new found knowledge stays fresh.
Got questions, got stuck or just want to say hi? kindly use the comment box. If this tutorial was helpful to you in some way, show me some 👏. | [
{
"code": null,
"e": 458,
"s": 172,
"text": "NumPy (Numerical Python) is a linear algebra library in Python. It is a very important library on which almost every data science or machine learning Python packages such as SciPy (Scientific Python), Mat−plotlib (plotting library), Scikit-learn, etc depends on to a reasonable extent."
},
{
"code": null,
"e": 636,
"s": 458,
"text": "NumPy is very useful for performing mathematical and logical operations on Arrays. It provides an abundance of useful features for operations on n-arrays and matrices in Python."
},
{
"code": null,
"e": 1008,
"s": 636,
"text": "This course covers basics things to know about NumPy as a beginner in Data science. These includes how to create NumPy arrays, use broadcasting, access values, and manipulate arrays. More importantly, you will learn NumPy’s benefit over Python lists, which include: being more compact, faster access in reading and writing items, being more convenient and more efficient."
},
{
"code": null,
"e": 1077,
"s": 1008,
"text": "In this course, we will be using the Jupyter notebook as our editor."
},
{
"code": null,
"e": 1087,
"s": 1077,
"text": "Let’s Go!"
},
{
"code": null,
"e": 1182,
"s": 1087,
"text": "If you have Anaconda, you can simply install NumPy from your terminal or command prompt using:"
},
{
"code": null,
"e": 1202,
"s": 1182,
"text": "conda install numpy"
},
{
"code": null,
"e": 1288,
"s": 1202,
"text": "If you do not have Anaconda on your computer, install NumPy from your terminal using:"
},
{
"code": null,
"e": 1306,
"s": 1288,
"text": "pip install numpy"
},
{
"code": null,
"e": 1413,
"s": 1306,
"text": "Once you have NumPy installed, launch your Jupyter notebook and get started. Let’s begin with NumPy Arrays"
},
{
"code": null,
"e": 1691,
"s": 1413,
"text": "A NumPy array is simply a grid that contains values of the same type. NumPy Arrays come in two forms; Vectors and Matrices. Vectors are strictly one-dimensional(1-d) arrays, while Matrices are multidimensional. In some cases, Matrices can still have only one row or one column."
},
{
"code": null,
"e": 1748,
"s": 1691,
"text": "Let’s start by importing NumPy in your Jupyter notebook."
},
{
"code": null,
"e": 1767,
"s": 1748,
"text": "import numpy as np"
},
{
"code": null,
"e": 1807,
"s": 1767,
"text": "Creating numpy arrays from python lists"
},
{
"code": null,
"e": 1834,
"s": 1807,
"text": "Say we have a Python list:"
},
{
"code": null,
"e": 1860,
"s": 1834,
"text": "my_list = [1, 2, 3, 4, 5]"
},
{
"code": null,
"e": 1940,
"s": 1860,
"text": "We can simply create a NumPy array called my_numpy_list and display the result:"
},
{
"code": null,
"e": 2038,
"s": 1940,
"text": "my_numpy_list = np.array(my_list)my_numpy_list #This line show the result of the array generated"
},
{
"code": null,
"e": 2193,
"s": 2038,
"text": "What we have just done is casting a python list into a one-dimensional array. To get a 2-dimensional array, we have to cast a list of list as shown below."
},
{
"code": null,
"e": 2330,
"s": 2193,
"text": "second_list = [[1,2,3], [5,4,1], [3,6,7]]new_2d_arr = np.array(second_list)new_2d_arr #This line show the result of the array generated"
},
{
"code": null,
"e": 2402,
"s": 2330,
"text": "We have successfully created a 2-d array that has 3 rows and 3 columns."
},
{
"code": null,
"e": 2457,
"s": 2402,
"text": "Creating NumPy array using arange() built-in function."
},
{
"code": null,
"e": 2551,
"s": 2457,
"text": "Similar to the python built-in range() function, we will create a NumPy array using arange()."
},
{
"code": null,
"e": 2603,
"s": 2551,
"text": "my_list = np.arange(10)#ORmy_list = np.arange(0,10)"
},
{
"code": null,
"e": 2658,
"s": 2603,
"text": "This generates 10 digits of values from index 0 to 10."
},
{
"code": null,
"e": 2888,
"s": 2658,
"text": "It is important to note that the arange() function can also take 3 arguments. The third argument signifies the step size of the operation. For example, to get all even numbers from 0 to 10, simply add a step size of 2 like below."
},
{
"code": null,
"e": 2916,
"s": 2888,
"text": "my_list = np.arange(0,11,2)"
},
{
"code": null,
"e": 2977,
"s": 2916,
"text": "We can also generate a one-dimensional array of seven zeros."
},
{
"code": null,
"e": 3000,
"s": 2977,
"text": "my_zeros = np.zeros(7)"
},
{
"code": null,
"e": 3059,
"s": 3000,
"text": "We can also generate a one-dimensional array of five ones."
},
{
"code": null,
"e": 3080,
"s": 3059,
"text": "my_ones = np.ones(5)"
},
{
"code": null,
"e": 3170,
"s": 3080,
"text": "Similarly, we could generate a two-dimensional array of zeros having 3 rows and 5 columns"
},
{
"code": null,
"e": 3194,
"s": 3170,
"text": "two_d = np.zeros((3,5))"
},
{
"code": null,
"e": 3251,
"s": 3194,
"text": "Creating NumPy array using linspace() built-in function."
},
{
"code": null,
"e": 3401,
"s": 3251,
"text": "The linspace() function returns numbers evenly spaced over a specified intervals. Say we want 15 evenly spaced points from 1 to 3, we can easily use:"
},
{
"code": null,
"e": 3433,
"s": 3401,
"text": "lin_arr = np.linspace(1, 3, 15)"
},
{
"code": null,
"e": 3473,
"s": 3433,
"text": "This gives us a one dimensional vector."
},
{
"code": null,
"e": 3636,
"s": 3473,
"text": "Unlike the arange() function which takes the third argument as the number of steps, linspace() takes the third argument as the number of datapoints to be created."
},
{
"code": null,
"e": 3673,
"s": 3636,
"text": "Creating an identity matrix in NumPy"
},
{
"code": null,
"e": 4030,
"s": 3673,
"text": "Identity matrices are very useful when dealing with linear algebras. Usually, is a two-dimensional square matrix. This means the number of row is equal to the number of column. One unique thing to note about identity matrix is that the diagonals are 1’s and everything else is 0. Identity matrices usually takes a single argument. Here’s how to create one."
},
{
"code": null,
"e": 4096,
"s": 4030,
"text": "my_matrx = np.eye(6) #6 is the number of columns/rows you want"
},
{
"code": null,
"e": 4143,
"s": 4096,
"text": "Generating an array of random numbers in NumPy"
},
{
"code": null,
"e": 4232,
"s": 4143,
"text": "We can generate an array of random numbers using rand(), randn() or randint() functions."
},
{
"code": null,
"e": 4362,
"s": 4232,
"text": "Using random.rand(), we can generate an array of random numbers of the shape we pass to it from uniform distribution over 0 to 1."
},
{
"code": null,
"e": 4484,
"s": 4362,
"text": "For example, say we want a one-dimensional array of 4 objects that are uniformly distributed from 0 to 1, we can do this:"
},
{
"code": null,
"e": 4512,
"s": 4484,
"text": "my_rand = np.random.rand(4)"
},
{
"code": null,
"e": 4574,
"s": 4512,
"text": "And if we want a two-dimensional array of 5rows and 4columns:"
},
{
"code": null,
"e": 4612,
"s": 4574,
"text": "my_rand = np.random.rand(5, 4)my_rand"
},
{
"code": null,
"e": 4770,
"s": 4612,
"text": "Using randn(), we can generate random samples from Standard, normal or Gaussian distribution centered around 0. For example, let’s generate 7 random numbers:"
},
{
"code": null,
"e": 4808,
"s": 4770,
"text": "my_randn = np.random.randn(7)my_randn"
},
{
"code": null,
"e": 4875,
"s": 4808,
"text": "When you plot the result will give us a normal distribution curve."
},
{
"code": null,
"e": 4956,
"s": 4875,
"text": "Similarly, to generate a two-dimensional array of 3 rows and 5 columns, do this:"
},
{
"code": null,
"e": 4977,
"s": 4956,
"text": "np.random.randn(3,5)"
},
{
"code": null,
"e": 5163,
"s": 4977,
"text": "Lastly, we can use the randint() function to generate an array of integers. The randint() function can take up to 3 arguments; the low(inclusive), high(exclusive) and size of the array."
},
{
"code": null,
"e": 5395,
"s": 5163,
"text": "np.random.randint(20) #generates a random integer exclusive of 20np.random.randint(2, 20) #generates a random integer including 2 but excluding 20np.random.randint(2, 20, 7) #generates 7 random integers including 2 but excluding 20"
},
{
"code": null,
"e": 5447,
"s": 5395,
"text": "Converting one-dimensional array to two-dimensional"
},
{
"code": null,
"e": 5500,
"s": 5447,
"text": "First, we generate a 1-d array of random 25 integers"
},
{
"code": null,
"e": 5525,
"s": 5500,
"text": "arr = np.random.rand(25)"
},
{
"code": null,
"e": 5585,
"s": 5525,
"text": "Then convert it to a 2-d array using the reshape() function"
},
{
"code": null,
"e": 5602,
"s": 5585,
"text": "arr.reshape(5,5)"
},
{
"code": null,
"e": 5830,
"s": 5602,
"text": "Note: The reshape() can only convert to equal number or rows and columns and must together be equal to equal to the number of elements. In the example above, arr contained 25 elements hence can only be reshaped to a 5X5 matrix."
},
{
"code": null,
"e": 5887,
"s": 5830,
"text": "Locating the maximum and minimum values of a NumPy Array"
},
{
"code": null,
"e": 5969,
"s": 5887,
"text": "Using the max(), and min(), we can get the maximum or minimum values in an array."
},
{
"code": null,
"e": 6115,
"s": 5969,
"text": "arr_2 = np.random.randint(0, 20, 10) arr_2.max() #This gives the highest value in the array arr_2.min() #This gives the lowest value in the array"
},
{
"code": null,
"e": 6228,
"s": 6115,
"text": "Using the argmax() and argmin() functions, we can locate the index of the maximum or minimum values in an array."
},
{
"code": null,
"e": 6369,
"s": 6228,
"text": "arr_2.argmax() #This shows the index of the highest value in the array arr_2.argmin() #This shows the index of the lowest value in the array"
},
{
"code": null,
"e": 6564,
"s": 6369,
"text": "Say you have a large volume of array and you are trying to figure out the shape of that array, you want to know if it’s a one-dimensional or two-dimensional array, simply use the shape function."
},
{
"code": null,
"e": 6574,
"s": 6564,
"text": "arr.shape"
},
{
"code": null,
"e": 6643,
"s": 6574,
"text": "Indexing/Selecting elements or groups of elements from a NumPy array"
},
{
"code": null,
"e": 6734,
"s": 6643,
"text": "Indexing NumPy arrays is similar to that of Python. You simply pass in the index you want."
},
{
"code": null,
"e": 6820,
"s": 6734,
"text": "my_array = np.arange(0,11)my_array[8] #This gives us the value of element at index 8"
},
{
"code": null,
"e": 6913,
"s": 6820,
"text": "To get a range of values in an array, we will use the slice notation ‘:’ just like in Python"
},
{
"code": null,
"e": 7122,
"s": 6913,
"text": "my_array[2:6] #This returns everything from index 2 to 6(exclusive)my_array[:6] #This returns everything from index 0 to 6(exclusive)my_array[5:] #This returns everything from index 5 to the end of the array."
},
{
"code": null,
"e": 7253,
"s": 7122,
"text": "Similarly, we can select elements in a 2-d array using either the double bracket [][] notation or the single bracket [,] notation."
},
{
"code": null,
"e": 7342,
"s": 7253,
"text": "Using the double bracket notation, we will grab the value ‘60’ from the 2-d array below:"
},
{
"code": null,
"e": 7476,
"s": 7342,
"text": "two_d_arr = np.array([[10,20,30], [40,50,60], [70,80,90]])two_d_arr[1][2] #The value 60 appears is in row index 1, and column index 2"
},
{
"code": null,
"e": 7561,
"s": 7476,
"text": "Using the single bracket notation, we will grab the value ‘20’ from the array above:"
},
{
"code": null,
"e": 7577,
"s": 7561,
"text": "two_d_arr[0,1] "
},
{
"code": null,
"e": 7716,
"s": 7577,
"text": "We can also go further to grab subsections of a 2-d array using the slice notation. Let’s grab some elements in some corners of the array:"
},
{
"code": null,
"e": 7899,
"s": 7716,
"text": "two_d_arr[:1, :2] # This returns [[10, 20]]two_d_arr[:2, 1:] # This returns ([[20, 30], [50, 60]])two_d_arr[:2, :2] #This returns ([[10, 20], [40, 50]])"
},
{
"code": null,
"e": 7999,
"s": 7899,
"text": "We can also index an entire row or column. To grab any row, simple use it’s index number like this:"
},
{
"code": null,
"e": 8141,
"s": 7999,
"text": "two_d_arr[0] #This grabs row 0 of the array ([10, 20, 30])two_d_arr[:2] #This grabs everything before row 2 ([[10, 20, 30], [40, 50, 60]])"
},
{
"code": null,
"e": 8320,
"s": 8141,
"text": "We can also perform conditional and logical selections on arrays using & (AND), | (OR), <, > and == operators to compare the values in the array with the given value. Here’s how:"
},
{
"code": null,
"e": 8486,
"s": 8320,
"text": "new_arr = np.arange(5,15)new_arr > 10 #This returns TRUE where the elements are greater than 10 [False, False, False, False, False, False, True, True, True, True]"
},
{
"code": null,
"e": 8574,
"s": 8486,
"text": "Now we can print out the actual elements that were TRUE in the above conditional using:"
},
{
"code": null,
"e": 8735,
"s": 8574,
"text": "bool_arr = new_arr > 10new_arr[bool_arr] #This returns elements greater than 10 [11, 12, 13, 14]new_arr[new_arr>10] #A shorter way to do what we have just done"
},
{
"code": null,
"e": 8863,
"s": 8735,
"text": "Using a combination of conditional and Logical & (AND) operators, we can get elements that are greater than 6 but less than 10."
},
{
"code": null,
"e": 8899,
"s": 8863,
"text": "new_arr[(new_arr>6) & (new_arr<10)]"
},
{
"code": null,
"e": 8935,
"s": 8899,
"text": "Our expected result is: ([7, 8, 9])"
},
{
"code": null,
"e": 8948,
"s": 8935,
"text": "Broadcasting"
},
{
"code": null,
"e": 9015,
"s": 8948,
"text": "Broadcasting is a quick way to change the values of a NumPy array."
},
{
"code": null,
"e": 9088,
"s": 9015,
"text": "my_array[0:3] = 50#Result is: [50, 50, 50, 3, 4, 5, 6, 7, 8, 9, 10]"
},
{
"code": null,
"e": 9192,
"s": 9088,
"text": "In this example, we changed the values of the elements in index 0 to 3 from their initial values to 50."
},
{
"code": null,
"e": 9241,
"s": 9192,
"text": "Performing arithmetic operations on NumPy Arrays"
},
{
"code": null,
"e": 9484,
"s": 9241,
"text": "arr = np.arange(1,11)arr * arr #Multiplies each element by itself arr - arr #Subtracts each element from itselfarr + arr #Adds each element to itselfarr / arr #Divides each element by itself"
},
{
"code": null,
"e": 9581,
"s": 9484,
"text": "We can also perform scalar operations on an array. NumPy makes it possible through broadcasting."
},
{
"code": null,
"e": 9648,
"s": 9581,
"text": "arr + 50 #This adds 50 to every element in that array"
},
{
"code": null,
"e": 9762,
"s": 9648,
"text": "Numpy also let’s you perform universal functions such as square roots, exponentials, trigonometric, etc on array."
},
{
"code": null,
"e": 10157,
"s": 9762,
"text": "np.sqrt(arr) #Returns the square root of each element np.exp(arr) #Returns the exponentials of each elementnp.sin(arr) #Returns the sin of each elementnp.cos(arr) #Returns the cosine of each elementnp.log(arr) #Returns the logarithm of each elementnp.sum(arr) #Returns the sum total of elements in the arraynp.std(arr) #Returns the standard deviation of in the array"
},
{
"code": null,
"e": 10217,
"s": 10157,
"text": "We can also grab the sum of columns or rows in a 2-d array:"
},
{
"code": null,
"e": 10428,
"s": 10217,
"text": "mat = np.arange(1,26).reshape(5,5)mat.sum() #Returns the sum of all the values in matmat.sum(axis=0) #Returns the sum of all the columns in matmat.sum(axis=1) #Returns the sum of all the rows in mat"
},
{
"code": null,
"e": 10492,
"s": 10428,
"text": "Congratulations, we have come to the end of the NumPy tutorial!"
},
{
"code": null,
"e": 10625,
"s": 10492,
"text": "If you completed this lesson, then you have covered a lot of grounds. Keep practicing, so that your new found knowledge stays fresh."
}
] |
Deep Reinforcement Learning With Python | Part 3| Using Tensorboard to Analyse Trained Models | by Mohammed AL-Ma'amari | Towards Data Science | First part explained and created the game environment.
towardsdatascience.com
Second part discussed the process of training the DQN, explained DQNs and gave reasons to choose DQN over Q-Learning.
towardsdatascience.com
We are going to:
Use Tensorboard to visualize the goodness of trained models.
Explain the way of loading and trying a trained model.
Use the best model and let it play the game.
1- Use a modified Tensorboard to make Tensorboard logs the data from all episodes in the training process in one log file instead of making a new log file every time we fit the model.
The next code of the ModifiedTensorBoard is from this blog by sentdex, I just changed it a little bit to make it run on TensorFlow2.0:
2- Define an object of the modified tensorboard in the __init__ of the agent class:
PATH and name are used to define the full path where the log file will be saved in.
3- Pass the modified tensorboard as a callback when fitting the model:
4- At the start of each episode :
5- To update the logs, use the next line:
Open the terminal on the directory where the “logs” folder is and run:
tensorboard --logdir="logs/"
A browser window will appear:
You can try the other options by yourself.
By using these visualisations we can see the relations between logged variables, such as epsilon and max_reward.
Deep Q Learning w/ DQN — Reinforcement Learning p.5
Other parts of this series:
towardsdatascience.com
towardsdatascience.com
You can follow me on:
Twitter
LinkedIn
FaceBook
Deep Neural Networks for Regression Problems
AI Generates Taylor Swift’s Song Lyrics
Introduction to Random Forest Algorithm with Python
Machine Learning Crash Course with TensorFlow APIs Summary
How To Make A CNN Using Tensorflow and Keras ?
How to Choose the Best Machine Learning Model ? | [
{
"code": null,
"e": 227,
"s": 172,
"text": "First part explained and created the game environment."
},
{
"code": null,
"e": 250,
"s": 227,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 368,
"s": 250,
"text": "Second part discussed the process of training the DQN, explained DQNs and gave reasons to choose DQN over Q-Learning."
},
{
"code": null,
"e": 391,
"s": 368,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 408,
"s": 391,
"text": "We are going to:"
},
{
"code": null,
"e": 469,
"s": 408,
"text": "Use Tensorboard to visualize the goodness of trained models."
},
{
"code": null,
"e": 524,
"s": 469,
"text": "Explain the way of loading and trying a trained model."
},
{
"code": null,
"e": 569,
"s": 524,
"text": "Use the best model and let it play the game."
},
{
"code": null,
"e": 753,
"s": 569,
"text": "1- Use a modified Tensorboard to make Tensorboard logs the data from all episodes in the training process in one log file instead of making a new log file every time we fit the model."
},
{
"code": null,
"e": 888,
"s": 753,
"text": "The next code of the ModifiedTensorBoard is from this blog by sentdex, I just changed it a little bit to make it run on TensorFlow2.0:"
},
{
"code": null,
"e": 972,
"s": 888,
"text": "2- Define an object of the modified tensorboard in the __init__ of the agent class:"
},
{
"code": null,
"e": 1056,
"s": 972,
"text": "PATH and name are used to define the full path where the log file will be saved in."
},
{
"code": null,
"e": 1127,
"s": 1056,
"text": "3- Pass the modified tensorboard as a callback when fitting the model:"
},
{
"code": null,
"e": 1161,
"s": 1127,
"text": "4- At the start of each episode :"
},
{
"code": null,
"e": 1203,
"s": 1161,
"text": "5- To update the logs, use the next line:"
},
{
"code": null,
"e": 1274,
"s": 1203,
"text": "Open the terminal on the directory where the “logs” folder is and run:"
},
{
"code": null,
"e": 1303,
"s": 1274,
"text": "tensorboard --logdir=\"logs/\""
},
{
"code": null,
"e": 1333,
"s": 1303,
"text": "A browser window will appear:"
},
{
"code": null,
"e": 1376,
"s": 1333,
"text": "You can try the other options by yourself."
},
{
"code": null,
"e": 1489,
"s": 1376,
"text": "By using these visualisations we can see the relations between logged variables, such as epsilon and max_reward."
},
{
"code": null,
"e": 1541,
"s": 1489,
"text": "Deep Q Learning w/ DQN — Reinforcement Learning p.5"
},
{
"code": null,
"e": 1569,
"s": 1541,
"text": "Other parts of this series:"
},
{
"code": null,
"e": 1592,
"s": 1569,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 1615,
"s": 1592,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 1637,
"s": 1615,
"text": "You can follow me on:"
},
{
"code": null,
"e": 1645,
"s": 1637,
"text": "Twitter"
},
{
"code": null,
"e": 1654,
"s": 1645,
"text": "LinkedIn"
},
{
"code": null,
"e": 1663,
"s": 1654,
"text": "FaceBook"
},
{
"code": null,
"e": 1708,
"s": 1663,
"text": "Deep Neural Networks for Regression Problems"
},
{
"code": null,
"e": 1748,
"s": 1708,
"text": "AI Generates Taylor Swift’s Song Lyrics"
},
{
"code": null,
"e": 1800,
"s": 1748,
"text": "Introduction to Random Forest Algorithm with Python"
},
{
"code": null,
"e": 1859,
"s": 1800,
"text": "Machine Learning Crash Course with TensorFlow APIs Summary"
},
{
"code": null,
"e": 1906,
"s": 1859,
"text": "How To Make A CNN Using Tensorflow and Keras ?"
}
] |
Difference Between throw and throws in Java - GeeksforGeeks | 07 Dec, 2021
Prerequisite: Throw and Throws in Java
The throw and throws are the concepts of exception handling in Java where the throw keyword throws the exception explicitly from a method or a block of code, whereas the throws keyword is used in the signature of the method.
The differences between throw and throws in Java are:
S. No.
Key Difference
throw
throws
1. Java throw
Java
// Java program to demonstrate the working // of throw keyword in exception handling public class GFG { public static void main(String[] args) { // Use of unchecked Exception try { // double x=3/0; throw new ArithmeticException(); } catch (ArithmeticException e) { e.printStackTrace(); } }}
Output:
java.lang.ArithmeticException
at GFG.main(GFG.java:10)
2. Java throws
Java
// Java program to demonstrate the working// of throws keyword in exception handlingimport java.io.*;import java.util.*; public class GFG { public static void writeToFile() throws Exception { BufferedWriter bw = new BufferedWriter( new FileWriter("myFile.txt")); bw.write("Test"); bw.close(); } public static void main(String[] args) throws Exception { try { writeToFile(); } catch (Exception e) { e.printStackTrace(); } }}
Output:
java.security.AccessControlException: access denied ("java.io.FilePermission" "myFile.txt" "write")
at GFG.writeToFile(GFG.java:10)
nishkarshgandhi
Exception Handling
java-basics
Java-Exceptions
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Interfaces in Java
ArrayList in Java
Multidimensional Arrays in Java
Stack Class in Java
Stream In Java
Singleton Class in Java
Set in Java
Overriding in Java
LinkedList in Java
Collections in Java | [
{
"code": null,
"e": 24453,
"s": 24425,
"text": "\n07 Dec, 2021"
},
{
"code": null,
"e": 24492,
"s": 24453,
"text": "Prerequisite: Throw and Throws in Java"
},
{
"code": null,
"e": 24717,
"s": 24492,
"text": "The throw and throws are the concepts of exception handling in Java where the throw keyword throws the exception explicitly from a method or a block of code, whereas the throws keyword is used in the signature of the method."
},
{
"code": null,
"e": 24771,
"s": 24717,
"text": "The differences between throw and throws in Java are:"
},
{
"code": null,
"e": 24778,
"s": 24771,
"text": "S. No."
},
{
"code": null,
"e": 24793,
"s": 24778,
"text": "Key Difference"
},
{
"code": null,
"e": 24799,
"s": 24793,
"text": "throw"
},
{
"code": null,
"e": 24806,
"s": 24799,
"text": "throws"
},
{
"code": null,
"e": 24820,
"s": 24806,
"text": "1. Java throw"
},
{
"code": null,
"e": 24825,
"s": 24820,
"text": "Java"
},
{
"code": "// Java program to demonstrate the working // of throw keyword in exception handling public class GFG { public static void main(String[] args) { // Use of unchecked Exception try { // double x=3/0; throw new ArithmeticException(); } catch (ArithmeticException e) { e.printStackTrace(); } }}",
"e": 25194,
"s": 24825,
"text": null
},
{
"code": null,
"e": 25203,
"s": 25194,
"text": "Output: "
},
{
"code": null,
"e": 25262,
"s": 25203,
"text": "java.lang.ArithmeticException\n at GFG.main(GFG.java:10)"
},
{
"code": null,
"e": 25277,
"s": 25262,
"text": "2. Java throws"
},
{
"code": null,
"e": 25282,
"s": 25277,
"text": "Java"
},
{
"code": "// Java program to demonstrate the working// of throws keyword in exception handlingimport java.io.*;import java.util.*; public class GFG { public static void writeToFile() throws Exception { BufferedWriter bw = new BufferedWriter( new FileWriter(\"myFile.txt\")); bw.write(\"Test\"); bw.close(); } public static void main(String[] args) throws Exception { try { writeToFile(); } catch (Exception e) { e.printStackTrace(); } }}",
"e": 25811,
"s": 25282,
"text": null
},
{
"code": null,
"e": 25819,
"s": 25811,
"text": "Output:"
},
{
"code": null,
"e": 25953,
"s": 25819,
"text": "java.security.AccessControlException: access denied (\"java.io.FilePermission\" \"myFile.txt\" \"write\")\n at GFG.writeToFile(GFG.java:10)"
},
{
"code": null,
"e": 25969,
"s": 25953,
"text": "nishkarshgandhi"
},
{
"code": null,
"e": 25988,
"s": 25969,
"text": "Exception Handling"
},
{
"code": null,
"e": 26000,
"s": 25988,
"text": "java-basics"
},
{
"code": null,
"e": 26016,
"s": 26000,
"text": "Java-Exceptions"
},
{
"code": null,
"e": 26021,
"s": 26016,
"text": "Java"
},
{
"code": null,
"e": 26026,
"s": 26021,
"text": "Java"
},
{
"code": null,
"e": 26124,
"s": 26026,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26143,
"s": 26124,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 26161,
"s": 26143,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 26193,
"s": 26161,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 26213,
"s": 26193,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 26228,
"s": 26213,
"text": "Stream In Java"
},
{
"code": null,
"e": 26252,
"s": 26228,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 26264,
"s": 26252,
"text": "Set in Java"
},
{
"code": null,
"e": 26283,
"s": 26264,
"text": "Overriding in Java"
},
{
"code": null,
"e": 26302,
"s": 26283,
"text": "LinkedList in Java"
}
] |
Is it possible to style HTML5 audio tag? | HTML 5 audio tags can be styled. By using the audio tag with “controls” attribute, the default browsers player is used. You can customize by not using the browsers controls.
By removing the controls attribute, you can hide the built in browser user’s interface −
<audioid = "player" src = "kalimba.mp3"></audio>
<div>
<buttononclick = "document.getElementById('player').play()">Play</button>
<buttononclick = "document.getElementById('player').pause()">Pause</button>
<buttononclick = "document.getElementById('player').volume += 0.2">Vol+</button>
<buttononclick = "document.getElementById('player').volume -= 0.2">Vol-</button>
</div>
You can also add CSS classes to each one of the elements and style them accordingly. | [
{
"code": null,
"e": 1237,
"s": 1062,
"text": "HTML 5 audio tags can be styled. By using the audio tag with “controls” attribute, the default browsers player is used. You can customize by not using the browsers controls. "
},
{
"code": null,
"e": 1326,
"s": 1237,
"text": "By removing the controls attribute, you can hide the built in browser user’s interface −"
},
{
"code": null,
"e": 1712,
"s": 1326,
"text": "<audioid = \"player\" src = \"kalimba.mp3\"></audio>\n<div>\n <buttononclick = \"document.getElementById('player').play()\">Play</button>\n <buttononclick = \"document.getElementById('player').pause()\">Pause</button>\n <buttononclick = \"document.getElementById('player').volume += 0.2\">Vol+</button>\n <buttononclick = \"document.getElementById('player').volume -= 0.2\">Vol-</button>\n</div>"
},
{
"code": null,
"e": 1797,
"s": 1712,
"text": "You can also add CSS classes to each one of the elements and style them accordingly."
}
] |
Beat Cache Invalidation in ASP.NET Core Using Kafka and Debezium | by Seyed Morteza Mousavi | Towards Data Science | When building web applications, we use cache most of the time to store the result of an (expensive) database query. After some time, because our underlying database state is changed, we want to remove or replace cache entries. A process that is called cache invalidation. The problem is when do we have to remove or replace a cache entry? The answer is whenever your underlying database record is changed. But data might be changed by a process that is not in our control.
If we can subscribe to any change events (insert, update and delete) that occurs to database records then we can successfully invalidate the relevant cache entry in real time. The good news is that most databases publish their insert, update and remove events. This feature is called change data capture (CDC).
In this article, I want to show you how we can use CDC to subscribe in any event that changes MySQL database records and publish each of these events as a separate message to Apache Kafka. Debezium is a platform that makes this possible for us. Then we use these events to build our in-memory cache in ASP.NET Core. We will see how we can build our REST API based on our real-time cache.
This is similar to how replication works in databases. In replication secondary replica subscribes to any transaction (change events) on primary and apply that transaction to its own database records and in this way secondary database state will be eventually equal to the primary. As shown in the image, we subscribe Kafka cluster as a replica to the database and process change events to build our cache:
Not only this approach solves cache invalidation, but it also solves other problems such as race condition and cache warm start as Martin Kleppmann described in his Turning the database inside-out article.
The source code of this article is available in GitHub.
.NET Core 2.2
docker and docker-compose
We will set up our Apache Kafka cluster, MySQL database and Debezium connector (which we will discuss it shortly) using Docker. First, create a docker-compose.yml file with the following content:
version: '3.1'services:mysql: image: mysql:5.7 environment: MYSQL_ROOT_PASSWORD: 123456 MYSQL_USER: mysql volumes: - ./my.cnf:/etc/mysql/my.cnf ports: - 3306:3306zookeeper: image: confluentinc/cp-zookeeper ports: - "2181:2181" environment: ZOOKEEPER_CLIENT_PORT: 2181kafka: image: confluentinc/cp-kafka depends_on: - zookeeper - mysql ports: - "9092:9092" environment: KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181 KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka:9092 KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1 KAFKA_LOG_CLEANER_DELETE_RETENTION_MS: 5000 KAFKA_BROKER_ID: 1 KAFKA_MIN_INSYNC_REPLICAS: 1connector: image: debezium/connect:0.10 ports: - "8083:8083" environment: GROUP_ID: 1 CONFIG_STORAGE_TOPIC: my_connect_configs OFFSET_STORAGE_TOPIC: my_connect_offsets BOOTSTRAP_SERVERS: kafka:9092 depends_on: - zookeeper - mysql - kafka
my.cnf file enables CDC feature of MySQL. Now start all docker services:
docker-compose up
Open another terminal in the same path, connect to MySQL container and run MySQL CLI:
docker-compose exec mysql bash -c 'mysql -u root -p$MYSQL_ROOT_PASSWORD'
Now we want to create a database in MySQL. Run the following script to create a database named mystore, a table named products and insert a simple record to the products table:
create database mystore;use mystore;create table products (id int unsigned auto_increment primary key, name varchar(50), price int, creation_time datetime default current_timestamp, modification_time datetime on update current_timestamp);insert into products(name, price) values("Red T-Shirt", 12);
Now we want to move every change that happens to products table to Kafka. To this end, we must create a connector. A connector is an application that is responsible for moving data from a database (or any other storage system) to Kafka cluster (and vice versa). If you are not familiar with Kafka connector you can read Confluent documents. Here we want to move MySQL change events to Apache Kafka cluster. Debezium is a Kafka Connector that can read all change events from MySQL (and some other databases) and publish them to Kafka:
Debezium exposes a REST API to create a connector. So to create a Debezium connector open another terminal and run the following script (Most of the configuration is self-explanatory but for more information read Debezium MySQL tutorial):
curl -i -X POST -H "Accept:application/json" -H "Content-Type:application/json" localhost:8083/connectors/ -d '{ "name": "mystore-connector", "config": { "connector.class": "io.debezium.connector.mysql.MySqlConnector", "tasks.max": "1", "database.hostname": "mysql", "database.port": "3306", "database.user": "root", "database.password": "123456", "database.server.id": "223345", "database.server.name": "mysql", "database.whitelist": "mystore", "database.history.kafka.bootstrap.servers": "kafka:9092", "database.history.kafka.topic": "dbhistory.mystore","transforms":"unwrap","transforms.unwrap.type":"io.debezium.transforms.UnwrapFromEnvelope","transforms.unwrap.drop.tombstones":"false","key.converter": "org.apache.kafka.connect.json.JsonConverter","key.converter.schemas.enable": "false","value.converter": "org.apache.kafka.connect.json.JsonConverter","value.converter.schemas.enable": "false","include.schema.changes": "false"} }'
If you receive HTTP/1.1 201 Created, your connector has been created successfully. You can also check the status of the connector:
curl localhost:8083/connectors/mystore-connector/status{ "name": "mystore-connector", "connector": { "state": "RUNNING", "worker_id": "172.24.0.5:8083" }, "tasks": [ { "id": 0, "state": "RUNNING", "worker_id": "172.24.0.5:8083" } ], "type": "source"}
Running value in the state field indicates that your connector is working. Now let's check that any database changes will be synced to Kafka. First, connect to Kafka container:
docker-compose exec kafka bash
And view the list of topics:
kafka-topics --zookeeper zookeeper:2181 --list__confluent.support.metrics__consumer_offsetsconnect-statusdbhistory.mystoremy_connect_configsmy_connect_offsetsmysqlmysql.mystore.products
mysql.mystore.products topic stores change events of products table. We can read messages inside this topic using the following script(message keys are separated by -):
kafka-console-consumer --bootstrap-server kafka:9092 --from-beginning --topic mysql.mystore.products --property print.key=true --property key.separator="-"{"id":1}-{"id":1,"name":"Red T-Shirt","price":12,"creation_time":1553595845000,"modification_time":null}
To check that the changes will be synced in (near) real time, in MySQL container, add another record:
insert into products(name, price) values("Blue Hat", 5);
The change will be shown immediately in the consumer terminal:
{"id":1}-{"id":1,"name":"Red T-Shirt","price":12,"creation_time":1553595845000,"modification_time":null}{"id":2}-{"id":2,"name":"Blue Hat","price":5,"creation_time":1553595958000,"modification_time":null}
Update “Blue Hat” record:
update products set price = 17 where name = "Blue Hat";
An update event is published:
{"id":1}-{"id":1,"name":"Red T-Shirt","price":12,"creation_time":1553595845000,"modification_time":null}{"id":2}-{"id":2,"name":"Blue Hat","price":5,"creation_time":1553595958000,"modification_time":null}{"id":2}-{"id":2,"name":"Blue Hat","price":17,"creation_time":1553595958000,"modification_time":1553595986000}
Delete record with the id of 1:
delete from products where id = 1;
A message with a null value will be added to the topic:
{"id":1}-{"id":1,"name":"Red T-Shirt","price":12,"creation_time":1553595845000,"modification_time":null}{"id":2}-{"id":2,"name":"Blue Hat","price":5,"creation_time":1553595958000,"modification_time":null}{"id":2}-{"id":2,"name":"Blue Hat","price":17,"creation_time":1553595958000,"modification_time":1553595986000}{"id":1}-null
a null value indicates that the record is deleted. Let's add a column named description:
alter table products add column description nvarchar(1000);
And update a product record:
update products set description = "Can be used for the spring!" where id = 2;
And you will see that even schema changes will be reflected in the message:
{"id":1}-{"id":1,"name":"Red T-Shirt","price":12,"creation_time":1553595845000,"modification_time":null}{"id":2}-{"id":2,"name":"Blue Hat","price":5,"creation_time":1553595958000,"modification_time":null}{"id":2}-{"id":2,"name":"Blue Hat","price":17,"creation_time":1553595958000,"modification_time":1553595986000}{"id":1}-null{"id":2}-{"id":2,"name":"Blue Hat","price":17,"creation_time":1553595958000,"modification_time":1553596044000,"description":"Can be used for the spring!"}
Note that some RDBMSs like SQL Server does not automatically reflect schema changes in CDC data. But MySQL CDC supports schema changes.
mysql.mystore.products topic holds every change for products table. To build our cache, we want to keep the latest value for each record. To this end, we can keep the latest value for each product id in a separate topic named products.cache. We also create a project called cache builder that will read every message in mysql.mystore.products topic and produce them to products.cache topic. products.cache topic is a compacted topic which means, for each key (in this case product id) will hold only one message. You can read more about the compacted topic in Cloudurable and my recent article.
Create a compacted topic in Kafka by running following script inside Kafka container:
kafka-topics --create --zookeeper zookeeper:2181 --topic products.cache --replication-factor 1 --partitions 1 --config "cleanup.policy=compact" --config "delete.retention.ms=100" --config "segment.ms=100" --config "min.cleanable.dirty.ratio=0.01"
In order to connect to Kafka broker from our application we also need to add kafka hostname to the hosts file (just add the bold line):
sudo vi /etc/hosts127.0.0.1 localhost# ...127.0.0.1 kafka
Create a solution and CacheBuilder project (You can see the complete code in GitHub):
mkdir srccd src/dotnet new sln --name KafkaCachedotnet new console -o KafkaCache.CacheBuilderdotnet sln add KafkaCache.CacheBuilder/KafkaCache.CacheBuilder.csproj
And install Confluent.Kafka and Newtonsoft.Json NuGet packages:
dotnet add KafkaCache.CacheBuilder/KafkaCache.CacheBuilder.csproj package Confluent.Kafka --version 1.0.0-RC1dotnet add KafkaCache.CacheBuilder/KafkaCache.CacheBuilder.csproj package Newtonsoft.Json --version 12.0.1
Here you can see Program.cs code:
And here is ProductKey class:
In Program.cs we just read messages from mysql.mystore.products topic, extract product id field and create another message and publish it to products.cache topic. Now run CacheBuilder project (in a separate terminal):
dotnet run --project KafkaCache.CacheBuilder/KafkaCache.CacheBuilder.csproj
You can view this topic inside Kafka container:
kafka-console-consumer --bootstrap-server kafka:9092 --from-beginning --topic products.cache
We create a Web API project that will expose simple REST API to get the details of a product (retrieved from the cache). Also, this project is responsible for consuming cache entry from products.cache topic and store them in the in-memory cache. Run the following script to create the project:
dotnet new webapi -o KafkaCache.Apidotnet sln add KafkaCache.Api/KafkaCache.Api.csproj
And install Confluent.Kafka and Newtonsoft.Json packages:
dotnet add KafkaCache.CacheBuilder/KafkaCache.CacheBuilder.csproj package Confluent.Kafka --version 1.0.0-RC1dotnet add KafkaCache.CacheBuilder/KafkaCache.CacheBuilder.csproj package Newtonsoft.Json --version 12.0.1
Enable in-memory cache in Startup class:
services.AddMemoryCache();
This allows us to use IMemoryCache which is used for storing and retrieving cache entry from memory in ASP.NET Core. To fill this cache we need a CacheUpdater class responsible for consuming message from products.cache topic and update our memory cache:
And ProductItemCache class:
Notice that we have a Run method that is responsible for updating the cache. The method receives a returnOnLastOffset parameter that is used to return on the last message on the topic. If it has true value and we are at the end of the topic/partition, we return from the method. This is useful during startup when we want to warm our cache before proceeding to serve any REST API request. We now use CacheUpdater in application initialization:
As you see above, we call CacheUpdater.Run method two times. At first, for warming cache and secondly for running a background job to continuously read products.cache topic and update in-memory cache.
Finally here is our controller that directly serve requests from the cache:
Now run the API project:
dotnet run --project KafkaCache.Api/KafkaCache.Api.csproj
And check your API:
curl -k https://localhost:5001/api/products/2{"id":2,"name":"Blue Hat","price":17}
Let's change the price of the product with id 2 inside MySQL container:
update products set price = 56 where id = 2;
And again request to your API:
curl -k https://localhost:5001/api/products/2{"id":2,"name":"Blue Hat","price":56}
As you see any changes are reflected immediately to our cache!
Using CDC we can reflect our database changes near real-time into Kafka. Then we could create an In-Memory cache by consuming Kafka messages. Now I would like to point out some of the advantages and disadvantages of this approach.
Advantages:
Mitigate 3 problems in implementing a cache: cache invalidation, race condition, and warm start performance.
Syncing database changes to cache in real time.
Faster cache warms up due to sequential IO (in reading messages from Kafka topic).
Disadvantages:
More complexity: you need to implement cache builder, use Debezium Connector, Enable CDC for database and read events from Kafka cluster.
Need to monitor Kafka, connector and cache builder.
Needs more knowledge: New developer must learn more frameworks. | [
{
"code": null,
"e": 645,
"s": 172,
"text": "When building web applications, we use cache most of the time to store the result of an (expensive) database query. After some time, because our underlying database state is changed, we want to remove or replace cache entries. A process that is called cache invalidation. The problem is when do we have to remove or replace a cache entry? The answer is whenever your underlying database record is changed. But data might be changed by a process that is not in our control."
},
{
"code": null,
"e": 956,
"s": 645,
"text": "If we can subscribe to any change events (insert, update and delete) that occurs to database records then we can successfully invalidate the relevant cache entry in real time. The good news is that most databases publish their insert, update and remove events. This feature is called change data capture (CDC)."
},
{
"code": null,
"e": 1344,
"s": 956,
"text": "In this article, I want to show you how we can use CDC to subscribe in any event that changes MySQL database records and publish each of these events as a separate message to Apache Kafka. Debezium is a platform that makes this possible for us. Then we use these events to build our in-memory cache in ASP.NET Core. We will see how we can build our REST API based on our real-time cache."
},
{
"code": null,
"e": 1751,
"s": 1344,
"text": "This is similar to how replication works in databases. In replication secondary replica subscribes to any transaction (change events) on primary and apply that transaction to its own database records and in this way secondary database state will be eventually equal to the primary. As shown in the image, we subscribe Kafka cluster as a replica to the database and process change events to build our cache:"
},
{
"code": null,
"e": 1957,
"s": 1751,
"text": "Not only this approach solves cache invalidation, but it also solves other problems such as race condition and cache warm start as Martin Kleppmann described in his Turning the database inside-out article."
},
{
"code": null,
"e": 2013,
"s": 1957,
"text": "The source code of this article is available in GitHub."
},
{
"code": null,
"e": 2027,
"s": 2013,
"text": ".NET Core 2.2"
},
{
"code": null,
"e": 2053,
"s": 2027,
"text": "docker and docker-compose"
},
{
"code": null,
"e": 2249,
"s": 2053,
"text": "We will set up our Apache Kafka cluster, MySQL database and Debezium connector (which we will discuss it shortly) using Docker. First, create a docker-compose.yml file with the following content:"
},
{
"code": null,
"e": 3240,
"s": 2249,
"text": "version: '3.1'services:mysql: image: mysql:5.7 environment: MYSQL_ROOT_PASSWORD: 123456 MYSQL_USER: mysql volumes: - ./my.cnf:/etc/mysql/my.cnf ports: - 3306:3306zookeeper: image: confluentinc/cp-zookeeper ports: - \"2181:2181\" environment: ZOOKEEPER_CLIENT_PORT: 2181kafka: image: confluentinc/cp-kafka depends_on: - zookeeper - mysql ports: - \"9092:9092\" environment: KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181 KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka:9092 KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1 KAFKA_LOG_CLEANER_DELETE_RETENTION_MS: 5000 KAFKA_BROKER_ID: 1 KAFKA_MIN_INSYNC_REPLICAS: 1connector: image: debezium/connect:0.10 ports: - \"8083:8083\" environment: GROUP_ID: 1 CONFIG_STORAGE_TOPIC: my_connect_configs OFFSET_STORAGE_TOPIC: my_connect_offsets BOOTSTRAP_SERVERS: kafka:9092 depends_on: - zookeeper - mysql - kafka"
},
{
"code": null,
"e": 3313,
"s": 3240,
"text": "my.cnf file enables CDC feature of MySQL. Now start all docker services:"
},
{
"code": null,
"e": 3331,
"s": 3313,
"text": "docker-compose up"
},
{
"code": null,
"e": 3417,
"s": 3331,
"text": "Open another terminal in the same path, connect to MySQL container and run MySQL CLI:"
},
{
"code": null,
"e": 3490,
"s": 3417,
"text": "docker-compose exec mysql bash -c 'mysql -u root -p$MYSQL_ROOT_PASSWORD'"
},
{
"code": null,
"e": 3667,
"s": 3490,
"text": "Now we want to create a database in MySQL. Run the following script to create a database named mystore, a table named products and insert a simple record to the products table:"
},
{
"code": null,
"e": 3966,
"s": 3667,
"text": "create database mystore;use mystore;create table products (id int unsigned auto_increment primary key, name varchar(50), price int, creation_time datetime default current_timestamp, modification_time datetime on update current_timestamp);insert into products(name, price) values(\"Red T-Shirt\", 12);"
},
{
"code": null,
"e": 4500,
"s": 3966,
"text": "Now we want to move every change that happens to products table to Kafka. To this end, we must create a connector. A connector is an application that is responsible for moving data from a database (or any other storage system) to Kafka cluster (and vice versa). If you are not familiar with Kafka connector you can read Confluent documents. Here we want to move MySQL change events to Apache Kafka cluster. Debezium is a Kafka Connector that can read all change events from MySQL (and some other databases) and publish them to Kafka:"
},
{
"code": null,
"e": 4739,
"s": 4500,
"text": "Debezium exposes a REST API to create a connector. So to create a Debezium connector open another terminal and run the following script (Most of the configuration is self-explanatory but for more information read Debezium MySQL tutorial):"
},
{
"code": null,
"e": 5678,
"s": 4739,
"text": "curl -i -X POST -H \"Accept:application/json\" -H \"Content-Type:application/json\" localhost:8083/connectors/ -d '{ \"name\": \"mystore-connector\", \"config\": { \"connector.class\": \"io.debezium.connector.mysql.MySqlConnector\", \"tasks.max\": \"1\", \"database.hostname\": \"mysql\", \"database.port\": \"3306\", \"database.user\": \"root\", \"database.password\": \"123456\", \"database.server.id\": \"223345\", \"database.server.name\": \"mysql\", \"database.whitelist\": \"mystore\", \"database.history.kafka.bootstrap.servers\": \"kafka:9092\", \"database.history.kafka.topic\": \"dbhistory.mystore\",\"transforms\":\"unwrap\",\"transforms.unwrap.type\":\"io.debezium.transforms.UnwrapFromEnvelope\",\"transforms.unwrap.drop.tombstones\":\"false\",\"key.converter\": \"org.apache.kafka.connect.json.JsonConverter\",\"key.converter.schemas.enable\": \"false\",\"value.converter\": \"org.apache.kafka.connect.json.JsonConverter\",\"value.converter.schemas.enable\": \"false\",\"include.schema.changes\": \"false\"} }'"
},
{
"code": null,
"e": 5809,
"s": 5678,
"text": "If you receive HTTP/1.1 201 Created, your connector has been created successfully. You can also check the status of the connector:"
},
{
"code": null,
"e": 6093,
"s": 5809,
"text": "curl localhost:8083/connectors/mystore-connector/status{ \"name\": \"mystore-connector\", \"connector\": { \"state\": \"RUNNING\", \"worker_id\": \"172.24.0.5:8083\" }, \"tasks\": [ { \"id\": 0, \"state\": \"RUNNING\", \"worker_id\": \"172.24.0.5:8083\" } ], \"type\": \"source\"}"
},
{
"code": null,
"e": 6270,
"s": 6093,
"text": "Running value in the state field indicates that your connector is working. Now let's check that any database changes will be synced to Kafka. First, connect to Kafka container:"
},
{
"code": null,
"e": 6301,
"s": 6270,
"text": "docker-compose exec kafka bash"
},
{
"code": null,
"e": 6330,
"s": 6301,
"text": "And view the list of topics:"
},
{
"code": null,
"e": 6516,
"s": 6330,
"text": "kafka-topics --zookeeper zookeeper:2181 --list__confluent.support.metrics__consumer_offsetsconnect-statusdbhistory.mystoremy_connect_configsmy_connect_offsetsmysqlmysql.mystore.products"
},
{
"code": null,
"e": 6685,
"s": 6516,
"text": "mysql.mystore.products topic stores change events of products table. We can read messages inside this topic using the following script(message keys are separated by -):"
},
{
"code": null,
"e": 6945,
"s": 6685,
"text": "kafka-console-consumer --bootstrap-server kafka:9092 --from-beginning --topic mysql.mystore.products --property print.key=true --property key.separator=\"-\"{\"id\":1}-{\"id\":1,\"name\":\"Red T-Shirt\",\"price\":12,\"creation_time\":1553595845000,\"modification_time\":null}"
},
{
"code": null,
"e": 7047,
"s": 6945,
"text": "To check that the changes will be synced in (near) real time, in MySQL container, add another record:"
},
{
"code": null,
"e": 7104,
"s": 7047,
"text": "insert into products(name, price) values(\"Blue Hat\", 5);"
},
{
"code": null,
"e": 7167,
"s": 7104,
"text": "The change will be shown immediately in the consumer terminal:"
},
{
"code": null,
"e": 7372,
"s": 7167,
"text": "{\"id\":1}-{\"id\":1,\"name\":\"Red T-Shirt\",\"price\":12,\"creation_time\":1553595845000,\"modification_time\":null}{\"id\":2}-{\"id\":2,\"name\":\"Blue Hat\",\"price\":5,\"creation_time\":1553595958000,\"modification_time\":null}"
},
{
"code": null,
"e": 7398,
"s": 7372,
"text": "Update “Blue Hat” record:"
},
{
"code": null,
"e": 7454,
"s": 7398,
"text": "update products set price = 17 where name = \"Blue Hat\";"
},
{
"code": null,
"e": 7484,
"s": 7454,
"text": "An update event is published:"
},
{
"code": null,
"e": 7799,
"s": 7484,
"text": "{\"id\":1}-{\"id\":1,\"name\":\"Red T-Shirt\",\"price\":12,\"creation_time\":1553595845000,\"modification_time\":null}{\"id\":2}-{\"id\":2,\"name\":\"Blue Hat\",\"price\":5,\"creation_time\":1553595958000,\"modification_time\":null}{\"id\":2}-{\"id\":2,\"name\":\"Blue Hat\",\"price\":17,\"creation_time\":1553595958000,\"modification_time\":1553595986000}"
},
{
"code": null,
"e": 7831,
"s": 7799,
"text": "Delete record with the id of 1:"
},
{
"code": null,
"e": 7866,
"s": 7831,
"text": "delete from products where id = 1;"
},
{
"code": null,
"e": 7922,
"s": 7866,
"text": "A message with a null value will be added to the topic:"
},
{
"code": null,
"e": 8250,
"s": 7922,
"text": "{\"id\":1}-{\"id\":1,\"name\":\"Red T-Shirt\",\"price\":12,\"creation_time\":1553595845000,\"modification_time\":null}{\"id\":2}-{\"id\":2,\"name\":\"Blue Hat\",\"price\":5,\"creation_time\":1553595958000,\"modification_time\":null}{\"id\":2}-{\"id\":2,\"name\":\"Blue Hat\",\"price\":17,\"creation_time\":1553595958000,\"modification_time\":1553595986000}{\"id\":1}-null"
},
{
"code": null,
"e": 8339,
"s": 8250,
"text": "a null value indicates that the record is deleted. Let's add a column named description:"
},
{
"code": null,
"e": 8399,
"s": 8339,
"text": "alter table products add column description nvarchar(1000);"
},
{
"code": null,
"e": 8428,
"s": 8399,
"text": "And update a product record:"
},
{
"code": null,
"e": 8506,
"s": 8428,
"text": "update products set description = \"Can be used for the spring!\" where id = 2;"
},
{
"code": null,
"e": 8582,
"s": 8506,
"text": "And you will see that even schema changes will be reflected in the message:"
},
{
"code": null,
"e": 9064,
"s": 8582,
"text": "{\"id\":1}-{\"id\":1,\"name\":\"Red T-Shirt\",\"price\":12,\"creation_time\":1553595845000,\"modification_time\":null}{\"id\":2}-{\"id\":2,\"name\":\"Blue Hat\",\"price\":5,\"creation_time\":1553595958000,\"modification_time\":null}{\"id\":2}-{\"id\":2,\"name\":\"Blue Hat\",\"price\":17,\"creation_time\":1553595958000,\"modification_time\":1553595986000}{\"id\":1}-null{\"id\":2}-{\"id\":2,\"name\":\"Blue Hat\",\"price\":17,\"creation_time\":1553595958000,\"modification_time\":1553596044000,\"description\":\"Can be used for the spring!\"}"
},
{
"code": null,
"e": 9200,
"s": 9064,
"text": "Note that some RDBMSs like SQL Server does not automatically reflect schema changes in CDC data. But MySQL CDC supports schema changes."
},
{
"code": null,
"e": 9795,
"s": 9200,
"text": "mysql.mystore.products topic holds every change for products table. To build our cache, we want to keep the latest value for each record. To this end, we can keep the latest value for each product id in a separate topic named products.cache. We also create a project called cache builder that will read every message in mysql.mystore.products topic and produce them to products.cache topic. products.cache topic is a compacted topic which means, for each key (in this case product id) will hold only one message. You can read more about the compacted topic in Cloudurable and my recent article."
},
{
"code": null,
"e": 9881,
"s": 9795,
"text": "Create a compacted topic in Kafka by running following script inside Kafka container:"
},
{
"code": null,
"e": 10129,
"s": 9881,
"text": "kafka-topics --create --zookeeper zookeeper:2181 --topic products.cache --replication-factor 1 --partitions 1 --config \"cleanup.policy=compact\" --config \"delete.retention.ms=100\" --config \"segment.ms=100\" --config \"min.cleanable.dirty.ratio=0.01\""
},
{
"code": null,
"e": 10265,
"s": 10129,
"text": "In order to connect to Kafka broker from our application we also need to add kafka hostname to the hosts file (just add the bold line):"
},
{
"code": null,
"e": 10323,
"s": 10265,
"text": "sudo vi /etc/hosts127.0.0.1 localhost# ...127.0.0.1 kafka"
},
{
"code": null,
"e": 10409,
"s": 10323,
"text": "Create a solution and CacheBuilder project (You can see the complete code in GitHub):"
},
{
"code": null,
"e": 10572,
"s": 10409,
"text": "mkdir srccd src/dotnet new sln --name KafkaCachedotnet new console -o KafkaCache.CacheBuilderdotnet sln add KafkaCache.CacheBuilder/KafkaCache.CacheBuilder.csproj"
},
{
"code": null,
"e": 10636,
"s": 10572,
"text": "And install Confluent.Kafka and Newtonsoft.Json NuGet packages:"
},
{
"code": null,
"e": 10853,
"s": 10636,
"text": "dotnet add KafkaCache.CacheBuilder/KafkaCache.CacheBuilder.csproj package Confluent.Kafka --version 1.0.0-RC1dotnet add KafkaCache.CacheBuilder/KafkaCache.CacheBuilder.csproj package Newtonsoft.Json --version 12.0.1"
},
{
"code": null,
"e": 10887,
"s": 10853,
"text": "Here you can see Program.cs code:"
},
{
"code": null,
"e": 10917,
"s": 10887,
"text": "And here is ProductKey class:"
},
{
"code": null,
"e": 11135,
"s": 10917,
"text": "In Program.cs we just read messages from mysql.mystore.products topic, extract product id field and create another message and publish it to products.cache topic. Now run CacheBuilder project (in a separate terminal):"
},
{
"code": null,
"e": 11211,
"s": 11135,
"text": "dotnet run --project KafkaCache.CacheBuilder/KafkaCache.CacheBuilder.csproj"
},
{
"code": null,
"e": 11259,
"s": 11211,
"text": "You can view this topic inside Kafka container:"
},
{
"code": null,
"e": 11352,
"s": 11259,
"text": "kafka-console-consumer --bootstrap-server kafka:9092 --from-beginning --topic products.cache"
},
{
"code": null,
"e": 11646,
"s": 11352,
"text": "We create a Web API project that will expose simple REST API to get the details of a product (retrieved from the cache). Also, this project is responsible for consuming cache entry from products.cache topic and store them in the in-memory cache. Run the following script to create the project:"
},
{
"code": null,
"e": 11733,
"s": 11646,
"text": "dotnet new webapi -o KafkaCache.Apidotnet sln add KafkaCache.Api/KafkaCache.Api.csproj"
},
{
"code": null,
"e": 11791,
"s": 11733,
"text": "And install Confluent.Kafka and Newtonsoft.Json packages:"
},
{
"code": null,
"e": 12008,
"s": 11791,
"text": "dotnet add KafkaCache.CacheBuilder/KafkaCache.CacheBuilder.csproj package Confluent.Kafka --version 1.0.0-RC1dotnet add KafkaCache.CacheBuilder/KafkaCache.CacheBuilder.csproj package Newtonsoft.Json --version 12.0.1"
},
{
"code": null,
"e": 12049,
"s": 12008,
"text": "Enable in-memory cache in Startup class:"
},
{
"code": null,
"e": 12076,
"s": 12049,
"text": "services.AddMemoryCache();"
},
{
"code": null,
"e": 12330,
"s": 12076,
"text": "This allows us to use IMemoryCache which is used for storing and retrieving cache entry from memory in ASP.NET Core. To fill this cache we need a CacheUpdater class responsible for consuming message from products.cache topic and update our memory cache:"
},
{
"code": null,
"e": 12358,
"s": 12330,
"text": "And ProductItemCache class:"
},
{
"code": null,
"e": 12802,
"s": 12358,
"text": "Notice that we have a Run method that is responsible for updating the cache. The method receives a returnOnLastOffset parameter that is used to return on the last message on the topic. If it has true value and we are at the end of the topic/partition, we return from the method. This is useful during startup when we want to warm our cache before proceeding to serve any REST API request. We now use CacheUpdater in application initialization:"
},
{
"code": null,
"e": 13003,
"s": 12802,
"text": "As you see above, we call CacheUpdater.Run method two times. At first, for warming cache and secondly for running a background job to continuously read products.cache topic and update in-memory cache."
},
{
"code": null,
"e": 13079,
"s": 13003,
"text": "Finally here is our controller that directly serve requests from the cache:"
},
{
"code": null,
"e": 13104,
"s": 13079,
"text": "Now run the API project:"
},
{
"code": null,
"e": 13162,
"s": 13104,
"text": "dotnet run --project KafkaCache.Api/KafkaCache.Api.csproj"
},
{
"code": null,
"e": 13182,
"s": 13162,
"text": "And check your API:"
},
{
"code": null,
"e": 13265,
"s": 13182,
"text": "curl -k https://localhost:5001/api/products/2{\"id\":2,\"name\":\"Blue Hat\",\"price\":17}"
},
{
"code": null,
"e": 13337,
"s": 13265,
"text": "Let's change the price of the product with id 2 inside MySQL container:"
},
{
"code": null,
"e": 13382,
"s": 13337,
"text": "update products set price = 56 where id = 2;"
},
{
"code": null,
"e": 13413,
"s": 13382,
"text": "And again request to your API:"
},
{
"code": null,
"e": 13496,
"s": 13413,
"text": "curl -k https://localhost:5001/api/products/2{\"id\":2,\"name\":\"Blue Hat\",\"price\":56}"
},
{
"code": null,
"e": 13559,
"s": 13496,
"text": "As you see any changes are reflected immediately to our cache!"
},
{
"code": null,
"e": 13790,
"s": 13559,
"text": "Using CDC we can reflect our database changes near real-time into Kafka. Then we could create an In-Memory cache by consuming Kafka messages. Now I would like to point out some of the advantages and disadvantages of this approach."
},
{
"code": null,
"e": 13802,
"s": 13790,
"text": "Advantages:"
},
{
"code": null,
"e": 13911,
"s": 13802,
"text": "Mitigate 3 problems in implementing a cache: cache invalidation, race condition, and warm start performance."
},
{
"code": null,
"e": 13959,
"s": 13911,
"text": "Syncing database changes to cache in real time."
},
{
"code": null,
"e": 14042,
"s": 13959,
"text": "Faster cache warms up due to sequential IO (in reading messages from Kafka topic)."
},
{
"code": null,
"e": 14057,
"s": 14042,
"text": "Disadvantages:"
},
{
"code": null,
"e": 14195,
"s": 14057,
"text": "More complexity: you need to implement cache builder, use Debezium Connector, Enable CDC for database and read events from Kafka cluster."
},
{
"code": null,
"e": 14247,
"s": 14195,
"text": "Need to monitor Kafka, connector and cache builder."
}
] |
Count by multiple fields with MongoDB aggregation | To count by multiple fields, use $facet in MongoDB. The $facet processes multiple aggregation pipelines within a single stage on the same set of input documents. Let us create a collection with documents −
> db.demo721.insertOne(
... {
...
... "details1": {
... "id":101
...
... },
... "details2": {
... "id":101
... },
... "details3": {
... "id":101
... }
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5eaaebdd43417811278f5887")
}
>
>
> db.demo721.insertOne(
... {
...
... "details1": {
... "id":101
...
... },
... "details2": {
... "id":102
... },
... "details3": {
... "id":102
... }
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5eaaebe943417811278f5888")
}
Display all documents from a collection with the help of find() method −
> db.demo721.find();
This will produce the following output −
{ "_id" : ObjectId("5eaaebdd43417811278f5887"), "details1" : { "id" : 101 }, "details2" : { "id" : 101 }, "details3" : { "id" : 101 } }
{ "_id" : ObjectId("5eaaebe943417811278f5888"), "details1" : { "id" : 101 }, "details2" : { "id" : 102 }, "details3" : { "id" : 102 } }
Following is the query to count by multiple fields −
> db.demo721.aggregate([
... {$facet:{
... ids:[
... {$group:{ _id:null,
... d3:{$addToSet: "$details3.id"},
... d2:{$addToSet:"$details2.id"},
... d1:{$addToSet:"$details1.id"}}},
... {$project:{ _id:0,
... listofall:{$setUnion:["$d1","$d2","$d3"]}}}],
... d:[{$project:{ _id:0,
... a1:"$details1.id",
... a2:"$details2.id",
... a3:"$details3.id"}}]}},
... {$unwind:"$d"},
... {$unwind:"$ids"},
... {$unwind:"$ids.listofall"},
... {$group:{ _id:"$ids.listofall",
... details1id:{$sum:{$cond:[{$eq:["$d.a1","$ids.listofall"]},1,0]}},
... details2id:{$sum:{$cond:[{$eq:["$d.a2","$ids.listofall"]},1,0]}},
... details3id:{$sum:{$cond:[{$eq:["$d.a3","$ids.listofall"]},1,0]}}}}])
This will produce the following output −
{ "_id" : 102, "details1id" : 0, "details2id" : 1, "details3id" : 1 }
{ "_id" : 101, "details1id" : 2, "details2id" : 1, "details3id" : 1 } | [
{
"code": null,
"e": 1268,
"s": 1062,
"text": "To count by multiple fields, use $facet in MongoDB. The $facet processes multiple aggregation pipelines within a single stage on the same set of input documents. Let us create a collection with documents −"
},
{
"code": null,
"e": 1908,
"s": 1268,
"text": "> db.demo721.insertOne(\n... {\n...\n... \"details1\": {\n... \"id\":101\n...\n... },\n... \"details2\": {\n... \"id\":101\n... },\n... \"details3\": {\n... \"id\":101\n... }\n... }\n... );\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5eaaebdd43417811278f5887\")\n}\n>\n>\n> db.demo721.insertOne(\n... {\n...\n... \"details1\": {\n... \"id\":101\n...\n... },\n... \"details2\": {\n... \"id\":102\n... },\n... \"details3\": {\n... \"id\":102\n... }\n... }\n... );\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5eaaebe943417811278f5888\")\n}"
},
{
"code": null,
"e": 1981,
"s": 1908,
"text": "Display all documents from a collection with the help of find() method −"
},
{
"code": null,
"e": 2002,
"s": 1981,
"text": "> db.demo721.find();"
},
{
"code": null,
"e": 2043,
"s": 2002,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2315,
"s": 2043,
"text": "{ \"_id\" : ObjectId(\"5eaaebdd43417811278f5887\"), \"details1\" : { \"id\" : 101 }, \"details2\" : { \"id\" : 101 }, \"details3\" : { \"id\" : 101 } }\n{ \"_id\" : ObjectId(\"5eaaebe943417811278f5888\"), \"details1\" : { \"id\" : 101 }, \"details2\" : { \"id\" : 102 }, \"details3\" : { \"id\" : 102 } }"
},
{
"code": null,
"e": 2368,
"s": 2315,
"text": "Following is the query to count by multiple fields −"
},
{
"code": null,
"e": 3162,
"s": 2368,
"text": "> db.demo721.aggregate([\n... {$facet:{\n... ids:[\n... {$group:{ _id:null,\n... d3:{$addToSet: \"$details3.id\"},\n... d2:{$addToSet:\"$details2.id\"},\n... d1:{$addToSet:\"$details1.id\"}}},\n... {$project:{ _id:0,\n... listofall:{$setUnion:[\"$d1\",\"$d2\",\"$d3\"]}}}],\n... d:[{$project:{ _id:0,\n... a1:\"$details1.id\",\n... a2:\"$details2.id\",\n... a3:\"$details3.id\"}}]}},\n... {$unwind:\"$d\"},\n... {$unwind:\"$ids\"},\n... {$unwind:\"$ids.listofall\"},\n... {$group:{ _id:\"$ids.listofall\",\n... details1id:{$sum:{$cond:[{$eq:[\"$d.a1\",\"$ids.listofall\"]},1,0]}},\n... details2id:{$sum:{$cond:[{$eq:[\"$d.a2\",\"$ids.listofall\"]},1,0]}},\n... details3id:{$sum:{$cond:[{$eq:[\"$d.a3\",\"$ids.listofall\"]},1,0]}}}}])"
},
{
"code": null,
"e": 3203,
"s": 3162,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 3343,
"s": 3203,
"text": "{ \"_id\" : 102, \"details1id\" : 0, \"details2id\" : 1, \"details3id\" : 1 }\n{ \"_id\" : 101, \"details1id\" : 2, \"details2id\" : 1, \"details3id\" : 1 }"
}
] |
Building a Generative Adversarial Network using Keras - GeeksforGeeks | 25 Jun, 2019
Prerequisites: Generative Adversarial Network
This article will demonstrate how to build a Generative Adversarial Network using the Keras library. The dataset which is used is the CIFAR10 Image dataset which is preloaded into Keras. You can read about the dataset here.
Step 1: Importing the required libraries
import numpy as npimport matplotlib.pyplot as pltimport kerasfrom keras.layers import Input, Dense, Reshape, Flatten, Dropoutfrom keras.layers import BatchNormalization, Activation, ZeroPadding2Dfrom keras.layers.advanced_activations import LeakyReLUfrom keras.layers.convolutional import UpSampling2D, Conv2Dfrom keras.models import Sequential, Modelfrom keras.optimizers import Adam,SGD
Step 2: Loading the data
#Loading the CIFAR10 data(X, y), (_, _) = keras.datasets.cifar10.load_data() #Selecting a single class images#The number was randomly chosen and any number#between 1 to 10 can be chosenX = X[y.flatten() == 8]
Step 3: Defining parameters to be used in later processes
#Defining the Input shapeimage_shape = (32, 32, 3) latent_dimensions = 100
Step 4: Defining a utility function to build the Generator
def build_generator(): model = Sequential() #Building the input layer model.add(Dense(128 * 8 * 8, activation="relu", input_dim=latent_dimensions)) model.add(Reshape((8, 8, 128))) model.add(UpSampling2D()) model.add(Conv2D(128, kernel_size=3, padding="same")) model.add(BatchNormalization(momentum=0.78)) model.add(Activation("relu")) model.add(UpSampling2D()) model.add(Conv2D(64, kernel_size=3, padding="same")) model.add(BatchNormalization(momentum=0.78)) model.add(Activation("relu")) model.add(Conv2D(3, kernel_size=3, padding="same")) model.add(Activation("tanh")) #Generating the output image noise = Input(shape=(latent_dimensions,)) image = model(noise) return Model(noise, image)
Step 5: Defining a utility function to build the Discriminator
def build_discriminator(): #Building the convolutional layers #to classify whether an image is real or fake model = Sequential() model.add(Conv2D(32, kernel_size=3, strides=2, input_shape=image_shape, padding="same")) model.add(LeakyReLU(alpha=0.2)) model.add(Dropout(0.25)) model.add(Conv2D(64, kernel_size=3, strides=2, padding="same")) model.add(ZeroPadding2D(padding=((0,1),(0,1)))) model.add(BatchNormalization(momentum=0.82)) model.add(LeakyReLU(alpha=0.25)) model.add(Dropout(0.25)) model.add(Conv2D(128, kernel_size=3, strides=2, padding="same")) model.add(BatchNormalization(momentum=0.82)) model.add(LeakyReLU(alpha=0.2)) model.add(Dropout(0.25)) model.add(Conv2D(256, kernel_size=3, strides=1, padding="same")) model.add(BatchNormalization(momentum=0.8)) model.add(LeakyReLU(alpha=0.25)) model.add(Dropout(0.25)) #Building the output layer model.add(Flatten()) model.add(Dense(1, activation='sigmoid')) image = Input(shape=image_shape) validity = model(image) return Model(image, validity)
Step 6: Defining a utility function to display the generated images
def display_images(): r, c = 4,4 noise = np.random.normal(0, 1, (r * c,latent_dimensions)) generated_images = generator.predict(noise) #Scaling the generated images generated_images = 0.5 * generated_images + 0.5 fig, axs = plt.subplots(r, c) count = 0 for i in range(r): for j in range(c): axs[i,j].imshow(generated_images[count, :,:,]) axs[i,j].axis('off') count += 1 plt.show() plt.close()
Step 7: Building the Generative Adversarial Network
# Building and compiling the discriminatordiscriminator = build_discriminator()discriminator.compile(loss='binary_crossentropy', optimizer=Adam(0.0002,0.5), metrics=['accuracy']) #Making the Discriminator untrainable#so that the generator can learn from fixed gradientdiscriminator.trainable = False # Building the generatorgenerator = build_generator() #Defining the input for the generator#and generating the imagesz = Input(shape=(latent_dimensions,))image = generator(z) #Checking the validity of the generated imagevalid = discriminator(image) #Defining the combined model of the Generator and the Discriminatorcombined_network = Model(z, valid)combined_network.compile(loss='binary_crossentropy', optimizer=Adam(0.0002,0.5))
Step 8: Training the network
num_epochs=15000batch_size=32display_interval=2500losses=[] #Normalizing the inputX = (X / 127.5) - 1. #Defining the Adversarial ground truthsvalid = np.ones((batch_size, 1)) #Adding some noise valid += 0.05 * np.random.random(valid.shape)fake = np.zeros((batch_size, 1))fake += 0.05 * np.random.random(fake.shape) for epoch in range(num_epochs): #Training the Discriminator #Sampling a random half of images index = np.random.randint(0, X.shape[0], batch_size) images = X[index] #Sampling noise and generating a batch of new images noise = np.random.normal(0, 1, (batch_size, latent_dimensions)) generated_images = generator.predict(noise) #Training the discriminator to detect more accurately #whether a generated image is real or fake discm_loss_real = discriminator.train_on_batch(images, valid) discm_loss_fake = discriminator.train_on_batch(generated_images, fake) discm_loss = 0.5 * np.add(discm_loss_real, discm_loss_fake) #Training the Generator #Training the generator to generate images #which pass the authenticity test genr_loss = combined_network.train_on_batch(noise, valid) #Tracking the progress if epoch % display_interval == 0: display_images()
Epoch 0:
Epoch 2500:
Epoch 5000:
Epoch 7500:
Epoch 10000:
Epoch 12500:
Note that the quality of images increases with each epoch.
Step 8: Evaluating the performance
The performance of the network will be evaluated by comparing the images generated on the last epoch to the original images visually.
a) Plotting the original images
#Plotting some of the original images s=X[:40]s = 0.5 * s + 0.5f, ax = plt.subplots(5,8, figsize=(16,10))for i, image in enumerate(s): ax[i//8, i%8].imshow(image) ax[i//8, i%8].axis('off') plt.show()
b) Plotting the images generated on the last epoch
#Plotting some of the last batch of generated imagesnoise = np.random.normal(size=(40, latent_dimensions))generated_images = generator.predict(noise)generated_images = 0.5 * generated_images + 0.5f, ax = plt.subplots(5,8, figsize=(16,10))for i, image in enumerate(generated_images): ax[i//8, i%8].imshow(image) ax[i//8, i%8].axis('off') plt.show()
On visually comparing the two sets of images, it can be concluded that the network is working at an acceptable level. The quality of images can be improved by training the network for more time or by tuning the parameters of the network.
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Decision Tree
Python | Decision tree implementation
Search Algorithms in AI
Decision Tree Introduction with example
Reinforcement learning
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe | [
{
"code": null,
"e": 24736,
"s": 24708,
"text": "\n25 Jun, 2019"
},
{
"code": null,
"e": 24782,
"s": 24736,
"text": "Prerequisites: Generative Adversarial Network"
},
{
"code": null,
"e": 25006,
"s": 24782,
"text": "This article will demonstrate how to build a Generative Adversarial Network using the Keras library. The dataset which is used is the CIFAR10 Image dataset which is preloaded into Keras. You can read about the dataset here."
},
{
"code": null,
"e": 25047,
"s": 25006,
"text": "Step 1: Importing the required libraries"
},
{
"code": "import numpy as npimport matplotlib.pyplot as pltimport kerasfrom keras.layers import Input, Dense, Reshape, Flatten, Dropoutfrom keras.layers import BatchNormalization, Activation, ZeroPadding2Dfrom keras.layers.advanced_activations import LeakyReLUfrom keras.layers.convolutional import UpSampling2D, Conv2Dfrom keras.models import Sequential, Modelfrom keras.optimizers import Adam,SGD",
"e": 25436,
"s": 25047,
"text": null
},
{
"code": null,
"e": 25461,
"s": 25436,
"text": "Step 2: Loading the data"
},
{
"code": "#Loading the CIFAR10 data(X, y), (_, _) = keras.datasets.cifar10.load_data() #Selecting a single class images#The number was randomly chosen and any number#between 1 to 10 can be chosenX = X[y.flatten() == 8]",
"e": 25671,
"s": 25461,
"text": null
},
{
"code": null,
"e": 25729,
"s": 25671,
"text": "Step 3: Defining parameters to be used in later processes"
},
{
"code": "#Defining the Input shapeimage_shape = (32, 32, 3) latent_dimensions = 100",
"e": 25813,
"s": 25729,
"text": null
},
{
"code": null,
"e": 25872,
"s": 25813,
"text": "Step 4: Defining a utility function to build the Generator"
},
{
"code": "def build_generator(): model = Sequential() #Building the input layer model.add(Dense(128 * 8 * 8, activation=\"relu\", input_dim=latent_dimensions)) model.add(Reshape((8, 8, 128))) model.add(UpSampling2D()) model.add(Conv2D(128, kernel_size=3, padding=\"same\")) model.add(BatchNormalization(momentum=0.78)) model.add(Activation(\"relu\")) model.add(UpSampling2D()) model.add(Conv2D(64, kernel_size=3, padding=\"same\")) model.add(BatchNormalization(momentum=0.78)) model.add(Activation(\"relu\")) model.add(Conv2D(3, kernel_size=3, padding=\"same\")) model.add(Activation(\"tanh\")) #Generating the output image noise = Input(shape=(latent_dimensions,)) image = model(noise) return Model(noise, image)",
"e": 26771,
"s": 25872,
"text": null
},
{
"code": null,
"e": 26834,
"s": 26771,
"text": "Step 5: Defining a utility function to build the Discriminator"
},
{
"code": "def build_discriminator(): #Building the convolutional layers #to classify whether an image is real or fake model = Sequential() model.add(Conv2D(32, kernel_size=3, strides=2, input_shape=image_shape, padding=\"same\")) model.add(LeakyReLU(alpha=0.2)) model.add(Dropout(0.25)) model.add(Conv2D(64, kernel_size=3, strides=2, padding=\"same\")) model.add(ZeroPadding2D(padding=((0,1),(0,1)))) model.add(BatchNormalization(momentum=0.82)) model.add(LeakyReLU(alpha=0.25)) model.add(Dropout(0.25)) model.add(Conv2D(128, kernel_size=3, strides=2, padding=\"same\")) model.add(BatchNormalization(momentum=0.82)) model.add(LeakyReLU(alpha=0.2)) model.add(Dropout(0.25)) model.add(Conv2D(256, kernel_size=3, strides=1, padding=\"same\")) model.add(BatchNormalization(momentum=0.8)) model.add(LeakyReLU(alpha=0.25)) model.add(Dropout(0.25)) #Building the output layer model.add(Flatten()) model.add(Dense(1, activation='sigmoid')) image = Input(shape=image_shape) validity = model(image) return Model(image, validity)",
"e": 28082,
"s": 26834,
"text": null
},
{
"code": null,
"e": 28150,
"s": 28082,
"text": "Step 6: Defining a utility function to display the generated images"
},
{
"code": "def display_images(): r, c = 4,4 noise = np.random.normal(0, 1, (r * c,latent_dimensions)) generated_images = generator.predict(noise) #Scaling the generated images generated_images = 0.5 * generated_images + 0.5 fig, axs = plt.subplots(r, c) count = 0 for i in range(r): for j in range(c): axs[i,j].imshow(generated_images[count, :,:,]) axs[i,j].axis('off') count += 1 plt.show() plt.close()",
"e": 28673,
"s": 28150,
"text": null
},
{
"code": null,
"e": 28725,
"s": 28673,
"text": "Step 7: Building the Generative Adversarial Network"
},
{
"code": "# Building and compiling the discriminatordiscriminator = build_discriminator()discriminator.compile(loss='binary_crossentropy', optimizer=Adam(0.0002,0.5), metrics=['accuracy']) #Making the Discriminator untrainable#so that the generator can learn from fixed gradientdiscriminator.trainable = False # Building the generatorgenerator = build_generator() #Defining the input for the generator#and generating the imagesz = Input(shape=(latent_dimensions,))image = generator(z) #Checking the validity of the generated imagevalid = discriminator(image) #Defining the combined model of the Generator and the Discriminatorcombined_network = Model(z, valid)combined_network.compile(loss='binary_crossentropy', optimizer=Adam(0.0002,0.5))",
"e": 29527,
"s": 28725,
"text": null
},
{
"code": null,
"e": 29556,
"s": 29527,
"text": "Step 8: Training the network"
},
{
"code": "num_epochs=15000batch_size=32display_interval=2500losses=[] #Normalizing the inputX = (X / 127.5) - 1. #Defining the Adversarial ground truthsvalid = np.ones((batch_size, 1)) #Adding some noise valid += 0.05 * np.random.random(valid.shape)fake = np.zeros((batch_size, 1))fake += 0.05 * np.random.random(fake.shape) for epoch in range(num_epochs): #Training the Discriminator #Sampling a random half of images index = np.random.randint(0, X.shape[0], batch_size) images = X[index] #Sampling noise and generating a batch of new images noise = np.random.normal(0, 1, (batch_size, latent_dimensions)) generated_images = generator.predict(noise) #Training the discriminator to detect more accurately #whether a generated image is real or fake discm_loss_real = discriminator.train_on_batch(images, valid) discm_loss_fake = discriminator.train_on_batch(generated_images, fake) discm_loss = 0.5 * np.add(discm_loss_real, discm_loss_fake) #Training the Generator #Training the generator to generate images #which pass the authenticity test genr_loss = combined_network.train_on_batch(noise, valid) #Tracking the progress if epoch % display_interval == 0: display_images()",
"e": 31040,
"s": 29556,
"text": null
},
{
"code": null,
"e": 31049,
"s": 31040,
"text": "Epoch 0:"
},
{
"code": null,
"e": 31061,
"s": 31049,
"text": "Epoch 2500:"
},
{
"code": null,
"e": 31073,
"s": 31061,
"text": "Epoch 5000:"
},
{
"code": null,
"e": 31085,
"s": 31073,
"text": "Epoch 7500:"
},
{
"code": null,
"e": 31098,
"s": 31085,
"text": "Epoch 10000:"
},
{
"code": null,
"e": 31111,
"s": 31098,
"text": "Epoch 12500:"
},
{
"code": null,
"e": 31170,
"s": 31111,
"text": "Note that the quality of images increases with each epoch."
},
{
"code": null,
"e": 31205,
"s": 31170,
"text": "Step 8: Evaluating the performance"
},
{
"code": null,
"e": 31339,
"s": 31205,
"text": "The performance of the network will be evaluated by comparing the images generated on the last epoch to the original images visually."
},
{
"code": null,
"e": 31371,
"s": 31339,
"text": "a) Plotting the original images"
},
{
"code": "#Plotting some of the original images s=X[:40]s = 0.5 * s + 0.5f, ax = plt.subplots(5,8, figsize=(16,10))for i, image in enumerate(s): ax[i//8, i%8].imshow(image) ax[i//8, i%8].axis('off') plt.show()",
"e": 31586,
"s": 31371,
"text": null
},
{
"code": null,
"e": 31637,
"s": 31586,
"text": "b) Plotting the images generated on the last epoch"
},
{
"code": "#Plotting some of the last batch of generated imagesnoise = np.random.normal(size=(40, latent_dimensions))generated_images = generator.predict(noise)generated_images = 0.5 * generated_images + 0.5f, ax = plt.subplots(5,8, figsize=(16,10))for i, image in enumerate(generated_images): ax[i//8, i%8].imshow(image) ax[i//8, i%8].axis('off') plt.show()",
"e": 32000,
"s": 31637,
"text": null
},
{
"code": null,
"e": 32238,
"s": 32000,
"text": "On visually comparing the two sets of images, it can be concluded that the network is working at an acceptable level. The quality of images can be improved by training the network for more time or by tuning the parameters of the network."
},
{
"code": null,
"e": 32255,
"s": 32238,
"text": "Machine Learning"
},
{
"code": null,
"e": 32262,
"s": 32255,
"text": "Python"
},
{
"code": null,
"e": 32279,
"s": 32262,
"text": "Machine Learning"
},
{
"code": null,
"e": 32377,
"s": 32279,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32391,
"s": 32377,
"text": "Decision Tree"
},
{
"code": null,
"e": 32429,
"s": 32391,
"text": "Python | Decision tree implementation"
},
{
"code": null,
"e": 32453,
"s": 32429,
"text": "Search Algorithms in AI"
},
{
"code": null,
"e": 32493,
"s": 32453,
"text": "Decision Tree Introduction with example"
},
{
"code": null,
"e": 32516,
"s": 32493,
"text": "Reinforcement learning"
},
{
"code": null,
"e": 32544,
"s": 32516,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 32594,
"s": 32544,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 32616,
"s": 32594,
"text": "Python map() function"
}
] |
10 Essential Numerical Summaries in Statistics for Data Science (Theory, Python and R) | by Gustavo Hideo | Towards Data Science | In this article, we will go over the theory and application (with examples in Python and R) of the following numerical summaries:
MeanMedianModePercentileQuartiles (five-number summary)Standard DeviationVarianceRangeProportionCorrelation
Mean
Median
Mode
Percentile
Quartiles (five-number summary)
Standard Deviation
Variance
Range
Proportion
Correlation
This is the point of balance, describing the most typical value for normally distributed data. I say “normally distributed” data because the mean is highly influenced by outliers.
The mean adds up all the data values and divides by the total number of values, as follows:
The ‘x-bar’ is used to represent the sample mean (the mean of a sample of data). ‘∑’ (sigma) implies de addition of all values up from ‘i=1’ until ‘i=n’ (’n’ is the number of data values). The result is then divided by ‘n’.
Python: np.mean([1,2,3,4,5]) The result is 3.
R: mean(c(2,2,4,4)) The result is 3.
Effect of outliers:
The first plot ranges from 1 to 10. The mean is 5.5. When we replace 10 with 20, the average increases to 6.5. In the next concept, we will go over the ‘median’, that is the perfect choice to ignore outliers.
This is the “middle data point”, where half of the data is below the median and half is above the median. It’s the 50th percentile of the data (we will cover percentile later in this article). It’s also mostly used with skewed data because outliers won’t have a big effect on the median.
There are two formulas to compute the median. The choice of which formula to use depends on n (number of data points in the sample, or sample size) if it’s even or odd.
When n is even, there is no “middle” data point, so the middle two values are averaged.
When n is odd, the middle data point is the median.
Python: np.median([1,2,3,4,5,6]) (n is even). The result is 3.5, the average between 3 and 4 (middle points).
R: median(c(1,2,3,4,5,6,7)) (n is odd). The result is 4, the middle point.
Effect of outliers:
In the graph above, we are using the same data used to calculate the mean. Notice how the median stays the same in the second graph when we replace 10 with 20. It doesn’t mean that the median will always ignore the outliers. If we had a larger number of numbers and/or outliers, the median could be affected, but the influence of an outlier is low.
The mode will return you the most commonly occurring data value.
Python: statistics.mode([1,2,2,2,3,3,4,5,6]) The result is 2.
R doesn’t give you specifically the mean, but you can do the following to get the frequency of each data value: R: table(c('apple','banana','banana','tomato','orange','orange','banana')) The result is apple:1, banana:3, orange:2, tomato:1. ‘Banana’ has a higher frequency with 3 occurrences. Follows below a histogram plot of this fruit vector.
The percent of data that is equal to or less than a given data point. It’s useful for describing where a data point stands within the data set. If the percentile is close to zero, then the observation is one of the smallest. If the percentile is close to 100, then the data point is one o the largest in the data set.
Python:
from scipy import statsx = [10, 12, 15, 17, 20, 25, 30]## In what percentile lies the number 25?stats.percentileofscore(x,25)# result: 85.7
R:
library(stats)x <- c(10, 12, 15, 17, 20, 25, 30)## In what percentile lies the number 25?ecdf(x)(25)# resul: 85.7## In what percentile lies the number 12?ecdf(x)(12)# resul: 0.29
Quartiles measure the center and it’s also great to describe the spread of the data. Highly useful for skewed data. There are four quartiles, and they compose the five-number summary (combined with the minimum). The Five-number summary is composed of:
Minimum25th percentile (lower quartile)50th percentile (median)75th percentile (upper quartile)100th percentile (maximum)
Minimum
25th percentile (lower quartile)
50th percentile (median)
75th percentile (upper quartile)
100th percentile (maximum)
Python:
import numpy as npx = [10,12,15,17,20,25,30]min = np.min(x)q1 = np.quantile(x, .25)median = np.median(x)q3 = np.quantile(x, .75)max = np.max(x)print(min, q1, median, q3, max)
R:
x <- c(10,12,15,17,20,25,30)min = min(x)q1 = quantile(x, .25)median = median(x)q3 = quantile(x, .75)max = max(x)paste(min, q1, median, q3, max)## You can also use the function favstats from the mosaic ## It will give you the five-number summary, mean, standard deviation, sample size and number of missing values.librarylibrary(mosaic)favstats(x)
A boxplot is one good way to plot the five-number summary and explore the data set.
The bottom end of the boxplot represents the minimum; the first horizontal line represents the lower quartile; the line inside the square is the median; the next line is the upper quartile, and the top is the maximum.
Standard deviation is extensively used in statistics and data science. It measures the amount of variation or dispersion of a data set, calculating how spread out the data are from the mean. Small values mean the data is consistent and close to the mean. Larger values indicate the data is highly variable.
Deviation: The idea is to use the mean as a reference point from which everything varies. A deviation is defined as the distance an observation lies from the reference point. This distance is obtained by subtracting the data point (xi) from the mean (x-bar).
Calculating the standard deviation: The average of all the deviations will always turn out to be zero, so we square each deviation and sum up the results. Then, we divide it for ‘n-1’ (called degrees of freedom). We square root the final result to undo de squaring of the deviations.
The standard deviation is a representation of all deviations in the data. It’s never negative and it’s zero only if all the values are the same.
This graph shows the density of Sepal.Width from the Iris data set. The standard deviation is 0.436. The blue line represents the mean, and the red lines one and two standard deviations away from the mean. For example, a Sepal.Width with a value of 3.5 lies 1 standard deviation from the mean.
Python: np.std(x)
R: sd(x)
Effect of outliers: The standard deviation, like the mean, is highly influenced by outliers. The code below will use R to compare the standard deviation of two vectors, one without outliers and a second with an outlier.
x <- c(1,2,3,4,5,6,7,8,9,10)sd(x)# result: 3.02765#Replacing 10 by 20:y <- c(1,2,3,4,5,6,7,8,9,20)sd(y)# result: 5.400617
Variance is almost the same calculation of the standard deviation, but it stays in squared units. So, if you take the square root of the variance, you have the standard deviation.
Note that it’s represented by ‘s-squared’, while the standard deviation is represented by ‘s’.
Python: np.var(x)
R: var(x)
The difference between the maximum and minimum values. Useful for some basic exploratory analysis, but not as powerful as the standard deviation.
Python: np.max(n) — np.min(x)
R: max(x) — min(x)
It’s often referred to as “percentage”. Defines the percent of observations in the data set that satisfy some requirements.
Defines the strength and direction of the association between two quantitative variables. It ranges between -1 and 1. Positive correlations mean that one variable increases as the other variable increases. Negative correlations mean that one variable decreases as the other increases. When the correlation is zero, there is no correlation at all. As closest to one of the extreme the result is, stronger is the association between the two variables.
Python: stats.pearsonr(x,y)
R: cor(x,y)
The graph is showing the correlation in the mtcars data set, between MPG and Weight (-0.87). This is a strong negative correlation, meaning that as the weight increases, the MPG decreases.
These basic summaries are essential as you explore and analyze your data. They are the foundations to dive deeper into statistics and work on advanced analytics. If there is any summary you would like me to include, feel free to reach out in the responses below. | [
{
"code": null,
"e": 302,
"s": 172,
"text": "In this article, we will go over the theory and application (with examples in Python and R) of the following numerical summaries:"
},
{
"code": null,
"e": 410,
"s": 302,
"text": "MeanMedianModePercentileQuartiles (five-number summary)Standard DeviationVarianceRangeProportionCorrelation"
},
{
"code": null,
"e": 415,
"s": 410,
"text": "Mean"
},
{
"code": null,
"e": 422,
"s": 415,
"text": "Median"
},
{
"code": null,
"e": 427,
"s": 422,
"text": "Mode"
},
{
"code": null,
"e": 438,
"s": 427,
"text": "Percentile"
},
{
"code": null,
"e": 470,
"s": 438,
"text": "Quartiles (five-number summary)"
},
{
"code": null,
"e": 489,
"s": 470,
"text": "Standard Deviation"
},
{
"code": null,
"e": 498,
"s": 489,
"text": "Variance"
},
{
"code": null,
"e": 504,
"s": 498,
"text": "Range"
},
{
"code": null,
"e": 515,
"s": 504,
"text": "Proportion"
},
{
"code": null,
"e": 527,
"s": 515,
"text": "Correlation"
},
{
"code": null,
"e": 707,
"s": 527,
"text": "This is the point of balance, describing the most typical value for normally distributed data. I say “normally distributed” data because the mean is highly influenced by outliers."
},
{
"code": null,
"e": 799,
"s": 707,
"text": "The mean adds up all the data values and divides by the total number of values, as follows:"
},
{
"code": null,
"e": 1023,
"s": 799,
"text": "The ‘x-bar’ is used to represent the sample mean (the mean of a sample of data). ‘∑’ (sigma) implies de addition of all values up from ‘i=1’ until ‘i=n’ (’n’ is the number of data values). The result is then divided by ‘n’."
},
{
"code": null,
"e": 1069,
"s": 1023,
"text": "Python: np.mean([1,2,3,4,5]) The result is 3."
},
{
"code": null,
"e": 1106,
"s": 1069,
"text": "R: mean(c(2,2,4,4)) The result is 3."
},
{
"code": null,
"e": 1126,
"s": 1106,
"text": "Effect of outliers:"
},
{
"code": null,
"e": 1335,
"s": 1126,
"text": "The first plot ranges from 1 to 10. The mean is 5.5. When we replace 10 with 20, the average increases to 6.5. In the next concept, we will go over the ‘median’, that is the perfect choice to ignore outliers."
},
{
"code": null,
"e": 1623,
"s": 1335,
"text": "This is the “middle data point”, where half of the data is below the median and half is above the median. It’s the 50th percentile of the data (we will cover percentile later in this article). It’s also mostly used with skewed data because outliers won’t have a big effect on the median."
},
{
"code": null,
"e": 1792,
"s": 1623,
"text": "There are two formulas to compute the median. The choice of which formula to use depends on n (number of data points in the sample, or sample size) if it’s even or odd."
},
{
"code": null,
"e": 1880,
"s": 1792,
"text": "When n is even, there is no “middle” data point, so the middle two values are averaged."
},
{
"code": null,
"e": 1932,
"s": 1880,
"text": "When n is odd, the middle data point is the median."
},
{
"code": null,
"e": 2042,
"s": 1932,
"text": "Python: np.median([1,2,3,4,5,6]) (n is even). The result is 3.5, the average between 3 and 4 (middle points)."
},
{
"code": null,
"e": 2117,
"s": 2042,
"text": "R: median(c(1,2,3,4,5,6,7)) (n is odd). The result is 4, the middle point."
},
{
"code": null,
"e": 2137,
"s": 2117,
"text": "Effect of outliers:"
},
{
"code": null,
"e": 2486,
"s": 2137,
"text": "In the graph above, we are using the same data used to calculate the mean. Notice how the median stays the same in the second graph when we replace 10 with 20. It doesn’t mean that the median will always ignore the outliers. If we had a larger number of numbers and/or outliers, the median could be affected, but the influence of an outlier is low."
},
{
"code": null,
"e": 2551,
"s": 2486,
"text": "The mode will return you the most commonly occurring data value."
},
{
"code": null,
"e": 2613,
"s": 2551,
"text": "Python: statistics.mode([1,2,2,2,3,3,4,5,6]) The result is 2."
},
{
"code": null,
"e": 2958,
"s": 2613,
"text": "R doesn’t give you specifically the mean, but you can do the following to get the frequency of each data value: R: table(c('apple','banana','banana','tomato','orange','orange','banana')) The result is apple:1, banana:3, orange:2, tomato:1. ‘Banana’ has a higher frequency with 3 occurrences. Follows below a histogram plot of this fruit vector."
},
{
"code": null,
"e": 3276,
"s": 2958,
"text": "The percent of data that is equal to or less than a given data point. It’s useful for describing where a data point stands within the data set. If the percentile is close to zero, then the observation is one of the smallest. If the percentile is close to 100, then the data point is one o the largest in the data set."
},
{
"code": null,
"e": 3284,
"s": 3276,
"text": "Python:"
},
{
"code": null,
"e": 3424,
"s": 3284,
"text": "from scipy import statsx = [10, 12, 15, 17, 20, 25, 30]## In what percentile lies the number 25?stats.percentileofscore(x,25)# result: 85.7"
},
{
"code": null,
"e": 3427,
"s": 3424,
"text": "R:"
},
{
"code": null,
"e": 3606,
"s": 3427,
"text": "library(stats)x <- c(10, 12, 15, 17, 20, 25, 30)## In what percentile lies the number 25?ecdf(x)(25)# resul: 85.7## In what percentile lies the number 12?ecdf(x)(12)# resul: 0.29"
},
{
"code": null,
"e": 3858,
"s": 3606,
"text": "Quartiles measure the center and it’s also great to describe the spread of the data. Highly useful for skewed data. There are four quartiles, and they compose the five-number summary (combined with the minimum). The Five-number summary is composed of:"
},
{
"code": null,
"e": 3980,
"s": 3858,
"text": "Minimum25th percentile (lower quartile)50th percentile (median)75th percentile (upper quartile)100th percentile (maximum)"
},
{
"code": null,
"e": 3988,
"s": 3980,
"text": "Minimum"
},
{
"code": null,
"e": 4021,
"s": 3988,
"text": "25th percentile (lower quartile)"
},
{
"code": null,
"e": 4046,
"s": 4021,
"text": "50th percentile (median)"
},
{
"code": null,
"e": 4079,
"s": 4046,
"text": "75th percentile (upper quartile)"
},
{
"code": null,
"e": 4106,
"s": 4079,
"text": "100th percentile (maximum)"
},
{
"code": null,
"e": 4114,
"s": 4106,
"text": "Python:"
},
{
"code": null,
"e": 4289,
"s": 4114,
"text": "import numpy as npx = [10,12,15,17,20,25,30]min = np.min(x)q1 = np.quantile(x, .25)median = np.median(x)q3 = np.quantile(x, .75)max = np.max(x)print(min, q1, median, q3, max)"
},
{
"code": null,
"e": 4292,
"s": 4289,
"text": "R:"
},
{
"code": null,
"e": 4639,
"s": 4292,
"text": "x <- c(10,12,15,17,20,25,30)min = min(x)q1 = quantile(x, .25)median = median(x)q3 = quantile(x, .75)max = max(x)paste(min, q1, median, q3, max)## You can also use the function favstats from the mosaic ## It will give you the five-number summary, mean, standard deviation, sample size and number of missing values.librarylibrary(mosaic)favstats(x)"
},
{
"code": null,
"e": 4723,
"s": 4639,
"text": "A boxplot is one good way to plot the five-number summary and explore the data set."
},
{
"code": null,
"e": 4941,
"s": 4723,
"text": "The bottom end of the boxplot represents the minimum; the first horizontal line represents the lower quartile; the line inside the square is the median; the next line is the upper quartile, and the top is the maximum."
},
{
"code": null,
"e": 5248,
"s": 4941,
"text": "Standard deviation is extensively used in statistics and data science. It measures the amount of variation or dispersion of a data set, calculating how spread out the data are from the mean. Small values mean the data is consistent and close to the mean. Larger values indicate the data is highly variable."
},
{
"code": null,
"e": 5507,
"s": 5248,
"text": "Deviation: The idea is to use the mean as a reference point from which everything varies. A deviation is defined as the distance an observation lies from the reference point. This distance is obtained by subtracting the data point (xi) from the mean (x-bar)."
},
{
"code": null,
"e": 5791,
"s": 5507,
"text": "Calculating the standard deviation: The average of all the deviations will always turn out to be zero, so we square each deviation and sum up the results. Then, we divide it for ‘n-1’ (called degrees of freedom). We square root the final result to undo de squaring of the deviations."
},
{
"code": null,
"e": 5936,
"s": 5791,
"text": "The standard deviation is a representation of all deviations in the data. It’s never negative and it’s zero only if all the values are the same."
},
{
"code": null,
"e": 6230,
"s": 5936,
"text": "This graph shows the density of Sepal.Width from the Iris data set. The standard deviation is 0.436. The blue line represents the mean, and the red lines one and two standard deviations away from the mean. For example, a Sepal.Width with a value of 3.5 lies 1 standard deviation from the mean."
},
{
"code": null,
"e": 6248,
"s": 6230,
"text": "Python: np.std(x)"
},
{
"code": null,
"e": 6257,
"s": 6248,
"text": "R: sd(x)"
},
{
"code": null,
"e": 6477,
"s": 6257,
"text": "Effect of outliers: The standard deviation, like the mean, is highly influenced by outliers. The code below will use R to compare the standard deviation of two vectors, one without outliers and a second with an outlier."
},
{
"code": null,
"e": 6599,
"s": 6477,
"text": "x <- c(1,2,3,4,5,6,7,8,9,10)sd(x)# result: 3.02765#Replacing 10 by 20:y <- c(1,2,3,4,5,6,7,8,9,20)sd(y)# result: 5.400617"
},
{
"code": null,
"e": 6779,
"s": 6599,
"text": "Variance is almost the same calculation of the standard deviation, but it stays in squared units. So, if you take the square root of the variance, you have the standard deviation."
},
{
"code": null,
"e": 6874,
"s": 6779,
"text": "Note that it’s represented by ‘s-squared’, while the standard deviation is represented by ‘s’."
},
{
"code": null,
"e": 6892,
"s": 6874,
"text": "Python: np.var(x)"
},
{
"code": null,
"e": 6902,
"s": 6892,
"text": "R: var(x)"
},
{
"code": null,
"e": 7048,
"s": 6902,
"text": "The difference between the maximum and minimum values. Useful for some basic exploratory analysis, but not as powerful as the standard deviation."
},
{
"code": null,
"e": 7078,
"s": 7048,
"text": "Python: np.max(n) — np.min(x)"
},
{
"code": null,
"e": 7097,
"s": 7078,
"text": "R: max(x) — min(x)"
},
{
"code": null,
"e": 7221,
"s": 7097,
"text": "It’s often referred to as “percentage”. Defines the percent of observations in the data set that satisfy some requirements."
},
{
"code": null,
"e": 7671,
"s": 7221,
"text": "Defines the strength and direction of the association between two quantitative variables. It ranges between -1 and 1. Positive correlations mean that one variable increases as the other variable increases. Negative correlations mean that one variable decreases as the other increases. When the correlation is zero, there is no correlation at all. As closest to one of the extreme the result is, stronger is the association between the two variables."
},
{
"code": null,
"e": 7699,
"s": 7671,
"text": "Python: stats.pearsonr(x,y)"
},
{
"code": null,
"e": 7711,
"s": 7699,
"text": "R: cor(x,y)"
},
{
"code": null,
"e": 7900,
"s": 7711,
"text": "The graph is showing the correlation in the mtcars data set, between MPG and Weight (-0.87). This is a strong negative correlation, meaning that as the weight increases, the MPG decreases."
}
] |
Count of sorted triplets (a, b, c) whose product is at most N - GeeksforGeeks | 24 Dec, 2021
Given an integer N, the task is to find the count of triplets (a, b, c) such that a <= b <= c and a * b * c <= N.
Examples:
Input: N = 5Output: 6Explanation: The triplets that follow the required conditions are (1, 1, 1), (1, 1, 2), (1, 1, 3), (1, 1, 4), (1, 1, 5) and (1, 2, 2). Hence the count of value triplets is 6.
Input: N = 20Output: 40
Approach: The given problem can be solved based on the following observations:
Since a <= b <=c, it can be observed that the value of a must lie in the range [1, N1/3].
Similarly, for a given a the value of b must lie in the range [a, (N/a)1/2].
Similarly, when the value of a and b is fixed, the value of c must lie in the range [b, N/(a*b)]. Hence the number of possible values of c is the count of integers in the range [b, N/(a*b)]. Therefore, for each valid a and b, the number of possible values of c are N/(a*b) – b + 1.
Therefore, using the above observations below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the above approach#include <iostream>using namespace std; // Function to find the count of valid// triplets (a, b, c) such that the value// of a * b * c <= N and a <= b <= clong long validTriplets(int N){ // Stores count of triplets long long ans = 0; // Loop to iterate in the // range [1, N^(1/3)] for (long long a = 1; a * a * a <= N; a++) { // Loop to iterate in the // range [a, (N/a)^(1/2)] for (long long b = a; a * b * b <= N; b++) { // Add the count of valid // values of c for a fixed // value of a and b ans += N / a / b - b + 1; } } // Return Answer return ans;} // Driver Codeint main(){ int N = 5; cout << validTriplets(N); return 0;}
// Java implementation of the above approachimport java.util.*; class GFG{ // Function to find the count of valid// triplets (a, b, c) such that the value// of a * b * c <= N and a <= b <= cstatic long validTriplets(int N){ // Stores count of triplets long ans = 0; // Loop to iterate in the // range [1, N^(1/3)] for (long a = 1; a * a * a <= N; a++) { // Loop to iterate in the // range [a, (N/a)^(1/2)] for (long b = a; a * b * b <= N; b++) { // Add the count of valid // values of c for a fixed // value of a and b ans += N / a / b - b + 1; } } // Return Answer return ans;} // Driver Codepublic static void main(String[] args){ int N = 5; System.out.print(validTriplets(N)); }} // This code is contributed by 29AjayKumar
# Python implementation of the above approach # Function to find the count of valid# triplets (a, b, c) such that the value# of a * b * c <= N and a <= b <= cdef validTriplets(N): # Stores count of triplets ans = 0; # Loop to iterate in the # range [1, N^(1/3)] for a in range(1, int(N ** (1 / 3)) + 1): # Loop to iterate in the # range [a, (N/a)^(1/2)] b = a; while(a * b * b <= N): # Add the count of valid # values of c for a fixed # value of a and b ans += N / a / b - b + 1; b += 1 # Return Answer return int(ans); # Driver CodeN = 5; print(validTriplets(N)); # This code is contributed by gfgking
// C# implementation of the above approachusing System;class GFG { // Function to find the count of valid // triplets (a, b, c) such that the value // of a * b * c <= N and a <= b <= c static long validTriplets(int N) { // Stores count of triplets long ans = 0; // Loop to iterate in the // range [1, N^(1/3)] for (long a = 1; a * a * a <= N; a++) { // Loop to iterate in the // range [a, (N/a)^(1/2)] for (long b = a; a * b * b <= N; b++) { // Add the count of valid // values of c for a fixed // value of a and b ans += N / a / b - b + 1; } } // Return Answer return ans; } // Driver Code public static void Main() { int N = 5; Console.WriteLine(validTriplets(N)); }} // This code is contributed by ukasp.
<script> // JavaScript implementation of the above approach // Function to find the count of valid// triplets (a, b, c) such that the value// of a * b * c <= N and a <= b <= cfunction validTriplets(N){ // Stores count of triplets let ans = 0; // Loop to iterate in the // range [1, N^(1/3)] for(let a = 1; a * a * a <= N; a++) { // Loop to iterate in the // range [a, (N/a)^(1/2)] for(let b = a; a * b * b <= N; b++) { // Add the count of valid // values of c for a fixed // value of a and b ans += N / a / b - b + 1; } } // Return Answer return Math.floor(ans);} // Driver Codelet N = 5; document.write(validTriplets(N)); // This code is contributed by Potta Lokesh </script>
6
Time Complexity: O(N2/3)Auxiliary Space: O(1)
lokeshpotta20
gfgking
ukasp
29AjayKumar
khushboogoyal499
Combinatorial
Greedy
Mathematical
Searching
Searching
Greedy
Mathematical
Combinatorial
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Find the Number of Permutations that satisfy the given condition in an array
Split array into subarrays at minimum cost by minimizing count of repeating elements in each subarray
Ways to sum to N using Natural Numbers up to K with repetitions allowed
Number of Simple Graph with N Vertices and M Edges
Largest substring with same Characters
Dijkstra's shortest path algorithm | Greedy Algo-7
Program for array rotation
Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Huffman Coding | Greedy Algo-3 | [
{
"code": null,
"e": 25061,
"s": 25033,
"text": "\n24 Dec, 2021"
},
{
"code": null,
"e": 25175,
"s": 25061,
"text": "Given an integer N, the task is to find the count of triplets (a, b, c) such that a <= b <= c and a * b * c <= N."
},
{
"code": null,
"e": 25185,
"s": 25175,
"text": "Examples:"
},
{
"code": null,
"e": 25382,
"s": 25185,
"text": "Input: N = 5Output: 6Explanation: The triplets that follow the required conditions are (1, 1, 1), (1, 1, 2), (1, 1, 3), (1, 1, 4), (1, 1, 5) and (1, 2, 2). Hence the count of value triplets is 6. "
},
{
"code": null,
"e": 25406,
"s": 25382,
"text": "Input: N = 20Output: 40"
},
{
"code": null,
"e": 25485,
"s": 25406,
"text": "Approach: The given problem can be solved based on the following observations:"
},
{
"code": null,
"e": 25575,
"s": 25485,
"text": "Since a <= b <=c, it can be observed that the value of a must lie in the range [1, N1/3]."
},
{
"code": null,
"e": 25652,
"s": 25575,
"text": "Similarly, for a given a the value of b must lie in the range [a, (N/a)1/2]."
},
{
"code": null,
"e": 25934,
"s": 25652,
"text": "Similarly, when the value of a and b is fixed, the value of c must lie in the range [b, N/(a*b)]. Hence the number of possible values of c is the count of integers in the range [b, N/(a*b)]. Therefore, for each valid a and b, the number of possible values of c are N/(a*b) – b + 1."
},
{
"code": null,
"e": 26025,
"s": 25934,
"text": "Therefore, using the above observations below is the implementation of the above approach:"
},
{
"code": null,
"e": 26029,
"s": 26025,
"text": "C++"
},
{
"code": null,
"e": 26034,
"s": 26029,
"text": "Java"
},
{
"code": null,
"e": 26042,
"s": 26034,
"text": "Python3"
},
{
"code": null,
"e": 26045,
"s": 26042,
"text": "C#"
},
{
"code": null,
"e": 26056,
"s": 26045,
"text": "Javascript"
},
{
"code": "// C++ implementation of the above approach#include <iostream>using namespace std; // Function to find the count of valid// triplets (a, b, c) such that the value// of a * b * c <= N and a <= b <= clong long validTriplets(int N){ // Stores count of triplets long long ans = 0; // Loop to iterate in the // range [1, N^(1/3)] for (long long a = 1; a * a * a <= N; a++) { // Loop to iterate in the // range [a, (N/a)^(1/2)] for (long long b = a; a * b * b <= N; b++) { // Add the count of valid // values of c for a fixed // value of a and b ans += N / a / b - b + 1; } } // Return Answer return ans;} // Driver Codeint main(){ int N = 5; cout << validTriplets(N); return 0;}",
"e": 26840,
"s": 26056,
"text": null
},
{
"code": "// Java implementation of the above approachimport java.util.*; class GFG{ // Function to find the count of valid// triplets (a, b, c) such that the value// of a * b * c <= N and a <= b <= cstatic long validTriplets(int N){ // Stores count of triplets long ans = 0; // Loop to iterate in the // range [1, N^(1/3)] for (long a = 1; a * a * a <= N; a++) { // Loop to iterate in the // range [a, (N/a)^(1/2)] for (long b = a; a * b * b <= N; b++) { // Add the count of valid // values of c for a fixed // value of a and b ans += N / a / b - b + 1; } } // Return Answer return ans;} // Driver Codepublic static void main(String[] args){ int N = 5; System.out.print(validTriplets(N)); }} // This code is contributed by 29AjayKumar",
"e": 27675,
"s": 26840,
"text": null
},
{
"code": "# Python implementation of the above approach # Function to find the count of valid# triplets (a, b, c) such that the value# of a * b * c <= N and a <= b <= cdef validTriplets(N): # Stores count of triplets ans = 0; # Loop to iterate in the # range [1, N^(1/3)] for a in range(1, int(N ** (1 / 3)) + 1): # Loop to iterate in the # range [a, (N/a)^(1/2)] b = a; while(a * b * b <= N): # Add the count of valid # values of c for a fixed # value of a and b ans += N / a / b - b + 1; b += 1 # Return Answer return int(ans); # Driver CodeN = 5; print(validTriplets(N)); # This code is contributed by gfgking",
"e": 28398,
"s": 27675,
"text": null
},
{
"code": "// C# implementation of the above approachusing System;class GFG { // Function to find the count of valid // triplets (a, b, c) such that the value // of a * b * c <= N and a <= b <= c static long validTriplets(int N) { // Stores count of triplets long ans = 0; // Loop to iterate in the // range [1, N^(1/3)] for (long a = 1; a * a * a <= N; a++) { // Loop to iterate in the // range [a, (N/a)^(1/2)] for (long b = a; a * b * b <= N; b++) { // Add the count of valid // values of c for a fixed // value of a and b ans += N / a / b - b + 1; } } // Return Answer return ans; } // Driver Code public static void Main() { int N = 5; Console.WriteLine(validTriplets(N)); }} // This code is contributed by ukasp.",
"e": 29315,
"s": 28398,
"text": null
},
{
"code": "<script> // JavaScript implementation of the above approach // Function to find the count of valid// triplets (a, b, c) such that the value// of a * b * c <= N and a <= b <= cfunction validTriplets(N){ // Stores count of triplets let ans = 0; // Loop to iterate in the // range [1, N^(1/3)] for(let a = 1; a * a * a <= N; a++) { // Loop to iterate in the // range [a, (N/a)^(1/2)] for(let b = a; a * b * b <= N; b++) { // Add the count of valid // values of c for a fixed // value of a and b ans += N / a / b - b + 1; } } // Return Answer return Math.floor(ans);} // Driver Codelet N = 5; document.write(validTriplets(N)); // This code is contributed by Potta Lokesh </script>",
"e": 30131,
"s": 29315,
"text": null
},
{
"code": null,
"e": 30133,
"s": 30131,
"text": "6"
},
{
"code": null,
"e": 30179,
"s": 30133,
"text": "Time Complexity: O(N2/3)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 30195,
"s": 30181,
"text": "lokeshpotta20"
},
{
"code": null,
"e": 30203,
"s": 30195,
"text": "gfgking"
},
{
"code": null,
"e": 30209,
"s": 30203,
"text": "ukasp"
},
{
"code": null,
"e": 30221,
"s": 30209,
"text": "29AjayKumar"
},
{
"code": null,
"e": 30238,
"s": 30221,
"text": "khushboogoyal499"
},
{
"code": null,
"e": 30252,
"s": 30238,
"text": "Combinatorial"
},
{
"code": null,
"e": 30259,
"s": 30252,
"text": "Greedy"
},
{
"code": null,
"e": 30272,
"s": 30259,
"text": "Mathematical"
},
{
"code": null,
"e": 30282,
"s": 30272,
"text": "Searching"
},
{
"code": null,
"e": 30292,
"s": 30282,
"text": "Searching"
},
{
"code": null,
"e": 30299,
"s": 30292,
"text": "Greedy"
},
{
"code": null,
"e": 30312,
"s": 30299,
"text": "Mathematical"
},
{
"code": null,
"e": 30326,
"s": 30312,
"text": "Combinatorial"
},
{
"code": null,
"e": 30424,
"s": 30326,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30433,
"s": 30424,
"text": "Comments"
},
{
"code": null,
"e": 30446,
"s": 30433,
"text": "Old Comments"
},
{
"code": null,
"e": 30523,
"s": 30446,
"text": "Find the Number of Permutations that satisfy the given condition in an array"
},
{
"code": null,
"e": 30625,
"s": 30523,
"text": "Split array into subarrays at minimum cost by minimizing count of repeating elements in each subarray"
},
{
"code": null,
"e": 30697,
"s": 30625,
"text": "Ways to sum to N using Natural Numbers up to K with repetitions allowed"
},
{
"code": null,
"e": 30748,
"s": 30697,
"text": "Number of Simple Graph with N Vertices and M Edges"
},
{
"code": null,
"e": 30787,
"s": 30748,
"text": "Largest substring with same Characters"
},
{
"code": null,
"e": 30838,
"s": 30787,
"text": "Dijkstra's shortest path algorithm | Greedy Algo-7"
},
{
"code": null,
"e": 30865,
"s": 30838,
"text": "Program for array rotation"
},
{
"code": null,
"e": 30916,
"s": 30865,
"text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5"
},
{
"code": null,
"e": 30974,
"s": 30916,
"text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2"
}
] |
Angular7 - Data Binding | Data Binding is available right from AngularJS, and all the versions of Angular released later on. We use curly braces for data binding - {{}}; this process is called interpolation. We have already seen in our previous examples how we declared the value to the variable title and the same is printed in the browser.
The variable in the app.component.html file is referred as {{title}} and the value of title is initialized in the app.component.ts file and in app.component.html, the value is displayed.
Let us now create a dropdown of months in the browser. To do that, we have created an array of months in app.component.ts as follows −
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Angular 7';
// declared array of months.
months = ["January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December"];
}
The month’s array that is shown above is to be displayed in a dropdown in the browser.
We have created the normal select tag with option. In option, we have used the for loop. The for loop is used to iterate over the months’ array, which in turn will create the option tag with the value present in the months.
The syntax for in Angular is as follows −
*ngFor = “let I of months”
and to get the value of months we are displaying it in −
{{i}}
The two curly brackets help with data binding. You declare the variables in your app.component.ts file and the same will be replaced using the curly brackets.
Following is the output of the above month’s array in the browser −
The variable that is set in the app.component.ts can be binded inside the app.component.html using the curly brackets. For example: {{}}.
Let us now display the data in the browser based on condition. Here, we have added a variable and assigned the value as true. Using the if statement, we can hide/show the content to be displayed.
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Angular 7';
// declared array of months.
months = ["January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December"];
isavailable = true; //variable is set to true
}
app.component.html
<!--The content below is only a placeholder and can be replaced.-->
<div style = "text-align:center">
<h1> Welcome to {{title}}. </h1>
</div>
<div> Months :
<select>
<option *ngFor = "let i of months">{{i}}</option>
</select>
</div>
<br/>
<div>
<span *ngIf = "isavailable">Condition is valid.</span>
//over here based on if condition the text condition is valid is displayed.
//If the value of isavailable is set to false it will not display the text.
</div>
Let us explain the above example using the IF THEN ELSE condition.
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Angular 7';
// declared array of months.
months = ["January", "Feburary", "March", "April", "May","June", "July",
"August", "September", "October", "November", "December"];
isavailable = false; //variable is set to true
}
In this case, we have made the isavailable variable as false. To print the else condition, we will have to create the ng-template as follows −
<ng-template #condition1>Condition is invalid</ng-template>
The full code is given below −
<!--The content below is only a placeholder and can be replaced.-->
<div style = "text-align:center">
<h1> Welcome to {{title}}. </h1>
</div>
<div> Months :
<select>
<option *ngFor = "let i of months">{{i}}</option>
</select>
</div>
<br/>
<div>
<span *ngIf = "isavailable; else condition1">Condition is valid.</span>
<ng-template #condition1>Condition is invalid</ng-template>
</div>
If is used with the else condition and the variable used is condition1. The same is assigned as an id to the ng-template, and when the available variable is set to false the text Condition is invalid is displayed.
Following screenshot shows the display in the browser −
Let us now use the if then else condition.
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Angular 7';
// declared array of months.
months = ["January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December"];
isavailable = true; //variable is set to true
}
Now, we will make the variable isavailable as true. In the html, the condition is written in the following way −
<!--The content below is only a placeholder and can be replaced.-->
<div style = "text-align:center">
<h1> Welcome to {{title}}. </h1>
</div>
<div> Months :
<select>
<option *ngFor="let i of months">{{i}}</option>
</select>
</div>
<br/>
<div>
<span *ngIf = "isavailable; then condition1 else condition2">
Condition is valid.
</span>
<ng-template #condition1>Condition is valid</ng-template>
<ng-template #condition2>Condition is invalid</ng-template>
</div>
If the variable is true, then condition1, else condition2. Now, two templates are created with id #condition1 and #condition2.
The display in the browser is as follows −
16 Lectures
1.5 hours
Anadi Sharma
28 Lectures
2.5 hours
Anadi Sharma
11 Lectures
7.5 hours
SHIVPRASAD KOIRALA
16 Lectures
2.5 hours
Frahaan Hussain
69 Lectures
5 hours
Senol Atac
53 Lectures
3.5 hours
Senol Atac
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2377,
"s": 2061,
"text": "Data Binding is available right from AngularJS, and all the versions of Angular released later on. We use curly braces for data binding - {{}}; this process is called interpolation. We have already seen in our previous examples how we declared the value to the variable title and the same is printed in the browser."
},
{
"code": null,
"e": 2564,
"s": 2377,
"text": "The variable in the app.component.html file is referred as {{title}} and the value of title is initialized in the app.component.ts file and in app.component.html, the value is displayed."
},
{
"code": null,
"e": 2699,
"s": 2564,
"text": "Let us now create a dropdown of months in the browser. To do that, we have created an array of months in app.component.ts as follows −"
},
{
"code": null,
"e": 3102,
"s": 2699,
"text": "import { Component } from '@angular/core';\n\n@Component({ \n selector: 'app-root', \n templateUrl: './app.component.html', \n styleUrls: ['./app.component.css'] \n}) \nexport class AppComponent {\n title = 'Angular 7'; \n \n // declared array of months. \n months = [\"January\", \"February\", \"March\", \"April\", \"May\", \"June\", \"July\", \n \"August\", \"September\", \"October\", \"November\", \"December\"];\n}"
},
{
"code": null,
"e": 3189,
"s": 3102,
"text": "The month’s array that is shown above is to be displayed in a dropdown in the browser."
},
{
"code": null,
"e": 3413,
"s": 3189,
"text": "We have created the normal select tag with option. In option, we have used the for loop. The for loop is used to iterate over the months’ array, which in turn will create the option tag with the value present in the months."
},
{
"code": null,
"e": 3455,
"s": 3413,
"text": "The syntax for in Angular is as follows −"
},
{
"code": null,
"e": 3483,
"s": 3455,
"text": "*ngFor = “let I of months”\n"
},
{
"code": null,
"e": 3540,
"s": 3483,
"text": "and to get the value of months we are displaying it in −"
},
{
"code": null,
"e": 3547,
"s": 3540,
"text": "{{i}}\n"
},
{
"code": null,
"e": 3706,
"s": 3547,
"text": "The two curly brackets help with data binding. You declare the variables in your app.component.ts file and the same will be replaced using the curly brackets."
},
{
"code": null,
"e": 3774,
"s": 3706,
"text": "Following is the output of the above month’s array in the browser −"
},
{
"code": null,
"e": 3912,
"s": 3774,
"text": "The variable that is set in the app.component.ts can be binded inside the app.component.html using the curly brackets. For example: {{}}."
},
{
"code": null,
"e": 4108,
"s": 3912,
"text": "Let us now display the data in the browser based on condition. Here, we have added a variable and assigned the value as true. Using the if statement, we can hide/show the content to be displayed."
},
{
"code": null,
"e": 4565,
"s": 4108,
"text": "import { Component } from '@angular/core';\n\n@Component({\n selector: 'app-root', \n templateUrl: './app.component.html', \n styleUrls: ['./app.component.css'] \n}) \nexport class AppComponent { \n title = 'Angular 7'; \n \n // declared array of months. \n months = [\"January\", \"February\", \"March\", \"April\", \"May\", \"June\", \"July\", \n \"August\", \"September\", \"October\", \"November\", \"December\"]; \n \n isavailable = true; //variable is set to true\n}"
},
{
"code": null,
"e": 4584,
"s": 4565,
"text": "app.component.html"
},
{
"code": null,
"e": 5082,
"s": 4584,
"text": "<!--The content below is only a placeholder and can be replaced.--> \n<div style = \"text-align:center\"> \n <h1> Welcome to {{title}}. </h1> \n</div>\n\n<div> Months : \n <select> \n <option *ngFor = \"let i of months\">{{i}}</option> \n </select> \n</div> \n<br/>\n\n<div> \n <span *ngIf = \"isavailable\">Condition is valid.</span> \n //over here based on if condition the text condition is valid is displayed. \n //If the value of isavailable is set to false it will not display the text. \n</div>"
},
{
"code": null,
"e": 5149,
"s": 5082,
"text": "Let us explain the above example using the IF THEN ELSE condition."
},
{
"code": null,
"e": 5597,
"s": 5149,
"text": "import { Component } from '@angular/core';\n@Component({\n selector: 'app-root',\n templateUrl: './app.component.html',\n styleUrls: ['./app.component.css']\n})\nexport class AppComponent {\n title = 'Angular 7';\n \n // declared array of months.\n months = [\"January\", \"Feburary\", \"March\", \"April\", \"May\",\"June\", \"July\", \n \"August\", \"September\", \"October\", \"November\", \"December\"];\n \n isavailable = false; //variable is set to true\n}"
},
{
"code": null,
"e": 5740,
"s": 5597,
"text": "In this case, we have made the isavailable variable as false. To print the else condition, we will have to create the ng-template as follows −"
},
{
"code": null,
"e": 5801,
"s": 5740,
"text": "<ng-template #condition1>Condition is invalid</ng-template>\n"
},
{
"code": null,
"e": 5832,
"s": 5801,
"text": "The full code is given below −"
},
{
"code": null,
"e": 6248,
"s": 5832,
"text": "<!--The content below is only a placeholder and can be replaced.--> \n<div style = \"text-align:center\"> \n <h1> Welcome to {{title}}. </h1> \n</div>\n\n<div> Months : \n <select> \n <option *ngFor = \"let i of months\">{{i}}</option>\n </select>\n</div> \n<br/>\n\n<div> \n <span *ngIf = \"isavailable; else condition1\">Condition is valid.</span> \n <ng-template #condition1>Condition is invalid</ng-template> \n</div>"
},
{
"code": null,
"e": 6462,
"s": 6248,
"text": "If is used with the else condition and the variable used is condition1. The same is assigned as an id to the ng-template, and when the available variable is set to false the text Condition is invalid is displayed."
},
{
"code": null,
"e": 6518,
"s": 6462,
"text": "Following screenshot shows the display in the browser −"
},
{
"code": null,
"e": 6561,
"s": 6518,
"text": "Let us now use the if then else condition."
},
{
"code": null,
"e": 7018,
"s": 6561,
"text": "import { Component } from '@angular/core';\n@Component({\n selector: 'app-root', \n templateUrl: './app.component.html', \n styleUrls: ['./app.component.css'] \n}) \nexport class AppComponent { \n title = 'Angular 7'; \n \n // declared array of months. \n months = [\"January\", \"February\", \"March\", \"April\", \"May\", \"June\", \"July\", \n \"August\", \"September\", \"October\", \"November\", \"December\"]; \n \n isavailable = true; //variable is set to true \n}"
},
{
"code": null,
"e": 7131,
"s": 7018,
"text": "Now, we will make the variable isavailable as true. In the html, the condition is written in the following way −"
},
{
"code": null,
"e": 7635,
"s": 7131,
"text": "<!--The content below is only a placeholder and can be replaced.--> \n<div style = \"text-align:center\"> \n <h1> Welcome to {{title}}. </h1> \n</div>\n\n<div> Months : \n <select> \n <option *ngFor=\"let i of months\">{{i}}</option>\n </select> \n</div> \n<br/>\n\n<div> \n <span *ngIf = \"isavailable; then condition1 else condition2\">\n Condition is valid.\n </span> \n <ng-template #condition1>Condition is valid</ng-template> \n <ng-template #condition2>Condition is invalid</ng-template> \n</div>"
},
{
"code": null,
"e": 7762,
"s": 7635,
"text": "If the variable is true, then condition1, else condition2. Now, two templates are created with id #condition1 and #condition2."
},
{
"code": null,
"e": 7805,
"s": 7762,
"text": "The display in the browser is as follows −"
},
{
"code": null,
"e": 7840,
"s": 7805,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 7854,
"s": 7840,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 7889,
"s": 7854,
"text": "\n 28 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 7903,
"s": 7889,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 7938,
"s": 7903,
"text": "\n 11 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 7958,
"s": 7938,
"text": " SHIVPRASAD KOIRALA"
},
{
"code": null,
"e": 7993,
"s": 7958,
"text": "\n 16 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 8010,
"s": 7993,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 8043,
"s": 8010,
"text": "\n 69 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 8055,
"s": 8043,
"text": " Senol Atac"
},
{
"code": null,
"e": 8090,
"s": 8055,
"text": "\n 53 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 8102,
"s": 8090,
"text": " Senol Atac"
},
{
"code": null,
"e": 8109,
"s": 8102,
"text": " Print"
},
{
"code": null,
"e": 8120,
"s": 8109,
"text": " Add Notes"
}
] |
File Path with double slash in Java | The double slash in the file path is required as to create the ’\’ character , another ‘\’ needs to be added to escape it. A program that demonstrates this is given as follows −
Live Demo
import java.io.File;
public class Demo {
public static void main(String[] args) {
File file = new File("C:\\jdk11.0.2\\demo1.txt");
System.out.println(file);
}
}
The output of the above program is as follows −
C:\jdk11.0.2\demo1.txt
Now let us understand the above program.
The file path of the file is provided with double slash and then it is printed. A code snippet that demonstrates this is given as follows −
File file = new File("C:\\jdk11.0.2\\demo1.txt");
System.out.println(file); | [
{
"code": null,
"e": 1240,
"s": 1062,
"text": "The double slash in the file path is required as to create the ’\\’ character , another ‘\\’ needs to be added to escape it. A program that demonstrates this is given as follows −"
},
{
"code": null,
"e": 1251,
"s": 1240,
"text": " Live Demo"
},
{
"code": null,
"e": 1431,
"s": 1251,
"text": "import java.io.File;\npublic class Demo {\n public static void main(String[] args) {\n File file = new File(\"C:\\\\jdk11.0.2\\\\demo1.txt\");\n System.out.println(file);\n }\n}"
},
{
"code": null,
"e": 1479,
"s": 1431,
"text": "The output of the above program is as follows −"
},
{
"code": null,
"e": 1502,
"s": 1479,
"text": "C:\\jdk11.0.2\\demo1.txt"
},
{
"code": null,
"e": 1543,
"s": 1502,
"text": "Now let us understand the above program."
},
{
"code": null,
"e": 1683,
"s": 1543,
"text": "The file path of the file is provided with double slash and then it is printed. A code snippet that demonstrates this is given as follows −"
},
{
"code": null,
"e": 1759,
"s": 1683,
"text": "File file = new File(\"C:\\\\jdk11.0.2\\\\demo1.txt\");\nSystem.out.println(file);"
}
] |
Explain Top Hat and Black hat morphological operations in Java. | Morphological operations are the set of operations that process images according to the given shapes.
Erosion − Erosion is a morphological operation during which pixels are removed from the image boundaries.
Erosion − Erosion is a morphological operation during which pixels are removed from the image boundaries.
Dilation − During is a morphological operation during which pixels are added to the image boundaries.
Dilation − During is a morphological operation during which pixels are added to the image boundaries.
Where the total number of pixels added/removed depends on the
dimensions of the structuring element used.
Where the total number of pixels added/removed depends on the
dimensions of the structuring element used.
Morphological Opening − During this operation erosion is applied on the given input and on the result dilation is applied. This is used to remove small objects from the foreground of an image.
Morphological Opening − During this operation erosion is applied on the given input and on the result dilation is applied. This is used to remove small objects from the foreground of an image.
Morphological Closing − During this operation dilation is applied on the given input and on the result erosion is applied. This is used to remove small objects on an image.
Morphological Closing − During this operation dilation is applied on the given input and on the result erosion is applied. This is used to remove small objects on an image.
A Morphological Top Hat is a difference between the given image and its opening.
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.highgui.HighGui;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
public class TopHatExample {
public static void main(String args[]) {
//Loading the OpenCV core library
System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
//Reading image data
String file ="D:\\Images\\morph_input1.jpg";
Mat src = Imgcodecs.imread(file);
//Creating destination matrix
Mat dst = new Mat(src.rows(), src.cols(), src.type());
//Preparing the kernel matrix object
Mat kernel = Mat.ones(5,5, CvType.CV_32F);
//Applying dilate on the Image
Imgproc.morphologyEx(src, dst, Imgproc.MORPH_TOPHAT, kernel);
//Displaying the image
HighGui.imshow("Blackhat Gradient", dst);
HighGui.waitKey();
}
}
A Morphological Black Hat is a difference between the closing and the given image.
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.highgui.HighGui;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
public class TopHatExample {
public static void main(String args[]) {
//Loading the OpenCV core library
System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
//Reading image data
String file ="D:\\Images\\morph_input1.jpg";
Mat src = Imgcodecs.imread(file);
//Creating destination matrix
Mat dst = new Mat(src.rows(), src.cols(), src.type());
//Preparing the kernel matrix object
Mat kernel = Mat.ones(5,5, CvType.CV_32F);
//Applying dilate on the Image
Imgproc.morphologyEx(src, dst, Imgproc.MORPH_BLACKHAT, kernel);
//Displaying the image
HighGui.imshow("Blackhat Gradient", dst);
HighGui.waitKey();
}
} | [
{
"code": null,
"e": 1164,
"s": 1062,
"text": "Morphological operations are the set of operations that process images according to the given shapes."
},
{
"code": null,
"e": 1270,
"s": 1164,
"text": "Erosion − Erosion is a morphological operation during which pixels are removed from the image boundaries."
},
{
"code": null,
"e": 1376,
"s": 1270,
"text": "Erosion − Erosion is a morphological operation during which pixels are removed from the image boundaries."
},
{
"code": null,
"e": 1478,
"s": 1376,
"text": "Dilation − During is a morphological operation during which pixels are added to the image boundaries."
},
{
"code": null,
"e": 1580,
"s": 1478,
"text": "Dilation − During is a morphological operation during which pixels are added to the image boundaries."
},
{
"code": null,
"e": 1686,
"s": 1580,
"text": "Where the total number of pixels added/removed depends on the\ndimensions of the structuring element used."
},
{
"code": null,
"e": 1792,
"s": 1686,
"text": "Where the total number of pixels added/removed depends on the\ndimensions of the structuring element used."
},
{
"code": null,
"e": 1985,
"s": 1792,
"text": "Morphological Opening − During this operation erosion is applied on the given input and on the result dilation is applied. This is used to remove small objects from the foreground of an image."
},
{
"code": null,
"e": 2178,
"s": 1985,
"text": "Morphological Opening − During this operation erosion is applied on the given input and on the result dilation is applied. This is used to remove small objects from the foreground of an image."
},
{
"code": null,
"e": 2351,
"s": 2178,
"text": "Morphological Closing − During this operation dilation is applied on the given input and on the result erosion is applied. This is used to remove small objects on an image."
},
{
"code": null,
"e": 2524,
"s": 2351,
"text": "Morphological Closing − During this operation dilation is applied on the given input and on the result erosion is applied. This is used to remove small objects on an image."
},
{
"code": null,
"e": 2605,
"s": 2524,
"text": "A Morphological Top Hat is a difference between the given image and its opening."
},
{
"code": null,
"e": 3490,
"s": 2605,
"text": "import org.opencv.core.Core;\nimport org.opencv.core.CvType;\nimport org.opencv.core.Mat;\nimport org.opencv.highgui.HighGui;\nimport org.opencv.imgcodecs.Imgcodecs;\nimport org.opencv.imgproc.Imgproc;\npublic class TopHatExample {\n public static void main(String args[]) {\n //Loading the OpenCV core library\n System.loadLibrary( Core.NATIVE_LIBRARY_NAME );\n //Reading image data\n String file =\"D:\\\\Images\\\\morph_input1.jpg\";\n Mat src = Imgcodecs.imread(file);\n //Creating destination matrix\n Mat dst = new Mat(src.rows(), src.cols(), src.type());\n //Preparing the kernel matrix object\n Mat kernel = Mat.ones(5,5, CvType.CV_32F);\n //Applying dilate on the Image\n Imgproc.morphologyEx(src, dst, Imgproc.MORPH_TOPHAT, kernel);\n //Displaying the image\n HighGui.imshow(\"Blackhat Gradient\", dst);\n HighGui.waitKey();\n }\n}"
},
{
"code": null,
"e": 3573,
"s": 3490,
"text": "A Morphological Black Hat is a difference between the closing and the given image."
},
{
"code": null,
"e": 4460,
"s": 3573,
"text": "import org.opencv.core.Core;\nimport org.opencv.core.CvType;\nimport org.opencv.core.Mat;\nimport org.opencv.highgui.HighGui;\nimport org.opencv.imgcodecs.Imgcodecs;\nimport org.opencv.imgproc.Imgproc;\npublic class TopHatExample {\n public static void main(String args[]) {\n //Loading the OpenCV core library\n System.loadLibrary( Core.NATIVE_LIBRARY_NAME );\n //Reading image data\n String file =\"D:\\\\Images\\\\morph_input1.jpg\";\n Mat src = Imgcodecs.imread(file);\n //Creating destination matrix\n Mat dst = new Mat(src.rows(), src.cols(), src.type());\n //Preparing the kernel matrix object\n Mat kernel = Mat.ones(5,5, CvType.CV_32F);\n //Applying dilate on the Image\n Imgproc.morphologyEx(src, dst, Imgproc.MORPH_BLACKHAT, kernel);\n //Displaying the image\n HighGui.imshow(\"Blackhat Gradient\", dst);\n HighGui.waitKey();\n }\n}"
}
] |
Computer Programming - Basic Syntax | Let’s start with a little coding, which will really make you a computer programmer. We are going to write a single-line computer program to write Hello, World! on your screen. Let’s see how it can be written using different programming languages.
Try the following example using our online compiler option available at www.compileonline.com.
For most of the examples given in this tutorial, you will find a Try it option in our website code sections at the top right corner that will take you to the online compiler.
Try to change the content inside printf(), i.e., type anything in place of Hello World! and then check its result. It just prints whatever you keep inside the two double quotes.
#include <stdio.h>
int main() {
/* printf() function to write Hello, World! */
printf( "Hello, World!" );
}
which produces the following result −
Hello, World!
This little Hello World program will help us understand various basic concepts related to C Programming.
For now, just forget about the #include <stdio.h> statement, but keep a note that you have to put this statement at the top of a C program.
Every C program starts with main(), which is called the main function, and then it is followed by a left curly brace. The rest of the program instruction is written in between and finally a right curly brace ends the program.
The coding part inside these two curly braces is called the program body. The left curly brace can be in the same line as main(){ or in the next line like it has been mentioned in the above program.
Functions are small units of programs and they are used to carry out a specific task. For example, the above program makes use of two functions: main() and printf(). Here, the function main() provides the entry point for the program execution and the other function printf() is being used to print an information on the computer screen.
You can write your own functions which we will see in a separate chapter, but C programming itself provides various built-in functions like main(), printf(), etc., which we can use in our programs based on our requirement.
Some of the programming languages use the word sub-routine instead of function, but their functionality is more or less the same.
A C program can have statements enclosed inside /*.....*/. Such statements are called comments and these comments are used to make the programs user friendly and easy to understand. The good thing about comments is that they are completely ignored by compilers and interpreters. So you can use whatever language you want to write your comments.
When we write a program using any programming language, we use various printable characters to prepare programming statements. These printable characters are a, b, c,......z, A, B, C,.....Z, 1, 2, 3,...... 0, !, @, #, $, %, ^, &, *, (, ), -, _, +, =, \, |, {, }, [, ], :, ;, <, >, ?, /, \, ~. `. ", '. Hope I'm not missing any printable characters from your keyboard.
Apart from these characters, there are some characters which we use very frequently but they are invisible in your program and these characters are spaces, tabs (\t), new lines(\n). These characters are called whitespaces.
These three important whitespace characters are common in all the programming languages and they remain invisible in your text document −
A line containing only whitespace, possibly with a comment, is known as a blank line, and a C compiler totally ignores it. Whitespace is the term used in C to describe blanks, tabs, newline characters, and comments. So you can write printf("Hello, World!" ); as shown below. Here all the created spaces around "Hello, World!" are useless and the compiler will ignore them at the time of compilation.
#include <stdio.h>
int main() {
/* printf() function to write Hello, World! */
printf( "Hello, World!" );
}
which produces the following result −
Hello, World!
If we make all these whitespace characters visible, then the above program will look like this and you will not be able to compile it −
#include <stdio.h>\n
\n
int main()\n
{
\n
\t/* printf() function to write Hello, World! */
\n
\tprintf(\t"Hello, World!"\t);\n
\n
}\n
Every individual statement in a C Program must be ended with a semicolon (;), for example, if you want to write "Hello, World!" twice, then it will be written as follows −
#include <stdio.h>
int main() {
/* printf() function to write Hello, World! */
printf( "Hello, World!\n" );
printf( "Hello, World!" );
}
This program will produce the following result −
Hello, World!
Hello, World!
Here, we are using a new line character \n in the first printf() function to create a new line. Let us see what happens if we do not use this new line character −
#include <stdio.h>
int main() {
/* printf() function to write Hello, World! */
printf( "Hello, World!" );
printf( "Hello, World!" );
}
This program will produce the following result −
Hello, World! Hello, World!
We will learn identifiers and keywords in next few chapters.
Let us understand how the above C program works. First of all, the above program is converted into a binary format using C compiler. So let’s put this code in test.c file and compile it as follows −
$gcc test.c -o demo
If there is any grammatical error (Syntax errors in computer terminologies), then we fix it before converting it into binary format. If everything goes fine, then it produces a binary file called demo. Finally, we execute the produced binary demo as follows −
$./demo
which produces the following result −
Hello, World!
Here, when we execute the binary a.out file, the computer enters inside the program starting from main() and encounters a printf() statement. Keep a note that the line inside /*....*/ is a comment and it is filtered at the time of compilation. So printf() function instructs the computer to print the given line at the computer screen. Finally, it encounters a right curly brace which indicates the end of main() function and exits the program.
If you do not follow the rules defined by the programing language, then at the time of compilation, you will get syntax errors and the program will not be compiled. From syntax point of view, even a single dot or comma or a single semicolon matters and you should take care of such small syntax as well. In the following example, we have skipped a semicolon, let's try to compile the program −
#include <stdio.h>
main() {
printf("Hello, World!")
}
This program will produce the following result −
main.c: In function 'main':
main.c:7:1: error: expected ';' before '}' token
}
^
So the bottom-line is that if you are not following proper syntax defined by the programming language in your program, then you will get syntax errors. Before attempting another compilation, you will need to fix them and then proceed.
Following is the equivalent program written in Java. This program will also produce the same result Hello, World!.
public class HelloWorld {
public static void main(String []args) {
/* println() function to write Hello, World! */
System.out.println("Hello, World!");
}
}
which produces the following result −
Hello, World!
Following is the equivalent program written in Python. This program will also produce the same result Hello, World!.
# print function to write Hello, World! */
print "Hello, World!"
which produces the following result −
Hello, World!
Hope you noted that for C and Java examples, first we are compiling the programs and then executing the produced binaries, but in Python program, we are directly executing it. As we explained in the previous chapter, Python is an interpreted language and it does not need an intermediate step called compilation.
Python does not require a semicolon (;) to terminate a statement, rather a new line always means termination of the statement.
107 Lectures
13.5 hours
Arnab Chakraborty
106 Lectures
8 hours
Arnab Chakraborty
99 Lectures
6 hours
Arnab Chakraborty
46 Lectures
2.5 hours
Shweta
70 Lectures
9 hours
Abhilash Nelson
52 Lectures
7 hours
Abhishek And Pukhraj
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2387,
"s": 2140,
"text": "Let’s start with a little coding, which will really make you a computer programmer. We are going to write a single-line computer program to write Hello, World! on your screen. Let’s see how it can be written using different programming languages."
},
{
"code": null,
"e": 2482,
"s": 2387,
"text": "Try the following example using our online compiler option available at www.compileonline.com."
},
{
"code": null,
"e": 2657,
"s": 2482,
"text": "For most of the examples given in this tutorial, you will find a Try it option in our website code sections at the top right corner that will take you to the online compiler."
},
{
"code": null,
"e": 2835,
"s": 2657,
"text": "Try to change the content inside printf(), i.e., type anything in place of Hello World! and then check its result. It just prints whatever you keep inside the two double quotes."
},
{
"code": null,
"e": 2950,
"s": 2835,
"text": "#include <stdio.h>\n\nint main() {\n /* printf() function to write Hello, World! */\n printf( \"Hello, World!\" );\n}"
},
{
"code": null,
"e": 2988,
"s": 2950,
"text": "which produces the following result −"
},
{
"code": null,
"e": 3003,
"s": 2988,
"text": "Hello, World!\n"
},
{
"code": null,
"e": 3108,
"s": 3003,
"text": "This little Hello World program will help us understand various basic concepts related to C Programming."
},
{
"code": null,
"e": 3248,
"s": 3108,
"text": "For now, just forget about the #include <stdio.h> statement, but keep a note that you have to put this statement at the top of a C program."
},
{
"code": null,
"e": 3474,
"s": 3248,
"text": "Every C program starts with main(), which is called the main function, and then it is followed by a left curly brace. The rest of the program instruction is written in between and finally a right curly brace ends the program."
},
{
"code": null,
"e": 3673,
"s": 3474,
"text": "The coding part inside these two curly braces is called the program body. The left curly brace can be in the same line as main(){ or in the next line like it has been mentioned in the above program."
},
{
"code": null,
"e": 4010,
"s": 3673,
"text": "Functions are small units of programs and they are used to carry out a specific task. For example, the above program makes use of two functions: main() and printf(). Here, the function main() provides the entry point for the program execution and the other function printf() is being used to print an information on the computer screen."
},
{
"code": null,
"e": 4233,
"s": 4010,
"text": "You can write your own functions which we will see in a separate chapter, but C programming itself provides various built-in functions like main(), printf(), etc., which we can use in our programs based on our requirement."
},
{
"code": null,
"e": 4363,
"s": 4233,
"text": "Some of the programming languages use the word sub-routine instead of function, but their functionality is more or less the same."
},
{
"code": null,
"e": 4708,
"s": 4363,
"text": "A C program can have statements enclosed inside /*.....*/. Such statements are called comments and these comments are used to make the programs user friendly and easy to understand. The good thing about comments is that they are completely ignored by compilers and interpreters. So you can use whatever language you want to write your comments."
},
{
"code": null,
"e": 5077,
"s": 4708,
"text": "When we write a program using any programming language, we use various printable characters to prepare programming statements. These printable characters are a, b, c,......z, A, B, C,.....Z, 1, 2, 3,...... 0, !, @, #, $, %, ^, &, *, (, ), -, _, +, =, \\, |, {, }, [, ], :, ;, <, >, ?, /, \\, ~. `. \", '. Hope I'm not missing any printable characters from your keyboard."
},
{
"code": null,
"e": 5300,
"s": 5077,
"text": "Apart from these characters, there are some characters which we use very frequently but they are invisible in your program and these characters are spaces, tabs (\\t), new lines(\\n). These characters are called whitespaces."
},
{
"code": null,
"e": 5438,
"s": 5300,
"text": "These three important whitespace characters are common in all the programming languages and they remain invisible in your text document −"
},
{
"code": null,
"e": 5838,
"s": 5438,
"text": "A line containing only whitespace, possibly with a comment, is known as a blank line, and a C compiler totally ignores it. Whitespace is the term used in C to describe blanks, tabs, newline characters, and comments. So you can write printf(\"Hello, World!\" ); as shown below. Here all the created spaces around \"Hello, World!\" are useless and the compiler will ignore them at the time of compilation."
},
{
"code": null,
"e": 5970,
"s": 5838,
"text": "#include <stdio.h>\n\nint main() {\n\n /* printf() function to write Hello, World! */\n \n printf( \"Hello, World!\" );\n \n}"
},
{
"code": null,
"e": 6008,
"s": 5970,
"text": "which produces the following result −"
},
{
"code": null,
"e": 6023,
"s": 6008,
"text": "Hello, World!\n"
},
{
"code": null,
"e": 6159,
"s": 6023,
"text": "If we make all these whitespace characters visible, then the above program will look like this and you will not be able to compile it −"
},
{
"code": null,
"e": 6309,
"s": 6159,
"text": "#include <stdio.h>\\n\n\\n\nint main()\\n\n{\n \\n\n \\t/* printf() function to write Hello, World! */\n \\n \n \\tprintf(\\t\"Hello, World!\"\\t);\\n\n \\n\n}\\n"
},
{
"code": null,
"e": 6481,
"s": 6309,
"text": "Every individual statement in a C Program must be ended with a semicolon (;), for example, if you want to write \"Hello, World!\" twice, then it will be written as follows −"
},
{
"code": null,
"e": 6628,
"s": 6481,
"text": "#include <stdio.h>\n\nint main() {\n /* printf() function to write Hello, World! */\n printf( \"Hello, World!\\n\" );\n printf( \"Hello, World!\" );\n}"
},
{
"code": null,
"e": 6677,
"s": 6628,
"text": "This program will produce the following result −"
},
{
"code": null,
"e": 6707,
"s": 6677,
"text": "Hello, World! \nHello, World!\n"
},
{
"code": null,
"e": 6870,
"s": 6707,
"text": "Here, we are using a new line character \\n in the first printf() function to create a new line. Let us see what happens if we do not use this new line character −"
},
{
"code": null,
"e": 7015,
"s": 6870,
"text": "#include <stdio.h>\n\nint main() {\n /* printf() function to write Hello, World! */\n printf( \"Hello, World!\" );\n printf( \"Hello, World!\" );\n}"
},
{
"code": null,
"e": 7064,
"s": 7015,
"text": "This program will produce the following result −"
},
{
"code": null,
"e": 7093,
"s": 7064,
"text": "Hello, World! Hello, World!\n"
},
{
"code": null,
"e": 7154,
"s": 7093,
"text": "We will learn identifiers and keywords in next few chapters."
},
{
"code": null,
"e": 7353,
"s": 7154,
"text": "Let us understand how the above C program works. First of all, the above program is converted into a binary format using C compiler. So let’s put this code in test.c file and compile it as follows −"
},
{
"code": null,
"e": 7374,
"s": 7353,
"text": "$gcc test.c -o demo\n"
},
{
"code": null,
"e": 7634,
"s": 7374,
"text": "If there is any grammatical error (Syntax errors in computer terminologies), then we fix it before converting it into binary format. If everything goes fine, then it produces a binary file called demo. Finally, we execute the produced binary demo as follows −"
},
{
"code": null,
"e": 7643,
"s": 7634,
"text": "$./demo\n"
},
{
"code": null,
"e": 7681,
"s": 7643,
"text": "which produces the following result −"
},
{
"code": null,
"e": 7696,
"s": 7681,
"text": "Hello, World!\n"
},
{
"code": null,
"e": 8141,
"s": 7696,
"text": "Here, when we execute the binary a.out file, the computer enters inside the program starting from main() and encounters a printf() statement. Keep a note that the line inside /*....*/ is a comment and it is filtered at the time of compilation. So printf() function instructs the computer to print the given line at the computer screen. Finally, it encounters a right curly brace which indicates the end of main() function and exits the program."
},
{
"code": null,
"e": 8535,
"s": 8141,
"text": "If you do not follow the rules defined by the programing language, then at the time of compilation, you will get syntax errors and the program will not be compiled. From syntax point of view, even a single dot or comma or a single semicolon matters and you should take care of such small syntax as well. In the following example, we have skipped a semicolon, let's try to compile the program −"
},
{
"code": null,
"e": 8593,
"s": 8535,
"text": "#include <stdio.h>\n\nmain() {\n printf(\"Hello, World!\")\n}"
},
{
"code": null,
"e": 8642,
"s": 8593,
"text": "This program will produce the following result −"
},
{
"code": null,
"e": 8726,
"s": 8642,
"text": "main.c: In function 'main':\nmain.c:7:1: error: expected ';' before '}' token\n }\n ^\n"
},
{
"code": null,
"e": 8961,
"s": 8726,
"text": "So the bottom-line is that if you are not following proper syntax defined by the programming language in your program, then you will get syntax errors. Before attempting another compilation, you will need to fix them and then proceed."
},
{
"code": null,
"e": 9076,
"s": 8961,
"text": "Following is the equivalent program written in Java. This program will also produce the same result Hello, World!."
},
{
"code": null,
"e": 9256,
"s": 9076,
"text": "public class HelloWorld { \n public static void main(String []args) {\n /* println() function to write Hello, World! */\n System.out.println(\"Hello, World!\"); \n }\n}"
},
{
"code": null,
"e": 9294,
"s": 9256,
"text": "which produces the following result −"
},
{
"code": null,
"e": 9309,
"s": 9294,
"text": "Hello, World!\n"
},
{
"code": null,
"e": 9426,
"s": 9309,
"text": "Following is the equivalent program written in Python. This program will also produce the same result Hello, World!."
},
{
"code": null,
"e": 9492,
"s": 9426,
"text": "# print function to write Hello, World! */\nprint \"Hello, World!\""
},
{
"code": null,
"e": 9530,
"s": 9492,
"text": "which produces the following result −"
},
{
"code": null,
"e": 9545,
"s": 9530,
"text": "Hello, World!\n"
},
{
"code": null,
"e": 9858,
"s": 9545,
"text": "Hope you noted that for C and Java examples, first we are compiling the programs and then executing the produced binaries, but in Python program, we are directly executing it. As we explained in the previous chapter, Python is an interpreted language and it does not need an intermediate step called compilation."
},
{
"code": null,
"e": 9985,
"s": 9858,
"text": "Python does not require a semicolon (;) to terminate a statement, rather a new line always means termination of the statement."
},
{
"code": null,
"e": 10022,
"s": 9985,
"text": "\n 107 Lectures \n 13.5 hours \n"
},
{
"code": null,
"e": 10041,
"s": 10022,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 10075,
"s": 10041,
"text": "\n 106 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 10094,
"s": 10075,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 10127,
"s": 10094,
"text": "\n 99 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 10146,
"s": 10127,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 10181,
"s": 10146,
"text": "\n 46 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 10189,
"s": 10181,
"text": " Shweta"
},
{
"code": null,
"e": 10222,
"s": 10189,
"text": "\n 70 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 10239,
"s": 10222,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 10272,
"s": 10239,
"text": "\n 52 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 10294,
"s": 10272,
"text": " Abhishek And Pukhraj"
},
{
"code": null,
"e": 10301,
"s": 10294,
"text": " Print"
},
{
"code": null,
"e": 10312,
"s": 10301,
"text": " Add Notes"
}
] |
A Cloud ML first: Google’s AI Platform Deep Learning Container with NVIDIA Tensor Core A100 GPU | by James Green | Towards Data Science | A pivotal step forwards in Cloud-based deep learning; for the first time, data scientists can access the unprecedented acceleration of the NVIDIA A100 Tensor Core GPU.
In this article, we provide an introduction to Google’s AI Platform and Deep Learning Containers, before exploring the astonishing performance of the A100 GPU.
For those of you not familiar with AI Platform, essentially it’s a suite of services on the Google Cloud Platform specifically targeted at building, deploying, and managing machine learning models in the Cloud.
AI Platform is designed to make it easy for data scientists and data engineers to streamline their ML workflows. We use it a lot with AutoML (Google’s point-and-click ML engine) but in addition, it supports the training, prediction, and version management of advanced models built using Tensorflow.
Take advantage of Google’s expertise in AI by infusing our cutting-edge AI technologies into your applications via tools like TPUs and TensorFlow Google Cloud
AI Platform has a suite of services designed to support the activities seen in a typical ML workflow.
In this article, we will be focusing on Deep Learning Containers (these fall under the Pipeline section in the diagram above). Whilst the other services are out of scope for this article, we have included a brief description of each together with some links in case you would like to learn more.
1. Prepare
We typically first prepare (ingest, cleanse, feature engineer) our data in BigQuery Datasets, collections of tables in Google Clouds hyper-scale data warehouse.
Google offers a Data Labelling Service for labeling training data (typically we use for the classification of images, video, audio, and text).
2. Build
We’ve already mentioned AutoML, the zero code platform for training models.
We use AI Platform Notebooks (hosted Jupyter Notebooks) for building custom models (typically Tensorflow or SkLearn).
Finally, we use AI Platform Training for convenient model training.
3. Validate
Explainable AI is a great suite of tools that helps you understand your model’s outputs, verify the model behavior, recognize bias in your models, and get ideas for ways to improve your model and your training data. This really helps to take the guesswork out of activities such as model tuning.
AI Platform Vizier takes this a step further, and offers a black-box optimization service, to tune hyperparameters and optimize your model’s output.
4. Deploy
Whether you have a model trained using no-code AutoML, or an advanced Tensorflow model built using AI Platform Notebooks, AI Platform offers a number of services to help deploy models and generate predictions.
AI Platform Prediction manages the infrastructure needed to run your model and makes it available for online and batch prediction requests.
AutoML Vision Edge helps deploy edge models (run on local devices e.g. smartphone, IoT device) and can trigger real-time actions based on local data.
TensorFlow Enterprise offers enterprise-grade support for your TensorFlow instance.
5. ML Pipelines (ML Ops)
ML Ops is the practice of deploying robust, repeatable, and scalable ML pipelines to manage your models. AI Platform offers a number of services to assist with these pipelines.
AI Platform Pipelines provides support for creating ML pipelines using either Kubeflow Pipelines or TensorFlow Extended (TFX).
Continuous evaluation helps you monitor the performance of your models and provides continual feedback on how your models are performing over time.
Deep Learning VM Image supports easy provisioning of Cloud VMs for deep learning ML applications.
Finally, Deep Learning Containers provides preconfigured and optimized containers for deep learning environments.
AI Platform Deep Learning Containers provides you with performance optimized, consistent environments to help you prototype and implement workflows quickly. Deep Learning Container images come with the latest machine learning data science frameworks, libraries, and tools pre-installed.Google Cloud
It’s easy to underestimate how much time it takes to get a machine learning project up and running. All too often, these projects require you to manage the compatibility and complexities of an ever-evolving software stack, which can be frustrating, time-consuming, and keep you from what you really want to do: spending time iterating and refining your model.
Deep Learning Containers were designed to accelerate this process.
All Deep Learning Containers have a pre-configured Jupyter environment, so each can be pulled and used directly as a prototyping space. First, make sure you have the gcloud tool installed and configured. Then, determine the container that you would like to use. All containers are hosted under gcr.io/deeplearning-platform-release, and can be listed with the command:
gcloud container images list --repository=”gcr.io/deeplearning-platform-release”
Each container provides a Python3 environment consistent with the corresponding Deep Learning VM, including the selected data science framework, conda, the NVIDIA stack for GPU images (CUDA, cuDNN, NCCL), and a host of other supporting packages and tools.
Example creating a CPU Tensorflow container
This is really straightforward. The following command will start the TensorFlow Deep Learning Container in detached mode, bind the running Jupyter server to port 8080 on the local machine, and mount /path/to/local/dir to /home in the container.
docker run -d -p 8080:8080 -v /path/to/local/dir:/home \gcr.io/deeplearning-platform-release/tf-cpu.1–13
Then, the running JupyterLab instance can be accessed at localhost:8080. Make sure to develop in /home, as any other files will be removed when the container is stopped.
If you would like to use the GPU-enabled containers, you will need a CUDA 10 compatible GPU, the associated driver, and nvidia-docker installed. Then, you can run a similar command.
docker run --runtime=nvidia -d -p 8080:8080 -v /path/to/local/dir:/home \gcr.io/deeplearning-platform-release/tf-gpu.1–13
And now you simply develop your model using this container.
So, now you’re orientated with Google Cloud AI Platform and it’s Deep Learning Containers, let’s explore a Cloud-first; the ability to access a Deep Learning Container powered by the NVIDIA A100 Tensor Core GPU.
The A100 GPU. Accelerating the Most Important Work of Our Time.Nvidia
So what does that actually mean in real-world terms?
The first thing to note is this line of GPUs was specifically designed with deep learning and other applications of high-compute AI in mind. The second thing to note is compared to its predecessor, the A100 provides up to 20X higher performance with zero code changes. That’s a massive leap.
A100 GPU technical specification
Highlights of the A100’s data sheet include:
40GB of GPU memory
1.6 TB/sec memory bandwidth
312 teraFLOPS of deep learning (20x that of the predecessor)
250W-450W max power consumption
structural sparsity architecture of the A100s Tensor Cores supports up to 2x performance gains for “sparse” models (models whose parameter sets contain lots of zeros, great for NLP applications).
And if one of these powerhouses isn’t enough for your use case, don’t worry because thanks to some clever SDK support from NVIDIA, these will scale to 1,000s of A100 GPUs.
BERT stands for Bidirectional Encoder Representations from Transformersis. Recently published by Google, BERT is a natural language processing (NLP) ML model. BERT is frequently used for benchmarking due to the high-compute needed to fully train the model.
The A100 produced some astonishing results:
So what are the A100 options available in Google Ai Platforms’ Deep Learning Containers?
A whopping 16 GPUs per VM
For demanding workloads, you can opt for the a2-megagpu-16g Deep Learning Container. With 16 A100 GPUs, this offers an astonishing 640 GB of GPU memory and providing an effective performance of up to 10 petaflops of FP16 or 20 petaOps of int8 in a single VM when using the new sparsity feature. Wow. We had to read these numbers twice.
Then we had to double-take on the system memory; a whopping 1.3 TB. And don’t worry about any bottlenecks accessing it, the memory bus supports up to 9.6 TB/s.
Enough to consume the most demanding of workloads...
Of course, A100 powered VMs are available in smaller configurations too, allowing you to match your application’s needs for GPU compute power.
1. Read the Google Cloud AI Platform release notes
2. Learn more about Ancoris Data, Analytics & AI
3. Connect with the author | [
{
"code": null,
"e": 339,
"s": 171,
"text": "A pivotal step forwards in Cloud-based deep learning; for the first time, data scientists can access the unprecedented acceleration of the NVIDIA A100 Tensor Core GPU."
},
{
"code": null,
"e": 499,
"s": 339,
"text": "In this article, we provide an introduction to Google’s AI Platform and Deep Learning Containers, before exploring the astonishing performance of the A100 GPU."
},
{
"code": null,
"e": 710,
"s": 499,
"text": "For those of you not familiar with AI Platform, essentially it’s a suite of services on the Google Cloud Platform specifically targeted at building, deploying, and managing machine learning models in the Cloud."
},
{
"code": null,
"e": 1009,
"s": 710,
"text": "AI Platform is designed to make it easy for data scientists and data engineers to streamline their ML workflows. We use it a lot with AutoML (Google’s point-and-click ML engine) but in addition, it supports the training, prediction, and version management of advanced models built using Tensorflow."
},
{
"code": null,
"e": 1168,
"s": 1009,
"text": "Take advantage of Google’s expertise in AI by infusing our cutting-edge AI technologies into your applications via tools like TPUs and TensorFlow Google Cloud"
},
{
"code": null,
"e": 1270,
"s": 1168,
"text": "AI Platform has a suite of services designed to support the activities seen in a typical ML workflow."
},
{
"code": null,
"e": 1566,
"s": 1270,
"text": "In this article, we will be focusing on Deep Learning Containers (these fall under the Pipeline section in the diagram above). Whilst the other services are out of scope for this article, we have included a brief description of each together with some links in case you would like to learn more."
},
{
"code": null,
"e": 1577,
"s": 1566,
"text": "1. Prepare"
},
{
"code": null,
"e": 1738,
"s": 1577,
"text": "We typically first prepare (ingest, cleanse, feature engineer) our data in BigQuery Datasets, collections of tables in Google Clouds hyper-scale data warehouse."
},
{
"code": null,
"e": 1881,
"s": 1738,
"text": "Google offers a Data Labelling Service for labeling training data (typically we use for the classification of images, video, audio, and text)."
},
{
"code": null,
"e": 1890,
"s": 1881,
"text": "2. Build"
},
{
"code": null,
"e": 1966,
"s": 1890,
"text": "We’ve already mentioned AutoML, the zero code platform for training models."
},
{
"code": null,
"e": 2084,
"s": 1966,
"text": "We use AI Platform Notebooks (hosted Jupyter Notebooks) for building custom models (typically Tensorflow or SkLearn)."
},
{
"code": null,
"e": 2152,
"s": 2084,
"text": "Finally, we use AI Platform Training for convenient model training."
},
{
"code": null,
"e": 2164,
"s": 2152,
"text": "3. Validate"
},
{
"code": null,
"e": 2460,
"s": 2164,
"text": "Explainable AI is a great suite of tools that helps you understand your model’s outputs, verify the model behavior, recognize bias in your models, and get ideas for ways to improve your model and your training data. This really helps to take the guesswork out of activities such as model tuning."
},
{
"code": null,
"e": 2609,
"s": 2460,
"text": "AI Platform Vizier takes this a step further, and offers a black-box optimization service, to tune hyperparameters and optimize your model’s output."
},
{
"code": null,
"e": 2619,
"s": 2609,
"text": "4. Deploy"
},
{
"code": null,
"e": 2829,
"s": 2619,
"text": "Whether you have a model trained using no-code AutoML, or an advanced Tensorflow model built using AI Platform Notebooks, AI Platform offers a number of services to help deploy models and generate predictions."
},
{
"code": null,
"e": 2969,
"s": 2829,
"text": "AI Platform Prediction manages the infrastructure needed to run your model and makes it available for online and batch prediction requests."
},
{
"code": null,
"e": 3119,
"s": 2969,
"text": "AutoML Vision Edge helps deploy edge models (run on local devices e.g. smartphone, IoT device) and can trigger real-time actions based on local data."
},
{
"code": null,
"e": 3203,
"s": 3119,
"text": "TensorFlow Enterprise offers enterprise-grade support for your TensorFlow instance."
},
{
"code": null,
"e": 3228,
"s": 3203,
"text": "5. ML Pipelines (ML Ops)"
},
{
"code": null,
"e": 3405,
"s": 3228,
"text": "ML Ops is the practice of deploying robust, repeatable, and scalable ML pipelines to manage your models. AI Platform offers a number of services to assist with these pipelines."
},
{
"code": null,
"e": 3532,
"s": 3405,
"text": "AI Platform Pipelines provides support for creating ML pipelines using either Kubeflow Pipelines or TensorFlow Extended (TFX)."
},
{
"code": null,
"e": 3680,
"s": 3532,
"text": "Continuous evaluation helps you monitor the performance of your models and provides continual feedback on how your models are performing over time."
},
{
"code": null,
"e": 3778,
"s": 3680,
"text": "Deep Learning VM Image supports easy provisioning of Cloud VMs for deep learning ML applications."
},
{
"code": null,
"e": 3892,
"s": 3778,
"text": "Finally, Deep Learning Containers provides preconfigured and optimized containers for deep learning environments."
},
{
"code": null,
"e": 4191,
"s": 3892,
"text": "AI Platform Deep Learning Containers provides you with performance optimized, consistent environments to help you prototype and implement workflows quickly. Deep Learning Container images come with the latest machine learning data science frameworks, libraries, and tools pre-installed.Google Cloud"
},
{
"code": null,
"e": 4551,
"s": 4191,
"text": "It’s easy to underestimate how much time it takes to get a machine learning project up and running. All too often, these projects require you to manage the compatibility and complexities of an ever-evolving software stack, which can be frustrating, time-consuming, and keep you from what you really want to do: spending time iterating and refining your model."
},
{
"code": null,
"e": 4618,
"s": 4551,
"text": "Deep Learning Containers were designed to accelerate this process."
},
{
"code": null,
"e": 4986,
"s": 4618,
"text": "All Deep Learning Containers have a pre-configured Jupyter environment, so each can be pulled and used directly as a prototyping space. First, make sure you have the gcloud tool installed and configured. Then, determine the container that you would like to use. All containers are hosted under gcr.io/deeplearning-platform-release, and can be listed with the command:"
},
{
"code": null,
"e": 5067,
"s": 4986,
"text": "gcloud container images list --repository=”gcr.io/deeplearning-platform-release”"
},
{
"code": null,
"e": 5323,
"s": 5067,
"text": "Each container provides a Python3 environment consistent with the corresponding Deep Learning VM, including the selected data science framework, conda, the NVIDIA stack for GPU images (CUDA, cuDNN, NCCL), and a host of other supporting packages and tools."
},
{
"code": null,
"e": 5367,
"s": 5323,
"text": "Example creating a CPU Tensorflow container"
},
{
"code": null,
"e": 5612,
"s": 5367,
"text": "This is really straightforward. The following command will start the TensorFlow Deep Learning Container in detached mode, bind the running Jupyter server to port 8080 on the local machine, and mount /path/to/local/dir to /home in the container."
},
{
"code": null,
"e": 5717,
"s": 5612,
"text": "docker run -d -p 8080:8080 -v /path/to/local/dir:/home \\gcr.io/deeplearning-platform-release/tf-cpu.1–13"
},
{
"code": null,
"e": 5887,
"s": 5717,
"text": "Then, the running JupyterLab instance can be accessed at localhost:8080. Make sure to develop in /home, as any other files will be removed when the container is stopped."
},
{
"code": null,
"e": 6069,
"s": 5887,
"text": "If you would like to use the GPU-enabled containers, you will need a CUDA 10 compatible GPU, the associated driver, and nvidia-docker installed. Then, you can run a similar command."
},
{
"code": null,
"e": 6191,
"s": 6069,
"text": "docker run --runtime=nvidia -d -p 8080:8080 -v /path/to/local/dir:/home \\gcr.io/deeplearning-platform-release/tf-gpu.1–13"
},
{
"code": null,
"e": 6251,
"s": 6191,
"text": "And now you simply develop your model using this container."
},
{
"code": null,
"e": 6463,
"s": 6251,
"text": "So, now you’re orientated with Google Cloud AI Platform and it’s Deep Learning Containers, let’s explore a Cloud-first; the ability to access a Deep Learning Container powered by the NVIDIA A100 Tensor Core GPU."
},
{
"code": null,
"e": 6533,
"s": 6463,
"text": "The A100 GPU. Accelerating the Most Important Work of Our Time.Nvidia"
},
{
"code": null,
"e": 6586,
"s": 6533,
"text": "So what does that actually mean in real-world terms?"
},
{
"code": null,
"e": 6878,
"s": 6586,
"text": "The first thing to note is this line of GPUs was specifically designed with deep learning and other applications of high-compute AI in mind. The second thing to note is compared to its predecessor, the A100 provides up to 20X higher performance with zero code changes. That’s a massive leap."
},
{
"code": null,
"e": 6911,
"s": 6878,
"text": "A100 GPU technical specification"
},
{
"code": null,
"e": 6956,
"s": 6911,
"text": "Highlights of the A100’s data sheet include:"
},
{
"code": null,
"e": 6975,
"s": 6956,
"text": "40GB of GPU memory"
},
{
"code": null,
"e": 7003,
"s": 6975,
"text": "1.6 TB/sec memory bandwidth"
},
{
"code": null,
"e": 7064,
"s": 7003,
"text": "312 teraFLOPS of deep learning (20x that of the predecessor)"
},
{
"code": null,
"e": 7096,
"s": 7064,
"text": "250W-450W max power consumption"
},
{
"code": null,
"e": 7292,
"s": 7096,
"text": "structural sparsity architecture of the A100s Tensor Cores supports up to 2x performance gains for “sparse” models (models whose parameter sets contain lots of zeros, great for NLP applications)."
},
{
"code": null,
"e": 7464,
"s": 7292,
"text": "And if one of these powerhouses isn’t enough for your use case, don’t worry because thanks to some clever SDK support from NVIDIA, these will scale to 1,000s of A100 GPUs."
},
{
"code": null,
"e": 7721,
"s": 7464,
"text": "BERT stands for Bidirectional Encoder Representations from Transformersis. Recently published by Google, BERT is a natural language processing (NLP) ML model. BERT is frequently used for benchmarking due to the high-compute needed to fully train the model."
},
{
"code": null,
"e": 7765,
"s": 7721,
"text": "The A100 produced some astonishing results:"
},
{
"code": null,
"e": 7854,
"s": 7765,
"text": "So what are the A100 options available in Google Ai Platforms’ Deep Learning Containers?"
},
{
"code": null,
"e": 7880,
"s": 7854,
"text": "A whopping 16 GPUs per VM"
},
{
"code": null,
"e": 8216,
"s": 7880,
"text": "For demanding workloads, you can opt for the a2-megagpu-16g Deep Learning Container. With 16 A100 GPUs, this offers an astonishing 640 GB of GPU memory and providing an effective performance of up to 10 petaflops of FP16 or 20 petaOps of int8 in a single VM when using the new sparsity feature. Wow. We had to read these numbers twice."
},
{
"code": null,
"e": 8376,
"s": 8216,
"text": "Then we had to double-take on the system memory; a whopping 1.3 TB. And don’t worry about any bottlenecks accessing it, the memory bus supports up to 9.6 TB/s."
},
{
"code": null,
"e": 8429,
"s": 8376,
"text": "Enough to consume the most demanding of workloads..."
},
{
"code": null,
"e": 8572,
"s": 8429,
"text": "Of course, A100 powered VMs are available in smaller configurations too, allowing you to match your application’s needs for GPU compute power."
},
{
"code": null,
"e": 8623,
"s": 8572,
"text": "1. Read the Google Cloud AI Platform release notes"
},
{
"code": null,
"e": 8672,
"s": 8623,
"text": "2. Learn more about Ancoris Data, Analytics & AI"
}
] |
Filter a Pandas DataFrame by a Partial String or Pattern in 8 Ways | by Susan Maina | Towards Data Science | Filtering a DataFrame refers to checking its contents and returning only those that fit certain criteria. It is part of the data analysis task known as data wrangling and is efficiently done using the Pandas library of Python.
The idea is that once you have filtered this data, you can analyze it separately and gain insights that might be unique to this group, and inform the predictive modeling steps of the project moving forward.
In this article, we will use functions such as Series.isin() and Series.str.contains() to filter the data. I minimized the use of apply() and Lambda functions which use more code and are confusing to many people including myself. However, I will explain the code and include links to related articles.
We will use the Netflix dataset from Kaggle which contains details of TV shows and movies including the title, director, the cast, age rating, year of release, and duration. Let us now import the required libraries and load the dataset into our Jupyter notebook.
import pandas as pddata = pd.read_csv('netflix_titles_nov_2019.csv')data.head()
Here, we want to filter by the contents of a particular column. We will use the Series.isin([list_of_values] ) function from Pandas which returns a ‘mask’ of True for every element in the column that exactly matches or False if it does not match any of the list values in the isin() function. Note that you must always include the value(s) in square brackets even if it is just one.
mask = data['type'].isin(['TV Show'])#display the maskmask.head()
We then apply this mask to the whole DataFrame to return the rows where the condition was True. Note how the index positions where the mask was True above are the only rows returned in the filtered DataFrame below.
#Display first 5 rows #of the filtered datadata[mask].head()
Note: df.loc[mask] generates the same results as df[mask]. This is especially useful when you want to select a few columns to display.
data.loc[mask, ['title','country','duration']]
Other ways to generate the mask above;
If you do not want to deal with a mix of upper and lowercase letters in the isin() function, first convert all the column’s elements into lowercase.
mask = data['type'].str.lower().isin(['tv show'])
We can also use the == equality operator which compares if two objects are the same. This will compare whether each element in a column is equal to the string provided.
mask = (data['type'] == 'TV Show')
We can provide a list of strings like isin([‘str1’,’str2']) and check if a column’s elements match any of them. The two masks below return the same results.
mask = data[’type’].isin([’Movie’,’TV Show’])#ormask = (data[’type’] == 'Movie’) | (data[’type’] == 'TV Show’)
The mask returned will be all Trues because the ‘type’ column contains only ‘Movie’ and ‘TV Show’ categories.
Here, we want to check if a sub-string is present in a column.
For example, the ‘listed-in’ column contains the genres that each movie or show belongs to, separated by commas. I want to filter and return only those that have a ‘horror’ element in them because right now Halloween is upon us.
We will use the string method Series.str.contains(‘pattern’, case=False, na=False) where ‘pattern’ is the substring to search for, and case=False implies case insensitivity. na=False means that any NaN values in the column will be returned as False (meaning without the pattern) instead of as NaN which removes the boolean identity from the mask.
mask = data['listed_in'].str.contains('horror', case=False, na=False)
We will then apply the mask to our data and display three sample rows of the filtered dataframe.
data[mask].sample(3)
Other examples:
We can also check for the presence of symbols in a column. For example, the ‘cast’ column contains the actors separated by commas, and we can check for rows where there is only one actor. This is by checking for rows with a comma (,) and then applying the filtering mask to the data using a tilde (~) to negate the statement.
mask = data['cast'].str.contains(',', na=False)data[~mask].head()
But now these results have NaNs because we used na=False and the tilde returns all rows where the mask was False. We will use df.dropna(axis=0, subset=’cast)to the filtered data. We use axis=0 to mean row-wise because we want to drop the row not the column. subset=[‘cast’] checks only this column for NaNs.
data[~mask].dropna(axis=0, subset=['cast'])
Note: To check for special characters such as + or ^, use regex=False (the default is True) so that all characters are interpreted as normal strings not regex patterns. You can alternatively use the backslash escape character.
df['a'].str.contains('^', regex=False)#ordf['a'].str.contains('\^')
You can check for the presence of any two or more strings and return True if any of the strings are present.
Let us check for either ‘horrors’ or ‘stand-up comedies’ to complement our emotional states after each watch.
We use str.contains() and pass the two strings separated by a vertical bar (|) which means ‘or’.
pattern = 'horror|stand-up'mask = data[’listed_in’].str.contains(pattern, case=False, na=False)data[mask].sample(3)
We can also use the long-form where we create two masks and pass them into our data using |.
Note: You can create many masks and pass them into the data using the symbols | or & . The & means combine the masks and return True where both masks are True, while | means return True where any of the masks is True.
mask1 = (data['listed_in'].str.contains('horror', case=False, na=False))mask2 = (data['type'].isin(['TV Show']))data[mask1 & mask2].head(3)
Sometimes, we want to check if multiple sub-strings appear in the elements of a column.
In this example, we will search for movies that were filmed in both US and Mexico countries.
The code str.contains('str1.*str2') uses the symbols .* to search if both strings appear strictly in that order, where str1 must appear first to return True.
pattern = 'states.*mexico'mask = data['country'].str.contains(pattern, case=False, na=False)data[mask].head()
Note how ‘United States’ always appears first in the filtered rows.
Where the order does not matter (Mexico can appear first in a row), use str.contains('str1.*str2|str2.*str1'). The | means ‘return rows where str1 appears first, or str2 appears first’.
pattern = 'states.*mexico|mexico.*states'mask = data['country'].str.contains(pattern, case=False, na=False)data[mask].head()
See how in the fourth row ‘Mexico’ appears first.
You can also create a mask for each country, then pass the masks into the data using & symbol. The code below displays the same DataFrame as above.
mask1 = (data['country'].str.contains('states', case=False, na=False)) mask2 = (data['country'].str.contains('mexico', case=False, na=False))data[mask1 & mask2].head()
We might also want to check for numbers in a column using the regex pattern ‘[0–9]’. The code looks like str.contains(‘[0–9]’).
In the next example, we want to check the age rating and return those with specific ages after the dash such as TV-14, PG-13, NC-17 and leave out TV-Y7 and TV-Y7-FV. We, therefore, add a dash (-) before the number pattern.
pattern = '-[0-9]'mask = data['rating'].str.contains(pattern, na=False)data[mask].sample(3)
We can check for rows where a sub-string is present in two or more given columns.
For example, let us check for the presence of ‘tv’ in three columns (‘rating’,’listed_in’ and ’type’) and return rows where it’s present in all of them. The easiest way is to create three masks each for a specific column, and filter the data using & symbol meaning ‘and’ (use | symbol to return True if it’s in at least one column).
mask1 = data['rating'].str.contains('tv', case=False, na=False)mask2 = data['listed_in'].str.contains('tv', case=False, na=False)mask3 = data['type'].str.contains('tv', case=False, na=False)data[mask1 & mask2 & mask3].head()
See how ‘tv’ is present in all three columns in the filtered data above.
Another way is using the slightly complicated apply() and Lambda functions. Read the article Lambda Functions with Practical Examples in Python for clarity on how these two functions work.
cols_to_check = ['rating','listed_in','type']pattern = 'tv'mask = data[cols_to_check].apply( lambda col:col.str.contains( pattern, na=False, case=False)).all(axis=1)
The code for the mask above says that for every column in the list cols_to_check, apply str.contains('tv') function. It then uses .all(axis=1) to consolidate the three masks into one mask (or column) by returning True for every row where all the columns are True. (use .any() to return True for presence in at-least one column).
The filtered DataFrame is the same as the one displayed previously.
We can check whether the value in one column is present as a partial string in another column.
Using our Netflix dataset, let us check for rows where the ‘director’ also appeared in the ‘cast’ as an actor.
In this example, we will use df.apply(), lambda, and the 'in’ keyword which checks if a certain value is present in a given sequence of strings.
mask = data.apply( lambda x: str(x[’director’]) in str(x[’cast’]), axis=1)
df.apply()above holds a lambda function which says that for every row (x), check if the value in ‘director’ is present in the ‘cast’ column and return True or False. I wrapped the columns with str() to convert each value into a String because it raised a TypeError probably because of NaNs. We use axis=1 to mean column-wise, therefore the operation is done for every row and the result will be a column (or series).
data[mask].head()
Whoops! That’s a lot of NaNs. Let’s drop them using the director’s column as the subset and display afresh.
data[mask].dropna(subset=['director'])
For other ways to check if values in one column match those in another, read this article.
We can check for the presence of a partial string in column headers and return those columns.
Filter column names
In the example below, we will use df.filter(like=pattern, axis=1) to return column names with the given pattern. We can also use axis=columns. Note that this returns the filtered data and no mask is generated.
data.filter(like='in', axis=1)
We can also use df.loc where we display all the rows but only the columns with the given sub-string.
data.loc[:, data.columns.str.contains('in')]
This code generates the same results like the image above. Read this article for how .loc works.
Filter by index values
Let us first set the title as the index, then filter by the word ‘Love’. We will use the same methods as above with slight adjustments.
Use df.filter(like=’Love’, axis=0) . We can also use axis=index.
df = data.set_index('title')df.filter(like='Love', axis=0)
Use df.loc[] to display the same results as above. Here we choose the desired rows in the first part of .loc and return all columns in the second part.
df.loc[df.index.str.contains('Love'), :]
Using the pandas query() function
This is a data filtering method especially favored by SQL ninjas. The syntax is df.query(‘expression’) and the result is a modified DataFrame. The cool thing is that aside from filtering by individual columns as we’ve done earlier, you can reference a local variable and call methods such as mean() inside the expression. It also offers performance advantages to other complex masks.
#Exampledata.query('country == "South Africa"')
I rarely use this approach myself, but many people find it simpler and more readable. I encourage you to explore more as it has compelling advantages. This and this articles are a good place to start.
Using other string (Series.str.) example functions
These methods can also filter data to return a mask
Series.str.len() > 10
Series.str.startswith(‘Nov’)
Series.str.endswith(‘2019’)
Series.str.isnumeric()
Series.str.isupper()
Series.str.islower()
As a data professional, chances are you will often need to separate data based on its contents. In this article, we looked at 8 ways to filter a DataFrame by the string values present in the columns. We used Pandas, Lambda functions, and the ‘in’ keyword. We also used the | and & symbols, and the tilde (~) to negate a statement.
We learned that these functions return a mask (a column) of True and False values. We then pass this mask into our DataFrame using square brackets like df[mask] or using the .loc function like df.loc[mask]. You can download the full code here from Github.
I hope you enjoyed the article. To receive more like these whenever I publish a new one, subscribe here. If you are not yet a medium member and would like to support me as a writer, follow this link and I will earn a small commission. Thank you for reading!
10 Ways to Filter Pandas DataFrame
Python Pandas String Operations— Working with Text Data
Select by partial string from a pandas DataFrame | [
{
"code": null,
"e": 399,
"s": 172,
"text": "Filtering a DataFrame refers to checking its contents and returning only those that fit certain criteria. It is part of the data analysis task known as data wrangling and is efficiently done using the Pandas library of Python."
},
{
"code": null,
"e": 606,
"s": 399,
"text": "The idea is that once you have filtered this data, you can analyze it separately and gain insights that might be unique to this group, and inform the predictive modeling steps of the project moving forward."
},
{
"code": null,
"e": 908,
"s": 606,
"text": "In this article, we will use functions such as Series.isin() and Series.str.contains() to filter the data. I minimized the use of apply() and Lambda functions which use more code and are confusing to many people including myself. However, I will explain the code and include links to related articles."
},
{
"code": null,
"e": 1171,
"s": 908,
"text": "We will use the Netflix dataset from Kaggle which contains details of TV shows and movies including the title, director, the cast, age rating, year of release, and duration. Let us now import the required libraries and load the dataset into our Jupyter notebook."
},
{
"code": null,
"e": 1251,
"s": 1171,
"text": "import pandas as pddata = pd.read_csv('netflix_titles_nov_2019.csv')data.head()"
},
{
"code": null,
"e": 1634,
"s": 1251,
"text": "Here, we want to filter by the contents of a particular column. We will use the Series.isin([list_of_values] ) function from Pandas which returns a ‘mask’ of True for every element in the column that exactly matches or False if it does not match any of the list values in the isin() function. Note that you must always include the value(s) in square brackets even if it is just one."
},
{
"code": null,
"e": 1700,
"s": 1634,
"text": "mask = data['type'].isin(['TV Show'])#display the maskmask.head()"
},
{
"code": null,
"e": 1915,
"s": 1700,
"text": "We then apply this mask to the whole DataFrame to return the rows where the condition was True. Note how the index positions where the mask was True above are the only rows returned in the filtered DataFrame below."
},
{
"code": null,
"e": 1976,
"s": 1915,
"text": "#Display first 5 rows #of the filtered datadata[mask].head()"
},
{
"code": null,
"e": 2111,
"s": 1976,
"text": "Note: df.loc[mask] generates the same results as df[mask]. This is especially useful when you want to select a few columns to display."
},
{
"code": null,
"e": 2158,
"s": 2111,
"text": "data.loc[mask, ['title','country','duration']]"
},
{
"code": null,
"e": 2197,
"s": 2158,
"text": "Other ways to generate the mask above;"
},
{
"code": null,
"e": 2346,
"s": 2197,
"text": "If you do not want to deal with a mix of upper and lowercase letters in the isin() function, first convert all the column’s elements into lowercase."
},
{
"code": null,
"e": 2396,
"s": 2346,
"text": "mask = data['type'].str.lower().isin(['tv show'])"
},
{
"code": null,
"e": 2565,
"s": 2396,
"text": "We can also use the == equality operator which compares if two objects are the same. This will compare whether each element in a column is equal to the string provided."
},
{
"code": null,
"e": 2600,
"s": 2565,
"text": "mask = (data['type'] == 'TV Show')"
},
{
"code": null,
"e": 2757,
"s": 2600,
"text": "We can provide a list of strings like isin([‘str1’,’str2']) and check if a column’s elements match any of them. The two masks below return the same results."
},
{
"code": null,
"e": 2868,
"s": 2757,
"text": "mask = data[’type’].isin([’Movie’,’TV Show’])#ormask = (data[’type’] == 'Movie’) | (data[’type’] == 'TV Show’)"
},
{
"code": null,
"e": 2978,
"s": 2868,
"text": "The mask returned will be all Trues because the ‘type’ column contains only ‘Movie’ and ‘TV Show’ categories."
},
{
"code": null,
"e": 3041,
"s": 2978,
"text": "Here, we want to check if a sub-string is present in a column."
},
{
"code": null,
"e": 3270,
"s": 3041,
"text": "For example, the ‘listed-in’ column contains the genres that each movie or show belongs to, separated by commas. I want to filter and return only those that have a ‘horror’ element in them because right now Halloween is upon us."
},
{
"code": null,
"e": 3617,
"s": 3270,
"text": "We will use the string method Series.str.contains(‘pattern’, case=False, na=False) where ‘pattern’ is the substring to search for, and case=False implies case insensitivity. na=False means that any NaN values in the column will be returned as False (meaning without the pattern) instead of as NaN which removes the boolean identity from the mask."
},
{
"code": null,
"e": 3687,
"s": 3617,
"text": "mask = data['listed_in'].str.contains('horror', case=False, na=False)"
},
{
"code": null,
"e": 3784,
"s": 3687,
"text": "We will then apply the mask to our data and display three sample rows of the filtered dataframe."
},
{
"code": null,
"e": 3805,
"s": 3784,
"text": "data[mask].sample(3)"
},
{
"code": null,
"e": 3821,
"s": 3805,
"text": "Other examples:"
},
{
"code": null,
"e": 4147,
"s": 3821,
"text": "We can also check for the presence of symbols in a column. For example, the ‘cast’ column contains the actors separated by commas, and we can check for rows where there is only one actor. This is by checking for rows with a comma (,) and then applying the filtering mask to the data using a tilde (~) to negate the statement."
},
{
"code": null,
"e": 4213,
"s": 4147,
"text": "mask = data['cast'].str.contains(',', na=False)data[~mask].head()"
},
{
"code": null,
"e": 4521,
"s": 4213,
"text": "But now these results have NaNs because we used na=False and the tilde returns all rows where the mask was False. We will use df.dropna(axis=0, subset=’cast)to the filtered data. We use axis=0 to mean row-wise because we want to drop the row not the column. subset=[‘cast’] checks only this column for NaNs."
},
{
"code": null,
"e": 4565,
"s": 4521,
"text": "data[~mask].dropna(axis=0, subset=['cast'])"
},
{
"code": null,
"e": 4792,
"s": 4565,
"text": "Note: To check for special characters such as + or ^, use regex=False (the default is True) so that all characters are interpreted as normal strings not regex patterns. You can alternatively use the backslash escape character."
},
{
"code": null,
"e": 4860,
"s": 4792,
"text": "df['a'].str.contains('^', regex=False)#ordf['a'].str.contains('\\^')"
},
{
"code": null,
"e": 4969,
"s": 4860,
"text": "You can check for the presence of any two or more strings and return True if any of the strings are present."
},
{
"code": null,
"e": 5079,
"s": 4969,
"text": "Let us check for either ‘horrors’ or ‘stand-up comedies’ to complement our emotional states after each watch."
},
{
"code": null,
"e": 5176,
"s": 5079,
"text": "We use str.contains() and pass the two strings separated by a vertical bar (|) which means ‘or’."
},
{
"code": null,
"e": 5292,
"s": 5176,
"text": "pattern = 'horror|stand-up'mask = data[’listed_in’].str.contains(pattern, case=False, na=False)data[mask].sample(3)"
},
{
"code": null,
"e": 5385,
"s": 5292,
"text": "We can also use the long-form where we create two masks and pass them into our data using |."
},
{
"code": null,
"e": 5603,
"s": 5385,
"text": "Note: You can create many masks and pass them into the data using the symbols | or & . The & means combine the masks and return True where both masks are True, while | means return True where any of the masks is True."
},
{
"code": null,
"e": 5743,
"s": 5603,
"text": "mask1 = (data['listed_in'].str.contains('horror', case=False, na=False))mask2 = (data['type'].isin(['TV Show']))data[mask1 & mask2].head(3)"
},
{
"code": null,
"e": 5831,
"s": 5743,
"text": "Sometimes, we want to check if multiple sub-strings appear in the elements of a column."
},
{
"code": null,
"e": 5924,
"s": 5831,
"text": "In this example, we will search for movies that were filmed in both US and Mexico countries."
},
{
"code": null,
"e": 6082,
"s": 5924,
"text": "The code str.contains('str1.*str2') uses the symbols .* to search if both strings appear strictly in that order, where str1 must appear first to return True."
},
{
"code": null,
"e": 6192,
"s": 6082,
"text": "pattern = 'states.*mexico'mask = data['country'].str.contains(pattern, case=False, na=False)data[mask].head()"
},
{
"code": null,
"e": 6260,
"s": 6192,
"text": "Note how ‘United States’ always appears first in the filtered rows."
},
{
"code": null,
"e": 6446,
"s": 6260,
"text": "Where the order does not matter (Mexico can appear first in a row), use str.contains('str1.*str2|str2.*str1'). The | means ‘return rows where str1 appears first, or str2 appears first’."
},
{
"code": null,
"e": 6571,
"s": 6446,
"text": "pattern = 'states.*mexico|mexico.*states'mask = data['country'].str.contains(pattern, case=False, na=False)data[mask].head()"
},
{
"code": null,
"e": 6621,
"s": 6571,
"text": "See how in the fourth row ‘Mexico’ appears first."
},
{
"code": null,
"e": 6769,
"s": 6621,
"text": "You can also create a mask for each country, then pass the masks into the data using & symbol. The code below displays the same DataFrame as above."
},
{
"code": null,
"e": 6937,
"s": 6769,
"text": "mask1 = (data['country'].str.contains('states', case=False, na=False)) mask2 = (data['country'].str.contains('mexico', case=False, na=False))data[mask1 & mask2].head()"
},
{
"code": null,
"e": 7065,
"s": 6937,
"text": "We might also want to check for numbers in a column using the regex pattern ‘[0–9]’. The code looks like str.contains(‘[0–9]’)."
},
{
"code": null,
"e": 7288,
"s": 7065,
"text": "In the next example, we want to check the age rating and return those with specific ages after the dash such as TV-14, PG-13, NC-17 and leave out TV-Y7 and TV-Y7-FV. We, therefore, add a dash (-) before the number pattern."
},
{
"code": null,
"e": 7380,
"s": 7288,
"text": "pattern = '-[0-9]'mask = data['rating'].str.contains(pattern, na=False)data[mask].sample(3)"
},
{
"code": null,
"e": 7462,
"s": 7380,
"text": "We can check for rows where a sub-string is present in two or more given columns."
},
{
"code": null,
"e": 7795,
"s": 7462,
"text": "For example, let us check for the presence of ‘tv’ in three columns (‘rating’,’listed_in’ and ’type’) and return rows where it’s present in all of them. The easiest way is to create three masks each for a specific column, and filter the data using & symbol meaning ‘and’ (use | symbol to return True if it’s in at least one column)."
},
{
"code": null,
"e": 8020,
"s": 7795,
"text": "mask1 = data['rating'].str.contains('tv', case=False, na=False)mask2 = data['listed_in'].str.contains('tv', case=False, na=False)mask3 = data['type'].str.contains('tv', case=False, na=False)data[mask1 & mask2 & mask3].head()"
},
{
"code": null,
"e": 8093,
"s": 8020,
"text": "See how ‘tv’ is present in all three columns in the filtered data above."
},
{
"code": null,
"e": 8282,
"s": 8093,
"text": "Another way is using the slightly complicated apply() and Lambda functions. Read the article Lambda Functions with Practical Examples in Python for clarity on how these two functions work."
},
{
"code": null,
"e": 8462,
"s": 8282,
"text": "cols_to_check = ['rating','listed_in','type']pattern = 'tv'mask = data[cols_to_check].apply( lambda col:col.str.contains( pattern, na=False, case=False)).all(axis=1)"
},
{
"code": null,
"e": 8791,
"s": 8462,
"text": "The code for the mask above says that for every column in the list cols_to_check, apply str.contains('tv') function. It then uses .all(axis=1) to consolidate the three masks into one mask (or column) by returning True for every row where all the columns are True. (use .any() to return True for presence in at-least one column)."
},
{
"code": null,
"e": 8859,
"s": 8791,
"text": "The filtered DataFrame is the same as the one displayed previously."
},
{
"code": null,
"e": 8954,
"s": 8859,
"text": "We can check whether the value in one column is present as a partial string in another column."
},
{
"code": null,
"e": 9065,
"s": 8954,
"text": "Using our Netflix dataset, let us check for rows where the ‘director’ also appeared in the ‘cast’ as an actor."
},
{
"code": null,
"e": 9210,
"s": 9065,
"text": "In this example, we will use df.apply(), lambda, and the 'in’ keyword which checks if a certain value is present in a given sequence of strings."
},
{
"code": null,
"e": 9292,
"s": 9210,
"text": "mask = data.apply( lambda x: str(x[’director’]) in str(x[’cast’]), axis=1)"
},
{
"code": null,
"e": 9709,
"s": 9292,
"text": "df.apply()above holds a lambda function which says that for every row (x), check if the value in ‘director’ is present in the ‘cast’ column and return True or False. I wrapped the columns with str() to convert each value into a String because it raised a TypeError probably because of NaNs. We use axis=1 to mean column-wise, therefore the operation is done for every row and the result will be a column (or series)."
},
{
"code": null,
"e": 9727,
"s": 9709,
"text": "data[mask].head()"
},
{
"code": null,
"e": 9835,
"s": 9727,
"text": "Whoops! That’s a lot of NaNs. Let’s drop them using the director’s column as the subset and display afresh."
},
{
"code": null,
"e": 9874,
"s": 9835,
"text": "data[mask].dropna(subset=['director'])"
},
{
"code": null,
"e": 9965,
"s": 9874,
"text": "For other ways to check if values in one column match those in another, read this article."
},
{
"code": null,
"e": 10059,
"s": 9965,
"text": "We can check for the presence of a partial string in column headers and return those columns."
},
{
"code": null,
"e": 10079,
"s": 10059,
"text": "Filter column names"
},
{
"code": null,
"e": 10289,
"s": 10079,
"text": "In the example below, we will use df.filter(like=pattern, axis=1) to return column names with the given pattern. We can also use axis=columns. Note that this returns the filtered data and no mask is generated."
},
{
"code": null,
"e": 10320,
"s": 10289,
"text": "data.filter(like='in', axis=1)"
},
{
"code": null,
"e": 10421,
"s": 10320,
"text": "We can also use df.loc where we display all the rows but only the columns with the given sub-string."
},
{
"code": null,
"e": 10466,
"s": 10421,
"text": "data.loc[:, data.columns.str.contains('in')]"
},
{
"code": null,
"e": 10563,
"s": 10466,
"text": "This code generates the same results like the image above. Read this article for how .loc works."
},
{
"code": null,
"e": 10586,
"s": 10563,
"text": "Filter by index values"
},
{
"code": null,
"e": 10722,
"s": 10586,
"text": "Let us first set the title as the index, then filter by the word ‘Love’. We will use the same methods as above with slight adjustments."
},
{
"code": null,
"e": 10787,
"s": 10722,
"text": "Use df.filter(like=’Love’, axis=0) . We can also use axis=index."
},
{
"code": null,
"e": 10846,
"s": 10787,
"text": "df = data.set_index('title')df.filter(like='Love', axis=0)"
},
{
"code": null,
"e": 10998,
"s": 10846,
"text": "Use df.loc[] to display the same results as above. Here we choose the desired rows in the first part of .loc and return all columns in the second part."
},
{
"code": null,
"e": 11039,
"s": 10998,
"text": "df.loc[df.index.str.contains('Love'), :]"
},
{
"code": null,
"e": 11073,
"s": 11039,
"text": "Using the pandas query() function"
},
{
"code": null,
"e": 11457,
"s": 11073,
"text": "This is a data filtering method especially favored by SQL ninjas. The syntax is df.query(‘expression’) and the result is a modified DataFrame. The cool thing is that aside from filtering by individual columns as we’ve done earlier, you can reference a local variable and call methods such as mean() inside the expression. It also offers performance advantages to other complex masks."
},
{
"code": null,
"e": 11505,
"s": 11457,
"text": "#Exampledata.query('country == \"South Africa\"')"
},
{
"code": null,
"e": 11706,
"s": 11505,
"text": "I rarely use this approach myself, but many people find it simpler and more readable. I encourage you to explore more as it has compelling advantages. This and this articles are a good place to start."
},
{
"code": null,
"e": 11757,
"s": 11706,
"text": "Using other string (Series.str.) example functions"
},
{
"code": null,
"e": 11809,
"s": 11757,
"text": "These methods can also filter data to return a mask"
},
{
"code": null,
"e": 11831,
"s": 11809,
"text": "Series.str.len() > 10"
},
{
"code": null,
"e": 11860,
"s": 11831,
"text": "Series.str.startswith(‘Nov’)"
},
{
"code": null,
"e": 11888,
"s": 11860,
"text": "Series.str.endswith(‘2019’)"
},
{
"code": null,
"e": 11911,
"s": 11888,
"text": "Series.str.isnumeric()"
},
{
"code": null,
"e": 11932,
"s": 11911,
"text": "Series.str.isupper()"
},
{
"code": null,
"e": 11953,
"s": 11932,
"text": "Series.str.islower()"
},
{
"code": null,
"e": 12284,
"s": 11953,
"text": "As a data professional, chances are you will often need to separate data based on its contents. In this article, we looked at 8 ways to filter a DataFrame by the string values present in the columns. We used Pandas, Lambda functions, and the ‘in’ keyword. We also used the | and & symbols, and the tilde (~) to negate a statement."
},
{
"code": null,
"e": 12540,
"s": 12284,
"text": "We learned that these functions return a mask (a column) of True and False values. We then pass this mask into our DataFrame using square brackets like df[mask] or using the .loc function like df.loc[mask]. You can download the full code here from Github."
},
{
"code": null,
"e": 12798,
"s": 12540,
"text": "I hope you enjoyed the article. To receive more like these whenever I publish a new one, subscribe here. If you are not yet a medium member and would like to support me as a writer, follow this link and I will earn a small commission. Thank you for reading!"
},
{
"code": null,
"e": 12833,
"s": 12798,
"text": "10 Ways to Filter Pandas DataFrame"
},
{
"code": null,
"e": 12889,
"s": 12833,
"text": "Python Pandas String Operations— Working with Text Data"
}
] |
Program to find number of swaps required to sort the sequence in python | Suppose we have a list of distinct numbers; we have to find the minimum number of swaps required to sort the list in increasing order.
So, if the input is like nums = [3, 1, 7, 5], then the output will be 2, as we can swap 3 and 1, then 5 and 7.
To solve this, we will follow these steps:
sort_seq := sort the list nums
table := a new map
for each index i and value n in nums, dotable[n] := i
table[n] := i
swaps := 0
for i in range 0 to size of nums, don := nums[i]s_n := sort_seq[i]s_i := table[s_n]if s_n is not same as n, thenswaps := swaps + 1nums[s_i] := nnums[i] := s_ntable[n] := s_itable[s_n] := i
n := nums[i]
s_n := sort_seq[i]
s_i := table[s_n]
if s_n is not same as n, thenswaps := swaps + 1nums[s_i] := nnums[i] := s_ntable[n] := s_itable[s_n] := i
swaps := swaps + 1
nums[s_i] := n
nums[i] := s_n
table[n] := s_i
table[s_n] := i
return swaps
Let us see the following implementation to get better understanding:
Live Demo
class Solution:
def solve(self, nums):
sort_seq = sorted(nums)
table = {}
for i, n in enumerate(nums):
table[n] = i
swaps = 0
for i in range(len(nums)):
n = nums[i]
s_n = sort_seq[i]
s_i = table[s_n]
if s_n != n:
swaps += 1
nums[s_i] = n
nums[i] = s_n
table[n] = s_i
table[s_n] = i
return swaps
ob = Solution()
nums = [3, 1, 7, 5]
print(ob.solve(nums))
[3, 1, 7, 5]
2 | [
{
"code": null,
"e": 1197,
"s": 1062,
"text": "Suppose we have a list of distinct numbers; we have to find the minimum number of swaps required to sort the list in increasing order."
},
{
"code": null,
"e": 1308,
"s": 1197,
"text": "So, if the input is like nums = [3, 1, 7, 5], then the output will be 2, as we can swap 3 and 1, then 5 and 7."
},
{
"code": null,
"e": 1351,
"s": 1308,
"text": "To solve this, we will follow these steps:"
},
{
"code": null,
"e": 1382,
"s": 1351,
"text": "sort_seq := sort the list nums"
},
{
"code": null,
"e": 1401,
"s": 1382,
"text": "table := a new map"
},
{
"code": null,
"e": 1455,
"s": 1401,
"text": "for each index i and value n in nums, dotable[n] := i"
},
{
"code": null,
"e": 1469,
"s": 1455,
"text": "table[n] := i"
},
{
"code": null,
"e": 1480,
"s": 1469,
"text": "swaps := 0"
},
{
"code": null,
"e": 1669,
"s": 1480,
"text": "for i in range 0 to size of nums, don := nums[i]s_n := sort_seq[i]s_i := table[s_n]if s_n is not same as n, thenswaps := swaps + 1nums[s_i] := nnums[i] := s_ntable[n] := s_itable[s_n] := i"
},
{
"code": null,
"e": 1682,
"s": 1669,
"text": "n := nums[i]"
},
{
"code": null,
"e": 1701,
"s": 1682,
"text": "s_n := sort_seq[i]"
},
{
"code": null,
"e": 1719,
"s": 1701,
"text": "s_i := table[s_n]"
},
{
"code": null,
"e": 1825,
"s": 1719,
"text": "if s_n is not same as n, thenswaps := swaps + 1nums[s_i] := nnums[i] := s_ntable[n] := s_itable[s_n] := i"
},
{
"code": null,
"e": 1844,
"s": 1825,
"text": "swaps := swaps + 1"
},
{
"code": null,
"e": 1859,
"s": 1844,
"text": "nums[s_i] := n"
},
{
"code": null,
"e": 1874,
"s": 1859,
"text": "nums[i] := s_n"
},
{
"code": null,
"e": 1890,
"s": 1874,
"text": "table[n] := s_i"
},
{
"code": null,
"e": 1906,
"s": 1890,
"text": "table[s_n] := i"
},
{
"code": null,
"e": 1919,
"s": 1906,
"text": "return swaps"
},
{
"code": null,
"e": 1988,
"s": 1919,
"text": "Let us see the following implementation to get better understanding:"
},
{
"code": null,
"e": 1998,
"s": 1988,
"text": "Live Demo"
},
{
"code": null,
"e": 2451,
"s": 1998,
"text": "class Solution:\ndef solve(self, nums):\n sort_seq = sorted(nums)\n table = {}\n\n for i, n in enumerate(nums):\n table[n] = i\n swaps = 0\n for i in range(len(nums)):\n n = nums[i]\n s_n = sort_seq[i]\n s_i = table[s_n]\n\n if s_n != n:\n swaps += 1\n nums[s_i] = n\n nums[i] = s_n\n table[n] = s_i\n table[s_n] = i\n\n return swaps\n\nob = Solution()\nnums = [3, 1, 7, 5]\nprint(ob.solve(nums))"
},
{
"code": null,
"e": 2464,
"s": 2451,
"text": "[3, 1, 7, 5]"
},
{
"code": null,
"e": 2466,
"s": 2464,
"text": "2"
}
] |
PDFBox - Quick Guide | The Portable Document Format (PDF) is a file format that helps to present data in a manner that is independent of Application software, hardware, and operating systems.
Each PDF file holds description of a fixed-layout flat document, including the text, fonts, graphics, and other information needed to display it.
There are several libraries available to create and manipulate PDF documents through programs, such as −
Adobe PDF Library − This library provides API in languages such as C++, .NET and Java and using this we can edit, view print and extract text from PDF documents.
Adobe PDF Library − This library provides API in languages such as C++, .NET and Java and using this we can edit, view print and extract text from PDF documents.
Formatting Objects Processor − Open-source print formatter driven by XSL Formatting Objects and an output independent formatter. The primary output target is PDF.
Formatting Objects Processor − Open-source print formatter driven by XSL Formatting Objects and an output independent formatter. The primary output target is PDF.
iText − This library provides API in languages such as Java, C#, and other .NET languages and using this library we can create and manipulate PDF, RTF and HTML documents.
iText − This library provides API in languages such as Java, C#, and other .NET languages and using this library we can create and manipulate PDF, RTF and HTML documents.
JasperReports − This is a Java reporting tool which generates reports in PDF document including Microsoft Excel, RTF, ODT, comma-separated values and XML files.
JasperReports − This is a Java reporting tool which generates reports in PDF document including Microsoft Excel, RTF, ODT, comma-separated values and XML files.
Apache PDFBox is an open-source Java library that supports the development and conversion of PDF documents. Using this library, you can develop Java programs that create, convert and manipulate PDF documents.
In addition to this, PDFBox also includes a command line utility for performing various operations over PDF using the available Jar file.
Following are the notable features of PDFBox −
Extract Text − Using PDFBox, you can extract Unicode text from PDF files.
Extract Text − Using PDFBox, you can extract Unicode text from PDF files.
Split & Merge − Using PDFBox, you can divide a single PDF file into multiple files, and merge them back as a single file.
Split & Merge − Using PDFBox, you can divide a single PDF file into multiple files, and merge them back as a single file.
Fill Forms − Using PDFBox, you can fill the form data in a document.
Fill Forms − Using PDFBox, you can fill the form data in a document.
Print − Using PDFBox, you can print a PDF file using the standard Java printing API.
Print − Using PDFBox, you can print a PDF file using the standard Java printing API.
Save as Image − Using PDFBox, you can save PDFs as image files, such as PNG or JPEG.
Save as Image − Using PDFBox, you can save PDFs as image files, such as PNG or JPEG.
Create PDFs − Using PDFBox, you can create a new PDF file by creating Java programs and, you can also include images and fonts.
Create PDFs − Using PDFBox, you can create a new PDF file by creating Java programs and, you can also include images and fonts.
Signing− Using PDFBox, you can add digital signatures to the PDF files.
Signing− Using PDFBox, you can add digital signatures to the PDF files.
The following are the applications of PDFBox −
Apache Nutch − Apache Nutch is an open-source web-search software. It builds on Apache Lucene, adding web-specifics, such as a crawler, a link-graph database, parsers for HTML and other document formats, etc.
Apache Nutch − Apache Nutch is an open-source web-search software. It builds on Apache Lucene, adding web-specifics, such as a crawler, a link-graph database, parsers for HTML and other document formats, etc.
Apache Tika − Apache Tika is a toolkit for detecting and extracting metadata and structured text content from various documents using existing parser libraries.
Apache Tika − Apache Tika is a toolkit for detecting and extracting metadata and structured text content from various documents using existing parser libraries.
The following are the four main components of PDFBox −
PDFBox − This is the main part of the PDFBox. This contains the classes and interfaces related to content extraction and manipulation.
PDFBox − This is the main part of the PDFBox. This contains the classes and interfaces related to content extraction and manipulation.
FontBox − This contains the classes and interfaces related to font, and using these classes we can modify the font of the text of the PDF document.
FontBox − This contains the classes and interfaces related to font, and using these classes we can modify the font of the text of the PDF document.
XmpBox − This contains the classes and interfaces that handle XMP metadata.
XmpBox − This contains the classes and interfaces that handle XMP metadata.
Preflight − This component is used to verify the PDF files against the PDF/A-1b standard.
Preflight − This component is used to verify the PDF files against the PDF/A-1b standard.
Following are the steps to download Apache PDFBox −
Step 1 − Open the homepage of Apache PDFBox by clicking on the following link − https://pdfbox.apache.org/
Step 2 − The above link will direct you to the homepage as shown in the following screenshot −
Step 3 − Now, click on the Downloads link highlighted in the above screenshot. On clicking, you will be directed to the downloads page of PDFBox as shown in the following screenshot.
Step 4 − In the Downloads page, you will have links for PDFBox. Click on the respective link for the latest release. For instance, we are opting for PDFBox 2.0.1 and on clicking this, you will be directed to the required jar files as shown in the following screenshot.
Step 5 − Download the jar files pdfbox-2.0.1.jar, fontbox-2.0.1.jar, preflight-2.0.1.jar, xmpbox-2.0.1.jar and, pdfbox-tools-2.0.1.jar.
After downloading the required jar files, you have to embed these JAR files to your Eclipse environment. You can do this by setting the Build path to these JAR files and by using pom.xml.
Following are the steps to install PDFBox in Eclipse −
Step 1 − Ensure that you have installed Eclipse in your system. If not, download and install Eclipse in your system.
Step 2 − Open Eclipse, click on File, New, and Open a new project as shown in the following screenshot.
Step 3 − On selecting the project, you will get New Project wizard. In this wizard, select Java project and proceed by clicking Next button as shown in the following screenshot.
Step 4 − On proceeding forward, you will be directed to the New Java Project wizard. Create a new project and click on Next as shown in the following screenshot.
Step 5 − After creating a new project, right click on it; select Build Path and click on Configure Build Path... as shown in the following screenshot.
Step 6 − On clicking on the Build Path option you will be directed to the Java Build Path wizard. Select the Add External JARs as shown in the following screenshot.
Step 7 − Select the jar files fontbox-2.0.1.jar, pdfbox-2.0.1.jar, pdfbox-tools-2.0.1.jar, preflight-2.0.1.jar, xmpbox-2.0.1.jar as shown in the following screenshot.
Step 8 − On clicking the Open button in the above screenshot, those files will be added to your library as shown in the following screenshot.
Step 9 − On clicking OK, you will successfully add the required JAR files to the current project and you can verify these added libraries by expanding the Referenced Libraries as shown in the following screenshot.
Convert the project into maven project and add the following contents to its pom.xml.
<project xmlns="https://maven.apache.org/POM/4.0.0"
xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://maven.apache.org/POM/4.0.0
https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>my_project</groupId>
<artifactId>my_project</artifactId>
<version>0.0.1-SNAPSHOT</version>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.1</version>
</dependency>
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>fontbox</artifactId>
<version>2.0.0</version>
</dependency>
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>jempbox</artifactId>
<version>1.8.11</version>
</dependency>
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>xmpbox</artifactId>
<version>2.0.0</version>
</dependency>
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>preflight</artifactId>
<version>2.0.0</version>
</dependency>
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox-tools</artifactId>
<version>2.0.0</version>
</dependency>
</dependencies>
</project>
Let us now understand how to create a PDF document using the PDFBox library.
You can create an empty PDF Document by instantiating the PDDocument class. You can save the document in your desired location using the Save() method.
Following are the steps to create an empty PDF document.
The PDDocument class that belongs to the package org.apache.pdfbox.pdmodel, is an In-memory representation of the PDFDocument. Therefore, by instantiating this class, you can create an empty PDFDocument as shown in the following code block.
PDDocument document = new PDDocument();
After creating the document, you need to save this document in the desired path, you can do so using the Save() method of the PDDocument class. This method accepts a string value, representing the path where you want to store the document, as a parameter. Following is the prototype of the save() method of the PDDocument class.
document.save("Path");
When your task is completed, at the end, you need to close the PDDocument object using the close () method. Following is the prototype of the close() method of PDDocument class.
document.close();
This example demonstrates the creation of a PDF Document. Here, we will create a Java program to generate a PDF document named my_doc.pdf and save it in the path C:/PdfBox_Examples/. Save this code in a file with name Document_Creation.java.
import java.io.IOException;
import org.apache.pdfbox.pdmodel.PDDocument;
public class Document_Creation {
public static void main (String args[]) throws IOException {
//Creating PDF document object
PDDocument document = new PDDocument();
//Saving the document
document.save("C:/PdfBox_Examples/my_doc.pdf");
System.out.println("PDF created");
//Closing the document
document.close();
}
}
Compile and execute the saved Java file from the command prompt using the following commands.
javac Document_Creation.java
java Document_Creation
Upon execution, the above program creates a PDF document displaying the following message.
PDF created
If you verify the specified path, you can find the created PDF document as shown below.
Since this is an empty document, if you try to open this document, this gives you a prompt displaying an error message as shown in the following screenshot.
In the previous chapter, we have seen how to create a PDF document. After creating a PDF document, you need to add pages to it. Let us now understand how to add pages in a PDF document.
You can create an empty page by instantiating the PDPage class and add it to the PDF document using the addPage() method of the PDDocument class.
Following are the steps to create an empty document and add pages to it.
Create an empty PDF document by instantiating the PDDocument class as shown below.
PDDocument document = new PDDocument();
The PDPage class represents a page in the PDF document therefore, you can create an empty page by instantiating this class as shown in the following code block.
PDPage my_page = new PDPage();
You can add a page to the PDF document using the addPage() method of the PDDocument class. To this method you need to pass the PDPage object as a parameter.
Therefore, add the blank page created in the previous step to the PDDocument object as shown in the following code block.
document.addPage(my_page);
In this way you can add as many pages as you want to a PDF document.
After adding all the pages, save the PDF document using the save() method of the PDDocument class as shown in the following code block.
document.save("Path");
Finally close the document using the close() method of the PDDocument class as shown below.
document.close();
This example demonstrates how to create a PDF Document and add pages to it. Here we will create a PDF Document named my_doc.pdf and further add 10 blank pages to it, and save it in the path C:/PdfBox_Examples/. Save this code in a file with name Adding_pages.java.
package document;
import java.io.IOException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
public class Adding_Pages {
public static void main(String args[]) throws IOException {
//Creating PDF document object
PDDocument document = new PDDocument();
for (int i=0; i<10; i++) {
//Creating a blank page
PDPage blankPage = new PDPage();
//Adding the blank page to the document
document.addPage( blankPage );
}
//Saving the document
document.save("C:/PdfBox_Examples/my_doc.pdf");
System.out.println("PDF created");
//Closing the document
document.close();
}
}
Compile and execute the saved Java file from the command prompt using the following commands −
javac Adding_pages.java
java Adding_pages
Upon execution, the above program creates a PDF document with blank pages displaying the following message −
PDF created
If you verify the specified path, you can find the created PDF document as shown in the following screenshot.
In the previous examples, you have seen how to create a new document and add pages to it. This chapter teaches you how to load a PDF document that already exists in your system, and perform some operations on it.
The load() method of the PDDocument class is used to load an existing PDF document. Follow the steps given below to load an existing PDF document.
Load an existing PDF document using the static method load() of the PDDocument class. This method accepts a file object as a parameter, since this is a static method you can invoke it using class name as shown below.
File file = new File("path of the document")
PDDocument.load(file);
Perform the required operations such as adding pages adding text, adding images to the loaded document.
After adding all the pages, save the PDF document using the save() method of the PDDocument class as shown in the following code block.
document.save("Path");
Finally close the document using the close() method of the PDDocument class as shown below.
document.close();
Suppose we have a PDF document which contains a single page, in the path, C:/PdfBox_Examples/ as shown in the following screenshot.
This example demonstrates how to load an existing PDF Document. Here, we will load the PDF document sample.pdf shown above, add a page to it, and save it in the same path with the same name.
Step 1 − Save this code in a file with name LoadingExistingDocument.java.
import java.io.File;
import java.io.IOException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
public class LoadingExistingDocument {
public static void main(String args[]) throws IOException {
//Loading an existing document
File file = new File("C:/PdfBox_Examples/sample.pdf");
PDDocument document = PDDocument.load(file);
System.out.println("PDF loaded");
//Adding a blank page to the document
document.addPage(new PDPage());
//Saving the document
document.save("C:/PdfBox_Examples/sample.pdf");
//Closing the document
document.close();
}
}
Compile and execute the saved Java file from the command prompt using the following commands
javac LoadingExistingDocument.java
java LoadingExistingDocument
Upon execution, the above program loads the specified PDF document and adds a blank page to it displaying the following message.
PDF loaded
If you verify the specified path, you can find an additional page added to the specified PDF document as shown below.
Let us now learn how to remove pages from a PDF document.
You can remove a page from an existing PDF document using the removePage() method of the PDDocument class.
Load an existing PDF document using the static method load() of the PDDocument class. This method accepts a file object as a parameter, since this is a static method you can invoke it using class name as shown below.
File file = new File("path of the document")
PDDocument.load(file);
You can list the number of pages that exists in the PDF document using the getNumberOfPages() method as shown below.
int noOfPages= document.getNumberOfPages();
System.out.print(noOfPages);
You can remove a page from the PDF document using the removePage() method of the PDDocument class. To this method, you need to pass the index of the page that is to be deleted.
While specifying the index for the pages in a PDF document, keep in mind that indexing of these pages starts from zero, i.e., if you want to delete the 1st page then the index value needs to be 0.
document.removePage(2);
After removing the page, save the PDF document using the save() method of the PDDocument class as shown in the following code block.
document.save("Path");
Finally, close the document using the close() method of the PDDocument class as shown below.
document.close();
Suppose, we have a PDF document with name sample.pdf and it contains three empty pages as shown below.
This example demonstrates how to remove pages from an existing PDF document. Here, we will load the above specified PDF document named sample.pdf, remove a page from it, and save it in the path C:/PdfBox_Examples/. Save this code in a file with name Removing_pages.java.
import java.io.File;
import java.io.IOException;
import org.apache.pdfbox.pdmodel.PDDocument;
public class RemovingPages {
public static void main(String args[]) throws IOException {
//Loading an existing document
File file = new File("C:/PdfBox_Examples/sample.pdf");
PDDocument document = PDDocument.load(file);
//Listing the number of existing pages
int noOfPages= document.getNumberOfPages();
System.out.print(noOfPages);
//Removing the pages
document.removePage(2);
System.out.println("page removed");
//Saving the document
document.save("C:/PdfBox_Examples/sample.pdf");
//Closing the document
document.close();
}
}
Compile and execute the saved Java file from the command prompt using the following commands.
javac RemovingPages.java
java RemovingPages
Upon execution, the above program creates a PDF document with blank pages displaying the following message.
3
page removed
If you verify the specified path, you can find that the required page was deleted and only two pages remained in the document as shown below.
Like other files, a PDF document also has document properties. These properties are key-value pairs. Each property gives particular information about the document.
Following are the properties of a PDF document −
File
This property holds the name of the file.
Title
Using this property, you can set the title for the document.
Author
Using this property, you can set the name of the author for the document.
Subject
Using this property, you can specify the subject of the PDF document.
Keywords
Using this property, you can list the keywords with which we can search the document.
Created
Using this property, you can set the date created for the document.
Modified
Using this property, you can set the date modified for the document.
Application
Using this property, you can set the Application of the document.
Following is a screenshot of the document properties table of a PDF document.
PDFBox provides you a class named PDDocumentInformation. This class has a set of setter and getter methods.
The setter methods of this class are used to set values to various properties of a document and getter methods which are used to retrieve these values.
Following are the setter methods of the PDDocumentInformation class.
setAuthor(String author)
This method is used to set the value for the property of the PDF document named Author.
setTitle(String title)
This method is used to set the value for the property of the PDF document named Title.
setCreator(String creator)
This method is used to set the value for the property of the PDF document named Creator.
setSubject(String subject)
This method is used to set the value for the property of the PDF document named Subject.
setCreationDate(Calendar date)
This method is used to set the value for the property of the PDF document named CreationDate.
setModificationDate(Calendar date)
This method is used to set the value for the property of the PDF document named ModificationDate.
setKeywords(String keywords list)
This method is used to set the value for the property of the PDF document named Keywords.
PDFBox provides a class called PDDocumentInformation and this class provides various methods. These methods can set various properties to the document and retrieve them.
This example demonstrates how to add properties such as Author, Title, Date, and Subject to a PDF document. Here, we will create a PDF document named doc_attributes.pdf, add various attributes to it, and save it in the path C:/PdfBox_Examples/. Save this code in a file with name AddingAttributes.java.
import java.io.IOException;
import java.util.Calendar;
import java.util.GregorianCalendar;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDDocumentInformation;
import org.apache.pdfbox.pdmodel.PDPage;
public class AddingDocumentAttributes {
public static void main(String args[]) throws IOException {
//Creating PDF document object
PDDocument document = new PDDocument();
//Creating a blank page
PDPage blankPage = new PDPage();
//Adding the blank page to the document
document.addPage( blankPage );
//Creating the PDDocumentInformation object
PDDocumentInformation pdd = document.getDocumentInformation();
//Setting the author of the document
pdd.setAuthor("Tutorialspoint");
// Setting the title of the document
pdd.setTitle("Sample document");
//Setting the creator of the document
pdd.setCreator("PDF Examples");
//Setting the subject of the document
pdd.setSubject("Example document");
//Setting the created date of the document
Calendar date = new GregorianCalendar();
date.set(2015, 11, 5);
pdd.setCreationDate(date);
//Setting the modified date of the document
date.set(2016, 6, 5);
pdd.setModificationDate(date);
//Setting keywords for the document
pdd.setKeywords("sample, first example, my pdf");
//Saving the document
document.save("C:/PdfBox_Examples/doc_attributes.pdf");
System.out.println("Properties added successfully ");
//Closing the document
document.close();
}
}
Compile and execute the saved Java file from the command prompt using the following commands.
javac AddingAttributes.java
java AddingAttributes
Upon execution, the above program adds all the specified attributes to the document displaying the following message.
Properties added successfully
Now, if you visit the given path you can find the PDF created in it. Right click on the document and select the document properties option as shown below.
This will give you the document properties window and here you can observe all the properties of the document were set to specified values.
You can retrieve the properties of a document using the getter methods provided by the PDDocumentInformation class.
Following are the getter methods of the PDDocumentInformation class.
getAuthor()
This method is used to retrieve the value for the property of the PDF document named Author.
getTitle()
This method is used to retrieve the value for the property of the PDF document named Title.
getCreator()
This method is used to retrieve the value for the property of the PDF document named Creator.
getSubject()
This method is used to retrieve the value for the property of the PDF document named Subject.
getCreationDate()
This method is used to retrieve the value for the property of the PDF document named CreationDate.
getModificationDate()
This method is used to retrieve the value for the property of the PDF document named ModificationDate.
getKeywords()
This method is used to retrieve the value for the property of the PDF document named Keywords.
This example demonstrates how to retrieve the properties of an existing PDF document. Here, we will create a Java program and load the PDF document named doc_attributes.pdf, which is saved in the path C:/PdfBox_Examples/, and retrieve its properties. Save this code in a file with name RetrivingDocumentAttributes.java.
import java.io.File;
import java.io.IOException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDDocumentInformation;
public class RetrivingDocumentAttributes {
public static void main(String args[]) throws IOException {
//Loading an existing document
File file = new File("C:/PdfBox_Examples/doc_attributes.pdf")
PDDocument document = PDDocument.load(file);
//Getting the PDDocumentInformation object
PDDocumentInformation pdd = document.getDocumentInformation();
//Retrieving the info of a PDF document
System.out.println("Author of the document is :"+ pdd.getAuthor());
System.out.println("Title of the document is :"+ pdd.getTitle());
System.out.println("Subject of the document is :"+ pdd.getSubject());
System.out.println("Creator of the document is :"+ pdd.getCreator());
System.out.println("Creation date of the document is :"+ pdd.getCreationDate());
System.out.println("Modification date of the document is :"+
pdd.getModificationDate());
System.out.println("Keywords of the document are :"+ pdd.getKeywords());
//Closing the document
document.close();
}
}
Compile and execute the saved Java file from the command prompt using the following commands.
javac RetrivingDocumentAttributes.java
java RetrivingDocumentAttributes
Upon execution, the above program retrieves all the attributes of the document and displays them as shown below.
Author of the document is :Tutorialspoint
Title of the document is :Sample document
Subject of the document is :Example document
Creator of the document is :PDF Examples
Creation date of the document is :11/5/2015
Modification date of the document is :6/5/2016
Keywords of the document are :sample, first example, my pdf
In the previous chapter, we discussed how to add pages to a PDF document. In this chapter, we will discuss how to add text to an existing PDF document.
You can add contents to a document using the PDFBox library, this provides you a class named PDPageContentStream which contains the required methods to insert text, images, and other types of contents in a page of a PDFDocument.
Following are the steps to create an empty document and add contents to a page in it.
You can load an existing document using the load() method of the PDDocument class. Therefore, instantiate this class and load the required document as shown below.
File file = new File("Path of the document");
PDDocument doc = document.load(file);
You can get the required page in a document using the getPage() method. Retrieve the object of the required page by passing its index to this method as shown below.
PDPage page = doc.getPage(1);
You can insert various kinds of data elements using the object of the class PDPageContentStream. You need to pass the document object and the page object to the constructor of this class therefore, instantiate this class by passing these two objects created in the previous steps as shown below.
PDPageContentStream contentStream = new PDPageContentStream(doc, page);
While inserting text in a PDF document, you can specify the start and end points of the text using the beginText() and endText() methods of the PDPageContentStream class as shown below.
contentStream.beginText();
.............................
code to add text content
.............................
contentStream.endText();
Therefore, begin the text using the beginText() method as shown below.
contentStream.beginText();
Using the newLineAtOffset() method, you can set the position on the content stream in the page.
//Setting the position for the line
contentStream.newLineAtOffset(25, 700);
You can set the font of the text to the required style using the setFont() method of the PDPageContentStream class as shown below. To this method you need to pass the type and size of the font.
contentStream.setFont( font_type, font_size );
You can insert the text into the page using the ShowText() method of the PDPageContentStream class as shown below. This method accepts the required text in the form of string.
contentStream.showText(text);
After inserting the text, you need to end the text using the endText() method of the PDPageContentStream class as shown below.
contentStream.endText();
Close the PDPageContentStream object using the close() method as shown below.
contentstream.close();
After adding the required content, save the PDF document using the save() method of the PDDocument class as shown in the following code block.
doc.save("Path");
Finally, close the document using the close() method of the PDDocument class as shown below.
doc.close();
This example demonstrates how to add contents to a page in a document. Here, we will create a Java program to load the PDF document named my_doc.pdf, which is saved in the path C:/PdfBox_Examples/, and add some text to it. Save this code in a file with name AddingContent.java.
import java.io.File;
import java.io.IOException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
public class AddingContent {
public static void main (String args[]) throws IOException {
//Loading an existing document
File file = new File("C:/PdfBox_Examples/my_doc.pdf");
PDDocument document = PDDocument.load(file);
//Retrieving the pages of the document
PDPage page = document.getPage(1);
PDPageContentStream contentStream = new PDPageContentStream(document, page);
//Begin the Content stream
contentStream.beginText();
//Setting the font to the Content stream
contentStream.setFont(PDType1Font.TIMES_ROMAN, 12);
//Setting the position for the line
contentStream.newLineAtOffset(25, 500);
String text = "This is the sample document and we are adding content to it.";
//Adding text in the form of string
contentStream.showText(text);
//Ending the content stream
contentStream.endText();
System.out.println("Content added");
//Closing the content stream
contentStream.close();
//Saving the document
document.save(new File("C:/PdfBox_Examples/new.pdf"));
//Closing the document
document.close();
}
}
Compile and execute the saved Java file from the command prompt using the following commands.
javac AddingContent.java
java AddingContent
Upon execution, the above program adds the given text to the document and displays the following message.
Content added
If you verify the PDF Document new.pdf in the specified path, you can observe that the given content is added to the document as shown below.
In the example provided in the previous chapter we discussed how to add text to a page in a PDF but through this program, you can only add the text that would fit in a single line. If you try to add more content, all the text that exceeds the line space will not be displayed.
For example, if you execute the above program in the previous chapter by passing the following string only a part of it will be displayed.
String text = "This is an example of adding text to a page in the pdf document. we can
add as many lines as we want like this using the showText() method of the
ContentStream class";
Replace the string text of the example in the previous chapter with the above mentioned string and execute it. Upon execution, you will receive the following output.
If you observe the output carefully, you can notice that only a part of the string is displayed.
In order to add multiple lines to a PDF you need to set the leading using the setLeading() method and shift to new line using newline() method after finishing each line.
Following are the steps to create an empty document and add contents to a page in it.
You can load an existing document using the load() method of the PDDocument class. Therefore, instantiate this class and load the required document as shown below.
File file = new File("Path of the document");
PDDocument doc = PDDocument.load(file);
You can get the required page in a document using the getPage() method. Retrieve the object of the required page by passing its index to this method as shown below.
PDPage page = doc.getPage(1);
You can insert various kinds of data elements using the object of the class named PDPageContentStream. You need to pass the document object and the page object to the constructor of this class therefore, instantiate this class by passing these two objects created in the previous steps as shown below.
PDPageContentStream contentStream = new PDPageContentStream(doc, page);
While inserting text in a PDF document, you can specify the start and end points of the text using the beginText() and endText() methods of the PDPageContentStream class as shown below.
contentStream.beginText();
.............................
code to add text content
.............................
contentStream.endText();
Therefore, begin the text using the beginText() method as shown below.
contentStream.beginText();
Using the newLineAtOffset() method, you can set the position on the content stream in the page.
//Setting the position for the line
contentStream.newLineAtOffset(25, 700);
You can set the font of the text to the required style using the setFont() method of the PDPageContentStream class as shown below to this method you need to pass the type and size of the font.
contentStream.setFont( font_type, font_size );
You can set the text leading using the setLeading() method as shown below.
contentStream.setLeading(14.5f);
You can insert multiple strings using the ShowText() method of the PDPageContentStream class, by dividing each of them using the newline() method as shown below.
contentStream. ShowText(text1);
contentStream.newLine();
contentStream. ShowText(text2);
After inserting the text, you need to end the text using the endText() method of the PDPageContentStream class as shown below.
contentStream.endText();
Close the PDPageContentStream object using the close() method as shown below.
contentstream.close();
After adding the required content, save the PDF document using the save() method of the PDDocument class as shown in the following code block.
doc.save("Path");
Finally, close the document using the close() method of the PDDocument class as shown below.
doc.close();
This example demonstrates how to add multiple lines in a PDF using PDFBox. Save this program in a file with name AddMultipleLines.java.
import java.io.File;
import java.io.IOException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
public class AddMultipleLines {
public static void main(String args[]) throws IOException {
//Loading an existing document
File file = new File("C:/PdfBox_Examples/my_pdf.pdf");
PDDocument doc = document.load(file);
//Creating a PDF Document
PDPage page = doc.getPage(1);
PDPageContentStream contentStream = new PDPageContentStream(doc, page);
//Begin the Content stream
contentStream.beginText();
//Setting the font to the Content stream
contentStream.setFont( PDType1Font.TIMES_ROMAN, 16 );
//Setting the leading
contentStream.setLeading(14.5f);
//Setting the position for the line
contentStream.newLineAtOffset(25, 725);
String text1 = "This is an example of adding text to a page in the pdf document.
we can add as many lines";
String text2 = "as we want like this using the ShowText() method of the
ContentStream class";
//Adding text in the form of string
contentStream. ShowText(text1);
contentStream.newLine();
contentStream. ShowText(text2);
//Ending the content stream
contentStream.endText();
System.out.println("Content added");
//Closing the content stream
contentStream.close();
//Saving the document
doc.save(new File("C:/PdfBox_Examples/new.pdf"));
//Closing the document
doc.close();
}
}
Compile and execute the saved Java file from the command prompt using the following commands.
javac AddMultipleLines.java
java AddMultipleLines
Upon execution, the above program adds the given text to the document and displays the following message.
Content added
If you verify the PDF Document new.pdf in the specified path, you can observe that the given content is added to the document in multiple lines as shown below.
In the previous chapter, we have seen how to add text to an existing PDF document. In this chapter, we will discuss how to read text from an existing PDF document.
Extracting text is one of the main features of the PDF box library. You can extract text using the getText() method of the PDFTextStripper class. This class extracts all the text from the given PDF document.
Following are the steps to extract text from an existing PDF document.
Load an existing PDF document using the static method load() of the PDDocument class. This method accepts a file object as a parameter, since this is a static method you can invoke it using class name as shown below.
File file = new File("path of the document")
PDDocument document = PDDocument.load(file);
The PDFTextStripper class provides methods to retrieve text from a PDF document therefore, instantiate this class as shown below.
PDFTextStripper pdfStripper = new PDFTextStripper();
You can read/retrieve the contents of a page from the PDF document using the getText() method of the PDFTextStripper class. To this method you need to pass the document object as a parameter. This method retrieves the text in a given document and returns it in the form of a String object.
String text = pdfStripper.getText(document);
Finally, close the document using the close() method of the PDDocument class as shown below.
document.close();
Suppose, we have a PDF document with some text in it as shown below.
This example demonstrates how to read text from the above mentioned PDF document. Here, we will create a Java program and load a PDF document named new.pdf, which is saved in the path C:/PdfBox_Examples/. Save this code in a file with name ReadingText.java.
import java.io.File;
import java.io.IOException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
public class ReadingText {
public static void main(String args[]) throws IOException {
//Loading an existing document
File file = new File("C:/PdfBox_Examples/new.pdf");
PDDocument document = PDDocument.load(file);
//Instantiate PDFTextStripper class
PDFTextStripper pdfStripper = new PDFTextStripper();
//Retrieving text from PDF document
String text = pdfStripper.getText(document);
System.out.println(text);
//Closing the document
document.close();
}
}
Compile and execute the saved Java file from the command prompt using the following commands.
javac ReadingText.java
java ReadingText
Upon execution, the above program retrieves the text from the given PDF document and displays it as shown below.
This is an example of adding text to a page in the pdf document. we can add as many lines
as we want like this using the ShowText() method of the ContentStream class.
In the previous chapter, we have seen how to extract text from an existing PDF document. In this chapter, we will discuss how to insert image to a PDF document.
You can insert an image into a PDF document using the createFromFile() and drawImage() methods of the classes PDImageXObject and PDPageContentStream respectively.
Following are the steps to extract text from an existing PDF document.
Load an existing PDF document using the static method load() of the PDDocument class. This method accepts a file object as a parameter, since this is a static method you can invoke it using class name as shown below.
File file = new File("path of the document")
PDDocument doc = PDDocument.load(file);
Select a page in the PDF document and retrieve its page object using the getPage() method as shown below.
PDPage page = doc.getPage(0);
The class PDImageXObject in PDFBox library represents an image. It provides all the required methods to perform operations related to an image, such as, inserting an image, setting its height, setting its width etc.
We can create an object of this class using the method createFromFile(). To this method, we need to pass the path of the image which we want to add in the form of a string and the document object to which the image needs to be added.
PDImageXObject pdImage = PDImageXObject.createFromFile("C:/logo.png", doc);
You can insert various kinds of data elements using the object of the class named PDPageContentStream. You need to pass the document object and the page object to the constructor of this class therefore, instantiate this class by passing these two objects created in the previous steps as shown below.
PDPageContentStream contentStream = new PDPageContentStream(doc, page);
You can insert an image in the PDF document using the drawImage() method. To this method, you need to add the image object created in the above step and the required dimensions of the image (width and height) as shown below.
contentstream.drawImage(pdImage, 70, 250);
Close the PDPageContentStream object using the close() method as shown below.
contentstream.close();
After adding the required content, save the PDF document using the save() method of the PDDocument class as shown in the following code block.
doc.save("Path");
Finally, close the document using the close() method of the PDDocument class as shown below.
doc.close();
Suppose we have a PDF document named sample.pdf, in the path C:/PdfBox_Examples/ with empty pages as shown below.
This example demonstrates how to add image to a blank page of the above mentioned PDF document. Here, we will load the PDF document named sample.pdf and add image to it. Save this code in a file with name InsertingImage.java.
import java.io.File;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
public class InsertingImage {
public static void main(String args[]) throws Exception {
//Loading an existing document
File file = new File("C:/PdfBox_Examples/sample.pdf");
PDDocument doc = PDDocument.load(file);
//Retrieving the page
PDPage page = doc.getPage(0);
//Creating PDImageXObject object
PDImageXObject pdImage = PDImageXObject.createFromFile("C:/PdfBox_Examples/logo.png",doc);
//creating the PDPageContentStream object
PDPageContentStream contents = new PDPageContentStream(doc, page);
//Drawing the image in the PDF document
contents.drawImage(pdImage, 70, 250);
System.out.println("Image inserted");
//Closing the PDPageContentStream object
contents.close();
//Saving the document
doc.save("C:/PdfBox_Examples/sample.pdf");
//Closing the document
doc.close();
}
}
Compile and execute the saved Java file from the command prompt using the following commands.
javac InsertingImage.java
java InsertingImage
Upon execution, the above program inserts an image into the specified page of the given PDF document displaying the following message.
Image inserted
If you verify the document sample.pdf, you can observe that an image is inserted in it as shown below.
In the previous chapter, we have seen how to insert an image in a PDF document. In this chapter, we will discuss how to encrypt a PDF document.
You can encrypt a PDF document using the methods provided by StandardProtectionPolicy and AccessPermission classes.
The AccessPermission class is used to protect the PDF Document by assigning access permissions to it. Using this class, you can restrict users from performing the following operations.
Print the document
Modify the content of the document
Copy or extract content of the document
Add or modify annotations
Fill in interactive form fields
Extract text and graphics for accessibility to visually impaired people
Assemble the document
Print in degraded quality
The StandardProtectionPolicy class is used to add a password based protection to a document.
Following are the steps to encrypt an existing PDF document.
Load an existing PDF document using the static method load() of the PDDocument class. This method accepts a file object as a parameter, since this is a static method you can invoke it using class name as shown below.
File file = new File("path of the document")
PDDocument document = PDDocument.load(file);
Instantiate the AccessPermission class as shown below.
AccessPermission accessPermission = new AccessPermission();
Instantiate the StandardProtectionPolicy class by passing the owner password, user password, and the AccessPermission object as shown below.
StandardProtectionPolicy spp = new StandardProtectionPolicy("1234","1234",accessPermission);
Set the encryption key length using the setEncryptionKeyLength() method as shown below.
spp.setEncryptionKeyLength(128);
Set the permissions using the setPermissions() method of the StandardProtectionPolicy class. This method accepts an AccessPermission object as a parameter.
spp.setPermissions(accessPermission);
You can protect your document using the protect() method of the PDDocument class as shown below. Pass the StandardProtectionPolicy object as a parameter to this method.
document.protect(spp);
After adding the required content save the PDF document using the save() method of the PDDocument class as shown in the following code block.
document.save("Path");
Finally, close the document using close() method of PDDocument class as shown below.
document.close();
Suppose, we have a PDF document named sample.pdf, in the path C:/PdfBox_Examples/ with empty pages as shown below.
This example demonstrates how to encrypt the above mentioned PDF document. Here, we will load the PDF document named sample.pdf and encrypt it. Save this code in a file with name EncriptingPDF.java.
import java.io.File;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.encryption.AccessPermission;
import org.apache.pdfbox.pdmodel.encryption.StandardProtectionPolicy;
public class EncriptingPDF {
public static void main(String args[]) throws Exception {
//Loading an existing document
File file = new File("C:/PdfBox_Examples/sample.pdf");
PDDocument document = PDDocument.load(file);
//Creating access permission object
AccessPermission ap = new AccessPermission();
//Creating StandardProtectionPolicy object
StandardProtectionPolicy spp = new StandardProtectionPolicy("1234", "1234", ap);
//Setting the length of the encryption key
spp.setEncryptionKeyLength(128);
//Setting the access permissions
spp.setPermissions(ap);
//Protecting the document
document.protect(spp);
System.out.println("Document encrypted");
//Saving the document
document.save("C:/PdfBox_Examples/sample.pdf");
//Closing the document
document.close();
}
}
Compile and execute the saved Java file from the command prompt using the following commands.
javac EncriptingPDF.java
java EncriptingPDF
Upon execution, the above program encrypts the given PDF document displaying the following message.
Document encrypted
If you try to open the document sample.pdf, you cannot, since it is encrypted. Instead, it prompts to type the password to open the document as shown below.
In the previous chapter, we have learnt how to insert image into a PDF document. In this chapter, we will discuss how to add JavaScript to a PDF document.
You can add JavaScript actions to a PDF document using the PDActionJavaScript class. This represents a JavaScript action.
Following are the steps to add JavaScript actions to an existing PDF document.
Load an existing PDF document using the static method load() of the PDDocument class. This method accepts a file object as a parameter, since this is a static method you can invoke it using class name as shown below.
File file = new File("path of the document")
PDDocument document = PDDocument.load(file);
Instantiate the PDActionJavaScript object as shown below. To the constructor of this class, pass the required JavaScript in the form of String as shown below.
String javaScript = "app.alert( {cMsg: 'this is an example', nIcon: 3,"
+ " nType: 0,cTitle: 'PDFBox Javascript example' } );";
PDActionJavaScript PDAjavascript = new PDActionJavaScript(javaScript);
Embed the required string to the PDF document as shown below.
document.getDocumentCatalog().setOpenAction(PDAjavascript);
After adding the required content save the PDF document using the save() method of the PDDocument class as shown in the following code block.
document.save("Path");
Finally, close the document using close() method of the PDDocument class as shown below.
document.close();
Suppose, we have a PDF document named sample.pdf, in the path C:/PdfBox_Examples/ with empty pages as shown below.
This example demonstrates how to embed JavaScript in the above mentioned PDF document. Here, we will load the PDF document named sample.pdf and embed JavaScript in it. Save this code in a file with name AddJavaScript.java.
import java.io.File;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.interactive.action.PDActionJavaScript;
public class AddJavaScript {
public static void main(String args[]) throws Exception {
//Loading an existing file
File file = new File("C:/PdfBox_Examples/new.pdf");
PDDocument document = PDDocument.load(file);
String javaScript = "app.alert( {cMsg: 'this is an example', nIcon: 3,"
+ " nType: 0, cTitle: 'PDFBox Javascript example’} );";
//Creating PDActionJavaScript object
PDActionJavaScript PDAjavascript = new PDActionJavaScript(javaScript);
//Embedding java script
document.getDocumentCatalog().setOpenAction(PDAjavascript);
//Saving the document
document.save( new File("C:/PdfBox_Examples/new.pdf") );
System.out.println("Data added to the given PDF");
//Closing the document
document.close();
}
}
Compile and execute the saved Java file from the command prompt using the following commands.
javac AddJavaScript.java
java AddJavaScript
Upon execution, the above program embeds JavaScript in the given PDF document displaying the following message.
Data added to the given PDF
If you try to open the document new.pdf it will display an alert message as shown below.
In the previous chapter, we have seen how to add JavaScript to a PDF document. Let us now learn how to split a given PDF document into multiple documents.
You can split the given PDF document in to multiple PDF documents using the class named Splitter. This class is used to split the given PDF document into several other documents.
Following are the steps to split an existing PDF document
Load an existing PDF document using the static method load() of the PDDocument class. This method accepts a file object as a parameter, since this is a static method you can invoke it using class name as shown below.
File file = new File("path of the document")
PDDocument document = PDDocument.load(file);
The class named Splitter contains the methods to split the given PDF document therefore, instantiate this class as shown below.
Splitter splitter = new Splitter();
You can split the given document using the Split() method of the Splitter class this class. This method accepts an object of the PDDocument class as a parameter.
List<PDDocument> Pages = splitter.split(document);
The split() method splits each page of the given document as an individual document and returns all these in the form of a list.
In order to traverse through the list of documents you need to get an iterator object of the list acquired in the above step, you need to get the iterator object of the list using the listIterator() method as shown below.
Iterator<PDDocument> iterator = Pages.listIterator();
Finally, close the document using close() method of PDDocument class as shown below.
document.close();
Suppose, there is a PDF document with name sample.pdf in the path C:\PdfBox_Examples\ and this document contains two pages — one page containing image and another page containing text as shown below.
This example demonstrates how to split the above mentioned PDF document. Here, we will split the PDF document named sample.pdf into two different documents sample1.pdf and sample2.pdf. Save this code in a file with name SplitPages.java.
import org.apache.pdfbox.multipdf.Splitter;
import org.apache.pdfbox.pdmodel.PDDocument;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Iterator;
public class SplitPages {
public static void main(String[] args) throws IOException {
//Loading an existing PDF document
File file = new File("C:/PdfBox_Examples/sample.pdf");
PDDocument document = PDDocument.load(file);
//Instantiating Splitter class
Splitter splitter = new Splitter();
//splitting the pages of a PDF document
List<PDDocument> Pages = splitter.split(document);
//Creating an iterator
Iterator<PDDocument> iterator = Pages.listIterator();
//Saving each page as an individual document
int i = 1;
while(iterator.hasNext()) {
PDDocument pd = iterator.next();
pd.save("C:/PdfBox_Examples/sample"+ i++ +".pdf");
}
System.out.println("Multiple PDF’s created");
document.close();
}
}
Compile and execute the saved Java file from the command prompt using the following commands
javac SplitPages.java
java SplitPages
Upon execution, the above program encrypts the given PDF document displaying the following message.
Multiple PDF’s created
If you verify the given path, you can observe that multiple PDFs were created with names sample1 and sample2 as shown below.
In the previous chapter, we have seen how to split a given PDF document into multiple documents. Let us now learn how to merge multiple PDF documents as a single document.
You can merge multiple PDF documents into a single PDF document using the class named PDFMergerUtility class, this class provides methods to merge two or more PDF documents in to a single PDF document.
Following are the steps to merge multiple PDF documents.
Instantiate the merge utility class as shown below.
PDFMergerUtility PDFmerger = new PDFMergerUtility();
Set the destination files using the setDestinationFileName() method as shown below.
PDFmerger.setDestinationFileName("C:/PdfBox_Examples/data1/merged.pdf");
Set the source files using the addSource() method as shown below.
File file = new File("path of the document")
PDFmerger.addSource(file);
Merge the documents using the mergeDocuments() method of the PDFmerger class as shown below.
PDFmerger.mergeDocuments();
Suppose, we have two PDF documents — sample1.pdf and sample2.pdf, in the path C:\PdfBox_Examples\ as shown below.
This example demonstrates how to merge the above PDF documents. Here, we will merge the PDF documents named sample1.pdf and sample2.pdf in to a single PDF document merged.pdf. Save this code in a file with name MergePDFs.java.
import org.apache.pdfbox.multipdf.PDFMergerUtility;
import java.io.File;
import java.io.IOException;
public class MergePDFs {
public static void main(String[] args) throws IOException {
File file1 = new File("C:\\EXAMPLES\\Demo1.pdf");
File file2 = new File("C:\\EXAMPLES\\Demo2.pdf");
//Instantiating PDFMergerUtility class
PDFMergerUtility PDFmerger = new PDFMergerUtility();
//Setting the destination file
PDFmerger.setDestinationFileName("C:\\Examples\\merged.pdf");
//adding the source files
PDFmerger.addSource(file1);
PDFmerger.addSource(file2);
//Merging the two documents
PDFmerger.mergeDocuments();
System.out.println("Documents merged");
}
}
Compile and execute the saved Java file from the command prompt using the following commands.
javac MergePDFs.java
java MergePDFs
Upon execution, the above program encrypts the given PDF document displaying the following message.
Documents merged
If you verify the given path, you can observe that a PDF document with name merged.pdf is created and this contains the pages of both the source documents as shown below.
In the previous chapter, we have seen how to merge multiple PDF documents. In this chapter, we will understand how to extract an image from a page of a PDF document.
PDFBox library provides you a class named PDFRenderer which renders a PDF document into an AWT BufferedImage.
Following are the steps to generate an image from a PDF document.
Load an existing PDF document using the static method load() of the PDDocument class. This method accepts a file object as a parameter, since this is a static method you can invoke it using class name as shown below.
File file = new File("path of the document")
PDDocument document = PDDocument.load(file);
The class named PDFRenderer renders a PDF document into an AWT BufferedImage. Therefore, you need to instantiate this class as shown below. The constructor of this class accepts a document object; pass the document object created in the previous step as shown below.
PDFRenderer renderer = new PDFRenderer(document);
You can render the image in a particular page using the method renderImage() of the Renderer class, to this method you need to pass the index of the page where you have the image that is to be rendered.
BufferedImage image = renderer.renderImage(0);
You can write the image rendered in the previous step to a file using the write() method. To this method, you need to pass three parameters −
The rendered image object.
String representing the type of the image (jpg or png).
File object to which you need to save the extracted image.
ImageIO.write(image, "JPEG", new File("C:/PdfBox_Examples/myimage.jpg"));
Finally, close the document using the close() method of the PDDocument class as shown below.
document.close();
Suppose, we have a PDF document — sample.pdf in the path C:\PdfBox_Examples\ and this contains an image in its first page as shown below.
This example demonstrates how to convert the above PDF document into an image file. Here, we will retrieve the image in the 1st page of the PDF document and save it as myimage.jpg. Save this code as PdfToImage.java
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
public class PdfToImage {
public static void main(String args[]) throws Exception {
//Loading an existing PDF document
File file = new File("C:/PdfBox_Examples/sample.pdf");
PDDocument document = PDDocument.load(file);
//Instantiating the PDFRenderer class
PDFRenderer renderer = new PDFRenderer(document);
//Rendering an image from the PDF document
BufferedImage image = renderer.renderImage(0);
//Writing the image to a file
ImageIO.write(image, "JPEG", new File("C:/PdfBox_Examples/myimage.jpg"));
System.out.println("Image created");
//Closing the document
document.close();
}
}
Compile and execute the saved Java file from the command prompt using the following commands.
javac PdfToImage.java
java PdfToImage
Upon execution, the above program retrieves the image in the given PDF document displaying the following message.
Image created
If you verify the given path, you can observe that the image is generated and saved as myimage.jpg as shown below.
This chapter teaches you how to create color boxes in a page of a PDF document.
You can add rectangular boxes in a PDF page using the addRect() method of the PDPageContentStream class.
Following are the steps to create rectangular shapes in a page of a PDF document.
Load an existing PDF document using the static method load() of the PDDocument class. This method accepts a file object as a parameter, since this is a static method you can invoke it using class name as shown below.
File file = new File("path of the document")
PDDocument document = PDDocument.load(file);
You need to retrieve the PDPage object of the required page where you want to add rectangles using the getPage() method of the PDDocument class. To this method you need to pass the index of the page where you want to add rectangles.
PDPage page = document.getPage(0);
You can insert various kinds of data elements using the object of the class named PDPageContentStream. You need to pass the document object and the page object to the constructor of this class therefore, instantiate this class by passing these two objects created in the previous steps as shown below.
PDPageContentStream contentStream = new PDPageContentStream(document, page);
You can set the non-stroking color to the rectangle using the setNonStrokingColor() method of the class PDPageContentStream. To this method, you need to pass the required color as a parameter as shown below.
contentStream.setNonStrokingColor(Color.DARK_GRAY);
Draw the rectangle with required dimensions using the addRect() method. To this method, you need to pass the dimensions of the rectangle that is to be added as shown below.
contentStream.addRect(200, 650, 100, 100);
The fill() method of the PDPageContentStream class fills the path between the specified dimensions with the required color as shown below.
contentStream.fill();
Finally close the document using close() method of the PDDocument class as shown below.
document.close();
Suppose we have a PDF document named blankpage.pdf in the path C:\PdfBox_Examples\ and this contains a single blank page as shown below.
This example demonstrates how to create/insert rectangles in a PDF document. Here, we will create a box in a Blank PDF. Save this code as AddRectangles.java.
import java.awt.Color;
import java.io.File;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
public class ShowColorBoxes {
public static void main(String args[]) throws Exception {
//Loading an existing document
File file = new File("C:/PdfBox_Examples/BlankPage.pdf");
PDDocument document = PDDocument.load(file);
//Retrieving a page of the PDF Document
PDPage page = document.getPage(0);
//Instantiating the PDPageContentStream class
PDPageContentStream contentStream = new PDPageContentStream(document, page);
//Setting the non stroking color
contentStream.setNonStrokingColor(Color.DARK_GRAY);
//Drawing a rectangle
contentStream.addRect(200, 650, 100, 100);
//Drawing a rectangle
contentStream.fill();
System.out.println("rectangle added");
//Closing the ContentStream object
contentStream.close();
//Saving the document
File file1 = new File("C:/PdfBox_Examples/colorbox.pdf");
document.save(file1);
//Closing the document
document.close();
}
}
Compile and execute the saved Java file from the command prompt using the following commands.
javac AddRectangles.java
java AddRectangles
Upon execution, the above program creates a rectangle in a PDF document displaying the following image.
Rectangle created
If you verify the given path and open the saved document — colorbox.pdf, you can observe that a box is inserted in it as shown below.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2196,
"s": 2027,
"text": "The Portable Document Format (PDF) is a file format that helps to present data in a manner that is independent of Application software, hardware, and operating systems."
},
{
"code": null,
"e": 2342,
"s": 2196,
"text": "Each PDF file holds description of a fixed-layout flat document, including the text, fonts, graphics, and other information needed to display it."
},
{
"code": null,
"e": 2447,
"s": 2342,
"text": "There are several libraries available to create and manipulate PDF documents through programs, such as −"
},
{
"code": null,
"e": 2609,
"s": 2447,
"text": "Adobe PDF Library − This library provides API in languages such as C++, .NET and Java and using this we can edit, view print and extract text from PDF documents."
},
{
"code": null,
"e": 2771,
"s": 2609,
"text": "Adobe PDF Library − This library provides API in languages such as C++, .NET and Java and using this we can edit, view print and extract text from PDF documents."
},
{
"code": null,
"e": 2934,
"s": 2771,
"text": "Formatting Objects Processor − Open-source print formatter driven by XSL Formatting Objects and an output independent formatter. The primary output target is PDF."
},
{
"code": null,
"e": 3097,
"s": 2934,
"text": "Formatting Objects Processor − Open-source print formatter driven by XSL Formatting Objects and an output independent formatter. The primary output target is PDF."
},
{
"code": null,
"e": 3268,
"s": 3097,
"text": "iText − This library provides API in languages such as Java, C#, and other .NET languages and using this library we can create and manipulate PDF, RTF and HTML documents."
},
{
"code": null,
"e": 3439,
"s": 3268,
"text": "iText − This library provides API in languages such as Java, C#, and other .NET languages and using this library we can create and manipulate PDF, RTF and HTML documents."
},
{
"code": null,
"e": 3600,
"s": 3439,
"text": "JasperReports − This is a Java reporting tool which generates reports in PDF document including Microsoft Excel, RTF, ODT, comma-separated values and XML files."
},
{
"code": null,
"e": 3761,
"s": 3600,
"text": "JasperReports − This is a Java reporting tool which generates reports in PDF document including Microsoft Excel, RTF, ODT, comma-separated values and XML files."
},
{
"code": null,
"e": 3970,
"s": 3761,
"text": "Apache PDFBox is an open-source Java library that supports the development and conversion of PDF documents. Using this library, you can develop Java programs that create, convert and manipulate PDF documents."
},
{
"code": null,
"e": 4108,
"s": 3970,
"text": "In addition to this, PDFBox also includes a command line utility for performing various operations over PDF using the available Jar file."
},
{
"code": null,
"e": 4155,
"s": 4108,
"text": "Following are the notable features of PDFBox −"
},
{
"code": null,
"e": 4229,
"s": 4155,
"text": "Extract Text − Using PDFBox, you can extract Unicode text from PDF files."
},
{
"code": null,
"e": 4303,
"s": 4229,
"text": "Extract Text − Using PDFBox, you can extract Unicode text from PDF files."
},
{
"code": null,
"e": 4425,
"s": 4303,
"text": "Split & Merge − Using PDFBox, you can divide a single PDF file into multiple files, and merge them back as a single file."
},
{
"code": null,
"e": 4547,
"s": 4425,
"text": "Split & Merge − Using PDFBox, you can divide a single PDF file into multiple files, and merge them back as a single file."
},
{
"code": null,
"e": 4616,
"s": 4547,
"text": "Fill Forms − Using PDFBox, you can fill the form data in a document."
},
{
"code": null,
"e": 4685,
"s": 4616,
"text": "Fill Forms − Using PDFBox, you can fill the form data in a document."
},
{
"code": null,
"e": 4770,
"s": 4685,
"text": "Print − Using PDFBox, you can print a PDF file using the standard Java printing API."
},
{
"code": null,
"e": 4855,
"s": 4770,
"text": "Print − Using PDFBox, you can print a PDF file using the standard Java printing API."
},
{
"code": null,
"e": 4940,
"s": 4855,
"text": "Save as Image − Using PDFBox, you can save PDFs as image files, such as PNG or JPEG."
},
{
"code": null,
"e": 5025,
"s": 4940,
"text": "Save as Image − Using PDFBox, you can save PDFs as image files, such as PNG or JPEG."
},
{
"code": null,
"e": 5153,
"s": 5025,
"text": "Create PDFs − Using PDFBox, you can create a new PDF file by creating Java programs and, you can also include images and fonts."
},
{
"code": null,
"e": 5281,
"s": 5153,
"text": "Create PDFs − Using PDFBox, you can create a new PDF file by creating Java programs and, you can also include images and fonts."
},
{
"code": null,
"e": 5353,
"s": 5281,
"text": "Signing− Using PDFBox, you can add digital signatures to the PDF files."
},
{
"code": null,
"e": 5425,
"s": 5353,
"text": "Signing− Using PDFBox, you can add digital signatures to the PDF files."
},
{
"code": null,
"e": 5472,
"s": 5425,
"text": "The following are the applications of PDFBox −"
},
{
"code": null,
"e": 5681,
"s": 5472,
"text": "Apache Nutch − Apache Nutch is an open-source web-search software. It builds on Apache Lucene, adding web-specifics, such as a crawler, a link-graph database, parsers for HTML and other document formats, etc."
},
{
"code": null,
"e": 5890,
"s": 5681,
"text": "Apache Nutch − Apache Nutch is an open-source web-search software. It builds on Apache Lucene, adding web-specifics, such as a crawler, a link-graph database, parsers for HTML and other document formats, etc."
},
{
"code": null,
"e": 6051,
"s": 5890,
"text": "Apache Tika − Apache Tika is a toolkit for detecting and extracting metadata and structured text content from various documents using existing parser libraries."
},
{
"code": null,
"e": 6212,
"s": 6051,
"text": "Apache Tika − Apache Tika is a toolkit for detecting and extracting metadata and structured text content from various documents using existing parser libraries."
},
{
"code": null,
"e": 6267,
"s": 6212,
"text": "The following are the four main components of PDFBox −"
},
{
"code": null,
"e": 6402,
"s": 6267,
"text": "PDFBox − This is the main part of the PDFBox. This contains the classes and interfaces related to content extraction and manipulation."
},
{
"code": null,
"e": 6537,
"s": 6402,
"text": "PDFBox − This is the main part of the PDFBox. This contains the classes and interfaces related to content extraction and manipulation."
},
{
"code": null,
"e": 6685,
"s": 6537,
"text": "FontBox − This contains the classes and interfaces related to font, and using these classes we can modify the font of the text of the PDF document."
},
{
"code": null,
"e": 6833,
"s": 6685,
"text": "FontBox − This contains the classes and interfaces related to font, and using these classes we can modify the font of the text of the PDF document."
},
{
"code": null,
"e": 6909,
"s": 6833,
"text": "XmpBox − This contains the classes and interfaces that handle XMP metadata."
},
{
"code": null,
"e": 6985,
"s": 6909,
"text": "XmpBox − This contains the classes and interfaces that handle XMP metadata."
},
{
"code": null,
"e": 7075,
"s": 6985,
"text": "Preflight − This component is used to verify the PDF files against the PDF/A-1b standard."
},
{
"code": null,
"e": 7165,
"s": 7075,
"text": "Preflight − This component is used to verify the PDF files against the PDF/A-1b standard."
},
{
"code": null,
"e": 7217,
"s": 7165,
"text": "Following are the steps to download Apache PDFBox −"
},
{
"code": null,
"e": 7324,
"s": 7217,
"text": "Step 1 − Open the homepage of Apache PDFBox by clicking on the following link − https://pdfbox.apache.org/"
},
{
"code": null,
"e": 7419,
"s": 7324,
"text": "Step 2 − The above link will direct you to the homepage as shown in the following screenshot −"
},
{
"code": null,
"e": 7602,
"s": 7419,
"text": "Step 3 − Now, click on the Downloads link highlighted in the above screenshot. On clicking, you will be directed to the downloads page of PDFBox as shown in the following screenshot."
},
{
"code": null,
"e": 7871,
"s": 7602,
"text": "Step 4 − In the Downloads page, you will have links for PDFBox. Click on the respective link for the latest release. For instance, we are opting for PDFBox 2.0.1 and on clicking this, you will be directed to the required jar files as shown in the following screenshot."
},
{
"code": null,
"e": 8007,
"s": 7871,
"text": "Step 5 − Download the jar files pdfbox-2.0.1.jar, fontbox-2.0.1.jar, preflight-2.0.1.jar, xmpbox-2.0.1.jar and, pdfbox-tools-2.0.1.jar."
},
{
"code": null,
"e": 8195,
"s": 8007,
"text": "After downloading the required jar files, you have to embed these JAR files to your Eclipse environment. You can do this by setting the Build path to these JAR files and by using pom.xml."
},
{
"code": null,
"e": 8250,
"s": 8195,
"text": "Following are the steps to install PDFBox in Eclipse −"
},
{
"code": null,
"e": 8367,
"s": 8250,
"text": "Step 1 − Ensure that you have installed Eclipse in your system. If not, download and install Eclipse in your system."
},
{
"code": null,
"e": 8471,
"s": 8367,
"text": "Step 2 − Open Eclipse, click on File, New, and Open a new project as shown in the following screenshot."
},
{
"code": null,
"e": 8649,
"s": 8471,
"text": "Step 3 − On selecting the project, you will get New Project wizard. In this wizard, select Java project and proceed by clicking Next button as shown in the following screenshot."
},
{
"code": null,
"e": 8811,
"s": 8649,
"text": "Step 4 − On proceeding forward, you will be directed to the New Java Project wizard. Create a new project and click on Next as shown in the following screenshot."
},
{
"code": null,
"e": 8962,
"s": 8811,
"text": "Step 5 − After creating a new project, right click on it; select Build Path and click on Configure Build Path... as shown in the following screenshot."
},
{
"code": null,
"e": 9127,
"s": 8962,
"text": "Step 6 − On clicking on the Build Path option you will be directed to the Java Build Path wizard. Select the Add External JARs as shown in the following screenshot."
},
{
"code": null,
"e": 9294,
"s": 9127,
"text": "Step 7 − Select the jar files fontbox-2.0.1.jar, pdfbox-2.0.1.jar, pdfbox-tools-2.0.1.jar, preflight-2.0.1.jar, xmpbox-2.0.1.jar as shown in the following screenshot."
},
{
"code": null,
"e": 9436,
"s": 9294,
"text": "Step 8 − On clicking the Open button in the above screenshot, those files will be added to your library as shown in the following screenshot."
},
{
"code": null,
"e": 9650,
"s": 9436,
"text": "Step 9 − On clicking OK, you will successfully add the required JAR files to the current project and you can verify these added libraries by expanding the Referenced Libraries as shown in the following screenshot."
},
{
"code": null,
"e": 9736,
"s": 9650,
"text": "Convert the project into maven project and add the following contents to its pom.xml."
},
{
"code": null,
"e": 11560,
"s": 9736,
"text": "<project xmlns=\"https://maven.apache.org/POM/4.0.0\"\n xmlns:xsi=\"https://www.w3.org/2001/XMLSchema-instance\" \n xsi:schemaLocation=\"https://maven.apache.org/POM/4.0.0\n https://maven.apache.org/xsd/maven-4.0.0.xsd\">\n <modelVersion>4.0.0</modelVersion>\n <groupId>my_project</groupId>\n <artifactId>my_project</artifactId>\n <version>0.0.1-SNAPSHOT</version>\n\n <build>\n <sourceDirectory>src</sourceDirectory>\n <plugins>\n <plugin>\n <artifactId>maven-compiler-plugin</artifactId>\n <version>3.3</version>\n <configuration>\n <source>1.8</source>\n <target>1.8</target>\n </configuration> \n </plugin>\n </plugins> \n </build> \n \n <dependencies> \n <dependency> \n <groupId>org.apache.pdfbox</groupId> \n <artifactId>pdfbox</artifactId> \n <version>2.0.1</version> \n </dependency> \n \n <dependency> \n <groupId>org.apache.pdfbox</groupId> \n <artifactId>fontbox</artifactId> \n <version>2.0.0</version> \n </dependency>\n \n <dependency> \n <groupId>org.apache.pdfbox</groupId> \n <artifactId>jempbox</artifactId> \n <version>1.8.11</version> \n </dependency> \n \n <dependency>\n <groupId>org.apache.pdfbox</groupId> \n <artifactId>xmpbox</artifactId> \n <version>2.0.0</version> \n </dependency> \n \n <dependency> \n <groupId>org.apache.pdfbox</groupId> \n <artifactId>preflight</artifactId> \n <version>2.0.0</version> \n </dependency> \n \n <dependency> \n <groupId>org.apache.pdfbox</groupId> \n <artifactId>pdfbox-tools</artifactId> \n <version>2.0.0</version> \n </dependency>\n\n </dependencies>\n \n</project>"
},
{
"code": null,
"e": 11637,
"s": 11560,
"text": "Let us now understand how to create a PDF document using the PDFBox library."
},
{
"code": null,
"e": 11789,
"s": 11637,
"text": "You can create an empty PDF Document by instantiating the PDDocument class. You can save the document in your desired location using the Save() method."
},
{
"code": null,
"e": 11846,
"s": 11789,
"text": "Following are the steps to create an empty PDF document."
},
{
"code": null,
"e": 12087,
"s": 11846,
"text": "The PDDocument class that belongs to the package org.apache.pdfbox.pdmodel, is an In-memory representation of the PDFDocument. Therefore, by instantiating this class, you can create an empty PDFDocument as shown in the following code block."
},
{
"code": null,
"e": 12128,
"s": 12087,
"text": "PDDocument document = new PDDocument();\n"
},
{
"code": null,
"e": 12457,
"s": 12128,
"text": "After creating the document, you need to save this document in the desired path, you can do so using the Save() method of the PDDocument class. This method accepts a string value, representing the path where you want to store the document, as a parameter. Following is the prototype of the save() method of the PDDocument class."
},
{
"code": null,
"e": 12481,
"s": 12457,
"text": "document.save(\"Path\");\n"
},
{
"code": null,
"e": 12659,
"s": 12481,
"text": "When your task is completed, at the end, you need to close the PDDocument object using the close () method. Following is the prototype of the close() method of PDDocument class."
},
{
"code": null,
"e": 12678,
"s": 12659,
"text": "document.close();\n"
},
{
"code": null,
"e": 12920,
"s": 12678,
"text": "This example demonstrates the creation of a PDF Document. Here, we will create a Java program to generate a PDF document named my_doc.pdf and save it in the path C:/PdfBox_Examples/. Save this code in a file with name Document_Creation.java."
},
{
"code": null,
"e": 13408,
"s": 12920,
"text": "import java.io.IOException; \nimport org.apache.pdfbox.pdmodel.PDDocument;\n \npublic class Document_Creation {\n \n public static void main (String args[]) throws IOException {\n \n //Creating PDF document object \n PDDocument document = new PDDocument(); \n \n //Saving the document\n document.save(\"C:/PdfBox_Examples/my_doc.pdf\");\n \n System.out.println(\"PDF created\"); \n \n //Closing the document \n document.close();\n\n } \n}"
},
{
"code": null,
"e": 13502,
"s": 13408,
"text": "Compile and execute the saved Java file from the command prompt using the following commands."
},
{
"code": null,
"e": 13556,
"s": 13502,
"text": "javac Document_Creation.java \njava Document_Creation\n"
},
{
"code": null,
"e": 13647,
"s": 13556,
"text": "Upon execution, the above program creates a PDF document displaying the following message."
},
{
"code": null,
"e": 13659,
"s": 13647,
"text": "PDF created"
},
{
"code": null,
"e": 13747,
"s": 13659,
"text": "If you verify the specified path, you can find the created PDF document as shown below."
},
{
"code": null,
"e": 13904,
"s": 13747,
"text": "Since this is an empty document, if you try to open this document, this gives you a prompt displaying an error message as shown in the following screenshot."
},
{
"code": null,
"e": 14090,
"s": 13904,
"text": "In the previous chapter, we have seen how to create a PDF document. After creating a PDF document, you need to add pages to it. Let us now understand how to add pages in a PDF document."
},
{
"code": null,
"e": 14236,
"s": 14090,
"text": "You can create an empty page by instantiating the PDPage class and add it to the PDF document using the addPage() method of the PDDocument class."
},
{
"code": null,
"e": 14309,
"s": 14236,
"text": "Following are the steps to create an empty document and add pages to it."
},
{
"code": null,
"e": 14392,
"s": 14309,
"text": "Create an empty PDF document by instantiating the PDDocument class as shown below."
},
{
"code": null,
"e": 14433,
"s": 14392,
"text": "PDDocument document = new PDDocument();\n"
},
{
"code": null,
"e": 14594,
"s": 14433,
"text": "The PDPage class represents a page in the PDF document therefore, you can create an empty page by instantiating this class as shown in the following code block."
},
{
"code": null,
"e": 14626,
"s": 14594,
"text": "PDPage my_page = new PDPage();\n"
},
{
"code": null,
"e": 14783,
"s": 14626,
"text": "You can add a page to the PDF document using the addPage() method of the PDDocument class. To this method you need to pass the PDPage object as a parameter."
},
{
"code": null,
"e": 14905,
"s": 14783,
"text": "Therefore, add the blank page created in the previous step to the PDDocument object as shown in the following code block."
},
{
"code": null,
"e": 14933,
"s": 14905,
"text": "document.addPage(my_page);\n"
},
{
"code": null,
"e": 15002,
"s": 14933,
"text": "In this way you can add as many pages as you want to a PDF document."
},
{
"code": null,
"e": 15138,
"s": 15002,
"text": "After adding all the pages, save the PDF document using the save() method of the PDDocument class as shown in the following code block."
},
{
"code": null,
"e": 15162,
"s": 15138,
"text": "document.save(\"Path\");\n"
},
{
"code": null,
"e": 15254,
"s": 15162,
"text": "Finally close the document using the close() method of the PDDocument class as shown below."
},
{
"code": null,
"e": 15273,
"s": 15254,
"text": "document.close();\n"
},
{
"code": null,
"e": 15538,
"s": 15273,
"text": "This example demonstrates how to create a PDF Document and add pages to it. Here we will create a PDF Document named my_doc.pdf and further add 10 blank pages to it, and save it in the path C:/PdfBox_Examples/. Save this code in a file with name Adding_pages.java."
},
{
"code": null,
"e": 16267,
"s": 15538,
"text": "package document;\n \nimport java.io.IOException;\n\nimport org.apache.pdfbox.pdmodel.PDDocument;\nimport org.apache.pdfbox.pdmodel.PDPage;\n\npublic class Adding_Pages {\n\n public static void main(String args[]) throws IOException {\n \n //Creating PDF document object \n PDDocument document = new PDDocument();\n\n for (int i=0; i<10; i++) {\n //Creating a blank page \n PDPage blankPage = new PDPage();\n\n //Adding the blank page to the document\n document.addPage( blankPage );\n } \n \n //Saving the document\n document.save(\"C:/PdfBox_Examples/my_doc.pdf\");\n System.out.println(\"PDF created\");\n \n //Closing the document\n document.close();\n\n } \n} "
},
{
"code": null,
"e": 16362,
"s": 16267,
"text": "Compile and execute the saved Java file from the command prompt using the following commands −"
},
{
"code": null,
"e": 16407,
"s": 16362,
"text": "javac Adding_pages.java \njava Adding_pages \n"
},
{
"code": null,
"e": 16516,
"s": 16407,
"text": "Upon execution, the above program creates a PDF document with blank pages displaying the following message −"
},
{
"code": null,
"e": 16530,
"s": 16516,
"text": "PDF created \n"
},
{
"code": null,
"e": 16640,
"s": 16530,
"text": "If you verify the specified path, you can find the created PDF document as shown in the following screenshot."
},
{
"code": null,
"e": 16853,
"s": 16640,
"text": "In the previous examples, you have seen how to create a new document and add pages to it. This chapter teaches you how to load a PDF document that already exists in your system, and perform some operations on it."
},
{
"code": null,
"e": 17000,
"s": 16853,
"text": "The load() method of the PDDocument class is used to load an existing PDF document. Follow the steps given below to load an existing PDF document."
},
{
"code": null,
"e": 17217,
"s": 17000,
"text": "Load an existing PDF document using the static method load() of the PDDocument class. This method accepts a file object as a parameter, since this is a static method you can invoke it using class name as shown below."
},
{
"code": null,
"e": 17287,
"s": 17217,
"text": "File file = new File(\"path of the document\") \nPDDocument.load(file);\n"
},
{
"code": null,
"e": 17391,
"s": 17287,
"text": "Perform the required operations such as adding pages adding text, adding images to the loaded document."
},
{
"code": null,
"e": 17527,
"s": 17391,
"text": "After adding all the pages, save the PDF document using the save() method of the PDDocument class as shown in the following code block."
},
{
"code": null,
"e": 17551,
"s": 17527,
"text": "document.save(\"Path\");\n"
},
{
"code": null,
"e": 17643,
"s": 17551,
"text": "Finally close the document using the close() method of the PDDocument class as shown below."
},
{
"code": null,
"e": 17662,
"s": 17643,
"text": "document.close();\n"
},
{
"code": null,
"e": 17794,
"s": 17662,
"text": "Suppose we have a PDF document which contains a single page, in the path, C:/PdfBox_Examples/ as shown in the following screenshot."
},
{
"code": null,
"e": 17985,
"s": 17794,
"text": "This example demonstrates how to load an existing PDF Document. Here, we will load the PDF document sample.pdf shown above, add a page to it, and save it in the same path with the same name."
},
{
"code": null,
"e": 18059,
"s": 17985,
"text": "Step 1 − Save this code in a file with name LoadingExistingDocument.java."
},
{
"code": null,
"e": 18759,
"s": 18059,
"text": "import java.io.File;\nimport java.io.IOException;\n \nimport org.apache.pdfbox.pdmodel.PDDocument; \nimport org.apache.pdfbox.pdmodel.PDPage;\npublic class LoadingExistingDocument {\n\n public static void main(String args[]) throws IOException {\n \n //Loading an existing document \n File file = new File(\"C:/PdfBox_Examples/sample.pdf\"); \n PDDocument document = PDDocument.load(file); \n \n System.out.println(\"PDF loaded\"); \n \n //Adding a blank page to the document \n document.addPage(new PDPage()); \n\n //Saving the document \n document.save(\"C:/PdfBox_Examples/sample.pdf\");\n\n //Closing the document \n document.close(); \n \n } \n}"
},
{
"code": null,
"e": 18852,
"s": 18759,
"text": "Compile and execute the saved Java file from the command prompt using the following commands"
},
{
"code": null,
"e": 18920,
"s": 18852,
"text": "javac LoadingExistingDocument.java \njava LoadingExistingDocument \n"
},
{
"code": null,
"e": 19049,
"s": 18920,
"text": "Upon execution, the above program loads the specified PDF document and adds a blank page to it displaying the following message."
},
{
"code": null,
"e": 19061,
"s": 19049,
"text": "PDF loaded\n"
},
{
"code": null,
"e": 19179,
"s": 19061,
"text": "If you verify the specified path, you can find an additional page added to the specified PDF document as shown below."
},
{
"code": null,
"e": 19237,
"s": 19179,
"text": "Let us now learn how to remove pages from a PDF document."
},
{
"code": null,
"e": 19344,
"s": 19237,
"text": "You can remove a page from an existing PDF document using the removePage() method of the PDDocument class."
},
{
"code": null,
"e": 19561,
"s": 19344,
"text": "Load an existing PDF document using the static method load() of the PDDocument class. This method accepts a file object as a parameter, since this is a static method you can invoke it using class name as shown below."
},
{
"code": null,
"e": 19631,
"s": 19561,
"text": "File file = new File(\"path of the document\") \nPDDocument.load(file);\n"
},
{
"code": null,
"e": 19748,
"s": 19631,
"text": "You can list the number of pages that exists in the PDF document using the getNumberOfPages() method as shown below."
},
{
"code": null,
"e": 19822,
"s": 19748,
"text": "int noOfPages= document.getNumberOfPages();\nSystem.out.print(noOfPages);\n"
},
{
"code": null,
"e": 19999,
"s": 19822,
"text": "You can remove a page from the PDF document using the removePage() method of the PDDocument class. To this method, you need to pass the index of the page that is to be deleted."
},
{
"code": null,
"e": 20196,
"s": 19999,
"text": "While specifying the index for the pages in a PDF document, keep in mind that indexing of these pages starts from zero, i.e., if you want to delete the 1st page then the index value needs to be 0."
},
{
"code": null,
"e": 20221,
"s": 20196,
"text": "document.removePage(2);\n"
},
{
"code": null,
"e": 20354,
"s": 20221,
"text": "After removing the page, save the PDF document using the save() method of the PDDocument class as shown in the following code block."
},
{
"code": null,
"e": 20378,
"s": 20354,
"text": "document.save(\"Path\");\n"
},
{
"code": null,
"e": 20471,
"s": 20378,
"text": "Finally, close the document using the close() method of the PDDocument class as shown below."
},
{
"code": null,
"e": 20490,
"s": 20471,
"text": "document.close();\n"
},
{
"code": null,
"e": 20593,
"s": 20490,
"text": "Suppose, we have a PDF document with name sample.pdf and it contains three empty pages as shown below."
},
{
"code": null,
"e": 20864,
"s": 20593,
"text": "This example demonstrates how to remove pages from an existing PDF document. Here, we will load the above specified PDF document named sample.pdf, remove a page from it, and save it in the path C:/PdfBox_Examples/. Save this code in a file with name Removing_pages.java."
},
{
"code": null,
"e": 21600,
"s": 20864,
"text": "import java.io.File;\nimport java.io.IOException;\n\nimport org.apache.pdfbox.pdmodel.PDDocument;\n\npublic class RemovingPages {\n\n public static void main(String args[]) throws IOException {\n\n //Loading an existing document\n File file = new File(\"C:/PdfBox_Examples/sample.pdf\");\n PDDocument document = PDDocument.load(file);\n \n //Listing the number of existing pages\n int noOfPages= document.getNumberOfPages();\n System.out.print(noOfPages);\n \n //Removing the pages\n document.removePage(2);\n \n System.out.println(\"page removed\");\n\n //Saving the document\n document.save(\"C:/PdfBox_Examples/sample.pdf\");\n\n //Closing the document\n document.close();\n\n }\n}"
},
{
"code": null,
"e": 21694,
"s": 21600,
"text": "Compile and execute the saved Java file from the command prompt using the following commands."
},
{
"code": null,
"e": 21741,
"s": 21694,
"text": "javac RemovingPages.java \njava RemovingPages \n"
},
{
"code": null,
"e": 21849,
"s": 21741,
"text": "Upon execution, the above program creates a PDF document with blank pages displaying the following message."
},
{
"code": null,
"e": 21865,
"s": 21849,
"text": "3\npage removed\n"
},
{
"code": null,
"e": 22007,
"s": 21865,
"text": "If you verify the specified path, you can find that the required page was deleted and only two pages remained in the document as shown below."
},
{
"code": null,
"e": 22171,
"s": 22007,
"text": "Like other files, a PDF document also has document properties. These properties are key-value pairs. Each property gives particular information about the document."
},
{
"code": null,
"e": 22220,
"s": 22171,
"text": "Following are the properties of a PDF document −"
},
{
"code": null,
"e": 22225,
"s": 22220,
"text": "File"
},
{
"code": null,
"e": 22267,
"s": 22225,
"text": "This property holds the name of the file."
},
{
"code": null,
"e": 22273,
"s": 22267,
"text": "Title"
},
{
"code": null,
"e": 22334,
"s": 22273,
"text": "Using this property, you can set the title for the document."
},
{
"code": null,
"e": 22341,
"s": 22334,
"text": "Author"
},
{
"code": null,
"e": 22415,
"s": 22341,
"text": "Using this property, you can set the name of the author for the document."
},
{
"code": null,
"e": 22423,
"s": 22415,
"text": "Subject"
},
{
"code": null,
"e": 22493,
"s": 22423,
"text": "Using this property, you can specify the subject of the PDF document."
},
{
"code": null,
"e": 22502,
"s": 22493,
"text": "Keywords"
},
{
"code": null,
"e": 22588,
"s": 22502,
"text": "Using this property, you can list the keywords with which we can search the document."
},
{
"code": null,
"e": 22596,
"s": 22588,
"text": "Created"
},
{
"code": null,
"e": 22664,
"s": 22596,
"text": "Using this property, you can set the date created for the document."
},
{
"code": null,
"e": 22673,
"s": 22664,
"text": "Modified"
},
{
"code": null,
"e": 22742,
"s": 22673,
"text": "Using this property, you can set the date modified for the document."
},
{
"code": null,
"e": 22754,
"s": 22742,
"text": "Application"
},
{
"code": null,
"e": 22820,
"s": 22754,
"text": "Using this property, you can set the Application of the document."
},
{
"code": null,
"e": 22898,
"s": 22820,
"text": "Following is a screenshot of the document properties table of a PDF document."
},
{
"code": null,
"e": 23006,
"s": 22898,
"text": "PDFBox provides you a class named PDDocumentInformation. This class has a set of setter and getter methods."
},
{
"code": null,
"e": 23158,
"s": 23006,
"text": "The setter methods of this class are used to set values to various properties of a document and getter methods which are used to retrieve these values."
},
{
"code": null,
"e": 23228,
"s": 23158,
"text": "Following are the setter methods of the PDDocumentInformation class. "
},
{
"code": null,
"e": 23253,
"s": 23228,
"text": "setAuthor(String author)"
},
{
"code": null,
"e": 23341,
"s": 23253,
"text": "This method is used to set the value for the property of the PDF document named Author."
},
{
"code": null,
"e": 23364,
"s": 23341,
"text": "setTitle(String title)"
},
{
"code": null,
"e": 23451,
"s": 23364,
"text": "This method is used to set the value for the property of the PDF document named Title."
},
{
"code": null,
"e": 23478,
"s": 23451,
"text": "setCreator(String creator)"
},
{
"code": null,
"e": 23567,
"s": 23478,
"text": "This method is used to set the value for the property of the PDF document named Creator."
},
{
"code": null,
"e": 23594,
"s": 23567,
"text": "setSubject(String subject)"
},
{
"code": null,
"e": 23683,
"s": 23594,
"text": "This method is used to set the value for the property of the PDF document named Subject."
},
{
"code": null,
"e": 23714,
"s": 23683,
"text": "setCreationDate(Calendar date)"
},
{
"code": null,
"e": 23808,
"s": 23714,
"text": "This method is used to set the value for the property of the PDF document named CreationDate."
},
{
"code": null,
"e": 23843,
"s": 23808,
"text": "setModificationDate(Calendar date)"
},
{
"code": null,
"e": 23941,
"s": 23843,
"text": "This method is used to set the value for the property of the PDF document named ModificationDate."
},
{
"code": null,
"e": 23975,
"s": 23941,
"text": "setKeywords(String keywords list)"
},
{
"code": null,
"e": 24065,
"s": 23975,
"text": "This method is used to set the value for the property of the PDF document named Keywords."
},
{
"code": null,
"e": 24235,
"s": 24065,
"text": "PDFBox provides a class called PDDocumentInformation and this class provides various methods. These methods can set various properties to the document and retrieve them."
},
{
"code": null,
"e": 24538,
"s": 24235,
"text": "This example demonstrates how to add properties such as Author, Title, Date, and Subject to a PDF document. Here, we will create a PDF document named doc_attributes.pdf, add various attributes to it, and save it in the path C:/PdfBox_Examples/. Save this code in a file with name AddingAttributes.java."
},
{
"code": null,
"e": 26225,
"s": 24538,
"text": "import java.io.IOException; \nimport java.util.Calendar; \nimport java.util.GregorianCalendar;\n \nimport org.apache.pdfbox.pdmodel.PDDocument;\nimport org.apache.pdfbox.pdmodel.PDDocumentInformation;\nimport org.apache.pdfbox.pdmodel.PDPage;\n\npublic class AddingDocumentAttributes {\n public static void main(String args[]) throws IOException {\n\n //Creating PDF document object\n PDDocument document = new PDDocument();\n\n //Creating a blank page\n PDPage blankPage = new PDPage();\n \n //Adding the blank page to the document\n document.addPage( blankPage );\n\n //Creating the PDDocumentInformation object \n PDDocumentInformation pdd = document.getDocumentInformation();\n\n //Setting the author of the document\n pdd.setAuthor(\"Tutorialspoint\");\n \n // Setting the title of the document\n pdd.setTitle(\"Sample document\"); \n \n //Setting the creator of the document \n pdd.setCreator(\"PDF Examples\"); \n \n //Setting the subject of the document \n pdd.setSubject(\"Example document\"); \n \n //Setting the created date of the document \n Calendar date = new GregorianCalendar();\n date.set(2015, 11, 5); \n pdd.setCreationDate(date);\n //Setting the modified date of the document \n date.set(2016, 6, 5); \n pdd.setModificationDate(date); \n \n //Setting keywords for the document \n pdd.setKeywords(\"sample, first example, my pdf\"); \n \n //Saving the document \n document.save(\"C:/PdfBox_Examples/doc_attributes.pdf\");\n\n System.out.println(\"Properties added successfully \");\n \n //Closing the document\n document.close();\n\n }\n}"
},
{
"code": null,
"e": 26319,
"s": 26225,
"text": "Compile and execute the saved Java file from the command prompt using the following commands."
},
{
"code": null,
"e": 26372,
"s": 26319,
"text": "javac AddingAttributes.java \njava AddingAttributes \n"
},
{
"code": null,
"e": 26490,
"s": 26372,
"text": "Upon execution, the above program adds all the specified attributes to the document displaying the following message."
},
{
"code": null,
"e": 26521,
"s": 26490,
"text": "Properties added successfully\n"
},
{
"code": null,
"e": 26676,
"s": 26521,
"text": "Now, if you visit the given path you can find the PDF created in it. Right click on the document and select the document properties option as shown below."
},
{
"code": null,
"e": 26816,
"s": 26676,
"text": "This will give you the document properties window and here you can observe all the properties of the document were set to specified values."
},
{
"code": null,
"e": 26932,
"s": 26816,
"text": "You can retrieve the properties of a document using the getter methods provided by the PDDocumentInformation class."
},
{
"code": null,
"e": 27001,
"s": 26932,
"text": "Following are the getter methods of the PDDocumentInformation class."
},
{
"code": null,
"e": 27013,
"s": 27001,
"text": "getAuthor()"
},
{
"code": null,
"e": 27106,
"s": 27013,
"text": "This method is used to retrieve the value for the property of the PDF document named Author."
},
{
"code": null,
"e": 27117,
"s": 27106,
"text": "getTitle()"
},
{
"code": null,
"e": 27209,
"s": 27117,
"text": "This method is used to retrieve the value for the property of the PDF document named Title."
},
{
"code": null,
"e": 27222,
"s": 27209,
"text": "getCreator()"
},
{
"code": null,
"e": 27316,
"s": 27222,
"text": "This method is used to retrieve the value for the property of the PDF document named Creator."
},
{
"code": null,
"e": 27329,
"s": 27316,
"text": "getSubject()"
},
{
"code": null,
"e": 27423,
"s": 27329,
"text": "This method is used to retrieve the value for the property of the PDF document named Subject."
},
{
"code": null,
"e": 27441,
"s": 27423,
"text": "getCreationDate()"
},
{
"code": null,
"e": 27540,
"s": 27441,
"text": "This method is used to retrieve the value for the property of the PDF document named CreationDate."
},
{
"code": null,
"e": 27562,
"s": 27540,
"text": "getModificationDate()"
},
{
"code": null,
"e": 27665,
"s": 27562,
"text": "This method is used to retrieve the value for the property of the PDF document named ModificationDate."
},
{
"code": null,
"e": 27679,
"s": 27665,
"text": "getKeywords()"
},
{
"code": null,
"e": 27774,
"s": 27679,
"text": "This method is used to retrieve the value for the property of the PDF document named Keywords."
},
{
"code": null,
"e": 28094,
"s": 27774,
"text": "This example demonstrates how to retrieve the properties of an existing PDF document. Here, we will create a Java program and load the PDF document named doc_attributes.pdf, which is saved in the path C:/PdfBox_Examples/, and retrieve its properties. Save this code in a file with name RetrivingDocumentAttributes.java."
},
{
"code": null,
"e": 29340,
"s": 28094,
"text": "import java.io.File; \nimport java.io.IOException;\n\nimport org.apache.pdfbox.pdmodel.PDDocument; \nimport org.apache.pdfbox.pdmodel.PDDocumentInformation;\n\npublic class RetrivingDocumentAttributes {\n public static void main(String args[]) throws IOException {\n \n //Loading an existing document \n File file = new File(\"C:/PdfBox_Examples/doc_attributes.pdf\")\n PDDocument document = PDDocument.load(file);\n //Getting the PDDocumentInformation object\n PDDocumentInformation pdd = document.getDocumentInformation();\n\n //Retrieving the info of a PDF document\n System.out.println(\"Author of the document is :\"+ pdd.getAuthor());\n System.out.println(\"Title of the document is :\"+ pdd.getTitle());\n System.out.println(\"Subject of the document is :\"+ pdd.getSubject());\n\n System.out.println(\"Creator of the document is :\"+ pdd.getCreator());\n System.out.println(\"Creation date of the document is :\"+ pdd.getCreationDate());\n System.out.println(\"Modification date of the document is :\"+ \n pdd.getModificationDate()); \n System.out.println(\"Keywords of the document are :\"+ pdd.getKeywords()); \n \n //Closing the document \n document.close(); \n } \n} "
},
{
"code": null,
"e": 29434,
"s": 29340,
"text": "Compile and execute the saved Java file from the command prompt using the following commands."
},
{
"code": null,
"e": 29508,
"s": 29434,
"text": "javac RetrivingDocumentAttributes.java \njava RetrivingDocumentAttributes\n"
},
{
"code": null,
"e": 29621,
"s": 29508,
"text": "Upon execution, the above program retrieves all the attributes of the document and displays them as shown below."
},
{
"code": null,
"e": 29947,
"s": 29621,
"text": "Author of the document is :Tutorialspoint \nTitle of the document is :Sample document \nSubject of the document is :Example document \nCreator of the document is :PDF Examples \nCreation date of the document is :11/5/2015\nModification date of the document is :6/5/2016\nKeywords of the document are :sample, first example, my pdf\n"
},
{
"code": null,
"e": 30099,
"s": 29947,
"text": "In the previous chapter, we discussed how to add pages to a PDF document. In this chapter, we will discuss how to add text to an existing PDF document."
},
{
"code": null,
"e": 30328,
"s": 30099,
"text": "You can add contents to a document using the PDFBox library, this provides you a class named PDPageContentStream which contains the required methods to insert text, images, and other types of contents in a page of a PDFDocument."
},
{
"code": null,
"e": 30414,
"s": 30328,
"text": "Following are the steps to create an empty document and add contents to a page in it."
},
{
"code": null,
"e": 30578,
"s": 30414,
"text": "You can load an existing document using the load() method of the PDDocument class. Therefore, instantiate this class and load the required document as shown below."
},
{
"code": null,
"e": 30664,
"s": 30578,
"text": "File file = new File(\"Path of the document\"); \nPDDocument doc = document.load(file);\n"
},
{
"code": null,
"e": 30829,
"s": 30664,
"text": "You can get the required page in a document using the getPage() method. Retrieve the object of the required page by passing its index to this method as shown below."
},
{
"code": null,
"e": 30860,
"s": 30829,
"text": "PDPage page = doc.getPage(1);\n"
},
{
"code": null,
"e": 31156,
"s": 30860,
"text": "You can insert various kinds of data elements using the object of the class PDPageContentStream. You need to pass the document object and the page object to the constructor of this class therefore, instantiate this class by passing these two objects created in the previous steps as shown below."
},
{
"code": null,
"e": 31229,
"s": 31156,
"text": "PDPageContentStream contentStream = new PDPageContentStream(doc, page);\n"
},
{
"code": null,
"e": 31415,
"s": 31229,
"text": "While inserting text in a PDF document, you can specify the start and end points of the text using the beginText() and endText() methods of the PDPageContentStream class as shown below."
},
{
"code": null,
"e": 31557,
"s": 31415,
"text": "contentStream.beginText(); \n............................. \ncode to add text content \n............................. \ncontentStream.endText();\n"
},
{
"code": null,
"e": 31628,
"s": 31557,
"text": "Therefore, begin the text using the beginText() method as shown below."
},
{
"code": null,
"e": 31656,
"s": 31628,
"text": "contentStream.beginText();\n"
},
{
"code": null,
"e": 31752,
"s": 31656,
"text": "Using the newLineAtOffset() method, you can set the position on the content stream in the page."
},
{
"code": null,
"e": 31830,
"s": 31752,
"text": "//Setting the position for the line \ncontentStream.newLineAtOffset(25, 700);\n"
},
{
"code": null,
"e": 32024,
"s": 31830,
"text": "You can set the font of the text to the required style using the setFont() method of the PDPageContentStream class as shown below. To this method you need to pass the type and size of the font."
},
{
"code": null,
"e": 32072,
"s": 32024,
"text": "contentStream.setFont( font_type, font_size );\n"
},
{
"code": null,
"e": 32248,
"s": 32072,
"text": "You can insert the text into the page using the ShowText() method of the PDPageContentStream class as shown below. This method accepts the required text in the form of string."
},
{
"code": null,
"e": 32279,
"s": 32248,
"text": "contentStream.showText(text);\n"
},
{
"code": null,
"e": 32406,
"s": 32279,
"text": "After inserting the text, you need to end the text using the endText() method of the PDPageContentStream class as shown below."
},
{
"code": null,
"e": 32432,
"s": 32406,
"text": "contentStream.endText();\n"
},
{
"code": null,
"e": 32510,
"s": 32432,
"text": "Close the PDPageContentStream object using the close() method as shown below."
},
{
"code": null,
"e": 32534,
"s": 32510,
"text": "contentstream.close();\n"
},
{
"code": null,
"e": 32677,
"s": 32534,
"text": "After adding the required content, save the PDF document using the save() method of the PDDocument class as shown in the following code block."
},
{
"code": null,
"e": 32696,
"s": 32677,
"text": "doc.save(\"Path\");\n"
},
{
"code": null,
"e": 32789,
"s": 32696,
"text": "Finally, close the document using the close() method of the PDDocument class as shown below."
},
{
"code": null,
"e": 32803,
"s": 32789,
"text": "doc.close();\n"
},
{
"code": null,
"e": 33081,
"s": 32803,
"text": "This example demonstrates how to add contents to a page in a document. Here, we will create a Java program to load the PDF document named my_doc.pdf, which is saved in the path C:/PdfBox_Examples/, and add some text to it. Save this code in a file with name AddingContent.java."
},
{
"code": null,
"e": 34529,
"s": 33081,
"text": "import java.io.File; \nimport java.io.IOException;\n \nimport org.apache.pdfbox.pdmodel.PDDocument; \nimport org.apache.pdfbox.pdmodel.PDPage; \nimport org.apache.pdfbox.pdmodel.PDPageContentStream; \nimport org.apache.pdfbox.pdmodel.font.PDType1Font;\n \npublic class AddingContent {\n public static void main (String args[]) throws IOException {\n\n //Loading an existing document\n File file = new File(\"C:/PdfBox_Examples/my_doc.pdf\");\n PDDocument document = PDDocument.load(file);\n \n //Retrieving the pages of the document \n PDPage page = document.getPage(1);\n PDPageContentStream contentStream = new PDPageContentStream(document, page);\n \n //Begin the Content stream \n contentStream.beginText(); \n \n //Setting the font to the Content stream \n contentStream.setFont(PDType1Font.TIMES_ROMAN, 12);\n\n //Setting the position for the line \n contentStream.newLineAtOffset(25, 500);\n\n String text = \"This is the sample document and we are adding content to it.\";\n\n //Adding text in the form of string \n contentStream.showText(text); \n\n //Ending the content stream\n contentStream.endText();\n\n System.out.println(\"Content added\");\n\n //Closing the content stream\n contentStream.close();\n\n //Saving the document\n document.save(new File(\"C:/PdfBox_Examples/new.pdf\"));\n\n //Closing the document\n document.close();\n }\n}"
},
{
"code": null,
"e": 34623,
"s": 34529,
"text": "Compile and execute the saved Java file from the command prompt using the following commands."
},
{
"code": null,
"e": 34670,
"s": 34623,
"text": "javac AddingContent.java \njava AddingContent \n"
},
{
"code": null,
"e": 34776,
"s": 34670,
"text": "Upon execution, the above program adds the given text to the document and displays the following message."
},
{
"code": null,
"e": 34791,
"s": 34776,
"text": "Content added\n"
},
{
"code": null,
"e": 34933,
"s": 34791,
"text": "If you verify the PDF Document new.pdf in the specified path, you can observe that the given content is added to the document as shown below."
},
{
"code": null,
"e": 35210,
"s": 34933,
"text": "In the example provided in the previous chapter we discussed how to add text to a page in a PDF but through this program, you can only add the text that would fit in a single line. If you try to add more content, all the text that exceeds the line space will not be displayed."
},
{
"code": null,
"e": 35349,
"s": 35210,
"text": "For example, if you execute the above program in the previous chapter by passing the following string only a part of it will be displayed."
},
{
"code": null,
"e": 35540,
"s": 35349,
"text": "String text = \"This is an example of adding text to a page in the pdf document. we can\n add as many lines as we want like this using the showText() method of the \n ContentStream class\";\n"
},
{
"code": null,
"e": 35706,
"s": 35540,
"text": "Replace the string text of the example in the previous chapter with the above mentioned string and execute it. Upon execution, you will receive the following output."
},
{
"code": null,
"e": 35803,
"s": 35706,
"text": "If you observe the output carefully, you can notice that only a part of the string is displayed."
},
{
"code": null,
"e": 35973,
"s": 35803,
"text": "In order to add multiple lines to a PDF you need to set the leading using the setLeading() method and shift to new line using newline() method after finishing each line."
},
{
"code": null,
"e": 36059,
"s": 35973,
"text": "Following are the steps to create an empty document and add contents to a page in it."
},
{
"code": null,
"e": 36223,
"s": 36059,
"text": "You can load an existing document using the load() method of the PDDocument class. Therefore, instantiate this class and load the required document as shown below."
},
{
"code": null,
"e": 36311,
"s": 36223,
"text": "File file = new File(\"Path of the document\"); \nPDDocument doc = PDDocument.load(file);\n"
},
{
"code": null,
"e": 36476,
"s": 36311,
"text": "You can get the required page in a document using the getPage() method. Retrieve the object of the required page by passing its index to this method as shown below."
},
{
"code": null,
"e": 36507,
"s": 36476,
"text": "PDPage page = doc.getPage(1);\n"
},
{
"code": null,
"e": 36809,
"s": 36507,
"text": "You can insert various kinds of data elements using the object of the class named PDPageContentStream. You need to pass the document object and the page object to the constructor of this class therefore, instantiate this class by passing these two objects created in the previous steps as shown below."
},
{
"code": null,
"e": 36882,
"s": 36809,
"text": "PDPageContentStream contentStream = new PDPageContentStream(doc, page);\n"
},
{
"code": null,
"e": 37068,
"s": 36882,
"text": "While inserting text in a PDF document, you can specify the start and end points of the text using the beginText() and endText() methods of the PDPageContentStream class as shown below."
},
{
"code": null,
"e": 37211,
"s": 37068,
"text": "contentStream.beginText(); \n............................. \ncode to add text content \n............................. \ncontentStream.endText(); \n"
},
{
"code": null,
"e": 37282,
"s": 37211,
"text": "Therefore, begin the text using the beginText() method as shown below."
},
{
"code": null,
"e": 37310,
"s": 37282,
"text": "contentStream.beginText();\n"
},
{
"code": null,
"e": 37406,
"s": 37310,
"text": "Using the newLineAtOffset() method, you can set the position on the content stream in the page."
},
{
"code": null,
"e": 37484,
"s": 37406,
"text": "//Setting the position for the line \ncontentStream.newLineAtOffset(25, 700);\n"
},
{
"code": null,
"e": 37677,
"s": 37484,
"text": "You can set the font of the text to the required style using the setFont() method of the PDPageContentStream class as shown below to this method you need to pass the type and size of the font."
},
{
"code": null,
"e": 37725,
"s": 37677,
"text": "contentStream.setFont( font_type, font_size );\n"
},
{
"code": null,
"e": 37800,
"s": 37725,
"text": "You can set the text leading using the setLeading() method as shown below."
},
{
"code": null,
"e": 37834,
"s": 37800,
"text": "contentStream.setLeading(14.5f);\n"
},
{
"code": null,
"e": 37996,
"s": 37834,
"text": "You can insert multiple strings using the ShowText() method of the PDPageContentStream class, by dividing each of them using the newline() method as shown below."
},
{
"code": null,
"e": 38088,
"s": 37996,
"text": "contentStream. ShowText(text1); \ncontentStream.newLine(); \ncontentStream. ShowText(text2);\n"
},
{
"code": null,
"e": 38215,
"s": 38088,
"text": "After inserting the text, you need to end the text using the endText() method of the PDPageContentStream class as shown below."
},
{
"code": null,
"e": 38241,
"s": 38215,
"text": "contentStream.endText();\n"
},
{
"code": null,
"e": 38319,
"s": 38241,
"text": "Close the PDPageContentStream object using the close() method as shown below."
},
{
"code": null,
"e": 38343,
"s": 38319,
"text": "contentstream.close();\n"
},
{
"code": null,
"e": 38486,
"s": 38343,
"text": "After adding the required content, save the PDF document using the save() method of the PDDocument class as shown in the following code block."
},
{
"code": null,
"e": 38505,
"s": 38486,
"text": "doc.save(\"Path\");\n"
},
{
"code": null,
"e": 38598,
"s": 38505,
"text": "Finally, close the document using the close() method of the PDDocument class as shown below."
},
{
"code": null,
"e": 38612,
"s": 38598,
"text": "doc.close();\n"
},
{
"code": null,
"e": 38748,
"s": 38612,
"text": "This example demonstrates how to add multiple lines in a PDF using PDFBox. Save this program in a file with name AddMultipleLines.java."
},
{
"code": null,
"e": 40459,
"s": 38748,
"text": "import java.io.File;\nimport java.io.IOException;\n\nimport org.apache.pdfbox.pdmodel.PDDocument;\nimport org.apache.pdfbox.pdmodel.PDPage;\nimport org.apache.pdfbox.pdmodel.PDPageContentStream;\nimport org.apache.pdfbox.pdmodel.font.PDType1Font;\n\npublic class AddMultipleLines {\n public static void main(String args[]) throws IOException {\n\n //Loading an existing document\n File file = new File(\"C:/PdfBox_Examples/my_pdf.pdf\");\n PDDocument doc = document.load(file);\n \n //Creating a PDF Document\n PDPage page = doc.getPage(1); \n \n PDPageContentStream contentStream = new PDPageContentStream(doc, page); \n \n //Begin the Content stream \n contentStream.beginText(); \n \n //Setting the font to the Content stream\n contentStream.setFont( PDType1Font.TIMES_ROMAN, 16 );\n \n //Setting the leading\n contentStream.setLeading(14.5f);\n\n //Setting the position for the line\n contentStream.newLineAtOffset(25, 725);\n\n String text1 = \"This is an example of adding text to a page in the pdf document.\n we can add as many lines\";\n String text2 = \"as we want like this using the ShowText() method of the\n ContentStream class\";\n\n //Adding text in the form of string\n contentStream. ShowText(text1);\n contentStream.newLine();\n contentStream. ShowText(text2);\n //Ending the content stream\n contentStream.endText();\n\n System.out.println(\"Content added\");\n\n //Closing the content stream\n contentStream.close();\n\n //Saving the document\n doc.save(new File(\"C:/PdfBox_Examples/new.pdf\"));\n \n //Closing the document\n doc.close();\n }\n}"
},
{
"code": null,
"e": 40553,
"s": 40459,
"text": "Compile and execute the saved Java file from the command prompt using the following commands."
},
{
"code": null,
"e": 40605,
"s": 40553,
"text": "javac AddMultipleLines.java \njava AddMultipleLines\n"
},
{
"code": null,
"e": 40711,
"s": 40605,
"text": "Upon execution, the above program adds the given text to the document and displays the following message."
},
{
"code": null,
"e": 40726,
"s": 40711,
"text": "Content added\n"
},
{
"code": null,
"e": 40886,
"s": 40726,
"text": "If you verify the PDF Document new.pdf in the specified path, you can observe that the given content is added to the document in multiple lines as shown below."
},
{
"code": null,
"e": 41050,
"s": 40886,
"text": "In the previous chapter, we have seen how to add text to an existing PDF document. In this chapter, we will discuss how to read text from an existing PDF document."
},
{
"code": null,
"e": 41258,
"s": 41050,
"text": "Extracting text is one of the main features of the PDF box library. You can extract text using the getText() method of the PDFTextStripper class. This class extracts all the text from the given PDF document."
},
{
"code": null,
"e": 41329,
"s": 41258,
"text": "Following are the steps to extract text from an existing PDF document."
},
{
"code": null,
"e": 41546,
"s": 41329,
"text": "Load an existing PDF document using the static method load() of the PDDocument class. This method accepts a file object as a parameter, since this is a static method you can invoke it using class name as shown below."
},
{
"code": null,
"e": 41638,
"s": 41546,
"text": "File file = new File(\"path of the document\") \nPDDocument document = PDDocument.load(file);\n"
},
{
"code": null,
"e": 41768,
"s": 41638,
"text": "The PDFTextStripper class provides methods to retrieve text from a PDF document therefore, instantiate this class as shown below."
},
{
"code": null,
"e": 41822,
"s": 41768,
"text": "PDFTextStripper pdfStripper = new PDFTextStripper();\n"
},
{
"code": null,
"e": 42112,
"s": 41822,
"text": "You can read/retrieve the contents of a page from the PDF document using the getText() method of the PDFTextStripper class. To this method you need to pass the document object as a parameter. This method retrieves the text in a given document and returns it in the form of a String object."
},
{
"code": null,
"e": 42158,
"s": 42112,
"text": "String text = pdfStripper.getText(document);\n"
},
{
"code": null,
"e": 42251,
"s": 42158,
"text": "Finally, close the document using the close() method of the PDDocument class as shown below."
},
{
"code": null,
"e": 42270,
"s": 42251,
"text": "document.close();\n"
},
{
"code": null,
"e": 42339,
"s": 42270,
"text": "Suppose, we have a PDF document with some text in it as shown below."
},
{
"code": null,
"e": 42597,
"s": 42339,
"text": "This example demonstrates how to read text from the above mentioned PDF document. Here, we will create a Java program and load a PDF document named new.pdf, which is saved in the path C:/PdfBox_Examples/. Save this code in a file with name ReadingText.java."
},
{
"code": null,
"e": 43267,
"s": 42597,
"text": "import java.io.File;\nimport java.io.IOException;\n\nimport org.apache.pdfbox.pdmodel.PDDocument;\nimport org.apache.pdfbox.text.PDFTextStripper;\npublic class ReadingText {\n\n public static void main(String args[]) throws IOException {\n\n //Loading an existing document\n File file = new File(\"C:/PdfBox_Examples/new.pdf\");\n PDDocument document = PDDocument.load(file);\n\n //Instantiate PDFTextStripper class\n PDFTextStripper pdfStripper = new PDFTextStripper();\n\n //Retrieving text from PDF document\n String text = pdfStripper.getText(document);\n System.out.println(text);\n\n //Closing the document\n document.close();\n\n }\n}"
},
{
"code": null,
"e": 43361,
"s": 43267,
"text": "Compile and execute the saved Java file from the command prompt using the following commands."
},
{
"code": null,
"e": 43403,
"s": 43361,
"text": "javac ReadingText.java \njava ReadingText\n"
},
{
"code": null,
"e": 43516,
"s": 43403,
"text": "Upon execution, the above program retrieves the text from the given PDF document and displays it as shown below."
},
{
"code": null,
"e": 43684,
"s": 43516,
"text": "This is an example of adding text to a page in the pdf document. we can add as many lines\nas we want like this using the ShowText() method of the ContentStream class.\n"
},
{
"code": null,
"e": 43845,
"s": 43684,
"text": "In the previous chapter, we have seen how to extract text from an existing PDF document. In this chapter, we will discuss how to insert image to a PDF document."
},
{
"code": null,
"e": 44008,
"s": 43845,
"text": "You can insert an image into a PDF document using the createFromFile() and drawImage() methods of the classes PDImageXObject and PDPageContentStream respectively."
},
{
"code": null,
"e": 44079,
"s": 44008,
"text": "Following are the steps to extract text from an existing PDF document."
},
{
"code": null,
"e": 44296,
"s": 44079,
"text": "Load an existing PDF document using the static method load() of the PDDocument class. This method accepts a file object as a parameter, since this is a static method you can invoke it using class name as shown below."
},
{
"code": null,
"e": 44382,
"s": 44296,
"text": "File file = new File(\"path of the document\")\nPDDocument doc = PDDocument.load(file);\n"
},
{
"code": null,
"e": 44488,
"s": 44382,
"text": "Select a page in the PDF document and retrieve its page object using the getPage() method as shown below."
},
{
"code": null,
"e": 44519,
"s": 44488,
"text": "PDPage page = doc.getPage(0);\n"
},
{
"code": null,
"e": 44735,
"s": 44519,
"text": "The class PDImageXObject in PDFBox library represents an image. It provides all the required methods to perform operations related to an image, such as, inserting an image, setting its height, setting its width etc."
},
{
"code": null,
"e": 44969,
"s": 44735,
"text": "We can create an object of this class using the method createFromFile(). To this method, we need to pass the path of the image which we want to add in the form of a string and the document object to which the image needs to be added."
},
{
"code": null,
"e": 45046,
"s": 44969,
"text": "PDImageXObject pdImage = PDImageXObject.createFromFile(\"C:/logo.png\", doc);\n"
},
{
"code": null,
"e": 45348,
"s": 45046,
"text": "You can insert various kinds of data elements using the object of the class named PDPageContentStream. You need to pass the document object and the page object to the constructor of this class therefore, instantiate this class by passing these two objects created in the previous steps as shown below."
},
{
"code": null,
"e": 45421,
"s": 45348,
"text": "PDPageContentStream contentStream = new PDPageContentStream(doc, page);\n"
},
{
"code": null,
"e": 45646,
"s": 45421,
"text": "You can insert an image in the PDF document using the drawImage() method. To this method, you need to add the image object created in the above step and the required dimensions of the image (width and height) as shown below."
},
{
"code": null,
"e": 45690,
"s": 45646,
"text": "contentstream.drawImage(pdImage, 70, 250);\n"
},
{
"code": null,
"e": 45768,
"s": 45690,
"text": "Close the PDPageContentStream object using the close() method as shown below."
},
{
"code": null,
"e": 45792,
"s": 45768,
"text": "contentstream.close();\n"
},
{
"code": null,
"e": 45935,
"s": 45792,
"text": "After adding the required content, save the PDF document using the save() method of the PDDocument class as shown in the following code block."
},
{
"code": null,
"e": 45954,
"s": 45935,
"text": "doc.save(\"Path\");\n"
},
{
"code": null,
"e": 46047,
"s": 45954,
"text": "Finally, close the document using the close() method of the PDDocument class as shown below."
},
{
"code": null,
"e": 46061,
"s": 46047,
"text": "doc.close();\n"
},
{
"code": null,
"e": 46175,
"s": 46061,
"text": "Suppose we have a PDF document named sample.pdf, in the path C:/PdfBox_Examples/ with empty pages as shown below."
},
{
"code": null,
"e": 46401,
"s": 46175,
"text": "This example demonstrates how to add image to a blank page of the above mentioned PDF document. Here, we will load the PDF document named sample.pdf and add image to it. Save this code in a file with name InsertingImage.java."
},
{
"code": null,
"e": 47575,
"s": 46401,
"text": "import java.io.File;\n \nimport org.apache.pdfbox.pdmodel.PDDocument; \nimport org.apache.pdfbox.pdmodel.PDPage;\nimport org.apache.pdfbox.pdmodel.PDPageContentStream;\nimport org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;\n\npublic class InsertingImage {\n\n public static void main(String args[]) throws Exception {\n //Loading an existing document\n File file = new File(\"C:/PdfBox_Examples/sample.pdf\");\n PDDocument doc = PDDocument.load(file);\n \n //Retrieving the page\n PDPage page = doc.getPage(0);\n \n //Creating PDImageXObject object\n PDImageXObject pdImage = PDImageXObject.createFromFile(\"C:/PdfBox_Examples/logo.png\",doc);\n \n //creating the PDPageContentStream object\n PDPageContentStream contents = new PDPageContentStream(doc, page);\n\n //Drawing the image in the PDF document\n contents.drawImage(pdImage, 70, 250);\n\n System.out.println(\"Image inserted\");\n\n //Closing the PDPageContentStream object\n contents.close();\n\t\t\n //Saving the document\n doc.save(\"C:/PdfBox_Examples/sample.pdf\");\n \n //Closing the document\n doc.close();\n \n }\n}"
},
{
"code": null,
"e": 47669,
"s": 47575,
"text": "Compile and execute the saved Java file from the command prompt using the following commands."
},
{
"code": null,
"e": 47717,
"s": 47669,
"text": "javac InsertingImage.java \njava InsertingImage\n"
},
{
"code": null,
"e": 47852,
"s": 47717,
"text": "Upon execution, the above program inserts an image into the specified page of the given PDF document displaying the following message."
},
{
"code": null,
"e": 47868,
"s": 47852,
"text": "Image inserted\n"
},
{
"code": null,
"e": 47971,
"s": 47868,
"text": "If you verify the document sample.pdf, you can observe that an image is inserted in it as shown below."
},
{
"code": null,
"e": 48115,
"s": 47971,
"text": "In the previous chapter, we have seen how to insert an image in a PDF document. In this chapter, we will discuss how to encrypt a PDF document."
},
{
"code": null,
"e": 48231,
"s": 48115,
"text": "You can encrypt a PDF document using the methods provided by StandardProtectionPolicy and AccessPermission classes."
},
{
"code": null,
"e": 48416,
"s": 48231,
"text": "The AccessPermission class is used to protect the PDF Document by assigning access permissions to it. Using this class, you can restrict users from performing the following operations."
},
{
"code": null,
"e": 48435,
"s": 48416,
"text": "Print the document"
},
{
"code": null,
"e": 48470,
"s": 48435,
"text": "Modify the content of the document"
},
{
"code": null,
"e": 48510,
"s": 48470,
"text": "Copy or extract content of the document"
},
{
"code": null,
"e": 48536,
"s": 48510,
"text": "Add or modify annotations"
},
{
"code": null,
"e": 48568,
"s": 48536,
"text": "Fill in interactive form fields"
},
{
"code": null,
"e": 48640,
"s": 48568,
"text": "Extract text and graphics for accessibility to visually impaired people"
},
{
"code": null,
"e": 48662,
"s": 48640,
"text": "Assemble the document"
},
{
"code": null,
"e": 48688,
"s": 48662,
"text": "Print in degraded quality"
},
{
"code": null,
"e": 48781,
"s": 48688,
"text": "The StandardProtectionPolicy class is used to add a password based protection to a document."
},
{
"code": null,
"e": 48842,
"s": 48781,
"text": "Following are the steps to encrypt an existing PDF document."
},
{
"code": null,
"e": 49059,
"s": 48842,
"text": "Load an existing PDF document using the static method load() of the PDDocument class. This method accepts a file object as a parameter, since this is a static method you can invoke it using class name as shown below."
},
{
"code": null,
"e": 49151,
"s": 49059,
"text": "File file = new File(\"path of the document\") \nPDDocument document = PDDocument.load(file);\n"
},
{
"code": null,
"e": 49206,
"s": 49151,
"text": "Instantiate the AccessPermission class as shown below."
},
{
"code": null,
"e": 49267,
"s": 49206,
"text": "AccessPermission accessPermission = new AccessPermission();\n"
},
{
"code": null,
"e": 49408,
"s": 49267,
"text": "Instantiate the StandardProtectionPolicy class by passing the owner password, user password, and the AccessPermission object as shown below."
},
{
"code": null,
"e": 49502,
"s": 49408,
"text": "StandardProtectionPolicy spp = new StandardProtectionPolicy(\"1234\",\"1234\",accessPermission);\n"
},
{
"code": null,
"e": 49590,
"s": 49502,
"text": "Set the encryption key length using the setEncryptionKeyLength() method as shown below."
},
{
"code": null,
"e": 49624,
"s": 49590,
"text": "spp.setEncryptionKeyLength(128);\n"
},
{
"code": null,
"e": 49780,
"s": 49624,
"text": "Set the permissions using the setPermissions() method of the StandardProtectionPolicy class. This method accepts an AccessPermission object as a parameter."
},
{
"code": null,
"e": 49819,
"s": 49780,
"text": "spp.setPermissions(accessPermission);\n"
},
{
"code": null,
"e": 49988,
"s": 49819,
"text": "You can protect your document using the protect() method of the PDDocument class as shown below. Pass the StandardProtectionPolicy object as a parameter to this method."
},
{
"code": null,
"e": 50012,
"s": 49988,
"text": "document.protect(spp);\n"
},
{
"code": null,
"e": 50154,
"s": 50012,
"text": "After adding the required content save the PDF document using the save() method of the PDDocument class as shown in the following code block."
},
{
"code": null,
"e": 50178,
"s": 50154,
"text": "document.save(\"Path\");\n"
},
{
"code": null,
"e": 50263,
"s": 50178,
"text": "Finally, close the document using close() method of PDDocument class as shown below."
},
{
"code": null,
"e": 50282,
"s": 50263,
"text": "document.close();\n"
},
{
"code": null,
"e": 50397,
"s": 50282,
"text": "Suppose, we have a PDF document named sample.pdf, in the path C:/PdfBox_Examples/ with empty pages as shown below."
},
{
"code": null,
"e": 50596,
"s": 50397,
"text": "This example demonstrates how to encrypt the above mentioned PDF document. Here, we will load the PDF document named sample.pdf and encrypt it. Save this code in a file with name EncriptingPDF.java."
},
{
"code": null,
"e": 51696,
"s": 50596,
"text": "import java.io.File;\n \nimport org.apache.pdfbox.pdmodel.PDDocument;\nimport org.apache.pdfbox.pdmodel.encryption.AccessPermission;\nimport org.apache.pdfbox.pdmodel.encryption.StandardProtectionPolicy;\npublic class EncriptingPDF {\n \n public static void main(String args[]) throws Exception {\n //Loading an existing document\n File file = new File(\"C:/PdfBox_Examples/sample.pdf\");\n PDDocument document = PDDocument.load(file);\n \n //Creating access permission object\n AccessPermission ap = new AccessPermission(); \n\n //Creating StandardProtectionPolicy object\n StandardProtectionPolicy spp = new StandardProtectionPolicy(\"1234\", \"1234\", ap);\n\n //Setting the length of the encryption key\n spp.setEncryptionKeyLength(128);\n\n //Setting the access permissions\n spp.setPermissions(ap);\n\n //Protecting the document\n document.protect(spp);\n\n System.out.println(\"Document encrypted\");\n\n //Saving the document\n document.save(\"C:/PdfBox_Examples/sample.pdf\");\n //Closing the document\n document.close();\n\n }\n}"
},
{
"code": null,
"e": 51790,
"s": 51696,
"text": "Compile and execute the saved Java file from the command prompt using the following commands."
},
{
"code": null,
"e": 51835,
"s": 51790,
"text": "javac EncriptingPDF.java\njava EncriptingPDF\n"
},
{
"code": null,
"e": 51935,
"s": 51835,
"text": "Upon execution, the above program encrypts the given PDF document displaying the following message."
},
{
"code": null,
"e": 51955,
"s": 51935,
"text": "Document encrypted\n"
},
{
"code": null,
"e": 52112,
"s": 51955,
"text": "If you try to open the document sample.pdf, you cannot, since it is encrypted. Instead, it prompts to type the password to open the document as shown below."
},
{
"code": null,
"e": 52267,
"s": 52112,
"text": "In the previous chapter, we have learnt how to insert image into a PDF document. In this chapter, we will discuss how to add JavaScript to a PDF document."
},
{
"code": null,
"e": 52389,
"s": 52267,
"text": "You can add JavaScript actions to a PDF document using the PDActionJavaScript class. This represents a JavaScript action."
},
{
"code": null,
"e": 52468,
"s": 52389,
"text": "Following are the steps to add JavaScript actions to an existing PDF document."
},
{
"code": null,
"e": 52685,
"s": 52468,
"text": "Load an existing PDF document using the static method load() of the PDDocument class. This method accepts a file object as a parameter, since this is a static method you can invoke it using class name as shown below."
},
{
"code": null,
"e": 52776,
"s": 52685,
"text": "File file = new File(\"path of the document\")\nPDDocument document = PDDocument.load(file);\n"
},
{
"code": null,
"e": 52935,
"s": 52776,
"text": "Instantiate the PDActionJavaScript object as shown below. To the constructor of this class, pass the required JavaScript in the form of String as shown below."
},
{
"code": null,
"e": 53145,
"s": 52935,
"text": "String javaScript = \"app.alert( {cMsg: 'this is an example', nIcon: 3,\"\n + \" nType: 0,cTitle: 'PDFBox Javascript example' } );\"; \nPDActionJavaScript PDAjavascript = new PDActionJavaScript(javaScript);\n"
},
{
"code": null,
"e": 53207,
"s": 53145,
"text": "Embed the required string to the PDF document as shown below."
},
{
"code": null,
"e": 53268,
"s": 53207,
"text": "document.getDocumentCatalog().setOpenAction(PDAjavascript);\n"
},
{
"code": null,
"e": 53410,
"s": 53268,
"text": "After adding the required content save the PDF document using the save() method of the PDDocument class as shown in the following code block."
},
{
"code": null,
"e": 53434,
"s": 53410,
"text": "document.save(\"Path\");\n"
},
{
"code": null,
"e": 53523,
"s": 53434,
"text": "Finally, close the document using close() method of the PDDocument class as shown below."
},
{
"code": null,
"e": 53542,
"s": 53523,
"text": "document.close();\n"
},
{
"code": null,
"e": 53657,
"s": 53542,
"text": "Suppose, we have a PDF document named sample.pdf, in the path C:/PdfBox_Examples/ with empty pages as shown below."
},
{
"code": null,
"e": 53880,
"s": 53657,
"text": "This example demonstrates how to embed JavaScript in the above mentioned PDF document. Here, we will load the PDF document named sample.pdf and embed JavaScript in it. Save this code in a file with name AddJavaScript.java."
},
{
"code": null,
"e": 54832,
"s": 53880,
"text": "import java.io.File;\n \nimport org.apache.pdfbox.pdmodel.PDDocument; \nimport org.apache.pdfbox.pdmodel.interactive.action.PDActionJavaScript;\n\npublic class AddJavaScript {\n\n public static void main(String args[]) throws Exception {\n\n //Loading an existing file\n File file = new File(\"C:/PdfBox_Examples/new.pdf\");\n PDDocument document = PDDocument.load(file);\n\n String javaScript = \"app.alert( {cMsg: 'this is an example', nIcon: 3,\"\n + \" nType: 0, cTitle: 'PDFBox Javascript example’} );\";\n\n //Creating PDActionJavaScript object \n PDActionJavaScript PDAjavascript = new PDActionJavaScript(javaScript);\n\n //Embedding java script\n document.getDocumentCatalog().setOpenAction(PDAjavascript);\n\n //Saving the document\n document.save( new File(\"C:/PdfBox_Examples/new.pdf\") );\n System.out.println(\"Data added to the given PDF\"); \n\n //Closing the document\n document.close();\n\n }\n}"
},
{
"code": null,
"e": 54926,
"s": 54832,
"text": "Compile and execute the saved Java file from the command prompt using the following commands."
},
{
"code": null,
"e": 54972,
"s": 54926,
"text": "javac AddJavaScript.java \njava AddJavaScript\n"
},
{
"code": null,
"e": 55084,
"s": 54972,
"text": "Upon execution, the above program embeds JavaScript in the given PDF document displaying the following message."
},
{
"code": null,
"e": 55113,
"s": 55084,
"text": "Data added to the given PDF\n"
},
{
"code": null,
"e": 55202,
"s": 55113,
"text": "If you try to open the document new.pdf it will display an alert message as shown below."
},
{
"code": null,
"e": 55357,
"s": 55202,
"text": "In the previous chapter, we have seen how to add JavaScript to a PDF document. Let us now learn how to split a given PDF document into multiple documents."
},
{
"code": null,
"e": 55536,
"s": 55357,
"text": "You can split the given PDF document in to multiple PDF documents using the class named Splitter. This class is used to split the given PDF document into several other documents."
},
{
"code": null,
"e": 55594,
"s": 55536,
"text": "Following are the steps to split an existing PDF document"
},
{
"code": null,
"e": 55811,
"s": 55594,
"text": "Load an existing PDF document using the static method load() of the PDDocument class. This method accepts a file object as a parameter, since this is a static method you can invoke it using class name as shown below."
},
{
"code": null,
"e": 55903,
"s": 55811,
"text": "File file = new File(\"path of the document\") \nPDDocument document = PDDocument.load(file);\n"
},
{
"code": null,
"e": 56031,
"s": 55903,
"text": "The class named Splitter contains the methods to split the given PDF document therefore, instantiate this class as shown below."
},
{
"code": null,
"e": 56068,
"s": 56031,
"text": "Splitter splitter = new Splitter();\n"
},
{
"code": null,
"e": 56230,
"s": 56068,
"text": "You can split the given document using the Split() method of the Splitter class this class. This method accepts an object of the PDDocument class as a parameter."
},
{
"code": null,
"e": 56282,
"s": 56230,
"text": "List<PDDocument> Pages = splitter.split(document);\n"
},
{
"code": null,
"e": 56411,
"s": 56282,
"text": "The split() method splits each page of the given document as an individual document and returns all these in the form of a list."
},
{
"code": null,
"e": 56633,
"s": 56411,
"text": "In order to traverse through the list of documents you need to get an iterator object of the list acquired in the above step, you need to get the iterator object of the list using the listIterator() method as shown below."
},
{
"code": null,
"e": 56688,
"s": 56633,
"text": "Iterator<PDDocument> iterator = Pages.listIterator();\n"
},
{
"code": null,
"e": 56773,
"s": 56688,
"text": "Finally, close the document using close() method of PDDocument class as shown below."
},
{
"code": null,
"e": 56792,
"s": 56773,
"text": "document.close();\n"
},
{
"code": null,
"e": 56992,
"s": 56792,
"text": "Suppose, there is a PDF document with name sample.pdf in the path C:\\PdfBox_Examples\\ and this document contains two pages — one page containing image and another page containing text as shown below."
},
{
"code": null,
"e": 57229,
"s": 56992,
"text": "This example demonstrates how to split the above mentioned PDF document. Here, we will split the PDF document named sample.pdf into two different documents sample1.pdf and sample2.pdf. Save this code in a file with name SplitPages.java."
},
{
"code": null,
"e": 58240,
"s": 57229,
"text": "import org.apache.pdfbox.multipdf.Splitter; \nimport org.apache.pdfbox.pdmodel.PDDocument;\n\nimport java.io.File; \nimport java.io.IOException; \nimport java.util.List; \nimport java.util.Iterator;\n \npublic class SplitPages {\n public static void main(String[] args) throws IOException {\n\n //Loading an existing PDF document\n File file = new File(\"C:/PdfBox_Examples/sample.pdf\");\n PDDocument document = PDDocument.load(file); \n\n //Instantiating Splitter class\n Splitter splitter = new Splitter();\n\n //splitting the pages of a PDF document\n List<PDDocument> Pages = splitter.split(document);\n\n //Creating an iterator \n Iterator<PDDocument> iterator = Pages.listIterator();\n\n //Saving each page as an individual document\n int i = 1;\n while(iterator.hasNext()) {\n PDDocument pd = iterator.next();\n pd.save(\"C:/PdfBox_Examples/sample\"+ i++ +\".pdf\");\n }\n System.out.println(\"Multiple PDF’s created\");\n document.close();\n }\n}"
},
{
"code": null,
"e": 58333,
"s": 58240,
"text": "Compile and execute the saved Java file from the command prompt using the following commands"
},
{
"code": null,
"e": 58373,
"s": 58333,
"text": "javac SplitPages.java \njava SplitPages\n"
},
{
"code": null,
"e": 58473,
"s": 58373,
"text": "Upon execution, the above program encrypts the given PDF document displaying the following message."
},
{
"code": null,
"e": 58497,
"s": 58473,
"text": "Multiple PDF’s created\n"
},
{
"code": null,
"e": 58622,
"s": 58497,
"text": "If you verify the given path, you can observe that multiple PDFs were created with names sample1 and sample2 as shown below."
},
{
"code": null,
"e": 58794,
"s": 58622,
"text": "In the previous chapter, we have seen how to split a given PDF document into multiple documents. Let us now learn how to merge multiple PDF documents as a single document."
},
{
"code": null,
"e": 58996,
"s": 58794,
"text": "You can merge multiple PDF documents into a single PDF document using the class named PDFMergerUtility class, this class provides methods to merge two or more PDF documents in to a single PDF document."
},
{
"code": null,
"e": 59053,
"s": 58996,
"text": "Following are the steps to merge multiple PDF documents."
},
{
"code": null,
"e": 59105,
"s": 59053,
"text": "Instantiate the merge utility class as shown below."
},
{
"code": null,
"e": 59159,
"s": 59105,
"text": "PDFMergerUtility PDFmerger = new PDFMergerUtility();\n"
},
{
"code": null,
"e": 59243,
"s": 59159,
"text": "Set the destination files using the setDestinationFileName() method as shown below."
},
{
"code": null,
"e": 59317,
"s": 59243,
"text": "PDFmerger.setDestinationFileName(\"C:/PdfBox_Examples/data1/merged.pdf\");\n"
},
{
"code": null,
"e": 59383,
"s": 59317,
"text": "Set the source files using the addSource() method as shown below."
},
{
"code": null,
"e": 59456,
"s": 59383,
"text": "File file = new File(\"path of the document\")\nPDFmerger.addSource(file);\n"
},
{
"code": null,
"e": 59549,
"s": 59456,
"text": "Merge the documents using the mergeDocuments() method of the PDFmerger class as shown below."
},
{
"code": null,
"e": 59578,
"s": 59549,
"text": "PDFmerger.mergeDocuments();\n"
},
{
"code": null,
"e": 59692,
"s": 59578,
"text": "Suppose, we have two PDF documents — sample1.pdf and sample2.pdf, in the path C:\\PdfBox_Examples\\ as shown below."
},
{
"code": null,
"e": 59919,
"s": 59692,
"text": "This example demonstrates how to merge the above PDF documents. Here, we will merge the PDF documents named sample1.pdf and sample2.pdf in to a single PDF document merged.pdf. Save this code in a file with name MergePDFs.java."
},
{
"code": null,
"e": 60675,
"s": 59919,
"text": "import org.apache.pdfbox.multipdf.PDFMergerUtility; \nimport java.io.File; \nimport java.io.IOException;\npublic class MergePDFs {\n public static void main(String[] args) throws IOException {\n File file1 = new File(\"C:\\\\EXAMPLES\\\\Demo1.pdf\"); \n File file2 = new File(\"C:\\\\EXAMPLES\\\\Demo2.pdf\"); \n\t\t\n //Instantiating PDFMergerUtility class\n PDFMergerUtility PDFmerger = new PDFMergerUtility();\n\t\t\n //Setting the destination file\n PDFmerger.setDestinationFileName(\"C:\\\\Examples\\\\merged.pdf\");\n\t\t\n //adding the source files\n PDFmerger.addSource(file1);\n PDFmerger.addSource(file2);\n\t\t\n //Merging the two documents\n PDFmerger.mergeDocuments();\n System.out.println(\"Documents merged\");\n }\n}"
},
{
"code": null,
"e": 60769,
"s": 60675,
"text": "Compile and execute the saved Java file from the command prompt using the following commands."
},
{
"code": null,
"e": 60808,
"s": 60769,
"text": "javac MergePDFs.java \njava MergePDFs \n"
},
{
"code": null,
"e": 60908,
"s": 60808,
"text": "Upon execution, the above program encrypts the given PDF document displaying the following message."
},
{
"code": null,
"e": 60926,
"s": 60908,
"text": "Documents merged\n"
},
{
"code": null,
"e": 61097,
"s": 60926,
"text": "If you verify the given path, you can observe that a PDF document with name merged.pdf is created and this contains the pages of both the source documents as shown below."
},
{
"code": null,
"e": 61263,
"s": 61097,
"text": "In the previous chapter, we have seen how to merge multiple PDF documents. In this chapter, we will understand how to extract an image from a page of a PDF document."
},
{
"code": null,
"e": 61373,
"s": 61263,
"text": "PDFBox library provides you a class named PDFRenderer which renders a PDF document into an AWT BufferedImage."
},
{
"code": null,
"e": 61439,
"s": 61373,
"text": "Following are the steps to generate an image from a PDF document."
},
{
"code": null,
"e": 61656,
"s": 61439,
"text": "Load an existing PDF document using the static method load() of the PDDocument class. This method accepts a file object as a parameter, since this is a static method you can invoke it using class name as shown below."
},
{
"code": null,
"e": 61748,
"s": 61656,
"text": "File file = new File(\"path of the document\") \nPDDocument document = PDDocument.load(file);\n"
},
{
"code": null,
"e": 62015,
"s": 61748,
"text": "The class named PDFRenderer renders a PDF document into an AWT BufferedImage. Therefore, you need to instantiate this class as shown below. The constructor of this class accepts a document object; pass the document object created in the previous step as shown below."
},
{
"code": null,
"e": 62066,
"s": 62015,
"text": "PDFRenderer renderer = new PDFRenderer(document);\n"
},
{
"code": null,
"e": 62269,
"s": 62066,
"text": "You can render the image in a particular page using the method renderImage() of the Renderer class, to this method you need to pass the index of the page where you have the image that is to be rendered."
},
{
"code": null,
"e": 62317,
"s": 62269,
"text": "BufferedImage image = renderer.renderImage(0);\n"
},
{
"code": null,
"e": 62459,
"s": 62317,
"text": "You can write the image rendered in the previous step to a file using the write() method. To this method, you need to pass three parameters −"
},
{
"code": null,
"e": 62486,
"s": 62459,
"text": "The rendered image object."
},
{
"code": null,
"e": 62542,
"s": 62486,
"text": "String representing the type of the image (jpg or png)."
},
{
"code": null,
"e": 62601,
"s": 62542,
"text": "File object to which you need to save the extracted image."
},
{
"code": null,
"e": 62676,
"s": 62601,
"text": "ImageIO.write(image, \"JPEG\", new File(\"C:/PdfBox_Examples/myimage.jpg\"));\n"
},
{
"code": null,
"e": 62769,
"s": 62676,
"text": "Finally, close the document using the close() method of the PDDocument class as shown below."
},
{
"code": null,
"e": 62788,
"s": 62769,
"text": "document.close();\n"
},
{
"code": null,
"e": 62926,
"s": 62788,
"text": "Suppose, we have a PDF document — sample.pdf in the path C:\\PdfBox_Examples\\ and this contains an image in its first page as shown below."
},
{
"code": null,
"e": 63141,
"s": 62926,
"text": "This example demonstrates how to convert the above PDF document into an image file. Here, we will retrieve the image in the 1st page of the PDF document and save it as myimage.jpg. Save this code as PdfToImage.java"
},
{
"code": null,
"e": 64013,
"s": 63141,
"text": "import java.awt.image.BufferedImage;\nimport java.io.File;\n\nimport javax.imageio.ImageIO;\nimport org.apache.pdfbox.pdmodel.PDDocument;\nimport org.apache.pdfbox.rendering.PDFRenderer;\npublic class PdfToImage {\n\n public static void main(String args[]) throws Exception {\n\n //Loading an existing PDF document\n File file = new File(\"C:/PdfBox_Examples/sample.pdf\");\n PDDocument document = PDDocument.load(file);\n \n //Instantiating the PDFRenderer class\n PDFRenderer renderer = new PDFRenderer(document);\n\n //Rendering an image from the PDF document\n BufferedImage image = renderer.renderImage(0);\n\n //Writing the image to a file\n ImageIO.write(image, \"JPEG\", new File(\"C:/PdfBox_Examples/myimage.jpg\"));\n \n System.out.println(\"Image created\");\n \n //Closing the document\n document.close();\n\n }\n}"
},
{
"code": null,
"e": 64107,
"s": 64013,
"text": "Compile and execute the saved Java file from the command prompt using the following commands."
},
{
"code": null,
"e": 64147,
"s": 64107,
"text": "javac PdfToImage.java \njava PdfToImage\n"
},
{
"code": null,
"e": 64261,
"s": 64147,
"text": "Upon execution, the above program retrieves the image in the given PDF document displaying the following message."
},
{
"code": null,
"e": 64276,
"s": 64261,
"text": "Image created\n"
},
{
"code": null,
"e": 64391,
"s": 64276,
"text": "If you verify the given path, you can observe that the image is generated and saved as myimage.jpg as shown below."
},
{
"code": null,
"e": 64471,
"s": 64391,
"text": "This chapter teaches you how to create color boxes in a page of a PDF document."
},
{
"code": null,
"e": 64577,
"s": 64471,
"text": "You can add rectangular boxes in a PDF page using the addRect() method of the PDPageContentStream class."
},
{
"code": null,
"e": 64659,
"s": 64577,
"text": "Following are the steps to create rectangular shapes in a page of a PDF document."
},
{
"code": null,
"e": 64876,
"s": 64659,
"text": "Load an existing PDF document using the static method load() of the PDDocument class. This method accepts a file object as a parameter, since this is a static method you can invoke it using class name as shown below."
},
{
"code": null,
"e": 64968,
"s": 64876,
"text": "File file = new File(\"path of the document\") \nPDDocument document = PDDocument.load(file);\n"
},
{
"code": null,
"e": 65201,
"s": 64968,
"text": "You need to retrieve the PDPage object of the required page where you want to add rectangles using the getPage() method of the PDDocument class. To this method you need to pass the index of the page where you want to add rectangles."
},
{
"code": null,
"e": 65237,
"s": 65201,
"text": "PDPage page = document.getPage(0);\n"
},
{
"code": null,
"e": 65539,
"s": 65237,
"text": "You can insert various kinds of data elements using the object of the class named PDPageContentStream. You need to pass the document object and the page object to the constructor of this class therefore, instantiate this class by passing these two objects created in the previous steps as shown below."
},
{
"code": null,
"e": 65617,
"s": 65539,
"text": "PDPageContentStream contentStream = new PDPageContentStream(document, page);\n"
},
{
"code": null,
"e": 65825,
"s": 65617,
"text": "You can set the non-stroking color to the rectangle using the setNonStrokingColor() method of the class PDPageContentStream. To this method, you need to pass the required color as a parameter as shown below."
},
{
"code": null,
"e": 65878,
"s": 65825,
"text": "contentStream.setNonStrokingColor(Color.DARK_GRAY);\n"
},
{
"code": null,
"e": 66051,
"s": 65878,
"text": "Draw the rectangle with required dimensions using the addRect() method. To this method, you need to pass the dimensions of the rectangle that is to be added as shown below."
},
{
"code": null,
"e": 66095,
"s": 66051,
"text": "contentStream.addRect(200, 650, 100, 100);\n"
},
{
"code": null,
"e": 66234,
"s": 66095,
"text": "The fill() method of the PDPageContentStream class fills the path between the specified dimensions with the required color as shown below."
},
{
"code": null,
"e": 66257,
"s": 66234,
"text": "contentStream.fill();\n"
},
{
"code": null,
"e": 66345,
"s": 66257,
"text": "Finally close the document using close() method of the PDDocument class as shown below."
},
{
"code": null,
"e": 66364,
"s": 66345,
"text": "document.close();\n"
},
{
"code": null,
"e": 66501,
"s": 66364,
"text": "Suppose we have a PDF document named blankpage.pdf in the path C:\\PdfBox_Examples\\ and this contains a single blank page as shown below."
},
{
"code": null,
"e": 66659,
"s": 66501,
"text": "This example demonstrates how to create/insert rectangles in a PDF document. Here, we will create a box in a Blank PDF. Save this code as AddRectangles.java."
},
{
"code": null,
"e": 67863,
"s": 66659,
"text": "import java.awt.Color;\nimport java.io.File;\n \nimport org.apache.pdfbox.pdmodel.PDDocument;\nimport org.apache.pdfbox.pdmodel.PDPage;\nimport org.apache.pdfbox.pdmodel.PDPageContentStream;\npublic class ShowColorBoxes {\n\n public static void main(String args[]) throws Exception {\n\n //Loading an existing document\n File file = new File(\"C:/PdfBox_Examples/BlankPage.pdf\");\n PDDocument document = PDDocument.load(file);\n \n //Retrieving a page of the PDF Document\n PDPage page = document.getPage(0);\n\n //Instantiating the PDPageContentStream class\n PDPageContentStream contentStream = new PDPageContentStream(document, page);\n \n //Setting the non stroking color\n contentStream.setNonStrokingColor(Color.DARK_GRAY);\n\n //Drawing a rectangle \n contentStream.addRect(200, 650, 100, 100);\n\n //Drawing a rectangle\n contentStream.fill();\n\n System.out.println(\"rectangle added\");\n\n //Closing the ContentStream object\n contentStream.close();\n\n //Saving the document\n File file1 = new File(\"C:/PdfBox_Examples/colorbox.pdf\");\n document.save(file1);\n\n //Closing the document\n document.close();\n }\n}"
},
{
"code": null,
"e": 67957,
"s": 67863,
"text": "Compile and execute the saved Java file from the command prompt using the following commands."
},
{
"code": null,
"e": 68003,
"s": 67957,
"text": "javac AddRectangles.java \njava AddRectangles\n"
},
{
"code": null,
"e": 68107,
"s": 68003,
"text": "Upon execution, the above program creates a rectangle in a PDF document displaying the following image."
},
{
"code": null,
"e": 68126,
"s": 68107,
"text": "Rectangle created\n"
},
{
"code": null,
"e": 68260,
"s": 68126,
"text": "If you verify the given path and open the saved document — colorbox.pdf, you can observe that a box is inserted in it as shown below."
},
{
"code": null,
"e": 68267,
"s": 68260,
"text": " Print"
},
{
"code": null,
"e": 68278,
"s": 68267,
"text": " Add Notes"
}
] |
Predicting Dengue Spread Using Seasonal ARIMAX Model and Meteorological Data | by Nam Nguyen | Towards Data Science | During the last decades, dengue viruses have spread throughout the sub-tropical parts of the world, with an increase in the number of severe forms of dengue such as severe bleeding, low blood pressure, and even death. Because the disease is carried by mosquitoes, the transmission of Dengue fever is related to meteorological variables such as temperature and precipitation. In this blog post, I will go over how I tackle the DengAI competition Paper and Rcode can be found on my github!
Here is the game plan:
Data SplitDescriptive Analysis and Data VisualizationHandling Missing ValuesModel DiagnosticsModel FormationForecasting
Data Split
Descriptive Analysis and Data Visualization
Handling Missing Values
Model Diagnostics
Model Formation
Forecasting
The DengAI competition data set is essentially a messy dataset with two different cities and two different time frames. I split the dataset into two small datasets based on two cities: San Juan and Iquitos. From two datasets, I divided each into train and validation sets in order to test different models before choosing the best one to perform on the final test set.
The Data Processing for both San Juan and Iquitos were quite similar, so I will only show San Juan’s graphs in this section. Charts and Graphs of Iquitos will be provided in my paper.
Each dataset contains 25 variables including meteorological and geographical variables. See the details about each variable here.
A Correlation plot will be helpful to diagnose if there are any linear relationships between 2 variables. We can see none of those variables is highly correlated to total cases (Figure 3). However, if we include more than 2 variables and run a multivariate linear regression, the magnitude of each predictor might change.
The time series plot indicates that there might be seasonality in the data since the number of total cases peaks every year around summer time. Two scatter plots also suggest possible linear relationships between total cases and two climate variables. (temperature and humidity)
Looking at the dual time series plots of total cases and temperature, and total cases and humidity, we can see sometimes the number of cases and climate values move up and down together; sometimes the weather variables peak or plummet first, then the total cases go up and down in 3 -4 weeks later. More interestingly, Dengue symptoms usually start 4 to 7 days after you are bitten by an infected mosquito. Mosquito might go through its life cycle in 14 days at 70° F and take only 10 days at 80° F. Therefore, in average, it takes 3–4 weeks for the cases to be reported after the temperature, precipitation or humidity go up and down.
The Descriptive Analysis and Data Visualization suggest a time series model with additional predictor variables, and possibly some previous lags of the predictors.
I handled missing data by using Last Observation Carried Forward method in R, which is basically replacing each NA with the most recent non-NA prior to it. Here I am assuming that the weather of the current week would not be too different to the weather of the previous week.
# build a function to impute data with the most recent that is non missing na.locf.data.frame <- function(object, ...) replace(object, TRUE, lapply(object, na.locf, ...)) #fill in NAs - SJ sjdata.train.imputed <- na.locf.data.frame(sjdata.train) #fill in NAs - IQ iqdata.train.imputed <- na.locf.data.frame(iqdata.train)
An Augmented Dickey-Fuller Test suggests that the time series dataset is stationary. The dataset has complex seasonality with weekly data points (frequency = 52.18). Most of the methods such as ETS, Decomposition require the seasonal period to be an integer. Even if we round it up to 52, most of the methods will not handle such a large seasonal period efficiently. A possible approach could be to use a dynamic harmonic regression model by including Fourier terms in ARIMA model.
Next, to pick MA and AR terms, I first examined the early lags (1, 2, 3, ...) to judge non-seasonal terms. Those spikes in the ACF at low lags indicate non-seasonal MA terms. Additionally, the spike in the PACF at low lags indicates a possible non-seasonal AR term.
With the empirical review and data diagnostics, I decided to try 3 models: SARIMA, SARIMAX, and Neural Networks. I started with a basic and simple Seasonal ARIMA with only total cases, then I added more predictors such as temperature, humidity, precipitation into the model. Lastly, I built Neural Networks model (multilayer feed-forward network) with NNETAR package in R. Here I will report only the process of building the best model, which is Seasonal ARIMAX.
Seasonal ARIMAX
Here after doing researches about what factors affect the proliferation of mosquitos, I added on these variables to Seasonal ARIMA using xreg arguments:
precipitation_amt_mm
reanalysis_dew_point_temp_k
reanalysis_relative_humidity_percent
station_avg_temp_c
station_diur_temp_rng_c
station_max_temp_c
station_min_temp_c
Basically, if you grew up in a tropical country, you might know that mosquitos’ lifecycle includes four separate and distinct stages in both water and air. Therefore, precipitation, temperature and humidity play an important role in accelerating the mosquito population. Refer this link for more information.
Sometimes, the impact of a predictor which is included in a regression model will not be simple and immediate. For example, the high temperature and high quantity of rainfall may impact total cases for some time after a few weeks. I ran CCF (Cross-Correlation Function) to see if any previous lags of the predictors are highly correlated with the current lag of total cases. It seems like the dew temperature of the previous 4 weeks might be positively correlated with the current number of cases.
The selection of ARIMA models was conducted using Akaike’s information criterion (AIC). Of all the model tested, a SARIMAX (3,0,2)(0,0,1)[52] are the most appropriate model for San Juan city, while ARIMAX (0,1,2) with K = 1 for seasonal Fourier term is the best model for Iquitos city.
The final choice between ARIMA and NNET based on in-sample cross-validation using MAE as the main parameter.
Here are the forecast plots of both cities. I combined the prediction of total cases of San Juan and Iquitos and submitted the result to Data Driven website. I got 25.6587 for MAE and ranked 674/4392.
The final model has some shortcomings that can be addressed in the future. Firstly, I totally left out “ndvi” (geographical variables and Satellite vegetation index) while these variables might be important to the breakouts of the disease. However, to include those variables, I need to do more researches to have a better understanding of what, why, and how they matter. Secondly, the model does not fully capture all the factors contributing to the spread of Dengue. More variables related to the infrastructure and healthcare systems of both cities should be included in the model. Lastly, a multiple-seasonal period model could be conducted to show the different seasonal patterns of week, month and year as the current model only captures the weekly seasonality. | [
{
"code": null,
"e": 660,
"s": 172,
"text": "During the last decades, dengue viruses have spread throughout the sub-tropical parts of the world, with an increase in the number of severe forms of dengue such as severe bleeding, low blood pressure, and even death. Because the disease is carried by mosquitoes, the transmission of Dengue fever is related to meteorological variables such as temperature and precipitation. In this blog post, I will go over how I tackle the DengAI competition Paper and Rcode can be found on my github!"
},
{
"code": null,
"e": 683,
"s": 660,
"text": "Here is the game plan:"
},
{
"code": null,
"e": 803,
"s": 683,
"text": "Data SplitDescriptive Analysis and Data VisualizationHandling Missing ValuesModel DiagnosticsModel FormationForecasting"
},
{
"code": null,
"e": 814,
"s": 803,
"text": "Data Split"
},
{
"code": null,
"e": 858,
"s": 814,
"text": "Descriptive Analysis and Data Visualization"
},
{
"code": null,
"e": 882,
"s": 858,
"text": "Handling Missing Values"
},
{
"code": null,
"e": 900,
"s": 882,
"text": "Model Diagnostics"
},
{
"code": null,
"e": 916,
"s": 900,
"text": "Model Formation"
},
{
"code": null,
"e": 928,
"s": 916,
"text": "Forecasting"
},
{
"code": null,
"e": 1297,
"s": 928,
"text": "The DengAI competition data set is essentially a messy dataset with two different cities and two different time frames. I split the dataset into two small datasets based on two cities: San Juan and Iquitos. From two datasets, I divided each into train and validation sets in order to test different models before choosing the best one to perform on the final test set."
},
{
"code": null,
"e": 1481,
"s": 1297,
"text": "The Data Processing for both San Juan and Iquitos were quite similar, so I will only show San Juan’s graphs in this section. Charts and Graphs of Iquitos will be provided in my paper."
},
{
"code": null,
"e": 1611,
"s": 1481,
"text": "Each dataset contains 25 variables including meteorological and geographical variables. See the details about each variable here."
},
{
"code": null,
"e": 1933,
"s": 1611,
"text": "A Correlation plot will be helpful to diagnose if there are any linear relationships between 2 variables. We can see none of those variables is highly correlated to total cases (Figure 3). However, if we include more than 2 variables and run a multivariate linear regression, the magnitude of each predictor might change."
},
{
"code": null,
"e": 2212,
"s": 1933,
"text": "The time series plot indicates that there might be seasonality in the data since the number of total cases peaks every year around summer time. Two scatter plots also suggest possible linear relationships between total cases and two climate variables. (temperature and humidity)"
},
{
"code": null,
"e": 2848,
"s": 2212,
"text": "Looking at the dual time series plots of total cases and temperature, and total cases and humidity, we can see sometimes the number of cases and climate values move up and down together; sometimes the weather variables peak or plummet first, then the total cases go up and down in 3 -4 weeks later. More interestingly, Dengue symptoms usually start 4 to 7 days after you are bitten by an infected mosquito. Mosquito might go through its life cycle in 14 days at 70° F and take only 10 days at 80° F. Therefore, in average, it takes 3–4 weeks for the cases to be reported after the temperature, precipitation or humidity go up and down."
},
{
"code": null,
"e": 3012,
"s": 2848,
"text": "The Descriptive Analysis and Data Visualization suggest a time series model with additional predictor variables, and possibly some previous lags of the predictors."
},
{
"code": null,
"e": 3288,
"s": 3012,
"text": "I handled missing data by using Last Observation Carried Forward method in R, which is basically replacing each NA with the most recent non-NA prior to it. Here I am assuming that the weather of the current week would not be too different to the weather of the previous week."
},
{
"code": null,
"e": 3622,
"s": 3288,
"text": "# build a function to impute data with the most recent that is non missing na.locf.data.frame <- function(object, ...) replace(object, TRUE, lapply(object, na.locf, ...)) #fill in NAs - SJ sjdata.train.imputed <- na.locf.data.frame(sjdata.train) #fill in NAs - IQ iqdata.train.imputed <- na.locf.data.frame(iqdata.train)"
},
{
"code": null,
"e": 4104,
"s": 3622,
"text": "An Augmented Dickey-Fuller Test suggests that the time series dataset is stationary. The dataset has complex seasonality with weekly data points (frequency = 52.18). Most of the methods such as ETS, Decomposition require the seasonal period to be an integer. Even if we round it up to 52, most of the methods will not handle such a large seasonal period efficiently. A possible approach could be to use a dynamic harmonic regression model by including Fourier terms in ARIMA model."
},
{
"code": null,
"e": 4370,
"s": 4104,
"text": "Next, to pick MA and AR terms, I first examined the early lags (1, 2, 3, ...) to judge non-seasonal terms. Those spikes in the ACF at low lags indicate non-seasonal MA terms. Additionally, the spike in the PACF at low lags indicates a possible non-seasonal AR term."
},
{
"code": null,
"e": 4833,
"s": 4370,
"text": "With the empirical review and data diagnostics, I decided to try 3 models: SARIMA, SARIMAX, and Neural Networks. I started with a basic and simple Seasonal ARIMA with only total cases, then I added more predictors such as temperature, humidity, precipitation into the model. Lastly, I built Neural Networks model (multilayer feed-forward network) with NNETAR package in R. Here I will report only the process of building the best model, which is Seasonal ARIMAX."
},
{
"code": null,
"e": 4849,
"s": 4833,
"text": "Seasonal ARIMAX"
},
{
"code": null,
"e": 5002,
"s": 4849,
"text": "Here after doing researches about what factors affect the proliferation of mosquitos, I added on these variables to Seasonal ARIMA using xreg arguments:"
},
{
"code": null,
"e": 5023,
"s": 5002,
"text": "precipitation_amt_mm"
},
{
"code": null,
"e": 5051,
"s": 5023,
"text": "reanalysis_dew_point_temp_k"
},
{
"code": null,
"e": 5088,
"s": 5051,
"text": "reanalysis_relative_humidity_percent"
},
{
"code": null,
"e": 5107,
"s": 5088,
"text": "station_avg_temp_c"
},
{
"code": null,
"e": 5131,
"s": 5107,
"text": "station_diur_temp_rng_c"
},
{
"code": null,
"e": 5150,
"s": 5131,
"text": "station_max_temp_c"
},
{
"code": null,
"e": 5169,
"s": 5150,
"text": "station_min_temp_c"
},
{
"code": null,
"e": 5478,
"s": 5169,
"text": "Basically, if you grew up in a tropical country, you might know that mosquitos’ lifecycle includes four separate and distinct stages in both water and air. Therefore, precipitation, temperature and humidity play an important role in accelerating the mosquito population. Refer this link for more information."
},
{
"code": null,
"e": 5976,
"s": 5478,
"text": "Sometimes, the impact of a predictor which is included in a regression model will not be simple and immediate. For example, the high temperature and high quantity of rainfall may impact total cases for some time after a few weeks. I ran CCF (Cross-Correlation Function) to see if any previous lags of the predictors are highly correlated with the current lag of total cases. It seems like the dew temperature of the previous 4 weeks might be positively correlated with the current number of cases."
},
{
"code": null,
"e": 6262,
"s": 5976,
"text": "The selection of ARIMA models was conducted using Akaike’s information criterion (AIC). Of all the model tested, a SARIMAX (3,0,2)(0,0,1)[52] are the most appropriate model for San Juan city, while ARIMAX (0,1,2) with K = 1 for seasonal Fourier term is the best model for Iquitos city."
},
{
"code": null,
"e": 6371,
"s": 6262,
"text": "The final choice between ARIMA and NNET based on in-sample cross-validation using MAE as the main parameter."
},
{
"code": null,
"e": 6572,
"s": 6371,
"text": "Here are the forecast plots of both cities. I combined the prediction of total cases of San Juan and Iquitos and submitted the result to Data Driven website. I got 25.6587 for MAE and ranked 674/4392."
}
] |
Node.js fs.readdir() Method - GeeksforGeeks | 11 Oct, 2021
The fs.readdir() method is used to asynchronously read the contents of a given directory. The callback of this method returns an array of all the file names in the directory. The options argument can be used to change the format in which the files are returned from the method.
Syntax:
fs.readdir( path, options, callback )
Parameters: This method accept three parameters as mentioned above and described below:
path: It holds the path of the directory from where the contents have to be read. It can be a String, Buffer or URL.
options: It is an object that can be used to specify optional parameters that will affect the method. It has two optional parameters:encoding: It is a string value which specifies which encoding would be used for the filenames given to the callback argument. The default value is ‘utf8’.withFileTypes: It is a boolean value which specifies whether the files would be returned as fs.Dirent objects. The default value is ‘false’.
encoding: It is a string value which specifies which encoding would be used for the filenames given to the callback argument. The default value is ‘utf8’.
withFileTypes: It is a boolean value which specifies whether the files would be returned as fs.Dirent objects. The default value is ‘false’.
callback: It is the function that would be called when the method is executed.err: It is an error that would be thrown if the operation fails.files: It is an array of String, Buffer or fs.Dirent objects that contain the files in the directory.
err: It is an error that would be thrown if the operation fails.
files: It is an array of String, Buffer or fs.Dirent objects that contain the files in the directory.
Below examples illustrate the fs.readdir() method in Node.js:
Example 1: This example uses fs.readdir() method to return the file names or file objects in the directory.
// Node.js program to demonstrate the// fs.readdir() method // Import the filesystem moduleconst fs = require('fs'); // Function to get current filenames// in directoryfs.readdir(__dirname, (err, files) => { if (err) console.log(err); else { console.log("\nCurrent directory filenames:"); files.forEach(file => { console.log(file); }) }}) // Function to get current filenames// in directory with "withFileTypes"// set to "true" fs.readdir(__dirname, { withFileTypes: true }, (err, files) => { console.log("\nCurrent directory files:"); if (err) console.log(err); else { files.forEach(file => { console.log(file); }) }})
Output:
Current directory filenames:
index.js
package.json
text_file_a.txt
text_file_b.txt
Current directory files:
Dirent { name: 'index.js', [Symbol(type)]: 1 }
Dirent { name: 'package.json', [Symbol(type)]: 1 }
Dirent { name: 'text_file_a.txt', [Symbol(type)]: 1 }
Dirent { name: 'text_file_b.txt', [Symbol(type)]: 1 }
Example 2: This example uses fs.readdir() method to return only the filenames with the “.txt” extension.
// Node.js program to demonstrate the// fs.readdir() method // Import the filesystem moduleconst fs = require('fs');const path = require('path'); // Function to get current filenames// in directory with specific extensionfs.readdir(__dirname, (err, files) => { if (err) console.log(err); else { console.log("\Filenames with the .txt extension:"); files.forEach(file => { if (path.extname(file) == ".txt") console.log(file); }) }})
Output:
Filenames with the .txt extension:
text_file_a.txt
text_file_b.txt
Reference: https://nodejs.org/api/fs.html#fs_fs_readdir_path_options_callback
Node.js-fs-module
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to install the previous version of node.js and npm ?
Difference between promise and async await in Node.js
How to use an ES6 import in Node.js?
Express.js res.sendFile() Function
Mongoose | findByIdAndUpdate() Function
Top 10 Front End Developer Skills That You Need in 2022
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript | [
{
"code": null,
"e": 24185,
"s": 24157,
"text": "\n11 Oct, 2021"
},
{
"code": null,
"e": 24463,
"s": 24185,
"text": "The fs.readdir() method is used to asynchronously read the contents of a given directory. The callback of this method returns an array of all the file names in the directory. The options argument can be used to change the format in which the files are returned from the method."
},
{
"code": null,
"e": 24471,
"s": 24463,
"text": "Syntax:"
},
{
"code": null,
"e": 24509,
"s": 24471,
"text": "fs.readdir( path, options, callback )"
},
{
"code": null,
"e": 24597,
"s": 24509,
"text": "Parameters: This method accept three parameters as mentioned above and described below:"
},
{
"code": null,
"e": 24714,
"s": 24597,
"text": "path: It holds the path of the directory from where the contents have to be read. It can be a String, Buffer or URL."
},
{
"code": null,
"e": 25142,
"s": 24714,
"text": "options: It is an object that can be used to specify optional parameters that will affect the method. It has two optional parameters:encoding: It is a string value which specifies which encoding would be used for the filenames given to the callback argument. The default value is ‘utf8’.withFileTypes: It is a boolean value which specifies whether the files would be returned as fs.Dirent objects. The default value is ‘false’."
},
{
"code": null,
"e": 25297,
"s": 25142,
"text": "encoding: It is a string value which specifies which encoding would be used for the filenames given to the callback argument. The default value is ‘utf8’."
},
{
"code": null,
"e": 25438,
"s": 25297,
"text": "withFileTypes: It is a boolean value which specifies whether the files would be returned as fs.Dirent objects. The default value is ‘false’."
},
{
"code": null,
"e": 25682,
"s": 25438,
"text": "callback: It is the function that would be called when the method is executed.err: It is an error that would be thrown if the operation fails.files: It is an array of String, Buffer or fs.Dirent objects that contain the files in the directory."
},
{
"code": null,
"e": 25747,
"s": 25682,
"text": "err: It is an error that would be thrown if the operation fails."
},
{
"code": null,
"e": 25849,
"s": 25747,
"text": "files: It is an array of String, Buffer or fs.Dirent objects that contain the files in the directory."
},
{
"code": null,
"e": 25911,
"s": 25849,
"text": "Below examples illustrate the fs.readdir() method in Node.js:"
},
{
"code": null,
"e": 26019,
"s": 25911,
"text": "Example 1: This example uses fs.readdir() method to return the file names or file objects in the directory."
},
{
"code": "// Node.js program to demonstrate the// fs.readdir() method // Import the filesystem moduleconst fs = require('fs'); // Function to get current filenames// in directoryfs.readdir(__dirname, (err, files) => { if (err) console.log(err); else { console.log(\"\\nCurrent directory filenames:\"); files.forEach(file => { console.log(file); }) }}) // Function to get current filenames// in directory with \"withFileTypes\"// set to \"true\" fs.readdir(__dirname, { withFileTypes: true }, (err, files) => { console.log(\"\\nCurrent directory files:\"); if (err) console.log(err); else { files.forEach(file => { console.log(file); }) }})",
"e": 26685,
"s": 26019,
"text": null
},
{
"code": null,
"e": 26693,
"s": 26685,
"text": "Output:"
},
{
"code": null,
"e": 27008,
"s": 26693,
"text": "Current directory filenames:\nindex.js\npackage.json\ntext_file_a.txt\ntext_file_b.txt\n\nCurrent directory files:\nDirent { name: 'index.js', [Symbol(type)]: 1 }\nDirent { name: 'package.json', [Symbol(type)]: 1 }\nDirent { name: 'text_file_a.txt', [Symbol(type)]: 1 }\nDirent { name: 'text_file_b.txt', [Symbol(type)]: 1 }"
},
{
"code": null,
"e": 27113,
"s": 27008,
"text": "Example 2: This example uses fs.readdir() method to return only the filenames with the “.txt” extension."
},
{
"code": "// Node.js program to demonstrate the// fs.readdir() method // Import the filesystem moduleconst fs = require('fs');const path = require('path'); // Function to get current filenames// in directory with specific extensionfs.readdir(__dirname, (err, files) => { if (err) console.log(err); else { console.log(\"\\Filenames with the .txt extension:\"); files.forEach(file => { if (path.extname(file) == \".txt\") console.log(file); }) }})",
"e": 27573,
"s": 27113,
"text": null
},
{
"code": null,
"e": 27581,
"s": 27573,
"text": "Output:"
},
{
"code": null,
"e": 27648,
"s": 27581,
"text": "Filenames with the .txt extension:\ntext_file_a.txt\ntext_file_b.txt"
},
{
"code": null,
"e": 27726,
"s": 27648,
"text": "Reference: https://nodejs.org/api/fs.html#fs_fs_readdir_path_options_callback"
},
{
"code": null,
"e": 27744,
"s": 27726,
"text": "Node.js-fs-module"
},
{
"code": null,
"e": 27751,
"s": 27744,
"text": "Picked"
},
{
"code": null,
"e": 27759,
"s": 27751,
"text": "Node.js"
},
{
"code": null,
"e": 27776,
"s": 27759,
"text": "Web Technologies"
},
{
"code": null,
"e": 27874,
"s": 27776,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27883,
"s": 27874,
"text": "Comments"
},
{
"code": null,
"e": 27896,
"s": 27883,
"text": "Old Comments"
},
{
"code": null,
"e": 27953,
"s": 27896,
"text": "How to install the previous version of node.js and npm ?"
},
{
"code": null,
"e": 28007,
"s": 27953,
"text": "Difference between promise and async await in Node.js"
},
{
"code": null,
"e": 28044,
"s": 28007,
"text": "How to use an ES6 import in Node.js?"
},
{
"code": null,
"e": 28079,
"s": 28044,
"text": "Express.js res.sendFile() Function"
},
{
"code": null,
"e": 28119,
"s": 28079,
"text": "Mongoose | findByIdAndUpdate() Function"
},
{
"code": null,
"e": 28175,
"s": 28119,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 28237,
"s": 28175,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 28280,
"s": 28237,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 28330,
"s": 28280,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
How to encrypt and decrypt a file using gpg command on linux | There are many choices on hand to secure your data. However, GPG provides the additional benefit to encrypting your data on a priority basis and transfers them securely over the internet. This article explains about – How to Encrypt and Decrypt a file using GPG command on Linux.
To get more information about GPG, use the following command –
$ gpg -h
The sample output should be like this –
gpg (GnuPG) 1.4.20
Copyright (C) 2015 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
Home: ~/.gnupg
Supported algorithms:
Pubkey: RSA, RSA-E, RSA-S, ELG-E, DSA
Cipher: IDEA, 3DES, CAST5, BLOWFISH, AES, AES192, AES256, TWOFISH,
CAMELLIA128, CAMELLIA192, CAMELLIA256
Hash: MD5, SHA1, RIPEMD160, SHA256, SHA384, SHA512, SHA224
Compression: Uncompressed, ZIP, ZLIB, BZIP2
Syntax: gpg [options] [files]
Sign, check, encrypt or decrypt
Default operation depends on the input data
Commands:
-s, --sign [file] make a signature
--clearsign [file] make a clear text signature
-b, --detach-sign make a detached signature
-e, --encrypt encrypt data
-c, --symmetric encryption only with symmetric cipher
-d, --decrypt decrypt data (default)
--verify verify a signature
--list-keys list keys
--list-sigs list keys and signatures
--check-sigs list and check key signatures
--fingerprint list keys and fingerprints
-K, --list-secret-keys list secret keys
--gen-key generate a new key pair
--delete-keys remove keys from the public keyring
--delete-secret-keys remove keys from the secret keyring
--sign-key sign a key
--lsign-key sign a key locally
--edit-key sign or edit a key
--gen-revoke generate a revocation certificate
--export export keys
--send-keys export keys to a key server
--recv-keys import keys from a key server
--search-keys search for keys on a key server
--refresh-keys update all keys from a keyserver
--import import/merge keys
--card-status print the card status
--card-edit change data on a card
--change-pin change a card's PIN
--update-trustdb update the trust database
--print-md algo [files] print message digests
...............................................................................
While encrypting and decrypting a file, it will ask to Enter passphrase(password) and Repeat passphrase to secure a file
To encrypt a file using GPG, please use the command as shown below –
$ gpg -c abc.txt
In the above command, it is encrypting abc.txt file. To verify it, use the following command –
$ ls
The sample output should be like this –
abc.txt Final_Url_Weight.csv site_health_depth5.txt
abc.txt.gpg FINAL_URL_WEIGHT.db tp_Crawled_few.txt
check_ageof_site.py final_url_weight.py
extracting_keywors.py final_url_weight_sqlite.py
To decrypt the above file, use the following command –
$ gpg -o abc.txt -d abc.txt.gpg
gpg: AES encrypted data
Enter passphrase:
Above the command de-crypts the file and stores in same directory.
In the above article, we have learnt – Learn how to Encrypt and Decrypt a file using GPG command on Linux. In our next articles, we will come up with more Linux based tricks and tips. Keep reading! | [
{
"code": null,
"e": 1342,
"s": 1062,
"text": "There are many choices on hand to secure your data. However, GPG provides the additional benefit to encrypting your data on a priority basis and transfers them securely over the internet. This article explains about – How to Encrypt and Decrypt a file using GPG command on Linux."
},
{
"code": null,
"e": 1405,
"s": 1342,
"text": "To get more information about GPG, use the following command –"
},
{
"code": null,
"e": 1414,
"s": 1405,
"text": "$ gpg -h"
},
{
"code": null,
"e": 1454,
"s": 1414,
"text": "The sample output should be like this –"
},
{
"code": null,
"e": 3751,
"s": 1454,
"text": "gpg (GnuPG) 1.4.20\nCopyright (C) 2015 Free Software Foundation, Inc.\nLicense GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>\nThis is free software: you are free to change and redistribute it.\nThere is NO WARRANTY, to the extent permitted by law.\n\nHome: ~/.gnupg\nSupported algorithms:\nPubkey: RSA, RSA-E, RSA-S, ELG-E, DSA\nCipher: IDEA, 3DES, CAST5, BLOWFISH, AES, AES192, AES256, TWOFISH,\n CAMELLIA128, CAMELLIA192, CAMELLIA256\nHash: MD5, SHA1, RIPEMD160, SHA256, SHA384, SHA512, SHA224\nCompression: Uncompressed, ZIP, ZLIB, BZIP2\n\nSyntax: gpg [options] [files]\nSign, check, encrypt or decrypt\nDefault operation depends on the input data\n\nCommands:\n\n-s, --sign [file] make a signature\n --clearsign [file] make a clear text signature\n-b, --detach-sign make a detached signature\n-e, --encrypt encrypt data\n-c, --symmetric encryption only with symmetric cipher\n-d, --decrypt decrypt data (default)\n --verify verify a signature\n --list-keys list keys\n --list-sigs list keys and signatures\n --check-sigs list and check key signatures\n --fingerprint list keys and fingerprints\n-K, --list-secret-keys list secret keys\n --gen-key generate a new key pair\n --delete-keys remove keys from the public keyring\n --delete-secret-keys remove keys from the secret keyring\n --sign-key sign a key\n --lsign-key sign a key locally\n --edit-key sign or edit a key\n --gen-revoke generate a revocation certificate\n --export export keys\n --send-keys export keys to a key server\n --recv-keys import keys from a key server\n --search-keys search for keys on a key server\n --refresh-keys update all keys from a keyserver\n --import import/merge keys\n--card-status print the card status\n--card-edit change data on a card\n--change-pin change a card's PIN\n--update-trustdb update the trust database\n--print-md algo [files] print message digests\n..............................................................................."
},
{
"code": null,
"e": 3872,
"s": 3751,
"text": "While encrypting and decrypting a file, it will ask to Enter passphrase(password) and Repeat passphrase to secure a file"
},
{
"code": null,
"e": 3941,
"s": 3872,
"text": "To encrypt a file using GPG, please use the command as shown below –"
},
{
"code": null,
"e": 3958,
"s": 3941,
"text": "$ gpg -c abc.txt"
},
{
"code": null,
"e": 4053,
"s": 3958,
"text": "In the above command, it is encrypting abc.txt file. To verify it, use the following command –"
},
{
"code": null,
"e": 4058,
"s": 4053,
"text": "$ ls"
},
{
"code": null,
"e": 4098,
"s": 4058,
"text": "The sample output should be like this –"
},
{
"code": null,
"e": 4337,
"s": 4098,
"text": "abc.txt Final_Url_Weight.csv site_health_depth5.txt\nabc.txt.gpg FINAL_URL_WEIGHT.db tp_Crawled_few.txt\ncheck_ageof_site.py final_url_weight.py\nextracting_keywors.py final_url_weight_sqlite.py"
},
{
"code": null,
"e": 4392,
"s": 4337,
"text": "To decrypt the above file, use the following command –"
},
{
"code": null,
"e": 4466,
"s": 4392,
"text": "$ gpg -o abc.txt -d abc.txt.gpg\ngpg: AES encrypted data\nEnter passphrase:"
},
{
"code": null,
"e": 4533,
"s": 4466,
"text": "Above the command de-crypts the file and stores in same directory."
},
{
"code": null,
"e": 4731,
"s": 4533,
"text": "In the above article, we have learnt – Learn how to Encrypt and Decrypt a file using GPG command on Linux. In our next articles, we will come up with more Linux based tricks and tips. Keep reading!"
}
] |
Visualizing Worldwide COVID-19 data using Python Plotly Maps | by Bee Guan Teo | Towards Data Science | Note from the editors: Towards Data Science is a Medium publication primarily based on the study of data science and machine learning. We are not health professionals or epidemiologists, and the opinions of this article should not be interpreted as professional advice. To learn more about the coronavirus pandemic, you can click here.
On 31 December 2019, an unknown pneumonia type disease was first reported to the World Health Organization (WHO) Country Office in China. This unknown disease was later named COVID-19 on 11 February 2020 as it is genetically related to the coronavirus which caused the SARS outbreak in 2003. COVID-19 is soon widely spread worldwide until WHO declared the outbreak a Public Health Emergency of International Concern on 30 January 2020.
In this article, I am going to introduce two ways of plotting maps using Python Plotly Libraries to show the distribution of COVID-19 cases around the world.
Python Plotly — https://plotly.com/python/
Python Pandas — https://pandas.pydata.org/
The installation guide can be found on the official webpage.
Novel Corona Virus Dataset
In this section, we are going to use plotly.graph_objects from Plotly libraries to create a scatter plot on a world map to show the distribution of COVID-19 confirmed cases around the world.
Code explanation
Line 1–2: import Pandas and Plotly library
Line 3: The worldwide COVID-19 data can be found in one of the CSV files of the Novel Corona Virus Dataset. We can use the Pandas read_csv method to read the file.
Line 4: Use the Pandas head method to show the first five row of records.
From the result above, we can observe the dataset includes the number of reported COVID-19 cases for each country from 22 Jan 2020 till 13 April 2020 (as of this writing). This dataset is updated on a daily basis. Unfortunately, there is a lack of province/state details in the dataset. We can see there are lots of NaN values in the Province/State column.
To ease our subsequent task to manipulate the column and plot the map, this is recommended to simplify some column names (e.g. Country/Region).
Code explanation
Line 5: We can use the Pandas rename method to change the column name “Country/Region” to “Country” and “Province/State” to “Province”.
Line 6: We use the Pandas head method to view the records again after renaming the columns.
We can now proceed to use Python Plotly library to create a scatter plot on a map using plotly.graph_objects.
The codes (Line 8 - 39) can seem daunting in the first place. Don’t worry, they are just the parameters we need to set for the map and the information about the parameters can be found at the Plotly reference page. Here I will only discuss several important parameters.
Code explanation
Line 8: Set text elements that will appear over the data points. This means when we hover over a data point on the map, the predefined text (e.g. Country Name + number of cases on 4 Apr 20) will be poped up.
Line 10–11: lon and lat are the parameters that we set for longitude and latitude of each data point on the map.
Line 14–23: marker is a representation of data points on the map. Here we set the symbol (Line 19) as square. This will render each data point as a square on the map. We can leave the reversescale and autocolorscale as True to enable the color of markers automatically changed by the number of reported COVID-19 cases.
Line 24–26: cmin and cmax are the lower bound and upper bound of the color domain for the data points.
Line 31–37: This is the part where we set the parameter values for the entire map such as the map title (Line 32) and more importantly the scope (Line 34). If we intend to show the worldwide data on the map, we need to set the scope as “world” and Plotly will generate a world map. If our purpose is just to show the data points only on the US, we can set the scope as “usa”. We can pick one of the following scope options:
world
usa
europe
africa
north america
south america
Line 39: fig.write_html will generate a HTML page that shows the scatter map.
Note: This is possible to display the map on Jupyter Notebook or Jupyter Lab instead of on a separate HTML page. To do so, we have to install an extension for our Jupyter Notebook / Jupyter Lab (https://plotly.com/python/getting-started/).
The scatterplot above gives us a general idea of reported cases of COVID-19 around the world on 13 April 2020. The markers with yellowish color reflect the relatively lower reported cases compared with those darker colors. From the map, we can see the US hits the most reported cases and it is followed by some countries in Europe such as Italy, UK, French, etc. When we hover over a data point on the map, we can see a predefined pop-up text which reveals the country name and number of reported cases associated with that data point.
We can also use the same dataset to plot a choropleth map using plotly.graph_objects. However, we will need to preprocess our data before we can proceed to create the choropleth map.
To create the choropleth map, we need to derive two pieces of info from our dataset:
A unique country listTotal reported COVID-19 cases for each country (13 Apr 2020)
A unique country list
Total reported COVID-19 cases for each country (13 Apr 2020)
Unfortunately, we can’t directly extract the two required pieces of info from the original datasets. Just look closely at our dataset again by previewing some records.
We could have two observations from our dataset as below:
There are duplicated country names in our record. This is because the given number of reported COVID-19 cases are broken down into several provinces/states that could belong to the same country.Each row of the reported COVID-19 case on 13 Apr 2020 is just the subtotal of cases that happen in each individual province or state in a country.
There are duplicated country names in our record. This is because the given number of reported COVID-19 cases are broken down into several provinces/states that could belong to the same country.
Each row of the reported COVID-19 case on 13 Apr 2020 is just the subtotal of cases that happen in each individual province or state in a country.
The two observations above can be seen intermittently when we traverse through the records country by country. This means the records on the original dataset are not consistent. There are some records that entail a breakdown of states in a country whereas some others only cover a single row of data for a whole nation.
Fortunately, there is a simple fix here. We can use Pandas library to restructure our data.
Code explanation
Line 1–5: These are the steps to import necessary Plotly and Pandas libraries, to read the CSV file and also to rename some columns.
Line 7: We can use Pandas groupby method to group our data based on the country and apply the sum method to calculate the total of reported cases for each country. The result is a list of sums and we assign it to a variable named total_list.
Line 9–13: We are going to clean the country list and generate a list of unique countries.
Firstly, use tolist method to convert the Country column to a list object and assign it to the variable country_list (Line 9).
Next, use set method to convert the country_list into a Python set object. The set method will automatically remove all the duplicated country names from the country_list. Only the unique country names will be stored in country_set (Line 10).
Next, convert the country_set to a list again and assign it back to country_list (Line 11).
Use sort method to rearrange the country_list following the alphabetical order (Line 12). *This step is required because the previously used set method will randomize the sequence of countries.
Line 14: At last, we create a new dataframe by using the country_list and total_list generated from previous steps as the only two columns in the new dataframe.
We have managed to restructure our data and store it into a new dataframe, new_df. The new_df includes the data we need (unique country list and total cases for each country) to generate a choropleth map and we are now ready to move on to the next step.
A choropleth map is a map that consists of colored polygons to represent spatial variations of a quantity. We are going to use go.Choropleth graph object to create a choropleth map that shows the distribution of reported COVID-19 cases around the world.
Again, the code can seem daunting in the first place. However, they are nothing more than setting parameters to build a choropleth map. We can refer to the reference page on the official website to gain further info about the parameters.
Code explanation
Line 17–19: We can define a color domain for our choropleth map. To define a color domain, we just create a list of Hexa color codes. (*The color codes can be obtained here).
Line 22–33: This is the part where we can set the parameters for the location list, color domain, text info displayed on the map, maker line color, etc.
Since we plot the map to show the COVID-19 cases around the world, we set the locationmode to “country names”. This enables us to set the Country column from new_df to locations parameter (Line 23–24). This is an important step to enable Plotly to map our COVID-19 data to their respective country location on the choropleth map. (*Please note that there is no coordinate, lat & long, are required).
We set the Total_Cases data from new_df to parameter z (Line 25). This is another crucial step to enable Plotly to reveal the frequency of reported cases based on a color domain applied to the choropleth map.
We can also set the “Total_Cases” to the text parameter (Line 26). This will display the total number of cases in a popup text whenever we hover over one of the country regions on the map.
Since we have defined our own color domain (Line 17–19), we can just set the parameter autocolorscale as false (Line 28).
We also set a title for the color bar (Line 30).
Line 33–37: Here, we simply set a title for the map and enable the coastline shown on the map.
Line 40: Output the map to a HTML page.
Finally, we have managed to create a Choropleth Map that shows an overview of the prevalence level of the coronavirus outbreak around the world. When we place our mouse on top of one of the country regions, we can see the number of reported cases shown in a popup text.
Have you ever wondered we can publish our map online? Plotly offers us an option to share our Map with the public free of charge. To do so, we just need to follow several simple steps below:
Open your Terminal (Mac)or Command Prompt (Windows), hit
pip install chart_studioorsudo pip install chart_studio
Visit Chart Studio Page and sign up for a free account. This process will only take less than 3 minutes. A free account allows us to share a maximum of 100 charts with the public.
After signing up a free Chart Studio account, visit the Setting page and look for API Keys. Copy the API Key and paste it at the top of our previous Python code (either Scatter Map or Choropleth Map).
Line 1–2: These two lines of code are to provide credential info to enable our Python program to access the Chart Studio features.
To share our map to the public, all we need is just to add one line of code at the last line (Line 42) of the existing Python program.
Run the code and Plotly will return a URL that redirects us to a web site that hosts our map.
You can view my shared Scatter Map at this link1 and Choropleth Map at this link 2.
Python Plotly is an easy to use chart plotting library that enables us to create stunning charts and share them with the public. This is definitely worthwhile to invest our time in learning Plotly and use it to accomplish our data visualization tasks. If you are interested in learning more about the Plotly library, a useful tutorial can be found on this blog post.
I wish this article can be one of the helpful reference sources for you.
Follow me on MediumConnect and reach me on LinkedIn
Follow me on Medium
Connect and reach me on LinkedIn
All the sources codes presented in this article are available in the GitHub repository. | [
{
"code": null,
"e": 508,
"s": 172,
"text": "Note from the editors: Towards Data Science is a Medium publication primarily based on the study of data science and machine learning. We are not health professionals or epidemiologists, and the opinions of this article should not be interpreted as professional advice. To learn more about the coronavirus pandemic, you can click here."
},
{
"code": null,
"e": 944,
"s": 508,
"text": "On 31 December 2019, an unknown pneumonia type disease was first reported to the World Health Organization (WHO) Country Office in China. This unknown disease was later named COVID-19 on 11 February 2020 as it is genetically related to the coronavirus which caused the SARS outbreak in 2003. COVID-19 is soon widely spread worldwide until WHO declared the outbreak a Public Health Emergency of International Concern on 30 January 2020."
},
{
"code": null,
"e": 1102,
"s": 944,
"text": "In this article, I am going to introduce two ways of plotting maps using Python Plotly Libraries to show the distribution of COVID-19 cases around the world."
},
{
"code": null,
"e": 1145,
"s": 1102,
"text": "Python Plotly — https://plotly.com/python/"
},
{
"code": null,
"e": 1188,
"s": 1145,
"text": "Python Pandas — https://pandas.pydata.org/"
},
{
"code": null,
"e": 1249,
"s": 1188,
"text": "The installation guide can be found on the official webpage."
},
{
"code": null,
"e": 1276,
"s": 1249,
"text": "Novel Corona Virus Dataset"
},
{
"code": null,
"e": 1467,
"s": 1276,
"text": "In this section, we are going to use plotly.graph_objects from Plotly libraries to create a scatter plot on a world map to show the distribution of COVID-19 confirmed cases around the world."
},
{
"code": null,
"e": 1484,
"s": 1467,
"text": "Code explanation"
},
{
"code": null,
"e": 1527,
"s": 1484,
"text": "Line 1–2: import Pandas and Plotly library"
},
{
"code": null,
"e": 1691,
"s": 1527,
"text": "Line 3: The worldwide COVID-19 data can be found in one of the CSV files of the Novel Corona Virus Dataset. We can use the Pandas read_csv method to read the file."
},
{
"code": null,
"e": 1765,
"s": 1691,
"text": "Line 4: Use the Pandas head method to show the first five row of records."
},
{
"code": null,
"e": 2122,
"s": 1765,
"text": "From the result above, we can observe the dataset includes the number of reported COVID-19 cases for each country from 22 Jan 2020 till 13 April 2020 (as of this writing). This dataset is updated on a daily basis. Unfortunately, there is a lack of province/state details in the dataset. We can see there are lots of NaN values in the Province/State column."
},
{
"code": null,
"e": 2266,
"s": 2122,
"text": "To ease our subsequent task to manipulate the column and plot the map, this is recommended to simplify some column names (e.g. Country/Region)."
},
{
"code": null,
"e": 2283,
"s": 2266,
"text": "Code explanation"
},
{
"code": null,
"e": 2419,
"s": 2283,
"text": "Line 5: We can use the Pandas rename method to change the column name “Country/Region” to “Country” and “Province/State” to “Province”."
},
{
"code": null,
"e": 2511,
"s": 2419,
"text": "Line 6: We use the Pandas head method to view the records again after renaming the columns."
},
{
"code": null,
"e": 2621,
"s": 2511,
"text": "We can now proceed to use Python Plotly library to create a scatter plot on a map using plotly.graph_objects."
},
{
"code": null,
"e": 2891,
"s": 2621,
"text": "The codes (Line 8 - 39) can seem daunting in the first place. Don’t worry, they are just the parameters we need to set for the map and the information about the parameters can be found at the Plotly reference page. Here I will only discuss several important parameters."
},
{
"code": null,
"e": 2908,
"s": 2891,
"text": "Code explanation"
},
{
"code": null,
"e": 3116,
"s": 2908,
"text": "Line 8: Set text elements that will appear over the data points. This means when we hover over a data point on the map, the predefined text (e.g. Country Name + number of cases on 4 Apr 20) will be poped up."
},
{
"code": null,
"e": 3229,
"s": 3116,
"text": "Line 10–11: lon and lat are the parameters that we set for longitude and latitude of each data point on the map."
},
{
"code": null,
"e": 3548,
"s": 3229,
"text": "Line 14–23: marker is a representation of data points on the map. Here we set the symbol (Line 19) as square. This will render each data point as a square on the map. We can leave the reversescale and autocolorscale as True to enable the color of markers automatically changed by the number of reported COVID-19 cases."
},
{
"code": null,
"e": 3651,
"s": 3548,
"text": "Line 24–26: cmin and cmax are the lower bound and upper bound of the color domain for the data points."
},
{
"code": null,
"e": 4075,
"s": 3651,
"text": "Line 31–37: This is the part where we set the parameter values for the entire map such as the map title (Line 32) and more importantly the scope (Line 34). If we intend to show the worldwide data on the map, we need to set the scope as “world” and Plotly will generate a world map. If our purpose is just to show the data points only on the US, we can set the scope as “usa”. We can pick one of the following scope options:"
},
{
"code": null,
"e": 4081,
"s": 4075,
"text": "world"
},
{
"code": null,
"e": 4085,
"s": 4081,
"text": "usa"
},
{
"code": null,
"e": 4092,
"s": 4085,
"text": "europe"
},
{
"code": null,
"e": 4099,
"s": 4092,
"text": "africa"
},
{
"code": null,
"e": 4113,
"s": 4099,
"text": "north america"
},
{
"code": null,
"e": 4127,
"s": 4113,
"text": "south america"
},
{
"code": null,
"e": 4205,
"s": 4127,
"text": "Line 39: fig.write_html will generate a HTML page that shows the scatter map."
},
{
"code": null,
"e": 4445,
"s": 4205,
"text": "Note: This is possible to display the map on Jupyter Notebook or Jupyter Lab instead of on a separate HTML page. To do so, we have to install an extension for our Jupyter Notebook / Jupyter Lab (https://plotly.com/python/getting-started/)."
},
{
"code": null,
"e": 4981,
"s": 4445,
"text": "The scatterplot above gives us a general idea of reported cases of COVID-19 around the world on 13 April 2020. The markers with yellowish color reflect the relatively lower reported cases compared with those darker colors. From the map, we can see the US hits the most reported cases and it is followed by some countries in Europe such as Italy, UK, French, etc. When we hover over a data point on the map, we can see a predefined pop-up text which reveals the country name and number of reported cases associated with that data point."
},
{
"code": null,
"e": 5164,
"s": 4981,
"text": "We can also use the same dataset to plot a choropleth map using plotly.graph_objects. However, we will need to preprocess our data before we can proceed to create the choropleth map."
},
{
"code": null,
"e": 5249,
"s": 5164,
"text": "To create the choropleth map, we need to derive two pieces of info from our dataset:"
},
{
"code": null,
"e": 5331,
"s": 5249,
"text": "A unique country listTotal reported COVID-19 cases for each country (13 Apr 2020)"
},
{
"code": null,
"e": 5353,
"s": 5331,
"text": "A unique country list"
},
{
"code": null,
"e": 5414,
"s": 5353,
"text": "Total reported COVID-19 cases for each country (13 Apr 2020)"
},
{
"code": null,
"e": 5582,
"s": 5414,
"text": "Unfortunately, we can’t directly extract the two required pieces of info from the original datasets. Just look closely at our dataset again by previewing some records."
},
{
"code": null,
"e": 5640,
"s": 5582,
"text": "We could have two observations from our dataset as below:"
},
{
"code": null,
"e": 5981,
"s": 5640,
"text": "There are duplicated country names in our record. This is because the given number of reported COVID-19 cases are broken down into several provinces/states that could belong to the same country.Each row of the reported COVID-19 case on 13 Apr 2020 is just the subtotal of cases that happen in each individual province or state in a country."
},
{
"code": null,
"e": 6176,
"s": 5981,
"text": "There are duplicated country names in our record. This is because the given number of reported COVID-19 cases are broken down into several provinces/states that could belong to the same country."
},
{
"code": null,
"e": 6323,
"s": 6176,
"text": "Each row of the reported COVID-19 case on 13 Apr 2020 is just the subtotal of cases that happen in each individual province or state in a country."
},
{
"code": null,
"e": 6643,
"s": 6323,
"text": "The two observations above can be seen intermittently when we traverse through the records country by country. This means the records on the original dataset are not consistent. There are some records that entail a breakdown of states in a country whereas some others only cover a single row of data for a whole nation."
},
{
"code": null,
"e": 6735,
"s": 6643,
"text": "Fortunately, there is a simple fix here. We can use Pandas library to restructure our data."
},
{
"code": null,
"e": 6752,
"s": 6735,
"text": "Code explanation"
},
{
"code": null,
"e": 6885,
"s": 6752,
"text": "Line 1–5: These are the steps to import necessary Plotly and Pandas libraries, to read the CSV file and also to rename some columns."
},
{
"code": null,
"e": 7127,
"s": 6885,
"text": "Line 7: We can use Pandas groupby method to group our data based on the country and apply the sum method to calculate the total of reported cases for each country. The result is a list of sums and we assign it to a variable named total_list."
},
{
"code": null,
"e": 7218,
"s": 7127,
"text": "Line 9–13: We are going to clean the country list and generate a list of unique countries."
},
{
"code": null,
"e": 7345,
"s": 7218,
"text": "Firstly, use tolist method to convert the Country column to a list object and assign it to the variable country_list (Line 9)."
},
{
"code": null,
"e": 7588,
"s": 7345,
"text": "Next, use set method to convert the country_list into a Python set object. The set method will automatically remove all the duplicated country names from the country_list. Only the unique country names will be stored in country_set (Line 10)."
},
{
"code": null,
"e": 7680,
"s": 7588,
"text": "Next, convert the country_set to a list again and assign it back to country_list (Line 11)."
},
{
"code": null,
"e": 7874,
"s": 7680,
"text": "Use sort method to rearrange the country_list following the alphabetical order (Line 12). *This step is required because the previously used set method will randomize the sequence of countries."
},
{
"code": null,
"e": 8035,
"s": 7874,
"text": "Line 14: At last, we create a new dataframe by using the country_list and total_list generated from previous steps as the only two columns in the new dataframe."
},
{
"code": null,
"e": 8289,
"s": 8035,
"text": "We have managed to restructure our data and store it into a new dataframe, new_df. The new_df includes the data we need (unique country list and total cases for each country) to generate a choropleth map and we are now ready to move on to the next step."
},
{
"code": null,
"e": 8543,
"s": 8289,
"text": "A choropleth map is a map that consists of colored polygons to represent spatial variations of a quantity. We are going to use go.Choropleth graph object to create a choropleth map that shows the distribution of reported COVID-19 cases around the world."
},
{
"code": null,
"e": 8781,
"s": 8543,
"text": "Again, the code can seem daunting in the first place. However, they are nothing more than setting parameters to build a choropleth map. We can refer to the reference page on the official website to gain further info about the parameters."
},
{
"code": null,
"e": 8798,
"s": 8781,
"text": "Code explanation"
},
{
"code": null,
"e": 8973,
"s": 8798,
"text": "Line 17–19: We can define a color domain for our choropleth map. To define a color domain, we just create a list of Hexa color codes. (*The color codes can be obtained here)."
},
{
"code": null,
"e": 9126,
"s": 8973,
"text": "Line 22–33: This is the part where we can set the parameters for the location list, color domain, text info displayed on the map, maker line color, etc."
},
{
"code": null,
"e": 9526,
"s": 9126,
"text": "Since we plot the map to show the COVID-19 cases around the world, we set the locationmode to “country names”. This enables us to set the Country column from new_df to locations parameter (Line 23–24). This is an important step to enable Plotly to map our COVID-19 data to their respective country location on the choropleth map. (*Please note that there is no coordinate, lat & long, are required)."
},
{
"code": null,
"e": 9735,
"s": 9526,
"text": "We set the Total_Cases data from new_df to parameter z (Line 25). This is another crucial step to enable Plotly to reveal the frequency of reported cases based on a color domain applied to the choropleth map."
},
{
"code": null,
"e": 9924,
"s": 9735,
"text": "We can also set the “Total_Cases” to the text parameter (Line 26). This will display the total number of cases in a popup text whenever we hover over one of the country regions on the map."
},
{
"code": null,
"e": 10046,
"s": 9924,
"text": "Since we have defined our own color domain (Line 17–19), we can just set the parameter autocolorscale as false (Line 28)."
},
{
"code": null,
"e": 10095,
"s": 10046,
"text": "We also set a title for the color bar (Line 30)."
},
{
"code": null,
"e": 10190,
"s": 10095,
"text": "Line 33–37: Here, we simply set a title for the map and enable the coastline shown on the map."
},
{
"code": null,
"e": 10230,
"s": 10190,
"text": "Line 40: Output the map to a HTML page."
},
{
"code": null,
"e": 10500,
"s": 10230,
"text": "Finally, we have managed to create a Choropleth Map that shows an overview of the prevalence level of the coronavirus outbreak around the world. When we place our mouse on top of one of the country regions, we can see the number of reported cases shown in a popup text."
},
{
"code": null,
"e": 10691,
"s": 10500,
"text": "Have you ever wondered we can publish our map online? Plotly offers us an option to share our Map with the public free of charge. To do so, we just need to follow several simple steps below:"
},
{
"code": null,
"e": 10748,
"s": 10691,
"text": "Open your Terminal (Mac)or Command Prompt (Windows), hit"
},
{
"code": null,
"e": 10804,
"s": 10748,
"text": "pip install chart_studioorsudo pip install chart_studio"
},
{
"code": null,
"e": 10984,
"s": 10804,
"text": "Visit Chart Studio Page and sign up for a free account. This process will only take less than 3 minutes. A free account allows us to share a maximum of 100 charts with the public."
},
{
"code": null,
"e": 11185,
"s": 10984,
"text": "After signing up a free Chart Studio account, visit the Setting page and look for API Keys. Copy the API Key and paste it at the top of our previous Python code (either Scatter Map or Choropleth Map)."
},
{
"code": null,
"e": 11316,
"s": 11185,
"text": "Line 1–2: These two lines of code are to provide credential info to enable our Python program to access the Chart Studio features."
},
{
"code": null,
"e": 11451,
"s": 11316,
"text": "To share our map to the public, all we need is just to add one line of code at the last line (Line 42) of the existing Python program."
},
{
"code": null,
"e": 11545,
"s": 11451,
"text": "Run the code and Plotly will return a URL that redirects us to a web site that hosts our map."
},
{
"code": null,
"e": 11629,
"s": 11545,
"text": "You can view my shared Scatter Map at this link1 and Choropleth Map at this link 2."
},
{
"code": null,
"e": 11996,
"s": 11629,
"text": "Python Plotly is an easy to use chart plotting library that enables us to create stunning charts and share them with the public. This is definitely worthwhile to invest our time in learning Plotly and use it to accomplish our data visualization tasks. If you are interested in learning more about the Plotly library, a useful tutorial can be found on this blog post."
},
{
"code": null,
"e": 12069,
"s": 11996,
"text": "I wish this article can be one of the helpful reference sources for you."
},
{
"code": null,
"e": 12121,
"s": 12069,
"text": "Follow me on MediumConnect and reach me on LinkedIn"
},
{
"code": null,
"e": 12141,
"s": 12121,
"text": "Follow me on Medium"
},
{
"code": null,
"e": 12174,
"s": 12141,
"text": "Connect and reach me on LinkedIn"
}
] |
C# Program to combine Dictionary of two keys | Firstly, set the Dictionaries to be combined −
Dictionary <string, int> dict1 = new Dictionary <string, int> ();
dict1.Add("one", 1);
dict1.Add("Two", 2);
Dictionary <string, int> dict2 = new Dictionary <string, int> ();
dict2.Add("Three", 3);
dict2.Add("Four", 4);
Now, use HashSet to combine them. The method used for the same purpose is UnionWith() −
HashSet <string> hSet = new HashSet <string> (dict1.Keys);
hSet.UnionWith(dict2.Keys);
The following is the complete code −
Live Demo
using System;
using System.Collections.Generic;
public class Program {
public static void Main() {
Dictionary <string, int> dict1 = new Dictionary <string, int> ();
dict1.Add("one", 1);
dict1.Add("Two", 2);
Dictionary <string, int> dict2 = new Dictionary <string, int> ();
dict2.Add("Three", 3);
dict2.Add("Four", 4);
HashSet <string> hSet = new HashSet <string> (dict1.Keys);
hSet.UnionWith(dict2.Keys);
Console.WriteLine("Union of Dictionary...");
foreach(string val in hSet) {
Console.WriteLine(val);
}
}
}
Union of Dictionary...
one
Two
Three
Four | [
{
"code": null,
"e": 1109,
"s": 1062,
"text": "Firstly, set the Dictionaries to be combined −"
},
{
"code": null,
"e": 1328,
"s": 1109,
"text": "Dictionary <string, int> dict1 = new Dictionary <string, int> ();\ndict1.Add(\"one\", 1);\ndict1.Add(\"Two\", 2);\nDictionary <string, int> dict2 = new Dictionary <string, int> ();\ndict2.Add(\"Three\", 3);\ndict2.Add(\"Four\", 4);"
},
{
"code": null,
"e": 1416,
"s": 1328,
"text": "Now, use HashSet to combine them. The method used for the same purpose is UnionWith() −"
},
{
"code": null,
"e": 1503,
"s": 1416,
"text": "HashSet <string> hSet = new HashSet <string> (dict1.Keys);\nhSet.UnionWith(dict2.Keys);"
},
{
"code": null,
"e": 1540,
"s": 1503,
"text": "The following is the complete code −"
},
{
"code": null,
"e": 1551,
"s": 1540,
"text": " Live Demo"
},
{
"code": null,
"e": 2142,
"s": 1551,
"text": "using System;\nusing System.Collections.Generic;\npublic class Program {\n public static void Main() {\n Dictionary <string, int> dict1 = new Dictionary <string, int> ();\n dict1.Add(\"one\", 1);\n dict1.Add(\"Two\", 2);\n Dictionary <string, int> dict2 = new Dictionary <string, int> ();\n dict2.Add(\"Three\", 3);\n dict2.Add(\"Four\", 4);\n HashSet <string> hSet = new HashSet <string> (dict1.Keys);\n hSet.UnionWith(dict2.Keys);\n Console.WriteLine(\"Union of Dictionary...\");\n foreach(string val in hSet) {\n Console.WriteLine(val);\n }\n }\n}"
},
{
"code": null,
"e": 2184,
"s": 2142,
"text": "Union of Dictionary...\none\nTwo\nThree\nFour"
}
] |
How to find if two arrays contain any common item in Javascript? - GeeksforGeeks | 19 Oct, 2021
Given two arrays containing array elements and the task is to check if two arrays contain any common elements then it returns True otherwise return False.Examples:
Input: array1 = ['a', 'b', 'c', 'd', 'e']
array2 = ['f', 'g', 'c']
Output: true
Input: array1 = ['x', 'y', 'w', 'z']
array2 = ['m', 'n', 'k']
Output: false
There are many methods to solve this problem in JavaScript some of them are discussed below.Method 1: Brute Force approach
Compare each and every item from the first array to each and every item of second array.
Loop through array1 and iterate it from beginning to the end.
Loop through array2 and iterate it from beginning to the end.
Compare each and every item from array1 to array2 and if it finds any common item then return true otherwise return false.
Example:
javascript
<script> // Declare two arrayconst array1 = ['a', 'b', 'c', 'd'];const array2 = ['k', 'x', 'z']; // Function definition with passing two arraysfunction findCommonElement(array1, array2) { // Loop for array1 for(let i = 0; i < array1.length; i++) { // Loop for array2 for(let j = 0; j < array2.length; j++) { // Compare the element of each and // every element from both of the // arrays if(array1[i] === array2[j]) { // Return if common element found return true; } } } // Return if no common element exist return false;} document.write(findCommonElement(array1, array2))</script>
Output:
false
Time Complexity: O(M * N)Method 2:
Create an empty object and loop through first array.
Check if the elements from the first array exist in the object or not. If it doesn’t exist then assign properties === elements in the array.
Loop through second array and check if elements in the second array exists on created object.
If element exist then return true else return false.
Example:
javascript
<script> // Declare Two arrayconst array1 = ['a', 'd', 'm', 'x'];const array2 = ['p', 'y', 'k']; // Function callfunction findCommonElements2(arr1, arr2) { // Create an empty object let obj = {}; // Loop through the first array for (let i = 0; i < arr1.length; i++) { // Check if element from first array // already exist in object or not if(!obj[arr1[i]]) { // If it doesn't exist assign the // properties equals to the // elements in the array const element = arr1[i]; obj[element] = true; } } // Loop through the second array for (let j = 0; j < arr2.length ; j++) { // Check elements from second array exist // in the created object or not if(obj[arr2[j]]) { return true; } } return false;} document.write(findCommonElements2(array1, array2))</script>
Output:
false
Time Complexity: O(M + N)Method 3:
Use the inbuilt ES6 function some() to iterate through each and every element of first array and to test the array.
Use the inbuilt function includes() with second array to check if element exist in the first array or not.
If element exist then return true else return false
javascript
<script> // Declare two arrayconst array1= ['a', 'b', 'x', 'z'];const array2= ['k', 'x', 'c'] // Iterate through each element in the// first array and if some of them// include the elements in the second// array then return true.function findCommonElements3(arr1, arr2) { return arr1.some(item => arr2.includes(item))} document.write(findCommonElements3(array1, array2))</script>
Output:
true
JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.
kalrap615
javascript-array
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript | [
{
"code": null,
"e": 26683,
"s": 26655,
"text": "\n19 Oct, 2021"
},
{
"code": null,
"e": 26849,
"s": 26683,
"text": "Given two arrays containing array elements and the task is to check if two arrays contain any common elements then it returns True otherwise return False.Examples: "
},
{
"code": null,
"e": 27020,
"s": 26849,
"text": "Input: array1 = ['a', 'b', 'c', 'd', 'e']\n array2 = ['f', 'g', 'c']\nOutput: true\n\nInput: array1 = ['x', 'y', 'w', 'z']\n array2 = ['m', 'n', 'k']\nOutput: false"
},
{
"code": null,
"e": 27145,
"s": 27020,
"text": "There are many methods to solve this problem in JavaScript some of them are discussed below.Method 1: Brute Force approach "
},
{
"code": null,
"e": 27234,
"s": 27145,
"text": "Compare each and every item from the first array to each and every item of second array."
},
{
"code": null,
"e": 27296,
"s": 27234,
"text": "Loop through array1 and iterate it from beginning to the end."
},
{
"code": null,
"e": 27358,
"s": 27296,
"text": "Loop through array2 and iterate it from beginning to the end."
},
{
"code": null,
"e": 27481,
"s": 27358,
"text": "Compare each and every item from array1 to array2 and if it finds any common item then return true otherwise return false."
},
{
"code": null,
"e": 27492,
"s": 27481,
"text": "Example: "
},
{
"code": null,
"e": 27503,
"s": 27492,
"text": "javascript"
},
{
"code": "<script> // Declare two arrayconst array1 = ['a', 'b', 'c', 'd'];const array2 = ['k', 'x', 'z']; // Function definition with passing two arraysfunction findCommonElement(array1, array2) { // Loop for array1 for(let i = 0; i < array1.length; i++) { // Loop for array2 for(let j = 0; j < array2.length; j++) { // Compare the element of each and // every element from both of the // arrays if(array1[i] === array2[j]) { // Return if common element found return true; } } } // Return if no common element exist return false;} document.write(findCommonElement(array1, array2))</script> ",
"e": 28269,
"s": 27503,
"text": null
},
{
"code": null,
"e": 28279,
"s": 28269,
"text": "Output: "
},
{
"code": null,
"e": 28285,
"s": 28279,
"text": "false"
},
{
"code": null,
"e": 28322,
"s": 28285,
"text": "Time Complexity: O(M * N)Method 2: "
},
{
"code": null,
"e": 28375,
"s": 28322,
"text": "Create an empty object and loop through first array."
},
{
"code": null,
"e": 28516,
"s": 28375,
"text": "Check if the elements from the first array exist in the object or not. If it doesn’t exist then assign properties === elements in the array."
},
{
"code": null,
"e": 28610,
"s": 28516,
"text": "Loop through second array and check if elements in the second array exists on created object."
},
{
"code": null,
"e": 28663,
"s": 28610,
"text": "If element exist then return true else return false."
},
{
"code": null,
"e": 28674,
"s": 28663,
"text": "Example: "
},
{
"code": null,
"e": 28685,
"s": 28674,
"text": "javascript"
},
{
"code": "<script> // Declare Two arrayconst array1 = ['a', 'd', 'm', 'x'];const array2 = ['p', 'y', 'k']; // Function callfunction findCommonElements2(arr1, arr2) { // Create an empty object let obj = {}; // Loop through the first array for (let i = 0; i < arr1.length; i++) { // Check if element from first array // already exist in object or not if(!obj[arr1[i]]) { // If it doesn't exist assign the // properties equals to the // elements in the array const element = arr1[i]; obj[element] = true; } } // Loop through the second array for (let j = 0; j < arr2.length ; j++) { // Check elements from second array exist // in the created object or not if(obj[arr2[j]]) { return true; } } return false;} document.write(findCommonElements2(array1, array2))</script> ",
"e": 29723,
"s": 28685,
"text": null
},
{
"code": null,
"e": 29733,
"s": 29723,
"text": "Output: "
},
{
"code": null,
"e": 29739,
"s": 29733,
"text": "false"
},
{
"code": null,
"e": 29776,
"s": 29739,
"text": "Time Complexity: O(M + N)Method 3: "
},
{
"code": null,
"e": 29892,
"s": 29776,
"text": "Use the inbuilt ES6 function some() to iterate through each and every element of first array and to test the array."
},
{
"code": null,
"e": 29999,
"s": 29892,
"text": "Use the inbuilt function includes() with second array to check if element exist in the first array or not."
},
{
"code": null,
"e": 30051,
"s": 29999,
"text": "If element exist then return true else return false"
},
{
"code": null,
"e": 30064,
"s": 30053,
"text": "javascript"
},
{
"code": "<script> // Declare two arrayconst array1= ['a', 'b', 'x', 'z'];const array2= ['k', 'x', 'c'] // Iterate through each element in the// first array and if some of them// include the elements in the second// array then return true.function findCommonElements3(arr1, arr2) { return arr1.some(item => arr2.includes(item))} document.write(findCommonElements3(array1, array2))</script> ",
"e": 30466,
"s": 30064,
"text": null
},
{
"code": null,
"e": 30476,
"s": 30466,
"text": "Output: "
},
{
"code": null,
"e": 30481,
"s": 30476,
"text": "true"
},
{
"code": null,
"e": 30702,
"s": 30483,
"text": "JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples."
},
{
"code": null,
"e": 30714,
"s": 30704,
"text": "kalrap615"
},
{
"code": null,
"e": 30731,
"s": 30714,
"text": "javascript-array"
},
{
"code": null,
"e": 30742,
"s": 30731,
"text": "JavaScript"
},
{
"code": null,
"e": 30759,
"s": 30742,
"text": "Web Technologies"
},
{
"code": null,
"e": 30786,
"s": 30759,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 30884,
"s": 30786,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30924,
"s": 30884,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 30969,
"s": 30924,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 31030,
"s": 30969,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 31102,
"s": 31030,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 31154,
"s": 31102,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 31194,
"s": 31154,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 31227,
"s": 31194,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 31272,
"s": 31227,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 31315,
"s": 31272,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Python - Levy_stable Distribution in Statistics - GeeksforGeeks | 10 Jan, 2020
scipy.stats.levy_stable() is a Levy-stable continuous random variable. It is inherited from the of generic methods as an instance of the rv_continuous class. It completes the methods with details specific for this particular distribution.
Parameters :
q : lower and upper tail probabilityx : quantilesloc : [optional]location parameter. Default = 0scale : [optional]scale parameter. Default = 1size : [tuple of ints, optional] shape or random variates.moments : [optional] composed of letters [‘mvsk’]; ‘m’ = mean, ‘v’ = variance, ‘s’ = Fisher’s skew and ‘k’ = Fisher’s kurtosis. (default = ‘mv’).
Results : Levy-stable continuous random variable
Code #1 : Creating Levy-stable Levy continuous random variable
# importing library from scipy.stats import levy_stable numargs = levy_stable.numargs a, b = 4.32, 3.18rv = levy_stable(a, b) print ("RV : \n", rv)
Output :
RV :
scipy.stats._distn_infrastructure.rv_frozen object at 0x000002A9D6803648
Code #2 : Levy-stable continuous variates and probability distribution
import numpy as np quantile = np.arange (0.03, 2, 0.21) # Random Variates R = levy_stable.rvs(1.8, -0.5, size = 10) print ("Random Variates : \n", R) # PDF R = levy_stable.pdf(a, b, quantile) print ("\nProbability Distribution : \n", R)
Output :
Random Variates :
[ 1.20654126 -0.56381774 -1.31527459 -0.90027222 0.52535969 0.03076316
-4.69310302 0.61194358 1.31207992 -0.84552083]
Probability Distribution :
[nan nan nan nan nan nan nan nan nan nan]
Code #3 : Graphical Representation.
import numpy as np import matplotlib.pyplot as plt distribution = np.linspace(levy_stable.ppf(0.01, 1.8, -0.5), levy_stable.ppf(0.99, 1.8, -0.5), 100) print("Distribution : \n", distribution)
Output :
Distribution :
[-4.92358285 -4.8368521 -4.75012136 -4.66339061 -4.57665986 -4.48992912
-4.40319837 -4.31646762 -4.22973687 -4.14300613 -4.05627538 -3.96954463
-3.88281389 -3.79608314 -3.70935239 -3.62262164 -3.5358909 -3.44916015
-3.3624294 -3.27569866 -3.18896791 -3.10223716 -3.01550641 -2.92877567
-2.84204492 -2.75531417 -2.66858343 -2.58185268 -2.49512193 -2.40839118
-2.32166044 -2.23492969 -2.14819894 -2.06146819 -1.97473745 -1.8880067
-1.80127595 -1.71454521 -1.62781446 -1.54108371 -1.45435296 -1.36762222
-1.28089147 -1.19416072 -1.10742998 -1.02069923 -0.93396848 -0.84723773
-0.76050699 -0.67377624 -0.58704549 -0.50031475 -0.413584 -0.32685325
-0.2401225 -0.15339176 -0.06666101 0.02006974 0.10680048 0.19353123
0.28026198 0.36699273 0.45372347 0.54045422 0.62718497 0.71391571
0.80064646 0.88737721 0.97410796 1.0608387 1.14756945 1.2343002
1.32103094 1.40776169 1.49449244 1.58122319 1.66795393 1.75468468
1.84141543 1.92814618 2.01487692 2.10160767 2.18833842 2.27506916
2.36179991 2.44853066 2.53526141 2.62199215 2.7087229 2.79545365
2.88218439 2.96891514 3.05564589 3.14237664 3.22910738 3.31583813
3.40256888 3.48929962 3.57603037 3.66276112]
Python scipy-stats-functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Defaultdict in Python
Enumerate() in Python
sum() function in Python
Python String | replace()
Read a file line by line in Python
How to Install PIP on Windows ?
Deque in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Stack in Python | [
{
"code": null,
"e": 25463,
"s": 25435,
"text": "\n10 Jan, 2020"
},
{
"code": null,
"e": 25702,
"s": 25463,
"text": "scipy.stats.levy_stable() is a Levy-stable continuous random variable. It is inherited from the of generic methods as an instance of the rv_continuous class. It completes the methods with details specific for this particular distribution."
},
{
"code": null,
"e": 25715,
"s": 25702,
"text": "Parameters :"
},
{
"code": null,
"e": 26061,
"s": 25715,
"text": "q : lower and upper tail probabilityx : quantilesloc : [optional]location parameter. Default = 0scale : [optional]scale parameter. Default = 1size : [tuple of ints, optional] shape or random variates.moments : [optional] composed of letters [‘mvsk’]; ‘m’ = mean, ‘v’ = variance, ‘s’ = Fisher’s skew and ‘k’ = Fisher’s kurtosis. (default = ‘mv’)."
},
{
"code": null,
"e": 26110,
"s": 26061,
"text": "Results : Levy-stable continuous random variable"
},
{
"code": null,
"e": 26173,
"s": 26110,
"text": "Code #1 : Creating Levy-stable Levy continuous random variable"
},
{
"code": "# importing library from scipy.stats import levy_stable numargs = levy_stable.numargs a, b = 4.32, 3.18rv = levy_stable(a, b) print (\"RV : \\n\", rv) ",
"e": 26333,
"s": 26173,
"text": null
},
{
"code": null,
"e": 26342,
"s": 26333,
"text": "Output :"
},
{
"code": null,
"e": 26423,
"s": 26342,
"text": "RV : \n scipy.stats._distn_infrastructure.rv_frozen object at 0x000002A9D6803648\n"
},
{
"code": null,
"e": 26494,
"s": 26423,
"text": "Code #2 : Levy-stable continuous variates and probability distribution"
},
{
"code": "import numpy as np quantile = np.arange (0.03, 2, 0.21) # Random Variates R = levy_stable.rvs(1.8, -0.5, size = 10) print (\"Random Variates : \\n\", R) # PDF R = levy_stable.pdf(a, b, quantile) print (\"\\nProbability Distribution : \\n\", R) ",
"e": 26736,
"s": 26494,
"text": null
},
{
"code": null,
"e": 26745,
"s": 26736,
"text": "Output :"
},
{
"code": null,
"e": 26962,
"s": 26745,
"text": "Random Variates : \n [ 1.20654126 -0.56381774 -1.31527459 -0.90027222 0.52535969 0.03076316\n -4.69310302 0.61194358 1.31207992 -0.84552083]\n\nProbability Distribution : \n [nan nan nan nan nan nan nan nan nan nan]\n\n"
},
{
"code": null,
"e": 26998,
"s": 26962,
"text": "Code #3 : Graphical Representation."
},
{
"code": "import numpy as np import matplotlib.pyplot as plt distribution = np.linspace(levy_stable.ppf(0.01, 1.8, -0.5), levy_stable.ppf(0.99, 1.8, -0.5), 100) print(\"Distribution : \\n\", distribution) ",
"e": 27224,
"s": 26998,
"text": null
},
{
"code": null,
"e": 27233,
"s": 27224,
"text": "Output :"
},
{
"code": null,
"e": 28466,
"s": 27233,
"text": "Distribution : \n [-4.92358285 -4.8368521 -4.75012136 -4.66339061 -4.57665986 -4.48992912\n -4.40319837 -4.31646762 -4.22973687 -4.14300613 -4.05627538 -3.96954463\n -3.88281389 -3.79608314 -3.70935239 -3.62262164 -3.5358909 -3.44916015\n -3.3624294 -3.27569866 -3.18896791 -3.10223716 -3.01550641 -2.92877567\n -2.84204492 -2.75531417 -2.66858343 -2.58185268 -2.49512193 -2.40839118\n -2.32166044 -2.23492969 -2.14819894 -2.06146819 -1.97473745 -1.8880067\n -1.80127595 -1.71454521 -1.62781446 -1.54108371 -1.45435296 -1.36762222\n -1.28089147 -1.19416072 -1.10742998 -1.02069923 -0.93396848 -0.84723773\n -0.76050699 -0.67377624 -0.58704549 -0.50031475 -0.413584 -0.32685325\n -0.2401225 -0.15339176 -0.06666101 0.02006974 0.10680048 0.19353123\n 0.28026198 0.36699273 0.45372347 0.54045422 0.62718497 0.71391571\n 0.80064646 0.88737721 0.97410796 1.0608387 1.14756945 1.2343002\n 1.32103094 1.40776169 1.49449244 1.58122319 1.66795393 1.75468468\n 1.84141543 1.92814618 2.01487692 2.10160767 2.18833842 2.27506916\n 2.36179991 2.44853066 2.53526141 2.62199215 2.7087229 2.79545365\n 2.88218439 2.96891514 3.05564589 3.14237664 3.22910738 3.31583813\n 3.40256888 3.48929962 3.57603037 3.66276112]"
},
{
"code": null,
"e": 28495,
"s": 28466,
"text": "Python scipy-stats-functions"
},
{
"code": null,
"e": 28502,
"s": 28495,
"text": "Python"
},
{
"code": null,
"e": 28600,
"s": 28502,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28622,
"s": 28600,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28644,
"s": 28622,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28669,
"s": 28644,
"text": "sum() function in Python"
},
{
"code": null,
"e": 28695,
"s": 28669,
"text": "Python String | replace()"
},
{
"code": null,
"e": 28730,
"s": 28695,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 28762,
"s": 28730,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28778,
"s": 28762,
"text": "Deque in Python"
},
{
"code": null,
"e": 28820,
"s": 28778,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28850,
"s": 28820,
"text": "Iterate over a list in Python"
}
] |
How to install CSI Linux in VirtualBox? - GeeksforGeeks | 06 Oct, 2021
What if there is a multi-purpose operating system designed especially for cyber investigators, yes you read it right and the answer to that question is, yes there is one such operating system known as CSI Linux. It is an open-source ‘theme park’ for the cyber security industry enthusiast. It has tons of resources for investigations, analysis, and response. It is available in both Virtual Machines and Bootable distro.
Provides CSI Tools like Online Investigation Tools.
Has Centralized Evidence Capture.
Cryptocurrency Wallet Lookup.
More than 175 tools.
Also has CSI TorVpn.
Minimum 8 gigs of ram.
50 gigabytes of free space on your hard drive.
20 gigabytes of free space for the download.
VirtualBox extension pack should be installed. (Extension pack)
CSI Linux ova File can be downloaded from here.
Virtual Box on the System- Installing the virtual box.
Step 1: VMware and VirtualBox can open ova files so simply double click on CSI Linux ova file and click on import.
Step 2: One needs to agree to the license agreement in order to proceed, so click on Agree button.
Step 3: Then the importing process will start and will take 4-5 minutes.
Step 4: When the importing process is done, click on CSI machine in VirtualBox and go to settings. In settings, increase the CPU from 1 to 4.
Step 5: Also increase the video memory to 120 MB in the display option.
Step 6: After configuring settings like video memory, CPUs in VirtualBox, enter the password ‘csi’ and click on Log in.
Step 7: And just like that, there you have it!!! Your CSI Linux is installed, easy right?
Step 8: CSI Linux is installed on your VirtualBox. On the bottom we can see, there are various applications offered by CSI Linux.
On the right, we can see Today’s date and time, also one can know for how many minutes its CSI Linux has been up i.e. the uptime and many other things.
Open the terminal and get started.
whoami
ls
One can even see Live Threat Maps by simply right-clicking and selecting cyber threat maps.
Live Cyber Threat Map is given below:
It also has VirtualBox, VMware pre-installed, cool right!!
Also, there are tons of OSINT tools pre-installed on CSI Linux which can be accessed by either right-clicking and selecting it from the menu or click on the bottom left green icon of applications.
One can know its IP address and Tor IP address by simply clicking on the ‘question mark icon’ given on the top right corner.
In conclusion, CSI Linux is literally a gold mine for cyber enthusiasts as it is a one-stop shopping place where one can get literally anything and also a tool pre-installed. One can perform OSINT, browse websites, or share files safely using onion share. Go ahead, explore it yourself and see what else it has to offer.
how-to-install
How To
Installation Guide
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install FFmpeg on Windows?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Set Git Username and Password in GitBash?
How to create a nested RecyclerView in Android
How to Install Jupyter Notebook on MacOS?
Installation of Node.js on Linux
How to Install FFmpeg on Windows?
How to Install Pygame on Windows ?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Install Jupyter Notebook on MacOS? | [
{
"code": null,
"e": 26197,
"s": 26169,
"text": "\n06 Oct, 2021"
},
{
"code": null,
"e": 26618,
"s": 26197,
"text": "What if there is a multi-purpose operating system designed especially for cyber investigators, yes you read it right and the answer to that question is, yes there is one such operating system known as CSI Linux. It is an open-source ‘theme park’ for the cyber security industry enthusiast. It has tons of resources for investigations, analysis, and response. It is available in both Virtual Machines and Bootable distro."
},
{
"code": null,
"e": 26670,
"s": 26618,
"text": "Provides CSI Tools like Online Investigation Tools."
},
{
"code": null,
"e": 26704,
"s": 26670,
"text": "Has Centralized Evidence Capture."
},
{
"code": null,
"e": 26734,
"s": 26704,
"text": "Cryptocurrency Wallet Lookup."
},
{
"code": null,
"e": 26755,
"s": 26734,
"text": "More than 175 tools."
},
{
"code": null,
"e": 26776,
"s": 26755,
"text": "Also has CSI TorVpn."
},
{
"code": null,
"e": 26799,
"s": 26776,
"text": "Minimum 8 gigs of ram."
},
{
"code": null,
"e": 26846,
"s": 26799,
"text": "50 gigabytes of free space on your hard drive."
},
{
"code": null,
"e": 26891,
"s": 26846,
"text": "20 gigabytes of free space for the download."
},
{
"code": null,
"e": 26955,
"s": 26891,
"text": "VirtualBox extension pack should be installed. (Extension pack)"
},
{
"code": null,
"e": 27003,
"s": 26955,
"text": "CSI Linux ova File can be downloaded from here."
},
{
"code": null,
"e": 27058,
"s": 27003,
"text": "Virtual Box on the System- Installing the virtual box."
},
{
"code": null,
"e": 27174,
"s": 27058,
"text": "Step 1: VMware and VirtualBox can open ova files so simply double click on CSI Linux ova file and click on import."
},
{
"code": null,
"e": 27273,
"s": 27174,
"text": "Step 2: One needs to agree to the license agreement in order to proceed, so click on Agree button."
},
{
"code": null,
"e": 27346,
"s": 27273,
"text": "Step 3: Then the importing process will start and will take 4-5 minutes."
},
{
"code": null,
"e": 27488,
"s": 27346,
"text": "Step 4: When the importing process is done, click on CSI machine in VirtualBox and go to settings. In settings, increase the CPU from 1 to 4."
},
{
"code": null,
"e": 27560,
"s": 27488,
"text": "Step 5: Also increase the video memory to 120 MB in the display option."
},
{
"code": null,
"e": 27680,
"s": 27560,
"text": "Step 6: After configuring settings like video memory, CPUs in VirtualBox, enter the password ‘csi’ and click on Log in."
},
{
"code": null,
"e": 27770,
"s": 27680,
"text": "Step 7: And just like that, there you have it!!! Your CSI Linux is installed, easy right?"
},
{
"code": null,
"e": 27900,
"s": 27770,
"text": "Step 8: CSI Linux is installed on your VirtualBox. On the bottom we can see, there are various applications offered by CSI Linux."
},
{
"code": null,
"e": 28052,
"s": 27900,
"text": "On the right, we can see Today’s date and time, also one can know for how many minutes its CSI Linux has been up i.e. the uptime and many other things."
},
{
"code": null,
"e": 28087,
"s": 28052,
"text": "Open the terminal and get started."
},
{
"code": null,
"e": 28097,
"s": 28087,
"text": "whoami\nls"
},
{
"code": null,
"e": 28189,
"s": 28097,
"text": "One can even see Live Threat Maps by simply right-clicking and selecting cyber threat maps."
},
{
"code": null,
"e": 28227,
"s": 28189,
"text": "Live Cyber Threat Map is given below:"
},
{
"code": null,
"e": 28286,
"s": 28227,
"text": "It also has VirtualBox, VMware pre-installed, cool right!!"
},
{
"code": null,
"e": 28483,
"s": 28286,
"text": "Also, there are tons of OSINT tools pre-installed on CSI Linux which can be accessed by either right-clicking and selecting it from the menu or click on the bottom left green icon of applications."
},
{
"code": null,
"e": 28608,
"s": 28483,
"text": "One can know its IP address and Tor IP address by simply clicking on the ‘question mark icon’ given on the top right corner."
},
{
"code": null,
"e": 28929,
"s": 28608,
"text": "In conclusion, CSI Linux is literally a gold mine for cyber enthusiasts as it is a one-stop shopping place where one can get literally anything and also a tool pre-installed. One can perform OSINT, browse websites, or share files safely using onion share. Go ahead, explore it yourself and see what else it has to offer."
},
{
"code": null,
"e": 28944,
"s": 28929,
"text": "how-to-install"
},
{
"code": null,
"e": 28951,
"s": 28944,
"text": "How To"
},
{
"code": null,
"e": 28970,
"s": 28951,
"text": "Installation Guide"
},
{
"code": null,
"e": 28981,
"s": 28970,
"text": "Linux-Unix"
},
{
"code": null,
"e": 29079,
"s": 28981,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29113,
"s": 29079,
"text": "How to Install FFmpeg on Windows?"
},
{
"code": null,
"e": 29171,
"s": 29113,
"text": "How to Add External JAR File to an IntelliJ IDEA Project?"
},
{
"code": null,
"e": 29220,
"s": 29171,
"text": "How to Set Git Username and Password in GitBash?"
},
{
"code": null,
"e": 29267,
"s": 29220,
"text": "How to create a nested RecyclerView in Android"
},
{
"code": null,
"e": 29309,
"s": 29267,
"text": "How to Install Jupyter Notebook on MacOS?"
},
{
"code": null,
"e": 29342,
"s": 29309,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 29376,
"s": 29342,
"text": "How to Install FFmpeg on Windows?"
},
{
"code": null,
"e": 29411,
"s": 29376,
"text": "How to Install Pygame on Windows ?"
},
{
"code": null,
"e": 29469,
"s": 29411,
"text": "How to Add External JAR File to an IntelliJ IDEA Project?"
}
] |
Parse and balance angle brackets problem in JavaScript | We are given a string of angle brackets, and we are required to write a function that add brackets at the beginning and end of the string to make all brackets match.
The angle brackets match if for every < there is a corresponding > and for every > there is a corresponding <.
For example − If the input string is −
const str = '><<><';
Then the output should be −
const output = '<><<><>>';
Here, we added, '<' at the beginning and '>>' at the end to balance the string.
We will use a number that will keep count of the number of open '<' tags so far. And then, when we encounter a '>' tag, if there are no current open tags, we will add '<' to the beginning of the string (while keeping the open tag count at 0).
Then, at the end, add a number of '>'s matching the number of currently open tags.
The code for this will be −
const str = '><<><';
const buildPair = (str = '') => {
let count = 0;
let extras = 0;
for (const char of str) {
if (char === '>') {
if (count === 0) {
extras++;
} else {
count−−;
};
} else {
count++;
};
};
const leadingTags = '<'.repeat(extras);
const trailingTags = '>'.repeat(count);
return leadingTags + str + trailingTags;
};
console.log(buildPair(str));
And the output in the console will be −
><<><>> | [
{
"code": null,
"e": 1228,
"s": 1062,
"text": "We are given a string of angle brackets, and we are required to write a function that add brackets at the beginning and end of the string to make all brackets match."
},
{
"code": null,
"e": 1339,
"s": 1228,
"text": "The angle brackets match if for every < there is a corresponding > and for every > there is a corresponding <."
},
{
"code": null,
"e": 1378,
"s": 1339,
"text": "For example − If the input string is −"
},
{
"code": null,
"e": 1399,
"s": 1378,
"text": "const str = '><<><';"
},
{
"code": null,
"e": 1427,
"s": 1399,
"text": "Then the output should be −"
},
{
"code": null,
"e": 1454,
"s": 1427,
"text": "const output = '<><<><>>';"
},
{
"code": null,
"e": 1534,
"s": 1454,
"text": "Here, we added, '<' at the beginning and '>>' at the end to balance the string."
},
{
"code": null,
"e": 1777,
"s": 1534,
"text": "We will use a number that will keep count of the number of open '<' tags so far. And then, when we encounter a '>' tag, if there are no current open tags, we will add '<' to the beginning of the string (while keeping the open tag count at 0)."
},
{
"code": null,
"e": 1860,
"s": 1777,
"text": "Then, at the end, add a number of '>'s matching the number of currently open tags."
},
{
"code": null,
"e": 1888,
"s": 1860,
"text": "The code for this will be −"
},
{
"code": null,
"e": 2346,
"s": 1888,
"text": "const str = '><<><';\nconst buildPair = (str = '') => {\n let count = 0;\n let extras = 0;\n for (const char of str) {\n if (char === '>') {\n if (count === 0) {\n extras++;\n } else {\n count−−;\n };\n } else {\n count++;\n };\n };\n const leadingTags = '<'.repeat(extras);\n const trailingTags = '>'.repeat(count);\n return leadingTags + str + trailingTags;\n};\nconsole.log(buildPair(str));"
},
{
"code": null,
"e": 2386,
"s": 2346,
"text": "And the output in the console will be −"
},
{
"code": null,
"e": 2394,
"s": 2386,
"text": "><<><>>"
}
] |
2 Keys Keyboard Problem - GeeksforGeeks | 09 Jul, 2021
Given a positive integer N and a string S initially it is “A”, the task is to minimize the number of operations required to form a string consisting of N numbers of A’s by performing one of the following operations in each step:
Copy all the characters present in the string S.
Append all the characters to the string S which are copied last time.
Examples:
Input: N = 3Output: 3Explanation:Below are the operations performed:Operation 1: Copy the initial string S once i.e., “A”.Operation 2: Appending the copied string i.e., “A”, to the string S modifies the string S to “AA”.Operation 3: Appending the copied string i.e., “A”, to the string S modifies the string S to “AAA”.Therefore, the minimum number of operations required to get 3 A’s is 3.
Input: N = 7Output: 7
Approach: The given problem can be solved based on the following observations:
If N = P1*P2*Pm where {P1, P2, ..., Pm} are the prime numbers then one can perform the following moves:First, copy the string and then paste it (P1 – 1) times.Similarly, again copying the string and pasting it for (P2 – 1) times.Performing M times with the remaining prime number, one will get the string with N number of A’s.Therefore, the total number of minimum moves needed is given by (P1 + P2 + ... + Pm).
If N = P1*P2*Pm where {P1, P2, ..., Pm} are the prime numbers then one can perform the following moves:First, copy the string and then paste it (P1 – 1) times.Similarly, again copying the string and pasting it for (P2 – 1) times.Performing M times with the remaining prime number, one will get the string with N number of A’s.
First, copy the string and then paste it (P1 – 1) times.Similarly, again copying the string and pasting it for (P2 – 1) times.Performing M times with the remaining prime number, one will get the string with N number of A’s.
First, copy the string and then paste it (P1 – 1) times.
Similarly, again copying the string and pasting it for (P2 – 1) times.
Performing M times with the remaining prime number, one will get the string with N number of A’s.
Therefore, the total number of minimum moves needed is given by (P1 + P2 + ... + Pm).
Follow the steps below to solve the problem:
Initialize a variable, say ans as 0, that stores the resultant number of operations.
Find the prime factors and its power of the given integer N.
Now, iterate through all the prime factors of N and increment the value of ans by the product of the prime factor and its power.
Finally, after completing the above steps, print the value of ans as the resultant minimum number of moves.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find the minimum number// of steps required to form N number// of A'sint minSteps(int N){ // Stores the count of steps needed int ans = 0; // Traverse over the range [2, N] for (int d = 2; d * d <= N; d++) { // Iterate while N is divisible // by d while (N % d == 0) { // Increment the value of // ans by d ans += d; // Divide N by d N /= d; } } // If N is not 1 if (N != 1) { ans += N; } // Return the ans return ans;} // Driver Codeint main(){ int N = 3; cout << minSteps(N); return 0;}
// Java Program for the above approachimport java.io.*; class GFG{ // Function to find the minimum number // of steps required to form N number // of A's static int minSteps(int N) { // Stores the count of steps needed int ans = 0; // Traverse over the range [2, N] for (int d = 2; d * d <= N; d++) { // Iterate while N is divisible // by d while (N % d == 0) { // Increment the value of // ans by d ans += d; // Divide N by d N /= d; } } // If N is not 1 if (N != 1) { ans += N; } // Return the ans return ans; } // Driver Code public static void main(String[] args) { int N = 3; minSteps(N); System.out.println(minSteps(N)); }} // This code is contributed by lokesh potta.
# Python3 program for the above approach# Function to find the minimum number# of steps required to form N number# of A'sdef minSteps( N): # Stores the count of steps needed ans = 0 # Traverse over the range [2, N] d = 2 while(d * d <= N): # Iterate while N is divisible # by d while (N % d == 0): # Increment the value of # ans by d ans += d # Divide N by d N /= d d += 1 # If N is not 1 if (N != 1): ans += N # Return the ans return ans # Driver CodeN = 3print(minSteps(N)) # This code is contributed by shivanisinghss2110
// C# program for the above approachusing System; class GFG{ // Function to find the minimum number// of steps required to form N number// of A'sstatic int minSteps(int N){ // Stores the count of steps needed int ans = 0; // Traverse over the range [2, N] for (int d = 2; d * d <= N; d++) { // Iterate while N is divisible // by d while (N % d == 0) { // Increment the value of // ans by d ans += d; // Divide N by d N /= d; } } // If N is not 1 if (N != 1) { ans += N; } // Return the ans return ans;} // Driver Codestatic public void Main (){ int N = 3; Console.Write(minSteps(N));}} // This code is contributed by sanjoy_62.
<script> // JavaScript Program for the above approach// Function to find the minimum number // of steps required to form N number // of A's function minSteps(N) { // Stores the count of steps needed var ans = 0; // Traverse over the range [2, N] for (var d = 2; d * d <= N; d++) { // Iterate while N is divisible // by d while (N % d == 0) { // Increment the value of // ans by d ans += d; // Divide N by d N /= d; } } // If N is not 1 if (N != 1) { ans += N; } // Return the ans return ans; } // Driver Code var N = 3; minSteps(N); document.write(minSteps(N)); // This code is contributed by shivanisinghss2110 </script>
3
Time Complexity: O(√N)Auxiliary Space: O(1)
sanjoy_62
lokeshpotta20
shivanisinghss2110
Prime Number
prime-factor
Combinatorial
Mathematical
Mathematical
Prime Number
Combinatorial
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Largest number by rearranging digits of a given positive or negative number
Combinations with repetitions
Ways to sum to N using Natural Numbers up to K with repetitions allowed
Given number of matches played, find number of teams in tournament
Generate all possible combinations of at most X characters from a given array
Program for Fibonacci numbers
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7
Modulo Operator (%) in C/C++ with Examples | [
{
"code": null,
"e": 25396,
"s": 25368,
"text": "\n09 Jul, 2021"
},
{
"code": null,
"e": 25625,
"s": 25396,
"text": "Given a positive integer N and a string S initially it is “A”, the task is to minimize the number of operations required to form a string consisting of N numbers of A’s by performing one of the following operations in each step:"
},
{
"code": null,
"e": 25674,
"s": 25625,
"text": "Copy all the characters present in the string S."
},
{
"code": null,
"e": 25744,
"s": 25674,
"text": "Append all the characters to the string S which are copied last time."
},
{
"code": null,
"e": 25754,
"s": 25744,
"text": "Examples:"
},
{
"code": null,
"e": 26145,
"s": 25754,
"text": "Input: N = 3Output: 3Explanation:Below are the operations performed:Operation 1: Copy the initial string S once i.e., “A”.Operation 2: Appending the copied string i.e., “A”, to the string S modifies the string S to “AA”.Operation 3: Appending the copied string i.e., “A”, to the string S modifies the string S to “AAA”.Therefore, the minimum number of operations required to get 3 A’s is 3."
},
{
"code": null,
"e": 26167,
"s": 26145,
"text": "Input: N = 7Output: 7"
},
{
"code": null,
"e": 26247,
"s": 26167,
"text": "Approach: The given problem can be solved based on the following observations: "
},
{
"code": null,
"e": 26659,
"s": 26247,
"text": "If N = P1*P2*Pm where {P1, P2, ..., Pm} are the prime numbers then one can perform the following moves:First, copy the string and then paste it (P1 – 1) times.Similarly, again copying the string and pasting it for (P2 – 1) times.Performing M times with the remaining prime number, one will get the string with N number of A’s.Therefore, the total number of minimum moves needed is given by (P1 + P2 + ... + Pm)."
},
{
"code": null,
"e": 26986,
"s": 26659,
"text": "If N = P1*P2*Pm where {P1, P2, ..., Pm} are the prime numbers then one can perform the following moves:First, copy the string and then paste it (P1 – 1) times.Similarly, again copying the string and pasting it for (P2 – 1) times.Performing M times with the remaining prime number, one will get the string with N number of A’s."
},
{
"code": null,
"e": 27210,
"s": 26986,
"text": "First, copy the string and then paste it (P1 – 1) times.Similarly, again copying the string and pasting it for (P2 – 1) times.Performing M times with the remaining prime number, one will get the string with N number of A’s."
},
{
"code": null,
"e": 27267,
"s": 27210,
"text": "First, copy the string and then paste it (P1 – 1) times."
},
{
"code": null,
"e": 27338,
"s": 27267,
"text": "Similarly, again copying the string and pasting it for (P2 – 1) times."
},
{
"code": null,
"e": 27436,
"s": 27338,
"text": "Performing M times with the remaining prime number, one will get the string with N number of A’s."
},
{
"code": null,
"e": 27522,
"s": 27436,
"text": "Therefore, the total number of minimum moves needed is given by (P1 + P2 + ... + Pm)."
},
{
"code": null,
"e": 27567,
"s": 27522,
"text": "Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 27652,
"s": 27567,
"text": "Initialize a variable, say ans as 0, that stores the resultant number of operations."
},
{
"code": null,
"e": 27713,
"s": 27652,
"text": "Find the prime factors and its power of the given integer N."
},
{
"code": null,
"e": 27842,
"s": 27713,
"text": "Now, iterate through all the prime factors of N and increment the value of ans by the product of the prime factor and its power."
},
{
"code": null,
"e": 27950,
"s": 27842,
"text": "Finally, after completing the above steps, print the value of ans as the resultant minimum number of moves."
},
{
"code": null,
"e": 28001,
"s": 27950,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 28005,
"s": 28001,
"text": "C++"
},
{
"code": null,
"e": 28010,
"s": 28005,
"text": "Java"
},
{
"code": null,
"e": 28018,
"s": 28010,
"text": "Python3"
},
{
"code": null,
"e": 28021,
"s": 28018,
"text": "C#"
},
{
"code": null,
"e": 28032,
"s": 28021,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find the minimum number// of steps required to form N number// of A'sint minSteps(int N){ // Stores the count of steps needed int ans = 0; // Traverse over the range [2, N] for (int d = 2; d * d <= N; d++) { // Iterate while N is divisible // by d while (N % d == 0) { // Increment the value of // ans by d ans += d; // Divide N by d N /= d; } } // If N is not 1 if (N != 1) { ans += N; } // Return the ans return ans;} // Driver Codeint main(){ int N = 3; cout << minSteps(N); return 0;}",
"e": 28755,
"s": 28032,
"text": null
},
{
"code": "// Java Program for the above approachimport java.io.*; class GFG{ // Function to find the minimum number // of steps required to form N number // of A's static int minSteps(int N) { // Stores the count of steps needed int ans = 0; // Traverse over the range [2, N] for (int d = 2; d * d <= N; d++) { // Iterate while N is divisible // by d while (N % d == 0) { // Increment the value of // ans by d ans += d; // Divide N by d N /= d; } } // If N is not 1 if (N != 1) { ans += N; } // Return the ans return ans; } // Driver Code public static void main(String[] args) { int N = 3; minSteps(N); System.out.println(minSteps(N)); }} // This code is contributed by lokesh potta.",
"e": 29691,
"s": 28755,
"text": null
},
{
"code": "# Python3 program for the above approach# Function to find the minimum number# of steps required to form N number# of A'sdef minSteps( N): # Stores the count of steps needed ans = 0 # Traverse over the range [2, N] d = 2 while(d * d <= N): # Iterate while N is divisible # by d while (N % d == 0): # Increment the value of # ans by d ans += d # Divide N by d N /= d d += 1 # If N is not 1 if (N != 1): ans += N # Return the ans return ans # Driver CodeN = 3print(minSteps(N)) # This code is contributed by shivanisinghss2110 ",
"e": 30351,
"s": 29691,
"text": null
},
{
"code": "// C# program for the above approachusing System; class GFG{ // Function to find the minimum number// of steps required to form N number// of A'sstatic int minSteps(int N){ // Stores the count of steps needed int ans = 0; // Traverse over the range [2, N] for (int d = 2; d * d <= N; d++) { // Iterate while N is divisible // by d while (N % d == 0) { // Increment the value of // ans by d ans += d; // Divide N by d N /= d; } } // If N is not 1 if (N != 1) { ans += N; } // Return the ans return ans;} // Driver Codestatic public void Main (){ int N = 3; Console.Write(minSteps(N));}} // This code is contributed by sanjoy_62.",
"e": 31120,
"s": 30351,
"text": null
},
{
"code": "<script> // JavaScript Program for the above approach// Function to find the minimum number // of steps required to form N number // of A's function minSteps(N) { // Stores the count of steps needed var ans = 0; // Traverse over the range [2, N] for (var d = 2; d * d <= N; d++) { // Iterate while N is divisible // by d while (N % d == 0) { // Increment the value of // ans by d ans += d; // Divide N by d N /= d; } } // If N is not 1 if (N != 1) { ans += N; } // Return the ans return ans; } // Driver Code var N = 3; minSteps(N); document.write(minSteps(N)); // This code is contributed by shivanisinghss2110 </script>",
"e": 31990,
"s": 31120,
"text": null
},
{
"code": null,
"e": 31992,
"s": 31990,
"text": "3"
},
{
"code": null,
"e": 32036,
"s": 31992,
"text": "Time Complexity: O(√N)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 32046,
"s": 32036,
"text": "sanjoy_62"
},
{
"code": null,
"e": 32060,
"s": 32046,
"text": "lokeshpotta20"
},
{
"code": null,
"e": 32079,
"s": 32060,
"text": "shivanisinghss2110"
},
{
"code": null,
"e": 32092,
"s": 32079,
"text": "Prime Number"
},
{
"code": null,
"e": 32105,
"s": 32092,
"text": "prime-factor"
},
{
"code": null,
"e": 32119,
"s": 32105,
"text": "Combinatorial"
},
{
"code": null,
"e": 32132,
"s": 32119,
"text": "Mathematical"
},
{
"code": null,
"e": 32145,
"s": 32132,
"text": "Mathematical"
},
{
"code": null,
"e": 32158,
"s": 32145,
"text": "Prime Number"
},
{
"code": null,
"e": 32172,
"s": 32158,
"text": "Combinatorial"
},
{
"code": null,
"e": 32270,
"s": 32172,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32279,
"s": 32270,
"text": "Comments"
},
{
"code": null,
"e": 32292,
"s": 32279,
"text": "Old Comments"
},
{
"code": null,
"e": 32368,
"s": 32292,
"text": "Largest number by rearranging digits of a given positive or negative number"
},
{
"code": null,
"e": 32398,
"s": 32368,
"text": "Combinations with repetitions"
},
{
"code": null,
"e": 32470,
"s": 32398,
"text": "Ways to sum to N using Natural Numbers up to K with repetitions allowed"
},
{
"code": null,
"e": 32537,
"s": 32470,
"text": "Given number of matches played, find number of teams in tournament"
},
{
"code": null,
"e": 32615,
"s": 32537,
"text": "Generate all possible combinations of at most X characters from a given array"
},
{
"code": null,
"e": 32645,
"s": 32615,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 32660,
"s": 32645,
"text": "C++ Data Types"
},
{
"code": null,
"e": 32703,
"s": 32660,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 32722,
"s": 32703,
"text": "Coin Change | DP-7"
}
] |
Convert given Matrix into sorted Spiral Matrix - GeeksforGeeks | 24 Nov, 2021
Given a matrix, the task is to convert the given Matrix into sorted Spiral Matrix.Examples:
Input: y[][] = {
{ 2, 5, 12 },
{ 22, 54, 55 },
{ 1, 6, 8 }
};
Output:
1 2 5
45 55 6
22 12 8
Input: y[][] = {
{ 2, 5, 12 },
{ 22, 45, 55 },
{ 1, 6, 8 },
{ 13, 56, 10 }
};
Output:
1 2 5
45 55 6
22 56 8
13 12 10
Approach:
Convert the given 2D array into a 1D array.
Sort the 1D array
Convert 1D to Spiral matrix
This can be solved by 4 for loops which store all the elements. Every for loop defines a single direction movement along with the matrix. The first for loop represents the movement from left to right, whereas the second crawl represents the movement from top to bottom, the third represents the movement from the right to left, and the fourth represents the movement from bottom to up.
Below is the implementation of the above approach:
C++
Java
Python 3
C#
Javascript
// C++ program to Convert given Matrix// into sorted Spiral Matrix#include <bits/stdc++.h>using namespace std; const int MAX = 1000; // Function to convert the array to Spiralvoid ToSpiral(int m, int n, int Sorted[], int a[MAX][MAX]){ // For Array pointer int index = 0; // k - starting row index // m - ending row index // l - starting column index // n - ending column index int k = 0, l = 0; while (k < m && l < n) { // Print the first row // from the remaining rows for (int i = l; i < n; ++i) { a[k][i] = Sorted[index]; index++; } k++; // Print the last column // from the remaining columns for (int i = k; i < m; ++i) { a[i][n - 1] = Sorted[index]; index++; } n--; // Print the last row // from the remaining rows if (k < m) { for (int i = n - 1; i >= l; --i) { a[m - 1][i] = Sorted[index]; index++; } m--; } // Print the first column // from the remaining columns if (l < n) { for (int i = m - 1; i >= k; --i) { a[i][l] = Sorted[index]; index++; } l++; } }} // Function to convert 2D array to 1D arrayvoid convert2Dto1D(int y[MAX][MAX], int m, int n,int x[]){ int index = 0; // Store value 2D Matrix To 1D array for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { x[index] = y[i][j]; index++; } }} // Function to print the Matrixvoid PrintMatrix(int a[MAX][MAX], int m, int n){ // Print Spiral Matrix for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { cout << a[i][j] << " "; } cout << endl; }} // Function to Convert given Matrix// into sorted Spiral Matrixvoid convertMatrixToSortedSpiral( int y[MAX][MAX], int m, int n){ int a[MAX][MAX] = {0}; int x[m * n]; convert2Dto1D(y, m, n,x); sort(x, x + n * m); ToSpiral(m, n, x, a); PrintMatrix(a, m, n);} // Driver codeint main(){ int m = 4, n = 3; int y[MAX][MAX] = { { 2, 5, 12 }, { 22, 45, 55 }, { 1, 6, 8 }, { 13, 56, 10 }}; convertMatrixToSortedSpiral(y, m, n); return 0;} // This code is contributed by Arnab Kundu
// Java program to Convert given Matrix// into sorted Spiral Matrix import java.util.*; public class TwistedMatrix { static int MAX = 1000; // Function to convert the array to Spiral static void ToSpiral(int m, int n, int Sorted[], int a[][]) { // For Array pointer int index = 0; // k - starting row index // m - ending row index // l - starting column index // n - ending column index int k = 0, l = 0; while (k < m && l < n) { // Print the first row // from the remaining rows for (int i = l; i < n; ++i) { a[k][i] = Sorted[index]; index++; } k++; // Print the last column // from the remaining columns for (int i = k; i < m; ++i) { a[i][n - 1] = Sorted[index]; index++; } n--; // Print the last row // from the remaining rows if (k < m) { for (int i = n - 1; i >= l; --i) { a[m - 1][i] = Sorted[index]; index++; } m--; } // Print the first column // from the remaining columns if (l < n) { for (int i = m - 1; i >= k; --i) { a[i][l] = Sorted[index]; index++; } l++; } } } // Function to convert 2D array to 1D array public static int[] convert2Dto1D( int y[][], int m, int n) { int index = 0; int x[] = new int[m * n]; // Store value 2D Matrix To 1D array for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { x[index] = y[i][j]; index++; } } return x; } // Function to print the Matrix public static void PrintMatrix( int a[][], int m, int n) { // Print Spiral Matrix for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { System.out.print(a[i][j] + " "); } System.out.println(); } } // Function to sort the array public static int[] SortArray(int x[]) { // Sort array Using InBuilt Function Arrays.sort(x); return x; } // Function to Convert given Matrix // into sorted Spiral Matrix public static void convertMatrixToSortedSpiral( int y[][], int m, int n) { int a[][] = new int[MAX][MAX]; int x[] = new int[m * n]; x = convert2Dto1D(y, m, n); x = SortArray(x); ToSpiral(m, n, x, a); PrintMatrix(a, m, n); } // Driver code public static void main(String[] args) { int m = 4, n = 3; int y[][] = { { 2, 5, 12 }, { 22, 45, 55 }, { 1, 6, 8 }, { 13, 56, 10 } }; convertMatrixToSortedSpiral(y, m, n); }} // This article is contributed by VRUND R PATEL
# Python3 program to Convert given Matrix# into sorted Spiral MatrixMAX = 1000 # Function to convert the array to Spiraldef ToSpiral(m, n, Sorted, a): # For Array pointer index = 0 # k - starting row index # m - ending row index # l - starting column index # n - ending column index k = 0 l = 0 while (k < m and l < n): # Print the first row # from the remaining rows for i in range(l, n, 1): a[k][i] = Sorted[index] index += 1 k += 1 # Print the last column # from the remaining columns for i in range(k, m, 1): a[i][n - 1] = Sorted[index] index += 1 n -= 1 # Print the last row # from the remaining rows if (k < m): i = n - 1 while(i >= l): a[m - 1][i] = Sorted[index] index += 1 i -= 1 m -= 1 # Print the first column # from the remaining columns if (l < n): i = m - 1 while(i >= k): a[i][l] = Sorted[index] index += 1 i -= 1 l += 1 # Function to convert 2D array to 1D arraydef convert2Dto1D(y, m, n): index = 0 x = [0 for i in range(m * n)] # Store value 2D Matrix To 1D array for i in range(m): for j in range(n): x[index] = y[i][j] index += 1 return x # Function to print the Matrixdef PrintMatrix(a, m, n): # Print Spiral Matrix for i in range(m): for j in range(n): print(a[i][j], end =" ") print('\n', end = "") # Function to sort the arraydef SortArray(x): # Sort array Using InBuilt Function x.sort(reverse = False) return x # Function to Convert given Matrix# into sorted Spiral Matrixdef convertMatrixToSortedSpiral(y, m, n): a = [[0 for i in range(MAX)] for j in range(MAX)] x = [0 for i in range(15)] x = convert2Dto1D(y, m, n) x = SortArray(x) ToSpiral(m, n, x, a) PrintMatrix(a, m, n) # Driver codeif __name__ == '__main__': m = 4 n = 3 y = [[2, 5, 12], [22, 45, 55], [1, 6, 8], [13, 56, 10]] convertMatrixToSortedSpiral(y, m, n) # This code is contributed by Surendra_Gangwar
// C# program to Convert given Matrix// into sorted Spiral Matrixusing System; class GFG{ static int MAX = 1000; // Function to convert the array to Spiral static void ToSpiral(int m, int n, int []Sorted, int [,]a) { // For Array pointer int index = 0; // k - starting row index // m - ending row index // l - starting column index // n - ending column index int k = 0, l = 0; while (k < m && l < n) { // Print the first row // from the remaining rows for (int i = l; i < n; ++i) { a[k, i] = Sorted[index]; index++; } k++; // Print the last column // from the remaining columns for (int i = k; i < m; ++i) { a[i, n - 1] = Sorted[index]; index++; } n--; // Print the last row // from the remaining rows if (k < m) { for (int i = n - 1; i >= l; --i) { a[m - 1, i] = Sorted[index]; index++; } m--; } // Print the first column // from the remaining columns if (l < n) { for (int i = m - 1; i >= k; --i) { a[i, l] = Sorted[index]; index++; } l++; } } } // Function to convert 2D array to 1D array public static int[] convert2Dto1D(int [,]y, int m, int n) { int index = 0; int []x = new int[m * n]; // Store value 2D Matrix To 1D array for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { x[index] = y[i, j]; index++; } } return x; } // Function to print the Matrix public static void PrintMatrix(int [,]a, int m, int n) { // Print Spiral Matrix for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { Console.Write(a[i, j] + " "); } Console.WriteLine(); } } // Function to sort the array public static int[] SortArray(int []x) { // Sort array Using InBuilt Function Array.Sort(x); return x; } // Function to Convert given Matrix // into sorted Spiral Matrix public static void convertMatrixToSortedSpiral(int [,]y, int m, int n) { int [,]a = new int[MAX, MAX]; int []x = new int[m * n]; x = convert2Dto1D(y, m, n); x = SortArray(x); ToSpiral(m, n, x, a); PrintMatrix(a, m, n); } // Driver code public static void Main(String[] args) { int m = 4, n = 3; int [,]y = {{ 2, 5, 12 }, { 22, 45, 55 }, { 1, 6, 8 }, { 13, 56, 10 }}; convertMatrixToSortedSpiral(y, m, n); }} // This code is contributed by Rajput-Ji
<script>// Javascript program to Convert given Matrix// into sorted Spiral Matrix let MAX = 1000; // Function to convert the array to Spiralfunction ToSpiral(m,n,Sorted,a){ // For Array pointer let index = 0; // k - starting row index // m - ending row index // l - starting column index // n - ending column index let k = 0, l = 0; while (k < m && l < n) { // Print the first row // from the remaining rows for (let i = l; i < n; ++i) { a[k][i] = Sorted[index]; index++; } k++; // Print the last column // from the remaining columns for (let i = k; i < m; ++i) { a[i][n - 1] = Sorted[index]; index++; } n--; // Print the last row // from the remaining rows if (k < m) { for (let i = n - 1; i >= l; --i) { a[m - 1][i] = Sorted[index]; index++; } m--; } // Print the first column // from the remaining columns if (l < n) { for (let i = m - 1; i >= k; --i) { a[i][l] = Sorted[index]; index++; } l++; } }} // Function to convert 2D array to 1D arrayfunction convert2Dto1D(y,m,n){ let index = 0; let x = new Array(m * n); // Store value 2D Matrix To 1D array for (let i = 0; i < m; i++) { for (let j = 0; j < n; j++) { x[index] = y[i][j]; index++; } } return x;} // Function to print the Matrixfunction PrintMatrix(a,m,n){ // Print Spiral Matrix for (let i = 0; i < m; i++) { for (let j = 0; j < n; j++) { document.write(a[i][j] + " "); } document.write("<br>"); }} // Function to sort the arrayfunction SortArray(x){ // Sort array Using InBuilt Function x.sort(function(a,b){return a-b;}); return x;} // Function to Convert given Matrix // into sorted Spiral Matrixfunction convertMatrixToSortedSpiral(y,m,n){ let a = new Array(MAX); for(let i=0;i<MAX;i++) a[i]=new Array(MAX); let x = new Array(m * n); x = convert2Dto1D(y, m, n); x = SortArray(x); ToSpiral(m, n, x, a); PrintMatrix(a, m, n);} // Driver codelet m = 4, n = 3;let y = [[ 2, 5, 12 ],[ 22, 45, 55 ],[ 1, 6, 8 ],[ 13, 56, 10 ]]; convertMatrixToSortedSpiral(y, m, n); // This code is contributed by avanitrachhadiya2155</script>
1 2 5
45 55 6
22 56 8
13 12 10
Time Complexity: O(m*n)
Auxiliary Space: O(m*n)
Rajput-Ji
SURENDRA_GANGWAR
andrew1234
avanitrachhadiya2155
samim2000
spiral
Matrix
Sorting
Sorting
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Efficiently compute sums of diagonals of a matrix
Flood fill Algorithm - how to implement fill() in paint?
Zigzag (or diagonal) traversal of Matrix
Mathematics | L U Decomposition of a System of Linear Equations
Python program to add two Matrices | [
{
"code": null,
"e": 26251,
"s": 26223,
"text": "\n24 Nov, 2021"
},
{
"code": null,
"e": 26345,
"s": 26251,
"text": "Given a matrix, the task is to convert the given Matrix into sorted Spiral Matrix.Examples: "
},
{
"code": null,
"e": 26694,
"s": 26345,
"text": "Input: y[][] = {\n { 2, 5, 12 },\n { 22, 54, 55 },\n { 1, 6, 8 }\n };\nOutput:\n 1 2 5 \n 45 55 6\n 22 12 8\n\nInput: y[][] = {\n { 2, 5, 12 },\n { 22, 45, 55 },\n { 1, 6, 8 },\n { 13, 56, 10 }\n };\nOutput:\n 1 2 5 \n 45 55 6 \n 22 56 8 \n 13 12 10"
},
{
"code": null,
"e": 26708,
"s": 26696,
"text": "Approach: "
},
{
"code": null,
"e": 26752,
"s": 26708,
"text": "Convert the given 2D array into a 1D array."
},
{
"code": null,
"e": 26770,
"s": 26752,
"text": "Sort the 1D array"
},
{
"code": null,
"e": 26798,
"s": 26770,
"text": "Convert 1D to Spiral matrix"
},
{
"code": null,
"e": 27184,
"s": 26798,
"text": "This can be solved by 4 for loops which store all the elements. Every for loop defines a single direction movement along with the matrix. The first for loop represents the movement from left to right, whereas the second crawl represents the movement from top to bottom, the third represents the movement from the right to left, and the fourth represents the movement from bottom to up."
},
{
"code": null,
"e": 27237,
"s": 27184,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 27241,
"s": 27237,
"text": "C++"
},
{
"code": null,
"e": 27246,
"s": 27241,
"text": "Java"
},
{
"code": null,
"e": 27255,
"s": 27246,
"text": "Python 3"
},
{
"code": null,
"e": 27258,
"s": 27255,
"text": "C#"
},
{
"code": null,
"e": 27269,
"s": 27258,
"text": "Javascript"
},
{
"code": "// C++ program to Convert given Matrix// into sorted Spiral Matrix#include <bits/stdc++.h>using namespace std; const int MAX = 1000; // Function to convert the array to Spiralvoid ToSpiral(int m, int n, int Sorted[], int a[MAX][MAX]){ // For Array pointer int index = 0; // k - starting row index // m - ending row index // l - starting column index // n - ending column index int k = 0, l = 0; while (k < m && l < n) { // Print the first row // from the remaining rows for (int i = l; i < n; ++i) { a[k][i] = Sorted[index]; index++; } k++; // Print the last column // from the remaining columns for (int i = k; i < m; ++i) { a[i][n - 1] = Sorted[index]; index++; } n--; // Print the last row // from the remaining rows if (k < m) { for (int i = n - 1; i >= l; --i) { a[m - 1][i] = Sorted[index]; index++; } m--; } // Print the first column // from the remaining columns if (l < n) { for (int i = m - 1; i >= k; --i) { a[i][l] = Sorted[index]; index++; } l++; } }} // Function to convert 2D array to 1D arrayvoid convert2Dto1D(int y[MAX][MAX], int m, int n,int x[]){ int index = 0; // Store value 2D Matrix To 1D array for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { x[index] = y[i][j]; index++; } }} // Function to print the Matrixvoid PrintMatrix(int a[MAX][MAX], int m, int n){ // Print Spiral Matrix for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { cout << a[i][j] << \" \"; } cout << endl; }} // Function to Convert given Matrix// into sorted Spiral Matrixvoid convertMatrixToSortedSpiral( int y[MAX][MAX], int m, int n){ int a[MAX][MAX] = {0}; int x[m * n]; convert2Dto1D(y, m, n,x); sort(x, x + n * m); ToSpiral(m, n, x, a); PrintMatrix(a, m, n);} // Driver codeint main(){ int m = 4, n = 3; int y[MAX][MAX] = { { 2, 5, 12 }, { 22, 45, 55 }, { 1, 6, 8 }, { 13, 56, 10 }}; convertMatrixToSortedSpiral(y, m, n); return 0;} // This code is contributed by Arnab Kundu",
"e": 29765,
"s": 27269,
"text": null
},
{
"code": "// Java program to Convert given Matrix// into sorted Spiral Matrix import java.util.*; public class TwistedMatrix { static int MAX = 1000; // Function to convert the array to Spiral static void ToSpiral(int m, int n, int Sorted[], int a[][]) { // For Array pointer int index = 0; // k - starting row index // m - ending row index // l - starting column index // n - ending column index int k = 0, l = 0; while (k < m && l < n) { // Print the first row // from the remaining rows for (int i = l; i < n; ++i) { a[k][i] = Sorted[index]; index++; } k++; // Print the last column // from the remaining columns for (int i = k; i < m; ++i) { a[i][n - 1] = Sorted[index]; index++; } n--; // Print the last row // from the remaining rows if (k < m) { for (int i = n - 1; i >= l; --i) { a[m - 1][i] = Sorted[index]; index++; } m--; } // Print the first column // from the remaining columns if (l < n) { for (int i = m - 1; i >= k; --i) { a[i][l] = Sorted[index]; index++; } l++; } } } // Function to convert 2D array to 1D array public static int[] convert2Dto1D( int y[][], int m, int n) { int index = 0; int x[] = new int[m * n]; // Store value 2D Matrix To 1D array for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { x[index] = y[i][j]; index++; } } return x; } // Function to print the Matrix public static void PrintMatrix( int a[][], int m, int n) { // Print Spiral Matrix for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { System.out.print(a[i][j] + \" \"); } System.out.println(); } } // Function to sort the array public static int[] SortArray(int x[]) { // Sort array Using InBuilt Function Arrays.sort(x); return x; } // Function to Convert given Matrix // into sorted Spiral Matrix public static void convertMatrixToSortedSpiral( int y[][], int m, int n) { int a[][] = new int[MAX][MAX]; int x[] = new int[m * n]; x = convert2Dto1D(y, m, n); x = SortArray(x); ToSpiral(m, n, x, a); PrintMatrix(a, m, n); } // Driver code public static void main(String[] args) { int m = 4, n = 3; int y[][] = { { 2, 5, 12 }, { 22, 45, 55 }, { 1, 6, 8 }, { 13, 56, 10 } }; convertMatrixToSortedSpiral(y, m, n); }} // This article is contributed by VRUND R PATEL",
"e": 32858,
"s": 29765,
"text": null
},
{
"code": "# Python3 program to Convert given Matrix# into sorted Spiral MatrixMAX = 1000 # Function to convert the array to Spiraldef ToSpiral(m, n, Sorted, a): # For Array pointer index = 0 # k - starting row index # m - ending row index # l - starting column index # n - ending column index k = 0 l = 0 while (k < m and l < n): # Print the first row # from the remaining rows for i in range(l, n, 1): a[k][i] = Sorted[index] index += 1 k += 1 # Print the last column # from the remaining columns for i in range(k, m, 1): a[i][n - 1] = Sorted[index] index += 1 n -= 1 # Print the last row # from the remaining rows if (k < m): i = n - 1 while(i >= l): a[m - 1][i] = Sorted[index] index += 1 i -= 1 m -= 1 # Print the first column # from the remaining columns if (l < n): i = m - 1 while(i >= k): a[i][l] = Sorted[index] index += 1 i -= 1 l += 1 # Function to convert 2D array to 1D arraydef convert2Dto1D(y, m, n): index = 0 x = [0 for i in range(m * n)] # Store value 2D Matrix To 1D array for i in range(m): for j in range(n): x[index] = y[i][j] index += 1 return x # Function to print the Matrixdef PrintMatrix(a, m, n): # Print Spiral Matrix for i in range(m): for j in range(n): print(a[i][j], end =\" \") print('\\n', end = \"\") # Function to sort the arraydef SortArray(x): # Sort array Using InBuilt Function x.sort(reverse = False) return x # Function to Convert given Matrix# into sorted Spiral Matrixdef convertMatrixToSortedSpiral(y, m, n): a = [[0 for i in range(MAX)] for j in range(MAX)] x = [0 for i in range(15)] x = convert2Dto1D(y, m, n) x = SortArray(x) ToSpiral(m, n, x, a) PrintMatrix(a, m, n) # Driver codeif __name__ == '__main__': m = 4 n = 3 y = [[2, 5, 12], [22, 45, 55], [1, 6, 8], [13, 56, 10]] convertMatrixToSortedSpiral(y, m, n) # This code is contributed by Surendra_Gangwar",
"e": 35186,
"s": 32858,
"text": null
},
{
"code": "// C# program to Convert given Matrix// into sorted Spiral Matrixusing System; class GFG{ static int MAX = 1000; // Function to convert the array to Spiral static void ToSpiral(int m, int n, int []Sorted, int [,]a) { // For Array pointer int index = 0; // k - starting row index // m - ending row index // l - starting column index // n - ending column index int k = 0, l = 0; while (k < m && l < n) { // Print the first row // from the remaining rows for (int i = l; i < n; ++i) { a[k, i] = Sorted[index]; index++; } k++; // Print the last column // from the remaining columns for (int i = k; i < m; ++i) { a[i, n - 1] = Sorted[index]; index++; } n--; // Print the last row // from the remaining rows if (k < m) { for (int i = n - 1; i >= l; --i) { a[m - 1, i] = Sorted[index]; index++; } m--; } // Print the first column // from the remaining columns if (l < n) { for (int i = m - 1; i >= k; --i) { a[i, l] = Sorted[index]; index++; } l++; } } } // Function to convert 2D array to 1D array public static int[] convert2Dto1D(int [,]y, int m, int n) { int index = 0; int []x = new int[m * n]; // Store value 2D Matrix To 1D array for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { x[index] = y[i, j]; index++; } } return x; } // Function to print the Matrix public static void PrintMatrix(int [,]a, int m, int n) { // Print Spiral Matrix for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { Console.Write(a[i, j] + \" \"); } Console.WriteLine(); } } // Function to sort the array public static int[] SortArray(int []x) { // Sort array Using InBuilt Function Array.Sort(x); return x; } // Function to Convert given Matrix // into sorted Spiral Matrix public static void convertMatrixToSortedSpiral(int [,]y, int m, int n) { int [,]a = new int[MAX, MAX]; int []x = new int[m * n]; x = convert2Dto1D(y, m, n); x = SortArray(x); ToSpiral(m, n, x, a); PrintMatrix(a, m, n); } // Driver code public static void Main(String[] args) { int m = 4, n = 3; int [,]y = {{ 2, 5, 12 }, { 22, 45, 55 }, { 1, 6, 8 }, { 13, 56, 10 }}; convertMatrixToSortedSpiral(y, m, n); }} // This code is contributed by Rajput-Ji",
"e": 38449,
"s": 35186,
"text": null
},
{
"code": "<script>// Javascript program to Convert given Matrix// into sorted Spiral Matrix let MAX = 1000; // Function to convert the array to Spiralfunction ToSpiral(m,n,Sorted,a){ // For Array pointer let index = 0; // k - starting row index // m - ending row index // l - starting column index // n - ending column index let k = 0, l = 0; while (k < m && l < n) { // Print the first row // from the remaining rows for (let i = l; i < n; ++i) { a[k][i] = Sorted[index]; index++; } k++; // Print the last column // from the remaining columns for (let i = k; i < m; ++i) { a[i][n - 1] = Sorted[index]; index++; } n--; // Print the last row // from the remaining rows if (k < m) { for (let i = n - 1; i >= l; --i) { a[m - 1][i] = Sorted[index]; index++; } m--; } // Print the first column // from the remaining columns if (l < n) { for (let i = m - 1; i >= k; --i) { a[i][l] = Sorted[index]; index++; } l++; } }} // Function to convert 2D array to 1D arrayfunction convert2Dto1D(y,m,n){ let index = 0; let x = new Array(m * n); // Store value 2D Matrix To 1D array for (let i = 0; i < m; i++) { for (let j = 0; j < n; j++) { x[index] = y[i][j]; index++; } } return x;} // Function to print the Matrixfunction PrintMatrix(a,m,n){ // Print Spiral Matrix for (let i = 0; i < m; i++) { for (let j = 0; j < n; j++) { document.write(a[i][j] + \" \"); } document.write(\"<br>\"); }} // Function to sort the arrayfunction SortArray(x){ // Sort array Using InBuilt Function x.sort(function(a,b){return a-b;}); return x;} // Function to Convert given Matrix // into sorted Spiral Matrixfunction convertMatrixToSortedSpiral(y,m,n){ let a = new Array(MAX); for(let i=0;i<MAX;i++) a[i]=new Array(MAX); let x = new Array(m * n); x = convert2Dto1D(y, m, n); x = SortArray(x); ToSpiral(m, n, x, a); PrintMatrix(a, m, n);} // Driver codelet m = 4, n = 3;let y = [[ 2, 5, 12 ],[ 22, 45, 55 ],[ 1, 6, 8 ],[ 13, 56, 10 ]]; convertMatrixToSortedSpiral(y, m, n); // This code is contributed by avanitrachhadiya2155</script>",
"e": 41180,
"s": 38449,
"text": null
},
{
"code": null,
"e": 41214,
"s": 41180,
"text": "1 2 5 \n45 55 6 \n22 56 8 \n13 12 10"
},
{
"code": null,
"e": 41240,
"s": 41216,
"text": "Time Complexity: O(m*n)"
},
{
"code": null,
"e": 41264,
"s": 41240,
"text": "Auxiliary Space: O(m*n)"
},
{
"code": null,
"e": 41274,
"s": 41264,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 41291,
"s": 41274,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 41302,
"s": 41291,
"text": "andrew1234"
},
{
"code": null,
"e": 41323,
"s": 41302,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 41333,
"s": 41323,
"text": "samim2000"
},
{
"code": null,
"e": 41340,
"s": 41333,
"text": "spiral"
},
{
"code": null,
"e": 41347,
"s": 41340,
"text": "Matrix"
},
{
"code": null,
"e": 41355,
"s": 41347,
"text": "Sorting"
},
{
"code": null,
"e": 41363,
"s": 41355,
"text": "Sorting"
},
{
"code": null,
"e": 41370,
"s": 41363,
"text": "Matrix"
},
{
"code": null,
"e": 41468,
"s": 41370,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 41518,
"s": 41468,
"text": "Efficiently compute sums of diagonals of a matrix"
},
{
"code": null,
"e": 41575,
"s": 41518,
"text": "Flood fill Algorithm - how to implement fill() in paint?"
},
{
"code": null,
"e": 41616,
"s": 41575,
"text": "Zigzag (or diagonal) traversal of Matrix"
},
{
"code": null,
"e": 41680,
"s": 41616,
"text": "Mathematics | L U Decomposition of a System of Linear Equations"
}
] |
Plotly - Histogram | Introduced by Karl Pearson, a histogram is an accurate representation of the distribution of numerical data which is an estimate of the probability distribution of a continuous variable (CORAL). It appears similar to bar graph, but, a bar graph relates two variables, whereas a histogram relates only one.
A histogram requires bin (or bucket) which divides the entire range of values into a series of intervals—and then count how many values fall into each interval. The bins are usually specified as consecutive, non-overlapping intervals of a variable. The bins must be adjacent, and are often of equal size. A rectangle is erected over the bin with height proportional to the frequency—the number of cases in each bin.
Histogram trace object is returned by go.Histogram() function. Its customization is done by various arguments or attributes. One essential argument is x or y set to a list, numpy array or Pandas dataframe object which is to be distributed in bins.
By default, Plotly distributes the data points in automatically sized bins. However, you can define custom bin size. For that you need to set autobins to false, specify nbins (number of bins), its start and end values and size.
Following code generates a simple histogram showing distribution of marks of students in a class inbins (sized automatically) −
import numpy as np
x1 = np.array([22,87,5,43,56,73,55,54,11,20,51,5,79,31,27])
data = [go.Histogram(x = x1)]
fig = go.Figure(data)
iplot(fig)
The output is as shown below −
The go.Histogram() function accepts histnorm, which specifies the type of normalization used for this histogram trace. Default is "", the span of each bar corresponds to the number of occurrences (i.e. the number of data points lying inside the bins). If assigned "percent" / "probability", the span of each bar corresponds to the percentage / fraction of occurrences with respect to the total number of sample points. If it is equal to "density", the span of each bar corresponds to the number of occurrences in a bin divided by the size of the bin interval.
There is also histfunc parameter whose default value is count. As a result, height of rectangle over a bin corresponds to count of data points. It can be set to sum, avg, min or max.
The histogram() function can be set to display cumulative distribution of values in successive bins. For that, you need to set cumulative property to enabled. Result can be seen as below −
data=[go.Histogram(x = x1, cumulative_enabled = True)]
fig = go.Figure(data)
iplot(fig)
The output is as mentioned below −
12 Lectures
53 mins
Pranjal Srivastava
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2666,
"s": 2360,
"text": "Introduced by Karl Pearson, a histogram is an accurate representation of the distribution of numerical data which is an estimate of the probability distribution of a continuous variable (CORAL). It appears similar to bar graph, but, a bar graph relates two variables, whereas a histogram relates only one."
},
{
"code": null,
"e": 3082,
"s": 2666,
"text": "A histogram requires bin (or bucket) which divides the entire range of values into a series of intervals—and then count how many values fall into each interval. The bins are usually specified as consecutive, non-overlapping intervals of a variable. The bins must be adjacent, and are often of equal size. A rectangle is erected over the bin with height proportional to the frequency—the number of cases in each bin."
},
{
"code": null,
"e": 3330,
"s": 3082,
"text": "Histogram trace object is returned by go.Histogram() function. Its customization is done by various arguments or attributes. One essential argument is x or y set to a list, numpy array or Pandas dataframe object which is to be distributed in bins."
},
{
"code": null,
"e": 3558,
"s": 3330,
"text": "By default, Plotly distributes the data points in automatically sized bins. However, you can define custom bin size. For that you need to set autobins to false, specify nbins (number of bins), its start and end values and size."
},
{
"code": null,
"e": 3686,
"s": 3558,
"text": "Following code generates a simple histogram showing distribution of marks of students in a class inbins (sized automatically) −"
},
{
"code": null,
"e": 3828,
"s": 3686,
"text": "import numpy as np\nx1 = np.array([22,87,5,43,56,73,55,54,11,20,51,5,79,31,27])\ndata = [go.Histogram(x = x1)]\nfig = go.Figure(data)\niplot(fig)"
},
{
"code": null,
"e": 3859,
"s": 3828,
"text": "The output is as shown below −"
},
{
"code": null,
"e": 4419,
"s": 3859,
"text": "The go.Histogram() function accepts histnorm, which specifies the type of normalization used for this histogram trace. Default is \"\", the span of each bar corresponds to the number of occurrences (i.e. the number of data points lying inside the bins). If assigned \"percent\" / \"probability\", the span of each bar corresponds to the percentage / fraction of occurrences with respect to the total number of sample points. If it is equal to \"density\", the span of each bar corresponds to the number of occurrences in a bin divided by the size of the bin interval."
},
{
"code": null,
"e": 4602,
"s": 4419,
"text": "There is also histfunc parameter whose default value is count. As a result, height of rectangle over a bin corresponds to count of data points. It can be set to sum, avg, min or max."
},
{
"code": null,
"e": 4791,
"s": 4602,
"text": "The histogram() function can be set to display cumulative distribution of values in successive bins. For that, you need to set cumulative property to enabled. Result can be seen as below −"
},
{
"code": null,
"e": 4879,
"s": 4791,
"text": "data=[go.Histogram(x = x1, cumulative_enabled = True)]\nfig = go.Figure(data)\niplot(fig)"
},
{
"code": null,
"e": 4914,
"s": 4879,
"text": "The output is as mentioned below −"
},
{
"code": null,
"e": 4946,
"s": 4914,
"text": "\n 12 Lectures \n 53 mins\n"
},
{
"code": null,
"e": 4966,
"s": 4946,
"text": " Pranjal Srivastava"
},
{
"code": null,
"e": 4973,
"s": 4966,
"text": " Print"
},
{
"code": null,
"e": 4984,
"s": 4973,
"text": " Add Notes"
}
] |
Largest number less than or equal to N in BST (Iterative Approach) - GeeksforGeeks | 09 Aug, 2021
We have a binary search tree and a number N. Our task is to find the greatest number in the binary search tree that is less than or equal to N. Print the value of the element if it exists otherwise print -1.
Examples: For the above given binary search tree-
Input : N = 24
Output :result = 21
(searching for 24 will be like-5->12->21)
Input : N = 4
Output : result = 3
(searching for 4 will be like-5->2->3)
We have discussed recursive approach in below post. Largest number in BST which is less than or equal to NHere an iterative approach is discussed. We try to find the predecessor of the target. Keep two pointers, one pointing to the current node and one for storing the answer. If the current node’s data > N, we move towards left. In other case, when current node’s data is less than N, the current node can be our answer (so far), and we move towards right.
C++
Java
Python3
C#
Javascript
// C++ code to find the largest value smaller// than or equal to N#include <bits/stdc++.h>using namespace std; struct Node { int key; Node *left, *right;}; // To create new BST NodeNode* newNode(int item){ Node* temp = new Node; temp->key = item; temp->left = temp->right = NULL; return temp;} // To insert a new node in BSTNode* insert(Node* node, int key){ // if tree is empty return new node if (node == NULL) return newNode(key); // if key is less then or greater then // node value then recur down the tree if (key < node->key) node->left = insert(node->left, key); else if (key > node->key) node->right = insert(node->right, key); // return the (unchanged) node pointer return node;} // Returns largest value smaller than or equal to// key. If key is smaller than the smallest, it// returns -1.int findFloor(Node* root, int key){ Node *curr = root, *ans = NULL; while (curr) { if (curr->key <= key) { ans = curr; curr = curr->right; } else curr = curr->left; } if (ans) return ans->key; return -1;} // Driver codeint main(){ int N = 25; Node* root = insert(root, 19); insert(root, 2); insert(root, 1); insert(root, 3); insert(root, 12); insert(root, 9); insert(root, 21); insert(root, 19); insert(root, 25); printf("%d", findFloor(root, N)); return 0;}
// Java code to find the largest value smaller// than or equal to Nclass GFG{ static class Node{ int key; Node left, right;}; // To create new BST Nodestatic Node newNode(int item){ Node temp = new Node(); temp.key = item; temp.left = temp.right = null; return temp;} // To insert a new node in BSTstatic Node insert(Node node, int key){ // if tree is empty return new node if (node == null) return newNode(key); // if key is less then or greater then // node value then recur down the tree if (key < node.key) node.left = insert(node.left, key); else if (key > node.key) node.right = insert(node.right, key); // return the (unchanged) node pointer return node;} // Returns largest value smaller than or equal to// key. If key is smaller than the smallest, it// returns -1.static int findFloor(Node root, int key){ Node curr = root, ans = null; while (curr != null) { if (curr.key <= key) { ans = curr; curr = curr.right; } else curr = curr.left; } if (ans != null) return ans.key; return -1;} // Driver codepublic static void main(String[] args){ int N = 25; Node root = new Node(); insert(root, 19); insert(root, 2); insert(root, 1); insert(root, 3); insert(root, 12); insert(root, 9); insert(root, 21); insert(root, 19); insert(root, 25); System.out.printf("%d", findFloor(root, N));}} /* This code is contributed by PrinciRaj1992 */
# Python3 code to find the largest value# smaller than or equal to N class newNode: def __init__(self, item): self.key = item self.left = None self.right = None # To insert a new node in BSTdef insert(node, key): # If tree is empty return new node if (node == None): return newNode(key) # If key is less then or greater then # node value then recur down the tree if (key < node.key): node.left = insert(node.left, key) elif (key > node.key): node.right = insert(node.right, key) # Return the (unchanged) node pointer return node # Returns largest value smaller than or# equal to key. If key is smaller than# the smallest, it returns -1.def findFloor(root, key): curr = root ans = None while (curr): if (curr.key <= key): ans = curr curr = curr.right else: curr = curr.left if (ans): return ans.key return -1 # Driver codeif __name__ == '__main__': N = 25 root = None root = insert(root, 19) insert(root, 2) insert(root, 1) insert(root, 3) insert(root, 12) insert(root, 9) insert(root, 21) insert(root, 19) insert(root, 25) print(findFloor(root, N)) # This code is contributed by bgangwar59
// C# code to find the largest value smaller// than or equal to Nusing System;using System.Collections.Generic; class GFG{ public class Node{ public int key; public Node left, right;}; // To create new BST Nodestatic Node newNode(int item){ Node temp = new Node(); temp.key = item; temp.left = temp.right = null; return temp;} // To insert a new node in BSTstatic Node insert(Node node, int key){ // if tree is empty return new node if (node == null) return newNode(key); // if key is less then or greater then // node value then recur down the tree if (key < node.key) node.left = insert(node.left, key); else if (key > node.key) node.right = insert(node.right, key); // return the (unchanged) node pointer return node;} // Returns largest value smaller than or equal to// key. If key is smaller than the smallest, it// returns -1.static int findFloor(Node root, int key){ Node curr = root, ans = null; while (curr != null) { if (curr.key <= key) { ans = curr; curr = curr.right; } else curr = curr.left; } if (ans != null) return ans.key; return -1;} // Driver codepublic static void Main(String[] args){ int N = 25; Node root = new Node(); insert(root, 19); insert(root, 2); insert(root, 1); insert(root, 3); insert(root, 12); insert(root, 9); insert(root, 21); insert(root, 19); insert(root, 25); Console.Write("{0}", findFloor(root, N));}} // This code is contributed by Rajput-Ji
<script> // Javascript code to find the largest// value smaller than or equal to Nclass Node{ constructor(item) { this.key = item; this.left = null; this.right = null; }} // To create new BST Nodefunction newNode(item){ let temp = new Node(item); return temp;} // To insert a new node in BSTfunction insert(node, key){ // If tree is empty return new node if (node == null) return newNode(key); // If key is less then or greater then // node value then recur down the tree if (key < node.key) node.left = insert(node.left, key); else if (key > node.key) node.right = insert(node.right, key); // Return the (unchanged) node pointer return node;} // Returns largest value smaller than or// equal to key. If key is smaller than// the smallest, it returns -1.function findFloor(root, key){ let curr = root, ans = null; while (curr != null) { if (curr.key <= key) { ans = curr; curr = curr.right; } else curr = curr.left; } if (ans != null) return ans.key; return -1;} // Driver codelet N = 25; let root = new Node(N);insert(root, 19);insert(root, 2);insert(root, 1);insert(root, 3);insert(root, 12);insert(root, 9);insert(root, 21);insert(root, 19);insert(root, 25); document.write(findFloor(root, N)); // This code is contributed by divyeshrabadiya07 </script>
Output:
25
YouTubeGeeksforGeeks506K subscribersLargest number less than or equal to N in BST (Iterative Approach) | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:21•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=3EL8c9bBeco" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
princiraj1992
Rajput-Ji
bgangwar59
divyeshrabadiya07
akshaysingh98088
Binary Search Tree
Searching
Searching
Binary Search Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
set vs unordered_set in C++ STL
Construct BST from given preorder traversal | Set 2
Red Black Tree vs AVL Tree
Print BST keys in the given range
Find the node with maximum value in a Binary Search Tree
Binary Search
Maximum and minimum of an array using minimum number of comparisons
Linear Search
Search an element in a sorted and rotated array
Find the Missing Number | [
{
"code": null,
"e": 26579,
"s": 26551,
"text": "\n09 Aug, 2021"
},
{
"code": null,
"e": 26789,
"s": 26579,
"text": "We have a binary search tree and a number N. Our task is to find the greatest number in the binary search tree that is less than or equal to N. Print the value of the element if it exists otherwise print -1. "
},
{
"code": null,
"e": 26840,
"s": 26789,
"text": "Examples: For the above given binary search tree- "
},
{
"code": null,
"e": 26992,
"s": 26840,
"text": "Input : N = 24\nOutput :result = 21\n(searching for 24 will be like-5->12->21)\n\nInput : N = 4\nOutput : result = 3\n(searching for 4 will be like-5->2->3)"
},
{
"code": null,
"e": 27452,
"s": 26992,
"text": "We have discussed recursive approach in below post. Largest number in BST which is less than or equal to NHere an iterative approach is discussed. We try to find the predecessor of the target. Keep two pointers, one pointing to the current node and one for storing the answer. If the current node’s data > N, we move towards left. In other case, when current node’s data is less than N, the current node can be our answer (so far), and we move towards right. "
},
{
"code": null,
"e": 27456,
"s": 27452,
"text": "C++"
},
{
"code": null,
"e": 27461,
"s": 27456,
"text": "Java"
},
{
"code": null,
"e": 27469,
"s": 27461,
"text": "Python3"
},
{
"code": null,
"e": 27472,
"s": 27469,
"text": "C#"
},
{
"code": null,
"e": 27483,
"s": 27472,
"text": "Javascript"
},
{
"code": "// C++ code to find the largest value smaller// than or equal to N#include <bits/stdc++.h>using namespace std; struct Node { int key; Node *left, *right;}; // To create new BST NodeNode* newNode(int item){ Node* temp = new Node; temp->key = item; temp->left = temp->right = NULL; return temp;} // To insert a new node in BSTNode* insert(Node* node, int key){ // if tree is empty return new node if (node == NULL) return newNode(key); // if key is less then or greater then // node value then recur down the tree if (key < node->key) node->left = insert(node->left, key); else if (key > node->key) node->right = insert(node->right, key); // return the (unchanged) node pointer return node;} // Returns largest value smaller than or equal to// key. If key is smaller than the smallest, it// returns -1.int findFloor(Node* root, int key){ Node *curr = root, *ans = NULL; while (curr) { if (curr->key <= key) { ans = curr; curr = curr->right; } else curr = curr->left; } if (ans) return ans->key; return -1;} // Driver codeint main(){ int N = 25; Node* root = insert(root, 19); insert(root, 2); insert(root, 1); insert(root, 3); insert(root, 12); insert(root, 9); insert(root, 21); insert(root, 19); insert(root, 25); printf(\"%d\", findFloor(root, N)); return 0;}",
"e": 28922,
"s": 27483,
"text": null
},
{
"code": "// Java code to find the largest value smaller// than or equal to Nclass GFG{ static class Node{ int key; Node left, right;}; // To create new BST Nodestatic Node newNode(int item){ Node temp = new Node(); temp.key = item; temp.left = temp.right = null; return temp;} // To insert a new node in BSTstatic Node insert(Node node, int key){ // if tree is empty return new node if (node == null) return newNode(key); // if key is less then or greater then // node value then recur down the tree if (key < node.key) node.left = insert(node.left, key); else if (key > node.key) node.right = insert(node.right, key); // return the (unchanged) node pointer return node;} // Returns largest value smaller than or equal to// key. If key is smaller than the smallest, it// returns -1.static int findFloor(Node root, int key){ Node curr = root, ans = null; while (curr != null) { if (curr.key <= key) { ans = curr; curr = curr.right; } else curr = curr.left; } if (ans != null) return ans.key; return -1;} // Driver codepublic static void main(String[] args){ int N = 25; Node root = new Node(); insert(root, 19); insert(root, 2); insert(root, 1); insert(root, 3); insert(root, 12); insert(root, 9); insert(root, 21); insert(root, 19); insert(root, 25); System.out.printf(\"%d\", findFloor(root, N));}} /* This code is contributed by PrinciRaj1992 */",
"e": 30452,
"s": 28922,
"text": null
},
{
"code": "# Python3 code to find the largest value# smaller than or equal to N class newNode: def __init__(self, item): self.key = item self.left = None self.right = None # To insert a new node in BSTdef insert(node, key): # If tree is empty return new node if (node == None): return newNode(key) # If key is less then or greater then # node value then recur down the tree if (key < node.key): node.left = insert(node.left, key) elif (key > node.key): node.right = insert(node.right, key) # Return the (unchanged) node pointer return node # Returns largest value smaller than or# equal to key. If key is smaller than# the smallest, it returns -1.def findFloor(root, key): curr = root ans = None while (curr): if (curr.key <= key): ans = curr curr = curr.right else: curr = curr.left if (ans): return ans.key return -1 # Driver codeif __name__ == '__main__': N = 25 root = None root = insert(root, 19) insert(root, 2) insert(root, 1) insert(root, 3) insert(root, 12) insert(root, 9) insert(root, 21) insert(root, 19) insert(root, 25) print(findFloor(root, N)) # This code is contributed by bgangwar59",
"e": 31763,
"s": 30452,
"text": null
},
{
"code": "// C# code to find the largest value smaller// than or equal to Nusing System;using System.Collections.Generic; class GFG{ public class Node{ public int key; public Node left, right;}; // To create new BST Nodestatic Node newNode(int item){ Node temp = new Node(); temp.key = item; temp.left = temp.right = null; return temp;} // To insert a new node in BSTstatic Node insert(Node node, int key){ // if tree is empty return new node if (node == null) return newNode(key); // if key is less then or greater then // node value then recur down the tree if (key < node.key) node.left = insert(node.left, key); else if (key > node.key) node.right = insert(node.right, key); // return the (unchanged) node pointer return node;} // Returns largest value smaller than or equal to// key. If key is smaller than the smallest, it// returns -1.static int findFloor(Node root, int key){ Node curr = root, ans = null; while (curr != null) { if (curr.key <= key) { ans = curr; curr = curr.right; } else curr = curr.left; } if (ans != null) return ans.key; return -1;} // Driver codepublic static void Main(String[] args){ int N = 25; Node root = new Node(); insert(root, 19); insert(root, 2); insert(root, 1); insert(root, 3); insert(root, 12); insert(root, 9); insert(root, 21); insert(root, 19); insert(root, 25); Console.Write(\"{0}\", findFloor(root, N));}} // This code is contributed by Rajput-Ji",
"e": 33346,
"s": 31763,
"text": null
},
{
"code": "<script> // Javascript code to find the largest// value smaller than or equal to Nclass Node{ constructor(item) { this.key = item; this.left = null; this.right = null; }} // To create new BST Nodefunction newNode(item){ let temp = new Node(item); return temp;} // To insert a new node in BSTfunction insert(node, key){ // If tree is empty return new node if (node == null) return newNode(key); // If key is less then or greater then // node value then recur down the tree if (key < node.key) node.left = insert(node.left, key); else if (key > node.key) node.right = insert(node.right, key); // Return the (unchanged) node pointer return node;} // Returns largest value smaller than or// equal to key. If key is smaller than// the smallest, it returns -1.function findFloor(root, key){ let curr = root, ans = null; while (curr != null) { if (curr.key <= key) { ans = curr; curr = curr.right; } else curr = curr.left; } if (ans != null) return ans.key; return -1;} // Driver codelet N = 25; let root = new Node(N);insert(root, 19);insert(root, 2);insert(root, 1);insert(root, 3);insert(root, 12);insert(root, 9);insert(root, 21);insert(root, 19);insert(root, 25); document.write(findFloor(root, N)); // This code is contributed by divyeshrabadiya07 </script>",
"e": 34777,
"s": 33346,
"text": null
},
{
"code": null,
"e": 34786,
"s": 34777,
"text": "Output: "
},
{
"code": null,
"e": 34789,
"s": 34786,
"text": "25"
},
{
"code": null,
"e": 35654,
"s": 34789,
"text": "YouTubeGeeksforGeeks506K subscribersLargest number less than or equal to N in BST (Iterative Approach) | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:21•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=3EL8c9bBeco\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>"
},
{
"code": null,
"e": 35670,
"s": 35656,
"text": "princiraj1992"
},
{
"code": null,
"e": 35680,
"s": 35670,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 35691,
"s": 35680,
"text": "bgangwar59"
},
{
"code": null,
"e": 35709,
"s": 35691,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 35726,
"s": 35709,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 35745,
"s": 35726,
"text": "Binary Search Tree"
},
{
"code": null,
"e": 35755,
"s": 35745,
"text": "Searching"
},
{
"code": null,
"e": 35765,
"s": 35755,
"text": "Searching"
},
{
"code": null,
"e": 35784,
"s": 35765,
"text": "Binary Search Tree"
},
{
"code": null,
"e": 35882,
"s": 35784,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35914,
"s": 35882,
"text": "set vs unordered_set in C++ STL"
},
{
"code": null,
"e": 35966,
"s": 35914,
"text": "Construct BST from given preorder traversal | Set 2"
},
{
"code": null,
"e": 35993,
"s": 35966,
"text": "Red Black Tree vs AVL Tree"
},
{
"code": null,
"e": 36027,
"s": 35993,
"text": "Print BST keys in the given range"
},
{
"code": null,
"e": 36084,
"s": 36027,
"text": "Find the node with maximum value in a Binary Search Tree"
},
{
"code": null,
"e": 36098,
"s": 36084,
"text": "Binary Search"
},
{
"code": null,
"e": 36166,
"s": 36098,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 36180,
"s": 36166,
"text": "Linear Search"
},
{
"code": null,
"e": 36228,
"s": 36180,
"text": "Search an element in a sorted and rotated array"
}
] |
Check if a Stack contains an element in C# | To check if a Stack has elements, use the C# Contains() method. Following is the code −
Live Demo
using System;
using System.Collections.Generic;
public class Demo {
public static void Main(){
Stack<int> stack = new Stack<int>();
stack.Push(100);
stack.Push(150);
stack.Push(175);
stack.Push(200);
stack.Push(225);
stack.Push(250);
stack.Push(300);
stack.Push(400);
stack.Push(450);
stack.Push(500);
Console.WriteLine("Elements in the Stack:");
foreach(var val in stack){
Console.WriteLine(val);
}
Console.WriteLine("Count of elements in the Stack = "+stack.Count);
Console.WriteLine("Does Stack has the element 400?= "+stack.Contains(400));
}
}
This will produce the following output −
Elements in the Stack:
500
450
400
300
250
225
200
175
150
100
Count of elements in the Stack = 10 Does Stack has the element40400?= True
Let us see another example −
Live Demo
using System;
using System.Collections.Generic;
public class Demo {
public static void Main(){
Stack<string> stack = new Stack<string>();
stack.Push("Steve");
stack.Push("Gary");
stack.Push("Stephen");
stack.Push("Nathan");
stack.Push("Katie");
stack.Push("Andy");
stack.Push("David");
stack.Push("Amy");
Console.WriteLine("Elements in the Stack:");
foreach(var val in stack){
Console.WriteLine(val);
}
Console.WriteLine("Count of elements in the Stack = "+stack.Count);
Console.WriteLine("Does Stack has the element 400?= "+stack.Contains("Michael"));
}
}
This will produce the following output −
Elements in the Stack:
Amy
David
Andy
Katie
Nathan
Stephen
Gary
Steve
Count of elements in the Stack = 8 Does Stack has the element 400?= False | [
{
"code": null,
"e": 1150,
"s": 1062,
"text": "To check if a Stack has elements, use the C# Contains() method. Following is the code −"
},
{
"code": null,
"e": 1161,
"s": 1150,
"text": " Live Demo"
},
{
"code": null,
"e": 1820,
"s": 1161,
"text": "using System;\nusing System.Collections.Generic;\npublic class Demo {\n public static void Main(){\n Stack<int> stack = new Stack<int>();\n stack.Push(100);\n stack.Push(150);\n stack.Push(175);\n stack.Push(200);\n stack.Push(225);\n stack.Push(250);\n stack.Push(300);\n stack.Push(400);\n stack.Push(450);\n stack.Push(500);\n Console.WriteLine(\"Elements in the Stack:\");\n foreach(var val in stack){\n Console.WriteLine(val);\n }\n Console.WriteLine(\"Count of elements in the Stack = \"+stack.Count);\n Console.WriteLine(\"Does Stack has the element 400?= \"+stack.Contains(400));\n }\n}"
},
{
"code": null,
"e": 1861,
"s": 1820,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1999,
"s": 1861,
"text": "Elements in the Stack:\n500\n450\n400\n300\n250\n225\n200\n175\n150\n100\nCount of elements in the Stack = 10 Does Stack has the element40400?= True"
},
{
"code": null,
"e": 2028,
"s": 1999,
"text": "Let us see another example −"
},
{
"code": null,
"e": 2039,
"s": 2028,
"text": " Live Demo"
},
{
"code": null,
"e": 2695,
"s": 2039,
"text": "using System;\nusing System.Collections.Generic;\npublic class Demo {\n public static void Main(){\n Stack<string> stack = new Stack<string>();\n stack.Push(\"Steve\");\n stack.Push(\"Gary\");\n stack.Push(\"Stephen\");\n stack.Push(\"Nathan\");\n stack.Push(\"Katie\");\n stack.Push(\"Andy\");\n stack.Push(\"David\");\n stack.Push(\"Amy\");\n Console.WriteLine(\"Elements in the Stack:\");\n foreach(var val in stack){\n Console.WriteLine(val);\n }\n Console.WriteLine(\"Count of elements in the Stack = \"+stack.Count);\n Console.WriteLine(\"Does Stack has the element 400?= \"+stack.Contains(\"Michael\"));\n }\n}"
},
{
"code": null,
"e": 2736,
"s": 2695,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2880,
"s": 2736,
"text": "Elements in the Stack:\nAmy\nDavid\nAndy\nKatie\nNathan\nStephen\nGary\nSteve\nCount of elements in the Stack = 8 Does Stack has the element 400?= False"
}
] |
Android - XML Parser | XML stands for Extensible Mark-up Language.XML is a very popular format and commonly used for sharing data on the internet. This chapter explains how to parse the XML file and extract necessary information from it.
Android provides three types of XML parsers which are DOM,SAX and XMLPullParser. Among all of them android recommend XMLPullParser because it is efficient and easy to use. So we are going to use XMLPullParser for parsing XML.
The first step is to identify the fields in the XML data in which you are interested in. For example. In the XML given below we interested in getting temperature only.
<?xml version="1.0"?>
<current>
<city id="2643743" name="London">
<coord lon="-0.12574" lat="51.50853"/>
<country>GB</country>
<sun rise="2013-10-08T06:13:56" set="2013-10-08T17:21:45"/>
</city>
<temperature value="289.54" min="289.15" max="290.15" unit="kelvin"/>
<humidity value="77" unit="%"/>
<pressure value="1025" unit="hPa"/>
</current>
An xml file consist of many components. Here is the table defining the components of an XML file and their description.
Prolog
An XML file starts with a prolog. The first line that contains the information about a file is prolog
Events
An XML file has many events. Event could be like this. Document starts , Document ends, Tag start , Tag end and Text e.t.c
Text
Apart from tags and events, and xml file also contains simple text. Such as GB is a text in the country tag.
Attributes
Attributes are the additional properties of a tag such as value e.t.c
In the next step, we will create XMLPullParser object , but in order to create that we will first create XmlPullParserFactory object and then call its newPullParser() method to create XMLPullParser. Its syntax is given below −
private XmlPullParserFactory xmlFactoryObject = XmlPullParserFactory.newInstance();
private XmlPullParser myparser = xmlFactoryObject.newPullParser();
The next step involves specifying the file for XmlPullParser that contains XML. It could be a file or could be a Stream. In our case it is a stream.Its syntax is given below −
myparser.setInput(stream, null);
The last step is to parse the XML. An XML file consist of events, Name, Text, AttributesValue e.t.c. So XMLPullParser has a separate function for parsing each of the component of XML file. Its syntax is given below −
int event = myParser.getEventType();
while (event != XmlPullParser.END_DOCUMENT) {
String name=myParser.getName();
switch (event){
case XmlPullParser.START_TAG:
break;
case XmlPullParser.END_TAG:
if(name.equals("temperature")){
temperature = myParser.getAttributeValue(null,"value");
}
break;
}
event = myParser.next();
}
The method getEventType returns the type of event that happens. e.g: Document start , tag start e.t.c. The method getName returns the name of the tag and since we are only interested in temperature , so we just check in conditional statement that if we got a temperature tag , we call the method getAttributeValue to return us the value of temperature tag.
Apart from the these methods, there are other methods provided by this class for better parsing XML files. These methods are listed below −
getAttributeCount()
This method just Returns the number of attributes of the current start tag
getAttributeName(int index)
This method returns the name of the attribute specified by the index value
getColumnNumber()
This method returns the Returns the current column number, starting from 0.
getDepth()
This method returns Returns the current depth of the element.
getLineNumber()
Returns the current line number, starting from 1.
getNamespace()
This method returns the name space URI of the current element.
getPrefix()
This method returns the prefix of the current element
getName()
This method returns the name of the tag
getText()
This method returns the text for that particular element
isWhitespace()
This method checks whether the current TEXT event contains only whitespace characters.
Here is an example demonstrating the use of XML DOM Parser. It creates a basic application that allows you to parse XML.
To experiment with this example, you can run this on an actual device or in an emulator.
Following is the content of the modified main activity file MainActivity.java.
package com.example.sairamkrishna.myapplication;
import java.io.InputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView tv1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv1=(TextView)findViewById(R.id.textView1);
try {
InputStream is = getAssets().open("file.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(is);
Element element=doc.getDocumentElement();
element.normalize();
NodeList nList = doc.getElementsByTagName("employee");
for (int i=0; i<nList.getLength(); i++) {
Node node = nList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element2 = (Element) node;
tv1.setText(tv1.getText()+"\nName : " + getValue("name", element2)+"\n");
tv1.setText(tv1.getText()+"Surname : " + getValue("surname", element2)+"\n");
tv1.setText(tv1.getText()+"-----------------------");
}
}
} catch (Exception e) {e.printStackTrace();}
}
private static String getValue(String tag, Element element) {
NodeList nodeList = element.getElementsByTagName(tag).item(0).getChildNodes();
Node node = nodeList.item(0);
return node.getNodeValue();
}
}
Following is the content of Assets/file.xml.
<?xml version="1.0"?>
<records>
<employee>
<name>Sairamkrishna</name>
<surname>Mammahe</surname>
<salary>50000</salary>
</employee>
<employee>
<name>Gopal </name>
<surname>Varma</surname>
<salary>60000</salary>
</employee>
<employee>
<name>Raja</name>
<surname>Hr</surname>
<salary>70000</salary>
</employee>
</records>
Following is the modified content of the xml res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
Following is the content of AndroidManifest.xml file.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sairamkrishna.myapplication" >
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run our application we just modified. I assume you had created your AVD while doing environment setup. To run the app from Android studio, open one of your project's activity files and click Run icon from the toolbar. Android studio installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window −
46 Lectures
7.5 hours
Aditya Dua
32 Lectures
3.5 hours
Sharad Kumar
9 Lectures
1 hours
Abhilash Nelson
14 Lectures
1.5 hours
Abhilash Nelson
15 Lectures
1.5 hours
Abhilash Nelson
10 Lectures
1 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 3822,
"s": 3607,
"text": "XML stands for Extensible Mark-up Language.XML is a very popular format and commonly used for sharing data on the internet. This chapter explains how to parse the XML file and extract necessary information from it."
},
{
"code": null,
"e": 4048,
"s": 3822,
"text": "Android provides three types of XML parsers which are DOM,SAX and XMLPullParser. Among all of them android recommend XMLPullParser because it is efficient and easy to use. So we are going to use XMLPullParser for parsing XML."
},
{
"code": null,
"e": 4216,
"s": 4048,
"text": "The first step is to identify the fields in the XML data in which you are interested in. For example. In the XML given below we interested in getting temperature only."
},
{
"code": null,
"e": 4601,
"s": 4216,
"text": "<?xml version=\"1.0\"?>\n<current>\n \n <city id=\"2643743\" name=\"London\">\n <coord lon=\"-0.12574\" lat=\"51.50853\"/>\n <country>GB</country>\n <sun rise=\"2013-10-08T06:13:56\" set=\"2013-10-08T17:21:45\"/>\n </city>\n \n <temperature value=\"289.54\" min=\"289.15\" max=\"290.15\" unit=\"kelvin\"/>\n <humidity value=\"77\" unit=\"%\"/>\n <pressure value=\"1025\" unit=\"hPa\"/>\n</current>"
},
{
"code": null,
"e": 4721,
"s": 4601,
"text": "An xml file consist of many components. Here is the table defining the components of an XML file and their description."
},
{
"code": null,
"e": 4728,
"s": 4721,
"text": "Prolog"
},
{
"code": null,
"e": 4830,
"s": 4728,
"text": "An XML file starts with a prolog. The first line that contains the information about a file is prolog"
},
{
"code": null,
"e": 4837,
"s": 4830,
"text": "Events"
},
{
"code": null,
"e": 4960,
"s": 4837,
"text": "An XML file has many events. Event could be like this. Document starts , Document ends, Tag start , Tag end and Text e.t.c"
},
{
"code": null,
"e": 4965,
"s": 4960,
"text": "Text"
},
{
"code": null,
"e": 5074,
"s": 4965,
"text": "Apart from tags and events, and xml file also contains simple text. Such as GB is a text in the country tag."
},
{
"code": null,
"e": 5085,
"s": 5074,
"text": "Attributes"
},
{
"code": null,
"e": 5155,
"s": 5085,
"text": "Attributes are the additional properties of a tag such as value e.t.c"
},
{
"code": null,
"e": 5382,
"s": 5155,
"text": "In the next step, we will create XMLPullParser object , but in order to create that we will first create XmlPullParserFactory object and then call its newPullParser() method to create XMLPullParser. Its syntax is given below −"
},
{
"code": null,
"e": 5534,
"s": 5382,
"text": "private XmlPullParserFactory xmlFactoryObject = XmlPullParserFactory.newInstance();\nprivate XmlPullParser myparser = xmlFactoryObject.newPullParser();\n"
},
{
"code": null,
"e": 5710,
"s": 5534,
"text": "The next step involves specifying the file for XmlPullParser that contains XML. It could be a file or could be a Stream. In our case it is a stream.Its syntax is given below −"
},
{
"code": null,
"e": 5744,
"s": 5710,
"text": "myparser.setInput(stream, null);\n"
},
{
"code": null,
"e": 5961,
"s": 5744,
"text": "The last step is to parse the XML. An XML file consist of events, Name, Text, AttributesValue e.t.c. So XMLPullParser has a separate function for parsing each of the component of XML file. Its syntax is given below −"
},
{
"code": null,
"e": 6357,
"s": 5961,
"text": "int event = myParser.getEventType();\nwhile (event != XmlPullParser.END_DOCUMENT) {\n String name=myParser.getName();\n switch (event){\n case XmlPullParser.START_TAG:\n break;\n \n case XmlPullParser.END_TAG:\n if(name.equals(\"temperature\")){\n temperature = myParser.getAttributeValue(null,\"value\");\n }\n break;\n }\t\t \n event = myParser.next(); \t\t\t\t\t\n}"
},
{
"code": null,
"e": 6714,
"s": 6357,
"text": "The method getEventType returns the type of event that happens. e.g: Document start , tag start e.t.c. The method getName returns the name of the tag and since we are only interested in temperature , so we just check in conditional statement that if we got a temperature tag , we call the method getAttributeValue to return us the value of temperature tag."
},
{
"code": null,
"e": 6854,
"s": 6714,
"text": "Apart from the these methods, there are other methods provided by this class for better parsing XML files. These methods are listed below −"
},
{
"code": null,
"e": 6874,
"s": 6854,
"text": "getAttributeCount()"
},
{
"code": null,
"e": 6949,
"s": 6874,
"text": "This method just Returns the number of attributes of the current start tag"
},
{
"code": null,
"e": 6977,
"s": 6949,
"text": "getAttributeName(int index)"
},
{
"code": null,
"e": 7052,
"s": 6977,
"text": "This method returns the name of the attribute specified by the index value"
},
{
"code": null,
"e": 7070,
"s": 7052,
"text": "getColumnNumber()"
},
{
"code": null,
"e": 7146,
"s": 7070,
"text": "This method returns the Returns the current column number, starting from 0."
},
{
"code": null,
"e": 7157,
"s": 7146,
"text": "getDepth()"
},
{
"code": null,
"e": 7219,
"s": 7157,
"text": "This method returns Returns the current depth of the element."
},
{
"code": null,
"e": 7235,
"s": 7219,
"text": "getLineNumber()"
},
{
"code": null,
"e": 7285,
"s": 7235,
"text": "Returns the current line number, starting from 1."
},
{
"code": null,
"e": 7300,
"s": 7285,
"text": "getNamespace()"
},
{
"code": null,
"e": 7363,
"s": 7300,
"text": "This method returns the name space URI of the current element."
},
{
"code": null,
"e": 7375,
"s": 7363,
"text": "getPrefix()"
},
{
"code": null,
"e": 7429,
"s": 7375,
"text": "This method returns the prefix of the current element"
},
{
"code": null,
"e": 7439,
"s": 7429,
"text": "getName()"
},
{
"code": null,
"e": 7479,
"s": 7439,
"text": "This method returns the name of the tag"
},
{
"code": null,
"e": 7489,
"s": 7479,
"text": "getText()"
},
{
"code": null,
"e": 7547,
"s": 7489,
"text": "This method returns the text for that particular element "
},
{
"code": null,
"e": 7562,
"s": 7547,
"text": "isWhitespace()"
},
{
"code": null,
"e": 7649,
"s": 7562,
"text": "This method checks whether the current TEXT event contains only whitespace characters."
},
{
"code": null,
"e": 7770,
"s": 7649,
"text": "Here is an example demonstrating the use of XML DOM Parser. It creates a basic application that allows you to parse XML."
},
{
"code": null,
"e": 7859,
"s": 7770,
"text": "To experiment with this example, you can run this on an actual device or in an emulator."
},
{
"code": null,
"e": 7939,
"s": 7859,
"text": "Following is the content of the modified main activity file MainActivity.java. "
},
{
"code": null,
"e": 9758,
"s": 7939,
"text": "package com.example.sairamkrishna.myapplication;\n\nimport java.io.InputStream;\nimport javax.xml.parsers.DocumentBuilder;\nimport javax.xml.parsers.DocumentBuilderFactory;\nimport org.w3c.dom.Document;\nimport org.w3c.dom.Element;\nimport org.w3c.dom.Node;\nimport org.w3c.dom.NodeList;\nimport android.app.Activity;\nimport android.os.Bundle;\nimport android.widget.TextView;\n\npublic class MainActivity extends Activity {\n TextView tv1;\n\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n tv1=(TextView)findViewById(R.id.textView1);\n\t\t\n try {\n InputStream is = getAssets().open(\"file.xml\");\n\n DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();\n DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();\n Document doc = dBuilder.parse(is);\n\n Element element=doc.getDocumentElement();\n element.normalize();\n\n NodeList nList = doc.getElementsByTagName(\"employee\");\n\t\t\t\n for (int i=0; i<nList.getLength(); i++) {\n\n Node node = nList.item(i);\n if (node.getNodeType() == Node.ELEMENT_NODE) {\n Element element2 = (Element) node;\n tv1.setText(tv1.getText()+\"\\nName : \" + getValue(\"name\", element2)+\"\\n\");\n tv1.setText(tv1.getText()+\"Surname : \" + getValue(\"surname\", element2)+\"\\n\");\n tv1.setText(tv1.getText()+\"-----------------------\");\n }\n }\n\t\t\t\n } catch (Exception e) {e.printStackTrace();}\n\n }\n\t\n private static String getValue(String tag, Element element) {\n NodeList nodeList = element.getElementsByTagName(tag).item(0).getChildNodes();\n Node node = nodeList.item(0);\n return node.getNodeValue();\n }\n\n}"
},
{
"code": null,
"e": 9803,
"s": 9758,
"text": "Following is the content of Assets/file.xml."
},
{
"code": null,
"e": 10201,
"s": 9803,
"text": "<?xml version=\"1.0\"?>\n<records>\n <employee>\n <name>Sairamkrishna</name>\n <surname>Mammahe</surname>\n <salary>50000</salary>\n </employee>\n\t\n <employee>\n <name>Gopal </name>\n <surname>Varma</surname>\n <salary>60000</salary>\n </employee>\n\t\n <employee>\n <name>Raja</name>\n <surname>Hr</surname>\n <salary>70000</salary>\n </employee>\n\t\n</records>"
},
{
"code": null,
"e": 10276,
"s": 10201,
"text": "Following is the modified content of the xml res/layout/activity_main.xml."
},
{
"code": null,
"e": 10941,
"s": 10276,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:paddingBottom=\"@dimen/activity_vertical_margin\"\n android:paddingLeft=\"@dimen/activity_horizontal_margin\"\n android:paddingRight=\"@dimen/activity_horizontal_margin\"\n android:paddingTop=\"@dimen/activity_vertical_margin\"\n tools:context=\".MainActivity\">\n\n <TextView\n android:id=\"@+id/textView1\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 10995,
"s": 10941,
"text": "Following is the content of AndroidManifest.xml file."
},
{
"code": null,
"e": 11690,
"s": 10995,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"com.example.sairamkrishna.myapplication\" >\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:theme=\"@style/AppTheme\" >\n \n <activity\n android:name=\".MainActivity\"\n android:label=\"@string/app_name\" >\n \n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n \n </activity>\n \n </application>\n</manifest>"
},
{
"code": null,
"e": 12083,
"s": 11690,
"text": "Let's try to run our application we just modified. I assume you had created your AVD while doing environment setup. To run the app from Android studio, open one of your project's activity files and click Run icon from the toolbar. Android studio installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window −"
},
{
"code": null,
"e": 12118,
"s": 12083,
"text": "\n 46 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 12130,
"s": 12118,
"text": " Aditya Dua"
},
{
"code": null,
"e": 12165,
"s": 12130,
"text": "\n 32 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 12179,
"s": 12165,
"text": " Sharad Kumar"
},
{
"code": null,
"e": 12211,
"s": 12179,
"text": "\n 9 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 12228,
"s": 12211,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 12263,
"s": 12228,
"text": "\n 14 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 12280,
"s": 12263,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 12315,
"s": 12280,
"text": "\n 15 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 12332,
"s": 12315,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 12365,
"s": 12332,
"text": "\n 10 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 12382,
"s": 12365,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 12389,
"s": 12382,
"text": " Print"
},
{
"code": null,
"e": 12400,
"s": 12389,
"text": " Add Notes"
}
] |
Rearrange a given linked list in-place. - GeeksforGeeks | 18 Apr, 2022
Given a singly linked list L0 -> L1 -> ... -> Ln-1 -> Ln. Rearrange the nodes in the list so that the new formed list is : L0 -> Ln -> L1 -> Ln-1 -> L2 -> Ln-2 ...You are required to do this in place without altering the nodes’ values.
Examples:
Input: 1 -> 2 -> 3 -> 4
Output: 1 -> 4 -> 2 -> 3
Input: 1 -> 2 -> 3 -> 4 -> 5
Output: 1 -> 5 -> 2 -> 4 -> 3
Simple Solution
1) Initialize current node as head.
2) While next of current node is not null, do following
a) Find the last node, remove it from the end and insert it as next
of the current node.
b) Move current to next to next of current
The time complexity of the above simple solution is O(n2) where n is the number of nodes in the linked list.
Better Solution 1) Copy contents of the given linked list to a vector. 2) Rearrange the given vector by swapping nodes from both ends. 3) Copy the modified vector back to the linked list. Implementation of this approach: https://ide.geeksforgeeks.org/1eGSEy Thanks to Arushi Dhamija for suggesting this approach.
Efficient Solution:
1) Find the middle point using tortoise and hare method.
2) Split the linked list into two halves using found middle point in step 1.
3) Reverse the second half.
4) Do alternate merge of first and second halves.
The Time Complexity of this solution is O(n).
Below is the implementation of this method.
C++
C
Java
Python3
C#
Javascript
// C++ program to rearrange a linked list in-place#include <bits/stdc++.h>using namespace std; // Linkedlist Node structurestruct Node { int data; struct Node* next;}; // Function to create newNode in a linkedlistNode* newNode(int key){ Node* temp = new Node; temp->data = key; temp->next = NULL; return temp;} // Function to reverse the linked listvoid reverselist(Node** head){ // Initialize prev and current pointers Node *prev = NULL, *curr = *head, *next; while (curr) { next = curr->next; curr->next = prev; prev = curr; curr = next; } *head = prev;} // Function to print the linked listvoid printlist(Node* head){ while (head != NULL) { cout << head->data << " "; if (head->next) cout << "-> "; head = head->next; } cout << endl;} // Function to rearrange a linked listvoid rearrange(Node** head){ // 1) Find the middle point using tortoise and hare // method Node *slow = *head, *fast = slow->next; while (fast && fast->next) { slow = slow->next; fast = fast->next->next; } // 2) Split the linked list in two halves // head1, head of first half 1 -> 2 // head2, head of second half 3 -> 4 Node* head1 = *head; Node* head2 = slow->next; slow->next = NULL; // 3) Reverse the second half, i.e., 4 -> 3 reverselist(&head2); // 4) Merge alternate nodes *head = newNode(0); // Assign dummy Node // curr is the pointer to this dummy Node, which will // be used to form the new list Node* curr = *head; while (head1 || head2) { // First add the element from list if (head1) { curr->next = head1; curr = curr->next; head1 = head1->next; } // Then add the element from the second list if (head2) { curr->next = head2; curr = curr->next; head2 = head2->next; } } // Assign the head of the new list to head pointer *head = (*head)->next;} // Driver programint main(){ Node* head = newNode(1); head->next = newNode(2); head->next->next = newNode(3); head->next->next->next = newNode(4); head->next->next->next->next = newNode(5); printlist(head); // Print original list rearrange(&head); // Modify the list printlist(head); // Print modified list return 0;} // This code is contributed by Aditya Kumar (adityakumar129)
// C program to rearrange a linked list in-place#include <stdio.h>#include <stdlib.h> // Linkedlist Node structuretypedef struct Node { int data; struct Node* next;} Node; // Function to create newNode in a linkedlistNode* newNode(int key){ Node* temp = (Node*)malloc(sizeof(Node)); temp->data = key; temp->next = NULL; return temp;} // Function to reverse the linked listvoid reverselist(Node** head){ // Initialize prev and current pointers Node *prev = NULL, *curr = *head, *next; while (curr) { next = curr->next; curr->next = prev; prev = curr; curr = next; } *head = prev;} // Function to print the linked listvoid printlist(Node* head){ while (head != NULL) { printf("%d ", head->data); if (head->next) printf("-> "); head = head->next; } printf("\n");}// Function to rearrange a linked listvoid rearrange(Node** head){ // 1) Find the middle point using tortoise and hare // method Node *slow = *head, *fast = slow->next; while (fast && fast->next) { slow = slow->next; fast = fast->next->next; } // 2) Split the linked list in two halves // head1, head of first half 1 -> 2 // head2, head of second half 3 -> 4 Node* head1 = *head; Node* head2 = slow->next; slow->next = NULL; // 3) Reverse the second half, i.e., 4 -> 3 reverselist(&head2); // 4) Merge alternate nodes *head = newNode(0); // Assign dummy Node // curr is the pointer to this dummy Node, which will // be used to form the new list Node* curr = *head; while (head1 || head2) { // First add the element from list if (head1) { curr->next = head1; curr = curr->next; head1 = head1->next; } // Then add the element from the second list if (head2) { curr->next = head2; curr = curr->next; head2 = head2->next; } } // Assign the head of the new list to head pointer *head = (*head)->next;} // Driver programint main(){ Node* head = newNode(1); head->next = newNode(2); head->next->next = newNode(3); head->next->next->next = newNode(4); head->next->next->next->next = newNode(5); printlist(head); // Print original list rearrange(&head); // Modify the list printlist(head); // Print modified list return 0;} // This code is contributed by Aditya Kumar (adityakumar129)
// Java program to rearrange link list in place // Linked List Classclass LinkedList { static Node head; // head of the list /* Node Class */ static class Node { int data; Node next; // Constructor to create a new node Node(int d) { data = d; next = null; } } void printlist(Node node) { if (node == null) { return; } while (node != null) { System.out.print(node.data + " -> "); node = node.next; } } Node reverselist(Node node) { Node prev = null, curr = node, next; while (curr != null) { next = curr.next; curr.next = prev; prev = curr; curr = next; } node = prev; return node; } void rearrange(Node node) { // 1) Find the middle point using tortoise and hare // method Node slow = node, fast = slow.next; while (fast != null && fast.next != null) { slow = slow.next; fast = fast.next.next; } // 2) Split the linked list in two halves // node1, head of first half 1 -> 2 -> 3 // node2, head of second half 4 -> 5 Node node1 = node; Node node2 = slow.next; slow.next = null; // 3) Reverse the second half, i.e., 5 -> 4 node2 = reverselist(node2); // 4) Merge alternate nodes node = new Node(0); // Assign dummy Node // curr is the pointer to this dummy Node, which // will be used to form the new list Node curr = node; while (node1 != null || node2 != null) { // First add the element from first list if (node1 != null) { curr.next = node1; curr = curr.next; node1 = node1.next; } // Then add the element from second list if (node2 != null) { curr.next = node2; curr = curr.next; node2 = node2.next; } } // Assign the head of the new list to head pointer node = node.next; } public static void main(String[] args) { LinkedList list = new LinkedList(); list.head = new Node(1); list.head.next = new Node(2); list.head.next.next = new Node(3); list.head.next.next.next = new Node(4); list.head.next.next.next.next = new Node(5); list.printlist(head); // print original list list.rearrange(head); // rearrange list as per ques System.out.println(""); list.printlist(head); // print modified list }} // This code has been contributed by Mayank Jaiswal
# Python program to rearrange link list in place # Node Classclass Node: # Constructor to create a new node def __init__(self, d): self.data = d self.next = None def printlist(node): if(node == None): return while(node != None): print(node.data," -> ", end = "") node = node.next def reverselist(node): prev = None curr = node next=None while (curr != None): next = curr.next curr.next = prev prev = curr curr = next node = prev return node def rearrange(node): # 1) Find the middle point using tortoise and hare # method slow = node fast = slow.next while (fast != None and fast.next != None): slow = slow.next fast = fast.next.next # 2) Split the linked list in two halves # node1, head of first half 1 -> 2 -> 3 # node2, head of second half 4 -> 5 node1 = node node2 = slow.next slow.next = None # 3) Reverse the second half, i.e., 5 -> 4 node2 = reverselist(node2) # 4) Merge alternate nodes node = Node(0) #Assign dummy Node # curr is the pointer to this dummy Node, which # will be used to form the new list curr = node while (node1 != None or node2 != None): # First add the element from first list if (node1 != None): curr.next = node1 curr = curr.next node1 = node1.next # Then add the element from second list if(node2 != None): curr.next = node2 curr = curr.next node2 = node2.next # Assign the head of the new list to head pointer node = node.next head = Nonehead = Node(1)head.next = Node(2)head.next.next = Node(3)head.next.next.next = Node(4)head.next.next.next.next = Node(5) printlist(head) #print original listrearrange(head) #rearrange list as per quesprint()printlist(head) #print modified list # This code is contributed by ab2127
// C# program to rearrange link list in placeusing System; // Linked List Classpublic class LinkedList { Node head; // head of the list /* Node Class */ class Node { public int data; public Node next; // Constructor to create a new node public Node(int d) { data = d; next = null; } } void printlist(Node node) { if (node == null) { return; } while (node != null) { Console.Write(node.data + " -> "); node = node.next; } } Node reverselist(Node node) { Node prev = null, curr = node, next; while (curr != null) { next = curr.next; curr.next = prev; prev = curr; curr = next; } node = prev; return node; } void rearrange(Node node) { // 1) Find the middle point using // tortoise and hare method Node slow = node, fast = slow.next; while (fast != null && fast.next != null) { slow = slow.next; fast = fast.next.next; } // 2) Split the linked list in two halves // node1, head of first half 1 -> 2 -> 3 // node2, head of second half 4 -> 5 Node node1 = node; Node node2 = slow.next; slow.next = null; // 3) Reverse the second half, i.e., 5 -> 4 node2 = reverselist(node2); // 4) Merge alternate nodes node = new Node(0); // Assign dummy Node // curr is the pointer to this dummy Node, which // will be used to form the new list Node curr = node; while (node1 != null || node2 != null) { // First add the element from first list if (node1 != null) { curr.next = node1; curr = curr.next; node1 = node1.next; } // Then add the element from second list if (node2 != null) { curr.next = node2; curr = curr.next; node2 = node2.next; } } // Assign the head of the new list to head pointer node = node.next; } // Driver code public static void main(String[] args) { LinkedList list = new LinkedList(); list.head = new Node(1); list.head.next = new Node(2); list.head.next.next = new Node(3); list.head.next.next.next = new Node(4); list.head.next.next.next.next = new Node(5); list.printlist(list.head); // print original list list.rearrange( list.head); // rearrange list as per ques Console.WriteLine(""); list.printlist(list.head); // print modified list }} /* This code is contributed PrinciRaj1992 */
<script> // Javascript program to rearrange link list in place // Linked List Classvar head; // head of the list /* Node Class */ class Node { // Constructor to create a new nodeconstructor(d) { this.data = d; this.next = null;} } function printlist(node) { if (node == null) { return; } while (node != null) { document.write(node.data + " -> "); node = node.next; } } function reverselist(node) { var prev = null, curr = node, next; while (curr != null) { next = curr.next; curr.next = prev; prev = curr; curr = next; } node = prev; return node; } function rearrange(node) { // 1) Find the middle point using tortoise and hare // method var slow = node, fast = slow.next; while (fast != null && fast.next != null) { slow = slow.next; fast = fast.next.next; } // 2) Split the linked list in two halves // node1, head of first half 1 -> 2 -> 3 // node2, head of second half 4 -> 5 var node1 = node; var node2 = slow.next; slow.next = null; // 3) Reverse the second half, i.e., 5 -> 4 node2 = reverselist(node2); // 4) Merge alternate nodes node = new Node(0); // Assign dummy Node // curr is the pointer to this dummy Node, which // will be used to form the new list var curr = node; while (node1 != null || node2 != null) { // First add the element from first list if (node1 != null) { curr.next = node1; curr = curr.next; node1 = node1.next; } // Then add the element from second list if (node2 != null) { curr.next = node2; curr = curr.next; node2 = node2.next; } } // Assign the head of the new list to head pointer node = node.next; } head = new Node(1); head.next = new Node(2); head.next.next = new Node(3); head.next.next.next = new Node(4); head.next.next.next.next = new Node(5); printlist(head); // print original list rearrange(head); // rearrange list as per ques document.write("<br/>"); printlist(head); // print modified list // This code contributed by gauravrajput1</script>
1 -> 2 -> 3 -> 4 -> 5
1 -> 5 -> 2 -> 4 -> 3
Time Complexity: O(n) Auxiliary Space: O(1)Thanks to Gaurav Ahirwar for suggesting the above approach.
Another approach: 1. Take two pointers prev and curr, which hold the addresses of head and head-> next. 2. Compare their data and swap. After that, a new linked list is formed.
Below is the implementation:
C++
Java
Python3
C#
Javascript
// C++ code to rearrange linked list in place#include <bits/stdc++.h> using namespace std; struct node { int data; struct node* next;};typedef struct node Node; // function for rearranging a linked list with high and low// value.void rearrange(Node* head){ if (head == NULL) // Base case. return; // two pointer variable. Node *prev = head, *curr = head->next; while (curr) { // swap function for swapping data. if (prev->data > curr->data) swap(prev->data, curr->data); // swap function for swapping data. if (curr->next && curr->next->data > curr->data) swap(curr->next->data, curr->data); prev = curr->next; if (!curr->next) break; curr = curr->next->next; }} // function to insert a node in the linked list at the// beginning.void push(Node** head, int k){ Node* tem = (Node*)malloc(sizeof(Node)); tem->data = k; tem->next = *head; *head = tem;} // function to display node of linked list.void display(Node* head){ Node* curr = head; while (curr != NULL) { printf("%d ", curr->data); curr = curr->next; }} // driver codeint main(){ Node* head = NULL; // let create a linked list. // 9 -> 6 -> 8 -> 3 -> 7 push(&head, 7); push(&head, 3); push(&head, 8); push(&head, 6); push(&head, 9); rearrange(head); display(head); return 0;}
// Java code to rearrange linked list in placeclass Geeks { static class Node { int data; Node next; } // function for rearranging a linked list // with high and low value. static Node rearrange(Node head) { if (head == null) // Base case. return null; // two pointer variable. Node prev = head, curr = head.next; while (curr != null) { // swap function for swapping data. if (prev.data > curr.data) { int t = prev.data; prev.data = curr.data; curr.data = t; } // swap function for swapping data. if (curr.next != null && curr.next.data > curr.data) { int t = curr.next.data; curr.next.data = curr.data; curr.data = t; } prev = curr.next; if (curr.next == null) break; curr = curr.next.next; } return head; } // function to insert a Node in // the linked list at the beginning. static Node push(Node head, int k) { Node tem = new Node(); tem.data = k; tem.next = head; head = tem; return head; } // function to display Node of linked list. static void display(Node head) { Node curr = head; while (curr != null) { System.out.printf("%d ", curr.data); curr = curr.next; } } // Driver code public static void main(String args[]) { Node head = null; // let create a linked list. // 9 . 6 . 8 . 3 . 7 head = push(head, 7); head = push(head, 3); head = push(head, 8); head = push(head, 6); head = push(head, 9); head = rearrange(head); display(head); }} // This code is contributed by Arnab Kundu
# Python3 code to rearrange linked list in placeclass Node: def __init__(self, x): self.data = x self.next = None # Function for rearranging a linked# list with high and low value def rearrange(head): # Base case if (head == None): return head # Two pointer variable prev, curr = head, head.next while (curr): # Swap function for swapping data if (prev.data > curr.data): prev.data, curr.data = curr.data, prev.data # Swap function for swapping data if (curr.next and curr.next.data > curr.data): curr.next.data, curr.data = curr.data, curr.next.data prev = curr.next if (not curr.next): break curr = curr.next.next return head # Function to insert a node in the# linked list at the beginning def push(head, k): tem = Node(k) tem.data = k tem.next = head head = tem return head # Function to display node of linked list def display(head): curr = head while (curr != None): print(curr.data, end=" ") curr = curr.next # Driver codeif __name__ == '__main__': head = None # Let create a linked list # 9 . 6 . 8 . 3 . 7 head = push(head, 7) head = push(head, 3) head = push(head, 8) head = push(head, 6) head = push(head, 9) head = rearrange(head) display(head) # This code is contributed by mohit kumar 29
// C# code to rearrange linked list in placeusing System; class GFG { class Node { public int data; public Node next; } // Function for rearranging a linked list // with high and low value. static Node rearrange(Node head) { // Base case if (head == null) return null; // Two pointer variable. Node prev = head, curr = head.next; while (curr != null) { // Swap function for swapping data. if (prev.data > curr.data) { int t = prev.data; prev.data = curr.data; curr.data = t; } // Swap function for swapping data. if (curr.next != null && curr.next.data > curr.data) { int t = curr.next.data; curr.next.data = curr.data; curr.data = t; } prev = curr.next; if (curr.next == null) break; curr = curr.next.next; } return head; } // Function to insert a Node in // the linked list at the beginning. static Node push(Node head, int k) { Node tem = new Node(); tem.data = k; tem.next = head; head = tem; return head; } // Function to display Node of linked list. static void display(Node head) { Node curr = head; while (curr != null) { Console.Write(curr.data + " "); curr = curr.next; } } // Driver code public static void Main(string[] args) { Node head = null; // Let create a linked list. // 9 . 6 . 8 . 3 . 7 head = push(head, 7); head = push(head, 3); head = push(head, 8); head = push(head, 6); head = push(head, 9); head = rearrange(head); display(head); }} // This code is contributed by rutvik_56
<script>// Javascript code to rearrange linked list in place class Node { constructor() { this.data; this.next=null; } } // function for rearranging a linked list // with high and low value. function rearrange(head) { if (head == null) // Base case. return null; // two pointer variable. let prev = head, curr = head.next; while (curr != null) { // swap function for swapping data. if (prev.data > curr.data) { let t = prev.data; prev.data = curr.data; curr.data = t; } // swap function for swapping data. if (curr.next != null && curr.next.data > curr.data) { let t = curr.next.data; curr.next.data = curr.data; curr.data = t; } prev = curr.next; if (curr.next == null) break; curr = curr.next.next; } return head; } // function to display Node of linked list. function display(head) { let curr = head; while (curr != null) { document.write(curr.data+" "); curr = curr.next; } } // function to insert a Node in // the linked list at the beginning. function push(head,k) { let tem = new Node(); tem.data = k; tem.next = head; head = tem; return head; } // Driver code let head = null; head = push(head, 7); head = push(head, 3); head = push(head, 8); head = push(head, 6); head = push(head, 9); head = rearrange(head); display(head); // This code is contributed by unknown2108</script>
6 9 3 8 7
Time Complexity : O(n) Auxiliary Space : O(1) Thanks to Aditya for suggesting this approach.
Another Approach: (Using recursion)
Hold a pointer to the head node and go till the last node using recursionOnce the last node is reached, start swapping the last node to the next of head nodeMove the head pointer to the next nodeRepeat this until the head and the last node meet or come adjacent to each otherOnce the Stop condition met, we need to discard the left nodes to fix the loop created in the list while swapping nodes.
Hold a pointer to the head node and go till the last node using recursion
Once the last node is reached, start swapping the last node to the next of head node
Move the head pointer to the next node
Repeat this until the head and the last node meet or come adjacent to each other
Once the Stop condition met, we need to discard the left nodes to fix the loop created in the list while swapping nodes.
C
Java
Python3
C#
Javascript
// C/C++ implementation#include <stdio.h>#include <stdlib.h> // Creating the structure for nodestruct Node { int data; struct Node* next;}; // Function to create newNode in a linkedliststruct Node* newNode(int key){ struct Node* temp = malloc(sizeof(struct Node)); temp->data = key; temp->next = NULL; return temp;} // Function to print the listvoid printlist(struct Node* head){ while (head) { printf("%d ", head->data); if (head->next) printf("->"); head = head->next; } printf("\n");} // Function to rearrangevoid rearrange(struct Node** head, struct Node* last){ if (!last) return; // Recursive call rearrange(head, last->next); // (*head)->next will be set to NULL // after rearrangement. // Need not do any operation further // Just return here to come out of recursion if (!(*head)->next) return; // Rearrange the list until both head // and last meet or next to each other. if ((*head) != last && (*head)->next != last) { struct Node* tmp = (*head)->next; (*head)->next = last; last->next = tmp; *head = tmp; } else { if ((*head) != last) *head = (*head)->next; (*head)->next = NULL; }} // Drivers Codeint main(){ struct Node* head = newNode(1); head->next = newNode(2); head->next->next = newNode(3); head->next->next->next = newNode(4); head->next->next->next->next = newNode(5); // Print original list printlist(head); struct Node* tmp = head; // Modify the list rearrange(&tmp, head); // Print modified list printlist(head); return 0;}
// Java implementationimport java.io.*; // Creating the structure for nodeclass Node { int data; Node next; // Function to create newNode in a linkedlist Node(int key) { data = key; next = null; }}class GFG { Node left = null; // Function to print the list void printlist(Node head) { while (head != null) { System.out.print(head.data + " "); if (head.next != null) { System.out.print("->"); } head = head.next; } System.out.println(); } // Function to rearrange void rearrange(Node head) { if (head != null) { left = head; reorderListUtil(left); } } void reorderListUtil(Node right) { if (right == null) { return; } reorderListUtil(right.next); // we set left = null, when we reach stop condition, // so no processing required after that if (left == null) { return; } // Stop condition: odd case : left = right, even // case : left.next = right if (left != right && left.next != right) { Node temp = left.next; left.next = right; right.next = temp; left = temp; } else { // stop condition , set null to left nodes if (left.next == right) { left.next.next = null; // even case left = null; } else { left.next = null; // odd case left = null; } } } // Drivers Code public static void main(String[] args) { Node head = new Node(1); head.next = new Node(2); head.next.next = new Node(3); head.next.next.next = new Node(4); head.next.next.next.next = new Node(5); GFG gfg = new GFG(); // Print original list gfg.printlist(head); // Modify the list gfg.rearrange(head); // Print modified list gfg.printlist(head); }} // This code is contributed by Vishal Singh
# Python3 implementationclass Node: def __init__(self, key): self.data = key self.next = None left = None # Function to print the listdef printlist(head): while (head != None): print(head.data, end = " ") if (head.next != None): print("->", end = "") head = head.next print() # Function to rearrangedef rearrange(head): global left if (head != None): left = head reorderListUtil(left) def reorderListUtil(right): global left if (right == None): return reorderListUtil(right.next) # We set left = null, when we reach stop # condition, so no processing required # after that if (left == None): return # Stop condition: odd case : left = right, even # case : left.next = right if (left != right and left.next != right): temp = left.next left.next = right right.next = temp left = temp else: # Stop condition , set null to left nodes if (left.next == right): # Even case left.next.next = None left = None else: # Odd case left.next = None left = None # Driver codehead = Node(1)head.next = Node(2)head.next.next = Node(3)head.next.next.next = Node(4)head.next.next.next.next = Node(5) # Print original listprintlist(head) # Modify the listrearrange(head) # Print modified listprintlist(head) # This code is contributed by patel2127
// C# implementationusing System; // Creating the structure for nodepublic class Node{ public int data; public Node next; // Function to create newNode // in a linkedlist public Node(int key) { data = key; next = null; }} class GFG{ Node left = null; // Function to print the listvoid printlist(Node head){ while (head != null) { Console.Write(head.data + " "); if (head.next != null) { Console.Write("->"); } head = head.next; } Console.WriteLine();} // Function to rearrangevoid rearrange(Node head){ if (head != null) { left = head; reorderListUtil(left); }} void reorderListUtil(Node right){ if (right == null) { return; } reorderListUtil(right.next); // We set left = null, when we reach stop // condition, so no processing required // after that if (left == null) { return; } // Stop condition: odd case : left = right, even // case : left.next = right if (left != right && left.next != right) { Node temp = left.next; left.next = right; right.next = temp; left = temp; } else { // Stop condition , set null to left nodes if (left.next == right) { // Even case left.next.next = null; left = null; } else { // Odd case left.next = null; left = null; } }} // Driver Codestatic public void Main(){ Node head = new Node(1); head.next = new Node(2); head.next.next = new Node(3); head.next.next.next = new Node(4); head.next.next.next.next = new Node(5); GFG gfg = new GFG(); // Print original list gfg.printlist(head); // Modify the list gfg.rearrange(head); // Print modified list gfg.printlist(head);}} // This code is contributed by rag2127
<script>// javascript implementation// Creating the structure for nodeclass Node { // Function to create newNode in a linkedlist constructor(val) { this.data = val; this.next = null; }} var left = null; // Function to print the list function printlist(head) { while (head != null) { document.write(head.data + " "); if (head.next != null) { document.write("->"); } head = head.next; } document.write("<br/>"); } // Function to rearrange function rearrange(head) { if (head != null) { left = head; reorderListUtil(left); } } function reorderListUtil(right) { if (right == null) { return; } reorderListUtil(right.next); // we set left = null, when we reach stop condition, // so no processing required after that if (left == null) { return; } // Stop condition: odd case : left = right, even // case : left.next = right if (left != right && left.next != right) { var temp = left.next; left.next = right; right.next = temp; left = temp; } else { // stop condition , set null to left nodes if (left.next == right) { left.next.next = null; // even case left = null; } else { left.next = null; // odd case left = null; } } } // Drivers Code var head = new Node(1); head.next = new Node(2); head.next.next = new Node(3); head.next.next.next = new Node(4); head.next.next.next.next = new Node(5); // Print original list printlist(head); // Modify the list rearrange(head); // Print modified list printlist(head); // This code contributed by aashish1995</script>
1 ->2 ->3 ->4 ->5
1 ->5 ->2 ->4 ->3
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Balraj Parmar
princiraj1992
kalaikarthick
andrew1234
mohit kumar 29
rutvik_56
avanitrachhadiya2155
singhvishal240891
rag2127
unknown2108
GauravRajput1
aashish1995
Kirti_Mangal
ab2127
patel2127
Amazon
Linked List
Amazon
Linked List
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
LinkedList in Java
Linked List vs Array
Delete a Linked List node at a given position
Queue - Linked List Implementation
Implement a stack using singly linked list
Implementing a Linked List in Java using Class
Circular Linked List | Set 1 (Introduction and Applications)
Remove duplicates from a sorted linked list
Find Length of a Linked List (Iterative and Recursive)
Function to check if a singly linked list is palindrome | [
{
"code": null,
"e": 24581,
"s": 24553,
"text": "\n18 Apr, 2022"
},
{
"code": null,
"e": 24818,
"s": 24581,
"text": "Given a singly linked list L0 -> L1 -> ... -> Ln-1 -> Ln. Rearrange the nodes in the list so that the new formed list is : L0 -> Ln -> L1 -> Ln-1 -> L2 -> Ln-2 ...You are required to do this in place without altering the nodes’ values. "
},
{
"code": null,
"e": 24829,
"s": 24818,
"text": "Examples: "
},
{
"code": null,
"e": 24940,
"s": 24829,
"text": "Input: 1 -> 2 -> 3 -> 4\nOutput: 1 -> 4 -> 2 -> 3\n\nInput: 1 -> 2 -> 3 -> 4 -> 5\nOutput: 1 -> 5 -> 2 -> 4 -> 3"
},
{
"code": null,
"e": 24956,
"s": 24940,
"text": "Simple Solution"
},
{
"code": null,
"e": 25195,
"s": 24956,
"text": "1) Initialize current node as head.\n2) While next of current node is not null, do following\n a) Find the last node, remove it from the end and insert it as next\n of the current node.\n b) Move current to next to next of current"
},
{
"code": null,
"e": 25304,
"s": 25195,
"text": "The time complexity of the above simple solution is O(n2) where n is the number of nodes in the linked list."
},
{
"code": null,
"e": 25617,
"s": 25304,
"text": "Better Solution 1) Copy contents of the given linked list to a vector. 2) Rearrange the given vector by swapping nodes from both ends. 3) Copy the modified vector back to the linked list. Implementation of this approach: https://ide.geeksforgeeks.org/1eGSEy Thanks to Arushi Dhamija for suggesting this approach."
},
{
"code": null,
"e": 25637,
"s": 25617,
"text": "Efficient Solution:"
},
{
"code": null,
"e": 25849,
"s": 25637,
"text": "1) Find the middle point using tortoise and hare method.\n2) Split the linked list into two halves using found middle point in step 1.\n3) Reverse the second half.\n4) Do alternate merge of first and second halves."
},
{
"code": null,
"e": 25896,
"s": 25849,
"text": "The Time Complexity of this solution is O(n). "
},
{
"code": null,
"e": 25940,
"s": 25896,
"text": "Below is the implementation of this method."
},
{
"code": null,
"e": 25944,
"s": 25940,
"text": "C++"
},
{
"code": null,
"e": 25946,
"s": 25944,
"text": "C"
},
{
"code": null,
"e": 25951,
"s": 25946,
"text": "Java"
},
{
"code": null,
"e": 25959,
"s": 25951,
"text": "Python3"
},
{
"code": null,
"e": 25962,
"s": 25959,
"text": "C#"
},
{
"code": null,
"e": 25973,
"s": 25962,
"text": "Javascript"
},
{
"code": "// C++ program to rearrange a linked list in-place#include <bits/stdc++.h>using namespace std; // Linkedlist Node structurestruct Node { int data; struct Node* next;}; // Function to create newNode in a linkedlistNode* newNode(int key){ Node* temp = new Node; temp->data = key; temp->next = NULL; return temp;} // Function to reverse the linked listvoid reverselist(Node** head){ // Initialize prev and current pointers Node *prev = NULL, *curr = *head, *next; while (curr) { next = curr->next; curr->next = prev; prev = curr; curr = next; } *head = prev;} // Function to print the linked listvoid printlist(Node* head){ while (head != NULL) { cout << head->data << \" \"; if (head->next) cout << \"-> \"; head = head->next; } cout << endl;} // Function to rearrange a linked listvoid rearrange(Node** head){ // 1) Find the middle point using tortoise and hare // method Node *slow = *head, *fast = slow->next; while (fast && fast->next) { slow = slow->next; fast = fast->next->next; } // 2) Split the linked list in two halves // head1, head of first half 1 -> 2 // head2, head of second half 3 -> 4 Node* head1 = *head; Node* head2 = slow->next; slow->next = NULL; // 3) Reverse the second half, i.e., 4 -> 3 reverselist(&head2); // 4) Merge alternate nodes *head = newNode(0); // Assign dummy Node // curr is the pointer to this dummy Node, which will // be used to form the new list Node* curr = *head; while (head1 || head2) { // First add the element from list if (head1) { curr->next = head1; curr = curr->next; head1 = head1->next; } // Then add the element from the second list if (head2) { curr->next = head2; curr = curr->next; head2 = head2->next; } } // Assign the head of the new list to head pointer *head = (*head)->next;} // Driver programint main(){ Node* head = newNode(1); head->next = newNode(2); head->next->next = newNode(3); head->next->next->next = newNode(4); head->next->next->next->next = newNode(5); printlist(head); // Print original list rearrange(&head); // Modify the list printlist(head); // Print modified list return 0;} // This code is contributed by Aditya Kumar (adityakumar129)",
"e": 28412,
"s": 25973,
"text": null
},
{
"code": "// C program to rearrange a linked list in-place#include <stdio.h>#include <stdlib.h> // Linkedlist Node structuretypedef struct Node { int data; struct Node* next;} Node; // Function to create newNode in a linkedlistNode* newNode(int key){ Node* temp = (Node*)malloc(sizeof(Node)); temp->data = key; temp->next = NULL; return temp;} // Function to reverse the linked listvoid reverselist(Node** head){ // Initialize prev and current pointers Node *prev = NULL, *curr = *head, *next; while (curr) { next = curr->next; curr->next = prev; prev = curr; curr = next; } *head = prev;} // Function to print the linked listvoid printlist(Node* head){ while (head != NULL) { printf(\"%d \", head->data); if (head->next) printf(\"-> \"); head = head->next; } printf(\"\\n\");}// Function to rearrange a linked listvoid rearrange(Node** head){ // 1) Find the middle point using tortoise and hare // method Node *slow = *head, *fast = slow->next; while (fast && fast->next) { slow = slow->next; fast = fast->next->next; } // 2) Split the linked list in two halves // head1, head of first half 1 -> 2 // head2, head of second half 3 -> 4 Node* head1 = *head; Node* head2 = slow->next; slow->next = NULL; // 3) Reverse the second half, i.e., 4 -> 3 reverselist(&head2); // 4) Merge alternate nodes *head = newNode(0); // Assign dummy Node // curr is the pointer to this dummy Node, which will // be used to form the new list Node* curr = *head; while (head1 || head2) { // First add the element from list if (head1) { curr->next = head1; curr = curr->next; head1 = head1->next; } // Then add the element from the second list if (head2) { curr->next = head2; curr = curr->next; head2 = head2->next; } } // Assign the head of the new list to head pointer *head = (*head)->next;} // Driver programint main(){ Node* head = newNode(1); head->next = newNode(2); head->next->next = newNode(3); head->next->next->next = newNode(4); head->next->next->next->next = newNode(5); printlist(head); // Print original list rearrange(&head); // Modify the list printlist(head); // Print modified list return 0;} // This code is contributed by Aditya Kumar (adityakumar129)",
"e": 30873,
"s": 28412,
"text": null
},
{
"code": "// Java program to rearrange link list in place // Linked List Classclass LinkedList { static Node head; // head of the list /* Node Class */ static class Node { int data; Node next; // Constructor to create a new node Node(int d) { data = d; next = null; } } void printlist(Node node) { if (node == null) { return; } while (node != null) { System.out.print(node.data + \" -> \"); node = node.next; } } Node reverselist(Node node) { Node prev = null, curr = node, next; while (curr != null) { next = curr.next; curr.next = prev; prev = curr; curr = next; } node = prev; return node; } void rearrange(Node node) { // 1) Find the middle point using tortoise and hare // method Node slow = node, fast = slow.next; while (fast != null && fast.next != null) { slow = slow.next; fast = fast.next.next; } // 2) Split the linked list in two halves // node1, head of first half 1 -> 2 -> 3 // node2, head of second half 4 -> 5 Node node1 = node; Node node2 = slow.next; slow.next = null; // 3) Reverse the second half, i.e., 5 -> 4 node2 = reverselist(node2); // 4) Merge alternate nodes node = new Node(0); // Assign dummy Node // curr is the pointer to this dummy Node, which // will be used to form the new list Node curr = node; while (node1 != null || node2 != null) { // First add the element from first list if (node1 != null) { curr.next = node1; curr = curr.next; node1 = node1.next; } // Then add the element from second list if (node2 != null) { curr.next = node2; curr = curr.next; node2 = node2.next; } } // Assign the head of the new list to head pointer node = node.next; } public static void main(String[] args) { LinkedList list = new LinkedList(); list.head = new Node(1); list.head.next = new Node(2); list.head.next.next = new Node(3); list.head.next.next.next = new Node(4); list.head.next.next.next.next = new Node(5); list.printlist(head); // print original list list.rearrange(head); // rearrange list as per ques System.out.println(\"\"); list.printlist(head); // print modified list }} // This code has been contributed by Mayank Jaiswal",
"e": 33601,
"s": 30873,
"text": null
},
{
"code": "# Python program to rearrange link list in place # Node Classclass Node: # Constructor to create a new node def __init__(self, d): self.data = d self.next = None def printlist(node): if(node == None): return while(node != None): print(node.data,\" -> \", end = \"\") node = node.next def reverselist(node): prev = None curr = node next=None while (curr != None): next = curr.next curr.next = prev prev = curr curr = next node = prev return node def rearrange(node): # 1) Find the middle point using tortoise and hare # method slow = node fast = slow.next while (fast != None and fast.next != None): slow = slow.next fast = fast.next.next # 2) Split the linked list in two halves # node1, head of first half 1 -> 2 -> 3 # node2, head of second half 4 -> 5 node1 = node node2 = slow.next slow.next = None # 3) Reverse the second half, i.e., 5 -> 4 node2 = reverselist(node2) # 4) Merge alternate nodes node = Node(0) #Assign dummy Node # curr is the pointer to this dummy Node, which # will be used to form the new list curr = node while (node1 != None or node2 != None): # First add the element from first list if (node1 != None): curr.next = node1 curr = curr.next node1 = node1.next # Then add the element from second list if(node2 != None): curr.next = node2 curr = curr.next node2 = node2.next # Assign the head of the new list to head pointer node = node.next head = Nonehead = Node(1)head.next = Node(2)head.next.next = Node(3)head.next.next.next = Node(4)head.next.next.next.next = Node(5) printlist(head) #print original listrearrange(head) #rearrange list as per quesprint()printlist(head) #print modified list # This code is contributed by ab2127",
"e": 35588,
"s": 33601,
"text": null
},
{
"code": "// C# program to rearrange link list in placeusing System; // Linked List Classpublic class LinkedList { Node head; // head of the list /* Node Class */ class Node { public int data; public Node next; // Constructor to create a new node public Node(int d) { data = d; next = null; } } void printlist(Node node) { if (node == null) { return; } while (node != null) { Console.Write(node.data + \" -> \"); node = node.next; } } Node reverselist(Node node) { Node prev = null, curr = node, next; while (curr != null) { next = curr.next; curr.next = prev; prev = curr; curr = next; } node = prev; return node; } void rearrange(Node node) { // 1) Find the middle point using // tortoise and hare method Node slow = node, fast = slow.next; while (fast != null && fast.next != null) { slow = slow.next; fast = fast.next.next; } // 2) Split the linked list in two halves // node1, head of first half 1 -> 2 -> 3 // node2, head of second half 4 -> 5 Node node1 = node; Node node2 = slow.next; slow.next = null; // 3) Reverse the second half, i.e., 5 -> 4 node2 = reverselist(node2); // 4) Merge alternate nodes node = new Node(0); // Assign dummy Node // curr is the pointer to this dummy Node, which // will be used to form the new list Node curr = node; while (node1 != null || node2 != null) { // First add the element from first list if (node1 != null) { curr.next = node1; curr = curr.next; node1 = node1.next; } // Then add the element from second list if (node2 != null) { curr.next = node2; curr = curr.next; node2 = node2.next; } } // Assign the head of the new list to head pointer node = node.next; } // Driver code public static void main(String[] args) { LinkedList list = new LinkedList(); list.head = new Node(1); list.head.next = new Node(2); list.head.next.next = new Node(3); list.head.next.next.next = new Node(4); list.head.next.next.next.next = new Node(5); list.printlist(list.head); // print original list list.rearrange( list.head); // rearrange list as per ques Console.WriteLine(\"\"); list.printlist(list.head); // print modified list }} /* This code is contributed PrinciRaj1992 */",
"e": 38370,
"s": 35588,
"text": null
},
{
"code": "<script> // Javascript program to rearrange link list in place // Linked List Classvar head; // head of the list /* Node Class */ class Node { // Constructor to create a new nodeconstructor(d) { this.data = d; this.next = null;} } function printlist(node) { if (node == null) { return; } while (node != null) { document.write(node.data + \" -> \"); node = node.next; } } function reverselist(node) { var prev = null, curr = node, next; while (curr != null) { next = curr.next; curr.next = prev; prev = curr; curr = next; } node = prev; return node; } function rearrange(node) { // 1) Find the middle point using tortoise and hare // method var slow = node, fast = slow.next; while (fast != null && fast.next != null) { slow = slow.next; fast = fast.next.next; } // 2) Split the linked list in two halves // node1, head of first half 1 -> 2 -> 3 // node2, head of second half 4 -> 5 var node1 = node; var node2 = slow.next; slow.next = null; // 3) Reverse the second half, i.e., 5 -> 4 node2 = reverselist(node2); // 4) Merge alternate nodes node = new Node(0); // Assign dummy Node // curr is the pointer to this dummy Node, which // will be used to form the new list var curr = node; while (node1 != null || node2 != null) { // First add the element from first list if (node1 != null) { curr.next = node1; curr = curr.next; node1 = node1.next; } // Then add the element from second list if (node2 != null) { curr.next = node2; curr = curr.next; node2 = node2.next; } } // Assign the head of the new list to head pointer node = node.next; } head = new Node(1); head.next = new Node(2); head.next.next = new Node(3); head.next.next.next = new Node(4); head.next.next.next.next = new Node(5); printlist(head); // print original list rearrange(head); // rearrange list as per ques document.write(\"<br/>\"); printlist(head); // print modified list // This code contributed by gauravrajput1</script>",
"e": 40851,
"s": 38370,
"text": null
},
{
"code": null,
"e": 40896,
"s": 40851,
"text": "1 -> 2 -> 3 -> 4 -> 5 \n1 -> 5 -> 2 -> 4 -> 3"
},
{
"code": null,
"e": 41001,
"s": 40898,
"text": "Time Complexity: O(n) Auxiliary Space: O(1)Thanks to Gaurav Ahirwar for suggesting the above approach."
},
{
"code": null,
"e": 41179,
"s": 41001,
"text": "Another approach: 1. Take two pointers prev and curr, which hold the addresses of head and head-> next. 2. Compare their data and swap. After that, a new linked list is formed. "
},
{
"code": null,
"e": 41209,
"s": 41179,
"text": "Below is the implementation: "
},
{
"code": null,
"e": 41213,
"s": 41209,
"text": "C++"
},
{
"code": null,
"e": 41218,
"s": 41213,
"text": "Java"
},
{
"code": null,
"e": 41226,
"s": 41218,
"text": "Python3"
},
{
"code": null,
"e": 41229,
"s": 41226,
"text": "C#"
},
{
"code": null,
"e": 41240,
"s": 41229,
"text": "Javascript"
},
{
"code": "// C++ code to rearrange linked list in place#include <bits/stdc++.h> using namespace std; struct node { int data; struct node* next;};typedef struct node Node; // function for rearranging a linked list with high and low// value.void rearrange(Node* head){ if (head == NULL) // Base case. return; // two pointer variable. Node *prev = head, *curr = head->next; while (curr) { // swap function for swapping data. if (prev->data > curr->data) swap(prev->data, curr->data); // swap function for swapping data. if (curr->next && curr->next->data > curr->data) swap(curr->next->data, curr->data); prev = curr->next; if (!curr->next) break; curr = curr->next->next; }} // function to insert a node in the linked list at the// beginning.void push(Node** head, int k){ Node* tem = (Node*)malloc(sizeof(Node)); tem->data = k; tem->next = *head; *head = tem;} // function to display node of linked list.void display(Node* head){ Node* curr = head; while (curr != NULL) { printf(\"%d \", curr->data); curr = curr->next; }} // driver codeint main(){ Node* head = NULL; // let create a linked list. // 9 -> 6 -> 8 -> 3 -> 7 push(&head, 7); push(&head, 3); push(&head, 8); push(&head, 6); push(&head, 9); rearrange(head); display(head); return 0;}",
"e": 42660,
"s": 41240,
"text": null
},
{
"code": "// Java code to rearrange linked list in placeclass Geeks { static class Node { int data; Node next; } // function for rearranging a linked list // with high and low value. static Node rearrange(Node head) { if (head == null) // Base case. return null; // two pointer variable. Node prev = head, curr = head.next; while (curr != null) { // swap function for swapping data. if (prev.data > curr.data) { int t = prev.data; prev.data = curr.data; curr.data = t; } // swap function for swapping data. if (curr.next != null && curr.next.data > curr.data) { int t = curr.next.data; curr.next.data = curr.data; curr.data = t; } prev = curr.next; if (curr.next == null) break; curr = curr.next.next; } return head; } // function to insert a Node in // the linked list at the beginning. static Node push(Node head, int k) { Node tem = new Node(); tem.data = k; tem.next = head; head = tem; return head; } // function to display Node of linked list. static void display(Node head) { Node curr = head; while (curr != null) { System.out.printf(\"%d \", curr.data); curr = curr.next; } } // Driver code public static void main(String args[]) { Node head = null; // let create a linked list. // 9 . 6 . 8 . 3 . 7 head = push(head, 7); head = push(head, 3); head = push(head, 8); head = push(head, 6); head = push(head, 9); head = rearrange(head); display(head); }} // This code is contributed by Arnab Kundu",
"e": 44560,
"s": 42660,
"text": null
},
{
"code": "# Python3 code to rearrange linked list in placeclass Node: def __init__(self, x): self.data = x self.next = None # Function for rearranging a linked# list with high and low value def rearrange(head): # Base case if (head == None): return head # Two pointer variable prev, curr = head, head.next while (curr): # Swap function for swapping data if (prev.data > curr.data): prev.data, curr.data = curr.data, prev.data # Swap function for swapping data if (curr.next and curr.next.data > curr.data): curr.next.data, curr.data = curr.data, curr.next.data prev = curr.next if (not curr.next): break curr = curr.next.next return head # Function to insert a node in the# linked list at the beginning def push(head, k): tem = Node(k) tem.data = k tem.next = head head = tem return head # Function to display node of linked list def display(head): curr = head while (curr != None): print(curr.data, end=\" \") curr = curr.next # Driver codeif __name__ == '__main__': head = None # Let create a linked list # 9 . 6 . 8 . 3 . 7 head = push(head, 7) head = push(head, 3) head = push(head, 8) head = push(head, 6) head = push(head, 9) head = rearrange(head) display(head) # This code is contributed by mohit kumar 29",
"e": 45973,
"s": 44560,
"text": null
},
{
"code": "// C# code to rearrange linked list in placeusing System; class GFG { class Node { public int data; public Node next; } // Function for rearranging a linked list // with high and low value. static Node rearrange(Node head) { // Base case if (head == null) return null; // Two pointer variable. Node prev = head, curr = head.next; while (curr != null) { // Swap function for swapping data. if (prev.data > curr.data) { int t = prev.data; prev.data = curr.data; curr.data = t; } // Swap function for swapping data. if (curr.next != null && curr.next.data > curr.data) { int t = curr.next.data; curr.next.data = curr.data; curr.data = t; } prev = curr.next; if (curr.next == null) break; curr = curr.next.next; } return head; } // Function to insert a Node in // the linked list at the beginning. static Node push(Node head, int k) { Node tem = new Node(); tem.data = k; tem.next = head; head = tem; return head; } // Function to display Node of linked list. static void display(Node head) { Node curr = head; while (curr != null) { Console.Write(curr.data + \" \"); curr = curr.next; } } // Driver code public static void Main(string[] args) { Node head = null; // Let create a linked list. // 9 . 6 . 8 . 3 . 7 head = push(head, 7); head = push(head, 3); head = push(head, 8); head = push(head, 6); head = push(head, 9); head = rearrange(head); display(head); }} // This code is contributed by rutvik_56",
"e": 47892,
"s": 45973,
"text": null
},
{
"code": "<script>// Javascript code to rearrange linked list in place class Node { constructor() { this.data; this.next=null; } } // function for rearranging a linked list // with high and low value. function rearrange(head) { if (head == null) // Base case. return null; // two pointer variable. let prev = head, curr = head.next; while (curr != null) { // swap function for swapping data. if (prev.data > curr.data) { let t = prev.data; prev.data = curr.data; curr.data = t; } // swap function for swapping data. if (curr.next != null && curr.next.data > curr.data) { let t = curr.next.data; curr.next.data = curr.data; curr.data = t; } prev = curr.next; if (curr.next == null) break; curr = curr.next.next; } return head; } // function to display Node of linked list. function display(head) { let curr = head; while (curr != null) { document.write(curr.data+\" \"); curr = curr.next; } } // function to insert a Node in // the linked list at the beginning. function push(head,k) { let tem = new Node(); tem.data = k; tem.next = head; head = tem; return head; } // Driver code let head = null; head = push(head, 7); head = push(head, 3); head = push(head, 8); head = push(head, 6); head = push(head, 9); head = rearrange(head); display(head); // This code is contributed by unknown2108</script>",
"e": 49718,
"s": 47892,
"text": null
},
{
"code": null,
"e": 49728,
"s": 49718,
"text": "6 9 3 8 7"
},
{
"code": null,
"e": 49823,
"s": 49730,
"text": "Time Complexity : O(n) Auxiliary Space : O(1) Thanks to Aditya for suggesting this approach."
},
{
"code": null,
"e": 49861,
"s": 49823,
"text": "Another Approach: (Using recursion) "
},
{
"code": null,
"e": 50257,
"s": 49861,
"text": "Hold a pointer to the head node and go till the last node using recursionOnce the last node is reached, start swapping the last node to the next of head nodeMove the head pointer to the next nodeRepeat this until the head and the last node meet or come adjacent to each otherOnce the Stop condition met, we need to discard the left nodes to fix the loop created in the list while swapping nodes."
},
{
"code": null,
"e": 50331,
"s": 50257,
"text": "Hold a pointer to the head node and go till the last node using recursion"
},
{
"code": null,
"e": 50416,
"s": 50331,
"text": "Once the last node is reached, start swapping the last node to the next of head node"
},
{
"code": null,
"e": 50455,
"s": 50416,
"text": "Move the head pointer to the next node"
},
{
"code": null,
"e": 50536,
"s": 50455,
"text": "Repeat this until the head and the last node meet or come adjacent to each other"
},
{
"code": null,
"e": 50657,
"s": 50536,
"text": "Once the Stop condition met, we need to discard the left nodes to fix the loop created in the list while swapping nodes."
},
{
"code": null,
"e": 50659,
"s": 50657,
"text": "C"
},
{
"code": null,
"e": 50664,
"s": 50659,
"text": "Java"
},
{
"code": null,
"e": 50672,
"s": 50664,
"text": "Python3"
},
{
"code": null,
"e": 50675,
"s": 50672,
"text": "C#"
},
{
"code": null,
"e": 50686,
"s": 50675,
"text": "Javascript"
},
{
"code": "// C/C++ implementation#include <stdio.h>#include <stdlib.h> // Creating the structure for nodestruct Node { int data; struct Node* next;}; // Function to create newNode in a linkedliststruct Node* newNode(int key){ struct Node* temp = malloc(sizeof(struct Node)); temp->data = key; temp->next = NULL; return temp;} // Function to print the listvoid printlist(struct Node* head){ while (head) { printf(\"%d \", head->data); if (head->next) printf(\"->\"); head = head->next; } printf(\"\\n\");} // Function to rearrangevoid rearrange(struct Node** head, struct Node* last){ if (!last) return; // Recursive call rearrange(head, last->next); // (*head)->next will be set to NULL // after rearrangement. // Need not do any operation further // Just return here to come out of recursion if (!(*head)->next) return; // Rearrange the list until both head // and last meet or next to each other. if ((*head) != last && (*head)->next != last) { struct Node* tmp = (*head)->next; (*head)->next = last; last->next = tmp; *head = tmp; } else { if ((*head) != last) *head = (*head)->next; (*head)->next = NULL; }} // Drivers Codeint main(){ struct Node* head = newNode(1); head->next = newNode(2); head->next->next = newNode(3); head->next->next->next = newNode(4); head->next->next->next->next = newNode(5); // Print original list printlist(head); struct Node* tmp = head; // Modify the list rearrange(&tmp, head); // Print modified list printlist(head); return 0;}",
"e": 52349,
"s": 50686,
"text": null
},
{
"code": "// Java implementationimport java.io.*; // Creating the structure for nodeclass Node { int data; Node next; // Function to create newNode in a linkedlist Node(int key) { data = key; next = null; }}class GFG { Node left = null; // Function to print the list void printlist(Node head) { while (head != null) { System.out.print(head.data + \" \"); if (head.next != null) { System.out.print(\"->\"); } head = head.next; } System.out.println(); } // Function to rearrange void rearrange(Node head) { if (head != null) { left = head; reorderListUtil(left); } } void reorderListUtil(Node right) { if (right == null) { return; } reorderListUtil(right.next); // we set left = null, when we reach stop condition, // so no processing required after that if (left == null) { return; } // Stop condition: odd case : left = right, even // case : left.next = right if (left != right && left.next != right) { Node temp = left.next; left.next = right; right.next = temp; left = temp; } else { // stop condition , set null to left nodes if (left.next == right) { left.next.next = null; // even case left = null; } else { left.next = null; // odd case left = null; } } } // Drivers Code public static void main(String[] args) { Node head = new Node(1); head.next = new Node(2); head.next.next = new Node(3); head.next.next.next = new Node(4); head.next.next.next.next = new Node(5); GFG gfg = new GFG(); // Print original list gfg.printlist(head); // Modify the list gfg.rearrange(head); // Print modified list gfg.printlist(head); }} // This code is contributed by Vishal Singh",
"e": 54475,
"s": 52349,
"text": null
},
{
"code": "# Python3 implementationclass Node: def __init__(self, key): self.data = key self.next = None left = None # Function to print the listdef printlist(head): while (head != None): print(head.data, end = \" \") if (head.next != None): print(\"->\", end = \"\") head = head.next print() # Function to rearrangedef rearrange(head): global left if (head != None): left = head reorderListUtil(left) def reorderListUtil(right): global left if (right == None): return reorderListUtil(right.next) # We set left = null, when we reach stop # condition, so no processing required # after that if (left == None): return # Stop condition: odd case : left = right, even # case : left.next = right if (left != right and left.next != right): temp = left.next left.next = right right.next = temp left = temp else: # Stop condition , set null to left nodes if (left.next == right): # Even case left.next.next = None left = None else: # Odd case left.next = None left = None # Driver codehead = Node(1)head.next = Node(2)head.next.next = Node(3)head.next.next.next = Node(4)head.next.next.next.next = Node(5) # Print original listprintlist(head) # Modify the listrearrange(head) # Print modified listprintlist(head) # This code is contributed by patel2127",
"e": 56042,
"s": 54475,
"text": null
},
{
"code": "// C# implementationusing System; // Creating the structure for nodepublic class Node{ public int data; public Node next; // Function to create newNode // in a linkedlist public Node(int key) { data = key; next = null; }} class GFG{ Node left = null; // Function to print the listvoid printlist(Node head){ while (head != null) { Console.Write(head.data + \" \"); if (head.next != null) { Console.Write(\"->\"); } head = head.next; } Console.WriteLine();} // Function to rearrangevoid rearrange(Node head){ if (head != null) { left = head; reorderListUtil(left); }} void reorderListUtil(Node right){ if (right == null) { return; } reorderListUtil(right.next); // We set left = null, when we reach stop // condition, so no processing required // after that if (left == null) { return; } // Stop condition: odd case : left = right, even // case : left.next = right if (left != right && left.next != right) { Node temp = left.next; left.next = right; right.next = temp; left = temp; } else { // Stop condition , set null to left nodes if (left.next == right) { // Even case left.next.next = null; left = null; } else { // Odd case left.next = null; left = null; } }} // Driver Codestatic public void Main(){ Node head = new Node(1); head.next = new Node(2); head.next.next = new Node(3); head.next.next.next = new Node(4); head.next.next.next.next = new Node(5); GFG gfg = new GFG(); // Print original list gfg.printlist(head); // Modify the list gfg.rearrange(head); // Print modified list gfg.printlist(head);}} // This code is contributed by rag2127",
"e": 58014,
"s": 56042,
"text": null
},
{
"code": "<script>// javascript implementation// Creating the structure for nodeclass Node { // Function to create newNode in a linkedlist constructor(val) { this.data = val; this.next = null; }} var left = null; // Function to print the list function printlist(head) { while (head != null) { document.write(head.data + \" \"); if (head.next != null) { document.write(\"->\"); } head = head.next; } document.write(\"<br/>\"); } // Function to rearrange function rearrange(head) { if (head != null) { left = head; reorderListUtil(left); } } function reorderListUtil(right) { if (right == null) { return; } reorderListUtil(right.next); // we set left = null, when we reach stop condition, // so no processing required after that if (left == null) { return; } // Stop condition: odd case : left = right, even // case : left.next = right if (left != right && left.next != right) { var temp = left.next; left.next = right; right.next = temp; left = temp; } else { // stop condition , set null to left nodes if (left.next == right) { left.next.next = null; // even case left = null; } else { left.next = null; // odd case left = null; } } } // Drivers Code var head = new Node(1); head.next = new Node(2); head.next.next = new Node(3); head.next.next.next = new Node(4); head.next.next.next.next = new Node(5); // Print original list printlist(head); // Modify the list rearrange(head); // Print modified list printlist(head); // This code contributed by aashish1995</script>",
"e": 59961,
"s": 58014,
"text": null
},
{
"code": null,
"e": 59998,
"s": 59961,
"text": "1 ->2 ->3 ->4 ->5 \n1 ->5 ->2 ->4 ->3"
},
{
"code": null,
"e": 60125,
"s": 60000,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 60139,
"s": 60125,
"text": "Balraj Parmar"
},
{
"code": null,
"e": 60153,
"s": 60139,
"text": "princiraj1992"
},
{
"code": null,
"e": 60167,
"s": 60153,
"text": "kalaikarthick"
},
{
"code": null,
"e": 60178,
"s": 60167,
"text": "andrew1234"
},
{
"code": null,
"e": 60193,
"s": 60178,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 60203,
"s": 60193,
"text": "rutvik_56"
},
{
"code": null,
"e": 60224,
"s": 60203,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 60242,
"s": 60224,
"text": "singhvishal240891"
},
{
"code": null,
"e": 60250,
"s": 60242,
"text": "rag2127"
},
{
"code": null,
"e": 60262,
"s": 60250,
"text": "unknown2108"
},
{
"code": null,
"e": 60276,
"s": 60262,
"text": "GauravRajput1"
},
{
"code": null,
"e": 60288,
"s": 60276,
"text": "aashish1995"
},
{
"code": null,
"e": 60301,
"s": 60288,
"text": "Kirti_Mangal"
},
{
"code": null,
"e": 60308,
"s": 60301,
"text": "ab2127"
},
{
"code": null,
"e": 60318,
"s": 60308,
"text": "patel2127"
},
{
"code": null,
"e": 60325,
"s": 60318,
"text": "Amazon"
},
{
"code": null,
"e": 60337,
"s": 60325,
"text": "Linked List"
},
{
"code": null,
"e": 60344,
"s": 60337,
"text": "Amazon"
},
{
"code": null,
"e": 60356,
"s": 60344,
"text": "Linked List"
},
{
"code": null,
"e": 60454,
"s": 60356,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 60463,
"s": 60454,
"text": "Comments"
},
{
"code": null,
"e": 60476,
"s": 60463,
"text": "Old Comments"
},
{
"code": null,
"e": 60495,
"s": 60476,
"text": "LinkedList in Java"
},
{
"code": null,
"e": 60516,
"s": 60495,
"text": "Linked List vs Array"
},
{
"code": null,
"e": 60562,
"s": 60516,
"text": "Delete a Linked List node at a given position"
},
{
"code": null,
"e": 60597,
"s": 60562,
"text": "Queue - Linked List Implementation"
},
{
"code": null,
"e": 60640,
"s": 60597,
"text": "Implement a stack using singly linked list"
},
{
"code": null,
"e": 60687,
"s": 60640,
"text": "Implementing a Linked List in Java using Class"
},
{
"code": null,
"e": 60748,
"s": 60687,
"text": "Circular Linked List | Set 1 (Introduction and Applications)"
},
{
"code": null,
"e": 60792,
"s": 60748,
"text": "Remove duplicates from a sorted linked list"
},
{
"code": null,
"e": 60847,
"s": 60792,
"text": "Find Length of a Linked List (Iterative and Recursive)"
}
] |
Longest Common Prefix using Character by Character Matching - GeeksforGeeks | 08 Apr, 2021
Given a set of strings, find the longest common prefix.
Input : {“geeksforgeeks”, “geeks”, “geek”, “geezer”}
Output : "gee"
Input : {"apple", "ape", "april"}
Output : "ap"
We have discussed word by word matching algorithm in previous post.In this algorithm, instead of going through the strings one by one, we will go through the characters one by one. We consider our strings as – “geeksforgeeks”, “geeks”, “geek”, “geezer”.
Below is the implementation of this approach.
C++
Java
Python 3
C#
Javascript
// A C++ Program to find the longest common prefix#include<bits/stdc++.h>using namespace std; // A Function to find the string having the minimum// length and returns that lengthint findMinLength(string arr[], int n){ int min = arr[0].length(); for (int i=1; i<n; i++) if (arr[i].length() < min) min = arr[i].length(); return(min);} // A Function that returns the longest common prefix// from the array of stringsstring commonPrefix(string arr[], int n){ int minlen = findMinLength(arr, n); string result; // Our resultant string char current; // The current character for (int i=0; i<minlen; i++) { // Current character (must be same // in all strings to be a part of // result) current = arr[0][i]; for (int j=1 ; j<n; j++) if (arr[j][i] != current) return result; // Append to result result.push_back(current); } return (result);} // Driver program to test above functionint main(){ string arr[] = {"geeksforgeeks", "geeks", "geek", "geezer"}; int n = sizeof (arr) / sizeof (arr[0]); string ans = commonPrefix (arr, n); if (ans.length()) cout << "The longest common prefix is " << ans; else cout << "There is no common prefix"; return (0);}
// A Java Program to find the longest common prefixclass GFG{ // A Function to find the string having the minimum // length and returns that length static int findMinLength(String arr[], int n) { int min = arr[0].length(); for (int i = 1; i < n; i++) { if (arr[i].length() < min) { min = arr[i].length(); } } return (min); } // A Function that returns the longest common prefix // from the array of strings static String commonPrefix(String arr[], int n) { int minlen = findMinLength(arr, n); String result = ""; // Our resultant string char current; // The current character for (int i = 0; i < minlen; i++) { // Current character (must be same // in all strings to be a part of // result) current = arr[0].charAt(i); for (int j = 1; j < n; j++) { if (arr[j].charAt(i) != current) { return result; } } // Append to result result += (current); } return (result); } // Driver program to test above function public static void main(String[] args) { String arr[] = {"geeksforgeeks", "geeks", "geek", "geezer"}; int n = arr.length; String ans = commonPrefix(arr, n); if (ans.length() > 0) { System.out.println("The longest common prefix is " + ans); } else { System.out.println("There is no common prefix"); } }} // This code contributed by Rajput-Ji
# Python 3 Program to find the longest common prefix # A Function to find the string having the minimum# length and returns that lengthdef findMinLength(arr, n): min = len(arr[0]) for i in range(1,n): if (len(arr[i])< min): min = len(arr[i]) return(min) # A Function that returns the longest common prefix# from the array of stringsdef commonPrefix(arr, n): minlen = findMinLength(arr, n) result ="" for i in range(minlen): # Current character (must be same # in all strings to be a part of # result) current = arr[0][i] for j in range(1,n): if (arr[j][i] != current): return result # Append to result result = result+current return (result) # Driver program to test above functionif __name__ == "__main__": arr = ["geeksforgeeks", "geeks", "geek", "geezer"] n = len(arr) ans = commonPrefix (arr, n) if (len(ans)): print("The longest common prefix is ",ans) else: print("There is no common prefix")
// A C# Program to find the longest common prefixusing System; class GFG{ // A Function to find the string having the minimum // length and returns that length static int findMinLength(String []arr, int n) { int min = arr[0].Length; for (int i = 1; i < n; i++) { if (arr[i].Length < min) { min = arr[i].Length; } } return (min); } // A Function that returns the longest common prefix // from the array of strings static String commonPrefix(String []arr, int n) { int minlen = findMinLength(arr, n); String result = ""; // Our resultant string char current; // The current character for (int i = 0; i < minlen; i++) { // Current character (must be same // in all strings to be a part of // result) current = arr[0][i]; for (int j = 1; j < n; j++) { if (arr[j][i] != current) { return result; } } // Append to result result += (current); } return (result); } // Driver code public static void Main(String[] args) { String []arr = {"geeksforgeeks", "geeks", "geek", "geezer"}; int n = arr.Length; String ans = commonPrefix(arr, n); if (ans.Length > 0) { Console.WriteLine("The longest common prefix is " + ans); } else { Console.WriteLine("There is no common prefix"); } }} /* This code contributed by PrinciRaj1992 */
<script>// A Javascript Program to find the longest common prefix // A Function to find the string having the minimum // length and returns that length function findMinLength(arr,n) { let min = arr[0].length; for (let i = 1; i < n; i++) { if (arr[i].length < min) { min = arr[i].length; } } return (min); } // A Function that returns the longest common prefix // from the array of strings function commonPrefix(arr,n) { let minlen = findMinLength(arr, n); let result = ""; // Our resultant string let current; // The current character for (let i = 0; i < minlen; i++) { // Current character (must be same // in all strings to be a part of // result) current = arr[0][i]; for (let j = 1; j < n; j++) { if (arr[j][i] != current) { return result; } } // Append to result result += (current); } return (result); } // Driver program to test above function let arr=["geeksforgeeks", "geeks", "geek", "geezer"] let n = arr.length; let ans = commonPrefix(arr, n); if (ans.length > 0) { document.write("The longest common prefix is " + ans); } else { document.write("There is no common prefix"); } // This code is contributed by avanitrachhadiya2155</script>
Output :
The longest common prefix is gee
How is this algorithm better than the “Word by Word Matching” algorithm ?-In Set 1 we discussed about the “Word by Word Matching” Algorithm. Suppose you have the input strings as- “geeksforgeeks”, “geeks”, “geek”, “geezer”, “x”.Now there is no common prefix string of the above strings. By the “Word by Word Matching” algorithm discussed in Set 1, we come to the conclusion that there is no common prefix string by traversing all the strings. But if we use this algorithm, then in the first iteration itself we will come to know that there is no common prefix string, as we don’t go further to look for the second character of each strings. This algorithm has a huge advantage when there are too many strings. Time Complexity : Since we are iterating through all the characters of all the strings, so we can say that the time complexity is O(N M) where,
N = Number of strings
M = Length of the largest string string
Auxiliary Space : To store the longest prefix string we are allocating space which is O(M).This article is contributed by Rachit Belwariar. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
ukasp
Rajput-Ji
princiraj1992
avanitrachhadiya2155
Longest Common Prefix
VMWare
Arrays
Strings
VMWare
Arrays
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Stack Data Structure (Introduction and Program)
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Introduction to Arrays
Reverse a string in Java
Longest Common Subsequence | DP-4
Write a program to print all permutations of a given string
C++ Data Types
Check for Balanced Brackets in an expression (well-formedness) using Stack | [
{
"code": null,
"e": 24732,
"s": 24704,
"text": "\n08 Apr, 2021"
},
{
"code": null,
"e": 24789,
"s": 24732,
"text": "Given a set of strings, find the longest common prefix. "
},
{
"code": null,
"e": 24908,
"s": 24789,
"text": "Input : {“geeksforgeeks”, “geeks”, “geek”, “geezer”}\nOutput : \"gee\"\n\nInput : {\"apple\", \"ape\", \"april\"}\nOutput : \"ap\""
},
{
"code": null,
"e": 25165,
"s": 24910,
"text": "We have discussed word by word matching algorithm in previous post.In this algorithm, instead of going through the strings one by one, we will go through the characters one by one. We consider our strings as – “geeksforgeeks”, “geeks”, “geek”, “geezer”. "
},
{
"code": null,
"e": 25218,
"s": 25171,
"text": "Below is the implementation of this approach. "
},
{
"code": null,
"e": 25222,
"s": 25218,
"text": "C++"
},
{
"code": null,
"e": 25227,
"s": 25222,
"text": "Java"
},
{
"code": null,
"e": 25236,
"s": 25227,
"text": "Python 3"
},
{
"code": null,
"e": 25239,
"s": 25236,
"text": "C#"
},
{
"code": null,
"e": 25250,
"s": 25239,
"text": "Javascript"
},
{
"code": "// A C++ Program to find the longest common prefix#include<bits/stdc++.h>using namespace std; // A Function to find the string having the minimum// length and returns that lengthint findMinLength(string arr[], int n){ int min = arr[0].length(); for (int i=1; i<n; i++) if (arr[i].length() < min) min = arr[i].length(); return(min);} // A Function that returns the longest common prefix// from the array of stringsstring commonPrefix(string arr[], int n){ int minlen = findMinLength(arr, n); string result; // Our resultant string char current; // The current character for (int i=0; i<minlen; i++) { // Current character (must be same // in all strings to be a part of // result) current = arr[0][i]; for (int j=1 ; j<n; j++) if (arr[j][i] != current) return result; // Append to result result.push_back(current); } return (result);} // Driver program to test above functionint main(){ string arr[] = {\"geeksforgeeks\", \"geeks\", \"geek\", \"geezer\"}; int n = sizeof (arr) / sizeof (arr[0]); string ans = commonPrefix (arr, n); if (ans.length()) cout << \"The longest common prefix is \" << ans; else cout << \"There is no common prefix\"; return (0);}",
"e": 26591,
"s": 25250,
"text": null
},
{
"code": "// A Java Program to find the longest common prefixclass GFG{ // A Function to find the string having the minimum // length and returns that length static int findMinLength(String arr[], int n) { int min = arr[0].length(); for (int i = 1; i < n; i++) { if (arr[i].length() < min) { min = arr[i].length(); } } return (min); } // A Function that returns the longest common prefix // from the array of strings static String commonPrefix(String arr[], int n) { int minlen = findMinLength(arr, n); String result = \"\"; // Our resultant string char current; // The current character for (int i = 0; i < minlen; i++) { // Current character (must be same // in all strings to be a part of // result) current = arr[0].charAt(i); for (int j = 1; j < n; j++) { if (arr[j].charAt(i) != current) { return result; } } // Append to result result += (current); } return (result); } // Driver program to test above function public static void main(String[] args) { String arr[] = {\"geeksforgeeks\", \"geeks\", \"geek\", \"geezer\"}; int n = arr.length; String ans = commonPrefix(arr, n); if (ans.length() > 0) { System.out.println(\"The longest common prefix is \" + ans); } else { System.out.println(\"There is no common prefix\"); } }} // This code contributed by Rajput-Ji",
"e": 28281,
"s": 26591,
"text": null
},
{
"code": "# Python 3 Program to find the longest common prefix # A Function to find the string having the minimum# length and returns that lengthdef findMinLength(arr, n): min = len(arr[0]) for i in range(1,n): if (len(arr[i])< min): min = len(arr[i]) return(min) # A Function that returns the longest common prefix# from the array of stringsdef commonPrefix(arr, n): minlen = findMinLength(arr, n) result =\"\" for i in range(minlen): # Current character (must be same # in all strings to be a part of # result) current = arr[0][i] for j in range(1,n): if (arr[j][i] != current): return result # Append to result result = result+current return (result) # Driver program to test above functionif __name__ == \"__main__\": arr = [\"geeksforgeeks\", \"geeks\", \"geek\", \"geezer\"] n = len(arr) ans = commonPrefix (arr, n) if (len(ans)): print(\"The longest common prefix is \",ans) else: print(\"There is no common prefix\")",
"e": 29371,
"s": 28281,
"text": null
},
{
"code": "// A C# Program to find the longest common prefixusing System; class GFG{ // A Function to find the string having the minimum // length and returns that length static int findMinLength(String []arr, int n) { int min = arr[0].Length; for (int i = 1; i < n; i++) { if (arr[i].Length < min) { min = arr[i].Length; } } return (min); } // A Function that returns the longest common prefix // from the array of strings static String commonPrefix(String []arr, int n) { int minlen = findMinLength(arr, n); String result = \"\"; // Our resultant string char current; // The current character for (int i = 0; i < minlen; i++) { // Current character (must be same // in all strings to be a part of // result) current = arr[0][i]; for (int j = 1; j < n; j++) { if (arr[j][i] != current) { return result; } } // Append to result result += (current); } return (result); } // Driver code public static void Main(String[] args) { String []arr = {\"geeksforgeeks\", \"geeks\", \"geek\", \"geezer\"}; int n = arr.Length; String ans = commonPrefix(arr, n); if (ans.Length > 0) { Console.WriteLine(\"The longest common prefix is \" + ans); } else { Console.WriteLine(\"There is no common prefix\"); } }} /* This code contributed by PrinciRaj1992 */",
"e": 31055,
"s": 29371,
"text": null
},
{
"code": "<script>// A Javascript Program to find the longest common prefix // A Function to find the string having the minimum // length and returns that length function findMinLength(arr,n) { let min = arr[0].length; for (let i = 1; i < n; i++) { if (arr[i].length < min) { min = arr[i].length; } } return (min); } // A Function that returns the longest common prefix // from the array of strings function commonPrefix(arr,n) { let minlen = findMinLength(arr, n); let result = \"\"; // Our resultant string let current; // The current character for (let i = 0; i < minlen; i++) { // Current character (must be same // in all strings to be a part of // result) current = arr[0][i]; for (let j = 1; j < n; j++) { if (arr[j][i] != current) { return result; } } // Append to result result += (current); } return (result); } // Driver program to test above function let arr=[\"geeksforgeeks\", \"geeks\", \"geek\", \"geezer\"] let n = arr.length; let ans = commonPrefix(arr, n); if (ans.length > 0) { document.write(\"The longest common prefix is \" + ans); } else { document.write(\"There is no common prefix\"); } // This code is contributed by avanitrachhadiya2155</script>",
"e": 32628,
"s": 31055,
"text": null
},
{
"code": null,
"e": 32638,
"s": 32628,
"text": "Output : "
},
{
"code": null,
"e": 32672,
"s": 32638,
"text": "The longest common prefix is gee"
},
{
"code": null,
"e": 33527,
"s": 32672,
"text": "How is this algorithm better than the “Word by Word Matching” algorithm ?-In Set 1 we discussed about the “Word by Word Matching” Algorithm. Suppose you have the input strings as- “geeksforgeeks”, “geeks”, “geek”, “geezer”, “x”.Now there is no common prefix string of the above strings. By the “Word by Word Matching” algorithm discussed in Set 1, we come to the conclusion that there is no common prefix string by traversing all the strings. But if we use this algorithm, then in the first iteration itself we will come to know that there is no common prefix string, as we don’t go further to look for the second character of each strings. This algorithm has a huge advantage when there are too many strings. Time Complexity : Since we are iterating through all the characters of all the strings, so we can say that the time complexity is O(N M) where, "
},
{
"code": null,
"e": 33590,
"s": 33527,
"text": "N = Number of strings\nM = Length of the largest string string "
},
{
"code": null,
"e": 34075,
"s": 33590,
"text": "Auxiliary Space : To store the longest prefix string we are allocating space which is O(M).This article is contributed by Rachit Belwariar. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 34081,
"s": 34075,
"text": "ukasp"
},
{
"code": null,
"e": 34091,
"s": 34081,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 34105,
"s": 34091,
"text": "princiraj1992"
},
{
"code": null,
"e": 34126,
"s": 34105,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 34148,
"s": 34126,
"text": "Longest Common Prefix"
},
{
"code": null,
"e": 34155,
"s": 34148,
"text": "VMWare"
},
{
"code": null,
"e": 34162,
"s": 34155,
"text": "Arrays"
},
{
"code": null,
"e": 34170,
"s": 34162,
"text": "Strings"
},
{
"code": null,
"e": 34177,
"s": 34170,
"text": "VMWare"
},
{
"code": null,
"e": 34184,
"s": 34177,
"text": "Arrays"
},
{
"code": null,
"e": 34192,
"s": 34184,
"text": "Strings"
},
{
"code": null,
"e": 34290,
"s": 34192,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34358,
"s": 34290,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 34406,
"s": 34358,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 34450,
"s": 34406,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 34482,
"s": 34450,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 34505,
"s": 34482,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 34530,
"s": 34505,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 34564,
"s": 34530,
"text": "Longest Common Subsequence | DP-4"
},
{
"code": null,
"e": 34624,
"s": 34564,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 34639,
"s": 34624,
"text": "C++ Data Types"
}
] |
scipy stats.genpareto() | Python - GeeksforGeeks | 27 Mar, 2019
scipy.stats.genpareto() is an generalized Pareto continuous random variable that is defined with a standard format and some shape parameters to complete its specification.
Parameters :-> q : lower and upper tail probability-> a, b : shape parameters-> x : quantiles-> loc : [optional]location parameter. Default = 0-> scale : [optional]scale parameter. Default = 1-> size : [tuple of ints, optional] shape or random variates.-> moments : [optional] composed of letters [‘mvsk’]; ‘m’ = mean, ‘v’ = variance, ‘s’ = Fisher’s skew and ‘k’ = Fisher’s kurtosis. (default = ‘mv’).
Results : generalized Pareto continuous random variable
Code #1 : Creating generalized Pareto continuous random variable
from scipy.stats import genpareto numargs = genpareto .numargs[a] = [0.7, ] * numargsrv = genpareto (a) print ("RV : \n", rv)
Output :
RV :
<scipy.stats._distn_infrastructure.rv_frozen object at 0x0000018D579B85C0>
Code #2 : generalized Pareto random variates.
import numpy as npquantile = np.arange (0.01, 1, 0.1) # Random VariatesR = genpareto.rvs(a, scale = 2, size = 10)print ("Random Variates : \n", R)
Output :
Random Variates :
[ 1.55978773 0.03897083 7.68148511 0.78339525 1.1217962 0.20434352
1.16663003 2.06115353 12.82886098 0.27780119]
Code #3 : Graphical Representation.
import numpy as npimport matplotlib.pyplot as plt distribution = np.linspace(0, np.minimum(rv.dist.b, 3))print("Distribution : \n", distribution) plot = plt.plot(distribution, rv.pdf(distribution))
Output :
Distribution :
[0. 0.06122449 0.12244898 0.18367347 0.24489796 0.30612245
0.36734694 0.42857143 0.48979592 0.55102041 0.6122449 0.67346939
0.73469388 0.79591837 0.85714286 0.91836735 0.97959184 1.04081633
1.10204082 1.16326531 1.2244898 1.28571429 1.34693878 1.40816327
1.46938776 1.53061224 1.59183673 1.65306122 1.71428571 1.7755102
1.83673469 1.89795918 1.95918367 2.02040816 2.08163265 2.14285714
2.20408163 2.26530612 2.32653061 2.3877551 2.44897959 2.51020408
2.57142857 2.63265306 2.69387755 2.75510204 2.81632653 2.87755102
2.93877551 3. ]
Code #4 : Varying Positional Arguments
import matplotlib.pyplot as pltimport numpy as np x = np.linspace(0, 5, 100) # Varying positional argumentsy1 = genpareto.pdf(x, 1, 3)y2 = genpareto.pdf(x, 1, 4)plt.plot(x, y1, "*", x, y2, "r--")
Output :
Python scipy-stats-functions
Python-scipy
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
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python | [
{
"code": null,
"e": 24188,
"s": 24160,
"text": "\n27 Mar, 2019"
},
{
"code": null,
"e": 24360,
"s": 24188,
"text": "scipy.stats.genpareto() is an generalized Pareto continuous random variable that is defined with a standard format and some shape parameters to complete its specification."
},
{
"code": null,
"e": 24762,
"s": 24360,
"text": "Parameters :-> q : lower and upper tail probability-> a, b : shape parameters-> x : quantiles-> loc : [optional]location parameter. Default = 0-> scale : [optional]scale parameter. Default = 1-> size : [tuple of ints, optional] shape or random variates.-> moments : [optional] composed of letters [‘mvsk’]; ‘m’ = mean, ‘v’ = variance, ‘s’ = Fisher’s skew and ‘k’ = Fisher’s kurtosis. (default = ‘mv’)."
},
{
"code": null,
"e": 24818,
"s": 24762,
"text": "Results : generalized Pareto continuous random variable"
},
{
"code": null,
"e": 24883,
"s": 24818,
"text": "Code #1 : Creating generalized Pareto continuous random variable"
},
{
"code": "from scipy.stats import genpareto numargs = genpareto .numargs[a] = [0.7, ] * numargsrv = genpareto (a) print (\"RV : \\n\", rv) ",
"e": 25013,
"s": 24883,
"text": null
},
{
"code": null,
"e": 25022,
"s": 25013,
"text": "Output :"
},
{
"code": null,
"e": 25105,
"s": 25022,
"text": "RV : \n <scipy.stats._distn_infrastructure.rv_frozen object at 0x0000018D579B85C0>\n"
},
{
"code": null,
"e": 25151,
"s": 25105,
"text": "Code #2 : generalized Pareto random variates."
},
{
"code": "import numpy as npquantile = np.arange (0.01, 1, 0.1) # Random VariatesR = genpareto.rvs(a, scale = 2, size = 10)print (\"Random Variates : \\n\", R)",
"e": 25301,
"s": 25151,
"text": null
},
{
"code": null,
"e": 25310,
"s": 25301,
"text": "Output :"
},
{
"code": null,
"e": 25453,
"s": 25310,
"text": "Random Variates : \n [ 1.55978773 0.03897083 7.68148511 0.78339525 1.1217962 0.20434352\n 1.16663003 2.06115353 12.82886098 0.27780119]"
},
{
"code": null,
"e": 25489,
"s": 25453,
"text": "Code #3 : Graphical Representation."
},
{
"code": "import numpy as npimport matplotlib.pyplot as plt distribution = np.linspace(0, np.minimum(rv.dist.b, 3))print(\"Distribution : \\n\", distribution) plot = plt.plot(distribution, rv.pdf(distribution))",
"e": 25689,
"s": 25489,
"text": null
},
{
"code": null,
"e": 25698,
"s": 25689,
"text": "Output :"
},
{
"code": null,
"e": 26274,
"s": 25698,
"text": "Distribution : \n [0. 0.06122449 0.12244898 0.18367347 0.24489796 0.30612245\n 0.36734694 0.42857143 0.48979592 0.55102041 0.6122449 0.67346939\n 0.73469388 0.79591837 0.85714286 0.91836735 0.97959184 1.04081633\n 1.10204082 1.16326531 1.2244898 1.28571429 1.34693878 1.40816327\n 1.46938776 1.53061224 1.59183673 1.65306122 1.71428571 1.7755102\n 1.83673469 1.89795918 1.95918367 2.02040816 2.08163265 2.14285714\n 2.20408163 2.26530612 2.32653061 2.3877551 2.44897959 2.51020408\n 2.57142857 2.63265306 2.69387755 2.75510204 2.81632653 2.87755102\n 2.93877551 3. ]"
},
{
"code": null,
"e": 26313,
"s": 26274,
"text": "Code #4 : Varying Positional Arguments"
},
{
"code": "import matplotlib.pyplot as pltimport numpy as np x = np.linspace(0, 5, 100) # Varying positional argumentsy1 = genpareto.pdf(x, 1, 3)y2 = genpareto.pdf(x, 1, 4)plt.plot(x, y1, \"*\", x, y2, \"r--\")",
"e": 26511,
"s": 26313,
"text": null
},
{
"code": null,
"e": 26520,
"s": 26511,
"text": "Output :"
},
{
"code": null,
"e": 26549,
"s": 26520,
"text": "Python scipy-stats-functions"
},
{
"code": null,
"e": 26562,
"s": 26549,
"text": "Python-scipy"
},
{
"code": null,
"e": 26569,
"s": 26562,
"text": "Python"
},
{
"code": null,
"e": 26667,
"s": 26569,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26676,
"s": 26667,
"text": "Comments"
},
{
"code": null,
"e": 26689,
"s": 26676,
"text": "Old Comments"
},
{
"code": null,
"e": 26707,
"s": 26689,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26742,
"s": 26707,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 26764,
"s": 26742,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 26796,
"s": 26764,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26826,
"s": 26796,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 26868,
"s": 26826,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 26894,
"s": 26868,
"text": "Python String | replace()"
},
{
"code": null,
"e": 26937,
"s": 26894,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 26974,
"s": 26937,
"text": "Create a Pandas DataFrame from Lists"
}
] |
Check if Pascal's Triangle is possible with a complete layer by using numbers upto N - GeeksforGeeks | 05 Apr, 2021
Given a number N, the task is to determine if it is possible to make Pascal’s triangle with a complete layer by using total number N integer if possible print Yes otherwise print No.
Note: Pascal’s triangle is a triangular array of the binomial coefficients. Following are the first 6 rows of Pascal’s Triangle.
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
In Pascal’s Triangle from the topmost layer there is 1 integer, at every next layer from top to bottom size of the layer increased by 1.
Examples:
Input: N = 10Output: YesExplanation: You can use 1, 2, 3 and 4 integers to make first, second, third, and fourth layer of pascal’s triangle respectively and also N = 10 satisfy by using (1 + 2 + 3 + 4) integers on each layer = 10.Input: N = 5 Output: NoExplanation: You can use 1 and 2 integers to make first and second layer respectively and after that you have only 2 integers left and you can’t make 3rd layer complete as that layer required 3 integers.
Approach: Here we are using integer 1, 2, 3, ... on every layer starting from first layer, so we can only make Pascal’s triangle complete if it’s possible to represent N by the sum of 1 + 2 +...
The sum of first X integers is given by
The sum of first X integers is given by
We can only make pascal’s triangle by using N integers if and only if where X must be a positive integer. So we have to check is there any positive integer value of x exist or not.To determine value of X from second step we can deduced the formula as:
We can only make pascal’s triangle by using N integers if and only if where X must be a positive integer. So we have to check is there any positive integer value of x exist or not.
To determine value of X from second step we can deduced the formula as:
If the value of X integer for the given value of N then we can make Pascal Triangle. Otherwise, we can’t make Pascal Triangle.
If the value of X integer for the given value of N then we can make Pascal Triangle. Otherwise, we can’t make Pascal Triangle.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to check if Pascaltriangle// can be made by N integersvoid checkPascaltriangle(int N){ // Find X double x = (sqrt(8 * N + 1) - 1) / 2; // If x is integer if (ceil(x) - x == 0) cout << "Yes"; else cout << "No";} // Driver Codeint main(){ // Given number N int N = 10; // Function Call checkPascaltriangle(N); return 0;}
// Java program for the above approachclass GFG{ // Function to check if Pascaltriangle// can be made by N integersstatic void checkPascaltriangle(int N){ // Find X double x = (Math.sqrt(8 * N + 1) - 1) / 2; // If x is integer if (Math.ceil(x) - x == 0) System.out.print("Yes"); else System.out.print("No");} // Driver Codepublic static void main(String[] args){ // Given number N int N = 10; // Function call checkPascaltriangle(N);}} // This code is contributed by amal kumar choubey
# Python3 program for the above approachimport math # Function to check if Pascaltriangle# can be made by N integersdef checkPascaltriangle(N): # Find X x = (math.sqrt(8 * N + 1) - 1) / 2 # If x is integer if (math.ceil(x) - x == 0): print("Yes") else: print("No") # Driver Code # Given number NN = 10 # Function callcheckPascaltriangle(N) # This code is contributed by sanjoy_62
// C# program for the above approachusing System; class GFG{ // Function to check if Pascaltriangle// can be made by N integersstatic void checkPascaltriangle(int N){ // Find X double x = (Math.Sqrt(8 * N + 1) - 1) / 2; // If x is integer if (Math.Ceiling(x) - x == 0) Console.Write("Yes"); else Console.Write("No");} // Driver Codepublic static void Main(String[] args){ // Given number N int N = 10; // Function call checkPascaltriangle(N);}} // This code is contributed by amal kumar choubey
<script> // JavaScript program for the above approach // Function to check if Pascaltriangle // can be made by N integers function checkPascaltriangle(N) { // Find X var x = (Math.sqrt(8 * N + 1) - 1) / 2; // If x is integer if (Math.ceil(x) - x == 0) document.write("Yes"); else document.write("No"); } // Driver Code // Given number N var N = 10; // Function Call checkPascaltriangle(N); </script>
Yes
Time Complexity: O(sqrt(N)) Auxiliary Space: O(1)
Amal Kumar Choubey
sanjoy_62
rdtank
pattern-printing
Analysis
Competitive Programming
Mathematical
Pattern Searching
Mathematical
pattern-printing
Pattern Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Understanding Time Complexity with Simple Examples
Time Complexity and Space Complexity
Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
Time Complexity of building a heap
Analysis of different sorting techniques
Competitive Programming - A Complete Guide
Practice for cracking any coding interview
Arrow operator -> in C/C++ with Examples
Top 15 Websites for Coding Challenges and Competitions
Modulo 10^9+7 (1000000007) | [
{
"code": null,
"e": 25344,
"s": 25316,
"text": "\n05 Apr, 2021"
},
{
"code": null,
"e": 25527,
"s": 25344,
"text": "Given a number N, the task is to determine if it is possible to make Pascal’s triangle with a complete layer by using total number N integer if possible print Yes otherwise print No."
},
{
"code": null,
"e": 25658,
"s": 25527,
"text": "Note: Pascal’s triangle is a triangular array of the binomial coefficients. Following are the first 6 rows of Pascal’s Triangle. "
},
{
"code": null,
"e": 25709,
"s": 25658,
"text": "1 \n1 1 \n1 2 1 \n1 3 3 1 \n1 4 6 4 1 \n1 5 10 10 5 1 "
},
{
"code": null,
"e": 25846,
"s": 25709,
"text": "In Pascal’s Triangle from the topmost layer there is 1 integer, at every next layer from top to bottom size of the layer increased by 1."
},
{
"code": null,
"e": 25856,
"s": 25846,
"text": "Examples:"
},
{
"code": null,
"e": 26313,
"s": 25856,
"text": "Input: N = 10Output: YesExplanation: You can use 1, 2, 3 and 4 integers to make first, second, third, and fourth layer of pascal’s triangle respectively and also N = 10 satisfy by using (1 + 2 + 3 + 4) integers on each layer = 10.Input: N = 5 Output: NoExplanation: You can use 1 and 2 integers to make first and second layer respectively and after that you have only 2 integers left and you can’t make 3rd layer complete as that layer required 3 integers."
},
{
"code": null,
"e": 26508,
"s": 26313,
"text": "Approach: Here we are using integer 1, 2, 3, ... on every layer starting from first layer, so we can only make Pascal’s triangle complete if it’s possible to represent N by the sum of 1 + 2 +..."
},
{
"code": null,
"e": 26550,
"s": 26508,
"text": "The sum of first X integers is given by "
},
{
"code": null,
"e": 26592,
"s": 26550,
"text": "The sum of first X integers is given by "
},
{
"code": null,
"e": 26846,
"s": 26592,
"text": "We can only make pascal’s triangle by using N integers if and only if where X must be a positive integer. So we have to check is there any positive integer value of x exist or not.To determine value of X from second step we can deduced the formula as: "
},
{
"code": null,
"e": 27027,
"s": 26846,
"text": "We can only make pascal’s triangle by using N integers if and only if where X must be a positive integer. So we have to check is there any positive integer value of x exist or not."
},
{
"code": null,
"e": 27101,
"s": 27027,
"text": "To determine value of X from second step we can deduced the formula as: "
},
{
"code": null,
"e": 27228,
"s": 27101,
"text": "If the value of X integer for the given value of N then we can make Pascal Triangle. Otherwise, we can’t make Pascal Triangle."
},
{
"code": null,
"e": 27355,
"s": 27228,
"text": "If the value of X integer for the given value of N then we can make Pascal Triangle. Otherwise, we can’t make Pascal Triangle."
},
{
"code": null,
"e": 27407,
"s": 27355,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 27411,
"s": 27407,
"text": "C++"
},
{
"code": null,
"e": 27416,
"s": 27411,
"text": "Java"
},
{
"code": null,
"e": 27424,
"s": 27416,
"text": "Python3"
},
{
"code": null,
"e": 27427,
"s": 27424,
"text": "C#"
},
{
"code": null,
"e": 27438,
"s": 27427,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to check if Pascaltriangle// can be made by N integersvoid checkPascaltriangle(int N){ // Find X double x = (sqrt(8 * N + 1) - 1) / 2; // If x is integer if (ceil(x) - x == 0) cout << \"Yes\"; else cout << \"No\";} // Driver Codeint main(){ // Given number N int N = 10; // Function Call checkPascaltriangle(N); return 0;}",
"e": 27898,
"s": 27438,
"text": null
},
{
"code": "// Java program for the above approachclass GFG{ // Function to check if Pascaltriangle// can be made by N integersstatic void checkPascaltriangle(int N){ // Find X double x = (Math.sqrt(8 * N + 1) - 1) / 2; // If x is integer if (Math.ceil(x) - x == 0) System.out.print(\"Yes\"); else System.out.print(\"No\");} // Driver Codepublic static void main(String[] args){ // Given number N int N = 10; // Function call checkPascaltriangle(N);}} // This code is contributed by amal kumar choubey",
"e": 28437,
"s": 27898,
"text": null
},
{
"code": "# Python3 program for the above approachimport math # Function to check if Pascaltriangle# can be made by N integersdef checkPascaltriangle(N): # Find X x = (math.sqrt(8 * N + 1) - 1) / 2 # If x is integer if (math.ceil(x) - x == 0): print(\"Yes\") else: print(\"No\") # Driver Code # Given number NN = 10 # Function callcheckPascaltriangle(N) # This code is contributed by sanjoy_62",
"e": 28852,
"s": 28437,
"text": null
},
{
"code": "// C# program for the above approachusing System; class GFG{ // Function to check if Pascaltriangle// can be made by N integersstatic void checkPascaltriangle(int N){ // Find X double x = (Math.Sqrt(8 * N + 1) - 1) / 2; // If x is integer if (Math.Ceiling(x) - x == 0) Console.Write(\"Yes\"); else Console.Write(\"No\");} // Driver Codepublic static void Main(String[] args){ // Given number N int N = 10; // Function call checkPascaltriangle(N);}} // This code is contributed by amal kumar choubey",
"e": 29400,
"s": 28852,
"text": null
},
{
"code": "<script> // JavaScript program for the above approach // Function to check if Pascaltriangle // can be made by N integers function checkPascaltriangle(N) { // Find X var x = (Math.sqrt(8 * N + 1) - 1) / 2; // If x is integer if (Math.ceil(x) - x == 0) document.write(\"Yes\"); else document.write(\"No\"); } // Driver Code // Given number N var N = 10; // Function Call checkPascaltriangle(N); </script>",
"e": 29915,
"s": 29400,
"text": null
},
{
"code": null,
"e": 29919,
"s": 29915,
"text": "Yes"
},
{
"code": null,
"e": 29972,
"s": 29921,
"text": "Time Complexity: O(sqrt(N)) Auxiliary Space: O(1) "
},
{
"code": null,
"e": 29991,
"s": 29972,
"text": "Amal Kumar Choubey"
},
{
"code": null,
"e": 30001,
"s": 29991,
"text": "sanjoy_62"
},
{
"code": null,
"e": 30008,
"s": 30001,
"text": "rdtank"
},
{
"code": null,
"e": 30025,
"s": 30008,
"text": "pattern-printing"
},
{
"code": null,
"e": 30034,
"s": 30025,
"text": "Analysis"
},
{
"code": null,
"e": 30058,
"s": 30034,
"text": "Competitive Programming"
},
{
"code": null,
"e": 30071,
"s": 30058,
"text": "Mathematical"
},
{
"code": null,
"e": 30089,
"s": 30071,
"text": "Pattern Searching"
},
{
"code": null,
"e": 30102,
"s": 30089,
"text": "Mathematical"
},
{
"code": null,
"e": 30119,
"s": 30102,
"text": "pattern-printing"
},
{
"code": null,
"e": 30137,
"s": 30119,
"text": "Pattern Searching"
},
{
"code": null,
"e": 30235,
"s": 30137,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30286,
"s": 30235,
"text": "Understanding Time Complexity with Simple Examples"
},
{
"code": null,
"e": 30323,
"s": 30286,
"text": "Time Complexity and Space Complexity"
},
{
"code": null,
"e": 30406,
"s": 30323,
"text": "Complexity of different operations in Binary tree, Binary Search Tree and AVL tree"
},
{
"code": null,
"e": 30441,
"s": 30406,
"text": "Time Complexity of building a heap"
},
{
"code": null,
"e": 30482,
"s": 30441,
"text": "Analysis of different sorting techniques"
},
{
"code": null,
"e": 30525,
"s": 30482,
"text": "Competitive Programming - A Complete Guide"
},
{
"code": null,
"e": 30568,
"s": 30525,
"text": "Practice for cracking any coding interview"
},
{
"code": null,
"e": 30609,
"s": 30568,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 30664,
"s": 30609,
"text": "Top 15 Websites for Coding Challenges and Competitions"
}
] |
How to find if element exists in document - MongoDB? | To find if element exists in a MongoDB document, use MongoDB $exists. Let us create a
collection with documents −
> db.demo497.insertOne({"details":[{"Name":"Chris"},{"Name":"Bob"}]});{
"acknowledged" : true,
"insertedId" : ObjectId("5e84b3cfb0f3fa88e22790d1")
}
> db.demo497.insertOne({"details":[{"Name":"Carol"}]});{
"acknowledged" : true,
"insertedId" : ObjectId("5e84b3d9b0f3fa88e22790d2")
}
> db.demo497.insertOne({"details":[{}]});{
"acknowledged" : true,
"insertedId" : ObjectId("5e84b3e9b0f3fa88e22790d3")
}
Display all documents from a collection with the help of find() method −
> db.demo497.find();
This will produce the following output −
{ "_id" : ObjectId("5e84b3cfb0f3fa88e22790d1"), "details" : [ { "Name" : "Chris" }, { "Name" : "Bob" } ] }
{ "_id" : ObjectId("5e84b3d9b0f3fa88e22790d2"), "details" : [ { "Name" : "Carol" } ] }
{ "_id" : ObjectId("5e84b3e9b0f3fa88e22790d3"), "details" : [ { } ] }
Following is the query to find if element exists in a document −
> db.demo497.find({$or:[
... {"details.Name" : {$ne : "Carol"}},
... {details: {$exists: false}}
... ]
... });
This will produce the following output −
{ "_id" : ObjectId("5e84b3cfb0f3fa88e22790d1"), "details" : [ { "Name" : "Chris" }, { "Name" : "Bob" } ] }
{ "_id" : ObjectId("5e84b3e9b0f3fa88e22790d3"), "details" : [ { } ] } | [
{
"code": null,
"e": 1176,
"s": 1062,
"text": "To find if element exists in a MongoDB document, use MongoDB $exists. Let us create a\ncollection with documents −"
},
{
"code": null,
"e": 1597,
"s": 1176,
"text": "> db.demo497.insertOne({\"details\":[{\"Name\":\"Chris\"},{\"Name\":\"Bob\"}]});{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e84b3cfb0f3fa88e22790d1\")\n}\n> db.demo497.insertOne({\"details\":[{\"Name\":\"Carol\"}]});{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e84b3d9b0f3fa88e22790d2\")\n}\n> db.demo497.insertOne({\"details\":[{}]});{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e84b3e9b0f3fa88e22790d3\")\n}"
},
{
"code": null,
"e": 1670,
"s": 1597,
"text": "Display all documents from a collection with the help of find() method −"
},
{
"code": null,
"e": 1691,
"s": 1670,
"text": "> db.demo497.find();"
},
{
"code": null,
"e": 1732,
"s": 1691,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1996,
"s": 1732,
"text": "{ \"_id\" : ObjectId(\"5e84b3cfb0f3fa88e22790d1\"), \"details\" : [ { \"Name\" : \"Chris\" }, { \"Name\" : \"Bob\" } ] }\n{ \"_id\" : ObjectId(\"5e84b3d9b0f3fa88e22790d2\"), \"details\" : [ { \"Name\" : \"Carol\" } ] }\n{ \"_id\" : ObjectId(\"5e84b3e9b0f3fa88e22790d3\"), \"details\" : [ { } ] }"
},
{
"code": null,
"e": 2061,
"s": 1996,
"text": "Following is the query to find if element exists in a document −"
},
{
"code": null,
"e": 2187,
"s": 2061,
"text": "> db.demo497.find({$or:[\n... {\"details.Name\" : {$ne : \"Carol\"}},\n... {details: {$exists: false}}\n... ]\n... });"
},
{
"code": null,
"e": 2228,
"s": 2187,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2405,
"s": 2228,
"text": "{ \"_id\" : ObjectId(\"5e84b3cfb0f3fa88e22790d1\"), \"details\" : [ { \"Name\" : \"Chris\" }, { \"Name\" : \"Bob\" } ] }\n{ \"_id\" : ObjectId(\"5e84b3e9b0f3fa88e22790d3\"), \"details\" : [ { } ] }"
}
] |
Word Embedding Using BERT In Python | by Anirudh S | Towards Data Science | In the world of NLP, representing words or sentences in a vector form or word embedding opens up the gates to various potential applications. This functionality of encoding words into vectors is a powerful tool for NLP tasks such as calculating semantic similarity between words with which one can build a semantic search engine. For example, here’s an application of word embedding with which Google understands search queries better using BERT. Arguably, it’s one of the most powerful language models that became hugely popular among machine learning communities.
BERT (Bidirectional Encoder Representations from Transformers) models were pre-trained using a large corpus of sentences. In brief, the training is done by masking a few words (~15% of the words according to the authors of the paper) in a sentence and tasking the model to predict the masked words. And as the model trains to predict, it learns to produce a powerful internal representation of words as word embedding. Today, we’ll see how to get the BERT model up and running with little to no hassle and encode words into word embedding.
There’s a suite of available options to run BERT model with Pytorch and Tensorflow. But to make it super easy for you to get your hands on BERT models, we’ll go with a Python library that’ll help us set it up in no time!
Bert-as-a-service is a Python library that enables us to deploy pre-trained BERT models in our local machine and run inference. It can be used to serve any of the released model types and even the models fine-tuned on specific downstream tasks. Also, it requires Tensorflow in the back-end to work with the pre-trained models. So, we’ll go ahead and install Tensorflow 1.15 in the console.
pip3 install tensorflow-gpu==1.15
Up next, we’ll install bert-as-a-service client and server. And again, this library doesn’t support Python 2. So, make sure that you have Python 3.5 or higher.
pip3 install -U bert-serving-server bert-serving-client
The BERT server deploys the model in the local machine and the client can subscribe to it. Moreover, one can install the two in the same machine or deploy the server in one and subscribe from another machine. Once the installation is complete, download the BERT model of your choice. And you can find the list of all models over here.
Now that the initial setup is done, let’s start the model service with the following command.
bert-serving-start -model_dir /path_to_the_model/ -num_worker=1
For example, if the model’s name is uncased_L-24_H-1024_A-16 and it’s in the directory “/model”, the command would like this
bert-serving-start -model_dir /model/uncased_L-24_H-1024_A-16/ -num_worker=1
The “num_workers” argument is to initialize the number of concurrent requests the server can handle. However, just go with num_workers=1 as we’re just playing with our model with a single client. If you’re deploying for multiple clients to subscribe, choose the “num_workers” argument accordingly.
We can run a Python script from which we use the BERT service to encode our words into word embedding. Given that, we just have to import the BERT-client library and create an instance of the client class. Once we do that, we can feed the list of words or sentences that we want to encode.
from bert_serving.client import BertClient()client = BertClient()vectors = client.encode([“dog”],[“cat”],[“man”])
We should feed the words that we want to encode as Python list. Above, I fed three lists, each having a single word. Therefore, the “vectors” object would be of shape (3,embedding_size). In general, embedding size is the length of the word vector that the BERT model encodes. Indeed, it encodes words of any length into a constant length vector. But this may differ between the different BERT models.
Okay, so far so good! What to do with the vectors which are just some numbers? Well, they’re more than just numbers. As I said earlier, these vectors represent where the words are encoded in the 1024-dimensional hyperspace (1024 for this model uncased_L-24_H-1024_A-16). Moreover, comparing the vectors of different words with some sort of similarity function would help determine how close they are related.
Cosine similarity is one such function that gives a similarity score between 0.0 and 1.0. Provided that, 1.0 means that the words mean the same (100% match) and 0 means that they’re completely dissimilar. Here’s a scikit-learn implementation of cosine similarity between word embedding.
from sklearn.metrics.pairwise import cosine_similaritycos_lib = cosine_similarity(vectors[1,:],vectors[2,:]) #similarity between #cat and dog
You can also feed an entire sentence rather than individual words and the server will take care of it. There are multiple ways in which word embeddings can be combined to form embedding for sentences like concatenation.
Check out the other articles on Object detection, authenticity verification and more!
Originally published at https://hackerstreak.com | [
{
"code": null,
"e": 738,
"s": 172,
"text": "In the world of NLP, representing words or sentences in a vector form or word embedding opens up the gates to various potential applications. This functionality of encoding words into vectors is a powerful tool for NLP tasks such as calculating semantic similarity between words with which one can build a semantic search engine. For example, here’s an application of word embedding with which Google understands search queries better using BERT. Arguably, it’s one of the most powerful language models that became hugely popular among machine learning communities."
},
{
"code": null,
"e": 1278,
"s": 738,
"text": "BERT (Bidirectional Encoder Representations from Transformers) models were pre-trained using a large corpus of sentences. In brief, the training is done by masking a few words (~15% of the words according to the authors of the paper) in a sentence and tasking the model to predict the masked words. And as the model trains to predict, it learns to produce a powerful internal representation of words as word embedding. Today, we’ll see how to get the BERT model up and running with little to no hassle and encode words into word embedding."
},
{
"code": null,
"e": 1499,
"s": 1278,
"text": "There’s a suite of available options to run BERT model with Pytorch and Tensorflow. But to make it super easy for you to get your hands on BERT models, we’ll go with a Python library that’ll help us set it up in no time!"
},
{
"code": null,
"e": 1889,
"s": 1499,
"text": "Bert-as-a-service is a Python library that enables us to deploy pre-trained BERT models in our local machine and run inference. It can be used to serve any of the released model types and even the models fine-tuned on specific downstream tasks. Also, it requires Tensorflow in the back-end to work with the pre-trained models. So, we’ll go ahead and install Tensorflow 1.15 in the console."
},
{
"code": null,
"e": 1923,
"s": 1889,
"text": "pip3 install tensorflow-gpu==1.15"
},
{
"code": null,
"e": 2083,
"s": 1923,
"text": "Up next, we’ll install bert-as-a-service client and server. And again, this library doesn’t support Python 2. So, make sure that you have Python 3.5 or higher."
},
{
"code": null,
"e": 2139,
"s": 2083,
"text": "pip3 install -U bert-serving-server bert-serving-client"
},
{
"code": null,
"e": 2474,
"s": 2139,
"text": "The BERT server deploys the model in the local machine and the client can subscribe to it. Moreover, one can install the two in the same machine or deploy the server in one and subscribe from another machine. Once the installation is complete, download the BERT model of your choice. And you can find the list of all models over here."
},
{
"code": null,
"e": 2568,
"s": 2474,
"text": "Now that the initial setup is done, let’s start the model service with the following command."
},
{
"code": null,
"e": 2632,
"s": 2568,
"text": "bert-serving-start -model_dir /path_to_the_model/ -num_worker=1"
},
{
"code": null,
"e": 2757,
"s": 2632,
"text": "For example, if the model’s name is uncased_L-24_H-1024_A-16 and it’s in the directory “/model”, the command would like this"
},
{
"code": null,
"e": 2834,
"s": 2757,
"text": "bert-serving-start -model_dir /model/uncased_L-24_H-1024_A-16/ -num_worker=1"
},
{
"code": null,
"e": 3132,
"s": 2834,
"text": "The “num_workers” argument is to initialize the number of concurrent requests the server can handle. However, just go with num_workers=1 as we’re just playing with our model with a single client. If you’re deploying for multiple clients to subscribe, choose the “num_workers” argument accordingly."
},
{
"code": null,
"e": 3422,
"s": 3132,
"text": "We can run a Python script from which we use the BERT service to encode our words into word embedding. Given that, we just have to import the BERT-client library and create an instance of the client class. Once we do that, we can feed the list of words or sentences that we want to encode."
},
{
"code": null,
"e": 3536,
"s": 3422,
"text": "from bert_serving.client import BertClient()client = BertClient()vectors = client.encode([“dog”],[“cat”],[“man”])"
},
{
"code": null,
"e": 3937,
"s": 3536,
"text": "We should feed the words that we want to encode as Python list. Above, I fed three lists, each having a single word. Therefore, the “vectors” object would be of shape (3,embedding_size). In general, embedding size is the length of the word vector that the BERT model encodes. Indeed, it encodes words of any length into a constant length vector. But this may differ between the different BERT models."
},
{
"code": null,
"e": 4346,
"s": 3937,
"text": "Okay, so far so good! What to do with the vectors which are just some numbers? Well, they’re more than just numbers. As I said earlier, these vectors represent where the words are encoded in the 1024-dimensional hyperspace (1024 for this model uncased_L-24_H-1024_A-16). Moreover, comparing the vectors of different words with some sort of similarity function would help determine how close they are related."
},
{
"code": null,
"e": 4633,
"s": 4346,
"text": "Cosine similarity is one such function that gives a similarity score between 0.0 and 1.0. Provided that, 1.0 means that the words mean the same (100% match) and 0 means that they’re completely dissimilar. Here’s a scikit-learn implementation of cosine similarity between word embedding."
},
{
"code": null,
"e": 4775,
"s": 4633,
"text": "from sklearn.metrics.pairwise import cosine_similaritycos_lib = cosine_similarity(vectors[1,:],vectors[2,:]) #similarity between #cat and dog"
},
{
"code": null,
"e": 4995,
"s": 4775,
"text": "You can also feed an entire sentence rather than individual words and the server will take care of it. There are multiple ways in which word embeddings can be combined to form embedding for sentences like concatenation."
},
{
"code": null,
"e": 5081,
"s": 4995,
"text": "Check out the other articles on Object detection, authenticity verification and more!"
}
] |
Sublime Text - Command Palette | Command Palette includes a list of items or commands which are used frequently. The entries of commands are included in the .sublime-commands file.
To open a command palette in Sublime Text editor, you can use the shortcut key combination Ctrl+Shift+P on Windows and Cmd+Shift+P on OSX.
The commonly used commands from the palette are −
Build with Python
Install Packages
This will generate all the dependencies and build the specified code of a given Python file.
With this command, we get list of packages which can be installed which is not included earlier.
All the commands included in the command palette are stored in the Packages directory. The basic example of command declared inside the Default.sublime-commands file is shown in the code given below −
[
{ "caption": "Project: Save As", "command": "save_project_as" },
{ "caption": "Project: Close", "command": "close_project" },
{ "caption": "Project: Add Folder", "command": "prompt_add_folder" },
]
Note − The JSON file includes 3 main keys for every command −
Name/Caption
Location
Content
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2605,
"s": 2457,
"text": "Command Palette includes a list of items or commands which are used frequently. The entries of commands are included in the .sublime-commands file."
},
{
"code": null,
"e": 2744,
"s": 2605,
"text": "To open a command palette in Sublime Text editor, you can use the shortcut key combination Ctrl+Shift+P on Windows and Cmd+Shift+P on OSX."
},
{
"code": null,
"e": 2794,
"s": 2744,
"text": "The commonly used commands from the palette are −"
},
{
"code": null,
"e": 2812,
"s": 2794,
"text": "Build with Python"
},
{
"code": null,
"e": 2829,
"s": 2812,
"text": "Install Packages"
},
{
"code": null,
"e": 2922,
"s": 2829,
"text": "This will generate all the dependencies and build the specified code of a given Python file."
},
{
"code": null,
"e": 3019,
"s": 2922,
"text": "With this command, we get list of packages which can be installed which is not included earlier."
},
{
"code": null,
"e": 3220,
"s": 3019,
"text": "All the commands included in the command palette are stored in the Packages directory. The basic example of command declared inside the Default.sublime-commands file is shown in the code given below −"
},
{
"code": null,
"e": 3437,
"s": 3220,
"text": "[\n { \"caption\": \"Project: Save As\", \"command\": \"save_project_as\" },\n \n { \"caption\": \"Project: Close\", \"command\": \"close_project\" },\n \n { \"caption\": \"Project: Add Folder\", \"command\": \"prompt_add_folder\" },\n]"
},
{
"code": null,
"e": 3499,
"s": 3437,
"text": "Note − The JSON file includes 3 main keys for every command −"
},
{
"code": null,
"e": 3512,
"s": 3499,
"text": "Name/Caption"
},
{
"code": null,
"e": 3521,
"s": 3512,
"text": "Location"
},
{
"code": null,
"e": 3529,
"s": 3521,
"text": "Content"
},
{
"code": null,
"e": 3536,
"s": 3529,
"text": " Print"
},
{
"code": null,
"e": 3547,
"s": 3536,
"text": " Add Notes"
}
] |
Impala - With Clause | In case a query is way too complex, we can define aliases to complex parts and include them in the query using the with clause of Impala.
Following is the syntax of the with clause in Impala.
with x as (select 1), y as (select 2) (select * from x union y);
Assume we have a table named customers in the database my_db and its contents are as follows −
[quickstart.cloudera:21000] > select * from customers;
Query: select * from customers
+----+----------+-----+-----------+--------+
| id | name | age | address | salary |
+----+----------+-----+-----------+--------+
| 1 | Ramesh | 32 | Ahmedabad | 20000 |
| 9 | robert | 23 | banglore | 28000 |
| 2 | Khilan | 25 | Delhi | 15000 |
| 4 | Chaitali | 25 | Mumbai | 35000 |
| 7 | ram | 25 | chennai | 23000 |
| 6 | Komal | 22 | MP | 32000 |
| 8 | ram | 22 | vizag | 31000 |
| 5 | Hardik | 27 | Bhopal | 40000 |
| 3 | kaushik | 23 | Kota | 30000 |
+----+----------+-----+-----------+--------+
Fetched 9 row(s) in 0.59s
In the same way, suppose we have another table named employee and its contents are as follows −
[quickstart.cloudera:21000] > select * from employee;
Query: select * from employee
+----+---------+-----+---------+--------+
| id | name | age | address | salary |
+----+---------+-----+---------+--------+
| 3 | mahesh | 54 | Chennai | 55000 |
| 2 | ramesh | 44 | Chennai | 50000 |
| 4 | Rupesh | 64 | Delhi | 60000 |
| 1 | subhash | 34 | Delhi | 40000 |
+----+---------+-----+---------+--------+
Fetched 4 row(s) in 0.59s
Following is an example of the with clause in Impala. In this example, we are displaying the records from both employee and customers whose age is greater than 25 using with clause.
[quickstart.cloudera:21000] >
with t1 as (select * from customers where age>25),
t2 as (select * from employee where age>25)
(select * from t1 union select * from t2);
On executing, the above query gives the following output.
Query: with t1 as (select * from customers where age>25), t2 as (select * from employee where age>25)
(select * from t1 union select * from t2)
+----+---------+-----+-----------+--------+
| id | name | age | address | salary |
+----+---------+-----+-----------+--------+
| 3 | mahesh | 54 | Chennai | 55000 |
| 1 | subhash | 34 | Delhi | 40000 |
| 2 | ramesh | 44 | Chennai | 50000 |
| 5 | Hardik | 27 | Bhopal | 40000 |
| 4 | Rupesh | 64 | Delhi | 60000 |
| 1 | Ramesh | 32 | Ahmedabad | 20000 |
+----+---------+-----+-----------+--------+
Fetched 6 row(s) in 1.73s
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2423,
"s": 2285,
"text": "In case a query is way too complex, we can define aliases to complex parts and include them in the query using the with clause of Impala."
},
{
"code": null,
"e": 2477,
"s": 2423,
"text": "Following is the syntax of the with clause in Impala."
},
{
"code": null,
"e": 2543,
"s": 2477,
"text": "with x as (select 1), y as (select 2) (select * from x union y);\n"
},
{
"code": null,
"e": 2638,
"s": 2543,
"text": "Assume we have a table named customers in the database my_db and its contents are as follows −"
},
{
"code": null,
"e": 3350,
"s": 2638,
"text": "[quickstart.cloudera:21000] > select * from customers;\nQuery: select * from customers \n+----+----------+-----+-----------+--------+ \n| id | name | age | address | salary | \n+----+----------+-----+-----------+--------+ \n| 1 | Ramesh | 32 | Ahmedabad | 20000 | \n| 9 | robert | 23 | banglore | 28000 | \n| 2 | Khilan | 25 | Delhi | 15000 | \n| 4 | Chaitali | 25 | Mumbai | 35000 | \n| 7 | ram | 25 | chennai | 23000 | \n| 6 | Komal | 22 | MP | 32000 | \n| 8 | ram | 22 | vizag | 31000 | \n| 5 | Hardik | 27 | Bhopal | 40000 | \n| 3 | kaushik | 23 | Kota | 30000 | \n+----+----------+-----+-----------+--------+ \nFetched 9 row(s) in 0.59s\n"
},
{
"code": null,
"e": 3446,
"s": 3350,
"text": "In the same way, suppose we have another table named employee and its contents are as follows −"
},
{
"code": null,
"e": 3903,
"s": 3446,
"text": "[quickstart.cloudera:21000] > select * from employee; \nQuery: select * from employee \n+----+---------+-----+---------+--------+ \n| id | name | age | address | salary | \n+----+---------+-----+---------+--------+ \n| 3 | mahesh | 54 | Chennai | 55000 | \n| 2 | ramesh | 44 | Chennai | 50000 | \n| 4 | Rupesh | 64 | Delhi | 60000 | \n| 1 | subhash | 34 | Delhi | 40000 | \n+----+---------+-----+---------+--------+ \nFetched 4 row(s) in 0.59s\n"
},
{
"code": null,
"e": 4085,
"s": 3903,
"text": "Following is an example of the with clause in Impala. In this example, we are displaying the records from both employee and customers whose age is greater than 25 using with clause."
},
{
"code": null,
"e": 4266,
"s": 4085,
"text": "[quickstart.cloudera:21000] > \n with t1 as (select * from customers where age>25), \n t2 as (select * from employee where age>25) \n (select * from t1 union select * from t2);\n"
},
{
"code": null,
"e": 4324,
"s": 4266,
"text": "On executing, the above query gives the following output."
},
{
"code": null,
"e": 4949,
"s": 4324,
"text": "Query: with t1 as (select * from customers where age>25), t2 as (select * from employee where age>25) \n (select * from t1 union select * from t2)\n+----+---------+-----+-----------+--------+ \n| id | name | age | address | salary | \n+----+---------+-----+-----------+--------+ \n| 3 | mahesh | 54 | Chennai | 55000 | \n| 1 | subhash | 34 | Delhi | 40000 | \n| 2 | ramesh | 44 | Chennai | 50000 | \n| 5 | Hardik | 27 | Bhopal | 40000 | \n| 4 | Rupesh | 64 | Delhi | 60000 | \n| 1 | Ramesh | 32 | Ahmedabad | 20000 | \n+----+---------+-----+-----------+--------+ \nFetched 6 row(s) in 1.73s\n"
},
{
"code": null,
"e": 4956,
"s": 4949,
"text": " Print"
},
{
"code": null,
"e": 4967,
"s": 4956,
"text": " Add Notes"
}
] |
Generate Random bytes in Java | In order to generate random bytes in Java, we use the nextBytes() method. The java.util.Random.nextBytes() method generates random bytes and provides it to the user defined byte array.
Declaration − The java.util.Random.nextBytes() method is declared as follows −
public void nextBytes(byte[] bytes)
where bytes is the byte array.
Let us see a program to generate random bytes in Java −
Live Demo
import java.util.Random;
public class Example {
public static void main(String[] args) {
Random rd = new Random();
byte[] arr = new byte[7];
rd.nextBytes(arr);
System.out.println(arr);
}
}
[B@15db9742
Note − The output might vary on Online Compilers. | [
{
"code": null,
"e": 1247,
"s": 1062,
"text": "In order to generate random bytes in Java, we use the nextBytes() method. The java.util.Random.nextBytes() method generates random bytes and provides it to the user defined byte array."
},
{
"code": null,
"e": 1326,
"s": 1247,
"text": "Declaration − The java.util.Random.nextBytes() method is declared as follows −"
},
{
"code": null,
"e": 1362,
"s": 1326,
"text": "public void nextBytes(byte[] bytes)"
},
{
"code": null,
"e": 1393,
"s": 1362,
"text": "where bytes is the byte array."
},
{
"code": null,
"e": 1449,
"s": 1393,
"text": "Let us see a program to generate random bytes in Java −"
},
{
"code": null,
"e": 1460,
"s": 1449,
"text": " Live Demo"
},
{
"code": null,
"e": 1679,
"s": 1460,
"text": "import java.util.Random;\npublic class Example {\n public static void main(String[] args) {\n Random rd = new Random();\n byte[] arr = new byte[7];\n rd.nextBytes(arr);\n System.out.println(arr);\n }\n}"
},
{
"code": null,
"e": 1691,
"s": 1679,
"text": "[B@15db9742"
},
{
"code": null,
"e": 1741,
"s": 1691,
"text": "Note − The output might vary on Online Compilers."
}
] |
Ruby - String split() Method with Examples - GeeksforGeeks | 03 Jul, 2020
split is a String class method in Ruby which is used to split the given string into an array of substrings based on a pattern specified.
Here the pattern can be a Regular Expression or a string. If pattern is a Regular Expression or a string, str is divided where the pattern matches.
Syntax:
arr = str.split(pattern, limit) public
Parameters: arr is the list, str is the string, pattern is the either string or regExp, and limit is the maximum entries into the array.
Returns: Array of strings based on the parameters.
Example 1:
# Ruby program to demonstrate split method # Split without parameters# Here the pattern is a # single whitespacemyArray = "Geeks For Geeks".splitputs myArray
Output:
Geeks
For
Geeks
Example 2:
# Ruby program to demonstrate split method # Here pattern is a regular expression# limit value is 2# / / is one white spacemyArray = "Geeks For Geeks".split(/ /, 2)puts myArray
Output:
Geeks
For Geeks
Example 3:
# Ruby program to demonstrate split method # Here the pattern is a regular expression# limit value is -1# if the limit is negative there is no # limit to the number of fields returned,# and trailing null fields are not # suppressed.myArray = "geeks geeks".split('s', -1)puts myArray
Output:
geek
geek
Ruby-Methods
Ruby-String
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Ruby | Enumerator each_with_index function
Global Variable in Ruby
Ruby | Array select() function
Ruby | Hash delete() function
Ruby | String gsub! Method
Ruby | String capitalize() Method
How to Make a Custom Array of Hashes in Ruby?
Ruby | Case Statement
Ruby | Numeric round() function
Ruby | Decision Making (if, if-else, if-else-if, ternary) | Set - 1 | [
{
"code": null,
"e": 23221,
"s": 23193,
"text": "\n03 Jul, 2020"
},
{
"code": null,
"e": 23358,
"s": 23221,
"text": "split is a String class method in Ruby which is used to split the given string into an array of substrings based on a pattern specified."
},
{
"code": null,
"e": 23506,
"s": 23358,
"text": "Here the pattern can be a Regular Expression or a string. If pattern is a Regular Expression or a string, str is divided where the pattern matches."
},
{
"code": null,
"e": 23514,
"s": 23506,
"text": "Syntax:"
},
{
"code": null,
"e": 23553,
"s": 23514,
"text": "arr = str.split(pattern, limit) public"
},
{
"code": null,
"e": 23690,
"s": 23553,
"text": "Parameters: arr is the list, str is the string, pattern is the either string or regExp, and limit is the maximum entries into the array."
},
{
"code": null,
"e": 23741,
"s": 23690,
"text": "Returns: Array of strings based on the parameters."
},
{
"code": null,
"e": 23752,
"s": 23741,
"text": "Example 1:"
},
{
"code": "# Ruby program to demonstrate split method # Split without parameters# Here the pattern is a # single whitespacemyArray = \"Geeks For Geeks\".splitputs myArray",
"e": 23912,
"s": 23752,
"text": null
},
{
"code": null,
"e": 23920,
"s": 23912,
"text": "Output:"
},
{
"code": null,
"e": 23936,
"s": 23920,
"text": "Geeks\nFor\nGeeks"
},
{
"code": null,
"e": 23947,
"s": 23936,
"text": "Example 2:"
},
{
"code": "# Ruby program to demonstrate split method # Here pattern is a regular expression# limit value is 2# / / is one white spacemyArray = \"Geeks For Geeks\".split(/ /, 2)puts myArray",
"e": 24125,
"s": 23947,
"text": null
},
{
"code": null,
"e": 24133,
"s": 24125,
"text": "Output:"
},
{
"code": null,
"e": 24149,
"s": 24133,
"text": "Geeks\nFor Geeks"
},
{
"code": null,
"e": 24160,
"s": 24149,
"text": "Example 3:"
},
{
"code": "# Ruby program to demonstrate split method # Here the pattern is a regular expression# limit value is -1# if the limit is negative there is no # limit to the number of fields returned,# and trailing null fields are not # suppressed.myArray = \"geeks geeks\".split('s', -1)puts myArray",
"e": 24444,
"s": 24160,
"text": null
},
{
"code": null,
"e": 24452,
"s": 24444,
"text": "Output:"
},
{
"code": null,
"e": 24463,
"s": 24452,
"text": "geek\n geek"
},
{
"code": null,
"e": 24476,
"s": 24463,
"text": "Ruby-Methods"
},
{
"code": null,
"e": 24488,
"s": 24476,
"text": "Ruby-String"
},
{
"code": null,
"e": 24493,
"s": 24488,
"text": "Ruby"
},
{
"code": null,
"e": 24591,
"s": 24493,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 24600,
"s": 24591,
"text": "Comments"
},
{
"code": null,
"e": 24613,
"s": 24600,
"text": "Old Comments"
},
{
"code": null,
"e": 24656,
"s": 24613,
"text": "Ruby | Enumerator each_with_index function"
},
{
"code": null,
"e": 24680,
"s": 24656,
"text": "Global Variable in Ruby"
},
{
"code": null,
"e": 24711,
"s": 24680,
"text": "Ruby | Array select() function"
},
{
"code": null,
"e": 24741,
"s": 24711,
"text": "Ruby | Hash delete() function"
},
{
"code": null,
"e": 24768,
"s": 24741,
"text": "Ruby | String gsub! Method"
},
{
"code": null,
"e": 24802,
"s": 24768,
"text": "Ruby | String capitalize() Method"
},
{
"code": null,
"e": 24848,
"s": 24802,
"text": "How to Make a Custom Array of Hashes in Ruby?"
},
{
"code": null,
"e": 24870,
"s": 24848,
"text": "Ruby | Case Statement"
},
{
"code": null,
"e": 24902,
"s": 24870,
"text": "Ruby | Numeric round() function"
}
] |
Reversing the first K elements of a Queue - GeeksforGeeks | 03 Dec, 2021
Given an integer k and a queue of integers, we need to reverse the order of the first k elements of the queue, leaving the other elements in the same relative order.Only following standard operations are allowed on queue.
enqueue(x) : Add an item x to rear of queue
dequeue() : Remove an item from front of queue
size() : Returns number of elements in queue.
front() : Finds front item.
Examples:
Input : Q = [10, 20, 30, 40, 50, 60,
70, 80, 90, 100]
k = 5
Output : Q = [50, 40, 30, 20, 10, 60,
70, 80, 90, 100]
Input : Q = [10, 20, 30, 40, 50, 60,
70, 80, 90, 100]
k = 4
Output : Q = [40, 30, 20, 10, 50, 60,
70, 80, 90, 100]
The idea is to use an auxiliary stack.
Create an empty stack.One by one dequeue first K items from given queue and push the dequeued items to stack.Enqueue the contents of stack at the back of the queueDequeue (size-k) elements from the front and enqueue them one by one to the same queue.
Create an empty stack.
One by one dequeue first K items from given queue and push the dequeued items to stack.
Enqueue the contents of stack at the back of the queue
Dequeue (size-k) elements from the front and enqueue them one by one to the same queue.
C++
Java
Python3
C#
// C++ program to reverse first// k elements of a queue.#include <bits/stdc++.h>using namespace std; /* Function to reverse the first K elements of the Queue */void reverseQueueFirstKElements( int k, queue<int>& Queue){ if (Queue.empty() == true || k > Queue.size()) return; if (k <= 0) return; stack<int> Stack; /* Push the first K elements into a Stack*/ for (int i = 0; i < k; i++) { Stack.push(Queue.front()); Queue.pop(); } /* Enqueue the contents of stack at the back of the queue*/ while (!Stack.empty()) { Queue.push(Stack.top()); Stack.pop(); } /* Remove the remaining elements and enqueue them at the end of the Queue*/ for (int i = 0; i < Queue.size() - k; i++) { Queue.push(Queue.front()); Queue.pop(); }} /* Utility Function to print the Queue */void Print(queue<int>& Queue){ while (!Queue.empty()) { cout << Queue.front() << " "; Queue.pop(); }} // Driver codeint main(){ queue<int> Queue; Queue.push(10); Queue.push(20); Queue.push(30); Queue.push(40); Queue.push(50); Queue.push(60); Queue.push(70); Queue.push(80); Queue.push(90); Queue.push(100); int k = 5; reverseQueueFirstKElements(k, Queue); Print(Queue);}
// Java program to reverse first k elements// of a queue.import java.util.LinkedList;import java.util.Queue;import java.util.Stack; public class Reverse_k_element_queue { static Queue<Integer> queue; // Function to reverse the first // K elements of the Queue static void reverseQueueFirstKElements(int k) { if (queue.isEmpty() == true || k > queue.size()) return; if (k <= 0) return; Stack<Integer> stack = new Stack<Integer>(); // Push the first K elements into a Stack for (int i = 0; i < k; i++) { stack.push(queue.peek()); queue.remove(); } // Enqueue the contents of stack // at the back of the queue while (!stack.empty()) { queue.add(stack.peek()); stack.pop(); } // Remove the remaining elements and enqueue // them at the end of the Queue for (int i = 0; i < queue.size() - k; i++) { queue.add(queue.peek()); queue.remove(); } } // Utility Function to print the Queue static void Print() { while (!queue.isEmpty()) { System.out.print(queue.peek() + " "); queue.remove(); } } // Driver code public static void main(String args[]) { queue = new LinkedList<Integer>(); queue.add(10); queue.add(20); queue.add(30); queue.add(40); queue.add(50); queue.add(60); queue.add(70); queue.add(80); queue.add(90); queue.add(100); int k = 5; reverseQueueFirstKElements(k); Print(); }}// This code is contributed by Sumit Ghosh
# Python3 program to reverse first k# elements of a queue.from queue import Queue # Function to reverse the first K# elements of the Queuedef reverseQueueFirstKElements(k, Queue): if (Queue.empty() == True or k > Queue.qsize()): return if (k <= 0): return Stack = [] # put the first K elements # into a Stack for i in range(k): Stack.append(Queue.queue[0]) Queue.get() # Enqueue the contents of stack # at the back of the queue while (len(Stack) != 0 ): Queue.put(Stack[-1]) Stack.pop() # Remove the remaining elements and # enqueue them at the end of the Queue for i in range(Queue.qsize() - k): Queue.put(Queue.queue[0]) Queue.get() # Utility Function to print the Queuedef Print(Queue): while (not Queue.empty()): print(Queue.queue[0], end =" ") Queue.get() # Driver codeif __name__ == '__main__': Queue = Queue() Queue.put(10) Queue.put(20) Queue.put(30) Queue.put(40) Queue.put(50) Queue.put(60) Queue.put(70) Queue.put(80) Queue.put(90) Queue.put(100) k = 5 reverseQueueFirstKElements(k, Queue) Print(Queue) # This code is contributed by PranchalK
// C# program to reverse first k elements// of a queue.using System;using System.Collections.Generic; class GFG { public static LinkedList<int> queue; // Function to reverse the first K // elements of the Queue public static void reverseQueueFirstKElements(int k) { if (queue.Count == 0 || k > queue.Count) { return; } if (k <= 0) { return; } Stack<int> stack = new Stack<int>(); // Push the first K elements into a Stack for (int i = 0; i < k; i++) { stack.Push(queue.First.Value); queue.RemoveFirst(); } // Enqueue the contents of stack at // the back of the queue while (stack.Count > 0) { queue.AddLast(stack.Peek()); stack.Pop(); } // Remove the remaining elements and // enqueue them at the end of the Queue for (int i = 0; i < queue.Count - k; i++) { queue.AddLast(queue.First.Value);<li><strong>Complexity Analysis:</strong><strong>Time Complexity:</strong> O(n<sup>3</sup>).As three nested for loops are used.<strong>Auxiliary Space :</strong>No use of any data structure for storing values-: O(1)</li> queue.RemoveFirst(); } } // Utility Function to print the Queue public static void Print() { while (queue.Count > 0) { Console.Write(queue.First.Value + " "); queue.RemoveFirst(); } } // Driver code public static void Main(string[] args) { queue = new LinkedList<int>(); queue.AddLast(10); queue.AddLast(20); queue.AddLast(30); queue.AddLast(40); queue.AddLast(50); queue.AddLast(60); queue.AddLast(70); queue.AddLast(80); queue.AddLast(90); queue.AddLast(100); int k = 5; reverseQueueFirstKElements(k); Print(); }} // This code is contributed by Shrikant13
50 40 30 20 10 60 70 80 90 100
Complexity Analysis:
Time Complexity: O(n+k). Where ‘n’ is the total number of elements in the queue and ‘k’ is the number of elements to be reversed. This is because firstly the whole queue is emptied into the stack and after that first ‘k’ elements are emptied and enqueued in the same way.
Auxiliary Space :Use of stack to store values for the purpose of reversing-: O(n)
-s This article is contributed by Raghav Sharma. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
shrikanth13
PranchalKatiyar
NikhilKumar23
SnehashishKalamkar
bidibaaz123
tanyakemkar
simmytarika5
Queue
Stack
Stack
Queue
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Queue | Set 1 (Introduction and Array Implementation)
Priority Queue | Set 1 (Introduction)
LRU Cache Implementation
Queue - Linked List Implementation
Circular Queue | Set 1 (Introduction and Array Implementation)
Stack Data Structure (Introduction and Program)
Stack in Python
Stack Class in Java
Inorder Tree Traversal without Recursion
Stack | Set 2 (Infix to Postfix) | [
{
"code": null,
"e": 24333,
"s": 24305,
"text": "\n03 Dec, 2021"
},
{
"code": null,
"e": 24556,
"s": 24333,
"text": "Given an integer k and a queue of integers, we need to reverse the order of the first k elements of the queue, leaving the other elements in the same relative order.Only following standard operations are allowed on queue. "
},
{
"code": null,
"e": 24600,
"s": 24556,
"text": "enqueue(x) : Add an item x to rear of queue"
},
{
"code": null,
"e": 24647,
"s": 24600,
"text": "dequeue() : Remove an item from front of queue"
},
{
"code": null,
"e": 24693,
"s": 24647,
"text": "size() : Returns number of elements in queue."
},
{
"code": null,
"e": 24721,
"s": 24693,
"text": "front() : Finds front item."
},
{
"code": null,
"e": 24732,
"s": 24721,
"text": "Examples: "
},
{
"code": null,
"e": 25033,
"s": 24732,
"text": "Input : Q = [10, 20, 30, 40, 50, 60, \n 70, 80, 90, 100]\n k = 5\nOutput : Q = [50, 40, 30, 20, 10, 60, \n 70, 80, 90, 100]\n\nInput : Q = [10, 20, 30, 40, 50, 60, \n 70, 80, 90, 100]\n k = 4\nOutput : Q = [40, 30, 20, 10, 50, 60, \n 70, 80, 90, 100]"
},
{
"code": null,
"e": 25073,
"s": 25033,
"text": "The idea is to use an auxiliary stack. "
},
{
"code": null,
"e": 25324,
"s": 25073,
"text": "Create an empty stack.One by one dequeue first K items from given queue and push the dequeued items to stack.Enqueue the contents of stack at the back of the queueDequeue (size-k) elements from the front and enqueue them one by one to the same queue."
},
{
"code": null,
"e": 25347,
"s": 25324,
"text": "Create an empty stack."
},
{
"code": null,
"e": 25435,
"s": 25347,
"text": "One by one dequeue first K items from given queue and push the dequeued items to stack."
},
{
"code": null,
"e": 25490,
"s": 25435,
"text": "Enqueue the contents of stack at the back of the queue"
},
{
"code": null,
"e": 25578,
"s": 25490,
"text": "Dequeue (size-k) elements from the front and enqueue them one by one to the same queue."
},
{
"code": null,
"e": 25582,
"s": 25578,
"text": "C++"
},
{
"code": null,
"e": 25587,
"s": 25582,
"text": "Java"
},
{
"code": null,
"e": 25595,
"s": 25587,
"text": "Python3"
},
{
"code": null,
"e": 25598,
"s": 25595,
"text": "C#"
},
{
"code": "// C++ program to reverse first// k elements of a queue.#include <bits/stdc++.h>using namespace std; /* Function to reverse the first K elements of the Queue */void reverseQueueFirstKElements( int k, queue<int>& Queue){ if (Queue.empty() == true || k > Queue.size()) return; if (k <= 0) return; stack<int> Stack; /* Push the first K elements into a Stack*/ for (int i = 0; i < k; i++) { Stack.push(Queue.front()); Queue.pop(); } /* Enqueue the contents of stack at the back of the queue*/ while (!Stack.empty()) { Queue.push(Stack.top()); Stack.pop(); } /* Remove the remaining elements and enqueue them at the end of the Queue*/ for (int i = 0; i < Queue.size() - k; i++) { Queue.push(Queue.front()); Queue.pop(); }} /* Utility Function to print the Queue */void Print(queue<int>& Queue){ while (!Queue.empty()) { cout << Queue.front() << \" \"; Queue.pop(); }} // Driver codeint main(){ queue<int> Queue; Queue.push(10); Queue.push(20); Queue.push(30); Queue.push(40); Queue.push(50); Queue.push(60); Queue.push(70); Queue.push(80); Queue.push(90); Queue.push(100); int k = 5; reverseQueueFirstKElements(k, Queue); Print(Queue);}",
"e": 26917,
"s": 25598,
"text": null
},
{
"code": "// Java program to reverse first k elements// of a queue.import java.util.LinkedList;import java.util.Queue;import java.util.Stack; public class Reverse_k_element_queue { static Queue<Integer> queue; // Function to reverse the first // K elements of the Queue static void reverseQueueFirstKElements(int k) { if (queue.isEmpty() == true || k > queue.size()) return; if (k <= 0) return; Stack<Integer> stack = new Stack<Integer>(); // Push the first K elements into a Stack for (int i = 0; i < k; i++) { stack.push(queue.peek()); queue.remove(); } // Enqueue the contents of stack // at the back of the queue while (!stack.empty()) { queue.add(stack.peek()); stack.pop(); } // Remove the remaining elements and enqueue // them at the end of the Queue for (int i = 0; i < queue.size() - k; i++) { queue.add(queue.peek()); queue.remove(); } } // Utility Function to print the Queue static void Print() { while (!queue.isEmpty()) { System.out.print(queue.peek() + \" \"); queue.remove(); } } // Driver code public static void main(String args[]) { queue = new LinkedList<Integer>(); queue.add(10); queue.add(20); queue.add(30); queue.add(40); queue.add(50); queue.add(60); queue.add(70); queue.add(80); queue.add(90); queue.add(100); int k = 5; reverseQueueFirstKElements(k); Print(); }}// This code is contributed by Sumit Ghosh",
"e": 28622,
"s": 26917,
"text": null
},
{
"code": "# Python3 program to reverse first k# elements of a queue.from queue import Queue # Function to reverse the first K# elements of the Queuedef reverseQueueFirstKElements(k, Queue): if (Queue.empty() == True or k > Queue.qsize()): return if (k <= 0): return Stack = [] # put the first K elements # into a Stack for i in range(k): Stack.append(Queue.queue[0]) Queue.get() # Enqueue the contents of stack # at the back of the queue while (len(Stack) != 0 ): Queue.put(Stack[-1]) Stack.pop() # Remove the remaining elements and # enqueue them at the end of the Queue for i in range(Queue.qsize() - k): Queue.put(Queue.queue[0]) Queue.get() # Utility Function to print the Queuedef Print(Queue): while (not Queue.empty()): print(Queue.queue[0], end =\" \") Queue.get() # Driver codeif __name__ == '__main__': Queue = Queue() Queue.put(10) Queue.put(20) Queue.put(30) Queue.put(40) Queue.put(50) Queue.put(60) Queue.put(70) Queue.put(80) Queue.put(90) Queue.put(100) k = 5 reverseQueueFirstKElements(k, Queue) Print(Queue) # This code is contributed by PranchalK",
"e": 29844,
"s": 28622,
"text": null
},
{
"code": "// C# program to reverse first k elements// of a queue.using System;using System.Collections.Generic; class GFG { public static LinkedList<int> queue; // Function to reverse the first K // elements of the Queue public static void reverseQueueFirstKElements(int k) { if (queue.Count == 0 || k > queue.Count) { return; } if (k <= 0) { return; } Stack<int> stack = new Stack<int>(); // Push the first K elements into a Stack for (int i = 0; i < k; i++) { stack.Push(queue.First.Value); queue.RemoveFirst(); } // Enqueue the contents of stack at // the back of the queue while (stack.Count > 0) { queue.AddLast(stack.Peek()); stack.Pop(); } // Remove the remaining elements and // enqueue them at the end of the Queue for (int i = 0; i < queue.Count - k; i++) { queue.AddLast(queue.First.Value);<li><strong>Complexity Analysis:</strong><strong>Time Complexity:</strong> O(n<sup>3</sup>).As three nested for loops are used.<strong>Auxiliary Space :</strong>No use of any data structure for storing values-: O(1)</li> queue.RemoveFirst(); } } // Utility Function to print the Queue public static void Print() { while (queue.Count > 0) { Console.Write(queue.First.Value + \" \"); queue.RemoveFirst(); } } // Driver code public static void Main(string[] args) { queue = new LinkedList<int>(); queue.AddLast(10); queue.AddLast(20); queue.AddLast(30); queue.AddLast(40); queue.AddLast(50); queue.AddLast(60); queue.AddLast(70); queue.AddLast(80); queue.AddLast(90); queue.AddLast(100); int k = 5; reverseQueueFirstKElements(k); Print(); }} // This code is contributed by Shrikant13",
"e": 31795,
"s": 29844,
"text": null
},
{
"code": null,
"e": 31826,
"s": 31795,
"text": "50 40 30 20 10 60 70 80 90 100"
},
{
"code": null,
"e": 31850,
"s": 31828,
"text": "Complexity Analysis: "
},
{
"code": null,
"e": 32122,
"s": 31850,
"text": "Time Complexity: O(n+k). Where ‘n’ is the total number of elements in the queue and ‘k’ is the number of elements to be reversed. This is because firstly the whole queue is emptied into the stack and after that first ‘k’ elements are emptied and enqueued in the same way."
},
{
"code": null,
"e": 32204,
"s": 32122,
"text": "Auxiliary Space :Use of stack to store values for the purpose of reversing-: O(n)"
},
{
"code": null,
"e": 32628,
"s": 32204,
"text": "-s This article is contributed by Raghav Sharma. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 32640,
"s": 32628,
"text": "shrikanth13"
},
{
"code": null,
"e": 32656,
"s": 32640,
"text": "PranchalKatiyar"
},
{
"code": null,
"e": 32670,
"s": 32656,
"text": "NikhilKumar23"
},
{
"code": null,
"e": 32689,
"s": 32670,
"text": "SnehashishKalamkar"
},
{
"code": null,
"e": 32701,
"s": 32689,
"text": "bidibaaz123"
},
{
"code": null,
"e": 32713,
"s": 32701,
"text": "tanyakemkar"
},
{
"code": null,
"e": 32726,
"s": 32713,
"text": "simmytarika5"
},
{
"code": null,
"e": 32732,
"s": 32726,
"text": "Queue"
},
{
"code": null,
"e": 32738,
"s": 32732,
"text": "Stack"
},
{
"code": null,
"e": 32744,
"s": 32738,
"text": "Stack"
},
{
"code": null,
"e": 32750,
"s": 32744,
"text": "Queue"
},
{
"code": null,
"e": 32848,
"s": 32750,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32857,
"s": 32848,
"text": "Comments"
},
{
"code": null,
"e": 32870,
"s": 32857,
"text": "Old Comments"
},
{
"code": null,
"e": 32924,
"s": 32870,
"text": "Queue | Set 1 (Introduction and Array Implementation)"
},
{
"code": null,
"e": 32962,
"s": 32924,
"text": "Priority Queue | Set 1 (Introduction)"
},
{
"code": null,
"e": 32987,
"s": 32962,
"text": "LRU Cache Implementation"
},
{
"code": null,
"e": 33022,
"s": 32987,
"text": "Queue - Linked List Implementation"
},
{
"code": null,
"e": 33085,
"s": 33022,
"text": "Circular Queue | Set 1 (Introduction and Array Implementation)"
},
{
"code": null,
"e": 33133,
"s": 33085,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 33149,
"s": 33133,
"text": "Stack in Python"
},
{
"code": null,
"e": 33169,
"s": 33149,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 33210,
"s": 33169,
"text": "Inorder Tree Traversal without Recursion"
}
] |
Why do we use re.compile() method in Python regular expression? | re.compile(pattern, repl, string):
We can combine a regular expression pattern into pattern objects, which can be used for pattern matching. It also helps to search a pattern again without rewriting it.
import re
pattern=re.compile('TP')
result=pattern.findall('TP Tutorialspoint TP')
print result
result2=pattern.findall('TP is most popular tutorials site of India')
print result2
['TP', 'TP']
['TP'] | [
{
"code": null,
"e": 1097,
"s": 1062,
"text": "re.compile(pattern, repl, string):"
},
{
"code": null,
"e": 1266,
"s": 1097,
"text": " We can combine a regular expression pattern into pattern objects, which can be used for pattern matching. It also helps to search a pattern again without rewriting it."
},
{
"code": null,
"e": 1445,
"s": 1266,
"text": "import re\npattern=re.compile('TP')\nresult=pattern.findall('TP Tutorialspoint TP')\nprint result\nresult2=pattern.findall('TP is most popular tutorials site of India')\nprint result2"
},
{
"code": null,
"e": 1465,
"s": 1445,
"text": "['TP', 'TP']\n['TP']"
}
] |
Check if value is empty in JavaScript | Use the condition with “” and NULL to check if value is empty. Throw a message whenever ua ser does not fill the text box value.
Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
<title>Document</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<form name="register" onsubmit="return checkingUserName()">
USERNAME: <input type="text" name="username">
<input type="submit" value="Save">
</form>
<script>
function checkingUserName() {
var username = document.forms["register"]["username"].value;
if (username == null || username == "") {
alert("Please enter> the username. Can’t be blank or empty !!!");
return false;
}
}
</script>
</body>
</html>
To run the above program, save the file name “anyName.html(index.html)” and right click on the
file. Select the option “Open with Live Server” in VS Code editor.
This will produce the following output −
On clicking the Save button, you will get the following alert along with a message − | [
{
"code": null,
"e": 1191,
"s": 1062,
"text": "Use the condition with “” and NULL to check if value is empty. Throw a message whenever ua ser does not fill the text box value."
},
{
"code": null,
"e": 1202,
"s": 1191,
"text": " Live Demo"
},
{
"code": null,
"e": 2038,
"s": 1202,
"text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\">\n<meta name=\"viewport\" content=\"width=device-width, initialscale=1.0\">\n<title>Document</title>\n<link rel=\"stylesheet\" href=\"//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css\">\n<script src=\"https://code.jquery.com/jquery-1.12.4.js\"></script>\n<script src=\"https://code.jquery.com/ui/1.12.1/jquery-ui.js\"></script>\n</head>\n<body>\n<form name=\"register\" onsubmit=\"return checkingUserName()\">\nUSERNAME: <input type=\"text\" name=\"username\">\n<input type=\"submit\" value=\"Save\">\n</form>\n<script>\n function checkingUserName() {\n var username = document.forms[\"register\"][\"username\"].value;\n if (username == null || username == \"\") {\n alert(\"Please enter> the username. Can’t be blank or empty !!!\");\n return false;\n }\n }\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 2200,
"s": 2038,
"text": "To run the above program, save the file name “anyName.html(index.html)” and right click on the\nfile. Select the option “Open with Live Server” in VS Code editor."
},
{
"code": null,
"e": 2241,
"s": 2200,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2326,
"s": 2241,
"text": "On clicking the Save button, you will get the following alert along with a message −"
}
] |
How do I change the background of a Frame in Tkinter? | In order to change the background color and foreground color of a tkinter frame, we can assign different values to the bg and fg parameters in the Frame function.
In this example, we have created two frames with different background colors.
#Import the required libraries
from tkinter import *
#Create an instance of tkinter frame
win= Tk()
#Set the geometry of frame
win.geometry("650x250")
#Create an frame
frame1= Frame(win, bg= "red")
frame2= Frame(win, bg="black")
#Create an label inside the frame
Label(frame2, text= "Line:1", font=('Lucida font',20)).pack(pady=20)
Label(frame1, text= "Line:2", font=('Lucida font',20)).pack(pady=20)
frame1.pack()
frame2.pack()
win.mainloop()
Running the above code will display a window containing two frames with different background colors. | [
{
"code": null,
"e": 1225,
"s": 1062,
"text": "In order to change the background color and foreground color of a tkinter frame, we can assign different values to the bg and fg parameters in the Frame function."
},
{
"code": null,
"e": 1303,
"s": 1225,
"text": "In this example, we have created two frames with different background colors."
},
{
"code": null,
"e": 1753,
"s": 1303,
"text": "#Import the required libraries\nfrom tkinter import *\n\n#Create an instance of tkinter frame\nwin= Tk()\n\n#Set the geometry of frame\nwin.geometry(\"650x250\")\n\n#Create an frame\nframe1= Frame(win, bg= \"red\")\nframe2= Frame(win, bg=\"black\")\n\n#Create an label inside the frame\nLabel(frame2, text= \"Line:1\", font=('Lucida font',20)).pack(pady=20)\nLabel(frame1, text= \"Line:2\", font=('Lucida font',20)).pack(pady=20)\n\nframe1.pack()\nframe2.pack()\n\nwin.mainloop()"
},
{
"code": null,
"e": 1854,
"s": 1753,
"text": "Running the above code will display a window containing two frames with different background colors."
}
] |
How to find the position of a data frame’s column value based on a column value of another data frame in R? | In data analysis, we encounter many problems with a lot of variations among them. One such problem is we have some information in a place that needs to be checked through a different place and these places can be data frames. Therefore, we need to find the position of a data frame’s column value based on a column value of another data frame. In R, we can easily do it with the help of which function.
Live Demo
Consider the below data frame −
set.seed(12121)
x1<−sample(0:2,20,replace=TRUE)
y1<−sample(0:5,20,replace=TRUE)
df1<−data.frame(x1,y1)
df1
x1 y1
1 0 3
2 2 2
3 0 2
4 1 4
5 0 4
6 2 0
7 0 3
8 0 1
9 2 5
10 1 0
11 0 1
12 1 1
13 0 3
14 0 0
15 2 0
16 1 5
17 0 2
18 2 0
19 1 4
20 0 5
x2<−sample(1:2,20,replace=TRUE)
y2<−sample(1:5,20,replace=TRUE)
df2<−data.frame(x2,y2)
df2
x2 y2
1 1 2
2 1 2
3 1 2
4 2 4
5 2 3
6 1 4
7 2 1
8 2 3
9 1 2
10 1 5
11 1 2
12 2 2
13 2 1
14 2 5
15 1 2
16 1 3
17 2 2
18 2 1
19 1 1
20 1 3
Finding the position of x1 of df1 in x2 of df2 −
which(df1$x1 %in% df2$x2)
[1] 2 4 6 9 10 12 15 16 18 19
Finding the position of y1 of df1 in y2 of df2 −
which(df1$y1 %in% df2$y2)
[1] 1 2 3 4 5 7 8 9 11 12 13 16 17 19 20
Let’s have a look at another example −
x3<−sample(21:25,20,replace=TRUE)
y3<−sample(26:50,20)
df3<−data.frame(x3,y3)
df3
x3 y3
1 21 39
2 24 36
3 24 31
4 22 46
5 25 27
6 24 29
7 24 30
8 23 26
9 24 45
10 22 37
11 23 35
12 23 43
13 22 38
14 22 32
15 25 49
16 23 44
17 24 34
18 21 40
19 21 47
20 25 42
Live Demo
x4<−sample(24:25,20,replace=TRUE)
y4<−sample(41:50,20,replace=TRUE)
df4<−data.frame(x4,y4)
df4
x4 y4
1 25 50
2 24 44
3 24 45
4 25 49
5 24 42
6 25 48
7 25 43
8 25 47
9 24 50
10 25 41
11 25 47
12 25 50
13 24 46
14 25 50
15 24 42
16 24 42
17 24 50
18 25 47
19 25 42
20 25 41
which(df3$x3 %in% df4$x4)
[1] 2 3 5 6 7 9 15 17 20
which(df3$y3 %in% df4$y4)
[1] 4 9 12 15 16 19 20 | [
{
"code": null,
"e": 1465,
"s": 1062,
"text": "In data analysis, we encounter many problems with a lot of variations among them. One such problem is we have some information in a place that needs to be checked through a different place and these places can be data frames. Therefore, we need to find the position of a data frame’s column value based on a column value of another data frame. In R, we can easily do it with the help of which function."
},
{
"code": null,
"e": 1476,
"s": 1465,
"text": " Live Demo"
},
{
"code": null,
"e": 1508,
"s": 1476,
"text": "Consider the below data frame −"
},
{
"code": null,
"e": 1615,
"s": 1508,
"text": "set.seed(12121)\nx1<−sample(0:2,20,replace=TRUE)\ny1<−sample(0:5,20,replace=TRUE)\ndf1<−data.frame(x1,y1)\ndf1"
},
{
"code": null,
"e": 1752,
"s": 1615,
"text": "x1 y1\n1 0 3\n2 2 2\n3 0 2\n4 1 4\n5 0 4\n6 2 0\n7 0 3\n8 0 1\n9 2 5\n10 1 0\n11 0 1\n12 1 1\n13 0 3\n14 0 0\n15 2 0\n16 1 5\n17 0 2\n18 2 0\n19 1 4\n20 0 5"
},
{
"code": null,
"e": 1843,
"s": 1752,
"text": "x2<−sample(1:2,20,replace=TRUE)\ny2<−sample(1:5,20,replace=TRUE)\ndf2<−data.frame(x2,y2)\ndf2"
},
{
"code": null,
"e": 1980,
"s": 1843,
"text": "x2 y2\n1 1 2\n2 1 2\n3 1 2\n4 2 4\n5 2 3\n6 1 4\n7 2 1\n8 2 3\n9 1 2\n10 1 5\n11 1 2\n12 2 2\n13 2 1\n14 2 5\n15 1 2\n16 1 3\n17 2 2\n18 2 1\n19 1 1\n20 1 3"
},
{
"code": null,
"e": 2029,
"s": 1980,
"text": "Finding the position of x1 of df1 in x2 of df2 −"
},
{
"code": null,
"e": 2055,
"s": 2029,
"text": "which(df1$x1 %in% df2$x2)"
},
{
"code": null,
"e": 2085,
"s": 2055,
"text": "[1] 2 4 6 9 10 12 15 16 18 19"
},
{
"code": null,
"e": 2134,
"s": 2085,
"text": "Finding the position of y1 of df1 in y2 of df2 −"
},
{
"code": null,
"e": 2160,
"s": 2134,
"text": "which(df1$y1 %in% df2$y2)"
},
{
"code": null,
"e": 2201,
"s": 2160,
"text": "[1] 1 2 3 4 5 7 8 9 11 12 13 16 17 19 20"
},
{
"code": null,
"e": 2240,
"s": 2201,
"text": "Let’s have a look at another example −"
},
{
"code": null,
"e": 2322,
"s": 2240,
"text": "x3<−sample(21:25,20,replace=TRUE)\ny3<−sample(26:50,20)\ndf3<−data.frame(x3,y3)\ndf3"
},
{
"code": null,
"e": 2502,
"s": 2322,
"text": " x3 y3\n1 21 39\n2 24 36\n3 24 31\n4 22 46\n5 25 27\n6 24 29\n7 24 30\n8 23 26\n9 24 45\n10 22 37\n11 23 35\n12 23 43\n13 22 38\n14 22 32\n15 25 49\n16 23 44\n17 24 34\n18 21 40\n19 21 47\n20 25 42"
},
{
"code": null,
"e": 2513,
"s": 2502,
"text": " Live Demo"
},
{
"code": null,
"e": 2608,
"s": 2513,
"text": "x4<−sample(24:25,20,replace=TRUE)\ny4<−sample(41:50,20,replace=TRUE)\ndf4<−data.frame(x4,y4)\ndf4"
},
{
"code": null,
"e": 2888,
"s": 2608,
"text": " x4 y4\n1 25 50\n2 24 44\n3 24 45\n4 25 49\n5 24 42\n6 25 48\n7 25 43\n8 25 47\n9 24 50\n10 25 41\n11 25 47\n12 25 50\n13 24 46\n14 25 50\n15 24 42\n16 24 42\n17 24 50\n18 25 47\n19 25 42\n20 25 41\nwhich(df3$x3 %in% df4$x4)\n[1] 2 3 5 6 7 9 15 17 20\nwhich(df3$y3 %in% df4$y4)\n[1] 4 9 12 15 16 19 20"
}
] |
java.time.LocalDateTime.minusHours() Method Example | The java.time.LocalDateTime.minusHours(long hoursToSubtract) method returns a copy of this LocalDateTime with the specified hours subtracted.
Following is the declaration for java.time.LocalDateTime.minusHours(long hoursToSubtract) method.
public LocalDateTime minusHours(long hoursToSubtract)
hoursToSubtract − the hours to subtract, may be negative.
a LocalDateTime based on this date-time with the hours subtracted, not null.
DateTimeException − if the result exceeds the supported date range.
The following example shows the usage of java.time.LocalDateTime.minusHours(long hoursToSubtract) method.
package com.tutorialspoint;
import java.time.LocalDateTime;
public class LocalDateTimeDemo {
public static void main(String[] args) {
LocalDateTime date = LocalDateTime.parse("2017-02-03T12:30:30");
System.out.println(date.minusHours(2));
}
}
Let us compile and run the above program, this will produce the following result −
2017-02-03T10:30:30
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2057,
"s": 1915,
"text": "The java.time.LocalDateTime.minusHours(long hoursToSubtract) method returns a copy of this LocalDateTime with the specified hours subtracted."
},
{
"code": null,
"e": 2155,
"s": 2057,
"text": "Following is the declaration for java.time.LocalDateTime.minusHours(long hoursToSubtract) method."
},
{
"code": null,
"e": 2210,
"s": 2155,
"text": "public LocalDateTime minusHours(long hoursToSubtract)\n"
},
{
"code": null,
"e": 2268,
"s": 2210,
"text": "hoursToSubtract − the hours to subtract, may be negative."
},
{
"code": null,
"e": 2345,
"s": 2268,
"text": "a LocalDateTime based on this date-time with the hours subtracted, not null."
},
{
"code": null,
"e": 2413,
"s": 2345,
"text": "DateTimeException − if the result exceeds the supported date range."
},
{
"code": null,
"e": 2519,
"s": 2413,
"text": "The following example shows the usage of java.time.LocalDateTime.minusHours(long hoursToSubtract) method."
},
{
"code": null,
"e": 2786,
"s": 2519,
"text": "package com.tutorialspoint;\n\nimport java.time.LocalDateTime;\n\npublic class LocalDateTimeDemo {\n public static void main(String[] args) {\n \n LocalDateTime date = LocalDateTime.parse(\"2017-02-03T12:30:30\");\n System.out.println(date.minusHours(2)); \n }\n}"
},
{
"code": null,
"e": 2869,
"s": 2786,
"text": "Let us compile and run the above program, this will produce the following result −"
},
{
"code": null,
"e": 2890,
"s": 2869,
"text": "2017-02-03T10:30:30\n"
},
{
"code": null,
"e": 2897,
"s": 2890,
"text": " Print"
},
{
"code": null,
"e": 2908,
"s": 2897,
"text": " Add Notes"
}
] |
Material Icons | Google provides a set of 750 icons designed under "material design guidelines" and these are known as Material Design icons. These icons are simple and they support all modern web browsers. Since these icons are vector based, they are scalable as well. To use these icons, we have to load the font (library) material-icons.
To load the material-icons library, copy and paste the following line in the <head> section of a webpage.
<head>
<link href = "https://fonts.googleapis.com/icon?family=Material+Icons" rel = "stylesheet">
</head>
Google's Material Icons provides a long list of icons. Choose any one of them and add the name of the icon class to any HTML element within the < body > tag. In the following example, we have used the icon named accessibility that belongs to the action category.
<!DOCTYPE html>
<html>
<head>
<link href = "https://fonts.googleapis.com/icon?family=Material+Icons" rel = "stylesheet">
</head>
<body>
<i class = "material-icons">accessibility</i>
</body>
</html>
It will produce the following output −
You can increase or decrease the size of an icon by defining its size in the CSS and using it along with the class name as shown below. In the following example, we have declared the size as 6 em.
<!DOCTYPE html>
<html>
<head>
<link href = "https://fonts.googleapis.com/icon?family=Material+Icons" rel = "stylesheet">
<style>
i.mysize {font-size: 6em;}
</style>
</head>
<body>
<i class = "material-icons mysize">accessibility</i>
</body>
</html>
It will produce the following output −
You can use the CSS to define the color of an icon. The following example shows how you can change the color of an icon called accessibility.
<!DOCTYPE html>
<html>
<head>
<link href = "https://fonts.googleapis.com/icon?family=Material+Icons" rel = "stylesheet">
<style>
i.custom {font-size: 6em; color: green;}
</style>
</head>
<body>
<i class = "material-icons custom">accessibility</i>
</body>
</html>
It will produce the following output −
Google's Material Icons font provides 519 icons in the following categories −
Action Icons
Alert Icons
AV Icons
Communication Icons
Content Icons
Device Icons
Editor Icons
File Icons
Hardware Icons
Image Icons
Maps Icons
Navigation Icons
Notification Icons
Social Icons
Toggle Icons
To use any of these icons, you have to replace the class name in the programs given in this chapter with the class name of the desired icon. In the coming chapters of this Unit (Material Icons), we have explained category-wise the usage and the respective outputs of various Material Icons.
26 Lectures
2 hours
Neha Gupta
20 Lectures
2 hours
Asif Hussain
43 Lectures
5 hours
Sharad Kumar
411 Lectures
38.5 hours
In28Minutes Official
71 Lectures
10 hours
Chaand Sheikh
207 Lectures
33 hours
Eduonix Learning Solutions
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2891,
"s": 2566,
"text": "Google provides a set of 750 icons designed under \"material design guidelines\" and these are known as Material Design icons. These icons are simple and they support all modern web browsers. Since these icons are vector based, they are scalable as well. To use these icons, we have to load the font (library) material-icons."
},
{
"code": null,
"e": 2997,
"s": 2891,
"text": "To load the material-icons library, copy and paste the following line in the <head> section of a webpage."
},
{
"code": null,
"e": 3106,
"s": 2997,
"text": "<head>\n <link href = \"https://fonts.googleapis.com/icon?family=Material+Icons\" rel = \"stylesheet\">\n</head>"
},
{
"code": null,
"e": 3369,
"s": 3106,
"text": "Google's Material Icons provides a long list of icons. Choose any one of them and add the name of the icon class to any HTML element within the < body > tag. In the following example, we have used the icon named accessibility that belongs to the action category."
},
{
"code": null,
"e": 3595,
"s": 3369,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <link href = \"https://fonts.googleapis.com/icon?family=Material+Icons\" rel = \"stylesheet\">\n </head>\n\t\n <body>\n <i class = \"material-icons\">accessibility</i>\n </body>\n\t\n</html>"
},
{
"code": null,
"e": 3634,
"s": 3595,
"text": "It will produce the following output −"
},
{
"code": null,
"e": 3831,
"s": 3634,
"text": "You can increase or decrease the size of an icon by defining its size in the CSS and using it along with the class name as shown below. In the following example, we have declared the size as 6 em."
},
{
"code": null,
"e": 4135,
"s": 3831,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <link href = \"https://fonts.googleapis.com/icon?family=Material+Icons\" rel = \"stylesheet\">\n\t\t\n <style>\n i.mysize {font-size: 6em;}\n </style>\n\t\t\n </head>\n\t\n <body>\n <i class = \"material-icons mysize\">accessibility</i>\n </body>\n\t\n</html>"
},
{
"code": null,
"e": 4174,
"s": 4135,
"text": "It will produce the following output −"
},
{
"code": null,
"e": 4316,
"s": 4174,
"text": "You can use the CSS to define the color of an icon. The following example shows how you can change the color of an icon called accessibility."
},
{
"code": null,
"e": 4634,
"s": 4316,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <link href = \"https://fonts.googleapis.com/icon?family=Material+Icons\" rel = \"stylesheet\">\n\t\t\n <style>\n i.custom {font-size: 6em; color: green;}\n </style>\n\t\t\n </head>\n\t\n <body>\n <i class = \"material-icons custom\">accessibility</i>\n </body>\n\t\n</html>"
},
{
"code": null,
"e": 4673,
"s": 4634,
"text": "It will produce the following output −"
},
{
"code": null,
"e": 4751,
"s": 4673,
"text": "Google's Material Icons font provides 519 icons in the following categories −"
},
{
"code": null,
"e": 4764,
"s": 4751,
"text": "Action Icons"
},
{
"code": null,
"e": 4776,
"s": 4764,
"text": "Alert Icons"
},
{
"code": null,
"e": 4785,
"s": 4776,
"text": "AV Icons"
},
{
"code": null,
"e": 4805,
"s": 4785,
"text": "Communication Icons"
},
{
"code": null,
"e": 4819,
"s": 4805,
"text": "Content Icons"
},
{
"code": null,
"e": 4832,
"s": 4819,
"text": "Device Icons"
},
{
"code": null,
"e": 4845,
"s": 4832,
"text": "Editor Icons"
},
{
"code": null,
"e": 4856,
"s": 4845,
"text": "File Icons"
},
{
"code": null,
"e": 4871,
"s": 4856,
"text": "Hardware Icons"
},
{
"code": null,
"e": 4883,
"s": 4871,
"text": "Image Icons"
},
{
"code": null,
"e": 4894,
"s": 4883,
"text": "Maps Icons"
},
{
"code": null,
"e": 4911,
"s": 4894,
"text": "Navigation Icons"
},
{
"code": null,
"e": 4930,
"s": 4911,
"text": "Notification Icons"
},
{
"code": null,
"e": 4943,
"s": 4930,
"text": "Social Icons"
},
{
"code": null,
"e": 4956,
"s": 4943,
"text": "Toggle Icons"
},
{
"code": null,
"e": 5247,
"s": 4956,
"text": "To use any of these icons, you have to replace the class name in the programs given in this chapter with the class name of the desired icon. In the coming chapters of this Unit (Material Icons), we have explained category-wise the usage and the respective outputs of various Material Icons."
},
{
"code": null,
"e": 5280,
"s": 5247,
"text": "\n 26 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 5292,
"s": 5280,
"text": " Neha Gupta"
},
{
"code": null,
"e": 5325,
"s": 5292,
"text": "\n 20 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 5339,
"s": 5325,
"text": " Asif Hussain"
},
{
"code": null,
"e": 5372,
"s": 5339,
"text": "\n 43 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 5386,
"s": 5372,
"text": " Sharad Kumar"
},
{
"code": null,
"e": 5423,
"s": 5386,
"text": "\n 411 Lectures \n 38.5 hours \n"
},
{
"code": null,
"e": 5445,
"s": 5423,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 5479,
"s": 5445,
"text": "\n 71 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 5494,
"s": 5479,
"text": " Chaand Sheikh"
},
{
"code": null,
"e": 5529,
"s": 5494,
"text": "\n 207 Lectures \n 33 hours \n"
},
{
"code": null,
"e": 5557,
"s": 5529,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 5564,
"s": 5557,
"text": " Print"
},
{
"code": null,
"e": 5575,
"s": 5564,
"text": " Add Notes"
}
] |
Apache Commons DBUtils - First Application | This chapter provides an example of how to create a simple JDBC application using DBUtils library. This will show you, how to open a database connection, execute a SQL query, and display the results.
All the steps mentioned in this template example, would be explained in subsequent chapters of this tutorial.
There are following six steps involved in building a JDBC application −
Import the packages − Requires that you include the packages containing the JDBC classes which are needed for database programming. Most often, using import java.sql.* will suffice.
Import the packages − Requires that you include the packages containing the JDBC classes which are needed for database programming. Most often, using import java.sql.* will suffice.
Register the JDBC driver − Requires that you initialize a driver, so you can open a communication channel with the database.
Register the JDBC driver − Requires that you initialize a driver, so you can open a communication channel with the database.
Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with the database.
Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with the database.
Execute a query − Requires using an object of type Statement for building and submitting an SQL statement to the database.
Execute a query − Requires using an object of type Statement for building and submitting an SQL statement to the database.
Extract data from result set − Requires that you use the appropriate ResultSet.getXXX() method to retrieve the data from the result set.
Extract data from result set − Requires that you use the appropriate ResultSet.getXXX() method to retrieve the data from the result set.
Clean up the environment − Requires explicitly closing all the database resources versus relying on the JVM's garbage collection.
Clean up the environment − Requires explicitly closing all the database resources versus relying on the JVM's garbage collection.
This sample example can serve as a template, when you need to create your own JDBC application in the future.
This sample code has been written based on the environment and database setup done in the previous chapter.
Copy and paste the following example in MainApp.java, compile and run as follows −
MainApp.java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.BeanHandler;
public class MainApp {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/emp";
// Database credentials
static final String USER = "root";
static final String PASS = "admin";
public static void main(String[] args) throws SQLException {
Connection conn = null;
QueryRunner queryRunner = new QueryRunner();
//Step 1: Register JDBC driver
DbUtils.loadDriver(JDBC_DRIVER);
//Step 2: Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
//Step 3: Create a ResultSet Handler to handle Employee Beans
ResultSetHandler<Employee> resultHandler = new BeanHandler<Employee>(Employee.class);
try {
Employee emp = queryRunner.query(conn,
"SELECT * FROM employees WHERE first=?", resultHandler, "Sumit");
//Display values
System.out.print("ID: " + emp.getId());
System.out.print(", Age: " + emp.getAge());
System.out.print(", First: " + emp.getFirst());
System.out.println(", Last: " + emp.getLast());
} finally {
DbUtils.close(conn);
}
}
}
Employee.java
The program is given below −
public class Employee {
private int id;
private int age;
private String first;
private String last;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getFirst() {
return first;
}
public void setFirst(String first) {
this.first = first;
}
public String getLast() {
return last;
}
public void setLast(String last) {
this.last = last;
}
}
Now let us compile the above example as follows −
C:\>javac MainApp.java Employee.java
C:\>
When you run MainApp, it produces the following result −
C:\>java MainApp
Connecting to database...
ID: 103, Age: 28, First: Sumit, Last: Mittal
C:\>
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2352,
"s": 2152,
"text": "This chapter provides an example of how to create a simple JDBC application using DBUtils library. This will show you, how to open a database connection, execute a SQL query, and display the results."
},
{
"code": null,
"e": 2462,
"s": 2352,
"text": "All the steps mentioned in this template example, would be explained in subsequent chapters of this tutorial."
},
{
"code": null,
"e": 2534,
"s": 2462,
"text": "There are following six steps involved in building a JDBC application −"
},
{
"code": null,
"e": 2716,
"s": 2534,
"text": "Import the packages − Requires that you include the packages containing the JDBC classes which are needed for database programming. Most often, using import java.sql.* will suffice."
},
{
"code": null,
"e": 2898,
"s": 2716,
"text": "Import the packages − Requires that you include the packages containing the JDBC classes which are needed for database programming. Most often, using import java.sql.* will suffice."
},
{
"code": null,
"e": 3023,
"s": 2898,
"text": "Register the JDBC driver − Requires that you initialize a driver, so you can open a communication channel with the database."
},
{
"code": null,
"e": 3148,
"s": 3023,
"text": "Register the JDBC driver − Requires that you initialize a driver, so you can open a communication channel with the database."
},
{
"code": null,
"e": 3313,
"s": 3148,
"text": "Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with the database."
},
{
"code": null,
"e": 3478,
"s": 3313,
"text": "Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with the database."
},
{
"code": null,
"e": 3601,
"s": 3478,
"text": "Execute a query − Requires using an object of type Statement for building and submitting an SQL statement to the database."
},
{
"code": null,
"e": 3724,
"s": 3601,
"text": "Execute a query − Requires using an object of type Statement for building and submitting an SQL statement to the database."
},
{
"code": null,
"e": 3861,
"s": 3724,
"text": "Extract data from result set − Requires that you use the appropriate ResultSet.getXXX() method to retrieve the data from the result set."
},
{
"code": null,
"e": 3998,
"s": 3861,
"text": "Extract data from result set − Requires that you use the appropriate ResultSet.getXXX() method to retrieve the data from the result set."
},
{
"code": null,
"e": 4128,
"s": 3998,
"text": "Clean up the environment − Requires explicitly closing all the database resources versus relying on the JVM's garbage collection."
},
{
"code": null,
"e": 4258,
"s": 4128,
"text": "Clean up the environment − Requires explicitly closing all the database resources versus relying on the JVM's garbage collection."
},
{
"code": null,
"e": 4368,
"s": 4258,
"text": "This sample example can serve as a template, when you need to create your own JDBC application in the future."
},
{
"code": null,
"e": 4476,
"s": 4368,
"text": "This sample code has been written based on the environment and database setup done in the previous chapter."
},
{
"code": null,
"e": 4559,
"s": 4476,
"text": "Copy and paste the following example in MainApp.java, compile and run as follows −"
},
{
"code": null,
"e": 4572,
"s": 4559,
"text": "MainApp.java"
},
{
"code": null,
"e": 6162,
"s": 4572,
"text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.SQLException;\n\nimport org.apache.commons.dbutils.DbUtils;\nimport org.apache.commons.dbutils.QueryRunner;\nimport org.apache.commons.dbutils.ResultSetHandler;\nimport org.apache.commons.dbutils.handlers.BeanHandler;\n\npublic class MainApp {\n // JDBC driver name and database URL\n static final String JDBC_DRIVER = \"com.mysql.jdbc.Driver\";\n static final String DB_URL = \"jdbc:mysql://localhost:3306/emp\";\n \n // Database credentials\n static final String USER = \"root\";\n static final String PASS = \"admin\";\n \n public static void main(String[] args) throws SQLException {\n Connection conn = null;\n QueryRunner queryRunner = new QueryRunner();\n \n //Step 1: Register JDBC driver\n DbUtils.loadDriver(JDBC_DRIVER);\n\n //Step 2: Open a connection\n System.out.println(\"Connecting to database...\");\n conn = DriverManager.getConnection(DB_URL, USER, PASS);\n \n //Step 3: Create a ResultSet Handler to handle Employee Beans\n ResultSetHandler<Employee> resultHandler = new BeanHandler<Employee>(Employee.class);\n \n try {\n Employee emp = queryRunner.query(conn,\n \"SELECT * FROM employees WHERE first=?\", resultHandler, \"Sumit\");\n //Display values\n System.out.print(\"ID: \" + emp.getId());\n System.out.print(\", Age: \" + emp.getAge());\n System.out.print(\", First: \" + emp.getFirst());\n System.out.println(\", Last: \" + emp.getLast());\n } finally {\n DbUtils.close(conn);\n }\n }\n}"
},
{
"code": null,
"e": 6176,
"s": 6162,
"text": "Employee.java"
},
{
"code": null,
"e": 6205,
"s": 6176,
"text": "The program is given below −"
},
{
"code": null,
"e": 6775,
"s": 6205,
"text": "public class Employee {\n private int id;\n private int age;\n private String first;\n private String last;\n public int getId() {\n return id;\n }\n public void setId(int id) {\n this.id = id;\n }\n public int getAge() {\n return age;\n }\n public void setAge(int age) {\n this.age = age;\n }\n public String getFirst() {\n return first;\n }\n public void setFirst(String first) {\n this.first = first;\n }\n public String getLast() {\n return last;\n }\n public void setLast(String last) {\n this.last = last;\n }\n}"
},
{
"code": null,
"e": 6825,
"s": 6775,
"text": "Now let us compile the above example as follows −"
},
{
"code": null,
"e": 6868,
"s": 6825,
"text": "C:\\>javac MainApp.java Employee.java\nC:\\>\n"
},
{
"code": null,
"e": 6925,
"s": 6868,
"text": "When you run MainApp, it produces the following result −"
},
{
"code": null,
"e": 7019,
"s": 6925,
"text": "C:\\>java MainApp\nConnecting to database...\nID: 103, Age: 28, First: Sumit, Last: Mittal\nC:\\>\n"
},
{
"code": null,
"e": 7026,
"s": 7019,
"text": " Print"
},
{
"code": null,
"e": 7037,
"s": 7026,
"text": " Add Notes"
}
] |
Arithmetic operations using OpenCV in Python | In this tutorial, we are going to perform arithmetic operations on images using OpenCV in Python. We need to install the OpenCV module.
Run the following command to install the OpenCV module.
pip install opencv-python==4.1.1.26
If you run the above command, you will get the following successful message.
Collecting opencv-python==4.1.1.26
Downloading https://files.pythonhosted.org/packages/1f/51/e0b9cef23098bc31c77b0e0
6221dd8d05119b9782d4c2b1d1482e22b5f5e/opencv_python-4.1.1.26-cp37-cp37m-win_amd64.w
hl (39.0MB)
Requirement already satisfied: numpy>=1.14.5 in c:\users\hafeezulkareem\anaconda3\l
ib\site-packages (from opencv-python==4.1.1.26) (1.16.2)
Installing collected packages: opencv-python
Successfully installed opencv-python-4.1.1.26
We need two images for the addition. We have a method called cv2.add(image_one,
image_two) to perform addition. It's very hand method. The sizes of the two images must be the same. Let's see the images.
Image One
Image two
Let's see the code.
# importing cv2 module
import cv2
# reading the images and storing in variables
image_one = cv2.imread('_one.jpg')
image_two = cv2.imread('_two.jpg')
# adding two images
result_image = cv2.add(image_one, image_two)
# displaying the final image
cv2.imshow('Final Image', result_image)
# deallocating the memory
if cv2.waitKey(0) & 0xff == 27:
cv2.destroyAllWindows()
Result Image
We have a method called cv2.substract(image_one, image_two) to perform subtraction on two images. We are going to use the same images as an addition. Let's see the code.
# importing cv2 module
import cv2
# reading the images and storing in variables
image_one = cv2.imread('_one.jpg')
image_two = cv2.imread('_two.jpg')
# substracting two images
result_image = cv2.subtract(image_one, image_two)
# displaying the final image
cv2.imshow('Final Image', result_image)
# deallocating the memory
if cv2.waitKey(0) & 0xff == 27:
cv2.destroyAllWindows()
Result Image
If you have any doubts regarding the tutorial, mention them in the comment section. | [
{
"code": null,
"e": 1198,
"s": 1062,
"text": "In this tutorial, we are going to perform arithmetic operations on images using OpenCV in Python. We need to install the OpenCV module."
},
{
"code": null,
"e": 1254,
"s": 1198,
"text": "Run the following command to install the OpenCV module."
},
{
"code": null,
"e": 1290,
"s": 1254,
"text": "pip install opencv-python==4.1.1.26"
},
{
"code": null,
"e": 1367,
"s": 1290,
"text": "If you run the above command, you will get the following successful message."
},
{
"code": null,
"e": 1812,
"s": 1367,
"text": "Collecting opencv-python==4.1.1.26\nDownloading https://files.pythonhosted.org/packages/1f/51/e0b9cef23098bc31c77b0e0\n6221dd8d05119b9782d4c2b1d1482e22b5f5e/opencv_python-4.1.1.26-cp37-cp37m-win_amd64.w\nhl (39.0MB)\nRequirement already satisfied: numpy>=1.14.5 in c:\\users\\hafeezulkareem\\anaconda3\\l\nib\\site-packages (from opencv-python==4.1.1.26) (1.16.2)\nInstalling collected packages: opencv-python\nSuccessfully installed opencv-python-4.1.1.26"
},
{
"code": null,
"e": 2015,
"s": 1812,
"text": "We need two images for the addition. We have a method called cv2.add(image_one,\nimage_two) to perform addition. It's very hand method. The sizes of the two images must be the same. Let's see the images."
},
{
"code": null,
"e": 2025,
"s": 2015,
"text": "Image One"
},
{
"code": null,
"e": 2035,
"s": 2025,
"text": "Image two"
},
{
"code": null,
"e": 2055,
"s": 2035,
"text": "Let's see the code."
},
{
"code": null,
"e": 2424,
"s": 2055,
"text": "# importing cv2 module\nimport cv2\n# reading the images and storing in variables\nimage_one = cv2.imread('_one.jpg')\nimage_two = cv2.imread('_two.jpg')\n# adding two images\nresult_image = cv2.add(image_one, image_two)\n# displaying the final image\ncv2.imshow('Final Image', result_image)\n# deallocating the memory\nif cv2.waitKey(0) & 0xff == 27:\n cv2.destroyAllWindows()"
},
{
"code": null,
"e": 2437,
"s": 2424,
"text": "Result Image"
},
{
"code": null,
"e": 2607,
"s": 2437,
"text": "We have a method called cv2.substract(image_one, image_two) to perform subtraction on two images. We are going to use the same images as an addition. Let's see the code."
},
{
"code": null,
"e": 2987,
"s": 2607,
"text": "# importing cv2 module\nimport cv2\n# reading the images and storing in variables\nimage_one = cv2.imread('_one.jpg')\nimage_two = cv2.imread('_two.jpg')\n# substracting two images\nresult_image = cv2.subtract(image_one, image_two)\n# displaying the final image\ncv2.imshow('Final Image', result_image)\n# deallocating the memory\nif cv2.waitKey(0) & 0xff == 27:\n cv2.destroyAllWindows()"
},
{
"code": null,
"e": 3000,
"s": 2987,
"text": "Result Image"
},
{
"code": null,
"e": 3084,
"s": 3000,
"text": "If you have any doubts regarding the tutorial, mention them in the comment section."
}
] |
Maximum sum of i*arr[i] among all rotations of a given array | 04 Jul, 2022
Given an array arr[] of n integers, find the maximum that maximizes the sum of the value of i*arr[i] where i varies from 0 to n-1.
Examples:
Input: arr[] = {8, 3, 1, 2}
Output: 29
Explanation: Lets look at all the rotations,
{8, 3, 1, 2} = 8*0 + 3*1 + 1*2 + 2*3 = 11
{3, 1, 2, 8} = 3*0 + 1*1 + 2*2 + 8*3 = 29
{1, 2, 8, 3} = 1*0 + 2*1 + 8*2 + 3*3 = 27
{2, 8, 3, 1} = 2*0 + 8*1 + 3*2 + 1*3 = 17
Input: arr[] = {3, 2, 1}
Output: 7
Explanation: Lets look at all the rotations,
{3, 2, 1} = 3*0 + 2*1 + 1*2 = 4
{2, 1, 3} = 2*0 + 1*1 + 3*2 = 7
{1, 3, 2} = 1*0 + 3*1 + 2*2 = 7
Method 1: This method discusses the Naive Solution which takes O(n2) amount of time. The solution involves finding the sum of all the elements of the array in each rotation and then deciding the maximum summation value.
Approach:A simple solution is to try all possible rotations. Compute sum of i*arr[i] for every rotation and return maximum sum.
Algorithm:Rotate the array for all values from 0 to n.Calculate the sum for each rotations.Check if the maximum sum is greater than the current sum then update the maximum sum.
Rotate the array for all values from 0 to n.Calculate the sum for each rotations.Check if the maximum sum is greater than the current sum then update the maximum sum.
Rotate the array for all values from 0 to n.
Calculate the sum for each rotations.
Check if the maximum sum is greater than the current sum then update the maximum sum.
Implementation:
C++
Java
Python3
C#
PHP
Javascript
// A Naive C++ program to find maximum sum rotation#include<bits/stdc++.h> using namespace std; // Returns maximum value of i*arr[i]int maxSum(int arr[], int n){ // Initialize result int res = INT_MIN; // Consider rotation beginning with i // for all possible values of i. for (int i=0; i<n; i++) { // Initialize sum of current rotation int curr_sum = 0; // Compute sum of all values. We don't // actually rotate the array, instead of that we compute the // sum by finding indexes when arr[i] is // first element for (int j=0; j<n; j++) { int index = (i+j)%n; curr_sum += j*arr[index]; } // Update result if required res = max(res, curr_sum); } return res;} // Driver codeint main(){ int arr[] = {8, 3, 1, 2}; int n = sizeof(arr)/sizeof(arr[0]); cout << maxSum(arr, n) << endl; return 0;}
// A Naive Java program to find// maximum sum rotationimport java.util.*;import java.io.*; class GFG { // Returns maximum value of i*arr[i]static int maxSum(int arr[], int n){// Initialize resultint res = Integer.MIN_VALUE; // Consider rotation beginning with i// for all possible values of i.for (int i = 0; i < n; i++){ // Initialize sum of current rotation int curr_sum = 0; // Compute sum of all values. We don't // actually rotation the array, but compute // sum by finding indexes when arr[i] is // first element for (int j = 0; j < n; j++) { int index = (i + j) % n; curr_sum += j * arr[index]; } // Update result if required res = Math.max(res, curr_sum);} return res;} // Driver codepublic static void main(String args[]){ int arr[] = {8, 3, 1, 2}; int n = arr.length; System.out.println(maxSum(arr, n));} } // This code is contributed by Sahil_Bansall
# A Naive Python3 program to find# maximum sum rotationimport sys # Returns maximum value of i * arr[i]def maxSum(arr, n): # Initialize result res = -sys.maxsize # Consider rotation beginning with i # for all possible values of i. for i in range(0, n): # Initialize sum of current rotation curr_sum = 0 # Compute sum of all values. We don't # actually rotation the array, but # compute sum by finding indexes when # arr[i] is first element for j in range(0, n): index = int((i + j)% n) curr_sum += j * arr[index] # Update result if required res = max(res, curr_sum) return res # Driver codearr = [8, 3, 1, 2]n = len(arr) print(maxSum(arr, n)) # This code is contributed by# Smitha Dinesh Semwal
// A Naive C# program to find// maximum sum rotationusing System; class GFG { // Returns maximum value of i*arr[i] static int maxSum(int[] arr, int n) { // Initialize result int res = int.MinValue; // Consider rotation beginning with i // for all possible values of i. for (int i = 0; i < n; i++) { // Initialize sum of current rotation int curr_sum = 0; // Compute sum of all values. We don't // actually rotate the array, instead we compute // sum by finding indexes when arr[i] is the // first element for (int j = 0; j < n; j++) { int index = (i + j) % n; curr_sum += j * arr[index]; } // Update result if required res = Math.Max(res, curr_sum); } return res; } // Driver code public static void Main() { int[] arr = { 8, 3, 1, 2 }; int n = arr.Length; Console.WriteLine(maxSum(arr, n)); }} // This code is contributed by vt_m.
<?php// A Naive PHP program to// find maximum sum rotation // Returns maximum value// of i*arr[i]function maxSum($arr, $n){// Initialize result$res = PHP_INT_MIN; // Consider rotation beginning// with i for all possible// values of i.for ($i = 0; $i < $n; $i++){ // Initialize sum of // current rotation $curr_sum = 0; // Compute sum of all values. // We don't actually rotate // the array, but compute sum // by finding indexes when // arr[i] is first element for ($j = 0; $j < $n; $j++) { $index = ($i + $j) % $n; $curr_sum += $j * $arr[$index]; } // Update result if required $res = max($res, $curr_sum);}return $res;} // Driver code$arr = array(8, 3, 1, 2);$n = sizeof($arr);echo maxSum($arr, $n), "\n"; // This code is contributed by ajit?>
<script>// A Naive javascript program to find// maximum sum rotation // Returns maximum value of i*arr[i] function maxSum(arr , n) { // Initialize result var res = Number.MIN_VALUE; // Consider rotation beginning with i // for all possible values of i. for (i = 0; i < n; i++) { // Initialize sum of current rotation var curr_sum = 0; // Compute sum of all values. We don't // actually rotation the array, but compute // sum by finding indexes when arr[i] is // first element for (j = 0; j < n; j++) { var index = (i + j) % n; curr_sum += j * arr[index]; } // Update result if required res = Math.max(res, curr_sum); } return res; } // Driver code var arr = [ 8, 3, 1, 2 ]; var n = arr.length; document.write(maxSum(arr, n)); // This code contributed by umadevi9616</script>
29
Complexity Analysis: Time Complexity : O(n2)Auxiliary Space : O(1)
Time Complexity : O(n2)
Auxiliary Space : O(1)
Method 2: This method discusses the efficient solution which solves the problem in O(n) time. In the naive solution, the values were calculated for every rotation. So if that can be done in constant time then the complexity will decrease.
Approach: The basic approach is to calculate the sum of new rotation from the previous rotations. This brings up a similarity where only the multipliers of first and last element change drastically and the multiplier of every other element increases or decreases by 1. So in this way, the sum of next rotation can be calculated from the sum of present rotation.
Algorithm: The idea is to compute the value of a rotation using values of previous rotation. When an array is rotated by one, following changes happen in sum of i*arr[i]. Multiplier of arr[i-1] changes from 0 to n-1, i.e., arr[i-1] * (n-1) is added to current value.Multipliers of other terms is decremented by 1. i.e., (cum_sum – arr[i-1]) is subtracted from current value where cum_sum is sum of all numbers.
Multiplier of arr[i-1] changes from 0 to n-1, i.e., arr[i-1] * (n-1) is added to current value.Multipliers of other terms is decremented by 1. i.e., (cum_sum – arr[i-1]) is subtracted from current value where cum_sum is sum of all numbers.
Multiplier of arr[i-1] changes from 0 to n-1, i.e., arr[i-1] * (n-1) is added to current value.
Multipliers of other terms is decremented by 1. i.e., (cum_sum – arr[i-1]) is subtracted from current value where cum_sum is sum of all numbers.
next_val = curr_val - (cum_sum - arr[i-1]) + arr[i-1] * (n-1);
next_val = Value of ∑i*arr[i] after one rotation.
curr_val = Current value of ∑i*arr[i]
cum_sum = Sum of all array elements, i.e., ∑arr[i].
Lets take example {1, 2, 3}. Current value is 1*0+2*1+3*2
= 8. Shifting it by one will make it {2, 3, 1} and next value
will be 8 - (6 - 1) + 1*2 = 5 which is same as 2*0 + 3*1 + 1*2
Implementation:
C++
Java
Python3
C#
PHP
Javascript
// An efficient C++ program to compute// maximum sum of i*arr[i]#include<bits/stdc++.h> using namespace std; int maxSum(int arr[], int n){ // Compute sum of all array elements int cum_sum = 0; for (int i=0; i<n; i++) cum_sum += arr[i]; // Compute sum of i*arr[i] for initial // configuration. int curr_val = 0; for (int i=0; i<n; i++) curr_val += i*arr[i]; // Initialize result int res = curr_val; // Compute values for other iterations for (int i=1; i<n; i++) { // Compute next value using previous // value in O(1) time int next_val = curr_val - (cum_sum - arr[i-1]) + arr[i-1] * (n-1); // Update current value curr_val = next_val; // Update result if required res = max(res, next_val); } return res;} // Driver codeint main(){ int arr[] = {8, 3, 1, 2}; int n = sizeof(arr)/sizeof(arr[0]); cout << maxSum(arr, n) << endl; return 0;}
// An efficient Java program to compute// maximum sum of i*arr[i]import java.io.*; class GFG { static int maxSum(int arr[], int n) { // Compute sum of all array elements int cum_sum = 0; for (int i = 0; i < n; i++) cum_sum += arr[i]; // Compute sum of i*arr[i] for // initial configuration. int curr_val = 0; for (int i = 0; i < n; i++) curr_val += i * arr[i]; // Initialize result int res = curr_val; // Compute values for other iterations for (int i = 1; i < n; i++) { // Compute next value using previous // value in O(1) time int next_val = curr_val - (cum_sum - arr[i-1]) + arr[i-1] * (n-1); // Update current value curr_val = next_val; // Update result if required res = Math.max(res, next_val); } return res; } // Driver code public static void main(String[] args) { int arr[] = {8, 3, 1, 2}; int n = arr.length; System.out.println(maxSum(arr, n)); }}// This code is contributed by Prerna Saini
# An efficient Python3 program to# compute maximum sum of i * arr[i] def maxSum(arr, n): # Compute sum of all array elements cum_sum = 0 for i in range(0, n): cum_sum += arr[i] # Compute sum of i * arr[i] for # initial configuration. curr_val = 0 for i in range(0, n): curr_val += i * arr[i] # Initialize result res = curr_val # Compute values for other iterations for i in range(1, n): # Compute next value using previous # value in O(1) time next_val = (curr_val - (cum_sum - arr[i-1]) + arr[i-1] * (n-1)) # Update current value curr_val = next_val # Update result if required res = max(res, next_val) return res # Driver codearr = [8, 3, 1, 2]n = len(arr) print(maxSum(arr, n)) # This code is contributed by# Smitha Dinesh Semwal
// An efficient C# program to compute// maximum sum of i*arr[i]using System; class GFG { static int maxSum(int []arr, int n) { // Compute sum of all array elements int cum_sum = 0; for (int i = 0; i < n; i++) cum_sum += arr[i]; // Compute sum of i*arr[i] for // initial configuration. int curr_val = 0; for (int i = 0; i < n; i++) curr_val += i * arr[i]; // Initialize result int res = curr_val; // Compute values for other iterations for (int i = 1; i < n; i++) { // Compute next value using previous // value in O(1) time int next_val = curr_val - (cum_sum - arr[i - 1]) + arr[i - 1] * (n - 1); // Update current value curr_val = next_val; // Update result if required res = Math.Max(res, next_val); } return res; } // Driver code public static void Main() { int []arr = {8, 3, 1, 2}; int n = arr.Length; Console.Write(maxSum(arr, n)); }} // This code is contributed by nitin mittal
<?php// An efficient PHP program to// compute maximum sum of i*arr[i] function maxSum($arr, $n){ // Compute sum of all // array elements $cum_sum = 0; for ($i = 0; $i < $n; $i++) $cum_sum += $arr[$i]; // Compute sum of i*arr[i] // for initial configuration. $curr_val = 0; for ($i = 0; $i < $n; $i++) $curr_val += $i * $arr[$i]; // Initialize result $res = $curr_val; // Compute values for // other iterations for ($i = 1; $i < $n; $i++) { // Compute next value using // previous value in O(1) time $next_val = $curr_val - ($cum_sum - $arr[$i - 1]) + $arr[$i - 1] * ($n - 1); // Update current value $curr_val = $next_val; // Update result if required $res = max($res, $next_val); } return $res;} // Driver code$arr = array(8, 3, 1, 2);$n = sizeof($arr);echo maxSum($arr, $n); // This code is contributed by ajit?>
<script>// An efficient JavaScript program to compute// maximum sum of i*arr[i] function maxSum(arr, n){ // Compute sum of all array elements let cum_sum = 0; for (let i=0; i<n; i++) cum_sum += arr[i]; // Compute sum of i*arr[i] for initial // configuration. let curr_val = 0; for (let i=0; i<n; i++) curr_val += i*arr[i]; // Initialize result let res = curr_val; // Compute values for other iterations for (let i=1; i<n; i++) { // Compute next value using previous // value in O(1) time let next_val = curr_val - (cum_sum - arr[i-1]) + arr[i-1] * (n-1); // Update current value curr_val = next_val; // Update result if required res = Math.max(res, next_val); } return res;} // Driver code let arr = [8, 3, 1, 2]; let n = arr.length; document.write(maxSum(arr, n) + "<br>"); // This code is contributed by Surbhi Tyagi.</script>
29
Complexity analysis: Time Complexity: O(n). Since one loop is needed from 0 to n to check all rotations and the sum of the present rotation is calculated from the previous rotations in O(1) time).Auxiliary Space: O(1). As no extra space is required to so the space complexity will be O(1)
Time Complexity: O(n). Since one loop is needed from 0 to n to check all rotations and the sum of the present rotation is calculated from the previous rotations in O(1) time).
Auxiliary Space: O(1). As no extra space is required to so the space complexity will be O(1)
Method 3: The method discusses the solution using pivot in O(n) time. The pivot method can only be used in the case of a sorted or a rotated sorted array. For example: {1, 2, 3, 4} or {2, 3, 4, 1}, {3, 4, 1, 2} etc.
Approach: Let’s assume the case of a sorted array. As we know for an array the maximum sum will be when the array is sorted in ascending order. In case of a sorted rotated array, we can rotate the array to make it in ascending order. So, in this case, the pivot element is needed to be found following which the maximum sum can be calculated.
Algorithm: Find the pivot of the array: if arr[i] > arr[(i+1)%n] then it is the pivot element. (i+1)%n is used to check for the last and first element.After getting pivot the sum can be calculated by finding the difference with the pivot which will be the multiplier and multiply it with the current element while calculating the sum
Find the pivot of the array: if arr[i] > arr[(i+1)%n] then it is the pivot element. (i+1)%n is used to check for the last and first element.After getting pivot the sum can be calculated by finding the difference with the pivot which will be the multiplier and multiply it with the current element while calculating the sum
Find the pivot of the array: if arr[i] > arr[(i+1)%n] then it is the pivot element. (i+1)%n is used to check for the last and first element.
After getting pivot the sum can be calculated by finding the difference with the pivot which will be the multiplier and multiply it with the current element while calculating the sum
Implementations:
C++
C
Java
Python3
C#
PHP
Javascript
// C++ program to find maximum sum of all// rotation of i*arr[i] using pivot.#include <iostream>using namespace std; // fun declarationint maxSum(int arr[], int n);int findPivot(int arr[], int n); // function definitionint maxSum(int arr[], int n){ int sum = 0; int i; int pivot = findPivot(arr, n); // difference in pivot and index of // last element of array int diff = n - 1 - pivot; for(i = 0; i < n; i++) { sum = sum + ((i + diff) % n) * arr[i]; } return sum;} // function to find pivotint findPivot(int arr[], int n){ int i; for(i = 0; i < n; i++) { if(arr[i] > arr[(i + 1) % n]) return i; }} // Driver codeint main(void){ // rotated input array int arr[] = {8, 3, 1, 2}; int n = sizeof(arr) / sizeof(int); int max = maxSum(arr, n); cout << max; return 0;} // This code is contributed by Shubhamsingh10
// C program to find maximum sum of all// rotation of i*arr[i] using pivot.#include<stdio.h> // fun declarationint maxSum(int arr[], int n);int findPivot(int arr[], int n); // function definitionint maxSum(int arr[], int n){ int sum = 0; int i; int pivot = findPivot(arr, n); // difference in pivot and index of // last element of array int diff = n - 1 - pivot; for(i = 0; i < n; i++) { sum= sum + ((i + diff) % n) * arr[i]; } return sum;} // function to find pivotint findPivot(int arr[], int n){ int i; for(i = 0; i < n; i++) { if(arr[i] > arr[(i + 1) % n]) return i; }} // Driver codeint main(void){ // rotated input array int arr[] = {8, 3, 1, 2}; int n = sizeof(arr) / sizeof(int); int max = maxSum(arr, n); printf("%d", max); return 0;}
// Java program to find maximum sum// of all rotation of i*arr[i] using pivot. import java.util.*;import java.lang.*;import java.io.*; class GFG{ // function definitionstatic int maxSum(int arr[], int n){ int sum = 0; int i; int pivot = findPivot(arr, n); // difference in pivot and index of // last element of array int diff = n - 1 - pivot; for(i = 0; i < n; i++) { sum= sum + ((i + diff) % n) * arr[i]; } return sum;} // function to find pivotstatic int findPivot(int arr[], int n){ int i; for(i = 0; i < n; i++) { if(arr[i] > arr[(i + 1) % n]) return i; } return 0;} // Driver codepublic static void main(String args[]){ // rotated input array int arr[] = {8, 3, 1, 2}; int n = arr.length; int max = maxSum(arr,n); System.out.println(max); }}
# Python3 program to find maximum sum of# all rotation of i*arr[i] using pivot. # function definitiondef maxSum(arr, n) : sum = 0 pivot = findPivot(arr, n) # difference in pivot and index # of last element of array diff = n - 1 - pivot for i in range(n) : sum = sum + ((i + diff) % n) * arr[i]; return sum # function to find pivotdef findPivot(arr, n) : for i in range(n) : if(arr[i] > arr[(i + 1) % n]) : return i; # Driver codeif __name__ == "__main__" : # rotated input array arr = [8, 3, 1, 2] n= len(arr) max= maxSum(arr, n) print(max) # This code is contributed by Ryuga
// C# program to find maximum sum// of all rotation of i*arr[i] using pivot.using System; class GFG{ // function definitionpublic static int maxSum(int[] arr, int n){ int sum = 0; int i; int pivot = findPivot(arr,n); // difference in pivot and index of // last element of array int diff = n - 1 - pivot; for (i = 0;i < n;i++) { sum = sum + ((i + diff) % n) * arr[i]; } return sum; } // function to find pivotpublic static int findPivot(int[] arr, int n){ int i; for (i = 0; i < n; i++) { if (arr[i] > arr[(i + 1) % n]) { return i; } } return 0; } // Driver codepublic static void Main(string[] args){ // rotated input array int[] arr = new int[] {8, 3, 1, 2}; int n = arr.Length; int max = maxSum(arr,n); Console.WriteLine(max);}} // This code is contributed by Shrikant13
<?php// PHP program to find maximum sum// of all rotation of i*arr[i] using pivot. // function definitionfunction maxSum($arr, $n){$sum = 0;$pivot = findPivot($arr, $n); // difference in pivot and index of// last element of array$diff = $n - 1 - $pivot;for($i = 0; $i < $n; $i++){ $sum = $sum + (($i + $diff) % $n) * $arr[$i];} return $sum; } // function to find pivotfunction findPivot($arr, $n){ for($i = 0; $i < $n; $i++) { if($arr[$i] > $arr[($i + 1) % $n]) return $i; } return 0;} // Driver code // rotated input array$arr = array(8, 3, 1, 2);$n = sizeof($arr);$max = maxSum($arr, $n);echo $max; // This code is contributed// by Akanksha Rai(Abby_akku)?>
<script> // js program to find maximum sum// of all rotation of i*arr[i] using pivot. // function definitionfunction maxSum(arr, n){ let sum = 0; let i; let pivot = findPivot(arr,n); // difference in pivot and index of // last element of array let diff = n - 1 - pivot; for (i = 0;i < n;i++) { sum = sum + ((i + diff) % n) * arr[i]; } return sum; } // function to find pivotfunction findPivot(arr, n){ let i; for (i = 0; i < n; i++) { if (arr[i] > arr[(i + 1) % n]) { return i; } } return 0;} // Driver code // rotated input arraylet arr = [8, 3, 1, 2];let n = arr.length;let ma = maxSum(arr,n);document.write(ma); // This code is contributed by mohit kumar 29.</script>
29
Complexity analysis: Time Complexity : O(n) As only one loop was needed to traverse from 0 to n to find the pivot. To find the sum another loop was needed, so the complexity remains O(n).Auxiliary Space : O(1). We do not require extra space to so the Auxiliary space is O(1)
Time Complexity : O(n) As only one loop was needed to traverse from 0 to n to find the pivot. To find the sum another loop was needed, so the complexity remains O(n).
Auxiliary Space : O(1). We do not require extra space to so the Auxiliary space is O(1)
This article is contributed by Shubham Joshi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
nitin mittal
jit_t
RSaini
tufan_gupta2000
shrikanth13
Akanksha_Rai
ankthon
jyotiradityafc
green_horn
Samim Jahin
SHUBHAMSINGH10
andrew1234
jaredliw
surbhityagi15
umadevi9616
mohit kumar 29
hapysingh1313
abhishek0719kadiyan
simmytarika5
hardikkoriintern
Amazon
rotation
Arrays
Amazon
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Arrays in Java
Write a program to reverse an array or string
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Largest Sum Contiguous Subarray
Arrays in C/C++
Multidimensional Arrays in Java
Stack Data Structure (Introduction and Program)
Linear Search
Subset Sum Problem | DP-25 | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n04 Jul, 2022"
},
{
"code": null,
"e": 185,
"s": 54,
"text": "Given an array arr[] of n integers, find the maximum that maximizes the sum of the value of i*arr[i] where i varies from 0 to n-1."
},
{
"code": null,
"e": 197,
"s": 185,
"text": "Examples: "
},
{
"code": null,
"e": 626,
"s": 197,
"text": "Input: arr[] = {8, 3, 1, 2}\nOutput: 29\nExplanation: Lets look at all the rotations,\n{8, 3, 1, 2} = 8*0 + 3*1 + 1*2 + 2*3 = 11\n{3, 1, 2, 8} = 3*0 + 1*1 + 2*2 + 8*3 = 29\n{1, 2, 8, 3} = 1*0 + 2*1 + 8*2 + 3*3 = 27\n{2, 8, 3, 1} = 2*0 + 8*1 + 3*2 + 1*3 = 17\n\nInput: arr[] = {3, 2, 1}\nOutput: 7\nExplanation: Lets look at all the rotations,\n{3, 2, 1} = 3*0 + 2*1 + 1*2 = 4\n{2, 1, 3} = 2*0 + 1*1 + 3*2 = 7\n{1, 3, 2} = 1*0 + 3*1 + 2*2 = 7"
},
{
"code": null,
"e": 847,
"s": 626,
"text": "Method 1: This method discusses the Naive Solution which takes O(n2) amount of time. The solution involves finding the sum of all the elements of the array in each rotation and then deciding the maximum summation value. "
},
{
"code": null,
"e": 975,
"s": 847,
"text": "Approach:A simple solution is to try all possible rotations. Compute sum of i*arr[i] for every rotation and return maximum sum."
},
{
"code": null,
"e": 1152,
"s": 975,
"text": "Algorithm:Rotate the array for all values from 0 to n.Calculate the sum for each rotations.Check if the maximum sum is greater than the current sum then update the maximum sum."
},
{
"code": null,
"e": 1319,
"s": 1152,
"text": "Rotate the array for all values from 0 to n.Calculate the sum for each rotations.Check if the maximum sum is greater than the current sum then update the maximum sum."
},
{
"code": null,
"e": 1364,
"s": 1319,
"text": "Rotate the array for all values from 0 to n."
},
{
"code": null,
"e": 1402,
"s": 1364,
"text": "Calculate the sum for each rotations."
},
{
"code": null,
"e": 1488,
"s": 1402,
"text": "Check if the maximum sum is greater than the current sum then update the maximum sum."
},
{
"code": null,
"e": 1504,
"s": 1488,
"text": "Implementation:"
},
{
"code": null,
"e": 1508,
"s": 1504,
"text": "C++"
},
{
"code": null,
"e": 1513,
"s": 1508,
"text": "Java"
},
{
"code": null,
"e": 1521,
"s": 1513,
"text": "Python3"
},
{
"code": null,
"e": 1524,
"s": 1521,
"text": "C#"
},
{
"code": null,
"e": 1528,
"s": 1524,
"text": "PHP"
},
{
"code": null,
"e": 1539,
"s": 1528,
"text": "Javascript"
},
{
"code": "// A Naive C++ program to find maximum sum rotation#include<bits/stdc++.h> using namespace std; // Returns maximum value of i*arr[i]int maxSum(int arr[], int n){ // Initialize result int res = INT_MIN; // Consider rotation beginning with i // for all possible values of i. for (int i=0; i<n; i++) { // Initialize sum of current rotation int curr_sum = 0; // Compute sum of all values. We don't // actually rotate the array, instead of that we compute the // sum by finding indexes when arr[i] is // first element for (int j=0; j<n; j++) { int index = (i+j)%n; curr_sum += j*arr[index]; } // Update result if required res = max(res, curr_sum); } return res;} // Driver codeint main(){ int arr[] = {8, 3, 1, 2}; int n = sizeof(arr)/sizeof(arr[0]); cout << maxSum(arr, n) << endl; return 0;}",
"e": 2421,
"s": 1539,
"text": null
},
{
"code": "// A Naive Java program to find// maximum sum rotationimport java.util.*;import java.io.*; class GFG { // Returns maximum value of i*arr[i]static int maxSum(int arr[], int n){// Initialize resultint res = Integer.MIN_VALUE; // Consider rotation beginning with i// for all possible values of i.for (int i = 0; i < n; i++){ // Initialize sum of current rotation int curr_sum = 0; // Compute sum of all values. We don't // actually rotation the array, but compute // sum by finding indexes when arr[i] is // first element for (int j = 0; j < n; j++) { int index = (i + j) % n; curr_sum += j * arr[index]; } // Update result if required res = Math.max(res, curr_sum);} return res;} // Driver codepublic static void main(String args[]){ int arr[] = {8, 3, 1, 2}; int n = arr.length; System.out.println(maxSum(arr, n));} } // This code is contributed by Sahil_Bansall",
"e": 3359,
"s": 2421,
"text": null
},
{
"code": "# A Naive Python3 program to find# maximum sum rotationimport sys # Returns maximum value of i * arr[i]def maxSum(arr, n): # Initialize result res = -sys.maxsize # Consider rotation beginning with i # for all possible values of i. for i in range(0, n): # Initialize sum of current rotation curr_sum = 0 # Compute sum of all values. We don't # actually rotation the array, but # compute sum by finding indexes when # arr[i] is first element for j in range(0, n): index = int((i + j)% n) curr_sum += j * arr[index] # Update result if required res = max(res, curr_sum) return res # Driver codearr = [8, 3, 1, 2]n = len(arr) print(maxSum(arr, n)) # This code is contributed by# Smitha Dinesh Semwal",
"e": 4181,
"s": 3359,
"text": null
},
{
"code": "// A Naive C# program to find// maximum sum rotationusing System; class GFG { // Returns maximum value of i*arr[i] static int maxSum(int[] arr, int n) { // Initialize result int res = int.MinValue; // Consider rotation beginning with i // for all possible values of i. for (int i = 0; i < n; i++) { // Initialize sum of current rotation int curr_sum = 0; // Compute sum of all values. We don't // actually rotate the array, instead we compute // sum by finding indexes when arr[i] is the // first element for (int j = 0; j < n; j++) { int index = (i + j) % n; curr_sum += j * arr[index]; } // Update result if required res = Math.Max(res, curr_sum); } return res; } // Driver code public static void Main() { int[] arr = { 8, 3, 1, 2 }; int n = arr.Length; Console.WriteLine(maxSum(arr, n)); }} // This code is contributed by vt_m.",
"e": 5265,
"s": 4181,
"text": null
},
{
"code": "<?php// A Naive PHP program to// find maximum sum rotation // Returns maximum value// of i*arr[i]function maxSum($arr, $n){// Initialize result$res = PHP_INT_MIN; // Consider rotation beginning// with i for all possible// values of i.for ($i = 0; $i < $n; $i++){ // Initialize sum of // current rotation $curr_sum = 0; // Compute sum of all values. // We don't actually rotate // the array, but compute sum // by finding indexes when // arr[i] is first element for ($j = 0; $j < $n; $j++) { $index = ($i + $j) % $n; $curr_sum += $j * $arr[$index]; } // Update result if required $res = max($res, $curr_sum);}return $res;} // Driver code$arr = array(8, 3, 1, 2);$n = sizeof($arr);echo maxSum($arr, $n), \"\\n\"; // This code is contributed by ajit?>",
"e": 6067,
"s": 5265,
"text": null
},
{
"code": "<script>// A Naive javascript program to find// maximum sum rotation // Returns maximum value of i*arr[i] function maxSum(arr , n) { // Initialize result var res = Number.MIN_VALUE; // Consider rotation beginning with i // for all possible values of i. for (i = 0; i < n; i++) { // Initialize sum of current rotation var curr_sum = 0; // Compute sum of all values. We don't // actually rotation the array, but compute // sum by finding indexes when arr[i] is // first element for (j = 0; j < n; j++) { var index = (i + j) % n; curr_sum += j * arr[index]; } // Update result if required res = Math.max(res, curr_sum); } return res; } // Driver code var arr = [ 8, 3, 1, 2 ]; var n = arr.length; document.write(maxSum(arr, n)); // This code contributed by umadevi9616</script>",
"e": 7075,
"s": 6067,
"text": null
},
{
"code": null,
"e": 7078,
"s": 7075,
"text": "29"
},
{
"code": null,
"e": 7145,
"s": 7078,
"text": "Complexity Analysis: Time Complexity : O(n2)Auxiliary Space : O(1)"
},
{
"code": null,
"e": 7169,
"s": 7145,
"text": "Time Complexity : O(n2)"
},
{
"code": null,
"e": 7192,
"s": 7169,
"text": "Auxiliary Space : O(1)"
},
{
"code": null,
"e": 7431,
"s": 7192,
"text": "Method 2: This method discusses the efficient solution which solves the problem in O(n) time. In the naive solution, the values were calculated for every rotation. So if that can be done in constant time then the complexity will decrease."
},
{
"code": null,
"e": 7793,
"s": 7431,
"text": "Approach: The basic approach is to calculate the sum of new rotation from the previous rotations. This brings up a similarity where only the multipliers of first and last element change drastically and the multiplier of every other element increases or decreases by 1. So in this way, the sum of next rotation can be calculated from the sum of present rotation."
},
{
"code": null,
"e": 8204,
"s": 7793,
"text": "Algorithm: The idea is to compute the value of a rotation using values of previous rotation. When an array is rotated by one, following changes happen in sum of i*arr[i]. Multiplier of arr[i-1] changes from 0 to n-1, i.e., arr[i-1] * (n-1) is added to current value.Multipliers of other terms is decremented by 1. i.e., (cum_sum – arr[i-1]) is subtracted from current value where cum_sum is sum of all numbers."
},
{
"code": null,
"e": 8444,
"s": 8204,
"text": "Multiplier of arr[i-1] changes from 0 to n-1, i.e., arr[i-1] * (n-1) is added to current value.Multipliers of other terms is decremented by 1. i.e., (cum_sum – arr[i-1]) is subtracted from current value where cum_sum is sum of all numbers."
},
{
"code": null,
"e": 8540,
"s": 8444,
"text": "Multiplier of arr[i-1] changes from 0 to n-1, i.e., arr[i-1] * (n-1) is added to current value."
},
{
"code": null,
"e": 8685,
"s": 8540,
"text": "Multipliers of other terms is decremented by 1. i.e., (cum_sum – arr[i-1]) is subtracted from current value where cum_sum is sum of all numbers."
},
{
"code": null,
"e": 9074,
"s": 8685,
"text": "next_val = curr_val - (cum_sum - arr[i-1]) + arr[i-1] * (n-1);\n\nnext_val = Value of ∑i*arr[i] after one rotation.\ncurr_val = Current value of ∑i*arr[i] \ncum_sum = Sum of all array elements, i.e., ∑arr[i].\n\nLets take example {1, 2, 3}. Current value is 1*0+2*1+3*2\n= 8. Shifting it by one will make it {2, 3, 1} and next value\nwill be 8 - (6 - 1) + 1*2 = 5 which is same as 2*0 + 3*1 + 1*2"
},
{
"code": null,
"e": 9090,
"s": 9074,
"text": "Implementation:"
},
{
"code": null,
"e": 9094,
"s": 9090,
"text": "C++"
},
{
"code": null,
"e": 9099,
"s": 9094,
"text": "Java"
},
{
"code": null,
"e": 9107,
"s": 9099,
"text": "Python3"
},
{
"code": null,
"e": 9110,
"s": 9107,
"text": "C#"
},
{
"code": null,
"e": 9114,
"s": 9110,
"text": "PHP"
},
{
"code": null,
"e": 9125,
"s": 9114,
"text": "Javascript"
},
{
"code": "// An efficient C++ program to compute// maximum sum of i*arr[i]#include<bits/stdc++.h> using namespace std; int maxSum(int arr[], int n){ // Compute sum of all array elements int cum_sum = 0; for (int i=0; i<n; i++) cum_sum += arr[i]; // Compute sum of i*arr[i] for initial // configuration. int curr_val = 0; for (int i=0; i<n; i++) curr_val += i*arr[i]; // Initialize result int res = curr_val; // Compute values for other iterations for (int i=1; i<n; i++) { // Compute next value using previous // value in O(1) time int next_val = curr_val - (cum_sum - arr[i-1]) + arr[i-1] * (n-1); // Update current value curr_val = next_val; // Update result if required res = max(res, next_val); } return res;} // Driver codeint main(){ int arr[] = {8, 3, 1, 2}; int n = sizeof(arr)/sizeof(arr[0]); cout << maxSum(arr, n) << endl; return 0;}",
"e": 10105,
"s": 9125,
"text": null
},
{
"code": "// An efficient Java program to compute// maximum sum of i*arr[i]import java.io.*; class GFG { static int maxSum(int arr[], int n) { // Compute sum of all array elements int cum_sum = 0; for (int i = 0; i < n; i++) cum_sum += arr[i]; // Compute sum of i*arr[i] for // initial configuration. int curr_val = 0; for (int i = 0; i < n; i++) curr_val += i * arr[i]; // Initialize result int res = curr_val; // Compute values for other iterations for (int i = 1; i < n; i++) { // Compute next value using previous // value in O(1) time int next_val = curr_val - (cum_sum - arr[i-1]) + arr[i-1] * (n-1); // Update current value curr_val = next_val; // Update result if required res = Math.max(res, next_val); } return res; } // Driver code public static void main(String[] args) { int arr[] = {8, 3, 1, 2}; int n = arr.length; System.out.println(maxSum(arr, n)); }}// This code is contributed by Prerna Saini",
"e": 11308,
"s": 10105,
"text": null
},
{
"code": "# An efficient Python3 program to# compute maximum sum of i * arr[i] def maxSum(arr, n): # Compute sum of all array elements cum_sum = 0 for i in range(0, n): cum_sum += arr[i] # Compute sum of i * arr[i] for # initial configuration. curr_val = 0 for i in range(0, n): curr_val += i * arr[i] # Initialize result res = curr_val # Compute values for other iterations for i in range(1, n): # Compute next value using previous # value in O(1) time next_val = (curr_val - (cum_sum - arr[i-1]) + arr[i-1] * (n-1)) # Update current value curr_val = next_val # Update result if required res = max(res, next_val) return res # Driver codearr = [8, 3, 1, 2]n = len(arr) print(maxSum(arr, n)) # This code is contributed by# Smitha Dinesh Semwal",
"e": 12202,
"s": 11308,
"text": null
},
{
"code": "// An efficient C# program to compute// maximum sum of i*arr[i]using System; class GFG { static int maxSum(int []arr, int n) { // Compute sum of all array elements int cum_sum = 0; for (int i = 0; i < n; i++) cum_sum += arr[i]; // Compute sum of i*arr[i] for // initial configuration. int curr_val = 0; for (int i = 0; i < n; i++) curr_val += i * arr[i]; // Initialize result int res = curr_val; // Compute values for other iterations for (int i = 1; i < n; i++) { // Compute next value using previous // value in O(1) time int next_val = curr_val - (cum_sum - arr[i - 1]) + arr[i - 1] * (n - 1); // Update current value curr_val = next_val; // Update result if required res = Math.Max(res, next_val); } return res; } // Driver code public static void Main() { int []arr = {8, 3, 1, 2}; int n = arr.Length; Console.Write(maxSum(arr, n)); }} // This code is contributed by nitin mittal",
"e": 13420,
"s": 12202,
"text": null
},
{
"code": "<?php// An efficient PHP program to// compute maximum sum of i*arr[i] function maxSum($arr, $n){ // Compute sum of all // array elements $cum_sum = 0; for ($i = 0; $i < $n; $i++) $cum_sum += $arr[$i]; // Compute sum of i*arr[i] // for initial configuration. $curr_val = 0; for ($i = 0; $i < $n; $i++) $curr_val += $i * $arr[$i]; // Initialize result $res = $curr_val; // Compute values for // other iterations for ($i = 1; $i < $n; $i++) { // Compute next value using // previous value in O(1) time $next_val = $curr_val - ($cum_sum - $arr[$i - 1]) + $arr[$i - 1] * ($n - 1); // Update current value $curr_val = $next_val; // Update result if required $res = max($res, $next_val); } return $res;} // Driver code$arr = array(8, 3, 1, 2);$n = sizeof($arr);echo maxSum($arr, $n); // This code is contributed by ajit?>",
"e": 14389,
"s": 13420,
"text": null
},
{
"code": "<script>// An efficient JavaScript program to compute// maximum sum of i*arr[i] function maxSum(arr, n){ // Compute sum of all array elements let cum_sum = 0; for (let i=0; i<n; i++) cum_sum += arr[i]; // Compute sum of i*arr[i] for initial // configuration. let curr_val = 0; for (let i=0; i<n; i++) curr_val += i*arr[i]; // Initialize result let res = curr_val; // Compute values for other iterations for (let i=1; i<n; i++) { // Compute next value using previous // value in O(1) time let next_val = curr_val - (cum_sum - arr[i-1]) + arr[i-1] * (n-1); // Update current value curr_val = next_val; // Update result if required res = Math.max(res, next_val); } return res;} // Driver code let arr = [8, 3, 1, 2]; let n = arr.length; document.write(maxSum(arr, n) + \"<br>\"); // This code is contributed by Surbhi Tyagi.</script>",
"e": 15361,
"s": 14389,
"text": null
},
{
"code": null,
"e": 15364,
"s": 15361,
"text": "29"
},
{
"code": null,
"e": 15653,
"s": 15364,
"text": "Complexity analysis: Time Complexity: O(n). Since one loop is needed from 0 to n to check all rotations and the sum of the present rotation is calculated from the previous rotations in O(1) time).Auxiliary Space: O(1). As no extra space is required to so the space complexity will be O(1)"
},
{
"code": null,
"e": 15829,
"s": 15653,
"text": "Time Complexity: O(n). Since one loop is needed from 0 to n to check all rotations and the sum of the present rotation is calculated from the previous rotations in O(1) time)."
},
{
"code": null,
"e": 15922,
"s": 15829,
"text": "Auxiliary Space: O(1). As no extra space is required to so the space complexity will be O(1)"
},
{
"code": null,
"e": 16138,
"s": 15922,
"text": "Method 3: The method discusses the solution using pivot in O(n) time. The pivot method can only be used in the case of a sorted or a rotated sorted array. For example: {1, 2, 3, 4} or {2, 3, 4, 1}, {3, 4, 1, 2} etc."
},
{
"code": null,
"e": 16481,
"s": 16138,
"text": "Approach: Let’s assume the case of a sorted array. As we know for an array the maximum sum will be when the array is sorted in ascending order. In case of a sorted rotated array, we can rotate the array to make it in ascending order. So, in this case, the pivot element is needed to be found following which the maximum sum can be calculated."
},
{
"code": null,
"e": 16815,
"s": 16481,
"text": "Algorithm: Find the pivot of the array: if arr[i] > arr[(i+1)%n] then it is the pivot element. (i+1)%n is used to check for the last and first element.After getting pivot the sum can be calculated by finding the difference with the pivot which will be the multiplier and multiply it with the current element while calculating the sum"
},
{
"code": null,
"e": 17138,
"s": 16815,
"text": "Find the pivot of the array: if arr[i] > arr[(i+1)%n] then it is the pivot element. (i+1)%n is used to check for the last and first element.After getting pivot the sum can be calculated by finding the difference with the pivot which will be the multiplier and multiply it with the current element while calculating the sum"
},
{
"code": null,
"e": 17279,
"s": 17138,
"text": "Find the pivot of the array: if arr[i] > arr[(i+1)%n] then it is the pivot element. (i+1)%n is used to check for the last and first element."
},
{
"code": null,
"e": 17462,
"s": 17279,
"text": "After getting pivot the sum can be calculated by finding the difference with the pivot which will be the multiplier and multiply it with the current element while calculating the sum"
},
{
"code": null,
"e": 17479,
"s": 17462,
"text": "Implementations:"
},
{
"code": null,
"e": 17483,
"s": 17479,
"text": "C++"
},
{
"code": null,
"e": 17485,
"s": 17483,
"text": "C"
},
{
"code": null,
"e": 17490,
"s": 17485,
"text": "Java"
},
{
"code": null,
"e": 17498,
"s": 17490,
"text": "Python3"
},
{
"code": null,
"e": 17501,
"s": 17498,
"text": "C#"
},
{
"code": null,
"e": 17505,
"s": 17501,
"text": "PHP"
},
{
"code": null,
"e": 17516,
"s": 17505,
"text": "Javascript"
},
{
"code": "// C++ program to find maximum sum of all// rotation of i*arr[i] using pivot.#include <iostream>using namespace std; // fun declarationint maxSum(int arr[], int n);int findPivot(int arr[], int n); // function definitionint maxSum(int arr[], int n){ int sum = 0; int i; int pivot = findPivot(arr, n); // difference in pivot and index of // last element of array int diff = n - 1 - pivot; for(i = 0; i < n; i++) { sum = sum + ((i + diff) % n) * arr[i]; } return sum;} // function to find pivotint findPivot(int arr[], int n){ int i; for(i = 0; i < n; i++) { if(arr[i] > arr[(i + 1) % n]) return i; }} // Driver codeint main(void){ // rotated input array int arr[] = {8, 3, 1, 2}; int n = sizeof(arr) / sizeof(int); int max = maxSum(arr, n); cout << max; return 0;} // This code is contributed by Shubhamsingh10",
"e": 18416,
"s": 17516,
"text": null
},
{
"code": "// C program to find maximum sum of all// rotation of i*arr[i] using pivot.#include<stdio.h> // fun declarationint maxSum(int arr[], int n);int findPivot(int arr[], int n); // function definitionint maxSum(int arr[], int n){ int sum = 0; int i; int pivot = findPivot(arr, n); // difference in pivot and index of // last element of array int diff = n - 1 - pivot; for(i = 0; i < n; i++) { sum= sum + ((i + diff) % n) * arr[i]; } return sum;} // function to find pivotint findPivot(int arr[], int n){ int i; for(i = 0; i < n; i++) { if(arr[i] > arr[(i + 1) % n]) return i; }} // Driver codeint main(void){ // rotated input array int arr[] = {8, 3, 1, 2}; int n = sizeof(arr) / sizeof(int); int max = maxSum(arr, n); printf(\"%d\", max); return 0;}",
"e": 19251,
"s": 18416,
"text": null
},
{
"code": "// Java program to find maximum sum// of all rotation of i*arr[i] using pivot. import java.util.*;import java.lang.*;import java.io.*; class GFG{ // function definitionstatic int maxSum(int arr[], int n){ int sum = 0; int i; int pivot = findPivot(arr, n); // difference in pivot and index of // last element of array int diff = n - 1 - pivot; for(i = 0; i < n; i++) { sum= sum + ((i + diff) % n) * arr[i]; } return sum;} // function to find pivotstatic int findPivot(int arr[], int n){ int i; for(i = 0; i < n; i++) { if(arr[i] > arr[(i + 1) % n]) return i; } return 0;} // Driver codepublic static void main(String args[]){ // rotated input array int arr[] = {8, 3, 1, 2}; int n = arr.length; int max = maxSum(arr,n); System.out.println(max); }}",
"e": 20088,
"s": 19251,
"text": null
},
{
"code": "# Python3 program to find maximum sum of# all rotation of i*arr[i] using pivot. # function definitiondef maxSum(arr, n) : sum = 0 pivot = findPivot(arr, n) # difference in pivot and index # of last element of array diff = n - 1 - pivot for i in range(n) : sum = sum + ((i + diff) % n) * arr[i]; return sum # function to find pivotdef findPivot(arr, n) : for i in range(n) : if(arr[i] > arr[(i + 1) % n]) : return i; # Driver codeif __name__ == \"__main__\" : # rotated input array arr = [8, 3, 1, 2] n= len(arr) max= maxSum(arr, n) print(max) # This code is contributed by Ryuga",
"e": 20747,
"s": 20088,
"text": null
},
{
"code": "// C# program to find maximum sum// of all rotation of i*arr[i] using pivot.using System; class GFG{ // function definitionpublic static int maxSum(int[] arr, int n){ int sum = 0; int i; int pivot = findPivot(arr,n); // difference in pivot and index of // last element of array int diff = n - 1 - pivot; for (i = 0;i < n;i++) { sum = sum + ((i + diff) % n) * arr[i]; } return sum; } // function to find pivotpublic static int findPivot(int[] arr, int n){ int i; for (i = 0; i < n; i++) { if (arr[i] > arr[(i + 1) % n]) { return i; } } return 0; } // Driver codepublic static void Main(string[] args){ // rotated input array int[] arr = new int[] {8, 3, 1, 2}; int n = arr.Length; int max = maxSum(arr,n); Console.WriteLine(max);}} // This code is contributed by Shrikant13",
"e": 21632,
"s": 20747,
"text": null
},
{
"code": "<?php// PHP program to find maximum sum// of all rotation of i*arr[i] using pivot. // function definitionfunction maxSum($arr, $n){$sum = 0;$pivot = findPivot($arr, $n); // difference in pivot and index of// last element of array$diff = $n - 1 - $pivot;for($i = 0; $i < $n; $i++){ $sum = $sum + (($i + $diff) % $n) * $arr[$i];} return $sum; } // function to find pivotfunction findPivot($arr, $n){ for($i = 0; $i < $n; $i++) { if($arr[$i] > $arr[($i + 1) % $n]) return $i; } return 0;} // Driver code // rotated input array$arr = array(8, 3, 1, 2);$n = sizeof($arr);$max = maxSum($arr, $n);echo $max; // This code is contributed// by Akanksha Rai(Abby_akku)?>",
"e": 22333,
"s": 21632,
"text": null
},
{
"code": "<script> // js program to find maximum sum// of all rotation of i*arr[i] using pivot. // function definitionfunction maxSum(arr, n){ let sum = 0; let i; let pivot = findPivot(arr,n); // difference in pivot and index of // last element of array let diff = n - 1 - pivot; for (i = 0;i < n;i++) { sum = sum + ((i + diff) % n) * arr[i]; } return sum; } // function to find pivotfunction findPivot(arr, n){ let i; for (i = 0; i < n; i++) { if (arr[i] > arr[(i + 1) % n]) { return i; } } return 0;} // Driver code // rotated input arraylet arr = [8, 3, 1, 2];let n = arr.length;let ma = maxSum(arr,n);document.write(ma); // This code is contributed by mohit kumar 29.</script>",
"e": 23098,
"s": 22333,
"text": null
},
{
"code": null,
"e": 23101,
"s": 23098,
"text": "29"
},
{
"code": null,
"e": 23376,
"s": 23101,
"text": "Complexity analysis: Time Complexity : O(n) As only one loop was needed to traverse from 0 to n to find the pivot. To find the sum another loop was needed, so the complexity remains O(n).Auxiliary Space : O(1). We do not require extra space to so the Auxiliary space is O(1)"
},
{
"code": null,
"e": 23543,
"s": 23376,
"text": "Time Complexity : O(n) As only one loop was needed to traverse from 0 to n to find the pivot. To find the sum another loop was needed, so the complexity remains O(n)."
},
{
"code": null,
"e": 23631,
"s": 23543,
"text": "Auxiliary Space : O(1). We do not require extra space to so the Auxiliary space is O(1)"
},
{
"code": null,
"e": 23928,
"s": 23631,
"text": "This article is contributed by Shubham Joshi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 23941,
"s": 23928,
"text": "nitin mittal"
},
{
"code": null,
"e": 23947,
"s": 23941,
"text": "jit_t"
},
{
"code": null,
"e": 23954,
"s": 23947,
"text": "RSaini"
},
{
"code": null,
"e": 23970,
"s": 23954,
"text": "tufan_gupta2000"
},
{
"code": null,
"e": 23982,
"s": 23970,
"text": "shrikanth13"
},
{
"code": null,
"e": 23995,
"s": 23982,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 24003,
"s": 23995,
"text": "ankthon"
},
{
"code": null,
"e": 24018,
"s": 24003,
"text": "jyotiradityafc"
},
{
"code": null,
"e": 24029,
"s": 24018,
"text": "green_horn"
},
{
"code": null,
"e": 24041,
"s": 24029,
"text": "Samim Jahin"
},
{
"code": null,
"e": 24056,
"s": 24041,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 24067,
"s": 24056,
"text": "andrew1234"
},
{
"code": null,
"e": 24076,
"s": 24067,
"text": "jaredliw"
},
{
"code": null,
"e": 24090,
"s": 24076,
"text": "surbhityagi15"
},
{
"code": null,
"e": 24102,
"s": 24090,
"text": "umadevi9616"
},
{
"code": null,
"e": 24117,
"s": 24102,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 24131,
"s": 24117,
"text": "hapysingh1313"
},
{
"code": null,
"e": 24151,
"s": 24131,
"text": "abhishek0719kadiyan"
},
{
"code": null,
"e": 24164,
"s": 24151,
"text": "simmytarika5"
},
{
"code": null,
"e": 24181,
"s": 24164,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 24188,
"s": 24181,
"text": "Amazon"
},
{
"code": null,
"e": 24197,
"s": 24188,
"text": "rotation"
},
{
"code": null,
"e": 24204,
"s": 24197,
"text": "Arrays"
},
{
"code": null,
"e": 24211,
"s": 24204,
"text": "Amazon"
},
{
"code": null,
"e": 24218,
"s": 24211,
"text": "Arrays"
},
{
"code": null,
"e": 24316,
"s": 24218,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 24331,
"s": 24316,
"text": "Arrays in Java"
},
{
"code": null,
"e": 24377,
"s": 24331,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 24445,
"s": 24377,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 24489,
"s": 24445,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 24521,
"s": 24489,
"text": "Largest Sum Contiguous Subarray"
},
{
"code": null,
"e": 24537,
"s": 24521,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 24569,
"s": 24537,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 24617,
"s": 24569,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 24631,
"s": 24617,
"text": "Linear Search"
}
] |
Explicit feature maps for non-linear kernel functions | by Konstantin Kutzkov | Towards Data Science | It is all about finding the right space
At a high level, many machine learning algorithms can be thought of as consisting of the following steps.
We are given an input dataset where examples are described by n-dimensional feature vectors. In supervised problems we are also given a target label.Map the feature vectors to new m-dimensional space using some function. (Usually, m is larger than n.)
We are given an input dataset where examples are described by n-dimensional feature vectors. In supervised problems we are also given a target label.
Map the feature vectors to new m-dimensional space using some function. (Usually, m is larger than n.)
3. Train a basic machine learning model in the new feature space.
For example, you can think of many deep learning models in the above framework. You convert your original input by passing it through several layers that create a new feature representation. Then you train a basic machine learning model in the new feature space. A multilayer perceptron used for regression tasks can be seen as a linear regression model applied to the features generated by the hidden layers. Similarly, by adding a sigmoid as an activation function for the output layer, we train a logistic regression classifier in the new feature space.
In fact, the huge success of neural networks can be attributed to the fact that the mapping function is complex and learnable and thus able to represent problem specific patterns.
But in many other instances we work with a fixed function that maps the original data features to a new domain. A standard example is to create new features by considering the product of pairs of the existing features. Look at the example below. By simply adding the product of the two dimensions as a third dimension, we obtain a linearly separable dataset.
At a high-level, a kernel function measures the similarity between objects represented by numerical vectors. Kernel functions are the basis of support-vector machines where the objective is to learn a separating hyperplane between objects. Kernel functions should satisfy certain mathematical requirements which, somewhat simplified, can be stated as follows.
The above says that we must be able to rewrite the kernel function between two vectors as the inner product between vectors in a new (high-dimensional) space.
Let us consider a few examples that will make the above formal definition clear:
Linear kernel. Here m = n and f is the identity map.
A variation of the linear kernel is the cosine kernel where the vectors are normalized to have unit norm.
Polynomial kernel.
Observe that for p=2 we can rewrite the vector x as an n2 dimensional vector. For example, let x = (x1, x2, x3) and y=(y1, y2, y3) be two 3-dimensional vectors and p=2. Then for the polynomial kernel of degree 2 it holds
i.e., we have a 9-dimensional vector for the explicit feature map.
More generally, the explicit feature map for the polynomial kernel is n^p-dimensional.
RBF kernel. The Radial Basis Function is used to define the RBF kernel:
The use of the exponential function makes the dimensionality of the explicit feature maps infinite.
The obvious problem with evaluating the explicit feature map is the high-dimensionality of the mapping for most kernels. This has led to the discovery of the infamous kernel trick. We refer the reader to this excellent explanation of the kernel trick but at a high level it achieves the following. By rewriting the objective function that we want to optimize, we can learn an implicitly defined separating hyperplane in a high-dimensional space without generating high-dimensional vectors. The separating hyperplane is defined by a set of vectors, the so-called support vectors, not by exact coordinates. When we need to decide on which side of the hyperplane a point x lies, we evaluate the kernel function k(x, y) against all support vectors y. This is much more efficient. Consider 100-dimensional input vectors and a polynomial kernel of degree p=4. Explicitly computing the feature representation would require us to work with vectors with 108, or 100 million, entries. But evaluating the product with a support vector requires the inner product of two 100-dimensional vectors and then raising the result to power 4.
To get a better idea of the computational savings we can achieve, assume we have detected that the hyperplane is implicitly defined by 1,000 support vectors. Evaluating the kernel for all support vectors will require a total of less than 1,000*100*4 multiplications (the last term 4 comes from the number of multiplications for evaluating the power of the inner product). This is a fraction of 0.004 of the number of multiplications required for the evaluation of a single example using. the explicit feature map.
However, in the era of Big data it turns out that SVMs are not really scalable. First, in order to compute a set of support vectors we need to compute the Gram matrix consisting of the kernel values k(x,y) for all pairs (x,y) of input instances. Thus, for t examples in our training dataset we need a matrix with t2 entries. Even if we decide to store a sparsified version of the Gram matrix by keeping only the largest entries, for massive datasets simply computing the kernel function for all pairs can be infeasible.
Another problem is that for massive complex datasets the number of support vectors grows linearly with the dataset size [1]. So, even if we can afford to train an SVM model, the prediction time will be very slow as we would need to evaluate the kernel function many times for a single prediction.
The above limitations of support vector machines have motivated researchers to consider the problem of obtaining a compact representation of explicit feature maps. This means that the original n-dimensional vectors x, y are replaced by new m-dimensional vectors f(x), f(y), for a reasonably large m, such that
Here m is a user defined parameter. The larger m the better the approximation. Thus, m is a trade-off between accuracy and scalability.
Please feel free to skip the below description of the underlying mechanism of constructing explicit feature maps. It is not crucial for understanding the next sections.
Next we consider two approaches to constructing explicit feature maps for the two most widely used kernels, the RBF and the polynomial kernels, and provide intuition how they work:
RBF sampler.
Using some advanced mathematical concepts from probability theory we can obtain the following representation for the kernel
where p(w) is a probability distribution [2].
The above formulation allows us to design a sampling procedure that samples vectors w according to p(w). Observe that the expression in brackets can be written as in inner product with two coordinates. A large number of samples will then result in an approximate explicit feature map. For a collection of vectors, we sample values w for each coordinate in the approximate explicit feature map using the same random seed. In this way we guarantee that the samples are coordinated and vectors that are similar to each other, i.e., have a small Euclidean distance, are likely to end up with similar samples in the respective coordinates.
Polynomial CountSketch.
The polynomial CountSketch, or TensorSketch [3], builds upon the CountSketch algorithm detecting heavy hitters in massive data streams. We will give an intuitive explanation of how the approach works. Imagine, we are given a vector x and construct the n2-dimensional explicit feature map, call it z. Then, each index i is placed at random by a hash function in one of m buckets, denoted by B and initialized with zeros. Also, the value z[i] is multiplied by -1 or 1 selected at random with equal probability. Precisely, we update a bucket as
Assume that some of the z[i] values are much larger than the rest, the so called heavy hitters. Let z[j] be such a heavy hitter. The bucket that contains it, B[h(j)] also contains other entries z[k]. The content of the bucket is
However, the signs are random and if the summation contains many small entries, they are likely to cancel out.
Now assume we have the explicit feature maps z and w of two vectors such that z[j] and w[j] are both large. (Ultimately, this is what we are looking for in a kernel, to detect subsets of features that are significant in both input vectors.) We replace the multiplication of z[j]*w[j] by
where Rz and Rw are the above sums of other entries hashed to the same bucket. Because the signs in front of z[j] and w[j] are the same, and Rz and Rw are small, we obtain a good approximation of z[i]*z[j].
The above assumes that we have direct access to the entries z[i] in the explicit feature map. In [3] the authors design an efficient algorithm that can perform the above by avoiding the generation of the explicit feature maps. It runs in nearly linear time in the length of the input vectors.
The good news is that explicit feature maps are already implemented in scikit-learn and are easy to use. (The code for the following example can be found at https://github.com/konstantinkutzkov/explicit_feature_maps)
First, import the necessary packages:
from sklearn import svm, datasetsfrom sklearn.kernel_approximation import RBFSamplerfrom sklearn.kernel_approximation import PolynomialCountSketch
Then we can simply convert the original vectors to a new feature representation.
poly_cs = PolynomialCountSketch( degree=3, gamma=1.0, random_state=1, n_components=1000 )X_train, y_train, X_test, y_test = get_train_test_split(X, y, train_index)X_train_poly, X_test_poly = poly_cs.fit_transform(X_train), poly_ts.fit_transform(X_test)
At the end, use a Linear SVM to train the models:
model_cs = svm.LinearSVC(C=1.0, max_iter=10000).fit(X_train_poly, y_train)
We trained the above models on the digits dataset consisting of hand-written digits described by 64-dimensional vectors. The explicit feature map of a polynomial kernel of degree 3 would thus result in vectors of dimensionality 262,144. Instead we work with feature maps with only 1,000 entries, 260 times less, and obtain essentially identical results. The below results are averaged over 10-fold cross validation:
Linear SVM: 0.985RBF SVM: 0.817Polynomial SVM: 0.998Explicit RBF: 0.818Explicit Polynomial: 0.997
In the above, RBF SVM and Polynomial SVM were trained by the dual SVM models that use the kernel trick. The polynomial kernel outperforms the other methods and the RBF kernel does not appear to be appropriate for this problem.
Always make sure you use the same random seed if you want to apply the same mapping to different sets, be it for model deployment or reproducibility of results.
Scale the features. If the features are not scaled, then in PolynomialCountSketch the feature maps will be biased towards the heaviest entries (see the discussion on how the approach works).
Consider that a smaller dimensionality of the approximation of the explicit maps serves as a regularization parameter.
The obvious application is to train a linear support vector machine using the explicit feature maps. But given that they are oblivious to the problem at hand, explicit feature maps can be used in combination with any other machine learning model, be it supervised or unsupervised. Just think about it as training your model in a new subspace formed by a combination of the coordinates of the original space.
Accessibility. Easy to use, publicly available implementation on scikit-learn.
Scalability. Generating explicit feature maps is a highly efficient mathematical manipulation and does not require training a model.
Well understood. We are approximating mathematical functions with rigorously understood properties. These kernel functions have been used by the ML community for decades.
There are two important drawbacks that should be kept in mind if you decide to include explicit feature maps in your project.
We have yet another hyperparameter that needs to be carefully tuned. Compared to the standard version of the kernel, we have an additional hyperparameter which is the dimensionality of the explicit feature maps. As discussed, this parameter is a trade-off between accuracy and scalability.
The explicit feature maps are not anymore interpretable. The individual dimensions in the original input correspond to features that in many cases are accessible to a human expert. This makes it possible to train explainable ML models such as linear or logistic regression, decision trees, etc. In particular, SVMs using the kernel trick are more or less interpretable as we can look at the kernel function scores between two vectors. However, explicit feature maps are the result of complex mathematical modifications of the original vectors and individual coordinates are not anymore meaningful to a human user.
https://github.com/konstantinkutzkov/explicit_feature_maps
[1] Thorsten Joachims: Training Linear SVMs in Linear Time. KDD 2006. https://www.cs.cornell.edu/people/tj/publications/joachims_06a.pdf
[2] Ali Rahimi, Benjamin Recht: Weighted Sums of Random Kitchen Sinks: Replacing minimization with randomization in learning. NIPS 2008 https://people.eecs.berkeley.edu/~brecht/papers/08.rah.rec.nips.pdf
[3] Ninh Pham, Rasmus Pagh. Fast and scalable polynomial kernels via explicit feature maps. KDD 2013 https://dl.acm.org/doi/10.1145/2487575.2487591 | [
{
"code": null,
"e": 211,
"s": 171,
"text": "It is all about finding the right space"
},
{
"code": null,
"e": 317,
"s": 211,
"text": "At a high level, many machine learning algorithms can be thought of as consisting of the following steps."
},
{
"code": null,
"e": 569,
"s": 317,
"text": "We are given an input dataset where examples are described by n-dimensional feature vectors. In supervised problems we are also given a target label.Map the feature vectors to new m-dimensional space using some function. (Usually, m is larger than n.)"
},
{
"code": null,
"e": 719,
"s": 569,
"text": "We are given an input dataset where examples are described by n-dimensional feature vectors. In supervised problems we are also given a target label."
},
{
"code": null,
"e": 822,
"s": 719,
"text": "Map the feature vectors to new m-dimensional space using some function. (Usually, m is larger than n.)"
},
{
"code": null,
"e": 888,
"s": 822,
"text": "3. Train a basic machine learning model in the new feature space."
},
{
"code": null,
"e": 1445,
"s": 888,
"text": "For example, you can think of many deep learning models in the above framework. You convert your original input by passing it through several layers that create a new feature representation. Then you train a basic machine learning model in the new feature space. A multilayer perceptron used for regression tasks can be seen as a linear regression model applied to the features generated by the hidden layers. Similarly, by adding a sigmoid as an activation function for the output layer, we train a logistic regression classifier in the new feature space."
},
{
"code": null,
"e": 1625,
"s": 1445,
"text": "In fact, the huge success of neural networks can be attributed to the fact that the mapping function is complex and learnable and thus able to represent problem specific patterns."
},
{
"code": null,
"e": 1984,
"s": 1625,
"text": "But in many other instances we work with a fixed function that maps the original data features to a new domain. A standard example is to create new features by considering the product of pairs of the existing features. Look at the example below. By simply adding the product of the two dimensions as a third dimension, we obtain a linearly separable dataset."
},
{
"code": null,
"e": 2344,
"s": 1984,
"text": "At a high-level, a kernel function measures the similarity between objects represented by numerical vectors. Kernel functions are the basis of support-vector machines where the objective is to learn a separating hyperplane between objects. Kernel functions should satisfy certain mathematical requirements which, somewhat simplified, can be stated as follows."
},
{
"code": null,
"e": 2503,
"s": 2344,
"text": "The above says that we must be able to rewrite the kernel function between two vectors as the inner product between vectors in a new (high-dimensional) space."
},
{
"code": null,
"e": 2584,
"s": 2503,
"text": "Let us consider a few examples that will make the above formal definition clear:"
},
{
"code": null,
"e": 2637,
"s": 2584,
"text": "Linear kernel. Here m = n and f is the identity map."
},
{
"code": null,
"e": 2743,
"s": 2637,
"text": "A variation of the linear kernel is the cosine kernel where the vectors are normalized to have unit norm."
},
{
"code": null,
"e": 2762,
"s": 2743,
"text": "Polynomial kernel."
},
{
"code": null,
"e": 2983,
"s": 2762,
"text": "Observe that for p=2 we can rewrite the vector x as an n2 dimensional vector. For example, let x = (x1, x2, x3) and y=(y1, y2, y3) be two 3-dimensional vectors and p=2. Then for the polynomial kernel of degree 2 it holds"
},
{
"code": null,
"e": 3050,
"s": 2983,
"text": "i.e., we have a 9-dimensional vector for the explicit feature map."
},
{
"code": null,
"e": 3137,
"s": 3050,
"text": "More generally, the explicit feature map for the polynomial kernel is n^p-dimensional."
},
{
"code": null,
"e": 3209,
"s": 3137,
"text": "RBF kernel. The Radial Basis Function is used to define the RBF kernel:"
},
{
"code": null,
"e": 3309,
"s": 3209,
"text": "The use of the exponential function makes the dimensionality of the explicit feature maps infinite."
},
{
"code": null,
"e": 4431,
"s": 3309,
"text": "The obvious problem with evaluating the explicit feature map is the high-dimensionality of the mapping for most kernels. This has led to the discovery of the infamous kernel trick. We refer the reader to this excellent explanation of the kernel trick but at a high level it achieves the following. By rewriting the objective function that we want to optimize, we can learn an implicitly defined separating hyperplane in a high-dimensional space without generating high-dimensional vectors. The separating hyperplane is defined by a set of vectors, the so-called support vectors, not by exact coordinates. When we need to decide on which side of the hyperplane a point x lies, we evaluate the kernel function k(x, y) against all support vectors y. This is much more efficient. Consider 100-dimensional input vectors and a polynomial kernel of degree p=4. Explicitly computing the feature representation would require us to work with vectors with 108, or 100 million, entries. But evaluating the product with a support vector requires the inner product of two 100-dimensional vectors and then raising the result to power 4."
},
{
"code": null,
"e": 4945,
"s": 4431,
"text": "To get a better idea of the computational savings we can achieve, assume we have detected that the hyperplane is implicitly defined by 1,000 support vectors. Evaluating the kernel for all support vectors will require a total of less than 1,000*100*4 multiplications (the last term 4 comes from the number of multiplications for evaluating the power of the inner product). This is a fraction of 0.004 of the number of multiplications required for the evaluation of a single example using. the explicit feature map."
},
{
"code": null,
"e": 5465,
"s": 4945,
"text": "However, in the era of Big data it turns out that SVMs are not really scalable. First, in order to compute a set of support vectors we need to compute the Gram matrix consisting of the kernel values k(x,y) for all pairs (x,y) of input instances. Thus, for t examples in our training dataset we need a matrix with t2 entries. Even if we decide to store a sparsified version of the Gram matrix by keeping only the largest entries, for massive datasets simply computing the kernel function for all pairs can be infeasible."
},
{
"code": null,
"e": 5762,
"s": 5465,
"text": "Another problem is that for massive complex datasets the number of support vectors grows linearly with the dataset size [1]. So, even if we can afford to train an SVM model, the prediction time will be very slow as we would need to evaluate the kernel function many times for a single prediction."
},
{
"code": null,
"e": 6072,
"s": 5762,
"text": "The above limitations of support vector machines have motivated researchers to consider the problem of obtaining a compact representation of explicit feature maps. This means that the original n-dimensional vectors x, y are replaced by new m-dimensional vectors f(x), f(y), for a reasonably large m, such that"
},
{
"code": null,
"e": 6208,
"s": 6072,
"text": "Here m is a user defined parameter. The larger m the better the approximation. Thus, m is a trade-off between accuracy and scalability."
},
{
"code": null,
"e": 6377,
"s": 6208,
"text": "Please feel free to skip the below description of the underlying mechanism of constructing explicit feature maps. It is not crucial for understanding the next sections."
},
{
"code": null,
"e": 6558,
"s": 6377,
"text": "Next we consider two approaches to constructing explicit feature maps for the two most widely used kernels, the RBF and the polynomial kernels, and provide intuition how they work:"
},
{
"code": null,
"e": 6571,
"s": 6558,
"text": "RBF sampler."
},
{
"code": null,
"e": 6695,
"s": 6571,
"text": "Using some advanced mathematical concepts from probability theory we can obtain the following representation for the kernel"
},
{
"code": null,
"e": 6741,
"s": 6695,
"text": "where p(w) is a probability distribution [2]."
},
{
"code": null,
"e": 7376,
"s": 6741,
"text": "The above formulation allows us to design a sampling procedure that samples vectors w according to p(w). Observe that the expression in brackets can be written as in inner product with two coordinates. A large number of samples will then result in an approximate explicit feature map. For a collection of vectors, we sample values w for each coordinate in the approximate explicit feature map using the same random seed. In this way we guarantee that the samples are coordinated and vectors that are similar to each other, i.e., have a small Euclidean distance, are likely to end up with similar samples in the respective coordinates."
},
{
"code": null,
"e": 7400,
"s": 7376,
"text": "Polynomial CountSketch."
},
{
"code": null,
"e": 7942,
"s": 7400,
"text": "The polynomial CountSketch, or TensorSketch [3], builds upon the CountSketch algorithm detecting heavy hitters in massive data streams. We will give an intuitive explanation of how the approach works. Imagine, we are given a vector x and construct the n2-dimensional explicit feature map, call it z. Then, each index i is placed at random by a hash function in one of m buckets, denoted by B and initialized with zeros. Also, the value z[i] is multiplied by -1 or 1 selected at random with equal probability. Precisely, we update a bucket as"
},
{
"code": null,
"e": 8171,
"s": 7942,
"text": "Assume that some of the z[i] values are much larger than the rest, the so called heavy hitters. Let z[j] be such a heavy hitter. The bucket that contains it, B[h(j)] also contains other entries z[k]. The content of the bucket is"
},
{
"code": null,
"e": 8282,
"s": 8171,
"text": "However, the signs are random and if the summation contains many small entries, they are likely to cancel out."
},
{
"code": null,
"e": 8569,
"s": 8282,
"text": "Now assume we have the explicit feature maps z and w of two vectors such that z[j] and w[j] are both large. (Ultimately, this is what we are looking for in a kernel, to detect subsets of features that are significant in both input vectors.) We replace the multiplication of z[j]*w[j] by"
},
{
"code": null,
"e": 8776,
"s": 8569,
"text": "where Rz and Rw are the above sums of other entries hashed to the same bucket. Because the signs in front of z[j] and w[j] are the same, and Rz and Rw are small, we obtain a good approximation of z[i]*z[j]."
},
{
"code": null,
"e": 9069,
"s": 8776,
"text": "The above assumes that we have direct access to the entries z[i] in the explicit feature map. In [3] the authors design an efficient algorithm that can perform the above by avoiding the generation of the explicit feature maps. It runs in nearly linear time in the length of the input vectors."
},
{
"code": null,
"e": 9286,
"s": 9069,
"text": "The good news is that explicit feature maps are already implemented in scikit-learn and are easy to use. (The code for the following example can be found at https://github.com/konstantinkutzkov/explicit_feature_maps)"
},
{
"code": null,
"e": 9324,
"s": 9286,
"text": "First, import the necessary packages:"
},
{
"code": null,
"e": 9471,
"s": 9324,
"text": "from sklearn import svm, datasetsfrom sklearn.kernel_approximation import RBFSamplerfrom sklearn.kernel_approximation import PolynomialCountSketch"
},
{
"code": null,
"e": 9552,
"s": 9471,
"text": "Then we can simply convert the original vectors to a new feature representation."
},
{
"code": null,
"e": 9883,
"s": 9552,
"text": "poly_cs = PolynomialCountSketch( degree=3, gamma=1.0, random_state=1, n_components=1000 )X_train, y_train, X_test, y_test = get_train_test_split(X, y, train_index)X_train_poly, X_test_poly = poly_cs.fit_transform(X_train), poly_ts.fit_transform(X_test)"
},
{
"code": null,
"e": 9933,
"s": 9883,
"text": "At the end, use a Linear SVM to train the models:"
},
{
"code": null,
"e": 10008,
"s": 9933,
"text": "model_cs = svm.LinearSVC(C=1.0, max_iter=10000).fit(X_train_poly, y_train)"
},
{
"code": null,
"e": 10424,
"s": 10008,
"text": "We trained the above models on the digits dataset consisting of hand-written digits described by 64-dimensional vectors. The explicit feature map of a polynomial kernel of degree 3 would thus result in vectors of dimensionality 262,144. Instead we work with feature maps with only 1,000 entries, 260 times less, and obtain essentially identical results. The below results are averaged over 10-fold cross validation:"
},
{
"code": null,
"e": 10522,
"s": 10424,
"text": "Linear SVM: 0.985RBF SVM: 0.817Polynomial SVM: 0.998Explicit RBF: 0.818Explicit Polynomial: 0.997"
},
{
"code": null,
"e": 10749,
"s": 10522,
"text": "In the above, RBF SVM and Polynomial SVM were trained by the dual SVM models that use the kernel trick. The polynomial kernel outperforms the other methods and the RBF kernel does not appear to be appropriate for this problem."
},
{
"code": null,
"e": 10910,
"s": 10749,
"text": "Always make sure you use the same random seed if you want to apply the same mapping to different sets, be it for model deployment or reproducibility of results."
},
{
"code": null,
"e": 11101,
"s": 10910,
"text": "Scale the features. If the features are not scaled, then in PolynomialCountSketch the feature maps will be biased towards the heaviest entries (see the discussion on how the approach works)."
},
{
"code": null,
"e": 11220,
"s": 11101,
"text": "Consider that a smaller dimensionality of the approximation of the explicit maps serves as a regularization parameter."
},
{
"code": null,
"e": 11628,
"s": 11220,
"text": "The obvious application is to train a linear support vector machine using the explicit feature maps. But given that they are oblivious to the problem at hand, explicit feature maps can be used in combination with any other machine learning model, be it supervised or unsupervised. Just think about it as training your model in a new subspace formed by a combination of the coordinates of the original space."
},
{
"code": null,
"e": 11707,
"s": 11628,
"text": "Accessibility. Easy to use, publicly available implementation on scikit-learn."
},
{
"code": null,
"e": 11840,
"s": 11707,
"text": "Scalability. Generating explicit feature maps is a highly efficient mathematical manipulation and does not require training a model."
},
{
"code": null,
"e": 12011,
"s": 11840,
"text": "Well understood. We are approximating mathematical functions with rigorously understood properties. These kernel functions have been used by the ML community for decades."
},
{
"code": null,
"e": 12137,
"s": 12011,
"text": "There are two important drawbacks that should be kept in mind if you decide to include explicit feature maps in your project."
},
{
"code": null,
"e": 12427,
"s": 12137,
"text": "We have yet another hyperparameter that needs to be carefully tuned. Compared to the standard version of the kernel, we have an additional hyperparameter which is the dimensionality of the explicit feature maps. As discussed, this parameter is a trade-off between accuracy and scalability."
},
{
"code": null,
"e": 13041,
"s": 12427,
"text": "The explicit feature maps are not anymore interpretable. The individual dimensions in the original input correspond to features that in many cases are accessible to a human expert. This makes it possible to train explainable ML models such as linear or logistic regression, decision trees, etc. In particular, SVMs using the kernel trick are more or less interpretable as we can look at the kernel function scores between two vectors. However, explicit feature maps are the result of complex mathematical modifications of the original vectors and individual coordinates are not anymore meaningful to a human user."
},
{
"code": null,
"e": 13100,
"s": 13041,
"text": "https://github.com/konstantinkutzkov/explicit_feature_maps"
},
{
"code": null,
"e": 13237,
"s": 13100,
"text": "[1] Thorsten Joachims: Training Linear SVMs in Linear Time. KDD 2006. https://www.cs.cornell.edu/people/tj/publications/joachims_06a.pdf"
},
{
"code": null,
"e": 13441,
"s": 13237,
"text": "[2] Ali Rahimi, Benjamin Recht: Weighted Sums of Random Kitchen Sinks: Replacing minimization with randomization in learning. NIPS 2008 https://people.eecs.berkeley.edu/~brecht/papers/08.rah.rec.nips.pdf"
}
] |
Count numbers from range whose prime factors are only 2 and 3 in C++ | We are provided two numbers START and END to define a range of numbers. The goal is to find the numbers that have only 2 and 3 as their prime factors and are in the range [START,END].
We will do this by traversing numbers from START to END and for each number we will check if the number is divisible by 2 and 3 only. If divisible, divide it and reduce it. If not, break the loop. In the end if the number is reduced to 1 then it has only 2 and 3 as its factors.
Let’s understand with examples.
Input
START=20 END=25
Output
Numbers with only 2 and 3 as prime factors: 1
Explanation
Prime factors of each number:
20 = 2*2*5
21 = 3*7
22 = 2*11
23 = 1*23
24 = 2*2*2*3
25 = 5*5
Only 24 has 2 and 3 as prime factors.
Input
START=1000 END=1500
Output
Numbers with only 2 and 3 as prime factors: 4
Explanation
1024 1152 1296 1458 are the numbers with only 2 and 3 as prime factors
We take an integers START and END as range variables.
We take an integers START and END as range variables.
Function twothreeFactors(int start, int end) takes range variables and returns the count of numbers with 2 and 3 as only prime factors.
Function twothreeFactors(int start, int end) takes range variables and returns the count of numbers with 2 and 3 as only prime factors.
Take the initial variable count as 0 for such numbers.
Take the initial variable count as 0 for such numbers.
Traverse range of numbers using for loop. i=start to i=end
Traverse range of numbers using for loop. i=start to i=end
Now for each number num=i, using while loop check if num%2==0, divide it.
Now for each number num=i, using while loop check if num%2==0, divide it.
if num%3==0, divide it. If not by both break the while loop
if num%3==0, divide it. If not by both break the while loop
If after the while loop num is 1 then increase count.
If after the while loop num is 1 then increase count.
At the end of all loops count will have a total number which has only 2 and 4 as prime factors.
At the end of all loops count will have a total number which has only 2 and 4 as prime factors.
Return the count as result.
Return the count as result.
Live Demo
#include <bits/stdc++.h>
using namespace std;
int twothreeFactors(int start, int end){
// Start with 2 so that 1 doesn't get counted
if (start == 1)
{ start++; }
int count = 0;
for (int i = start; i <= end; i++) {
int num = i;
while(num>1){
// if divisible by 2, divide it by 2
if(num % 2 == 0)
{ num /= 2; }
// if divisible by 3, divide it by 3
else if (num % 3 == 0)
{ num /= 3; }
else //if divisible by neither 2 nor 3 break
{ break; }
}
// means only 2 and 3 are factors of num
if (num == 1)
{ count++; }
}
return count;
}
int main(){
int START = 10, END = 20;
cout <<"Numbers with only 2 and 3 as prime factors:"<< twothreeFactors(START,END);
return 0;
}
If we run the above code it will generate the following output −
Numbers with only 2 and 3 as prime factors:3 | [
{
"code": null,
"e": 1246,
"s": 1062,
"text": "We are provided two numbers START and END to define a range of numbers. The goal is to find the numbers that have only 2 and 3 as their prime factors and are in the range [START,END]."
},
{
"code": null,
"e": 1525,
"s": 1246,
"text": "We will do this by traversing numbers from START to END and for each number we will check if the number is divisible by 2 and 3 only. If divisible, divide it and reduce it. If not, break the loop. In the end if the number is reduced to 1 then it has only 2 and 3 as its factors."
},
{
"code": null,
"e": 1557,
"s": 1525,
"text": "Let’s understand with examples."
},
{
"code": null,
"e": 1564,
"s": 1557,
"text": "Input "
},
{
"code": null,
"e": 1580,
"s": 1564,
"text": "START=20 END=25"
},
{
"code": null,
"e": 1588,
"s": 1580,
"text": "Output "
},
{
"code": null,
"e": 1634,
"s": 1588,
"text": "Numbers with only 2 and 3 as prime factors: 1"
},
{
"code": null,
"e": 1647,
"s": 1634,
"text": "Explanation "
},
{
"code": null,
"e": 1777,
"s": 1647,
"text": "Prime factors of each number:\n20 = 2*2*5\n21 = 3*7\n22 = 2*11\n23 = 1*23\n24 = 2*2*2*3\n25 = 5*5\nOnly 24 has 2 and 3 as prime factors."
},
{
"code": null,
"e": 1784,
"s": 1777,
"text": "Input "
},
{
"code": null,
"e": 1804,
"s": 1784,
"text": "START=1000 END=1500"
},
{
"code": null,
"e": 1812,
"s": 1804,
"text": "Output "
},
{
"code": null,
"e": 1858,
"s": 1812,
"text": "Numbers with only 2 and 3 as prime factors: 4"
},
{
"code": null,
"e": 1871,
"s": 1858,
"text": "Explanation "
},
{
"code": null,
"e": 1942,
"s": 1871,
"text": "1024 1152 1296 1458 are the numbers with only 2 and 3 as prime factors"
},
{
"code": null,
"e": 1996,
"s": 1942,
"text": "We take an integers START and END as range variables."
},
{
"code": null,
"e": 2050,
"s": 1996,
"text": "We take an integers START and END as range variables."
},
{
"code": null,
"e": 2186,
"s": 2050,
"text": "Function twothreeFactors(int start, int end) takes range variables and returns the count of numbers with 2 and 3 as only prime factors."
},
{
"code": null,
"e": 2322,
"s": 2186,
"text": "Function twothreeFactors(int start, int end) takes range variables and returns the count of numbers with 2 and 3 as only prime factors."
},
{
"code": null,
"e": 2377,
"s": 2322,
"text": "Take the initial variable count as 0 for such numbers."
},
{
"code": null,
"e": 2432,
"s": 2377,
"text": "Take the initial variable count as 0 for such numbers."
},
{
"code": null,
"e": 2491,
"s": 2432,
"text": "Traverse range of numbers using for loop. i=start to i=end"
},
{
"code": null,
"e": 2550,
"s": 2491,
"text": "Traverse range of numbers using for loop. i=start to i=end"
},
{
"code": null,
"e": 2624,
"s": 2550,
"text": "Now for each number num=i, using while loop check if num%2==0, divide it."
},
{
"code": null,
"e": 2698,
"s": 2624,
"text": "Now for each number num=i, using while loop check if num%2==0, divide it."
},
{
"code": null,
"e": 2758,
"s": 2698,
"text": "if num%3==0, divide it. If not by both break the while loop"
},
{
"code": null,
"e": 2818,
"s": 2758,
"text": "if num%3==0, divide it. If not by both break the while loop"
},
{
"code": null,
"e": 2872,
"s": 2818,
"text": "If after the while loop num is 1 then increase count."
},
{
"code": null,
"e": 2926,
"s": 2872,
"text": "If after the while loop num is 1 then increase count."
},
{
"code": null,
"e": 3022,
"s": 2926,
"text": "At the end of all loops count will have a total number which has only 2 and 4 as prime factors."
},
{
"code": null,
"e": 3118,
"s": 3022,
"text": "At the end of all loops count will have a total number which has only 2 and 4 as prime factors."
},
{
"code": null,
"e": 3146,
"s": 3118,
"text": "Return the count as result."
},
{
"code": null,
"e": 3174,
"s": 3146,
"text": "Return the count as result."
},
{
"code": null,
"e": 3185,
"s": 3174,
"text": " Live Demo"
},
{
"code": null,
"e": 3998,
"s": 3185,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nint twothreeFactors(int start, int end){\n // Start with 2 so that 1 doesn't get counted\n if (start == 1)\n { start++; }\n int count = 0;\n for (int i = start; i <= end; i++) {\n int num = i;\n while(num>1){\n // if divisible by 2, divide it by 2\n if(num % 2 == 0)\n { num /= 2; }\n // if divisible by 3, divide it by 3\n else if (num % 3 == 0)\n { num /= 3; }\n else //if divisible by neither 2 nor 3 break\n { break; }\n }\n // means only 2 and 3 are factors of num\n if (num == 1)\n { count++; }\n }\n return count;\n}\nint main(){\n int START = 10, END = 20;\n cout <<\"Numbers with only 2 and 3 as prime factors:\"<< twothreeFactors(START,END);\n return 0;\n}"
},
{
"code": null,
"e": 4063,
"s": 3998,
"text": "If we run the above code it will generate the following output −"
},
{
"code": null,
"e": 4108,
"s": 4063,
"text": "Numbers with only 2 and 3 as prime factors:3"
}
] |
Creating and training a U-Net model with PyTorch for 2D & 3D semantic segmentation: Dataset building [1/4] | by Johannes Schmidt | Towards Data Science | In this series (4 parts) we will perform semantic segmentation on images using plain PyTorch and the U-Net architecture. I will cover the following topics: Dataset building, model building (U-Net), training and inference. For that I will use a sample of the infamous Carvana dataset (2D images), but the code and the methods work for 3D datasets as well. For example: I will not use the torchvision package, as most transformations and augmentations only work on 2D input with PIL. You can find the repo of this project here with a jupyter notebook for every part (and more).
I was a master student in biology who started to learn programming with python and ended up trying deep learning (semantic segmentation with U-Net) on electron tomograms (3D images) for my master thesis. In this process I not only learned quite a lot about deep learning, python and programming but also how to better structure your project and code. This blog aims to share my experience and a tutorial to use plain PyTorch to efficiently use deep learning for your own semantic segmentation project.
To bring more structure into your project, I recommend to create a new project and create several python files, each having different classes and functions that can be imported and used. Personally, I like to use PyCharm for that but other IDEs such as Spyder are also a good choice. I also prefer working with the IPython console within PyCharm instead of Jupyter notebooks. A combination of both can be very helpful though. If you prefer a single Jupyter Notebook, that’s also fine, just bear in mind that it could get to be a long script. You can find the files and code on github. Most of the structure and code that I will be showing is inspired by the work of this project: elektronn3.
Before we start creating our data generator, let’s talk about the data first. What we would like to have is two directories, something like /Input and /Target. In the /Input directory, we find all input images and in the /Target directory the segmentation maps. Visualizing the images would look something like the image below. The labels are usually encoded with pixel values, meaning that all pixels of the same class have the same pixel value e.g. background=0, dog=1, cat=2 in the example below.
The goal of the network is to predict such a segmentation map from a given input image.
In deep learning, we want to feed our network with batches of data. Therefore, we would like to have a data generator that does the following:
It picks up the input-target pairsIt performs some transformations on the data “on the fly”
It picks up the input-target pairs
It performs some transformations on the data “on the fly”
With PyTorch it is fairly easy to create such a data generator. We create a custom Dataset class, instantiate it and pass it to PyTorch’s dataloader. Here is a simple example of such a dataset for a potential segmentation pipeline (Spoiler: In part 3 I will make use of the multiprocessing library and use caching to improve this dataset):
The SegmentationDataSet class inherits from torch.data.Dataset . In the initialization method __init__, we expect a list of input paths and a list of target paths. The __getitem__ method simply reads an item from our input and target list using the skimage.imread() function. This will give us our input and target image as numpy.ndarrays. We then process our data with the transform function that expects an input and target pair and should return the processed data as numpy.ndarrays again. But I will come to that later. At the end, we just make sure that we end up having a torch.tensor of certain type for our input and target. In this case, this is usually torch.float32 and torch.int64 (long) for input and target, respectively. This dataset can be then used to create our dataloader (the data generator that we want). You may ask: How do we make sure that this dataset will output the correct target for every input image? If the input and target lists happen to have the same order, e.g. because input and target have the same name, the mapping should be correct.
Let’s try it out with a simple example:
inputs = ['path\input\pic_01.png', 'path\input\pic_02.png']targets = ['path\target\pic_01.png', 'path\target\pic_02.png']training_dataset = SegmentationDataSet(inputs=inputs, targets=targets, transform=None)training_dataloader = data.DataLoader(dataset=training_dataset, batch_size=2, shuffle=True)x, y = next(iter(training_dataloader))print(f'x = shape: {x.shape}; type: {x.dtype}')print(f'x = min: {x.min()}; max: {x.max()}')print(f'y = shape: {y.shape}; class: {y.unique()}; type: {y.dtype}')
Here, we create an instance of our SegmentationDataSet class. For now, we don’t want any transformation to happen on our data, so we leave transform=None . In the next step we create our data loader by passing our training_dataset as input. We choose to have an batch_size of 2 and to shuffle the data shuffle=True . There are some other useful arguments that can be passed in when instantiating the dataloader and you should check them out. The result could look something like this:
x = shape: torch.Size([2, 144, 144, 3]); type: torch.float32x = min: 8.0; max: 255.0y = shape: torch.Size([2, 144, 144]); class: tensor([ 0, 255]); type: torch.int64
There are some things to notice here:
The type of x and y is already correct.The x should have a shape of [N, C, H, W] . So the channel dimension should be second instead of last.The y is supposed to have a shape [N, H, W] , (this is because torch’s loss function torch.nn.CrossEntropyLoss expects it, even though it will internally one-hot encode it).The target y has only 2 classes: 0 and 255. But we want dense integer encoding, meaning 0 and 1.The input is in the range [0-255] — uint8, but should be normalized or linearly scaled to [0, 1] or [-1, 1].
The type of x and y is already correct.
The x should have a shape of [N, C, H, W] . So the channel dimension should be second instead of last.
The y is supposed to have a shape [N, H, W] , (this is because torch’s loss function torch.nn.CrossEntropyLoss expects it, even though it will internally one-hot encode it).
The target y has only 2 classes: 0 and 255. But we want dense integer encoding, meaning 0 and 1.
The input is in the range [0-255] — uint8, but should be normalized or linearly scaled to [0, 1] or [-1, 1].
Because of this we need to transform the data a little bit.
Note: If we omit the typecasting at the end of our SegmentationDataSet, the dataloader would still not output numpy.ndarrays but torch.tensors. As our input is read as a numpy.ndarray in uint8, it will also output a torch.tensor in uint8. For float32 we need to change the type.
Let’s create a new file, that we name transformations.py.
In order to transform our data so that they meet the requirements of the network, we create a class FunctionWrapperDouble which can take any function and returns a partial (basically a function with defined arguments). This allows us to stack (functions) transformations in a list that we want to be applied on the data. To stack these functions I use the ComposeDouble class. The Double in these classes means that it is meant for a dataset with input-target pairs (like our case for semantic segmentation). There is also a Single version of these classes for the case that you want to just experiment with some input or target images (or visualize your dataset). So what we want, is to create an object, that comprises all the transformations that we want to apply to the data. We can then pass this object as an argument in our SegmentationDataSet instance. Confused? Let me show what I mean with an example:
The tranfsorms variable is an instance of the ComposeDouble class that comprises a list of transformations that is to be applied to the data! create_dense_target and normalize_01 are functions that I defined in transformations.py, while np.moveaxis is just a numpy function that simply moves the channel dimension C from last to second with the numpy library. It is important to note that these functions are expected to take in and output a np.ndarray ! This way, we can create and perform transformations including augmentations on arbitrary numpy.ndarrays . Or we could just write a wrapper class for other libraries, such as albumentations to make use of their transformations (more on that later). The __repr__ is just a printable representation of a object and makes it easier to understand what transformations and what arguments were used.
Why the effort you may ask? Well, this makes it clear what transformations are performed on the data when we create the dataset. The ComposeDouble class just puts the different transformation together.
Let’s test it out with some random input-target-data.
Here we also resize our input and target image by using the skimage.transform.resize(). And we linearly scale our input to the range [0, 1] using normalize01 . We could also normalize the input based on a mean and std of a given dataset with normalize from the transformations.py file, but this will do for now.
This will output:
x = shape: (128, 128, 3); type: uint8x = min: 0; max: 255x_t: shape: (3, 64, 64) type: float64x_t = min: 0.0; max: 1.0y = shape: (128, 128); class: [10 11 12 13 14]y_t = shape: (64, 64); class: [0 1 2 3 4]
Now let’s put these pieces of code together to create a dataset for the Carvana dataset. We have our input images stored in Carvana/Input and our targets stored in Carvana/Targets. This is just a sample of the original dataset and can be downloaded here or found in the github repo. This sample consists of only 6 cars, but each car from 16 angles — 96 images in total. I will be using the pathlib library to get the directory path of every input and target. If this library is new to you, you should check it out here.
We import the SegmentationDataSet class and the transformations that we want to use. To get the input-target paths, I use the function get_filenames_of_path that will return a list of all items within a directory. We then stack our transformations inside the Compose object that we name transforms. Because training is usually performed with a training dataset and a validation dataset, we split our input and target lists with sklearn.model_selection.train_test_split(). We could do it manually too (and it makes more sense for this dataset), but that’s ok for now. With these lists, we can create our datasets and the corresponding dataloaders. Now we should check if our datasets (training and validation) output the correct format! Since the datasets have a __getitem__ and method, we can treat them almost like a sequence object (e.g. list):
This will give us:
x = shape: torch.Size([2, 3, 1280, 1918]); type: torch.float32x = min: 0.0; max: 1.0y = shape: torch.Size([2, 1280, 1918]); class: tensor([0, 1]); type: torch.int64
To check if our dataloader functions the way we want, we can get a batch with:
x, y = next(iter(dataloader_training))
Everything seems to be in order now. Now let’s visualize this result.
In order to inspect our transformed images, we should visualize the input and it’s respective target image. For 2D images, we could use matplotlib. For 3D images, however, it becomes a bit hacky and slow. But there is an alternative: napari. This is a fast, interactive multi-dimensional image viewer for python, that can be used in a jupyter notebook, an Ipython console or within a .py script.
It’s built on top of Qt (for the GUI), vispy (for performant GPU-based rendering), and the scientific Python stack (numpy, scipy). — napari
To visualize our dataset, we should reverse some of the transformations we performed on the data, e.g. we would like to have an input image of shape [H, W, C], in the range of [0–255] and as numpy.ndarray. Let’s create a visual.py file in which we create a DatasetViewer class:
I won’t go into details about napari and the code here. This class basically allows us to view our the images and targets of our dataset by iterating over the dataset with custom keybindings (’n’ for next and ‘b’ for back)! Some comments on the transforms: The function re_normalize() scales the input image back to [0–255]. We assume that our images and targets are torch.tensors and force them to be on the cpu and as np.ndarrays.
Let’s test it out:
You do not need to enter %gui qt before using napari in Ipython or witihn a Jupyter notebook in this case, because this will be evoked when intantiating the class with the enabel_gui_qt() function.
# open napari instance for training dataset# navigate with 'n' for next and 'b' for back on the keyboard# you can do the same for the validation datasetfrom visual import DatasetViewerdataset_viewer_training = DatasetViewer(dataset_train) dataset_viewer_training.napari()
This will open a GUI that will look something like this:
When I press 'n' on the keyboard, I will get the next image-target pair from the dataset:
Now that we have a solid codebase, let’s expand our dataset with some augmentations.
For 2D images, we don’t have to implement everything from scratch with numpy. Instead, we could use a library like albumentations. For that, we just need to write a wrapper, like AlbuSeg2d. As an example, we could horizontally flip our training images and their respective targets. The validation images are usually not augmented, which makes it necessary to have different transformations for the training and validation dataset:
We can then change the code for our dataset objects accordingly:
The probability of a flipped image is p=0.5. When we visualize the image-target pairs again, we eventually get batches with horizontally flipped input-target pairs:
We have created a data generator that can feed a network with batches of transformed/augmented data in the correct format. We also know how to visualize our dataset with the help of napari. This applies to 2D and 3D datasets. Now that we have spent some time on creating and visualizing the dataset, let’s move on to model building in the next chapter. | [
{
"code": null,
"e": 747,
"s": 171,
"text": "In this series (4 parts) we will perform semantic segmentation on images using plain PyTorch and the U-Net architecture. I will cover the following topics: Dataset building, model building (U-Net), training and inference. For that I will use a sample of the infamous Carvana dataset (2D images), but the code and the methods work for 3D datasets as well. For example: I will not use the torchvision package, as most transformations and augmentations only work on 2D input with PIL. You can find the repo of this project here with a jupyter notebook for every part (and more)."
},
{
"code": null,
"e": 1249,
"s": 747,
"text": "I was a master student in biology who started to learn programming with python and ended up trying deep learning (semantic segmentation with U-Net) on electron tomograms (3D images) for my master thesis. In this process I not only learned quite a lot about deep learning, python and programming but also how to better structure your project and code. This blog aims to share my experience and a tutorial to use plain PyTorch to efficiently use deep learning for your own semantic segmentation project."
},
{
"code": null,
"e": 1941,
"s": 1249,
"text": "To bring more structure into your project, I recommend to create a new project and create several python files, each having different classes and functions that can be imported and used. Personally, I like to use PyCharm for that but other IDEs such as Spyder are also a good choice. I also prefer working with the IPython console within PyCharm instead of Jupyter notebooks. A combination of both can be very helpful though. If you prefer a single Jupyter Notebook, that’s also fine, just bear in mind that it could get to be a long script. You can find the files and code on github. Most of the structure and code that I will be showing is inspired by the work of this project: elektronn3."
},
{
"code": null,
"e": 2441,
"s": 1941,
"text": "Before we start creating our data generator, let’s talk about the data first. What we would like to have is two directories, something like /Input and /Target. In the /Input directory, we find all input images and in the /Target directory the segmentation maps. Visualizing the images would look something like the image below. The labels are usually encoded with pixel values, meaning that all pixels of the same class have the same pixel value e.g. background=0, dog=1, cat=2 in the example below."
},
{
"code": null,
"e": 2529,
"s": 2441,
"text": "The goal of the network is to predict such a segmentation map from a given input image."
},
{
"code": null,
"e": 2672,
"s": 2529,
"text": "In deep learning, we want to feed our network with batches of data. Therefore, we would like to have a data generator that does the following:"
},
{
"code": null,
"e": 2764,
"s": 2672,
"text": "It picks up the input-target pairsIt performs some transformations on the data “on the fly”"
},
{
"code": null,
"e": 2799,
"s": 2764,
"text": "It picks up the input-target pairs"
},
{
"code": null,
"e": 2857,
"s": 2799,
"text": "It performs some transformations on the data “on the fly”"
},
{
"code": null,
"e": 3197,
"s": 2857,
"text": "With PyTorch it is fairly easy to create such a data generator. We create a custom Dataset class, instantiate it and pass it to PyTorch’s dataloader. Here is a simple example of such a dataset for a potential segmentation pipeline (Spoiler: In part 3 I will make use of the multiprocessing library and use caching to improve this dataset):"
},
{
"code": null,
"e": 4270,
"s": 3197,
"text": "The SegmentationDataSet class inherits from torch.data.Dataset . In the initialization method __init__, we expect a list of input paths and a list of target paths. The __getitem__ method simply reads an item from our input and target list using the skimage.imread() function. This will give us our input and target image as numpy.ndarrays. We then process our data with the transform function that expects an input and target pair and should return the processed data as numpy.ndarrays again. But I will come to that later. At the end, we just make sure that we end up having a torch.tensor of certain type for our input and target. In this case, this is usually torch.float32 and torch.int64 (long) for input and target, respectively. This dataset can be then used to create our dataloader (the data generator that we want). You may ask: How do we make sure that this dataset will output the correct target for every input image? If the input and target lists happen to have the same order, e.g. because input and target have the same name, the mapping should be correct."
},
{
"code": null,
"e": 4310,
"s": 4270,
"text": "Let’s try it out with a simple example:"
},
{
"code": null,
"e": 4956,
"s": 4310,
"text": "inputs = ['path\\input\\pic_01.png', 'path\\input\\pic_02.png']targets = ['path\\target\\pic_01.png', 'path\\target\\pic_02.png']training_dataset = SegmentationDataSet(inputs=inputs, targets=targets, transform=None)training_dataloader = data.DataLoader(dataset=training_dataset, batch_size=2, shuffle=True)x, y = next(iter(training_dataloader))print(f'x = shape: {x.shape}; type: {x.dtype}')print(f'x = min: {x.min()}; max: {x.max()}')print(f'y = shape: {y.shape}; class: {y.unique()}; type: {y.dtype}')"
},
{
"code": null,
"e": 5441,
"s": 4956,
"text": "Here, we create an instance of our SegmentationDataSet class. For now, we don’t want any transformation to happen on our data, so we leave transform=None . In the next step we create our data loader by passing our training_dataset as input. We choose to have an batch_size of 2 and to shuffle the data shuffle=True . There are some other useful arguments that can be passed in when instantiating the dataloader and you should check them out. The result could look something like this:"
},
{
"code": null,
"e": 5608,
"s": 5441,
"text": "x = shape: torch.Size([2, 144, 144, 3]); type: torch.float32x = min: 8.0; max: 255.0y = shape: torch.Size([2, 144, 144]); class: tensor([ 0, 255]); type: torch.int64"
},
{
"code": null,
"e": 5646,
"s": 5608,
"text": "There are some things to notice here:"
},
{
"code": null,
"e": 6165,
"s": 5646,
"text": "The type of x and y is already correct.The x should have a shape of [N, C, H, W] . So the channel dimension should be second instead of last.The y is supposed to have a shape [N, H, W] , (this is because torch’s loss function torch.nn.CrossEntropyLoss expects it, even though it will internally one-hot encode it).The target y has only 2 classes: 0 and 255. But we want dense integer encoding, meaning 0 and 1.The input is in the range [0-255] — uint8, but should be normalized or linearly scaled to [0, 1] or [-1, 1]."
},
{
"code": null,
"e": 6205,
"s": 6165,
"text": "The type of x and y is already correct."
},
{
"code": null,
"e": 6308,
"s": 6205,
"text": "The x should have a shape of [N, C, H, W] . So the channel dimension should be second instead of last."
},
{
"code": null,
"e": 6482,
"s": 6308,
"text": "The y is supposed to have a shape [N, H, W] , (this is because torch’s loss function torch.nn.CrossEntropyLoss expects it, even though it will internally one-hot encode it)."
},
{
"code": null,
"e": 6579,
"s": 6482,
"text": "The target y has only 2 classes: 0 and 255. But we want dense integer encoding, meaning 0 and 1."
},
{
"code": null,
"e": 6688,
"s": 6579,
"text": "The input is in the range [0-255] — uint8, but should be normalized or linearly scaled to [0, 1] or [-1, 1]."
},
{
"code": null,
"e": 6748,
"s": 6688,
"text": "Because of this we need to transform the data a little bit."
},
{
"code": null,
"e": 7027,
"s": 6748,
"text": "Note: If we omit the typecasting at the end of our SegmentationDataSet, the dataloader would still not output numpy.ndarrays but torch.tensors. As our input is read as a numpy.ndarray in uint8, it will also output a torch.tensor in uint8. For float32 we need to change the type."
},
{
"code": null,
"e": 7085,
"s": 7027,
"text": "Let’s create a new file, that we name transformations.py."
},
{
"code": null,
"e": 7997,
"s": 7085,
"text": "In order to transform our data so that they meet the requirements of the network, we create a class FunctionWrapperDouble which can take any function and returns a partial (basically a function with defined arguments). This allows us to stack (functions) transformations in a list that we want to be applied on the data. To stack these functions I use the ComposeDouble class. The Double in these classes means that it is meant for a dataset with input-target pairs (like our case for semantic segmentation). There is also a Single version of these classes for the case that you want to just experiment with some input or target images (or visualize your dataset). So what we want, is to create an object, that comprises all the transformations that we want to apply to the data. We can then pass this object as an argument in our SegmentationDataSet instance. Confused? Let me show what I mean with an example:"
},
{
"code": null,
"e": 8845,
"s": 7997,
"text": "The tranfsorms variable is an instance of the ComposeDouble class that comprises a list of transformations that is to be applied to the data! create_dense_target and normalize_01 are functions that I defined in transformations.py, while np.moveaxis is just a numpy function that simply moves the channel dimension C from last to second with the numpy library. It is important to note that these functions are expected to take in and output a np.ndarray ! This way, we can create and perform transformations including augmentations on arbitrary numpy.ndarrays . Or we could just write a wrapper class for other libraries, such as albumentations to make use of their transformations (more on that later). The __repr__ is just a printable representation of a object and makes it easier to understand what transformations and what arguments were used."
},
{
"code": null,
"e": 9047,
"s": 8845,
"text": "Why the effort you may ask? Well, this makes it clear what transformations are performed on the data when we create the dataset. The ComposeDouble class just puts the different transformation together."
},
{
"code": null,
"e": 9101,
"s": 9047,
"text": "Let’s test it out with some random input-target-data."
},
{
"code": null,
"e": 9413,
"s": 9101,
"text": "Here we also resize our input and target image by using the skimage.transform.resize(). And we linearly scale our input to the range [0, 1] using normalize01 . We could also normalize the input based on a mean and std of a given dataset with normalize from the transformations.py file, but this will do for now."
},
{
"code": null,
"e": 9431,
"s": 9413,
"text": "This will output:"
},
{
"code": null,
"e": 9638,
"s": 9431,
"text": "x = shape: (128, 128, 3); type: uint8x = min: 0; max: 255x_t: shape: (3, 64, 64) type: float64x_t = min: 0.0; max: 1.0y = shape: (128, 128); class: [10 11 12 13 14]y_t = shape: (64, 64); class: [0 1 2 3 4]"
},
{
"code": null,
"e": 10158,
"s": 9638,
"text": "Now let’s put these pieces of code together to create a dataset for the Carvana dataset. We have our input images stored in Carvana/Input and our targets stored in Carvana/Targets. This is just a sample of the original dataset and can be downloaded here or found in the github repo. This sample consists of only 6 cars, but each car from 16 angles — 96 images in total. I will be using the pathlib library to get the directory path of every input and target. If this library is new to you, you should check it out here."
},
{
"code": null,
"e": 11005,
"s": 10158,
"text": "We import the SegmentationDataSet class and the transformations that we want to use. To get the input-target paths, I use the function get_filenames_of_path that will return a list of all items within a directory. We then stack our transformations inside the Compose object that we name transforms. Because training is usually performed with a training dataset and a validation dataset, we split our input and target lists with sklearn.model_selection.train_test_split(). We could do it manually too (and it makes more sense for this dataset), but that’s ok for now. With these lists, we can create our datasets and the corresponding dataloaders. Now we should check if our datasets (training and validation) output the correct format! Since the datasets have a __getitem__ and method, we can treat them almost like a sequence object (e.g. list):"
},
{
"code": null,
"e": 11024,
"s": 11005,
"text": "This will give us:"
},
{
"code": null,
"e": 11189,
"s": 11024,
"text": "x = shape: torch.Size([2, 3, 1280, 1918]); type: torch.float32x = min: 0.0; max: 1.0y = shape: torch.Size([2, 1280, 1918]); class: tensor([0, 1]); type: torch.int64"
},
{
"code": null,
"e": 11268,
"s": 11189,
"text": "To check if our dataloader functions the way we want, we can get a batch with:"
},
{
"code": null,
"e": 11307,
"s": 11268,
"text": "x, y = next(iter(dataloader_training))"
},
{
"code": null,
"e": 11377,
"s": 11307,
"text": "Everything seems to be in order now. Now let’s visualize this result."
},
{
"code": null,
"e": 11773,
"s": 11377,
"text": "In order to inspect our transformed images, we should visualize the input and it’s respective target image. For 2D images, we could use matplotlib. For 3D images, however, it becomes a bit hacky and slow. But there is an alternative: napari. This is a fast, interactive multi-dimensional image viewer for python, that can be used in a jupyter notebook, an Ipython console or within a .py script."
},
{
"code": null,
"e": 11913,
"s": 11773,
"text": "It’s built on top of Qt (for the GUI), vispy (for performant GPU-based rendering), and the scientific Python stack (numpy, scipy). — napari"
},
{
"code": null,
"e": 12191,
"s": 11913,
"text": "To visualize our dataset, we should reverse some of the transformations we performed on the data, e.g. we would like to have an input image of shape [H, W, C], in the range of [0–255] and as numpy.ndarray. Let’s create a visual.py file in which we create a DatasetViewer class:"
},
{
"code": null,
"e": 12624,
"s": 12191,
"text": "I won’t go into details about napari and the code here. This class basically allows us to view our the images and targets of our dataset by iterating over the dataset with custom keybindings (’n’ for next and ‘b’ for back)! Some comments on the transforms: The function re_normalize() scales the input image back to [0–255]. We assume that our images and targets are torch.tensors and force them to be on the cpu and as np.ndarrays."
},
{
"code": null,
"e": 12643,
"s": 12624,
"text": "Let’s test it out:"
},
{
"code": null,
"e": 12841,
"s": 12643,
"text": "You do not need to enter %gui qt before using napari in Ipython or witihn a Jupyter notebook in this case, because this will be evoked when intantiating the class with the enabel_gui_qt() function."
},
{
"code": null,
"e": 13113,
"s": 12841,
"text": "# open napari instance for training dataset# navigate with 'n' for next and 'b' for back on the keyboard# you can do the same for the validation datasetfrom visual import DatasetViewerdataset_viewer_training = DatasetViewer(dataset_train) dataset_viewer_training.napari()"
},
{
"code": null,
"e": 13170,
"s": 13113,
"text": "This will open a GUI that will look something like this:"
},
{
"code": null,
"e": 13260,
"s": 13170,
"text": "When I press 'n' on the keyboard, I will get the next image-target pair from the dataset:"
},
{
"code": null,
"e": 13345,
"s": 13260,
"text": "Now that we have a solid codebase, let’s expand our dataset with some augmentations."
},
{
"code": null,
"e": 13776,
"s": 13345,
"text": "For 2D images, we don’t have to implement everything from scratch with numpy. Instead, we could use a library like albumentations. For that, we just need to write a wrapper, like AlbuSeg2d. As an example, we could horizontally flip our training images and their respective targets. The validation images are usually not augmented, which makes it necessary to have different transformations for the training and validation dataset:"
},
{
"code": null,
"e": 13841,
"s": 13776,
"text": "We can then change the code for our dataset objects accordingly:"
},
{
"code": null,
"e": 14006,
"s": 13841,
"text": "The probability of a flipped image is p=0.5. When we visualize the image-target pairs again, we eventually get batches with horizontally flipped input-target pairs:"
}
] |
Creating AWS EC2 and connecting it with AWS Cloud9 IDE and AWS S3 | by Ahmed Amer | Towards Data Science | Sometimes, you can be blocked from completing a task just because of your desktop capabilities. As a data scientist for example, most of the time it is almost impossible to load a huge dataset to your personal desktop. Even if you were able to load this data, training your model might take forever. One possible solution is to use Amazon Web Services (AWS). You can read more about AWS from here.
Using Amazon Elastic Compute Cloud (Amazon EC2) will help solve the previously stated problems. It is scalable and eliminates the need to invest in hardware up front. You can read more about Amazon EC2 from here.
There is also Amazon Simple Storage Service (Amazon S3) that can be used to store and retrieve any amount of data at anytime. You can read more about Amazon S3 from here.
To make the communication with the Amazon EC2 easier, you can use AWS Cloud9. It is a cloud-based integrated development environment (IDE) that lets you write, run and debug your code using the browser. You can read more about AWS Cloud9 from here.
In this article, we will:
Get Access key and Secret KeyBuild an AWS EC2 instance.Connect to this instance using PuTTY.Connect to AWS S3.Connect to AWS Cloud9.
Get Access key and Secret Key
Build an AWS EC2 instance.
Connect to this instance using PuTTY.
Connect to AWS S3.
Connect to AWS Cloud9.
Access key and secret key are used to authenticate requests you make to AWS.
After creating an AWS account from here, log in to AWS Management Console from here.
First, we need to create an Access Key and Secret Key. In Security, Identity, & Compliance pick IAM (Identity and Access Management).
Press Users then choose your user name. If you cannot find your username, press Add user.
After pressing your user name, inside the Security credentials tab press Create Access Key. Then download .csv file. You will find your Access Key & Secret Key inside. Keep them stored in a safe place as you will need them later.
Go back to AWS Management Console, from compute pick EC2.
Press Launch Instance.
Choose whatever suits you from the options shown. For this tutorial I am going for Ubuntu Server 20.04 LTS. Press Select
Choose the instance you need. For this tutorial I am going for t2.micro. For more information about the Amazon EC2 Instance Types, you can press here.
From the tabs above, choose 4.Add Storage. You can increase the size if needed.
Choose 6.Configure Security Group. Change Assign a security group to Select an existing security group. Choose the group you want. The policy should be created already by your admin or you can create it. If you do not choose a security group, your machine will be public and can be accessed by anyone. Feel free to play around with any other configurations if needed. Finally, press Review and Launch then Launch.
Change choose an existing key pair to Create a new key pair. Then add a name for this key pair and press download key pair. This will download a pem file. Then press Launch Instances. Finally, Press View Instances.
You should find your machine in there without a name. Rename it to whatever you want then Click on it to choose it. Copy the Public DNS(IPv4) as we will need it in the next step.
For the next step you need to install PuTTY. PuTTY is a terminal emulation software that runs on Windows, Unix and Linux.
Open PuTTYgen. Choose Load. Go to the path where you saved the pem file (Was saved previously in step 2). Make sure to set the type of files to All Files(*.*) to see the pem file. Double click that pem file.
You should get a message that you successfully imported foreign key. Press ok then save private key.
Close PuTTYgen and open PuTTY.
In the Hostname write ubuntu@<Paste the Public DNS(IPv4)>
Expand the SSH then press on the AUTH. Click Browse and go to the PPK you saved before then double click on it.
Go back to Session then add a name in the “Saved Sessions” then press Save. This way you saved your configuration to PuTTY. The next time you want to connect to the machine, you will only press load next time.
Finally press “Open”
Now you are connected to the machine through the terminal and can write any linux commands you want.
You should start by the following 2 commands to update the environment.
sudo apt-get updatesudo apt-get -y upgrade
To interact with AWS S3 through the machine, you can install awscli through the following command
sudo apt-get install -y awscliaws configure
“aws configure” will ask you to enter the access key and secret key that you generate before in the IAM (From Step 1). For the other 2 prompts, just press enter (No need to fill them).
To copy something from aws to your machine is like using cp command in linux. Example:
aws s3 cp source destination
The source and destination can be either a local path on the machine, or path on s3.
For s3 path, you just need to add s3:// at the beginning.
Example to copy a file from S3 to local machine:
aws s3 cp s3://FolderName/fileName.txt ./fileName.txt
Keep PuTTY connected to the instance and the terminal running for the next step.
From AWS Management Console, inside the Developer Tools choose Cloud9.
Press Create environment. Add any name for that environment then press next.
In the configure settings, change the Environment type to Connect and run in remote server (SSH). In the user, write ubuntu. Add the instance’s public DNS IPv4. Then press Copy Key to Clipboard.
In PuTTY terminal that is connected to the machine, write the following commands to save the key in the machine:
echo <Paste the Copied Key> >> ~/.ssh/authorized_keyssudo apt-get install -y nodejs
Cloud9 needs nodejs that is why we installed it.
Press Next Step in Configure Settings then Create Environment.
Right click on “C9 install” and copy link address.
Press Next and leave everything ticked.
Go to PuTTY terminal and run the following commands:
wget <Paste the copied link address>chmod a+x c9-install.shsudo apt-get -y install pythonsudo apt-get install build-essential./c9-install.sh
Now you can close PuTTY and continue from Cloud9.
Now you are ready to start development on this IDE. You can upload files or data from your local machine to the EC2 using Cloud9 just by drag and drop. You can also run/debug the code or use terminal below to interact with the machine.
Note: If the instance’s IP address changed (Happens when you stop an Instance then restart its running), you will just simply need to copy the new IPv4 address.
In Cloud9, on the top left corner, press the Cloud9 icon.
Click on “Go to Your Dashboard”. Press the desired environment and from the top right corner then choose Edit. Then Scroll down to the Host and just change the IPv4 address.
This tutorial provided a step-by-step guide to launch and connect AWS EC2 to AWS Cloud9, along with moving data from or to AWS S3. This should help with setting a basic data science environment.
I recommend AWS Documentation for more information about all the services that amazon provides. | [
{
"code": null,
"e": 570,
"s": 172,
"text": "Sometimes, you can be blocked from completing a task just because of your desktop capabilities. As a data scientist for example, most of the time it is almost impossible to load a huge dataset to your personal desktop. Even if you were able to load this data, training your model might take forever. One possible solution is to use Amazon Web Services (AWS). You can read more about AWS from here."
},
{
"code": null,
"e": 783,
"s": 570,
"text": "Using Amazon Elastic Compute Cloud (Amazon EC2) will help solve the previously stated problems. It is scalable and eliminates the need to invest in hardware up front. You can read more about Amazon EC2 from here."
},
{
"code": null,
"e": 954,
"s": 783,
"text": "There is also Amazon Simple Storage Service (Amazon S3) that can be used to store and retrieve any amount of data at anytime. You can read more about Amazon S3 from here."
},
{
"code": null,
"e": 1203,
"s": 954,
"text": "To make the communication with the Amazon EC2 easier, you can use AWS Cloud9. It is a cloud-based integrated development environment (IDE) that lets you write, run and debug your code using the browser. You can read more about AWS Cloud9 from here."
},
{
"code": null,
"e": 1229,
"s": 1203,
"text": "In this article, we will:"
},
{
"code": null,
"e": 1362,
"s": 1229,
"text": "Get Access key and Secret KeyBuild an AWS EC2 instance.Connect to this instance using PuTTY.Connect to AWS S3.Connect to AWS Cloud9."
},
{
"code": null,
"e": 1392,
"s": 1362,
"text": "Get Access key and Secret Key"
},
{
"code": null,
"e": 1419,
"s": 1392,
"text": "Build an AWS EC2 instance."
},
{
"code": null,
"e": 1457,
"s": 1419,
"text": "Connect to this instance using PuTTY."
},
{
"code": null,
"e": 1476,
"s": 1457,
"text": "Connect to AWS S3."
},
{
"code": null,
"e": 1499,
"s": 1476,
"text": "Connect to AWS Cloud9."
},
{
"code": null,
"e": 1576,
"s": 1499,
"text": "Access key and secret key are used to authenticate requests you make to AWS."
},
{
"code": null,
"e": 1661,
"s": 1576,
"text": "After creating an AWS account from here, log in to AWS Management Console from here."
},
{
"code": null,
"e": 1795,
"s": 1661,
"text": "First, we need to create an Access Key and Secret Key. In Security, Identity, & Compliance pick IAM (Identity and Access Management)."
},
{
"code": null,
"e": 1885,
"s": 1795,
"text": "Press Users then choose your user name. If you cannot find your username, press Add user."
},
{
"code": null,
"e": 2115,
"s": 1885,
"text": "After pressing your user name, inside the Security credentials tab press Create Access Key. Then download .csv file. You will find your Access Key & Secret Key inside. Keep them stored in a safe place as you will need them later."
},
{
"code": null,
"e": 2173,
"s": 2115,
"text": "Go back to AWS Management Console, from compute pick EC2."
},
{
"code": null,
"e": 2196,
"s": 2173,
"text": "Press Launch Instance."
},
{
"code": null,
"e": 2317,
"s": 2196,
"text": "Choose whatever suits you from the options shown. For this tutorial I am going for Ubuntu Server 20.04 LTS. Press Select"
},
{
"code": null,
"e": 2468,
"s": 2317,
"text": "Choose the instance you need. For this tutorial I am going for t2.micro. For more information about the Amazon EC2 Instance Types, you can press here."
},
{
"code": null,
"e": 2548,
"s": 2468,
"text": "From the tabs above, choose 4.Add Storage. You can increase the size if needed."
},
{
"code": null,
"e": 2962,
"s": 2548,
"text": "Choose 6.Configure Security Group. Change Assign a security group to Select an existing security group. Choose the group you want. The policy should be created already by your admin or you can create it. If you do not choose a security group, your machine will be public and can be accessed by anyone. Feel free to play around with any other configurations if needed. Finally, press Review and Launch then Launch."
},
{
"code": null,
"e": 3177,
"s": 2962,
"text": "Change choose an existing key pair to Create a new key pair. Then add a name for this key pair and press download key pair. This will download a pem file. Then press Launch Instances. Finally, Press View Instances."
},
{
"code": null,
"e": 3356,
"s": 3177,
"text": "You should find your machine in there without a name. Rename it to whatever you want then Click on it to choose it. Copy the Public DNS(IPv4) as we will need it in the next step."
},
{
"code": null,
"e": 3478,
"s": 3356,
"text": "For the next step you need to install PuTTY. PuTTY is a terminal emulation software that runs on Windows, Unix and Linux."
},
{
"code": null,
"e": 3686,
"s": 3478,
"text": "Open PuTTYgen. Choose Load. Go to the path where you saved the pem file (Was saved previously in step 2). Make sure to set the type of files to All Files(*.*) to see the pem file. Double click that pem file."
},
{
"code": null,
"e": 3787,
"s": 3686,
"text": "You should get a message that you successfully imported foreign key. Press ok then save private key."
},
{
"code": null,
"e": 3818,
"s": 3787,
"text": "Close PuTTYgen and open PuTTY."
},
{
"code": null,
"e": 3876,
"s": 3818,
"text": "In the Hostname write ubuntu@<Paste the Public DNS(IPv4)>"
},
{
"code": null,
"e": 3988,
"s": 3876,
"text": "Expand the SSH then press on the AUTH. Click Browse and go to the PPK you saved before then double click on it."
},
{
"code": null,
"e": 4198,
"s": 3988,
"text": "Go back to Session then add a name in the “Saved Sessions” then press Save. This way you saved your configuration to PuTTY. The next time you want to connect to the machine, you will only press load next time."
},
{
"code": null,
"e": 4219,
"s": 4198,
"text": "Finally press “Open”"
},
{
"code": null,
"e": 4320,
"s": 4219,
"text": "Now you are connected to the machine through the terminal and can write any linux commands you want."
},
{
"code": null,
"e": 4392,
"s": 4320,
"text": "You should start by the following 2 commands to update the environment."
},
{
"code": null,
"e": 4435,
"s": 4392,
"text": "sudo apt-get updatesudo apt-get -y upgrade"
},
{
"code": null,
"e": 4533,
"s": 4435,
"text": "To interact with AWS S3 through the machine, you can install awscli through the following command"
},
{
"code": null,
"e": 4577,
"s": 4533,
"text": "sudo apt-get install -y awscliaws configure"
},
{
"code": null,
"e": 4762,
"s": 4577,
"text": "“aws configure” will ask you to enter the access key and secret key that you generate before in the IAM (From Step 1). For the other 2 prompts, just press enter (No need to fill them)."
},
{
"code": null,
"e": 4849,
"s": 4762,
"text": "To copy something from aws to your machine is like using cp command in linux. Example:"
},
{
"code": null,
"e": 4878,
"s": 4849,
"text": "aws s3 cp source destination"
},
{
"code": null,
"e": 4963,
"s": 4878,
"text": "The source and destination can be either a local path on the machine, or path on s3."
},
{
"code": null,
"e": 5021,
"s": 4963,
"text": "For s3 path, you just need to add s3:// at the beginning."
},
{
"code": null,
"e": 5070,
"s": 5021,
"text": "Example to copy a file from S3 to local machine:"
},
{
"code": null,
"e": 5124,
"s": 5070,
"text": "aws s3 cp s3://FolderName/fileName.txt ./fileName.txt"
},
{
"code": null,
"e": 5205,
"s": 5124,
"text": "Keep PuTTY connected to the instance and the terminal running for the next step."
},
{
"code": null,
"e": 5276,
"s": 5205,
"text": "From AWS Management Console, inside the Developer Tools choose Cloud9."
},
{
"code": null,
"e": 5353,
"s": 5276,
"text": "Press Create environment. Add any name for that environment then press next."
},
{
"code": null,
"e": 5548,
"s": 5353,
"text": "In the configure settings, change the Environment type to Connect and run in remote server (SSH). In the user, write ubuntu. Add the instance’s public DNS IPv4. Then press Copy Key to Clipboard."
},
{
"code": null,
"e": 5661,
"s": 5548,
"text": "In PuTTY terminal that is connected to the machine, write the following commands to save the key in the machine:"
},
{
"code": null,
"e": 5745,
"s": 5661,
"text": "echo <Paste the Copied Key> >> ~/.ssh/authorized_keyssudo apt-get install -y nodejs"
},
{
"code": null,
"e": 5794,
"s": 5745,
"text": "Cloud9 needs nodejs that is why we installed it."
},
{
"code": null,
"e": 5857,
"s": 5794,
"text": "Press Next Step in Configure Settings then Create Environment."
},
{
"code": null,
"e": 5908,
"s": 5857,
"text": "Right click on “C9 install” and copy link address."
},
{
"code": null,
"e": 5948,
"s": 5908,
"text": "Press Next and leave everything ticked."
},
{
"code": null,
"e": 6001,
"s": 5948,
"text": "Go to PuTTY terminal and run the following commands:"
},
{
"code": null,
"e": 6142,
"s": 6001,
"text": "wget <Paste the copied link address>chmod a+x c9-install.shsudo apt-get -y install pythonsudo apt-get install build-essential./c9-install.sh"
},
{
"code": null,
"e": 6192,
"s": 6142,
"text": "Now you can close PuTTY and continue from Cloud9."
},
{
"code": null,
"e": 6428,
"s": 6192,
"text": "Now you are ready to start development on this IDE. You can upload files or data from your local machine to the EC2 using Cloud9 just by drag and drop. You can also run/debug the code or use terminal below to interact with the machine."
},
{
"code": null,
"e": 6589,
"s": 6428,
"text": "Note: If the instance’s IP address changed (Happens when you stop an Instance then restart its running), you will just simply need to copy the new IPv4 address."
},
{
"code": null,
"e": 6647,
"s": 6589,
"text": "In Cloud9, on the top left corner, press the Cloud9 icon."
},
{
"code": null,
"e": 6821,
"s": 6647,
"text": "Click on “Go to Your Dashboard”. Press the desired environment and from the top right corner then choose Edit. Then Scroll down to the Host and just change the IPv4 address."
},
{
"code": null,
"e": 7016,
"s": 6821,
"text": "This tutorial provided a step-by-step guide to launch and connect AWS EC2 to AWS Cloud9, along with moving data from or to AWS S3. This should help with setting a basic data science environment."
}
] |
How do I subtract minutes from a date in JavaScript? | To subtract minutes to a JavaScript Date object, use the setMinutes() method. JavaScript date setMinutes() method sets the minutes for a specified date according to local time.
You can try to run the following code to subtract 20 minutes.
<html>
<head>
<title>JavaScript setMinutes Method</title>
</head>
<body>
<script>
var dt = new Date("December 31, 2017 11:30:25");
dt.setMinutes( dt.getMinutes() - 20 );
document.write( dt );
</script>
</body>
</html> | [
{
"code": null,
"e": 1239,
"s": 1062,
"text": "To subtract minutes to a JavaScript Date object, use the setMinutes() method. JavaScript date setMinutes() method sets the minutes for a specified date according to local time."
},
{
"code": null,
"e": 1301,
"s": 1239,
"text": "You can try to run the following code to subtract 20 minutes."
},
{
"code": null,
"e": 1576,
"s": 1301,
"text": "<html>\n <head>\n <title>JavaScript setMinutes Method</title>\n </head>\n <body>\n <script>\n var dt = new Date(\"December 31, 2017 11:30:25\");\n dt.setMinutes( dt.getMinutes() - 20 );\n document.write( dt );\n </script>\n </body>\n</html>"
}
] |
How to get local date in android using local date API class? | This example demonstrate about How to get local date in android using local date API class.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Local Date"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
In the above code, we have taken textview to show date.
Step 3 − Add the following code to src/MainActivity.java
package com.example.myapplication;
import android.icu.util.LocaleData;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import java.awt.font.TextAttribute;
import java.time.LocalDate;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textView=findViewById(R.id.date);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
LocalDate date=LocalDate.now();
LocalDate yesterday=date.minusDays(1);
LocalDate tomorrow=date.plusDays(1);
textView.setText(String.valueOf("Today "+date+" Yesterday "+yesterday+" tomorrow "+tomorrow));
}
}
}
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
In the above result, it is showing today date, yesterday and tomorrow date. To verify the date check system date as shown below −
Click here to download the project code | [
{
"code": null,
"e": 1154,
"s": 1062,
"text": "This example demonstrate about How to get local date in android using local date API class."
},
{
"code": null,
"e": 1283,
"s": 1154,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1348,
"s": 1283,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2125,
"s": 1348,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<android.support.constraint.ConstraintLayout\n xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:app=\"http://schemas.android.com/apk/res-auto\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n <TextView\n android:id=\"@+id/date\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Local Date\"\n app:layout_constraintBottom_toBottomOf=\"parent\"\n app:layout_constraintLeft_toLeftOf=\"parent\"\n app:layout_constraintRight_toRightOf=\"parent\"\n app:layout_constraintTop_toTopOf=\"parent\" />\n</android.support.constraint.ConstraintLayout>"
},
{
"code": null,
"e": 2181,
"s": 2125,
"text": "In the above code, we have taken textview to show date."
},
{
"code": null,
"e": 2238,
"s": 2181,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 3079,
"s": 2238,
"text": "package com.example.myapplication;\n\nimport android.icu.util.LocaleData;\nimport android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.widget.TextView;\n\nimport java.awt.font.TextAttribute;\nimport java.time.LocalDate;\n\npublic class MainActivity extends AppCompatActivity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n TextView textView=findViewById(R.id.date);\n if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {\n LocalDate date=LocalDate.now();\n LocalDate yesterday=date.minusDays(1);\n LocalDate tomorrow=date.plusDays(1);\n textView.setText(String.valueOf(\"Today \"+date+\" Yesterday \"+yesterday+\" tomorrow \"+tomorrow));\n }\n }\n}"
},
{
"code": null,
"e": 3426,
"s": 3079,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −"
},
{
"code": null,
"e": 3556,
"s": 3426,
"text": "In the above result, it is showing today date, yesterday and tomorrow date. To verify the date check system date as shown below −"
},
{
"code": null,
"e": 3596,
"s": 3556,
"text": "Click here to download the project code"
}
] |
How to Make a Professional-looking Shiny App and Not Get Intimidated (With R) | by Lathan Liou | Towards Data Science | This article is aimed towards people who have experience with R (ideally the tidyverse) and want to learn how to start making Shiny apps. For those who haven’t heard of Shiny before, it’s a package that allows you to create web applications using R without needing to know any HTML, CSS, or Javascript. That being said, if you do want to get deeper into app development, learning HTML, CSS, and Javascript will increase your ability to do more powerful things and have more control over the app development process. However, with access to so many tools, it can be overwhelming. So, this article aims to provide some baseline code and Shiny concepts to begin making a professional-looking Shiny app. It’s my hope that right off the bat, you will be able to produce a clean and high-quality app by following the steps in this article. And each step, if you’re curious, you can google more about it, and I think that’s one of the best ways to learn.
The motivation behind going straight into a more professional app as opposed to starting off with the boilerplate Shiny example is because the road to doing is often prolonged by theory and intermediate detours that may demotivate you. My philosophy is once you begin doing something, you’ll be able to 1) be proud of something advanced that you’ve done and 2) later fill in the details. I won’t go into too much detail about Shiny theory or some of the more complicated under-the-hood components of Shiny but a great resource is Hadley Wickham’s ongoing online textbook. So, for this article, bear with me, and it’ll take some effort on your part to look up any terms or concepts that I don’t explain comprehensively.
When you first install the shiny package and restart your RStudio workspace, you will see an option to initialize a shiny web app as so:
That will take you to a prompt that will give you a choice to either initialize the app in a single file (app.R) or in two files (ui.R and server.R). I will mention here that the backbone to any Shiny app is made up of two components: the UI (user interface) which defines how the app appears, and the server which defines how the app works. So for this example, we’re going to actually have three files (ui.R, server.R, and app.R, the last one is where we’ll load all our packages, source the UI and server scripts, and run the app). This three-script framework is often used for more complicated Shiny apps, and even though the sample app that I’ll take you guys through today is fairly simple, it’ll be good to start building good habits. So what you guys can do is go ahead and make three new R script files, and name them “ui.R”, “server.R”, and “app.R”.
Let’s start easy. Copy and paste the following code into your app.R file.
The main libraries that we’re going to be concerned with for the time being are shiny and shinydashboard. We’re using shinydashboardbecause it’s a neat package that provides a clean interface to present data and plots.
So, before we move on to the UI and server, let’s talk about what the app we’re building actually will be! We’ll be using the mtcars dataset and building a simple linear regression OLS model to predict mpg or miles per gallon. The app interface will allow the user to change various inputs, and the output will be a predicted mpg. Of course, the predicted mpg is, in of itself, meaningless since the model will have been overfit (we’re predicting on the same dataset for which we built the model), but that’s not our concern for this exercise.
A dashboard has three parts: a header, a sidebar, and a body. The most minimal example generates the following:
ui <- dashboardPage( dashboardHeader(), dashboardSidebar(), dashboardBody())server <- function(input, output) { }shinyApp(ui, server)
So, for this app, I’m thinking of having the inputs in the sidebar (the black part) and the output in the body (the light blue part). With more complicated apps, it’s good practice to specify separate header, sidebar, and body objects. We’ll start with the header because it’s the simplest.
header <- dashboardHeader(title = “Demo Predictor”)
Next, let’s start to populate the sidebar interface with the inputs we want the user to be able to choose from; these will be the predictor variables in the mtcars dataset. For simplicity’s sake, we’ll make the categorical variables a selectInput, which will essentially provide the user with a dropdown menu of choices, and continuous variables a numericInput, which will allow the user to type in a number. These inputs basically take three key arguments (there are more but I’ll leave you to explore that on your own): the input ID (which we will use later when connecting the server to the UI), the label (the text that gets displayed in the app), and the value(s). Note that the input ID must be a simple string that contains only letters, numbers, and underscores (no spaces, dashes, periods, or other special characters allowed!) and must be unique. For more types of inputs, check out this chapter.
This is what it currently looks like:
So, a couple of comments here. So I’m using menu items within the sidebarMenu layout to essentially store what I want in a dropdown menu that can be shown/hidden upon click. The parameters I’m using are as follows (and of course there are many more):
menuItem(text = "Predict!", tabName = "model", icon = icon("bar-chart-o"),...)
where text is what is displayed and the name of the tab that the menu item will activate. Don’t worry too much about tabName for now, it’s mainly there if we want to have more control about how we want the menu item to interact with other parts of the dashboard or if we wanted to customize it further with HTML/CSS/Javascript. Note that the order in which you list the items in the code is the order in which the items appear. The other two components are the “Predict!” and “Clear” buttons.
Currently, if you were to press them, nothing would happen as we haven’t specified a server function for the two buttons, but ultimately “Predict!” will output a predicted mpg and “Clear” resets all inputs. Note that there is some code surrounding them that doesn’t look like R code at all. That’s because that is CSS (Cascading Style Sheets), which is a language to customize how website elements look. The code I’ve written essentially puts the two buttons side by side in the same row, but again, don’t worry too much about the particulars.
Lastly, let’s fill out the body.
Here, I’m introducing a verbatimTextOutput() which will print the predicted mpg. It is usually paired with renderText() which I’ll talk about later in the server code. Another important concept in Shiny UI design is the fluidRow(). A fluid row has a width of 12, so you can organize your content in columns or boxes in widths that add up to 12. The last concept is tags, but that is a little more advanced since tags allow you greater control over the HTML/CSS/Javascript elements. Here, just know that tags$style allows me to change CSS elements to customize things like font size and family.
Now, we have all our UI components, so we bring everything together like so.
ui <- dashboardPage(header, sidebar, body, useShinyjs())
What you have to keep in mind is that for any UI decision you make that has an input ID, you should pair a server function with it (that’s a general rule of thumb). So you’ll recall that we have all our mtcar variable inputs, the “Predict!” button, and the “Clear” button. The server functions are quite straightforward. We want to use all the variable inputs in a linear regression model. And we’re going to also write some separate code to reset the values.
This is where the input ID becomes important. It has to be unique because in the server, you reference the input using input$someID. There are three functions that I’ll break down:
observeEvent()
eventReactive()
output$pred <- renderText(pred())
To understand these, however, I have to talk about reactivity. Reactivity is a core component of Shiny that admittedly can be tough to wrap your head around initially. Essentially, the gist of reactivity is that any time a user changes an input, we do not want all our code to be rerun; we want to control when we rerun certain parts of code. This is important because imagine if each time you did an action like clicking or scrolling on a website, the website had to reload every time — that would be the most frustrating website ever! For a more in-depth description of reactivity, be sure to check out Hadley Wickham’s chapter on it.
observeEvent() basically tells the app to do an action, in this case resetting values back to the default upon a certain action, which in our case is the click of the actionButton() that we called “Clear” (with the ID “reset”). I use eventReactive() to essentially specify the code I want to run when a user hits the “Predict!” button, which is some fairly straightforward dplyr and base predict functions. I could even make this more efficient by performing the wrangling outside so that it doesn’t have to rerun every time, but for now, since it’s a small dataset, the code still runs very quickly. When I save an eventReactive()statement as an R object, to call it again, I have to treat it as if it were a function (this is Shiny’s way of reactive programming). That’s why predbecomes pred(). The last thing is rendering the output which we do with renderTextand we have to assign it to the output with the correct ID, so recall in our UI script, we specified verbatimTextOutput(pred).
This is what the app looks like when we run it shinyApp(ui, server).
Shiny is a really easy and user-friendly way for existing R users to get into website and app development. A Shiny app can be a powerful tool to convey your insights and allow users to also explore concepts and insights themselves. Using something like shinydashboard is really helpful because whether we realize it or not, the way an app is designed really makes all the difference. The more seamless and intuitive our experience feels, usually the more under-the-hood stuff there is that makes it all happen. For those of you who are interested this, I encourage using this app as a springboard and trying to incorporate new functionalities. Trying to learn all of HTML, CSS, and Javascript is overwhelming and definitely not recommended, so here are some of my recommended resources for where to look next:
Advanced Shiny Tips
How to Make your Shiny Dashboard Faster
Shinyjs
Hadley Wickham’s Shiny Textbook | [
{
"code": null,
"e": 1120,
"s": 172,
"text": "This article is aimed towards people who have experience with R (ideally the tidyverse) and want to learn how to start making Shiny apps. For those who haven’t heard of Shiny before, it’s a package that allows you to create web applications using R without needing to know any HTML, CSS, or Javascript. That being said, if you do want to get deeper into app development, learning HTML, CSS, and Javascript will increase your ability to do more powerful things and have more control over the app development process. However, with access to so many tools, it can be overwhelming. So, this article aims to provide some baseline code and Shiny concepts to begin making a professional-looking Shiny app. It’s my hope that right off the bat, you will be able to produce a clean and high-quality app by following the steps in this article. And each step, if you’re curious, you can google more about it, and I think that’s one of the best ways to learn."
},
{
"code": null,
"e": 1839,
"s": 1120,
"text": "The motivation behind going straight into a more professional app as opposed to starting off with the boilerplate Shiny example is because the road to doing is often prolonged by theory and intermediate detours that may demotivate you. My philosophy is once you begin doing something, you’ll be able to 1) be proud of something advanced that you’ve done and 2) later fill in the details. I won’t go into too much detail about Shiny theory or some of the more complicated under-the-hood components of Shiny but a great resource is Hadley Wickham’s ongoing online textbook. So, for this article, bear with me, and it’ll take some effort on your part to look up any terms or concepts that I don’t explain comprehensively."
},
{
"code": null,
"e": 1976,
"s": 1839,
"text": "When you first install the shiny package and restart your RStudio workspace, you will see an option to initialize a shiny web app as so:"
},
{
"code": null,
"e": 2836,
"s": 1976,
"text": "That will take you to a prompt that will give you a choice to either initialize the app in a single file (app.R) or in two files (ui.R and server.R). I will mention here that the backbone to any Shiny app is made up of two components: the UI (user interface) which defines how the app appears, and the server which defines how the app works. So for this example, we’re going to actually have three files (ui.R, server.R, and app.R, the last one is where we’ll load all our packages, source the UI and server scripts, and run the app). This three-script framework is often used for more complicated Shiny apps, and even though the sample app that I’ll take you guys through today is fairly simple, it’ll be good to start building good habits. So what you guys can do is go ahead and make three new R script files, and name them “ui.R”, “server.R”, and “app.R”."
},
{
"code": null,
"e": 2910,
"s": 2836,
"text": "Let’s start easy. Copy and paste the following code into your app.R file."
},
{
"code": null,
"e": 3129,
"s": 2910,
"text": "The main libraries that we’re going to be concerned with for the time being are shiny and shinydashboard. We’re using shinydashboardbecause it’s a neat package that provides a clean interface to present data and plots."
},
{
"code": null,
"e": 3673,
"s": 3129,
"text": "So, before we move on to the UI and server, let’s talk about what the app we’re building actually will be! We’ll be using the mtcars dataset and building a simple linear regression OLS model to predict mpg or miles per gallon. The app interface will allow the user to change various inputs, and the output will be a predicted mpg. Of course, the predicted mpg is, in of itself, meaningless since the model will have been overfit (we’re predicting on the same dataset for which we built the model), but that’s not our concern for this exercise."
},
{
"code": null,
"e": 3785,
"s": 3673,
"text": "A dashboard has three parts: a header, a sidebar, and a body. The most minimal example generates the following:"
},
{
"code": null,
"e": 3922,
"s": 3785,
"text": "ui <- dashboardPage( dashboardHeader(), dashboardSidebar(), dashboardBody())server <- function(input, output) { }shinyApp(ui, server)"
},
{
"code": null,
"e": 4213,
"s": 3922,
"text": "So, for this app, I’m thinking of having the inputs in the sidebar (the black part) and the output in the body (the light blue part). With more complicated apps, it’s good practice to specify separate header, sidebar, and body objects. We’ll start with the header because it’s the simplest."
},
{
"code": null,
"e": 4265,
"s": 4213,
"text": "header <- dashboardHeader(title = “Demo Predictor”)"
},
{
"code": null,
"e": 5172,
"s": 4265,
"text": "Next, let’s start to populate the sidebar interface with the inputs we want the user to be able to choose from; these will be the predictor variables in the mtcars dataset. For simplicity’s sake, we’ll make the categorical variables a selectInput, which will essentially provide the user with a dropdown menu of choices, and continuous variables a numericInput, which will allow the user to type in a number. These inputs basically take three key arguments (there are more but I’ll leave you to explore that on your own): the input ID (which we will use later when connecting the server to the UI), the label (the text that gets displayed in the app), and the value(s). Note that the input ID must be a simple string that contains only letters, numbers, and underscores (no spaces, dashes, periods, or other special characters allowed!) and must be unique. For more types of inputs, check out this chapter."
},
{
"code": null,
"e": 5210,
"s": 5172,
"text": "This is what it currently looks like:"
},
{
"code": null,
"e": 5461,
"s": 5210,
"text": "So, a couple of comments here. So I’m using menu items within the sidebarMenu layout to essentially store what I want in a dropdown menu that can be shown/hidden upon click. The parameters I’m using are as follows (and of course there are many more):"
},
{
"code": null,
"e": 5540,
"s": 5461,
"text": "menuItem(text = \"Predict!\", tabName = \"model\", icon = icon(\"bar-chart-o\"),...)"
},
{
"code": null,
"e": 6033,
"s": 5540,
"text": "where text is what is displayed and the name of the tab that the menu item will activate. Don’t worry too much about tabName for now, it’s mainly there if we want to have more control about how we want the menu item to interact with other parts of the dashboard or if we wanted to customize it further with HTML/CSS/Javascript. Note that the order in which you list the items in the code is the order in which the items appear. The other two components are the “Predict!” and “Clear” buttons."
},
{
"code": null,
"e": 6577,
"s": 6033,
"text": "Currently, if you were to press them, nothing would happen as we haven’t specified a server function for the two buttons, but ultimately “Predict!” will output a predicted mpg and “Clear” resets all inputs. Note that there is some code surrounding them that doesn’t look like R code at all. That’s because that is CSS (Cascading Style Sheets), which is a language to customize how website elements look. The code I’ve written essentially puts the two buttons side by side in the same row, but again, don’t worry too much about the particulars."
},
{
"code": null,
"e": 6610,
"s": 6577,
"text": "Lastly, let’s fill out the body."
},
{
"code": null,
"e": 7204,
"s": 6610,
"text": "Here, I’m introducing a verbatimTextOutput() which will print the predicted mpg. It is usually paired with renderText() which I’ll talk about later in the server code. Another important concept in Shiny UI design is the fluidRow(). A fluid row has a width of 12, so you can organize your content in columns or boxes in widths that add up to 12. The last concept is tags, but that is a little more advanced since tags allow you greater control over the HTML/CSS/Javascript elements. Here, just know that tags$style allows me to change CSS elements to customize things like font size and family."
},
{
"code": null,
"e": 7281,
"s": 7204,
"text": "Now, we have all our UI components, so we bring everything together like so."
},
{
"code": null,
"e": 7398,
"s": 7281,
"text": "ui <- dashboardPage(header, sidebar, body, useShinyjs())"
},
{
"code": null,
"e": 7858,
"s": 7398,
"text": "What you have to keep in mind is that for any UI decision you make that has an input ID, you should pair a server function with it (that’s a general rule of thumb). So you’ll recall that we have all our mtcar variable inputs, the “Predict!” button, and the “Clear” button. The server functions are quite straightforward. We want to use all the variable inputs in a linear regression model. And we’re going to also write some separate code to reset the values."
},
{
"code": null,
"e": 8039,
"s": 7858,
"text": "This is where the input ID becomes important. It has to be unique because in the server, you reference the input using input$someID. There are three functions that I’ll break down:"
},
{
"code": null,
"e": 8054,
"s": 8039,
"text": "observeEvent()"
},
{
"code": null,
"e": 8070,
"s": 8054,
"text": "eventReactive()"
},
{
"code": null,
"e": 8104,
"s": 8070,
"text": "output$pred <- renderText(pred())"
},
{
"code": null,
"e": 8741,
"s": 8104,
"text": "To understand these, however, I have to talk about reactivity. Reactivity is a core component of Shiny that admittedly can be tough to wrap your head around initially. Essentially, the gist of reactivity is that any time a user changes an input, we do not want all our code to be rerun; we want to control when we rerun certain parts of code. This is important because imagine if each time you did an action like clicking or scrolling on a website, the website had to reload every time — that would be the most frustrating website ever! For a more in-depth description of reactivity, be sure to check out Hadley Wickham’s chapter on it."
},
{
"code": null,
"e": 9731,
"s": 8741,
"text": "observeEvent() basically tells the app to do an action, in this case resetting values back to the default upon a certain action, which in our case is the click of the actionButton() that we called “Clear” (with the ID “reset”). I use eventReactive() to essentially specify the code I want to run when a user hits the “Predict!” button, which is some fairly straightforward dplyr and base predict functions. I could even make this more efficient by performing the wrangling outside so that it doesn’t have to rerun every time, but for now, since it’s a small dataset, the code still runs very quickly. When I save an eventReactive()statement as an R object, to call it again, I have to treat it as if it were a function (this is Shiny’s way of reactive programming). That’s why predbecomes pred(). The last thing is rendering the output which we do with renderTextand we have to assign it to the output with the correct ID, so recall in our UI script, we specified verbatimTextOutput(pred)."
},
{
"code": null,
"e": 9800,
"s": 9731,
"text": "This is what the app looks like when we run it shinyApp(ui, server)."
},
{
"code": null,
"e": 10610,
"s": 9800,
"text": "Shiny is a really easy and user-friendly way for existing R users to get into website and app development. A Shiny app can be a powerful tool to convey your insights and allow users to also explore concepts and insights themselves. Using something like shinydashboard is really helpful because whether we realize it or not, the way an app is designed really makes all the difference. The more seamless and intuitive our experience feels, usually the more under-the-hood stuff there is that makes it all happen. For those of you who are interested this, I encourage using this app as a springboard and trying to incorporate new functionalities. Trying to learn all of HTML, CSS, and Javascript is overwhelming and definitely not recommended, so here are some of my recommended resources for where to look next:"
},
{
"code": null,
"e": 10630,
"s": 10610,
"text": "Advanced Shiny Tips"
},
{
"code": null,
"e": 10670,
"s": 10630,
"text": "How to Make your Shiny Dashboard Faster"
},
{
"code": null,
"e": 10678,
"s": 10670,
"text": "Shinyjs"
}
] |
Output of C programs | Set 50 (Control Structures) - GeeksforGeeks | 12 Jul, 2019
Here are some C programs which is related to the control structures With the detailed explanation, guess the output of the following programs:-
1.what will be the output of the below program?
#include <stdio.h>int main(){ int x = 2; switch (x) { x--; switch (x) { case 1: printf("Hello"); break; case 2: printf("GFG"); break; case 3: printf("Welcome"); break; default: printf("BYE"); } } return (0);}
Options:1. Hello2. GFG3. No Output4. BYE
The answer is option(3).
Explanation:The switch case control structure execute the statement present in the case. But in the above program, the outer switch does not has cases. Therefore, control does not enter inside the switch case. Thus, the program does not give any output and compiler does not produce any error.
2.Guess the correct answer of the mentioned program?
#include <stdio.h>int main(){ int x = 2; switch (x) { case 1: printf("Hello"); break; case 2: printf("Hello"); break; case 3: printf("GFG"); break; default: printf("BYE"); } return (0);}
Options:1. Abnormal termination2. Compile time error3. No output4. Hello
The output is option(4).
Explanation: In the above program, value of x is 2 so case 2 will execute and it will print Hello.Resource: https://www.geeksforgeeks.org/switch-statement-cc/
3.How many times does the loop run?
#include <stdio.h>int main(){ int i; for (i = 1; i <= 100; i++) { printf("GFG\n"); if (i == 5) break; } return (0);}
Options:1. 5 times2. 15 times3. 10 times4. 20 times
The answer is option(1).
Explanation: Here the loop print GFG five times. Because when the for loop counter value i.e. i is 5, the break statement will transfer the control to outside loop.Resource:www.geeksforgeeks.org/break-statement-cc/
4.what will be the output?
#include <stdio.h>int main(){ int i; for (i = 1; i <= 10; i++) { printf("welcome\n"); continue; printf("hii"); } return (0);}
Options:1. print welcome 5 times2. print hii 5 times3. print hii 10 times4. print welcome 10 times
The answer is option(4).
Explanation : When the control of the for loop reaches continue statement, the control automatically transfers to the beginning of the loop and leave the printf(“hii”); statement.Resource: https://www.geeksforgeeks.org/continue-statement-cpp/
5.How many time the program will print?
#include <stdio.h>>int main(){ int i; for (i = 2; i = 100; i += 2) { printf("Hi\\n"); } return (0);}
Options:1. print 2 times2. Infinitely3. print 10 times4. print 5 times
The answer is option(2).
Explanation: Because the value 100 is assigned to i every time and it does not check for any condition because here there is no = sign in the for loop. Therefore the loop goes into infinite loop.
This article is contributed by Bishal Kumar Dubey. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
shi143din
ManasChhabra2
C-Output
Program Output
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Output of Java program | Set 18 (Overriding)
Output of Java Program | Set 11
Output of Java programs | Set 13 (Collections)
Output of C++ programs | Set 34 (File Handling)
Different ways to copy a string in C/C++
Output of Java Program | Set 3
Runtime Errors
Output of Java program | Set 28
Output of Java program | Set 5
Output of Java Programs | Set 12 | [
{
"code": null,
"e": 25809,
"s": 25781,
"text": "\n12 Jul, 2019"
},
{
"code": null,
"e": 25953,
"s": 25809,
"text": "Here are some C programs which is related to the control structures With the detailed explanation, guess the output of the following programs:-"
},
{
"code": null,
"e": 26001,
"s": 25953,
"text": "1.what will be the output of the below program?"
},
{
"code": "#include <stdio.h>int main(){ int x = 2; switch (x) { x--; switch (x) { case 1: printf(\"Hello\"); break; case 2: printf(\"GFG\"); break; case 3: printf(\"Welcome\"); break; default: printf(\"BYE\"); } } return (0);}",
"e": 26348,
"s": 26001,
"text": null
},
{
"code": null,
"e": 26389,
"s": 26348,
"text": "Options:1. Hello2. GFG3. No Output4. BYE"
},
{
"code": null,
"e": 26414,
"s": 26389,
"text": "The answer is option(3)."
},
{
"code": null,
"e": 26708,
"s": 26414,
"text": "Explanation:The switch case control structure execute the statement present in the case. But in the above program, the outer switch does not has cases. Therefore, control does not enter inside the switch case. Thus, the program does not give any output and compiler does not produce any error."
},
{
"code": null,
"e": 26761,
"s": 26708,
"text": "2.Guess the correct answer of the mentioned program?"
},
{
"code": "#include <stdio.h>int main(){ int x = 2; switch (x) { case 1: printf(\"Hello\"); break; case 2: printf(\"Hello\"); break; case 3: printf(\"GFG\"); break; default: printf(\"BYE\"); } return (0);}",
"e": 27021,
"s": 26761,
"text": null
},
{
"code": null,
"e": 27094,
"s": 27021,
"text": "Options:1. Abnormal termination2. Compile time error3. No output4. Hello"
},
{
"code": null,
"e": 27119,
"s": 27094,
"text": "The output is option(4)."
},
{
"code": null,
"e": 27278,
"s": 27119,
"text": "Explanation: In the above program, value of x is 2 so case 2 will execute and it will print Hello.Resource: https://www.geeksforgeeks.org/switch-statement-cc/"
},
{
"code": null,
"e": 27314,
"s": 27278,
"text": "3.How many times does the loop run?"
},
{
"code": "#include <stdio.h>int main(){ int i; for (i = 1; i <= 100; i++) { printf(\"GFG\\n\"); if (i == 5) break; } return (0);}",
"e": 27468,
"s": 27314,
"text": null
},
{
"code": null,
"e": 27520,
"s": 27468,
"text": "Options:1. 5 times2. 15 times3. 10 times4. 20 times"
},
{
"code": null,
"e": 27545,
"s": 27520,
"text": "The answer is option(1)."
},
{
"code": null,
"e": 27760,
"s": 27545,
"text": "Explanation: Here the loop print GFG five times. Because when the for loop counter value i.e. i is 5, the break statement will transfer the control to outside loop.Resource:www.geeksforgeeks.org/break-statement-cc/"
},
{
"code": null,
"e": 27787,
"s": 27760,
"text": "4.what will be the output?"
},
{
"code": "#include <stdio.h>int main(){ int i; for (i = 1; i <= 10; i++) { printf(\"welcome\\n\"); continue; printf(\"hii\"); } return (0);}",
"e": 27946,
"s": 27787,
"text": null
},
{
"code": null,
"e": 28045,
"s": 27946,
"text": "Options:1. print welcome 5 times2. print hii 5 times3. print hii 10 times4. print welcome 10 times"
},
{
"code": null,
"e": 28070,
"s": 28045,
"text": "The answer is option(4)."
},
{
"code": null,
"e": 28313,
"s": 28070,
"text": "Explanation : When the control of the for loop reaches continue statement, the control automatically transfers to the beginning of the loop and leave the printf(“hii”); statement.Resource: https://www.geeksforgeeks.org/continue-statement-cpp/"
},
{
"code": null,
"e": 28353,
"s": 28313,
"text": "5.How many time the program will print?"
},
{
"code": "#include <stdio.h>>int main(){ int i; for (i = 2; i = 100; i += 2) { printf(\"Hi\\\\n\"); } return (0);}",
"e": 28473,
"s": 28353,
"text": null
},
{
"code": null,
"e": 28544,
"s": 28473,
"text": "Options:1. print 2 times2. Infinitely3. print 10 times4. print 5 times"
},
{
"code": null,
"e": 28569,
"s": 28544,
"text": "The answer is option(2)."
},
{
"code": null,
"e": 28765,
"s": 28569,
"text": "Explanation: Because the value 100 is assigned to i every time and it does not check for any condition because here there is no = sign in the for loop. Therefore the loop goes into infinite loop."
},
{
"code": null,
"e": 29071,
"s": 28765,
"text": "This article is contributed by Bishal Kumar Dubey. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 29196,
"s": 29071,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 29206,
"s": 29196,
"text": "shi143din"
},
{
"code": null,
"e": 29220,
"s": 29206,
"text": "ManasChhabra2"
},
{
"code": null,
"e": 29229,
"s": 29220,
"text": "C-Output"
},
{
"code": null,
"e": 29244,
"s": 29229,
"text": "Program Output"
},
{
"code": null,
"e": 29342,
"s": 29244,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29387,
"s": 29342,
"text": "Output of Java program | Set 18 (Overriding)"
},
{
"code": null,
"e": 29419,
"s": 29387,
"text": "Output of Java Program | Set 11"
},
{
"code": null,
"e": 29466,
"s": 29419,
"text": "Output of Java programs | Set 13 (Collections)"
},
{
"code": null,
"e": 29514,
"s": 29466,
"text": "Output of C++ programs | Set 34 (File Handling)"
},
{
"code": null,
"e": 29555,
"s": 29514,
"text": "Different ways to copy a string in C/C++"
},
{
"code": null,
"e": 29586,
"s": 29555,
"text": "Output of Java Program | Set 3"
},
{
"code": null,
"e": 29601,
"s": 29586,
"text": "Runtime Errors"
},
{
"code": null,
"e": 29633,
"s": 29601,
"text": "Output of Java program | Set 28"
},
{
"code": null,
"e": 29664,
"s": 29633,
"text": "Output of Java program | Set 5"
}
] |
Sorting contents of a Data Frame in Julia - GeeksforGeeks | 25 Mar, 2021
Sorting is a technique of storing data in sorted order. Sorting can be performed using sorting algorithms or sorting functions. to sort in a particular dataframe then extracting its values and applying the sorting function would easily sort the contents of a particular dataframe. Julia provides various methods that can be used to perform the sorting of DataFrames.
Remember to add the following package before starting i.e DataFrames with help of below code:
using Pkg
Pkg.add("DataFrames")
Julia provides some methods for sorting data of a DataFrame:
sort() function: This function returns a sorted array or sorted copy of an array
sort() function passing an algorithm: This function returns a sorted array with the help of an applied algorithm
sortperm() function: This function returns a list of indices that one can use on the collection to produce a sorted collection.
partialsortperm() function: This function partially sorts the algorithm up to a particular rang or permutation.
sort() function with rev=True: This function will sort the content of the dataframe into descending order.
sort!(): This function passing the dimension, this function can sort multidimensional arrays of DataFrames.
partialsortperm(): This function returns a partial permutation DataFrame’s column of the vector
sort() Function in Julia is the most basic sorting method that can be used to sort data of a dataframe.
Approach:
First, you can create the dataframe
The sort() function has arguments like the vector and the order in which the columns need to be sorted.
Julia
# Creating a dataframedf1 = DataFrame(b = [:Hi, :Med, :Hi, :Low, :Hi], x = ["A", "E", "I", "O","A"], y = [6, 3, 7, 2, 1], z = [2, 1, 1, 2, 2]) # Method1sort(df1,[:z,:y]) # sorted z then y
Julia allows passing the algorithm type to sort() function to sort the column. sort(dataframe.columnheader; alg=QuickSort) function takes column name and algorithm type as an argument.
Approach:
Here, the sort() function is applied to a specific column.
It is passed as an argument in the sort function
Then the algorithm with which you want to sort the particular column is also passed as an argument
Store the returned value of this function in a separate variable
Then update in the particular column
Julia
# Method2 Algorithm(Quicksort)# Sorting a particular column and storing it in ss = sort(df1.y; alg = QuickSort) # Now giving the value of s to the dataframe's y headerdf1.y = sdf1 # printing the sorted y
sort(dataframe.columnheader; alg=PartialQuickSort(range)) function is passed with PartialQuickSort algorithm to sort the column upto a certain limit which is passed in the algorithm.
Approach:
Here, the sort() function is applied to a specific column.
It is passed as an argument in the sort function
Then the algorithm(PartialQuickSort) with which you want to sort the particular column is also passed as an argument
Store the returned value of this function in a separate variable
Then update in the particular column
Julia
# Method3 Algorithm(PartialQuickSort)# If we want sort a column upto a certain numberB = 3t = sort(df1.z; alg = PartialQuickSort(B)) # passing the t variable in the dataframedf1.z = tdf1
sortperm() function is passed with the column name, to sort the column and return indexes of the sorted column.
Approach:
First store the particular column in which you want to apply this sorting in a separate variable
Apply the sortperm() function and pass the variable as argument this will return the sorted indexes of the particular column and store the returned indexes in a separate variable
Then traverse using the for loop in the variable where the indexes are stored
Print using the for loop and pass the index in the variable where the particular column was stored.
Julia
# Method4r = df1.y # returned indexes of the elementsk = sortperm(r) # traversing through indicesfor i in k println(r[i]) end
sort(dataframe.column;alg=InsertionSort) function is passed with InsertionSort algorithm to sort the column up to certain limit which is passed in the algorithm.
Approach:
Creating a new dataframe and applying the sort() function
This time the algorithm used is insertion sort
Then the algorithm(InsertionSort) with which you want to sort the particular column is also passed as an argument
Store the returned value of this function in a separate variable
Then update in the particular column
Julia
# Created new dataframe as df2df2 = DataFrame(x = [11,12, 13, 10, 23], y = [6, 3, 7, 2, 1], z = [2, 1, 1, 2, 2])# Method5s2 = sort(df2.x; alg = InsertionSort) # now update the df2.xdf2.x = s2df2
Method 6: Use of partialsortperm() function
partialsortperm(dataframe.column, range) function is an advanced form of sortperm() function which will return the indexes of the values which are in range. This partially sorts the column.
Approach:
Storing the particular column which needs to be sorted in another variable
Applying the partialsortperm() function passing the vector and the range till which it needs to be sorted
Finally, we can update with the help of passing the result into the particular DataFrame’s column
Now printing the dataframe would simply print with updated value
Julia
# Method6a = df2.ya = a[partialsortperm(a, 1:5)]a
sort(dataframe,rev=True) function is passed with dataframe and rev variable to sort the column. This function basically reverses or gives a descending order of the column passed.
Approach:
Sorting the dataframe’s particular column in the descending order using the sort() function
First storing the particular column in the variable
And applying the sort() function and passing the reverse of the particular column as rev = true
This now will sort in the descending order
At last, updating the dataframe by passing the variable into the dataframe
Julia
# Method7s2 = sort(df2, rev=true)df2 = s2 #updating the whole dataframedf2
sort!(vector,dim) function is passed with dataframe and dimension in which we want to sort the column (dimension means dim=1 means row and dim=2 means column).
Approach:
The function for now applying the sort with user’s choice to either sort by row or column
Sorting by row is done by passing vector into the sort!() function
Also, we need to pass the dim=1 which means to traverse row-wise
This function will print the sorting in the row manner
Now applying the same function by just passing dim=2 to sort in column manner.
This now would print the sorted vector in the column manner.
Julia
# Method8B = [4 3; 1 2]sort!(B, dims = 1); B # sorting through rowsort!(B, dims = 2); B # sorting through column
arorakashish0911
julia-DataFrames
Julia
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder)
Get array dimensions and size of a dimension in Julia - size() Method
Exception handling in Julia
Searching in Array for a given element in Julia
Find maximum element along with its index in Julia - findmax() Method
Get number of elements of array in Julia - length() Method
Join an array of strings into a single string in Julia - join() Method
Working with Excel Files in Julia
File Handling in Julia
Getting last element of an array in Julia - last() Method | [
{
"code": null,
"e": 25789,
"s": 25761,
"text": "\n25 Mar, 2021"
},
{
"code": null,
"e": 26157,
"s": 25789,
"text": "Sorting is a technique of storing data in sorted order. Sorting can be performed using sorting algorithms or sorting functions. to sort in a particular dataframe then extracting its values and applying the sorting function would easily sort the contents of a particular dataframe. Julia provides various methods that can be used to perform the sorting of DataFrames. "
},
{
"code": null,
"e": 26251,
"s": 26157,
"text": "Remember to add the following package before starting i.e DataFrames with help of below code:"
},
{
"code": null,
"e": 26283,
"s": 26251,
"text": "using Pkg\nPkg.add(\"DataFrames\")"
},
{
"code": null,
"e": 26344,
"s": 26283,
"text": "Julia provides some methods for sorting data of a DataFrame:"
},
{
"code": null,
"e": 26425,
"s": 26344,
"text": "sort() function: This function returns a sorted array or sorted copy of an array"
},
{
"code": null,
"e": 26538,
"s": 26425,
"text": "sort() function passing an algorithm: This function returns a sorted array with the help of an applied algorithm"
},
{
"code": null,
"e": 26666,
"s": 26538,
"text": "sortperm() function: This function returns a list of indices that one can use on the collection to produce a sorted collection."
},
{
"code": null,
"e": 26778,
"s": 26666,
"text": "partialsortperm() function: This function partially sorts the algorithm up to a particular rang or permutation."
},
{
"code": null,
"e": 26885,
"s": 26778,
"text": "sort() function with rev=True: This function will sort the content of the dataframe into descending order."
},
{
"code": null,
"e": 26993,
"s": 26885,
"text": "sort!(): This function passing the dimension, this function can sort multidimensional arrays of DataFrames."
},
{
"code": null,
"e": 27089,
"s": 26993,
"text": "partialsortperm(): This function returns a partial permutation DataFrame’s column of the vector"
},
{
"code": null,
"e": 27194,
"s": 27089,
"text": "sort() Function in Julia is the most basic sorting method that can be used to sort data of a dataframe. "
},
{
"code": null,
"e": 27204,
"s": 27194,
"text": "Approach:"
},
{
"code": null,
"e": 27240,
"s": 27204,
"text": "First, you can create the dataframe"
},
{
"code": null,
"e": 27344,
"s": 27240,
"text": "The sort() function has arguments like the vector and the order in which the columns need to be sorted."
},
{
"code": null,
"e": 27350,
"s": 27344,
"text": "Julia"
},
{
"code": "# Creating a dataframedf1 = DataFrame(b = [:Hi, :Med, :Hi, :Low, :Hi], x = [\"A\", \"E\", \"I\", \"O\",\"A\"], y = [6, 3, 7, 2, 1], z = [2, 1, 1, 2, 2]) # Method1sort(df1,[:z,:y]) # sorted z then y",
"e": 27580,
"s": 27350,
"text": null
},
{
"code": null,
"e": 27770,
"s": 27585,
"text": "Julia allows passing the algorithm type to sort() function to sort the column. sort(dataframe.columnheader; alg=QuickSort) function takes column name and algorithm type as an argument."
},
{
"code": null,
"e": 27782,
"s": 27772,
"text": "Approach:"
},
{
"code": null,
"e": 27843,
"s": 27784,
"text": "Here, the sort() function is applied to a specific column."
},
{
"code": null,
"e": 27892,
"s": 27843,
"text": "It is passed as an argument in the sort function"
},
{
"code": null,
"e": 27991,
"s": 27892,
"text": "Then the algorithm with which you want to sort the particular column is also passed as an argument"
},
{
"code": null,
"e": 28056,
"s": 27991,
"text": "Store the returned value of this function in a separate variable"
},
{
"code": null,
"e": 28093,
"s": 28056,
"text": "Then update in the particular column"
},
{
"code": null,
"e": 28101,
"s": 28095,
"text": "Julia"
},
{
"code": "# Method2 Algorithm(Quicksort)# Sorting a particular column and storing it in ss = sort(df1.y; alg = QuickSort) # Now giving the value of s to the dataframe's y headerdf1.y = sdf1 # printing the sorted y",
"e": 28305,
"s": 28101,
"text": null
},
{
"code": null,
"e": 28493,
"s": 28310,
"text": "sort(dataframe.columnheader; alg=PartialQuickSort(range)) function is passed with PartialQuickSort algorithm to sort the column upto a certain limit which is passed in the algorithm."
},
{
"code": null,
"e": 28505,
"s": 28495,
"text": "Approach:"
},
{
"code": null,
"e": 28566,
"s": 28507,
"text": "Here, the sort() function is applied to a specific column."
},
{
"code": null,
"e": 28615,
"s": 28566,
"text": "It is passed as an argument in the sort function"
},
{
"code": null,
"e": 28733,
"s": 28615,
"text": "Then the algorithm(PartialQuickSort) with which you want to sort the particular column is also passed as an argument"
},
{
"code": null,
"e": 28798,
"s": 28733,
"text": "Store the returned value of this function in a separate variable"
},
{
"code": null,
"e": 28835,
"s": 28798,
"text": "Then update in the particular column"
},
{
"code": null,
"e": 28843,
"s": 28837,
"text": "Julia"
},
{
"code": "# Method3 Algorithm(PartialQuickSort)# If we want sort a column upto a certain numberB = 3t = sort(df1.z; alg = PartialQuickSort(B)) # passing the t variable in the dataframedf1.z = tdf1",
"e": 29030,
"s": 28843,
"text": null
},
{
"code": null,
"e": 29147,
"s": 29035,
"text": "sortperm() function is passed with the column name, to sort the column and return indexes of the sorted column."
},
{
"code": null,
"e": 29159,
"s": 29149,
"text": "Approach:"
},
{
"code": null,
"e": 29258,
"s": 29161,
"text": "First store the particular column in which you want to apply this sorting in a separate variable"
},
{
"code": null,
"e": 29437,
"s": 29258,
"text": "Apply the sortperm() function and pass the variable as argument this will return the sorted indexes of the particular column and store the returned indexes in a separate variable"
},
{
"code": null,
"e": 29515,
"s": 29437,
"text": "Then traverse using the for loop in the variable where the indexes are stored"
},
{
"code": null,
"e": 29615,
"s": 29515,
"text": "Print using the for loop and pass the index in the variable where the particular column was stored."
},
{
"code": null,
"e": 29623,
"s": 29617,
"text": "Julia"
},
{
"code": "# Method4r = df1.y # returned indexes of the elementsk = sortperm(r) # traversing through indicesfor i in k println(r[i]) end",
"e": 29752,
"s": 29623,
"text": null
},
{
"code": null,
"e": 29914,
"s": 29752,
"text": "sort(dataframe.column;alg=InsertionSort) function is passed with InsertionSort algorithm to sort the column up to certain limit which is passed in the algorithm."
},
{
"code": null,
"e": 29924,
"s": 29914,
"text": "Approach:"
},
{
"code": null,
"e": 29983,
"s": 29924,
"text": "Creating a new dataframe and applying the sort() function"
},
{
"code": null,
"e": 30030,
"s": 29983,
"text": "This time the algorithm used is insertion sort"
},
{
"code": null,
"e": 30145,
"s": 30030,
"text": "Then the algorithm(InsertionSort) with which you want to sort the particular column is also passed as an argument"
},
{
"code": null,
"e": 30210,
"s": 30145,
"text": "Store the returned value of this function in a separate variable"
},
{
"code": null,
"e": 30247,
"s": 30210,
"text": "Then update in the particular column"
},
{
"code": null,
"e": 30253,
"s": 30247,
"text": "Julia"
},
{
"code": "# Created new dataframe as df2df2 = DataFrame(x = [11,12, 13, 10, 23], y = [6, 3, 7, 2, 1], z = [2, 1, 1, 2, 2])# Method5s2 = sort(df2.x; alg = InsertionSort) # now update the df2.xdf2.x = s2df2",
"e": 30478,
"s": 30253,
"text": null
},
{
"code": null,
"e": 30527,
"s": 30483,
"text": "Method 6: Use of partialsortperm() function"
},
{
"code": null,
"e": 30719,
"s": 30529,
"text": "partialsortperm(dataframe.column, range) function is an advanced form of sortperm() function which will return the indexes of the values which are in range. This partially sorts the column."
},
{
"code": null,
"e": 30731,
"s": 30721,
"text": "Approach:"
},
{
"code": null,
"e": 30808,
"s": 30733,
"text": "Storing the particular column which needs to be sorted in another variable"
},
{
"code": null,
"e": 30914,
"s": 30808,
"text": "Applying the partialsortperm() function passing the vector and the range till which it needs to be sorted"
},
{
"code": null,
"e": 31012,
"s": 30914,
"text": "Finally, we can update with the help of passing the result into the particular DataFrame’s column"
},
{
"code": null,
"e": 31077,
"s": 31012,
"text": "Now printing the dataframe would simply print with updated value"
},
{
"code": null,
"e": 31085,
"s": 31079,
"text": "Julia"
},
{
"code": "# Method6a = df2.ya = a[partialsortperm(a, 1:5)]a",
"e": 31135,
"s": 31085,
"text": null
},
{
"code": null,
"e": 31314,
"s": 31135,
"text": "sort(dataframe,rev=True) function is passed with dataframe and rev variable to sort the column. This function basically reverses or gives a descending order of the column passed."
},
{
"code": null,
"e": 31324,
"s": 31314,
"text": "Approach:"
},
{
"code": null,
"e": 31416,
"s": 31324,
"text": "Sorting the dataframe’s particular column in the descending order using the sort() function"
},
{
"code": null,
"e": 31468,
"s": 31416,
"text": "First storing the particular column in the variable"
},
{
"code": null,
"e": 31564,
"s": 31468,
"text": "And applying the sort() function and passing the reverse of the particular column as rev = true"
},
{
"code": null,
"e": 31607,
"s": 31564,
"text": "This now will sort in the descending order"
},
{
"code": null,
"e": 31682,
"s": 31607,
"text": "At last, updating the dataframe by passing the variable into the dataframe"
},
{
"code": null,
"e": 31688,
"s": 31682,
"text": "Julia"
},
{
"code": "# Method7s2 = sort(df2, rev=true)df2 = s2 #updating the whole dataframedf2",
"e": 31763,
"s": 31688,
"text": null
},
{
"code": null,
"e": 31939,
"s": 31779,
"text": "sort!(vector,dim) function is passed with dataframe and dimension in which we want to sort the column (dimension means dim=1 means row and dim=2 means column)."
},
{
"code": null,
"e": 31951,
"s": 31941,
"text": "Approach:"
},
{
"code": null,
"e": 32043,
"s": 31953,
"text": "The function for now applying the sort with user’s choice to either sort by row or column"
},
{
"code": null,
"e": 32111,
"s": 32043,
"text": "Sorting by row is done by passing vector into the sort!() function"
},
{
"code": null,
"e": 32176,
"s": 32111,
"text": "Also, we need to pass the dim=1 which means to traverse row-wise"
},
{
"code": null,
"e": 32231,
"s": 32176,
"text": "This function will print the sorting in the row manner"
},
{
"code": null,
"e": 32311,
"s": 32231,
"text": "Now applying the same function by just passing dim=2 to sort in column manner."
},
{
"code": null,
"e": 32372,
"s": 32311,
"text": "This now would print the sorted vector in the column manner."
},
{
"code": null,
"e": 32380,
"s": 32374,
"text": "Julia"
},
{
"code": "# Method8B = [4 3; 1 2]sort!(B, dims = 1); B # sorting through rowsort!(B, dims = 2); B # sorting through column",
"e": 32493,
"s": 32380,
"text": null
},
{
"code": null,
"e": 32515,
"s": 32498,
"text": "arorakashish0911"
},
{
"code": null,
"e": 32532,
"s": 32515,
"text": "julia-DataFrames"
},
{
"code": null,
"e": 32538,
"s": 32532,
"text": "Julia"
},
{
"code": null,
"e": 32636,
"s": 32538,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32709,
"s": 32636,
"text": "Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder)"
},
{
"code": null,
"e": 32779,
"s": 32709,
"text": "Get array dimensions and size of a dimension in Julia - size() Method"
},
{
"code": null,
"e": 32807,
"s": 32779,
"text": "Exception handling in Julia"
},
{
"code": null,
"e": 32855,
"s": 32807,
"text": "Searching in Array for a given element in Julia"
},
{
"code": null,
"e": 32925,
"s": 32855,
"text": "Find maximum element along with its index in Julia - findmax() Method"
},
{
"code": null,
"e": 32984,
"s": 32925,
"text": "Get number of elements of array in Julia - length() Method"
},
{
"code": null,
"e": 33055,
"s": 32984,
"text": "Join an array of strings into a single string in Julia - join() Method"
},
{
"code": null,
"e": 33089,
"s": 33055,
"text": "Working with Excel Files in Julia"
},
{
"code": null,
"e": 33112,
"s": 33089,
"text": "File Handling in Julia"
}
] |
Shell Scripting - Select Loop - GeeksforGeeks | 04 Jan, 2022
The select loop is one of the categories of loops in bash programming. A select-loop in the shell can be stopped in two cases only if there is a break statement or a keyboard interrupt. The main objective of using a select loop is that it represents different data elements in the form of a numbered list to the user. The user can easily select one of the options as listed by the program.
The syntax of a general select loop is given below,
Syntax:
select myVariable in variable1 variable2 ... variableN
do
# body to be executed for
# every value in the sequence.
done
Here, myVariable is a variable that is used to refer to each of the values from variable1 to variableN.
Example 1:
In the below program we are creating a numbered menu to allow a user (or Btech student) to select the department.
Source Code:
# Program to demonstrate the working of a
# select-loop in shell scripting
# PS3="Enter your choice ==> "
# echo "What is your department?"
select department in CS IT ECE EE
do
case $department in
CS)
echo "I am from CS department."
;;
IT)
echo "I am from IT department."
;;
ECE)
echo "I am from ECE department."
;;
EE)
echo "I am from EE department."
;;
none)
break
;;
*) echo "Invalid selection"
;;
esac
done
Output:
Example 2:
In the below program we are creating a numbered menu to allow a user to select a number. Once a number is selected by the user we are displaying whether the number is even or odd.
Source Code:
# Program to demonstrate the working of
# a select-loop in shell scripting
# PS3="Enter your choice ==> "
# echo "Choose a number:"
select num in 1 2 3 4 5 6 7
do
case $num in
2|4|6|8)
echo "Even number."
;;
1|3|5|7)
echo "Odd number."
;;
none)
break
;;
*) echo "ERROR: Invalid selection"
;;
esac
done
Output:
We can prompt users before asking for any selection from the menu with the help of the PS3 variable in bash programming. This variable must be declared before the select loop. The value or string with which a PS3 variable is initialized is used to prompt the user on the console.
Example 1:
In the below program we have prompted the user as “Enter your choice ==>”.
Source Code:
# Program to demonstrate the working of a
# select-loop in shell scripting
PS3="Enter your choice ==> "
echo "What is your department?"
select department in CS IT ECE EE
do
case $department in
CS)
echo "I am from CS department."
;;
IT)
echo "I am from IT department."
;;
ECE)
echo "I am from ECE department."
;;
EE)
echo "I am from EE department."
;;
none)
break
;;
*) echo "Invalid selection"
;;
esac
done
Output:
Example 2:
In this program, we have prompted the user as “Enter your choice ==>”.
Source Code:
# Program to demonstrate the working of a
# select-loop in shell scripting
PS3="Enter your choice ==> "
echo "Choose a number:"
select num in 1 2 3 4 5 6 7
do
case $num in
2|4|6|8)
echo "Even number."
;;
1|3|5|7)
echo "Odd number."
;;
none)
break
;;
*) echo "ERROR: Invalid selection"
;;
esac
done
Output:
When the end of file (EOF) of input is reached then the select loop gets completed in bash. But in the case of a command piped out to our script the output of the previous command becomes the input for the current command.
Let us understand what does a pipe command means in bash. The pipe is considered one of the most powerful operators in the shell. It is denoted by the symbol (|). The pipe takes the output from one command and uses it as input for another. And, we’re not limited to a single piped command but we can stack them as many times as you like, or until you run out of output or file descriptors. But in the case of select-loop using a pipe out command may lead to no output as demonstrated in the below program.
Example:
Source Code:
# Program to demonstrate the working of a
# select-loop in shell scripting
# script: select-loop-bash.sh
select department in CS IT ECE EE
do
case $department in
CS)
echo "I am from CS department."
;;
IT)
echo "I am from IT department."
;;
ECE)
echo "I am from ECE department."
;;
EE)
echo "I am from EE department."
;;
none)
break
;;
*) echo "Invalid selection"
;;
esac
done
Interactive commands (one after the another) and the output:
Piped:
This issue can be fixed by ensuring that the select menu will be read from the “/dev/tty” and that we are passing the option with proper word delimiter by using either the “echo” or the “printf” commands.
Example:
Source Code:
# Program to demonstrate the working of a
# select-loop in shell scripting
# script: select-loop-bash.sh
select department in CS IT ECE EE
do
case $department in
CS)
echo "I am from CS department."
;;
IT)
echo "I am from IT department."
;;
ECE)
echo "I am from ECE department."
;;
EE)
echo "I am from EE department."
;;
none)
break
;;
*) echo "Invalid selection"
;;
esac
done < /dev/tty
Interactive commands (one after the another) and the output:
Picked
Shell Script
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
scp command in Linux with Examples
mv command in Linux with examples
Docker - COPY Instruction
SED command in Linux | Set 2
chown command in Linux with Examples
nohup Command in Linux with Examples
Named Pipe or FIFO with example C program
Thread functions in C/C++
uniq Command in LINUX with examples
Start/Stop/Restart Services Using Systemctl in Linux | [
{
"code": null,
"e": 25651,
"s": 25623,
"text": "\n04 Jan, 2022"
},
{
"code": null,
"e": 26041,
"s": 25651,
"text": "The select loop is one of the categories of loops in bash programming. A select-loop in the shell can be stopped in two cases only if there is a break statement or a keyboard interrupt. The main objective of using a select loop is that it represents different data elements in the form of a numbered list to the user. The user can easily select one of the options as listed by the program."
},
{
"code": null,
"e": 26094,
"s": 26041,
"text": " The syntax of a general select loop is given below,"
},
{
"code": null,
"e": 26102,
"s": 26094,
"text": "Syntax:"
},
{
"code": null,
"e": 26231,
"s": 26102,
"text": "select myVariable in variable1 variable2 ... variableN\ndo\n # body to be executed for \n # every value in the sequence.\ndone"
},
{
"code": null,
"e": 26335,
"s": 26231,
"text": "Here, myVariable is a variable that is used to refer to each of the values from variable1 to variableN."
},
{
"code": null,
"e": 26346,
"s": 26335,
"text": "Example 1:"
},
{
"code": null,
"e": 26461,
"s": 26346,
"text": "In the below program we are creating a numbered menu to allow a user (or Btech student) to select the department. "
},
{
"code": null,
"e": 26474,
"s": 26461,
"text": "Source Code:"
},
{
"code": null,
"e": 26995,
"s": 26474,
"text": "# Program to demonstrate the working of a \n# select-loop in shell scripting\n\n# PS3=\"Enter your choice ==> \"\n# echo \"What is your department?\"\n \nselect department in CS IT ECE EE\ndo\n case $department in\n\n CS)\n echo \"I am from CS department.\"\n ;;\n\n IT)\n echo \"I am from IT department.\"\n ;;\n\n ECE)\n echo \"I am from ECE department.\"\n ;;\n\n EE)\n echo \"I am from EE department.\"\n ;;\n\n none)\n break\n ;;\n\n *) echo \"Invalid selection\"\n ;;\n esac\ndone"
},
{
"code": null,
"e": 27003,
"s": 26995,
"text": "Output:"
},
{
"code": null,
"e": 27014,
"s": 27003,
"text": "Example 2:"
},
{
"code": null,
"e": 27196,
"s": 27014,
"text": "In the below program we are creating a numbered menu to allow a user to select a number. Once a number is selected by the user we are displaying whether the number is even or odd. "
},
{
"code": null,
"e": 27209,
"s": 27196,
"text": "Source Code:"
},
{
"code": null,
"e": 27603,
"s": 27209,
"text": "# Program to demonstrate the working of\n# a select-loop in shell scripting\n\n# PS3=\"Enter your choice ==> \"\n# echo \"Choose a number:\"\n \nselect num in 1 2 3 4 5 6 7\ndo\n case $num in\n 2|4|6|8) \n echo \"Even number.\"\n ;;\n 1|3|5|7)\n echo \"Odd number.\"\n ;;\n none) \n break \n ;;\n *) echo \"ERROR: Invalid selection\" \n ;;\n esac\ndone"
},
{
"code": null,
"e": 27611,
"s": 27603,
"text": "Output:"
},
{
"code": null,
"e": 27892,
"s": 27611,
"text": "We can prompt users before asking for any selection from the menu with the help of the PS3 variable in bash programming. This variable must be declared before the select loop. The value or string with which a PS3 variable is initialized is used to prompt the user on the console. "
},
{
"code": null,
"e": 27903,
"s": 27892,
"text": "Example 1:"
},
{
"code": null,
"e": 27978,
"s": 27903,
"text": "In the below program we have prompted the user as “Enter your choice ==>”."
},
{
"code": null,
"e": 27991,
"s": 27978,
"text": "Source Code:"
},
{
"code": null,
"e": 28545,
"s": 27991,
"text": "# Program to demonstrate the working of a \n# select-loop in shell scripting\n\nPS3=\"Enter your choice ==> \"\necho \"What is your department?\"\n \nselect department in CS IT ECE EE\ndo\n case $department in\n\n CS) \n echo \"I am from CS department.\"\n ;;\n\n IT)\n echo \"I am from IT department.\"\n ;;\n\n ECE)\n echo \"I am from ECE department.\"\n ;;\n\n EE)\n echo \"I am from EE department.\"\n ;;\n \n none) \n break \n ;;\n\n *) echo \"Invalid selection\" \n ;;\n esac\ndone"
},
{
"code": null,
"e": 28553,
"s": 28545,
"text": "Output:"
},
{
"code": null,
"e": 28564,
"s": 28553,
"text": "Example 2:"
},
{
"code": null,
"e": 28635,
"s": 28564,
"text": "In this program, we have prompted the user as “Enter your choice ==>”."
},
{
"code": null,
"e": 28648,
"s": 28635,
"text": "Source Code:"
},
{
"code": null,
"e": 29039,
"s": 28648,
"text": "# Program to demonstrate the working of a \n# select-loop in shell scripting\n\nPS3=\"Enter your choice ==> \"\necho \"Choose a number:\"\n \nselect num in 1 2 3 4 5 6 7\ndo\n case $num in\n 2|4|6|8) \n echo \"Even number.\"\n ;;\n 1|3|5|7)\n echo \"Odd number.\"\n ;;\n none) \n break \n ;;\n *) echo \"ERROR: Invalid selection\" \n ;;\n esac\ndone"
},
{
"code": null,
"e": 29047,
"s": 29039,
"text": "Output:"
},
{
"code": null,
"e": 29270,
"s": 29047,
"text": "When the end of file (EOF) of input is reached then the select loop gets completed in bash. But in the case of a command piped out to our script the output of the previous command becomes the input for the current command."
},
{
"code": null,
"e": 29778,
"s": 29270,
"text": "Let us understand what does a pipe command means in bash. The pipe is considered one of the most powerful operators in the shell. It is denoted by the symbol (|). The pipe takes the output from one command and uses it as input for another. And, we’re not limited to a single piped command but we can stack them as many times as you like, or until you run out of output or file descriptors. But in the case of select-loop using a pipe out command may lead to no output as demonstrated in the below program. "
},
{
"code": null,
"e": 29787,
"s": 29778,
"text": "Example:"
},
{
"code": null,
"e": 29800,
"s": 29787,
"text": "Source Code:"
},
{
"code": null,
"e": 30320,
"s": 29800,
"text": "# Program to demonstrate the working of a \n# select-loop in shell scripting\n\n# script: select-loop-bash.sh\nselect department in CS IT ECE EE\ndo\n case $department in\n\n CS) \n echo \"I am from CS department.\"\n ;;\n\n IT)\n echo \"I am from IT department.\"\n ;;\n\n ECE)\n echo \"I am from ECE department.\"\n ;;\n\n EE)\n echo \"I am from EE department.\"\n ;;\n \n none) \n break \n ;;\n\n *) echo \"Invalid selection\" \n ;;\n esac\ndone"
},
{
"code": null,
"e": 30381,
"s": 30320,
"text": "Interactive commands (one after the another) and the output:"
},
{
"code": null,
"e": 30388,
"s": 30381,
"text": "Piped:"
},
{
"code": null,
"e": 30593,
"s": 30388,
"text": "This issue can be fixed by ensuring that the select menu will be read from the “/dev/tty” and that we are passing the option with proper word delimiter by using either the “echo” or the “printf” commands."
},
{
"code": null,
"e": 30602,
"s": 30593,
"text": "Example:"
},
{
"code": null,
"e": 30615,
"s": 30602,
"text": "Source Code:"
},
{
"code": null,
"e": 31146,
"s": 30615,
"text": "# Program to demonstrate the working of a \n# select-loop in shell scripting\n\n# script: select-loop-bash.sh\nselect department in CS IT ECE EE\ndo\n case $department in\n\n CS) \n echo \"I am from CS department.\"\n ;;\n\n IT)\n echo \"I am from IT department.\"\n ;;\n\n ECE)\n echo \"I am from ECE department.\"\n ;;\n\n EE)\n echo \"I am from EE department.\"\n ;;\n \n none) \n break \n ;;\n\n *) echo \"Invalid selection\" \n ;;\n esac\ndone < /dev/tty"
},
{
"code": null,
"e": 31207,
"s": 31146,
"text": "Interactive commands (one after the another) and the output:"
},
{
"code": null,
"e": 31214,
"s": 31207,
"text": "Picked"
},
{
"code": null,
"e": 31227,
"s": 31214,
"text": "Shell Script"
},
{
"code": null,
"e": 31238,
"s": 31227,
"text": "Linux-Unix"
},
{
"code": null,
"e": 31336,
"s": 31238,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31371,
"s": 31336,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 31405,
"s": 31371,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 31431,
"s": 31405,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 31460,
"s": 31431,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 31497,
"s": 31460,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 31534,
"s": 31497,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 31576,
"s": 31534,
"text": "Named Pipe or FIFO with example C program"
},
{
"code": null,
"e": 31602,
"s": 31576,
"text": "Thread functions in C/C++"
},
{
"code": null,
"e": 31638,
"s": 31602,
"text": "uniq Command in LINUX with examples"
}
] |
tar command in Linux with examples - GeeksforGeeks | 23 Jun, 2021
The Linux ‘tar’ stands for tape archive, is used to create Archive and extract the Archive files. tar command in Linux is one of the important command which provides archiving functionality in Linux. We can use Linux tar command to create compressed or uncompressed Archive files and also maintain and modify them.
Syntax:
tar [options] [archive-file] [file or directory to be archived]
Options: -c : Creates Archive -x : Extract the archive -f : creates archive with given filename -t : displays or lists files in archived file -u : archives and adds to an existing archive file -v : Displays Verbose Information -A : Concatenates the archive files -z : zip, tells tar command that creates tar file using gzip -j : filter archive tar file using tbzip -W : Verify a archive file -r : update or add file or directory in already existed .tar file
What is an Archive file? An Archive file is a file that is composed of one or more files along with metadata. Archive files are used to collect multiple data files together into a single file for easier portability and storage, or simply to compress files to use less storage space.
Examples: 1. Creating an uncompressed tar Archive using option -cvf : This command creates a tar file called file.tar which is the Archive of all .c files in current directory.
$ tar cvf file.tar *.c
Output :
os2.c
os3.c
os4.c
2. Extracting files from Archive using option -xvf : This command extracts files from Archives.
$ tar xvf file.tar
Output :
os2.c
os3.c
os4.c
3. gzip compression on the tar Archive, using option -z : This command creates a tar file called file.tar.gz which is the Archive of .c files.
$ tar cvzf file.tar.gz *.c
4. Extracting a gzip tar Archive *.tar.gz using option -xvzf : This command extracts files from tar archived file.tar.gz files.
$ tar xvzf file.tar.gz
5. Creating compressed tar archive file in Linux using option -j : This command compresses and creates archive file less than the size of the gzip. Both compress and decompress takes more time then gzip.
$ tar cvfj file.tar.tbz example.cpp
Output :
$tar cvfj file.tar.tbz example.cpp
example.cpp
$tar tvf file.tar.tbz
-rwxrwxrwx root/root 94 2017-09-17 02:47 example.cpp
6. Untar single tar file or specified directory in Linux : This command will Untar a file in current directory or in a specified directory using -C option.
$ tar xvfj file.tar
or
$ tar xvfj file.tar -C path of file in directory
7. Untar multiple .tar, .tar.gz, .tar.tbz file in Linux : This command will extract or untar multiple files from the tar, tar.gz and tar.bz2 archive file. For example the above command will extract “fileA” “fileB” from the archive files.
$ tar xvf file.tar "fileA" "fileB"
or
$ tar zxvf file1.tar.gz "fileA" "fileB"
or
$ tar jxvf file2.tar.tbz "fileA" "fileB"
8. Check size of existing tar, tar.gz, tar.tbz file in Linux : The above command will display the size of archive file in Kilobytes(KB).
$ tar czf file.tar | wc -c
or
$ tar czf file1.tar.gz | wc -c
or
$ tar czf file2.tar.tbz | wc -c
9. Update existing tar file in Linux
$ tar rvf file.tar *.c
Output :
os1.c
10. list the contents and specify the tarfile using option -tf : This command will list the entire list of archived file. We can also list for specific content in a tarfile
$ tar tf file.tar
Output :
example.cpp
11. Applying pipe to through ‘grep command’ to find what we are looking for : This command will list only for the mentioned text or image in grep from archived file.
$ tar tvf file.tar | grep "text to find"
or
$ tar tvf file.tar | grep "filename.file extension"
12. We can pass a file name as an argument to search a tarfile : This command views the archived files along with their details.
$ tar tvf file.tar filename
13. Viewing the Archive using option -tvf
$ tar tvf file.tar
Output :
-rwxrwxrwx root/root 191 2017-09-17 02:20 os2.c
-rwxrwxrwx root/root 218 2017-09-17 02:20 os3.c
-rwxrwxrwx root/root 493 2017-09-17 02:20 os4.c
What are wildcards in Linux Alternatively referred to as a ‘wild character’ or ‘wildcard character’, a wildcard is a symbol used to replace or represent one or more characters. Wildcards are typically either an asterisk (*), which represents one or more characters or question mark (?),which represents a single character.
Example :
14. To search for an image in .png format : This will extract only files with the extension .png from the archive file.tar. The –wildcards option tells tar to interpret wildcards in the name of the files to be extracted; the filename (*.png) is enclosed in single-quotes to protect the wildcard (*) from being expanded incorrectly by the shell.
$ tar tvf file.tar --wildcards '*.png'
Note: In above commands ” * ” is used in place of file name to take all the files present in that particular directory.
YouTubeGeeksforGeeks507K subscribersLinux Tutorials | Compressing and Archiving Files in Linux | tar and zip commands | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 7:08•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=KucqplDh7LI" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
?list=PLqM7alHXFySFc4KtwEZTANgmyJm3NqS_L This article is contributed by Akansh Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
surinderdawra388
linux-command
Linux-file-commands
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TCP Server-Client implementation in C
curl command in Linux with Examples
Conditional Statements | Shell Script
Tail command in Linux with examples
UDP Server-Client implementation in C
Cat command in Linux with examples
touch command in Linux with Examples
scp command in Linux with Examples
echo command in Linux with Examples
ps command in Linux with Examples | [
{
"code": null,
"e": 25169,
"s": 25141,
"text": "\n23 Jun, 2021"
},
{
"code": null,
"e": 25485,
"s": 25169,
"text": "The Linux ‘tar’ stands for tape archive, is used to create Archive and extract the Archive files. tar command in Linux is one of the important command which provides archiving functionality in Linux. We can use Linux tar command to create compressed or uncompressed Archive files and also maintain and modify them. "
},
{
"code": null,
"e": 25494,
"s": 25485,
"text": "Syntax: "
},
{
"code": null,
"e": 25558,
"s": 25494,
"text": "tar [options] [archive-file] [file or directory to be archived]"
},
{
"code": null,
"e": 26017,
"s": 25558,
"text": "Options: -c : Creates Archive -x : Extract the archive -f : creates archive with given filename -t : displays or lists files in archived file -u : archives and adds to an existing archive file -v : Displays Verbose Information -A : Concatenates the archive files -z : zip, tells tar command that creates tar file using gzip -j : filter archive tar file using tbzip -W : Verify a archive file -r : update or add file or directory in already existed .tar file "
},
{
"code": null,
"e": 26301,
"s": 26017,
"text": "What is an Archive file? An Archive file is a file that is composed of one or more files along with metadata. Archive files are used to collect multiple data files together into a single file for easier portability and storage, or simply to compress files to use less storage space. "
},
{
"code": null,
"e": 26479,
"s": 26301,
"text": "Examples: 1. Creating an uncompressed tar Archive using option -cvf : This command creates a tar file called file.tar which is the Archive of all .c files in current directory. "
},
{
"code": null,
"e": 26502,
"s": 26479,
"text": "$ tar cvf file.tar *.c"
},
{
"code": null,
"e": 26512,
"s": 26502,
"text": "Output : "
},
{
"code": null,
"e": 26530,
"s": 26512,
"text": "os2.c\nos3.c\nos4.c"
},
{
"code": null,
"e": 26627,
"s": 26530,
"text": "2. Extracting files from Archive using option -xvf : This command extracts files from Archives. "
},
{
"code": null,
"e": 26646,
"s": 26627,
"text": "$ tar xvf file.tar"
},
{
"code": null,
"e": 26657,
"s": 26646,
"text": "Output : "
},
{
"code": null,
"e": 26675,
"s": 26657,
"text": "os2.c\nos3.c\nos4.c"
},
{
"code": null,
"e": 26820,
"s": 26675,
"text": "3. gzip compression on the tar Archive, using option -z : This command creates a tar file called file.tar.gz which is the Archive of .c files. "
},
{
"code": null,
"e": 26847,
"s": 26820,
"text": "$ tar cvzf file.tar.gz *.c"
},
{
"code": null,
"e": 26977,
"s": 26847,
"text": "4. Extracting a gzip tar Archive *.tar.gz using option -xvzf : This command extracts files from tar archived file.tar.gz files. "
},
{
"code": null,
"e": 27000,
"s": 26977,
"text": "$ tar xvzf file.tar.gz"
},
{
"code": null,
"e": 27206,
"s": 27000,
"text": "5. Creating compressed tar archive file in Linux using option -j : This command compresses and creates archive file less than the size of the gzip. Both compress and decompress takes more time then gzip. "
},
{
"code": null,
"e": 27242,
"s": 27206,
"text": "$ tar cvfj file.tar.tbz example.cpp"
},
{
"code": null,
"e": 27253,
"s": 27242,
"text": "Output : "
},
{
"code": null,
"e": 27382,
"s": 27253,
"text": "$tar cvfj file.tar.tbz example.cpp\nexample.cpp\n$tar tvf file.tar.tbz\n-rwxrwxrwx root/root 94 2017-09-17 02:47 example.cpp"
},
{
"code": null,
"e": 27540,
"s": 27382,
"text": "6. Untar single tar file or specified directory in Linux : This command will Untar a file in current directory or in a specified directory using -C option. "
},
{
"code": null,
"e": 27615,
"s": 27540,
"text": "$ tar xvfj file.tar \nor \n$ tar xvfj file.tar -C path of file in directory "
},
{
"code": null,
"e": 27855,
"s": 27615,
"text": "7. Untar multiple .tar, .tar.gz, .tar.tbz file in Linux : This command will extract or untar multiple files from the tar, tar.gz and tar.bz2 archive file. For example the above command will extract “fileA” “fileB” from the archive files. "
},
{
"code": null,
"e": 27980,
"s": 27855,
"text": "$ tar xvf file.tar \"fileA\" \"fileB\" \nor \n$ tar zxvf file1.tar.gz \"fileA\" \"fileB\"\nor \n$ tar jxvf file2.tar.tbz \"fileA\" \"fileB\""
},
{
"code": null,
"e": 28119,
"s": 27980,
"text": "8. Check size of existing tar, tar.gz, tar.tbz file in Linux : The above command will display the size of archive file in Kilobytes(KB). "
},
{
"code": null,
"e": 28217,
"s": 28119,
"text": "$ tar czf file.tar | wc -c\nor \n$ tar czf file1.tar.gz | wc -c\nor \n$ tar czf file2.tar.tbz | wc -c"
},
{
"code": null,
"e": 28256,
"s": 28217,
"text": "9. Update existing tar file in Linux "
},
{
"code": null,
"e": 28279,
"s": 28256,
"text": "$ tar rvf file.tar *.c"
},
{
"code": null,
"e": 28290,
"s": 28279,
"text": "Output : "
},
{
"code": null,
"e": 28296,
"s": 28290,
"text": "os1.c"
},
{
"code": null,
"e": 28471,
"s": 28296,
"text": "10. list the contents and specify the tarfile using option -tf : This command will list the entire list of archived file. We can also list for specific content in a tarfile "
},
{
"code": null,
"e": 28489,
"s": 28471,
"text": "$ tar tf file.tar"
},
{
"code": null,
"e": 28500,
"s": 28489,
"text": "Output : "
},
{
"code": null,
"e": 28512,
"s": 28500,
"text": "example.cpp"
},
{
"code": null,
"e": 28680,
"s": 28512,
"text": "11. Applying pipe to through ‘grep command’ to find what we are looking for : This command will list only for the mentioned text or image in grep from archived file. "
},
{
"code": null,
"e": 28777,
"s": 28680,
"text": "$ tar tvf file.tar | grep \"text to find\" \nor\n$ tar tvf file.tar | grep \"filename.file extension\""
},
{
"code": null,
"e": 28908,
"s": 28777,
"text": "12. We can pass a file name as an argument to search a tarfile : This command views the archived files along with their details. "
},
{
"code": null,
"e": 28937,
"s": 28908,
"text": "$ tar tvf file.tar filename "
},
{
"code": null,
"e": 28981,
"s": 28937,
"text": "13. Viewing the Archive using option -tvf "
},
{
"code": null,
"e": 29000,
"s": 28981,
"text": "$ tar tvf file.tar"
},
{
"code": null,
"e": 29011,
"s": 29000,
"text": "Output : "
},
{
"code": null,
"e": 29173,
"s": 29011,
"text": "-rwxrwxrwx root/root 191 2017-09-17 02:20 os2.c\n-rwxrwxrwx root/root 218 2017-09-17 02:20 os3.c\n-rwxrwxrwx root/root 493 2017-09-17 02:20 os4.c"
},
{
"code": null,
"e": 29497,
"s": 29173,
"text": "What are wildcards in Linux Alternatively referred to as a ‘wild character’ or ‘wildcard character’, a wildcard is a symbol used to replace or represent one or more characters. Wildcards are typically either an asterisk (*), which represents one or more characters or question mark (?),which represents a single character. "
},
{
"code": null,
"e": 29508,
"s": 29497,
"text": "Example : "
},
{
"code": null,
"e": 29854,
"s": 29508,
"text": "14. To search for an image in .png format : This will extract only files with the extension .png from the archive file.tar. The –wildcards option tells tar to interpret wildcards in the name of the files to be extracted; the filename (*.png) is enclosed in single-quotes to protect the wildcard (*) from being expanded incorrectly by the shell. "
},
{
"code": null,
"e": 29894,
"s": 29854,
"text": "$ tar tvf file.tar --wildcards '*.png' "
},
{
"code": null,
"e": 30016,
"s": 29894,
"text": "Note: In above commands ” * ” is used in place of file name to take all the files present in that particular directory. "
},
{
"code": null,
"e": 30896,
"s": 30016,
"text": "YouTubeGeeksforGeeks507K subscribersLinux Tutorials | Compressing and Archiving Files in Linux | tar and zip commands | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 7:08•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=KucqplDh7LI\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>"
},
{
"code": null,
"e": 31234,
"s": 30896,
"text": "?list=PLqM7alHXFySFc4KtwEZTANgmyJm3NqS_L This article is contributed by Akansh Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. "
},
{
"code": null,
"e": 31360,
"s": 31234,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 31379,
"s": 31362,
"text": "surinderdawra388"
},
{
"code": null,
"e": 31393,
"s": 31379,
"text": "linux-command"
},
{
"code": null,
"e": 31413,
"s": 31393,
"text": "Linux-file-commands"
},
{
"code": null,
"e": 31424,
"s": 31413,
"text": "Linux-Unix"
},
{
"code": null,
"e": 31522,
"s": 31424,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31560,
"s": 31522,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 31596,
"s": 31560,
"text": "curl command in Linux with Examples"
},
{
"code": null,
"e": 31634,
"s": 31596,
"text": "Conditional Statements | Shell Script"
},
{
"code": null,
"e": 31670,
"s": 31634,
"text": "Tail command in Linux with examples"
},
{
"code": null,
"e": 31708,
"s": 31670,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 31743,
"s": 31708,
"text": "Cat command in Linux with examples"
},
{
"code": null,
"e": 31780,
"s": 31743,
"text": "touch command in Linux with Examples"
},
{
"code": null,
"e": 31815,
"s": 31780,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 31851,
"s": 31815,
"text": "echo command in Linux with Examples"
}
] |
Prime Numbers in Discrete Mathematics - GeeksforGeeks | 27 Aug, 2021
Overview :An integer p>1 is called a prime number, or prime if the only positive divisors of p are 1 and p. An integer q>1 that is not prime is called composite.
Example –The integers 2,3,5,7 and 11 are prime numbers, and the integers 4,6,8, and 9 are composite.
Theorem-1: An integer p>1 is prime if and only if for all integers a and b, p divides ab implies either p divides a or p divides b.
Example – Consider the integer 12.Now 12 divides 120 = 30 x 4 but 12|30 and 12|4.Hence,12 is not prime.
Theorem-2 : Every integer n>=2 has a prime factor.
Theorem-3 : If n is a composite integer, then n has a prime factor not exceeding √n.
Example-1 :Determine which of the following integers are prime?
a) 293 b) 9823
Solution –
We first find all primes p such that p2< = 293.These primes are 2,3,5,7,11,13 and 17.Now, none of these primes divide 293. Hence, 293 is a prime.We consider primes p such that p2< = 9823.These primes are 2,3,5,7,11,13,17, etc. None of 2,3,5,7 can divide 9823. However,11 divides 9823.Hence, 9823 is not a prime.
We first find all primes p such that p2< = 293.These primes are 2,3,5,7,11,13 and 17.Now, none of these primes divide 293. Hence, 293 is a prime.
We consider primes p such that p2< = 9823.These primes are 2,3,5,7,11,13,17, etc. None of 2,3,5,7 can divide 9823. However,11 divides 9823.Hence, 9823 is not a prime.
Example-2 : Let n be a positive integer such that n2-1 is prime. Then n =?
Solution – We can write, n2-1 = (n-1)(n2+n+1). Because n3-1 is prime, either n-1 = 1 or n2+n+1 = 1.Now n>=1, So n2+n+1 > 1,i.e., n2+n+1 != 1.Thus, we must have n-1 = 1.This implies that n=2.
Example-3 :Let p be a prime integer such that gcd(a, p3)=p and gcd(b,p4)=p. Find gcd(ab,p7).
Solution – By the given condition, gcd(a,p3)=p. Therefore, p | a. Also, p2|a.(For if p2| a, then gcd (a,p3)>=p2>p, which is a contradiction.) Now a can be written as a product of prime powers. Because p|a and p2| a, it follows that p appears as a factor in the prime factorization of a, but pk, where k>=2, does not appear in that prime factorization. Similarly ,gcd(b,p4)=p implies that p|b and p2|b. As before, it follows that p appears as a factor in the prime factorization of a, but pk, where k>=2, does not appear in that prime factorization. It now follows that p2|ab and p3|ab. Hence, gcd(b,p7) = p2 .
Primality Test Algorithm :
for i: [2,N-1]
if i divides N
return "Composite"
return "Prime"
Example –Let’s take an example and makes the algorithm more efficient, 36=
Take the inputs of a and b until,
a<=b
a . b = N
a . N/a = N
Modified algorithm :
for i : [2,√n]
if i divides N
return "Composite"
return "Prime"
C++
Java
Python3
Javascript
// C++ program to check primality of a number#include <bits/stdc++.h>using namespace std; bool is_prime(int n){ for(int i = 2; i * i <= n; i++){ if(n % i == 0){ return false; //if the number is composite or not prime. } } return true; // number is prime.}int main() { int n; cin >> n; cout << is_prime(n) ? "prime" : "composite"; return 0;}
// Java program to check primality of a number /*package whatever //do not write package name here */ import java.util.*;class prime{ public Boolean is_prime(int n){ for(int i = 2; i * i <= n; i++){ if(n % i == 0){ return false; //if the number is composite or not prime. } } return true; // number is prime. } } class GFG { public static void main (String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); prime ob = new prime(); System.out.println(ob.is_prime(n) ? "Prime" : "Composite"); }}
# Python program to check primality of a numberimport math def is_prime(n): for i in range(2, int(math.sqrt(n))): if(n % i == 0): return False # if the number is composite or not prime. return True # number is prime. if __name__ == "__main__": n = int(input()) if is_prime(n): print("prime") else: print("composite") # This code is contributed by rakeshsahni
<script>// JavaScript program to check primality of a numberfunction is_prime(n){ for(var i = 2; i * i <= n; i++) { if(n % i == 0){ return false; // if the number is composite or not prime. } } return true; // number is prime.} var n; document.write(is_prime(n) ? "prime" : "composite"); // This code is contributed by shivanisinghss2110</script>
Algorithm to find prime numbers :In mathematics, the sieve of Eratosthenes is an ancient algorithm for finding all prime numbers up to any given limit.
Algorithm Sieve of Eratosthenes is input: an integer n > 1.
output : all prime numbers from 2 through n.
let A be an array of Boolean values, indexed by integers 2 to n,
initially all set to true.
for i = 2, 3, 4, ..., not exceeding √n do
if A[i] is true
for j = i2, i2+i, i2+2i, i2+3i, ..., not exceeding n do
A[j] := false
return all i such that A[i] is true.
rakeshsahni
shivanisinghss2110
Misc
Prime Number
Engineering Mathematics
GATE CS
Misc
Misc
Prime Number
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Activation Functions
Difference between Propositional Logic and Predicate Logic
Logic Notations in LaTeX
Univariate, Bivariate and Multivariate data and its analysis
Z-test
Layers of OSI Model
ACID Properties in DBMS
TCP/IP Model
Types of Operating Systems
Normal Forms in DBMS | [
{
"code": null,
"e": 26162,
"s": 26134,
"text": "\n27 Aug, 2021"
},
{
"code": null,
"e": 26324,
"s": 26162,
"text": "Overview :An integer p>1 is called a prime number, or prime if the only positive divisors of p are 1 and p. An integer q>1 that is not prime is called composite."
},
{
"code": null,
"e": 26425,
"s": 26324,
"text": "Example –The integers 2,3,5,7 and 11 are prime numbers, and the integers 4,6,8, and 9 are composite."
},
{
"code": null,
"e": 26557,
"s": 26425,
"text": "Theorem-1: An integer p>1 is prime if and only if for all integers a and b, p divides ab implies either p divides a or p divides b."
},
{
"code": null,
"e": 26661,
"s": 26557,
"text": "Example – Consider the integer 12.Now 12 divides 120 = 30 x 4 but 12|30 and 12|4.Hence,12 is not prime."
},
{
"code": null,
"e": 26712,
"s": 26661,
"text": "Theorem-2 : Every integer n>=2 has a prime factor."
},
{
"code": null,
"e": 26797,
"s": 26712,
"text": "Theorem-3 : If n is a composite integer, then n has a prime factor not exceeding √n."
},
{
"code": null,
"e": 26861,
"s": 26797,
"text": "Example-1 :Determine which of the following integers are prime?"
},
{
"code": null,
"e": 26876,
"s": 26861,
"text": "a) 293 b) 9823"
},
{
"code": null,
"e": 26887,
"s": 26876,
"text": "Solution –"
},
{
"code": null,
"e": 27199,
"s": 26887,
"text": "We first find all primes p such that p2< = 293.These primes are 2,3,5,7,11,13 and 17.Now, none of these primes divide 293. Hence, 293 is a prime.We consider primes p such that p2< = 9823.These primes are 2,3,5,7,11,13,17, etc. None of 2,3,5,7 can divide 9823. However,11 divides 9823.Hence, 9823 is not a prime."
},
{
"code": null,
"e": 27345,
"s": 27199,
"text": "We first find all primes p such that p2< = 293.These primes are 2,3,5,7,11,13 and 17.Now, none of these primes divide 293. Hence, 293 is a prime."
},
{
"code": null,
"e": 27512,
"s": 27345,
"text": "We consider primes p such that p2< = 9823.These primes are 2,3,5,7,11,13,17, etc. None of 2,3,5,7 can divide 9823. However,11 divides 9823.Hence, 9823 is not a prime."
},
{
"code": null,
"e": 27587,
"s": 27512,
"text": "Example-2 : Let n be a positive integer such that n2-1 is prime. Then n =?"
},
{
"code": null,
"e": 27778,
"s": 27587,
"text": "Solution – We can write, n2-1 = (n-1)(n2+n+1). Because n3-1 is prime, either n-1 = 1 or n2+n+1 = 1.Now n>=1, So n2+n+1 > 1,i.e., n2+n+1 != 1.Thus, we must have n-1 = 1.This implies that n=2."
},
{
"code": null,
"e": 27871,
"s": 27778,
"text": "Example-3 :Let p be a prime integer such that gcd(a, p3)=p and gcd(b,p4)=p. Find gcd(ab,p7)."
},
{
"code": null,
"e": 28481,
"s": 27871,
"text": "Solution – By the given condition, gcd(a,p3)=p. Therefore, p | a. Also, p2|a.(For if p2| a, then gcd (a,p3)>=p2>p, which is a contradiction.) Now a can be written as a product of prime powers. Because p|a and p2| a, it follows that p appears as a factor in the prime factorization of a, but pk, where k>=2, does not appear in that prime factorization. Similarly ,gcd(b,p4)=p implies that p|b and p2|b. As before, it follows that p appears as a factor in the prime factorization of a, but pk, where k>=2, does not appear in that prime factorization. It now follows that p2|ab and p3|ab. Hence, gcd(b,p7) = p2 ."
},
{
"code": null,
"e": 28508,
"s": 28481,
"text": "Primality Test Algorithm :"
},
{
"code": null,
"e": 28593,
"s": 28508,
"text": "for i: [2,N-1]\n if i divides N\n return \"Composite\"\n \nreturn \"Prime\" "
},
{
"code": null,
"e": 28668,
"s": 28593,
"text": "Example –Let’s take an example and makes the algorithm more efficient, 36="
},
{
"code": null,
"e": 28801,
"s": 28668,
"text": "Take the inputs of a and b until, \n a<=b\n \n a . b = N\n a . N/a = N"
},
{
"code": null,
"e": 28822,
"s": 28801,
"text": "Modified algorithm :"
},
{
"code": null,
"e": 28904,
"s": 28822,
"text": "for i : [2,√n]\n if i divides N\n return \"Composite\"\n \nreturn \"Prime\" "
},
{
"code": null,
"e": 28908,
"s": 28904,
"text": "C++"
},
{
"code": null,
"e": 28913,
"s": 28908,
"text": "Java"
},
{
"code": null,
"e": 28921,
"s": 28913,
"text": "Python3"
},
{
"code": null,
"e": 28932,
"s": 28921,
"text": "Javascript"
},
{
"code": "// C++ program to check primality of a number#include <bits/stdc++.h>using namespace std; bool is_prime(int n){ for(int i = 2; i * i <= n; i++){ if(n % i == 0){ return false; //if the number is composite or not prime. } } return true; // number is prime.}int main() { int n; cin >> n; cout << is_prime(n) ? \"prime\" : \"composite\"; return 0;}",
"e": 29314,
"s": 28932,
"text": null
},
{
"code": "// Java program to check primality of a number /*package whatever //do not write package name here */ import java.util.*;class prime{ public Boolean is_prime(int n){ for(int i = 2; i * i <= n; i++){ if(n % i == 0){ return false; //if the number is composite or not prime. } } return true; // number is prime. } } class GFG { public static void main (String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); prime ob = new prime(); System.out.println(ob.is_prime(n) ? \"Prime\" : \"Composite\"); }}",
"e": 29943,
"s": 29314,
"text": null
},
{
"code": "# Python program to check primality of a numberimport math def is_prime(n): for i in range(2, int(math.sqrt(n))): if(n % i == 0): return False # if the number is composite or not prime. return True # number is prime. if __name__ == \"__main__\": n = int(input()) if is_prime(n): print(\"prime\") else: print(\"composite\") # This code is contributed by rakeshsahni",
"e": 30368,
"s": 29943,
"text": null
},
{
"code": "<script>// JavaScript program to check primality of a numberfunction is_prime(n){ for(var i = 2; i * i <= n; i++) { if(n % i == 0){ return false; // if the number is composite or not prime. } } return true; // number is prime.} var n; document.write(is_prime(n) ? \"prime\" : \"composite\"); // This code is contributed by shivanisinghss2110</script>",
"e": 30763,
"s": 30368,
"text": null
},
{
"code": null,
"e": 30915,
"s": 30763,
"text": "Algorithm to find prime numbers :In mathematics, the sieve of Eratosthenes is an ancient algorithm for finding all prime numbers up to any given limit."
},
{
"code": null,
"e": 31328,
"s": 30915,
"text": "Algorithm Sieve of Eratosthenes is input: an integer n > 1.\noutput : all prime numbers from 2 through n.\n\nlet A be an array of Boolean values, indexed by integers 2 to n,\ninitially all set to true.\n \n for i = 2, 3, 4, ..., not exceeding √n do\n if A[i] is true\n for j = i2, i2+i, i2+2i, i2+3i, ..., not exceeding n do\n A[j] := false\n\n return all i such that A[i] is true."
},
{
"code": null,
"e": 31340,
"s": 31328,
"text": "rakeshsahni"
},
{
"code": null,
"e": 31359,
"s": 31340,
"text": "shivanisinghss2110"
},
{
"code": null,
"e": 31364,
"s": 31359,
"text": "Misc"
},
{
"code": null,
"e": 31377,
"s": 31364,
"text": "Prime Number"
},
{
"code": null,
"e": 31401,
"s": 31377,
"text": "Engineering Mathematics"
},
{
"code": null,
"e": 31409,
"s": 31401,
"text": "GATE CS"
},
{
"code": null,
"e": 31414,
"s": 31409,
"text": "Misc"
},
{
"code": null,
"e": 31419,
"s": 31414,
"text": "Misc"
},
{
"code": null,
"e": 31432,
"s": 31419,
"text": "Prime Number"
},
{
"code": null,
"e": 31530,
"s": 31432,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31551,
"s": 31530,
"text": "Activation Functions"
},
{
"code": null,
"e": 31610,
"s": 31551,
"text": "Difference between Propositional Logic and Predicate Logic"
},
{
"code": null,
"e": 31635,
"s": 31610,
"text": "Logic Notations in LaTeX"
},
{
"code": null,
"e": 31696,
"s": 31635,
"text": "Univariate, Bivariate and Multivariate data and its analysis"
},
{
"code": null,
"e": 31703,
"s": 31696,
"text": "Z-test"
},
{
"code": null,
"e": 31723,
"s": 31703,
"text": "Layers of OSI Model"
},
{
"code": null,
"e": 31747,
"s": 31723,
"text": "ACID Properties in DBMS"
},
{
"code": null,
"e": 31760,
"s": 31747,
"text": "TCP/IP Model"
},
{
"code": null,
"e": 31787,
"s": 31760,
"text": "Types of Operating Systems"
}
] |
Summing the sum series - GeeksforGeeks | 15 Apr, 2021
Defined a function that calculates the twice of sum of first N natural numbers as sum(N). Your task is to modify the function to sumX(N, M, K) that calculates sum( K + sum( K + sum( K + ...sum(K + N)...))), continuing for M terms. For a given N, M and K calculate the value of sumX(N, M, K). Note: Since the answer can be very large, print the answer in modulo 10^9 + 7.Examples:
Input: N = 1, M = 2, K = 3 Output: 552 For M = 2 sum(3 + sum(3 + 1)) = sum(3 + 20) = 552.Input: N = 3, M =3, K = 2 Output: 1120422 For M = 3 sum(2 + sum(2 + sum(2 + 3))) = sum(2 + sum(2 + 30)) = sum(2 + 1056) = 1120422.
Approach:
Calculate value of sum(N) using the formula N*(N + 1).
Run a loop M times, each time adding K to the previous answer and applying sum(prev_ans + K), modulo 10^9 + 7 each time.
Print the value of sumX(N, M, K) in the end.
Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ program to calculate the // terms of summing of sum series #include <iostream> using namespace std;# define MOD 1000000007 // Function to calculate// twice of sum of first N natural numberslong sum(long N){ long val = N * (N+1); val = val % MOD; return val;} // Function to calculate the// terms of summing of sum seriesint sumX(int N, int M, int K){ for (int i = 0; i < M; i++) { N = (int)sum(K + N); } N = N % MOD; return N;} // Driver Codeint main(){ int N = 1, M = 2, K = 3; cout << sumX(N, M, K) << endl; return 0;} // This code is contributed by Rituraj Jain
// Java program to calculate the// terms of summing of sum series import java.io.*;import java.util.*;import java.lang.*; class GFG { static int MOD = 1000000007; // Function to calculate // twice of sum of first N natural numbers static long sum(long N) { long val = N * (N + 1); // taking modulo 10 ^ 9 + 7 val = val % MOD; return val; } // Function to calculate the // terms of summing of sum series static int sumX(int N, int M, int K) { for (int i = 0; i < M; i++) { N = (int)sum(K + N); } N = N % MOD; return N; } // Driver code public static void main(String args[]) { int N = 1, M = 2, K = 3; System.out.println(sumX(N, M, K)); }}
# Python3 program to calculate the # terms of summing of sum series MOD = 1000000007 # Function to calculate# twice of sum of first N natural numbersdef Sum(N): val = N * (N + 1) # taking modulo 10 ^ 9 + 7 val = val % MOD return val # Function to calculate the# terms of summing of sum seriesdef sumX(N, M, K): for i in range(M): N = int(Sum(K + N)) N = N % MOD return N if __name__ == "__main__": N, M, K = 1, 2, 3 print(sumX(N, M, K)) # This code is contributed by Rituraj Jain
// C# program to calculate the// terms of summing of sum series using System;class GFG { static int MOD = 1000000007; // Function to calculate // twice of sum of first N natural numbers static long sum(long N) { long val = N * (N + 1); // taking modulo 10 ^ 9 + 7 val = val % MOD; return val; } // Function to calculate the // terms of summing of sum series static int sumX(int N, int M, int K) { for (int i = 0; i < M; i++) { N = (int)sum(K + N); } N = N % MOD; return N; } // Driver code public static void Main() { int N = 1, M = 2, K = 3; Console.WriteLine(sumX(N, M, K)); }} // This code is contributed by anuj_67..
<?php// PHP program to calculate the// terms of summing of sum series // Function to calculate twice of// sum of first N natural numbersfunction sum($N){ $MOD = 1000000007; $val = $N * ($N + 1); $val = $val % $MOD; return $val;} // Function to calculate the terms// of summing of sum seriesfunction sumX($N, $M, $K){ $MOD = 1000000007; for ($i = 0; $i < $M; $i++) { $N = sum($K + $N); } $N = $N % $MOD; return $N;} // Driver Code$N = 1;$M = 2;$K = 3;echo (sumX($N, $M, $K)); // This code is contributed// by Shivi_Aggarwal?>
<script> // Javascript program to calculate the// terms of summing of sum series // Function to calculate twice of// sum of first N natural numbersfunction sum(N){ let MOD = 1000000007; let val = N * (N + 1); val = val % MOD; return val;} // Function to calculate the terms// of summing of sum seriesfunction sumX(N, M, K){ let MOD = 1000000007; for (let i = 0; i < M; i++) { N = sum(K + N); } N = N % MOD; return N;} // Driver Codelet N = 1;let M = 2;let K = 3;document.write (sumX(N, M, K)); // This code is contributed// by Sravan </script>
552
rituraj_jain
vt_m
Shivi_Aggarwal
sravankumar8128
series
series-sum
Mathematical
Technical Scripter
Mathematical
series
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program to print prime numbers from 1 to N.
Segment Tree | Set 1 (Sum of given range)
Modular multiplicative inverse
Count all possible paths from top left to bottom right of a mXn matrix
Fizz Buzz Implementation
Check if a number is Palindrome
Program to multiply two matrices
Merge two sorted arrays with O(1) extra space
Generate all permutation of a set in Python
Count ways to reach the n'th stair | [
{
"code": null,
"e": 25937,
"s": 25909,
"text": "\n15 Apr, 2021"
},
{
"code": null,
"e": 26319,
"s": 25937,
"text": "Defined a function that calculates the twice of sum of first N natural numbers as sum(N). Your task is to modify the function to sumX(N, M, K) that calculates sum( K + sum( K + sum( K + ...sum(K + N)...))), continuing for M terms. For a given N, M and K calculate the value of sumX(N, M, K). Note: Since the answer can be very large, print the answer in modulo 10^9 + 7.Examples: "
},
{
"code": null,
"e": 26541,
"s": 26319,
"text": "Input: N = 1, M = 2, K = 3 Output: 552 For M = 2 sum(3 + sum(3 + 1)) = sum(3 + 20) = 552.Input: N = 3, M =3, K = 2 Output: 1120422 For M = 3 sum(2 + sum(2 + sum(2 + 3))) = sum(2 + sum(2 + 30)) = sum(2 + 1056) = 1120422. "
},
{
"code": null,
"e": 26555,
"s": 26543,
"text": "Approach: "
},
{
"code": null,
"e": 26610,
"s": 26555,
"text": "Calculate value of sum(N) using the formula N*(N + 1)."
},
{
"code": null,
"e": 26731,
"s": 26610,
"text": "Run a loop M times, each time adding K to the previous answer and applying sum(prev_ans + K), modulo 10^9 + 7 each time."
},
{
"code": null,
"e": 26776,
"s": 26731,
"text": "Print the value of sumX(N, M, K) in the end."
},
{
"code": null,
"e": 26829,
"s": 26776,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26833,
"s": 26829,
"text": "C++"
},
{
"code": null,
"e": 26838,
"s": 26833,
"text": "Java"
},
{
"code": null,
"e": 26846,
"s": 26838,
"text": "Python3"
},
{
"code": null,
"e": 26849,
"s": 26846,
"text": "C#"
},
{
"code": null,
"e": 26853,
"s": 26849,
"text": "PHP"
},
{
"code": null,
"e": 26864,
"s": 26853,
"text": "Javascript"
},
{
"code": "// C++ program to calculate the // terms of summing of sum series #include <iostream> using namespace std;# define MOD 1000000007 // Function to calculate// twice of sum of first N natural numberslong sum(long N){ long val = N * (N+1); val = val % MOD; return val;} // Function to calculate the// terms of summing of sum seriesint sumX(int N, int M, int K){ for (int i = 0; i < M; i++) { N = (int)sum(K + N); } N = N % MOD; return N;} // Driver Codeint main(){ int N = 1, M = 2, K = 3; cout << sumX(N, M, K) << endl; return 0;} // This code is contributed by Rituraj Jain",
"e": 27497,
"s": 26864,
"text": null
},
{
"code": "// Java program to calculate the// terms of summing of sum series import java.io.*;import java.util.*;import java.lang.*; class GFG { static int MOD = 1000000007; // Function to calculate // twice of sum of first N natural numbers static long sum(long N) { long val = N * (N + 1); // taking modulo 10 ^ 9 + 7 val = val % MOD; return val; } // Function to calculate the // terms of summing of sum series static int sumX(int N, int M, int K) { for (int i = 0; i < M; i++) { N = (int)sum(K + N); } N = N % MOD; return N; } // Driver code public static void main(String args[]) { int N = 1, M = 2, K = 3; System.out.println(sumX(N, M, K)); }}",
"e": 28268,
"s": 27497,
"text": null
},
{
"code": "# Python3 program to calculate the # terms of summing of sum series MOD = 1000000007 # Function to calculate# twice of sum of first N natural numbersdef Sum(N): val = N * (N + 1) # taking modulo 10 ^ 9 + 7 val = val % MOD return val # Function to calculate the# terms of summing of sum seriesdef sumX(N, M, K): for i in range(M): N = int(Sum(K + N)) N = N % MOD return N if __name__ == \"__main__\": N, M, K = 1, 2, 3 print(sumX(N, M, K)) # This code is contributed by Rituraj Jain",
"e": 28824,
"s": 28268,
"text": null
},
{
"code": "// C# program to calculate the// terms of summing of sum series using System;class GFG { static int MOD = 1000000007; // Function to calculate // twice of sum of first N natural numbers static long sum(long N) { long val = N * (N + 1); // taking modulo 10 ^ 9 + 7 val = val % MOD; return val; } // Function to calculate the // terms of summing of sum series static int sumX(int N, int M, int K) { for (int i = 0; i < M; i++) { N = (int)sum(K + N); } N = N % MOD; return N; } // Driver code public static void Main() { int N = 1, M = 2, K = 3; Console.WriteLine(sumX(N, M, K)); }} // This code is contributed by anuj_67..",
"e": 29577,
"s": 28824,
"text": null
},
{
"code": "<?php// PHP program to calculate the// terms of summing of sum series // Function to calculate twice of// sum of first N natural numbersfunction sum($N){ $MOD = 1000000007; $val = $N * ($N + 1); $val = $val % $MOD; return $val;} // Function to calculate the terms// of summing of sum seriesfunction sumX($N, $M, $K){ $MOD = 1000000007; for ($i = 0; $i < $M; $i++) { $N = sum($K + $N); } $N = $N % $MOD; return $N;} // Driver Code$N = 1;$M = 2;$K = 3;echo (sumX($N, $M, $K)); // This code is contributed// by Shivi_Aggarwal?>",
"e": 30153,
"s": 29577,
"text": null
},
{
"code": "<script> // Javascript program to calculate the// terms of summing of sum series // Function to calculate twice of// sum of first N natural numbersfunction sum(N){ let MOD = 1000000007; let val = N * (N + 1); val = val % MOD; return val;} // Function to calculate the terms// of summing of sum seriesfunction sumX(N, M, K){ let MOD = 1000000007; for (let i = 0; i < M; i++) { N = sum(K + N); } N = N % MOD; return N;} // Driver Codelet N = 1;let M = 2;let K = 3;document.write (sumX(N, M, K)); // This code is contributed// by Sravan </script>",
"e": 30748,
"s": 30153,
"text": null
},
{
"code": null,
"e": 30752,
"s": 30748,
"text": "552"
},
{
"code": null,
"e": 30767,
"s": 30754,
"text": "rituraj_jain"
},
{
"code": null,
"e": 30772,
"s": 30767,
"text": "vt_m"
},
{
"code": null,
"e": 30787,
"s": 30772,
"text": "Shivi_Aggarwal"
},
{
"code": null,
"e": 30803,
"s": 30787,
"text": "sravankumar8128"
},
{
"code": null,
"e": 30810,
"s": 30803,
"text": "series"
},
{
"code": null,
"e": 30821,
"s": 30810,
"text": "series-sum"
},
{
"code": null,
"e": 30834,
"s": 30821,
"text": "Mathematical"
},
{
"code": null,
"e": 30853,
"s": 30834,
"text": "Technical Scripter"
},
{
"code": null,
"e": 30866,
"s": 30853,
"text": "Mathematical"
},
{
"code": null,
"e": 30873,
"s": 30866,
"text": "series"
},
{
"code": null,
"e": 30971,
"s": 30873,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31015,
"s": 30971,
"text": "Program to print prime numbers from 1 to N."
},
{
"code": null,
"e": 31057,
"s": 31015,
"text": "Segment Tree | Set 1 (Sum of given range)"
},
{
"code": null,
"e": 31088,
"s": 31057,
"text": "Modular multiplicative inverse"
},
{
"code": null,
"e": 31159,
"s": 31088,
"text": "Count all possible paths from top left to bottom right of a mXn matrix"
},
{
"code": null,
"e": 31184,
"s": 31159,
"text": "Fizz Buzz Implementation"
},
{
"code": null,
"e": 31216,
"s": 31184,
"text": "Check if a number is Palindrome"
},
{
"code": null,
"e": 31249,
"s": 31216,
"text": "Program to multiply two matrices"
},
{
"code": null,
"e": 31295,
"s": 31249,
"text": "Merge two sorted arrays with O(1) extra space"
},
{
"code": null,
"e": 31339,
"s": 31295,
"text": "Generate all permutation of a set in Python"
}
] |
JavaScript Date toDateString() Method - GeeksforGeeks | 22 Oct, 2021
Below is the example of Date toDateString() method.
Example:<script> // Here a date has been assigned // while creating Date object var dateobj = new Date('October 15, 1996 05:35:32'); // Contents of date portion of above date // object is converted into a string using // toDateString() method. var B = dateobj.toDateString(); // Printing the converted string. document.write(B);</script>
<script> // Here a date has been assigned // while creating Date object var dateobj = new Date('October 15, 1996 05:35:32'); // Contents of date portion of above date // object is converted into a string using // toDateString() method. var B = dateobj.toDateString(); // Printing the converted string. document.write(B);</script>
Output:Tue Oct 15 1996
Tue Oct 15 1996
The date.toDateString() method is used to convert the given date object’s contents of date portion into a string. The date object is created using date() constructor.
Syntax:
dateObj.toDateString()
Parameters: This method does not accept any parameter. It is just used along with a Date object created using Date() constructor.
Return Values: It returns the converted string of Date() constructor content’s of date portion.
Note: The dateObj is a valid Date object created using Date() constructor whose contents of date portion are converted into string.
More codes for the above method are as follows:Program 1: Here nothing as parameter is passed while creating date object but still toDateString() method return current day name, month name, date, year.
<script> // Here nothing has been assigned // while creating Date object var dateobj = new Date(); // Contents of date portion of above date // object is converted into a string using // toDateString() method. var B = dateobj.toDateString(); // Printing the converted string. document.write(B);</script>
Output:
Mon Apr 23 2018
Program 2: When some random list of values is passed then toDateString() method return the corresponding produced string.
The format for Date() constructor is like Date(month, date, year, time). By following this format some values are given in the below program and the corresponding string is produced as output. Time format should be like (number:number: number). If time does not lie in this format, it gives the output as an Invalid date.
<script> // Here some different values has been // assigned while creating Date object var dateobj1 = new Date('1'); var dateobj2 = new Date('2, 3'); var dateobj3 = new Date('4, 5, 6'); var dateobj4 = new Date('7, 8, 3, 4'); var dateobj5 = new Date('4, 5, 6, 11:00:12'); var dateobj6 = new Date('12, 5, 4, 0:0'); // Contents of date portion of above date // object is converted into a string using // toDateString() method. var B = dateobj1.toDateString(); var C = dateobj2.toDateString(); var D = dateobj3.toDateString(); var E = dateobj4.toDateString(); var F = dateobj5.toDateString(); var G = dateobj6.toDateString(); // Printing the converted string. document.write(B + "<br />"); document.write(C + "<br />"); document.write(D + "<br />"); document.write(E + "<br />"); document.write(F + "<br />"); document.write(G);</script>
Output:
Mon Jan 01 2001
Sat Feb 03 2001
Wed Apr 05 2006
Invalid Date
Wed Apr 05 2006
Sun Dec 05 2004
Program 3: Months, Date, hour, minute, second and millisecond should be in their respective range of 0 to 11 for months, 1 to 31 for a date, 0 to 23 for hours, 0 to 59 for a minute, 0 to 59 second, 0 to 999 for milliseconds otherwise toDateString() method return Invalid Date.Here date given as of 45 which is out of range of date that is why the below code gives the output as null.
<script> // Here a date has been assigned // while creating Date object var dateobj = new Date('October 45, 1996 05:35:32'); // Contents of date portion of above date // object is converted into a string using // toDateString() method. var B = dateobj.toDateString(); // Printing the converted string. document.write(B);</script>
Output:
Invalid Date
Supported Browsers: The browsers supported by JavaScript Date toDateString() Method are listed below:
Google Chrome 1 and above
Edge 12 and above
Firefox 1 and above
Internet Explorer 5.5 and above
Opera 5 and above
Safari 1 and above
ysachin2314
javascript-date
JavaScript-Methods
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript | [
{
"code": null,
"e": 26095,
"s": 26067,
"text": "\n22 Oct, 2021"
},
{
"code": null,
"e": 26147,
"s": 26095,
"text": "Below is the example of Date toDateString() method."
},
{
"code": null,
"e": 26510,
"s": 26147,
"text": "Example:<script> // Here a date has been assigned // while creating Date object var dateobj = new Date('October 15, 1996 05:35:32'); // Contents of date portion of above date // object is converted into a string using // toDateString() method. var B = dateobj.toDateString(); // Printing the converted string. document.write(B);</script>"
},
{
"code": "<script> // Here a date has been assigned // while creating Date object var dateobj = new Date('October 15, 1996 05:35:32'); // Contents of date portion of above date // object is converted into a string using // toDateString() method. var B = dateobj.toDateString(); // Printing the converted string. document.write(B);</script>",
"e": 26865,
"s": 26510,
"text": null
},
{
"code": null,
"e": 26888,
"s": 26865,
"text": "Output:Tue Oct 15 1996"
},
{
"code": null,
"e": 26904,
"s": 26888,
"text": "Tue Oct 15 1996"
},
{
"code": null,
"e": 27071,
"s": 26904,
"text": "The date.toDateString() method is used to convert the given date object’s contents of date portion into a string. The date object is created using date() constructor."
},
{
"code": null,
"e": 27079,
"s": 27071,
"text": "Syntax:"
},
{
"code": null,
"e": 27102,
"s": 27079,
"text": "dateObj.toDateString()"
},
{
"code": null,
"e": 27232,
"s": 27102,
"text": "Parameters: This method does not accept any parameter. It is just used along with a Date object created using Date() constructor."
},
{
"code": null,
"e": 27328,
"s": 27232,
"text": "Return Values: It returns the converted string of Date() constructor content’s of date portion."
},
{
"code": null,
"e": 27460,
"s": 27328,
"text": "Note: The dateObj is a valid Date object created using Date() constructor whose contents of date portion are converted into string."
},
{
"code": null,
"e": 27662,
"s": 27460,
"text": "More codes for the above method are as follows:Program 1: Here nothing as parameter is passed while creating date object but still toDateString() method return current day name, month name, date, year."
},
{
"code": "<script> // Here nothing has been assigned // while creating Date object var dateobj = new Date(); // Contents of date portion of above date // object is converted into a string using // toDateString() method. var B = dateobj.toDateString(); // Printing the converted string. document.write(B);</script>",
"e": 27985,
"s": 27662,
"text": null
},
{
"code": null,
"e": 27993,
"s": 27985,
"text": "Output:"
},
{
"code": null,
"e": 28009,
"s": 27993,
"text": "Mon Apr 23 2018"
},
{
"code": null,
"e": 28131,
"s": 28009,
"text": "Program 2: When some random list of values is passed then toDateString() method return the corresponding produced string."
},
{
"code": null,
"e": 28453,
"s": 28131,
"text": "The format for Date() constructor is like Date(month, date, year, time). By following this format some values are given in the below program and the corresponding string is produced as output. Time format should be like (number:number: number). If time does not lie in this format, it gives the output as an Invalid date."
},
{
"code": "<script> // Here some different values has been // assigned while creating Date object var dateobj1 = new Date('1'); var dateobj2 = new Date('2, 3'); var dateobj3 = new Date('4, 5, 6'); var dateobj4 = new Date('7, 8, 3, 4'); var dateobj5 = new Date('4, 5, 6, 11:00:12'); var dateobj6 = new Date('12, 5, 4, 0:0'); // Contents of date portion of above date // object is converted into a string using // toDateString() method. var B = dateobj1.toDateString(); var C = dateobj2.toDateString(); var D = dateobj3.toDateString(); var E = dateobj4.toDateString(); var F = dateobj5.toDateString(); var G = dateobj6.toDateString(); // Printing the converted string. document.write(B + \"<br />\"); document.write(C + \"<br />\"); document.write(D + \"<br />\"); document.write(E + \"<br />\"); document.write(F + \"<br />\"); document.write(G);</script>",
"e": 29332,
"s": 28453,
"text": null
},
{
"code": null,
"e": 29340,
"s": 29332,
"text": "Output:"
},
{
"code": null,
"e": 29433,
"s": 29340,
"text": "Mon Jan 01 2001\nSat Feb 03 2001\nWed Apr 05 2006\nInvalid Date\nWed Apr 05 2006\nSun Dec 05 2004"
},
{
"code": null,
"e": 29817,
"s": 29433,
"text": "Program 3: Months, Date, hour, minute, second and millisecond should be in their respective range of 0 to 11 for months, 1 to 31 for a date, 0 to 23 for hours, 0 to 59 for a minute, 0 to 59 second, 0 to 999 for milliseconds otherwise toDateString() method return Invalid Date.Here date given as of 45 which is out of range of date that is why the below code gives the output as null."
},
{
"code": "<script> // Here a date has been assigned // while creating Date object var dateobj = new Date('October 45, 1996 05:35:32'); // Contents of date portion of above date // object is converted into a string using // toDateString() method. var B = dateobj.toDateString(); // Printing the converted string. document.write(B);</script>",
"e": 30168,
"s": 29817,
"text": null
},
{
"code": null,
"e": 30176,
"s": 30168,
"text": "Output:"
},
{
"code": null,
"e": 30189,
"s": 30176,
"text": "Invalid Date"
},
{
"code": null,
"e": 30291,
"s": 30189,
"text": "Supported Browsers: The browsers supported by JavaScript Date toDateString() Method are listed below:"
},
{
"code": null,
"e": 30317,
"s": 30291,
"text": "Google Chrome 1 and above"
},
{
"code": null,
"e": 30335,
"s": 30317,
"text": "Edge 12 and above"
},
{
"code": null,
"e": 30355,
"s": 30335,
"text": "Firefox 1 and above"
},
{
"code": null,
"e": 30387,
"s": 30355,
"text": "Internet Explorer 5.5 and above"
},
{
"code": null,
"e": 30405,
"s": 30387,
"text": "Opera 5 and above"
},
{
"code": null,
"e": 30424,
"s": 30405,
"text": "Safari 1 and above"
},
{
"code": null,
"e": 30436,
"s": 30424,
"text": "ysachin2314"
},
{
"code": null,
"e": 30452,
"s": 30436,
"text": "javascript-date"
},
{
"code": null,
"e": 30471,
"s": 30452,
"text": "JavaScript-Methods"
},
{
"code": null,
"e": 30482,
"s": 30471,
"text": "JavaScript"
},
{
"code": null,
"e": 30499,
"s": 30482,
"text": "Web Technologies"
},
{
"code": null,
"e": 30597,
"s": 30499,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30637,
"s": 30597,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 30682,
"s": 30637,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 30743,
"s": 30682,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 30815,
"s": 30743,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 30867,
"s": 30815,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 30907,
"s": 30867,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 30940,
"s": 30907,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 30985,
"s": 30940,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 31028,
"s": 30985,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Mersenne Prime - GeeksforGeeks | 26 Mar, 2021
Mersenne Prime is a prime number that is one less than a power of two. In other words, any prime is Mersenne Prime if it is of the form 2k-1 where k is an integer greater than or equal to 2. First few Mersenne Primes are 3, 7, 31 and 127.The task is print all Mersenne Primes smaller than an input positive integer n.Examples:
Input: 10
Output: 3 7
3 and 7 are prime numbers smaller than or
equal to 10 and are of the form 2k-1
Input: 100
Output: 3 7 31
The idea is to generate all the primes less than or equal to the given number n using Sieve of Eratosthenes. Once we have generated all such primes, we iterate through all numbers of the form 2k-1 and check if they are primes or not.Below is the implementation of the idea.
C++
Java
Python3
C#
PHP
Javascript
// Program to generate mersenne primes#include<bits/stdc++.h>using namespace std; // Generate all prime numbers less than n.void SieveOfEratosthenes(int n, bool prime[]){ // Initialize all entries of boolean array // as true. A value in prime[i] will finally // be false if i is Not a prime, else true // bool prime[n+1]; for (int i=0; i<=n; i++) prime[i] = true; for (int p=2; p*p<=n; p++) { // If prime[p] is not changed, then it // is a prime if (prime[p] == true) { // Update all multiples of p for (int i=p*2; i<=n; i += p) prime[i] = false; } }} // Function to generate mersenne primes less// than or equal to nvoid mersennePrimes(int n){ // Create a boolean array "prime[0..n]" bool prime[n+1]; // Generating primes using Sieve SieveOfEratosthenes(n,prime); // Generate all numbers of the form 2^k - 1 // and smaller than or equal to n. for (int k=2; ((1<<k)-1) <= n; k++) { long long num = (1<<k) - 1; // Checking whether number is prime and is // one less then the power of 2 if (prime[num]) cout << num << " "; }} // Driven programint main(){ int n = 31; cout << "Mersenne prime numbers smaller " << "than or equal to " << n << endl; mersennePrimes(n); return 0;}
// Program to generate// mersenne primesimport java.io.*; class GFG { // Generate all prime numbers // less than n. static void SieveOfEratosthenes(int n, boolean prime[]) { // Initialize all entries of // boolean array as true. A // value in prime[i] will finally // be false if i is Not a prime, // else true bool prime[n+1]; for (int i = 0; i <= n; i++) prime[i] = true; for (int p = 2; p * p <= n; p++) { // If prime[p] is not changed // , then it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * 2; i <= n; i += p) prime[i] = false; } } } // Function to generate mersenne // primes lessthan or equal to n static void mersennePrimes(int n) { // Create a boolean array // "prime[0..n]" boolean prime[]=new boolean[n + 1]; // Generating primes // using Sieve SieveOfEratosthenes(n, prime); // Generate all numbers of // the form 2^k - 1 and // smaller than or equal to n. for (int k = 2; (( 1 << k) - 1) <= n; k++) { long num = ( 1 << k) - 1; // Checking whether number is // prime and is one less then // the power of 2 if (prime[(int)(num)]) System.out.print(num + " "); } } // Driven program public static void main(String args[]) { int n = 31; System.out.println("Mersenne prime"+ "numbers smaller than"+ "or equal to "+n); mersennePrimes(n); }} // This code is contributed by Nikita Tiwari.
# Program to generate mersenne primes # Generate all prime numbers# less than n.def SieveOfEratosthenes(n, prime): # Initialize all entries of boolean # array as true. A value in prime[i] # will finally be false if i is Not # a prime, else true bool prime[n+1] for i in range(0, n + 1) : prime[i] = True p = 2 while(p * p <= n): # If prime[p] is not changed, # then it is a prime if (prime[p] == True) : # Update all multiples of p for i in range(p * 2, n + 1, p): prime[i] = False p += 1 # Function to generate mersenne# primes less than or equal to ndef mersennePrimes(n) : # Create a boolean array # "prime[0..n]" prime = [0] * (n + 1) # Generating primes using Sieve SieveOfEratosthenes(n, prime) # Generate all numbers of the # form 2^k - 1 and smaller # than or equal to n. k = 2 while(((1 << k) - 1) <= n ): num = (1 << k) - 1 # Checking whether number # is prime and is one # less then the power of 2 if (prime[num]) : print(num, end = " " ) k += 1 # Driver Coden = 31print("Mersenne prime numbers smaller", "than or equal to " , n )mersennePrimes(n) # This code is contributed# by Smitha
// C# Program to generate mersenne primesusing System; class GFG { // Generate all prime numbers less than n. static void SieveOfEratosthenes(int n, bool []prime) { // Initialize all entries of // boolean array as true. A // value in prime[i] will finally // be false if i is Not a prime, // else true bool prime[n+1]; for (int i = 0; i <= n; i++) prime[i] = true; for (int p = 2; p * p <= n; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * 2; i <= n; i += p) prime[i] = false; } } } // Function to generate mersenne // primes lessthan or equal to n static void mersennePrimes(int n) { // Create a boolean array // "prime[0..n]" bool []prime = new bool[n + 1]; // Generating primes // using Sieve SieveOfEratosthenes(n, prime); // Generate all numbers of // the form 2^k - 1 and // smaller than or equal to n. for (int k = 2; (( 1 << k) - 1) <= n; k++) { long num = ( 1 << k) - 1; // Checking whether number is // prime and is one less then // the power of 2 if (prime[(int)(num)]) Console.Write(num + " "); } } // Driven program public static void Main() { int n = 31; Console.WriteLine("Mersenne prime numbers" + " smaller than or equal to " + n); mersennePrimes(n); }} // This code is contributed by nitin mittal.
<?php// Program to generate mersenne primes // Generate all prime numbers less than n.function SieveOf($n){ // Initialize all entries of boolean // array as true. A value in prime[i] // will finally be false if i is Not // a prime, else true $prime = array($n + 1); for ($i = 0; $i <= $n; $i++) $prime[$i] = true; for ($p = 2; $p * $p <= $n; $p++) { // If prime[p] is not changed, // then it is a prime if ($prime[$p] == true) { // Update all multiples of p for ($i = $p * 2; $i <= $n; $i += $p) $prime[$i] = false; } } return $prime;} // Function to generate mersenne// primes less than or equal to nfunction mersennePrimes($n){ // Create a boolean array "prime[0..n]" // bool prime[n+1]; // Generating primes using Sieve $prime = SieveOf($n); // Generate all numbers of the // form 2^k - 1 and smaller // than or equal to n. for ($k = 2; ((1 << $k) - 1) <= $n; $k++) { $num = (1 << $k) - 1; // Checking whether number is prime // and is one less then the power of 2 if ($prime[$num]) echo $num . " "; }} // Driver Code$n = 31;echo "Mersenne prime numbers smaller " . "than or equal to $n " . mersennePrimes($n); // This code is contributed by mits?>
<script> // JavaScript to generate// mersenne primes // Generate all prime numbers // less than n. function SieveOfEratosthenes( n, prime) { // Initialize all entries of // boolean array as true. A // value in prime[i] will finally // be false if i is Not a prime, // else true bool prime[n+1]; for (let i = 0; i <= n; i++) prime[i] = true; for (let p = 2; p * p <= n; p++) { // If prime[p] is not changed // , then it is a prime if (prime[p] == true) { // Update all multiples of p for (let i = p * 2; i <= n; i += p) prime[i] = false; } } } // Function to generate mersenne // primes lessthan or equal to n function mersennePrimes(n) { // Create a boolean array // "prime[0..n]" let prime=[]; // Generating primes // using Sieve SieveOfEratosthenes(n, prime); // Generate all numbers of // the form 2^k - 1 and // smaller than or equal to n. for (let k = 2; (( 1 << k) - 1) <= n; k++) { let num = ( 1 << k) - 1; // Checking whether number is // prime and is one less then // the power of 2 if (prime[(num)]) document.write(num + " "); } } // Driver Code let n = 31; document.write("Mersenne prime"+ "numbers smaller than"+ "or equal to "+n + "<br/>"); mersennePrimes(n); // This code is contributed by code_hunt.</script>
Output:
Mersenne prime numbers smaller than or equal to 31
3 7 31
References: https://en.wikipedia.org/wiki/Mersenne_primeThis article is contributed by Rahul Agrawal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
nitin mittal
Smitha Dinesh Semwal
Mithun Kumar
code_hunt
Prime Number
sieve
Mathematical
Mathematical
Prime Number
sieve
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Modulo Operator (%) in C/C++ with Examples
Prime Numbers
Print all possible combinations of r elements in a given array of size n
The Knight's tour problem | Backtracking-1
Operators in C / C++
Program for factorial of a number
Find minimum number of coins that make a given value
Program to find sum of elements in a given array
Minimum number of jumps to reach end | [
{
"code": null,
"e": 26327,
"s": 26299,
"text": "\n26 Mar, 2021"
},
{
"code": null,
"e": 26656,
"s": 26327,
"text": "Mersenne Prime is a prime number that is one less than a power of two. In other words, any prime is Mersenne Prime if it is of the form 2k-1 where k is an integer greater than or equal to 2. First few Mersenne Primes are 3, 7, 31 and 127.The task is print all Mersenne Primes smaller than an input positive integer n.Examples: "
},
{
"code": null,
"e": 26785,
"s": 26656,
"text": "Input: 10\nOutput: 3 7\n3 and 7 are prime numbers smaller than or\nequal to 10 and are of the form 2k-1\n\nInput: 100\nOutput: 3 7 31 "
},
{
"code": null,
"e": 27062,
"s": 26787,
"text": "The idea is to generate all the primes less than or equal to the given number n using Sieve of Eratosthenes. Once we have generated all such primes, we iterate through all numbers of the form 2k-1 and check if they are primes or not.Below is the implementation of the idea. "
},
{
"code": null,
"e": 27066,
"s": 27062,
"text": "C++"
},
{
"code": null,
"e": 27071,
"s": 27066,
"text": "Java"
},
{
"code": null,
"e": 27079,
"s": 27071,
"text": "Python3"
},
{
"code": null,
"e": 27082,
"s": 27079,
"text": "C#"
},
{
"code": null,
"e": 27086,
"s": 27082,
"text": "PHP"
},
{
"code": null,
"e": 27097,
"s": 27086,
"text": "Javascript"
},
{
"code": "// Program to generate mersenne primes#include<bits/stdc++.h>using namespace std; // Generate all prime numbers less than n.void SieveOfEratosthenes(int n, bool prime[]){ // Initialize all entries of boolean array // as true. A value in prime[i] will finally // be false if i is Not a prime, else true // bool prime[n+1]; for (int i=0; i<=n; i++) prime[i] = true; for (int p=2; p*p<=n; p++) { // If prime[p] is not changed, then it // is a prime if (prime[p] == true) { // Update all multiples of p for (int i=p*2; i<=n; i += p) prime[i] = false; } }} // Function to generate mersenne primes less// than or equal to nvoid mersennePrimes(int n){ // Create a boolean array \"prime[0..n]\" bool prime[n+1]; // Generating primes using Sieve SieveOfEratosthenes(n,prime); // Generate all numbers of the form 2^k - 1 // and smaller than or equal to n. for (int k=2; ((1<<k)-1) <= n; k++) { long long num = (1<<k) - 1; // Checking whether number is prime and is // one less then the power of 2 if (prime[num]) cout << num << \" \"; }} // Driven programint main(){ int n = 31; cout << \"Mersenne prime numbers smaller \" << \"than or equal to \" << n << endl; mersennePrimes(n); return 0;}",
"e": 28464,
"s": 27097,
"text": null
},
{
"code": "// Program to generate// mersenne primesimport java.io.*; class GFG { // Generate all prime numbers // less than n. static void SieveOfEratosthenes(int n, boolean prime[]) { // Initialize all entries of // boolean array as true. A // value in prime[i] will finally // be false if i is Not a prime, // else true bool prime[n+1]; for (int i = 0; i <= n; i++) prime[i] = true; for (int p = 2; p * p <= n; p++) { // If prime[p] is not changed // , then it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * 2; i <= n; i += p) prime[i] = false; } } } // Function to generate mersenne // primes lessthan or equal to n static void mersennePrimes(int n) { // Create a boolean array // \"prime[0..n]\" boolean prime[]=new boolean[n + 1]; // Generating primes // using Sieve SieveOfEratosthenes(n, prime); // Generate all numbers of // the form 2^k - 1 and // smaller than or equal to n. for (int k = 2; (( 1 << k) - 1) <= n; k++) { long num = ( 1 << k) - 1; // Checking whether number is // prime and is one less then // the power of 2 if (prime[(int)(num)]) System.out.print(num + \" \"); } } // Driven program public static void main(String args[]) { int n = 31; System.out.println(\"Mersenne prime\"+ \"numbers smaller than\"+ \"or equal to \"+n); mersennePrimes(n); }} // This code is contributed by Nikita Tiwari.",
"e": 30303,
"s": 28464,
"text": null
},
{
"code": "# Program to generate mersenne primes # Generate all prime numbers# less than n.def SieveOfEratosthenes(n, prime): # Initialize all entries of boolean # array as true. A value in prime[i] # will finally be false if i is Not # a prime, else true bool prime[n+1] for i in range(0, n + 1) : prime[i] = True p = 2 while(p * p <= n): # If prime[p] is not changed, # then it is a prime if (prime[p] == True) : # Update all multiples of p for i in range(p * 2, n + 1, p): prime[i] = False p += 1 # Function to generate mersenne# primes less than or equal to ndef mersennePrimes(n) : # Create a boolean array # \"prime[0..n]\" prime = [0] * (n + 1) # Generating primes using Sieve SieveOfEratosthenes(n, prime) # Generate all numbers of the # form 2^k - 1 and smaller # than or equal to n. k = 2 while(((1 << k) - 1) <= n ): num = (1 << k) - 1 # Checking whether number # is prime and is one # less then the power of 2 if (prime[num]) : print(num, end = \" \" ) k += 1 # Driver Coden = 31print(\"Mersenne prime numbers smaller\", \"than or equal to \" , n )mersennePrimes(n) # This code is contributed# by Smitha",
"e": 31656,
"s": 30303,
"text": null
},
{
"code": "// C# Program to generate mersenne primesusing System; class GFG { // Generate all prime numbers less than n. static void SieveOfEratosthenes(int n, bool []prime) { // Initialize all entries of // boolean array as true. A // value in prime[i] will finally // be false if i is Not a prime, // else true bool prime[n+1]; for (int i = 0; i <= n; i++) prime[i] = true; for (int p = 2; p * p <= n; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * 2; i <= n; i += p) prime[i] = false; } } } // Function to generate mersenne // primes lessthan or equal to n static void mersennePrimes(int n) { // Create a boolean array // \"prime[0..n]\" bool []prime = new bool[n + 1]; // Generating primes // using Sieve SieveOfEratosthenes(n, prime); // Generate all numbers of // the form 2^k - 1 and // smaller than or equal to n. for (int k = 2; (( 1 << k) - 1) <= n; k++) { long num = ( 1 << k) - 1; // Checking whether number is // prime and is one less then // the power of 2 if (prime[(int)(num)]) Console.Write(num + \" \"); } } // Driven program public static void Main() { int n = 31; Console.WriteLine(\"Mersenne prime numbers\" + \" smaller than or equal to \" + n); mersennePrimes(n); }} // This code is contributed by nitin mittal.",
"e": 33493,
"s": 31656,
"text": null
},
{
"code": "<?php// Program to generate mersenne primes // Generate all prime numbers less than n.function SieveOf($n){ // Initialize all entries of boolean // array as true. A value in prime[i] // will finally be false if i is Not // a prime, else true $prime = array($n + 1); for ($i = 0; $i <= $n; $i++) $prime[$i] = true; for ($p = 2; $p * $p <= $n; $p++) { // If prime[p] is not changed, // then it is a prime if ($prime[$p] == true) { // Update all multiples of p for ($i = $p * 2; $i <= $n; $i += $p) $prime[$i] = false; } } return $prime;} // Function to generate mersenne// primes less than or equal to nfunction mersennePrimes($n){ // Create a boolean array \"prime[0..n]\" // bool prime[n+1]; // Generating primes using Sieve $prime = SieveOf($n); // Generate all numbers of the // form 2^k - 1 and smaller // than or equal to n. for ($k = 2; ((1 << $k) - 1) <= $n; $k++) { $num = (1 << $k) - 1; // Checking whether number is prime // and is one less then the power of 2 if ($prime[$num]) echo $num . \" \"; }} // Driver Code$n = 31;echo \"Mersenne prime numbers smaller \" . \"than or equal to $n \" . mersennePrimes($n); // This code is contributed by mits?>",
"e": 34837,
"s": 33493,
"text": null
},
{
"code": "<script> // JavaScript to generate// mersenne primes // Generate all prime numbers // less than n. function SieveOfEratosthenes( n, prime) { // Initialize all entries of // boolean array as true. A // value in prime[i] will finally // be false if i is Not a prime, // else true bool prime[n+1]; for (let i = 0; i <= n; i++) prime[i] = true; for (let p = 2; p * p <= n; p++) { // If prime[p] is not changed // , then it is a prime if (prime[p] == true) { // Update all multiples of p for (let i = p * 2; i <= n; i += p) prime[i] = false; } } } // Function to generate mersenne // primes lessthan or equal to n function mersennePrimes(n) { // Create a boolean array // \"prime[0..n]\" let prime=[]; // Generating primes // using Sieve SieveOfEratosthenes(n, prime); // Generate all numbers of // the form 2^k - 1 and // smaller than or equal to n. for (let k = 2; (( 1 << k) - 1) <= n; k++) { let num = ( 1 << k) - 1; // Checking whether number is // prime and is one less then // the power of 2 if (prime[(num)]) document.write(num + \" \"); } } // Driver Code let n = 31; document.write(\"Mersenne prime\"+ \"numbers smaller than\"+ \"or equal to \"+n + \"<br/>\"); mersennePrimes(n); // This code is contributed by code_hunt.</script>",
"e": 36560,
"s": 34837,
"text": null
},
{
"code": null,
"e": 36570,
"s": 36560,
"text": "Output: "
},
{
"code": null,
"e": 36629,
"s": 36570,
"text": "Mersenne prime numbers smaller than or equal to 31\n3 7 31 "
},
{
"code": null,
"e": 37107,
"s": 36629,
"text": "References: https://en.wikipedia.org/wiki/Mersenne_primeThis article is contributed by Rahul Agrawal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 37120,
"s": 37107,
"text": "nitin mittal"
},
{
"code": null,
"e": 37141,
"s": 37120,
"text": "Smitha Dinesh Semwal"
},
{
"code": null,
"e": 37154,
"s": 37141,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 37164,
"s": 37154,
"text": "code_hunt"
},
{
"code": null,
"e": 37177,
"s": 37164,
"text": "Prime Number"
},
{
"code": null,
"e": 37183,
"s": 37177,
"text": "sieve"
},
{
"code": null,
"e": 37196,
"s": 37183,
"text": "Mathematical"
},
{
"code": null,
"e": 37209,
"s": 37196,
"text": "Mathematical"
},
{
"code": null,
"e": 37222,
"s": 37209,
"text": "Prime Number"
},
{
"code": null,
"e": 37228,
"s": 37222,
"text": "sieve"
},
{
"code": null,
"e": 37326,
"s": 37228,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37350,
"s": 37326,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 37393,
"s": 37350,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 37407,
"s": 37393,
"text": "Prime Numbers"
},
{
"code": null,
"e": 37480,
"s": 37407,
"text": "Print all possible combinations of r elements in a given array of size n"
},
{
"code": null,
"e": 37523,
"s": 37480,
"text": "The Knight's tour problem | Backtracking-1"
},
{
"code": null,
"e": 37544,
"s": 37523,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 37578,
"s": 37544,
"text": "Program for factorial of a number"
},
{
"code": null,
"e": 37631,
"s": 37578,
"text": "Find minimum number of coins that make a given value"
},
{
"code": null,
"e": 37680,
"s": 37631,
"text": "Program to find sum of elements in a given array"
}
] |
GATE | GATE CS 2018 | Question 7 - GeeksforGeeks | 22 Feb, 2018
In a party, 60% of the invited guests are male and 40% are female. If 80% of the invited guests attended the party and if all the invited female guests attended, what would be the ratio of males to females among the attendees in the party?
(A) 2:3(B) 1:1(C) 3:2(D) 2:1Answer: (B)Explanation:
Let total males and females be 60x and
40x respectively.
Total number of people = (60x + 40x)
Total number of people who attended :
0.8(60x + 40x) = 80x
Let y males attended. It is given all
1females attended
40x + y = 80x
y = 40x which is same as females.
Alternative Approach –Lets total number of people = 100.Therefore, 60 are male and and 40 are female.
But total 80 guests are attended and all 40 female attended the party.So, there remaining (80 – 40 = 40) attendees should be male.
Then the ration of male to female among attendees is 40 : 40 = 1 : 1Quiz of this Question
GATE CS 2018
GATE-GATE CS 2018
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | Gate IT 2007 | Question 25
GATE | GATE-CS-2001 | Question 39
GATE | GATE-CS-2000 | Question 41
GATE | GATE-CS-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE MOCK 2017 | Question 24
GATE | GATE-CS-2006 | Question 47
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90 | [
{
"code": null,
"e": 25589,
"s": 25561,
"text": "\n22 Feb, 2018"
},
{
"code": null,
"e": 25829,
"s": 25589,
"text": "In a party, 60% of the invited guests are male and 40% are female. If 80% of the invited guests attended the party and if all the invited female guests attended, what would be the ratio of males to females among the attendees in the party?"
},
{
"code": null,
"e": 25881,
"s": 25829,
"text": "(A) 2:3(B) 1:1(C) 3:2(D) 2:1Answer: (B)Explanation:"
},
{
"code": null,
"e": 26162,
"s": 25881,
"text": "Let total males and females be 60x and\n40x respectively.\n\nTotal number of people = (60x + 40x)\nTotal number of people who attended : \n 0.8(60x + 40x) = 80x\n\nLet y males attended. It is given all \n1females attended \n\n40x + y = 80x\ny = 40x which is same as females.\n"
},
{
"code": null,
"e": 26264,
"s": 26162,
"text": "Alternative Approach –Lets total number of people = 100.Therefore, 60 are male and and 40 are female."
},
{
"code": null,
"e": 26395,
"s": 26264,
"text": "But total 80 guests are attended and all 40 female attended the party.So, there remaining (80 – 40 = 40) attendees should be male."
},
{
"code": null,
"e": 26485,
"s": 26395,
"text": "Then the ration of male to female among attendees is 40 : 40 = 1 : 1Quiz of this Question"
},
{
"code": null,
"e": 26498,
"s": 26485,
"text": "GATE CS 2018"
},
{
"code": null,
"e": 26516,
"s": 26498,
"text": "GATE-GATE CS 2018"
},
{
"code": null,
"e": 26521,
"s": 26516,
"text": "GATE"
},
{
"code": null,
"e": 26619,
"s": 26521,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26653,
"s": 26619,
"text": "GATE | Gate IT 2007 | Question 25"
},
{
"code": null,
"e": 26687,
"s": 26653,
"text": "GATE | GATE-CS-2001 | Question 39"
},
{
"code": null,
"e": 26721,
"s": 26687,
"text": "GATE | GATE-CS-2000 | Question 41"
},
{
"code": null,
"e": 26754,
"s": 26721,
"text": "GATE | GATE-CS-2005 | Question 6"
},
{
"code": null,
"e": 26790,
"s": 26754,
"text": "GATE | GATE MOCK 2017 | Question 21"
},
{
"code": null,
"e": 26826,
"s": 26790,
"text": "GATE | GATE MOCK 2017 | Question 24"
},
{
"code": null,
"e": 26860,
"s": 26826,
"text": "GATE | GATE-CS-2006 | Question 47"
},
{
"code": null,
"e": 26894,
"s": 26860,
"text": "GATE | Gate IT 2008 | Question 43"
},
{
"code": null,
"e": 26928,
"s": 26894,
"text": "GATE | GATE-CS-2009 | Question 38"
}
] |
Setting decimal precision in C - GeeksforGeeks | 02 Jun, 2017
How to print floating point numbers with a specified precision? Rounding is not required. For example, 5.48958123 should be printed as 5.4895 if given precision is 4.
For example, below program sets the precision for 4 digits after the decimal point:
// C program to set precision in floating point numbers#include<stdio.h>#include<math.h>int main(){ float num = 5.48958123; // 4 digits after the decimal point num = floor(10000*num)/10000; printf("%f", num); return 0;}
Output:
5.489500
We can generalize above method using pow()
float newPrecision(float n, float i){ return floor(pow(10,i)*n)/pow(10,i);}
In C, there is a format specifier in C. To print 4 digits after dot, we can use 0.4f in printf(). Below is program to demonstrate the same.
// C program to set precision in floating point numbers// using format specifier#include<stdio.h> int main() { float num = 5.48958123; // 4 digits after the decimal point printf("%0.4f", num); return 0;}
Output:
5.4896
This article is contributed by Niharika Khandelwal. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
C-Data Types
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Multidimensional Arrays in C / C++
Left Shift and Right Shift Operators in C/C++
Function Pointer in C
Substring in C++
Core Dump (Segmentation fault) in C/C++
rand() and srand() in C/C++
fork() in C
std::string class in C++
Converting Strings to Numbers in C/C++
Enumeration (or enum) in C | [
{
"code": null,
"e": 25944,
"s": 25916,
"text": "\n02 Jun, 2017"
},
{
"code": null,
"e": 26111,
"s": 25944,
"text": "How to print floating point numbers with a specified precision? Rounding is not required. For example, 5.48958123 should be printed as 5.4895 if given precision is 4."
},
{
"code": null,
"e": 26195,
"s": 26111,
"text": "For example, below program sets the precision for 4 digits after the decimal point:"
},
{
"code": "// C program to set precision in floating point numbers#include<stdio.h>#include<math.h>int main(){ float num = 5.48958123; // 4 digits after the decimal point num = floor(10000*num)/10000; printf(\"%f\", num); return 0;}",
"e": 26429,
"s": 26195,
"text": null
},
{
"code": null,
"e": 26437,
"s": 26429,
"text": "Output:"
},
{
"code": null,
"e": 26446,
"s": 26437,
"text": "5.489500"
},
{
"code": null,
"e": 26489,
"s": 26446,
"text": "We can generalize above method using pow()"
},
{
"code": "float newPrecision(float n, float i){ return floor(pow(10,i)*n)/pow(10,i);}",
"e": 26568,
"s": 26489,
"text": null
},
{
"code": null,
"e": 26708,
"s": 26568,
"text": "In C, there is a format specifier in C. To print 4 digits after dot, we can use 0.4f in printf(). Below is program to demonstrate the same."
},
{
"code": "// C program to set precision in floating point numbers// using format specifier#include<stdio.h> int main() { float num = 5.48958123; // 4 digits after the decimal point printf(\"%0.4f\", num); return 0;}",
"e": 26930,
"s": 26708,
"text": null
},
{
"code": null,
"e": 26938,
"s": 26930,
"text": "Output:"
},
{
"code": null,
"e": 26945,
"s": 26938,
"text": "5.4896"
},
{
"code": null,
"e": 27218,
"s": 26945,
"text": "This article is contributed by Niharika Khandelwal. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 27342,
"s": 27218,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above"
},
{
"code": null,
"e": 27355,
"s": 27342,
"text": "C-Data Types"
},
{
"code": null,
"e": 27366,
"s": 27355,
"text": "C Language"
},
{
"code": null,
"e": 27464,
"s": 27366,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27499,
"s": 27464,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 27545,
"s": 27499,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 27567,
"s": 27545,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 27584,
"s": 27567,
"text": "Substring in C++"
},
{
"code": null,
"e": 27624,
"s": 27584,
"text": "Core Dump (Segmentation fault) in C/C++"
},
{
"code": null,
"e": 27652,
"s": 27624,
"text": "rand() and srand() in C/C++"
},
{
"code": null,
"e": 27664,
"s": 27652,
"text": "fork() in C"
},
{
"code": null,
"e": 27689,
"s": 27664,
"text": "std::string class in C++"
},
{
"code": null,
"e": 27728,
"s": 27689,
"text": "Converting Strings to Numbers in C/C++"
}
] |
wxPython - Change Font of StaticText - GeeksforGeeks | 18 Jun, 2020
In this article we are going to learn how can we change the font of static text present on the window. To do this first of all, we wil create a wx.Font class of wxPython. After this we will use SetFont() function of wx.StaticText class.SetFont() function takes a sing wx.Font type parameter.
Syntax: wx.StaticText.SetFont(self, font)
Parameters:
Code Example:
import wx class Example(wx.Frame): def __init__(self, *args, **kwargs): super(Example, self).__init__(*args, **kwargs) self.InitUI() def InitUI(self): self.locale = wx.Locale(wx.LANGUAGE_ENGLISH) self.pnl = wx.Panel(self) # create wx.Font object font = wx.Font(20, family = wx.FONTFAMILY_MODERN, style = 0, weight = 90, underline = False, faceName ="", encoding = wx.FONTENCODING_DEFAULT) self.st = wx.StaticText(self.pnl, id = 1, label ="This is the Label.", pos =(20, 20), size = wx.DefaultSize, style = wx.ST_ELLIPSIZE_MIDDLE, name ="statictext") # set font for the statictext self.st.SetFont(font) self.SetSize((350, 250)) self.SetTitle('wx.Button') self.Centre() def main(): app = wx.App() ex = Example(None) ex.Show() app.MainLoop() if __name__ == '__main__': main()
Output Window:
Python wxPython-StaticText
Python-gui
Python-wxPython
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Read a file line by line in Python
Different ways to create Pandas Dataframe
Python String | replace()
Reading and Writing to text files in Python
*args and **kwargs in Python
Convert integer to string in Python
Check if element exists in list in Python
Create a Pandas DataFrame from Lists | [
{
"code": null,
"e": 25675,
"s": 25647,
"text": "\n18 Jun, 2020"
},
{
"code": null,
"e": 25967,
"s": 25675,
"text": "In this article we are going to learn how can we change the font of static text present on the window. To do this first of all, we wil create a wx.Font class of wxPython. After this we will use SetFont() function of wx.StaticText class.SetFont() function takes a sing wx.Font type parameter."
},
{
"code": null,
"e": 26009,
"s": 25967,
"text": "Syntax: wx.StaticText.SetFont(self, font)"
},
{
"code": null,
"e": 26021,
"s": 26009,
"text": "Parameters:"
},
{
"code": null,
"e": 26035,
"s": 26021,
"text": "Code Example:"
},
{
"code": "import wx class Example(wx.Frame): def __init__(self, *args, **kwargs): super(Example, self).__init__(*args, **kwargs) self.InitUI() def InitUI(self): self.locale = wx.Locale(wx.LANGUAGE_ENGLISH) self.pnl = wx.Panel(self) # create wx.Font object font = wx.Font(20, family = wx.FONTFAMILY_MODERN, style = 0, weight = 90, underline = False, faceName =\"\", encoding = wx.FONTENCODING_DEFAULT) self.st = wx.StaticText(self.pnl, id = 1, label =\"This is the Label.\", pos =(20, 20), size = wx.DefaultSize, style = wx.ST_ELLIPSIZE_MIDDLE, name =\"statictext\") # set font for the statictext self.st.SetFont(font) self.SetSize((350, 250)) self.SetTitle('wx.Button') self.Centre() def main(): app = wx.App() ex = Example(None) ex.Show() app.MainLoop() if __name__ == '__main__': main()",
"e": 26985,
"s": 26035,
"text": null
},
{
"code": null,
"e": 27000,
"s": 26985,
"text": "Output Window:"
},
{
"code": null,
"e": 27027,
"s": 27000,
"text": "Python wxPython-StaticText"
},
{
"code": null,
"e": 27038,
"s": 27027,
"text": "Python-gui"
},
{
"code": null,
"e": 27054,
"s": 27038,
"text": "Python-wxPython"
},
{
"code": null,
"e": 27061,
"s": 27054,
"text": "Python"
},
{
"code": null,
"e": 27159,
"s": 27061,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27177,
"s": 27159,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27209,
"s": 27177,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27244,
"s": 27209,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 27286,
"s": 27244,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27312,
"s": 27286,
"text": "Python String | replace()"
},
{
"code": null,
"e": 27356,
"s": 27312,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 27385,
"s": 27356,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 27421,
"s": 27385,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 27463,
"s": 27421,
"text": "Check if element exists in list in Python"
}
] |
HTML | DOM Video playbackRate Property - GeeksforGeeks | 18 Nov, 2021
The Video playbackRate property in HTML DOM is used to set or return the current playback speed of the video. The video playbackRate property returns a number which represents the current playback speed.
Syntax:
It returns the Video playbackRate property.videoObject.playbackRate
videoObject.playbackRate
It is used to set the Video playbackRate property.videoObject.playbackRate = playbackspeed
videoObject.playbackRate = playbackspeed
Property Values: It contains single value playbackspeed which specifies the default playback speed of the video. The available options are:
1.0 is normal speed.
0.5 is half speed.
2.0 is double speed.
-1.0 is backwards, normal speed.
-0.5 is backwards, half speed.
Return Values: It returns a Number that represents the current playback speed
Below program illustrates the Video playbackRate property in HTML DOM:
Example: This example sets the video playing speed to double.
<!DOCTYPE html><html> <head> <title> HTML DOM Video playbackRate Property </title></head> <body style="text-align:center;"> <h1 style="color:greenl"> GeeksforGeeks </h1> <h2 style="font-family: Impact;"> Video PlaybackRate Property </h2><br> <video id="Test_Video" width="360" height="240" controls> <source src="samplevideo.mp4" type="video/mp4"> <source src="movie.ogg" type="video/ogg"> </video> <p> For returning the playback speed of the video, double click the "Return Playback Speed" button. </p> <button ondblclick="My_VideoRate()" type="button"> Return Playback Speed </button> <p> For changing the playback speed of the video by default, double click the "Change Playback Speed" button. </p> <button ondblclick="Set_VideoRate()" type="button"> Change Playback Speed </button> <script> var v = document.getElementById("Test_Video"); function My_VideoRate() { alert(v.playbackRate); } function Set_VideoRate() { v.playbackRate = 2; } </script></body> </html>
Output:
After loading the code:
Initial Playback Rate:
Updated Playback Rate:
Supported Browsers: The browser supported by Video playbackRate property are listed below:
Google Chrome
Internet Explorer 9.0/li>
Firefox
Opera
Apple Safari
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
hritikbhatnagar2182
HTML-DOM
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
REST API (Introduction)
How to Insert Form Data into Database using PHP ?
CSS to put icon inside an input element in a form
Types of CSS (Cascading Style Sheet)
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript | [
{
"code": null,
"e": 26302,
"s": 26274,
"text": "\n18 Nov, 2021"
},
{
"code": null,
"e": 26506,
"s": 26302,
"text": "The Video playbackRate property in HTML DOM is used to set or return the current playback speed of the video. The video playbackRate property returns a number which represents the current playback speed."
},
{
"code": null,
"e": 26514,
"s": 26506,
"text": "Syntax:"
},
{
"code": null,
"e": 26582,
"s": 26514,
"text": "It returns the Video playbackRate property.videoObject.playbackRate"
},
{
"code": null,
"e": 26607,
"s": 26582,
"text": "videoObject.playbackRate"
},
{
"code": null,
"e": 26698,
"s": 26607,
"text": "It is used to set the Video playbackRate property.videoObject.playbackRate = playbackspeed"
},
{
"code": null,
"e": 26739,
"s": 26698,
"text": "videoObject.playbackRate = playbackspeed"
},
{
"code": null,
"e": 26879,
"s": 26739,
"text": "Property Values: It contains single value playbackspeed which specifies the default playback speed of the video. The available options are:"
},
{
"code": null,
"e": 26900,
"s": 26879,
"text": "1.0 is normal speed."
},
{
"code": null,
"e": 26919,
"s": 26900,
"text": "0.5 is half speed."
},
{
"code": null,
"e": 26940,
"s": 26919,
"text": "2.0 is double speed."
},
{
"code": null,
"e": 26973,
"s": 26940,
"text": "-1.0 is backwards, normal speed."
},
{
"code": null,
"e": 27004,
"s": 26973,
"text": "-0.5 is backwards, half speed."
},
{
"code": null,
"e": 27082,
"s": 27004,
"text": "Return Values: It returns a Number that represents the current playback speed"
},
{
"code": null,
"e": 27153,
"s": 27082,
"text": "Below program illustrates the Video playbackRate property in HTML DOM:"
},
{
"code": null,
"e": 27215,
"s": 27153,
"text": "Example: This example sets the video playing speed to double."
},
{
"code": "<!DOCTYPE html><html> <head> <title> HTML DOM Video playbackRate Property </title></head> <body style=\"text-align:center;\"> <h1 style=\"color:greenl\"> GeeksforGeeks </h1> <h2 style=\"font-family: Impact;\"> Video PlaybackRate Property </h2><br> <video id=\"Test_Video\" width=\"360\" height=\"240\" controls> <source src=\"samplevideo.mp4\" type=\"video/mp4\"> <source src=\"movie.ogg\" type=\"video/ogg\"> </video> <p> For returning the playback speed of the video, double click the \"Return Playback Speed\" button. </p> <button ondblclick=\"My_VideoRate()\" type=\"button\"> Return Playback Speed </button> <p> For changing the playback speed of the video by default, double click the \"Change Playback Speed\" button. </p> <button ondblclick=\"Set_VideoRate()\" type=\"button\"> Change Playback Speed </button> <script> var v = document.getElementById(\"Test_Video\"); function My_VideoRate() { alert(v.playbackRate); } function Set_VideoRate() { v.playbackRate = 2; } </script></body> </html> ",
"e": 28508,
"s": 27215,
"text": null
},
{
"code": null,
"e": 28516,
"s": 28508,
"text": "Output:"
},
{
"code": null,
"e": 28540,
"s": 28516,
"text": "After loading the code:"
},
{
"code": null,
"e": 28563,
"s": 28540,
"text": "Initial Playback Rate:"
},
{
"code": null,
"e": 28586,
"s": 28563,
"text": "Updated Playback Rate:"
},
{
"code": null,
"e": 28677,
"s": 28586,
"text": "Supported Browsers: The browser supported by Video playbackRate property are listed below:"
},
{
"code": null,
"e": 28691,
"s": 28677,
"text": "Google Chrome"
},
{
"code": null,
"e": 28717,
"s": 28691,
"text": "Internet Explorer 9.0/li>"
},
{
"code": null,
"e": 28725,
"s": 28717,
"text": "Firefox"
},
{
"code": null,
"e": 28731,
"s": 28725,
"text": "Opera"
},
{
"code": null,
"e": 28744,
"s": 28731,
"text": "Apple Safari"
},
{
"code": null,
"e": 28881,
"s": 28744,
"text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course."
},
{
"code": null,
"e": 28901,
"s": 28881,
"text": "hritikbhatnagar2182"
},
{
"code": null,
"e": 28910,
"s": 28901,
"text": "HTML-DOM"
},
{
"code": null,
"e": 28915,
"s": 28910,
"text": "HTML"
},
{
"code": null,
"e": 28932,
"s": 28915,
"text": "Web Technologies"
},
{
"code": null,
"e": 28937,
"s": 28932,
"text": "HTML"
},
{
"code": null,
"e": 29035,
"s": 28937,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29083,
"s": 29035,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 29107,
"s": 29083,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 29157,
"s": 29107,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 29207,
"s": 29157,
"text": "CSS to put icon inside an input element in a form"
},
{
"code": null,
"e": 29244,
"s": 29207,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 29284,
"s": 29244,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29317,
"s": 29284,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 29362,
"s": 29317,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 29405,
"s": 29362,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
C/C++ Preprocessor directives | Set 2 | 26 Apr, 2022
C/C++ Preprocessor directives basics Preprocessor directives: In almost every program we come across in C/C++, we see a few lines at the top of the program preceded by a hash (#) sign. These lines are preprocessed by the compiler before actual compilation begins. The end of these lines are identified by the newline character ‘\n’ , no semicolon ‘;’ is needed to terminate these lines. Preprocessor directives are mostly used in defining macros, evaluating conditional statements, source file inclusion, pragma directive, line control, error detection etc. In this post, we will discuss about some more types of preprocessor directives given below:
Conditional CompilationLine controlError directive
Conditional Compilation
Line control
Error directive
Let us now have a look about each one of these directives in details:
Conditional Compilation: Conditional Compilation directives help to compile a specific portion of the program or let us skip compilation of some specific part of the program based on some conditions. In our previous article, we have discussed about two such directives ‘ifdef‘ and ‘endif‘. In this post we will discuss #ifndef, #if, #else and #elif.#ifdef: This directive is the simplest conditional directive. This block is called a conditional group. The controlled text will get included in the preprocessor output if the macroname is defined. The controlled text inside a conditional will embrace preprocessing directives. They are executed only if the conditional succeeds. You can nest these in multiple layers, but they must be completely nested. In other words, ‘#endif’ always matches the nearest ‘#ifdef’ (or ‘#ifndef’, or ‘#if’). Also, you can’t begin a conditional group in one file and finish it in another. Syntax:
#ifdef: This directive is the simplest conditional directive. This block is called a conditional group. The controlled text will get included in the preprocessor output if the macroname is defined. The controlled text inside a conditional will embrace preprocessing directives. They are executed only if the conditional succeeds. You can nest these in multiple layers, but they must be completely nested. In other words, ‘#endif’ always matches the nearest ‘#ifdef’ (or ‘#ifndef’, or ‘#if’). Also, you can’t begin a conditional group in one file and finish it in another. Syntax:
#ifdef: This directive is the simplest conditional directive. This block is called a conditional group. The controlled text will get included in the preprocessor output if the macroname is defined. The controlled text inside a conditional will embrace preprocessing directives. They are executed only if the conditional succeeds. You can nest these in multiple layers, but they must be completely nested. In other words, ‘#endif’ always matches the nearest ‘#ifdef’ (or ‘#ifndef’, or ‘#if’). Also, you can’t begin a conditional group in one file and finish it in another. Syntax:
#ifdef MACRO
controlled text
#endif /* macroname */
#ifndef: We know that the in #ifdef directive if the macroname is defined, then the block of statements following the #ifdef directive will execute normally but if it is not defined, the compiler will simply skip this block of statements. The #ifndef directive is simply opposite to that of the #ifdef directive. In case of #ifndef , the block of statements between #ifndef and #endif will be executed only if the macro or the identifier with #ifndef is not defined. Syntax :
#ifndef: We know that the in #ifdef directive if the macroname is defined, then the block of statements following the #ifdef directive will execute normally but if it is not defined, the compiler will simply skip this block of statements. The #ifndef directive is simply opposite to that of the #ifdef directive. In case of #ifndef , the block of statements between #ifndef and #endif will be executed only if the macro or the identifier with #ifndef is not defined. Syntax :
ifndef macro_name
statement1;
statement2;
statement3;
.
.
.
statementN;
endif
If the macro with name as ‘macroname‘ is not defined using the #define directive then only the block of statements will execute.#if, #else and #elif: These directives works together and control compilation of portions of the program using some conditions. If the condition with the #if directive evaluates to a non zero value, then the group of line immediately after the #if directive will be executed otherwise if the condition with the #elif directive evaluates to a non zero value, then the group of line immediately after the #elif directive will be executed else the lines after #else directive will be executed. Syntax:
If the macro with name as ‘macroname‘ is not defined using the #define directive then only the block of statements will execute.
#if, #else and #elif: These directives works together and control compilation of portions of the program using some conditions. If the condition with the #if directive evaluates to a non zero value, then the group of line immediately after the #if directive will be executed otherwise if the condition with the #elif directive evaluates to a non zero value, then the group of line immediately after the #elif directive will be executed else the lines after #else directive will be executed. Syntax:
#if macro_condition
statements
#elif macro_condition
statements
#else
statements
#endif
Example:
Example:
CPP
#include<iostream> #define gfg 7 #if gfg > 200 #undef gfg #define gfg 200#elif gfg < 50 #undef gfg #define gfg 50#else #undef gfg #define gfg 100#endif int main(){ std::cout << gfg; // gfg = 50}
Output:
Output:
50
Notice how the entire structure of #if, #elif and #else chained directives ends with #endif.
Notice how the entire structure of #if, #elif and #else chained directives ends with #endif.
Line control ( #line ): Whenever we compile a program, there are chances of occurrence of some error in the program. Whenever compiler identifies error in the program it provides us with the filename in which error is found along with the list of lines and with the exact line numbers where the error is. This makes easy for us to find and rectify error. However we can control what information should the compiler provide during errors in compilation using the #line directive. Syntax:
#line number "filename"
number – line number that will be assigned to the next code line. The line numbers of successive lines will be increased one by one from this point on. “filename” – optional parameter that allows to redefine the file name that will be shown.
Error directive ( #error ): This directive aborts the compilation process when it is found in the program during compilation and produces an error which is optional and can be specified as a parameter. Syntax:
#error optional_error
Here, optional_error is any error specified by the user which will be shown when this derective is found in the program. Example:
CPP
#ifndef GeeksforGeeks#error GeeksforGeeks not found !#endif
Output:
error: #error GeeksforGeeks not found !
References:
ppd_better_practice_cs.auckland.ac.nz
http://www.cplusplus.com/doc/tutorial/preprocessor/
This article is contributed by Amartya Ranjan Saikia and Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
RishabhPrabhu
surinderdawra388
C Basics
C-Macro & Preprocessor
cpp-macros
Macro & Preprocessor
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n26 Apr, 2022"
},
{
"code": null,
"e": 702,
"s": 52,
"text": "C/C++ Preprocessor directives basics Preprocessor directives: In almost every program we come across in C/C++, we see a few lines at the top of the program preceded by a hash (#) sign. These lines are preprocessed by the compiler before actual compilation begins. The end of these lines are identified by the newline character ‘\\n’ , no semicolon ‘;’ is needed to terminate these lines. Preprocessor directives are mostly used in defining macros, evaluating conditional statements, source file inclusion, pragma directive, line control, error detection etc. In this post, we will discuss about some more types of preprocessor directives given below:"
},
{
"code": null,
"e": 753,
"s": 702,
"text": "Conditional CompilationLine controlError directive"
},
{
"code": null,
"e": 777,
"s": 753,
"text": "Conditional Compilation"
},
{
"code": null,
"e": 790,
"s": 777,
"text": "Line control"
},
{
"code": null,
"e": 806,
"s": 790,
"text": "Error directive"
},
{
"code": null,
"e": 876,
"s": 806,
"text": "Let us now have a look about each one of these directives in details:"
},
{
"code": null,
"e": 1805,
"s": 876,
"text": "Conditional Compilation: Conditional Compilation directives help to compile a specific portion of the program or let us skip compilation of some specific part of the program based on some conditions. In our previous article, we have discussed about two such directives ‘ifdef‘ and ‘endif‘. In this post we will discuss #ifndef, #if, #else and #elif.#ifdef: This directive is the simplest conditional directive. This block is called a conditional group. The controlled text will get included in the preprocessor output if the macroname is defined. The controlled text inside a conditional will embrace preprocessing directives. They are executed only if the conditional succeeds. You can nest these in multiple layers, but they must be completely nested. In other words, ‘#endif’ always matches the nearest ‘#ifdef’ (or ‘#ifndef’, or ‘#if’). Also, you can’t begin a conditional group in one file and finish it in another. Syntax:"
},
{
"code": null,
"e": 2385,
"s": 1805,
"text": "#ifdef: This directive is the simplest conditional directive. This block is called a conditional group. The controlled text will get included in the preprocessor output if the macroname is defined. The controlled text inside a conditional will embrace preprocessing directives. They are executed only if the conditional succeeds. You can nest these in multiple layers, but they must be completely nested. In other words, ‘#endif’ always matches the nearest ‘#ifdef’ (or ‘#ifndef’, or ‘#if’). Also, you can’t begin a conditional group in one file and finish it in another. Syntax:"
},
{
"code": null,
"e": 2965,
"s": 2385,
"text": "#ifdef: This directive is the simplest conditional directive. This block is called a conditional group. The controlled text will get included in the preprocessor output if the macroname is defined. The controlled text inside a conditional will embrace preprocessing directives. They are executed only if the conditional succeeds. You can nest these in multiple layers, but they must be completely nested. In other words, ‘#endif’ always matches the nearest ‘#ifdef’ (or ‘#ifndef’, or ‘#if’). Also, you can’t begin a conditional group in one file and finish it in another. Syntax:"
},
{
"code": null,
"e": 3021,
"s": 2965,
"text": "#ifdef MACRO\n controlled text\n#endif /* macroname */"
},
{
"code": null,
"e": 3497,
"s": 3021,
"text": "#ifndef: We know that the in #ifdef directive if the macroname is defined, then the block of statements following the #ifdef directive will execute normally but if it is not defined, the compiler will simply skip this block of statements. The #ifndef directive is simply opposite to that of the #ifdef directive. In case of #ifndef , the block of statements between #ifndef and #endif will be executed only if the macro or the identifier with #ifndef is not defined. Syntax :"
},
{
"code": null,
"e": 3973,
"s": 3497,
"text": "#ifndef: We know that the in #ifdef directive if the macroname is defined, then the block of statements following the #ifdef directive will execute normally but if it is not defined, the compiler will simply skip this block of statements. The #ifndef directive is simply opposite to that of the #ifdef directive. In case of #ifndef , the block of statements between #ifndef and #endif will be executed only if the macro or the identifier with #ifndef is not defined. Syntax :"
},
{
"code": null,
"e": 4079,
"s": 3973,
"text": "ifndef macro_name\n statement1;\n statement2;\n statement3;\n .\n .\n .\n statementN;\nendif"
},
{
"code": null,
"e": 4706,
"s": 4079,
"text": "If the macro with name as ‘macroname‘ is not defined using the #define directive then only the block of statements will execute.#if, #else and #elif: These directives works together and control compilation of portions of the program using some conditions. If the condition with the #if directive evaluates to a non zero value, then the group of line immediately after the #if directive will be executed otherwise if the condition with the #elif directive evaluates to a non zero value, then the group of line immediately after the #elif directive will be executed else the lines after #else directive will be executed. Syntax:"
},
{
"code": null,
"e": 4835,
"s": 4706,
"text": "If the macro with name as ‘macroname‘ is not defined using the #define directive then only the block of statements will execute."
},
{
"code": null,
"e": 5334,
"s": 4835,
"text": "#if, #else and #elif: These directives works together and control compilation of portions of the program using some conditions. If the condition with the #if directive evaluates to a non zero value, then the group of line immediately after the #if directive will be executed otherwise if the condition with the #elif directive evaluates to a non zero value, then the group of line immediately after the #elif directive will be executed else the lines after #else directive will be executed. Syntax:"
},
{
"code": null,
"e": 5431,
"s": 5334,
"text": "#if macro_condition\n statements\n#elif macro_condition\n statements\n#else\n statements\n#endif"
},
{
"code": null,
"e": 5441,
"s": 5431,
"text": "Example: "
},
{
"code": null,
"e": 5451,
"s": 5441,
"text": "Example: "
},
{
"code": null,
"e": 5455,
"s": 5451,
"text": "CPP"
},
{
"code": "#include<iostream> #define gfg 7 #if gfg > 200 #undef gfg #define gfg 200#elif gfg < 50 #undef gfg #define gfg 50#else #undef gfg #define gfg 100#endif int main(){ std::cout << gfg; // gfg = 50} ",
"e": 5670,
"s": 5455,
"text": null
},
{
"code": null,
"e": 5678,
"s": 5670,
"text": "Output:"
},
{
"code": null,
"e": 5686,
"s": 5678,
"text": "Output:"
},
{
"code": null,
"e": 5689,
"s": 5686,
"text": "50"
},
{
"code": null,
"e": 5782,
"s": 5689,
"text": "Notice how the entire structure of #if, #elif and #else chained directives ends with #endif."
},
{
"code": null,
"e": 5875,
"s": 5782,
"text": "Notice how the entire structure of #if, #elif and #else chained directives ends with #endif."
},
{
"code": null,
"e": 6362,
"s": 5875,
"text": "Line control ( #line ): Whenever we compile a program, there are chances of occurrence of some error in the program. Whenever compiler identifies error in the program it provides us with the filename in which error is found along with the list of lines and with the exact line numbers where the error is. This makes easy for us to find and rectify error. However we can control what information should the compiler provide during errors in compilation using the #line directive. Syntax:"
},
{
"code": null,
"e": 6386,
"s": 6362,
"text": "#line number \"filename\""
},
{
"code": null,
"e": 6628,
"s": 6386,
"text": "number – line number that will be assigned to the next code line. The line numbers of successive lines will be increased one by one from this point on. “filename” – optional parameter that allows to redefine the file name that will be shown."
},
{
"code": null,
"e": 6838,
"s": 6628,
"text": "Error directive ( #error ): This directive aborts the compilation process when it is found in the program during compilation and produces an error which is optional and can be specified as a parameter. Syntax:"
},
{
"code": null,
"e": 6860,
"s": 6838,
"text": "#error optional_error"
},
{
"code": null,
"e": 6991,
"s": 6860,
"text": "Here, optional_error is any error specified by the user which will be shown when this derective is found in the program. Example: "
},
{
"code": null,
"e": 6995,
"s": 6991,
"text": "CPP"
},
{
"code": "#ifndef GeeksforGeeks#error GeeksforGeeks not found !#endif ",
"e": 7056,
"s": 6995,
"text": null
},
{
"code": null,
"e": 7064,
"s": 7056,
"text": "Output:"
},
{
"code": null,
"e": 7104,
"s": 7064,
"text": "error: #error GeeksforGeeks not found !"
},
{
"code": null,
"e": 7116,
"s": 7104,
"text": "References:"
},
{
"code": null,
"e": 7154,
"s": 7116,
"text": "ppd_better_practice_cs.auckland.ac.nz"
},
{
"code": null,
"e": 7206,
"s": 7154,
"text": "http://www.cplusplus.com/doc/tutorial/preprocessor/"
},
{
"code": null,
"e": 7654,
"s": 7206,
"text": "This article is contributed by Amartya Ranjan Saikia and Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 7668,
"s": 7654,
"text": "RishabhPrabhu"
},
{
"code": null,
"e": 7685,
"s": 7668,
"text": "surinderdawra388"
},
{
"code": null,
"e": 7694,
"s": 7685,
"text": "C Basics"
},
{
"code": null,
"e": 7717,
"s": 7694,
"text": "C-Macro & Preprocessor"
},
{
"code": null,
"e": 7728,
"s": 7717,
"text": "cpp-macros"
},
{
"code": null,
"e": 7749,
"s": 7728,
"text": "Macro & Preprocessor"
},
{
"code": null,
"e": 7760,
"s": 7749,
"text": "C Language"
},
{
"code": null,
"e": 7764,
"s": 7760,
"text": "C++"
},
{
"code": null,
"e": 7768,
"s": 7764,
"text": "CPP"
}
] |
ML | Hierarchical clustering (Agglomerative and Divisive clustering) | 06 Oct, 2021
In data mining and statistics, hierarchical clustering analysis is a method of cluster analysis that seeks to build a hierarchy of clusters i.e. tree-type structure based on the hierarchy.
Basically, there are two types of hierarchical cluster analysis strategies –
1. Agglomerative Clustering: Also known as bottom-up approach or hierarchical agglomerative clustering (HAC). A structure that is more informative than the unstructured set of clusters returned by flat clustering. This clustering algorithm does not require us to prespecify the number of clusters. Bottom-up algorithms treat each data as a singleton cluster at the outset and then successively agglomerates pairs of clusters until all clusters have been merged into a single cluster that contains all data.
Algorithm :
given a dataset (d1, d2, d3, ....dN) of size N
# compute the distance matrix
for i=1 to N:
# as the distance matrix is symmetric about
# the primary diagonal so we compute only lower
# part of the primary diagonal
for j=1 to i:
dis_mat[i][j] = distance[di, dj]
each data point is a singleton cluster
repeat
merge the two cluster having minimum distance
update the distance matrix
until only a single cluster remains
Python implementation of the above algorithm using the scikit-learn library:
Python3
from sklearn.cluster import AgglomerativeClusteringimport numpy as np # randomly chosen datasetX = np.array([[1, 2], [1, 4], [1, 0], [4, 2], [4, 4], [4, 0]]) # here we need to mention the number of clusters# otherwise the result will be a single cluster# containing all the dataclustering = AgglomerativeClustering(n_clusters = 2).fit(X) # print the class labelsprint(clustering.labels_)
Output :
[1, 1, 1, 0, 0, 0]
2. Divisive clustering: Also known as a top-down approach. This algorithm also does not require to prespecify the number of clusters. Top-down clustering requires a method for splitting a cluster that contains the whole data and proceeds by splitting clusters recursively until individual data have been split into singleton clusters.
Algorithm :
given a dataset (d1, d2, d3, ....dN) of size N
at the top we have all data in one cluster
the cluster is split using a flat clustering method eg. K-Means etc
repeat
choose the best cluster among all the clusters to split
split that cluster by the flat clustering algorithm
until each data is in its own singleton cluster
Hierarchical Agglomerative vs Divisive clustering –
Divisive clustering is more complex as compared to agglomerative clustering, as in the case of divisive clustering we need a flat clustering method as “subroutine” to split each cluster until we have each data having its own singleton cluster.
Divisive clustering is more efficient if we do not generate a complete hierarchy all the way down to individual data leaves. The time complexity of a naive agglomerative clustering is O(n3) because we exhaustively scan the N x N matrix dist_mat for the lowest distance in each of N-1 iterations. Using priority queue data structure we can reduce this complexity to O(n2logn). By using some more optimizations it can be brought down to O(n2). Whereas for divisive clustering given a fixed number of top levels, using an efficient flat algorithm like K-Means, divisive algorithms are linear in the number of patterns and clusters.
A divisive algorithm is also more accurate. Agglomerative clustering makes decisions by considering the local patterns or neighbor points without initially taking into account the global distribution of data. These early decisions cannot be undone. whereas divisive clustering takes into consideration the global distribution of data when making top-level partitioning decisions.
arorakashish0911
23603vaibhav2021
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n06 Oct, 2021"
},
{
"code": null,
"e": 242,
"s": 52,
"text": "In data mining and statistics, hierarchical clustering analysis is a method of cluster analysis that seeks to build a hierarchy of clusters i.e. tree-type structure based on the hierarchy. "
},
{
"code": null,
"e": 319,
"s": 242,
"text": "Basically, there are two types of hierarchical cluster analysis strategies –"
},
{
"code": null,
"e": 827,
"s": 319,
"text": "1. Agglomerative Clustering: Also known as bottom-up approach or hierarchical agglomerative clustering (HAC). A structure that is more informative than the unstructured set of clusters returned by flat clustering. This clustering algorithm does not require us to prespecify the number of clusters. Bottom-up algorithms treat each data as a singleton cluster at the outset and then successively agglomerates pairs of clusters until all clusters have been merged into a single cluster that contains all data. "
},
{
"code": null,
"e": 840,
"s": 827,
"text": "Algorithm : "
},
{
"code": null,
"e": 1284,
"s": 840,
"text": "given a dataset (d1, d2, d3, ....dN) of size N\n# compute the distance matrix\nfor i=1 to N:\n # as the distance matrix is symmetric about \n # the primary diagonal so we compute only lower \n # part of the primary diagonal \n for j=1 to i:\n dis_mat[i][j] = distance[di, dj] \neach data point is a singleton cluster\nrepeat\n merge the two cluster having minimum distance\n update the distance matrix\nuntil only a single cluster remains"
},
{
"code": null,
"e": 1362,
"s": 1284,
"text": "Python implementation of the above algorithm using the scikit-learn library: "
},
{
"code": null,
"e": 1370,
"s": 1362,
"text": "Python3"
},
{
"code": "from sklearn.cluster import AgglomerativeClusteringimport numpy as np # randomly chosen datasetX = np.array([[1, 2], [1, 4], [1, 0], [4, 2], [4, 4], [4, 0]]) # here we need to mention the number of clusters# otherwise the result will be a single cluster# containing all the dataclustering = AgglomerativeClustering(n_clusters = 2).fit(X) # print the class labelsprint(clustering.labels_)",
"e": 1771,
"s": 1370,
"text": null
},
{
"code": null,
"e": 1781,
"s": 1771,
"text": "Output : "
},
{
"code": null,
"e": 1800,
"s": 1781,
"text": "[1, 1, 1, 0, 0, 0]"
},
{
"code": null,
"e": 2135,
"s": 1800,
"text": "2. Divisive clustering: Also known as a top-down approach. This algorithm also does not require to prespecify the number of clusters. Top-down clustering requires a method for splitting a cluster that contains the whole data and proceeds by splitting clusters recursively until individual data have been split into singleton clusters."
},
{
"code": null,
"e": 2148,
"s": 2135,
"text": "Algorithm : "
},
{
"code": null,
"e": 2469,
"s": 2148,
"text": "given a dataset (d1, d2, d3, ....dN) of size N\nat the top we have all data in one cluster\nthe cluster is split using a flat clustering method eg. K-Means etc\nrepeat\nchoose the best cluster among all the clusters to split\nsplit that cluster by the flat clustering algorithm\nuntil each data is in its own singleton cluster"
},
{
"code": null,
"e": 2522,
"s": 2469,
"text": "Hierarchical Agglomerative vs Divisive clustering – "
},
{
"code": null,
"e": 2766,
"s": 2522,
"text": "Divisive clustering is more complex as compared to agglomerative clustering, as in the case of divisive clustering we need a flat clustering method as “subroutine” to split each cluster until we have each data having its own singleton cluster."
},
{
"code": null,
"e": 3395,
"s": 2766,
"text": "Divisive clustering is more efficient if we do not generate a complete hierarchy all the way down to individual data leaves. The time complexity of a naive agglomerative clustering is O(n3) because we exhaustively scan the N x N matrix dist_mat for the lowest distance in each of N-1 iterations. Using priority queue data structure we can reduce this complexity to O(n2logn). By using some more optimizations it can be brought down to O(n2). Whereas for divisive clustering given a fixed number of top levels, using an efficient flat algorithm like K-Means, divisive algorithms are linear in the number of patterns and clusters."
},
{
"code": null,
"e": 3775,
"s": 3395,
"text": "A divisive algorithm is also more accurate. Agglomerative clustering makes decisions by considering the local patterns or neighbor points without initially taking into account the global distribution of data. These early decisions cannot be undone. whereas divisive clustering takes into consideration the global distribution of data when making top-level partitioning decisions."
},
{
"code": null,
"e": 3794,
"s": 3777,
"text": "arorakashish0911"
},
{
"code": null,
"e": 3811,
"s": 3794,
"text": "23603vaibhav2021"
},
{
"code": null,
"e": 3828,
"s": 3811,
"text": "Machine Learning"
},
{
"code": null,
"e": 3835,
"s": 3828,
"text": "Python"
},
{
"code": null,
"e": 3852,
"s": 3835,
"text": "Machine Learning"
}
] |
TimeUnit toMillis() method in Java with Examples | 30 Oct, 2018
The toMillis() method of TimeUnit Class is used to get the time represented by the TimeUnit object, as the number of Seconds, since midnight UTC on the 1st January 1970.
Syntax:
public long toMillis(long duration)
Parameters: This method accepts a mandatory parameter duration which is the duration in milliSeconds.
Return Value: This method returns the converted duration as Seconds.
Below programt illustrate the implementation of TimeUnit toMillis() method:
Program 1:
// Java program to demonstrate// toMillis() method of TimeUnit Class import java.util.concurrent.*;import java.util.Date; class GFG { public static void main(String args[]) { // Get current time in seconds long timeInSec = (new Date().getTime()) / 1000; // Create a TimeUnit object TimeUnit time = TimeUnit.SECONDS; // Convert seconds to milliSeconds // using toMillis() method System.out.println("Time " + timeInSec + " Seconds in MilliSeconds = " + time.toMillis(timeInSec)); }}
Time 1539585757 Seconds in MilliSeconds = 1539585757000
Program 2:
// Java program to demonstrate// toMillis() method of TimeUnit Class import java.util.concurrent.*;import java.util.Calendar; class GFG { public static void main(String args[]) { // Get current time in milliseconds long timeInSec = (Calendar .getInstance() .getTimeInMillis()) / 1000; // Create a TimeUnit object TimeUnit time = TimeUnit.SECONDS; // Convert seconds to milliSeconds // using toMillis() method System.out.println("Time " + timeInSec + " Seconds in MilliSeconds = " + time.toMillis(timeInSec)); }}
Time 1539585759 Seconds in MilliSeconds = 1539585759000
Java - util package
Java-Date-Time
Java-Functions
Java-TimeUnit
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 Oct, 2018"
},
{
"code": null,
"e": 198,
"s": 28,
"text": "The toMillis() method of TimeUnit Class is used to get the time represented by the TimeUnit object, as the number of Seconds, since midnight UTC on the 1st January 1970."
},
{
"code": null,
"e": 206,
"s": 198,
"text": "Syntax:"
},
{
"code": null,
"e": 242,
"s": 206,
"text": "public long toMillis(long duration)"
},
{
"code": null,
"e": 344,
"s": 242,
"text": "Parameters: This method accepts a mandatory parameter duration which is the duration in milliSeconds."
},
{
"code": null,
"e": 413,
"s": 344,
"text": "Return Value: This method returns the converted duration as Seconds."
},
{
"code": null,
"e": 489,
"s": 413,
"text": "Below programt illustrate the implementation of TimeUnit toMillis() method:"
},
{
"code": null,
"e": 500,
"s": 489,
"text": "Program 1:"
},
{
"code": "// Java program to demonstrate// toMillis() method of TimeUnit Class import java.util.concurrent.*;import java.util.Date; class GFG { public static void main(String args[]) { // Get current time in seconds long timeInSec = (new Date().getTime()) / 1000; // Create a TimeUnit object TimeUnit time = TimeUnit.SECONDS; // Convert seconds to milliSeconds // using toMillis() method System.out.println(\"Time \" + timeInSec + \" Seconds in MilliSeconds = \" + time.toMillis(timeInSec)); }}",
"e": 1097,
"s": 500,
"text": null
},
{
"code": null,
"e": 1154,
"s": 1097,
"text": "Time 1539585757 Seconds in MilliSeconds = 1539585757000\n"
},
{
"code": null,
"e": 1165,
"s": 1154,
"text": "Program 2:"
},
{
"code": "// Java program to demonstrate// toMillis() method of TimeUnit Class import java.util.concurrent.*;import java.util.Calendar; class GFG { public static void main(String args[]) { // Get current time in milliseconds long timeInSec = (Calendar .getInstance() .getTimeInMillis()) / 1000; // Create a TimeUnit object TimeUnit time = TimeUnit.SECONDS; // Convert seconds to milliSeconds // using toMillis() method System.out.println(\"Time \" + timeInSec + \" Seconds in MilliSeconds = \" + time.toMillis(timeInSec)); }}",
"e": 1875,
"s": 1165,
"text": null
},
{
"code": null,
"e": 1932,
"s": 1875,
"text": "Time 1539585759 Seconds in MilliSeconds = 1539585759000\n"
},
{
"code": null,
"e": 1952,
"s": 1932,
"text": "Java - util package"
},
{
"code": null,
"e": 1967,
"s": 1952,
"text": "Java-Date-Time"
},
{
"code": null,
"e": 1982,
"s": 1967,
"text": "Java-Functions"
},
{
"code": null,
"e": 1996,
"s": 1982,
"text": "Java-TimeUnit"
},
{
"code": null,
"e": 2001,
"s": 1996,
"text": "Java"
},
{
"code": null,
"e": 2006,
"s": 2001,
"text": "Java"
}
] |
HashMap get() Method in Java | 11 May, 2022
The java.util.HashMap.get() method of HashMap class is used to retrieve or fetch the value mapped by a particular key mentioned in the parameter. It returns NULL when the map contains no such mapping for the key.
Syntax:
Hash_Map.get(Object key_element)
Parameter: The method takes one parameter key_element of object type and refers to the key whose associated value is supposed to be fetched.
Return Value: The method returns the value associated with the key_element in the parameter.
Below programs illustrates the working of java.util.HashMap.get() method:Program 1: Mapping String Values to Integer Keys.
// Java code to illustrate the get() methodimport java.util.*; public class Hash_Map_Demo { public static void main(String[] args) { // Creating an empty HashMap HashMap<Integer, String> hash_map = new HashMap<Integer, String>(); // Mapping string values to int keys hash_map.put(10, "Geeks"); hash_map.put(15, "4"); hash_map.put(20, "Geeks"); hash_map.put(25, "Welcomes"); hash_map.put(30, "You"); // Displaying the HashMap System.out.println("Initial Mappings are: " + hash_map); // Getting the value of 25 System.out.println("The Value is: " + hash_map.get(25)); // Getting the value of 10 System.out.println("The Value is: " + hash_map.get(10)); }}
Initial Mappings are: {20=Geeks, 25=Welcomes, 10=Geeks, 30=You, 15=4}
The Value is: Welcomes
The Value is: Geeks
Program 2: Mapping Integer Values to String Keys.
// Java code to illustrate the get() methodimport java.util.*; public class Hash_Map_Demo { public static void main(String[] args) { // Creating an empty HashMap HashMap<String, Integer> hash_map = new HashMap<String, Integer>(); // Mapping int values to string keys hash_map.put("Geeks", 10); hash_map.put("4", 15); hash_map.put("Geeks", 20); hash_map.put("Welcomes", 25); hash_map.put("You", 30); // Displaying the HashMap System.out.println("Initial Mappings are: " + hash_map); // Getting the value of "Geeks" System.out.println("The Value is: " + hash_map.get("Geeks")); // Getting the value of "You" System.out.println("The Value is: " + hash_map.get("You")); }}
Initial Mappings are: {4=15, Geeks=20, You=30, Welcomes=25}
The Value is: 20
The Value is: 30
Note: The same operation can be performed with any type of Mappings with variation and combination of different data types.
Java - util package
Java-Collections
Java-Functions
Java-HashMap
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Interfaces in Java
Multidimensional Arrays in Java
Collections in Java
ArrayList in Java
Multithreading in Java
Stream In Java
Introduction to Java
Constructors in Java
Initializing a List in Java
Initialize an ArrayList in Java | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n11 May, 2022"
},
{
"code": null,
"e": 265,
"s": 52,
"text": "The java.util.HashMap.get() method of HashMap class is used to retrieve or fetch the value mapped by a particular key mentioned in the parameter. It returns NULL when the map contains no such mapping for the key."
},
{
"code": null,
"e": 273,
"s": 265,
"text": "Syntax:"
},
{
"code": null,
"e": 306,
"s": 273,
"text": "Hash_Map.get(Object key_element)"
},
{
"code": null,
"e": 447,
"s": 306,
"text": "Parameter: The method takes one parameter key_element of object type and refers to the key whose associated value is supposed to be fetched."
},
{
"code": null,
"e": 540,
"s": 447,
"text": "Return Value: The method returns the value associated with the key_element in the parameter."
},
{
"code": null,
"e": 663,
"s": 540,
"text": "Below programs illustrates the working of java.util.HashMap.get() method:Program 1: Mapping String Values to Integer Keys."
},
{
"code": "// Java code to illustrate the get() methodimport java.util.*; public class Hash_Map_Demo { public static void main(String[] args) { // Creating an empty HashMap HashMap<Integer, String> hash_map = new HashMap<Integer, String>(); // Mapping string values to int keys hash_map.put(10, \"Geeks\"); hash_map.put(15, \"4\"); hash_map.put(20, \"Geeks\"); hash_map.put(25, \"Welcomes\"); hash_map.put(30, \"You\"); // Displaying the HashMap System.out.println(\"Initial Mappings are: \" + hash_map); // Getting the value of 25 System.out.println(\"The Value is: \" + hash_map.get(25)); // Getting the value of 10 System.out.println(\"The Value is: \" + hash_map.get(10)); }}",
"e": 1434,
"s": 663,
"text": null
},
{
"code": null,
"e": 1548,
"s": 1434,
"text": "Initial Mappings are: {20=Geeks, 25=Welcomes, 10=Geeks, 30=You, 15=4}\nThe Value is: Welcomes\nThe Value is: Geeks\n"
},
{
"code": null,
"e": 1598,
"s": 1548,
"text": "Program 2: Mapping Integer Values to String Keys."
},
{
"code": "// Java code to illustrate the get() methodimport java.util.*; public class Hash_Map_Demo { public static void main(String[] args) { // Creating an empty HashMap HashMap<String, Integer> hash_map = new HashMap<String, Integer>(); // Mapping int values to string keys hash_map.put(\"Geeks\", 10); hash_map.put(\"4\", 15); hash_map.put(\"Geeks\", 20); hash_map.put(\"Welcomes\", 25); hash_map.put(\"You\", 30); // Displaying the HashMap System.out.println(\"Initial Mappings are: \" + hash_map); // Getting the value of \"Geeks\" System.out.println(\"The Value is: \" + hash_map.get(\"Geeks\")); // Getting the value of \"You\" System.out.println(\"The Value is: \" + hash_map.get(\"You\")); }}",
"e": 2385,
"s": 1598,
"text": null
},
{
"code": null,
"e": 2480,
"s": 2385,
"text": "Initial Mappings are: {4=15, Geeks=20, You=30, Welcomes=25}\nThe Value is: 20\nThe Value is: 30\n"
},
{
"code": null,
"e": 2604,
"s": 2480,
"text": "Note: The same operation can be performed with any type of Mappings with variation and combination of different data types."
},
{
"code": null,
"e": 2624,
"s": 2604,
"text": "Java - util package"
},
{
"code": null,
"e": 2641,
"s": 2624,
"text": "Java-Collections"
},
{
"code": null,
"e": 2656,
"s": 2641,
"text": "Java-Functions"
},
{
"code": null,
"e": 2669,
"s": 2656,
"text": "Java-HashMap"
},
{
"code": null,
"e": 2674,
"s": 2669,
"text": "Java"
},
{
"code": null,
"e": 2679,
"s": 2674,
"text": "Java"
},
{
"code": null,
"e": 2696,
"s": 2679,
"text": "Java-Collections"
},
{
"code": null,
"e": 2794,
"s": 2696,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2813,
"s": 2794,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 2845,
"s": 2813,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 2865,
"s": 2845,
"text": "Collections in Java"
},
{
"code": null,
"e": 2883,
"s": 2865,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 2906,
"s": 2883,
"text": "Multithreading in Java"
},
{
"code": null,
"e": 2921,
"s": 2906,
"text": "Stream In Java"
},
{
"code": null,
"e": 2942,
"s": 2921,
"text": "Introduction to Java"
},
{
"code": null,
"e": 2963,
"s": 2942,
"text": "Constructors in Java"
},
{
"code": null,
"e": 2991,
"s": 2963,
"text": "Initializing a List in Java"
}
] |
Man in the Middle attack in Diffie-Hellman Key Exchange | 18 Jul, 2021
Prerequisite: Diffie-Hellman Algorithm
Diffie-Hellman Key Exchange algorithm is an advanced cryptographic method used to establish a shared secret (or shared secret key) that can be used to perform secret communication on a public network between Alice and Bob while preventing Eve (eavesdropper), who can eavesdrop on all their communication, from learning the generated secret.
The key exchange procedure has two steps :
One-time setup: We define some public parameters that are used by everyone forever.Protocol: To generate new secret keys, run a two-message key exchange protocol. This process is done using some simple algebra, prime numbers, and properties of modular arithmetic.
One-time setup: We define some public parameters that are used by everyone forever.
Protocol: To generate new secret keys, run a two-message key exchange protocol. This process is done using some simple algebra, prime numbers, and properties of modular arithmetic.
Let’s assume that the eavesdropper EVE knows the public values p and g like everyone else, and from her eavesdropping, she learns the values exchanged by Alice and Bob, ga mod p and gb mod p, as well. With all her knowledge, she still can’t compute the secret key S, as it turns out, if p and g are properly chosen, it’s very, very hard for her to do.
For instance, you could brute force it and try all the options, but The calculations (mod p) make the discrete log calculation super slow when the numbers are large. If p and g have thousands of bits, then the best-known algorithms to compute discrete logs, although faster than plain brute force, will still take millions of years to compute.
Even with its immunity to brute force, it’s vulnerable to MITM (man in the middle position).
A malicious Malory, that has a MitM (man in the middle) position, can manipulate the communications between Alice and Bob, and break the security of the key exchange.
Step by Step explanation of this process:
Step 1: Selected public numbers p and g, p is a prime number, called the “modulus” and g is called the base.
Step 2: Selecting private numbers.
let Alice pick a private random number a and let Bob pick a private random number b, Malory picks 2 random numbers c and d.
Step 3: Intercepting public values,
Malory intercepts Alice’s public value (ga(mod p)), block it from reaching Bob, and instead sends Bob her own public value (gc(modp)) and Malory intercepts Bob’s public value (gb(mod p)), block it from reaching Alice, and instead sends Alice her own public value (gd (modp))
Step 4: Computing secret key
Alice will compute a key S1=gda(mod p), and Bob will compute a different key, S2=gcb(mod p)
Step 5: If Alice uses S1 as a key to encrypt a later message to Bob, Malory can decrypt it, re-encrypt it using S2, and send it to Bob. Bob and Alice won’t notice any problem and may assume their communication is encrypted, but in reality, Malory can decrypt, read, modify, and then re-encrypt all their conversations.
Below is the implementation:
Python3
import random # public keys are taken# p is a prime number# g is a primitive root of pp = int(input('Enter a prime number : '))g = int(input('Enter a number : ')) class A: def __init__(self): # Generating a random private number selected by alice self.n = random.randint(1, p) def publish(self): # generating public values return (g**self.n)%p def compute_secret(self, gb): # computing secret key return (gb**self.n)%p class B: def __init__(self): # Generating a random private number selected for alice self.a = random.randint(1, p) # Generating a random private number selected for bob self.b = random.randint(1, p) self.arr = [self.a,self.b] def publish(self, i): # generating public values return (g**self.arr[i])%p def compute_secret(self, ga, i): # computing secret key return (ga**self.arr[i])%p alice = A()bob = A()eve = B() # Printing out the private selected number by Alice and Bobprint(f'Alice selected (a) : {alice.n}')print(f'Bob selected (b) : {bob.n}')print(f'Eve selectd private number for Alice (c) : {eve.a}')print(f'Eve selectd private number for Bob (d) : {eve.b}') # Generating public values ga = alice.publish()gb = bob.publish()gea = eve.publish(0)geb = eve.publish(1)print(f'Alice published (ga): {ga}')print(f'Bob published (gb): {gb}')print(f'Eve published value for Alice (gc): {gea}')print(f'Eve published value for Bob (gd): {geb}') # Computing the secret keysa = alice.compute_secret(gea)sea = eve.compute_secret(ga,0)sb = bob.compute_secret(geb)seb = eve.compute_secret(gb,1)print(f'Alice computed (S1) : {sa}')print(f'Eve computed key for Alice (S1) : {sea}')print(f'Bob computed (S2) : {sb}')print(f'Eve computed key for Bob (S2) : {seb}')
Output:
Enter a prime number (p) : 227
Enter a number (g) : 14
Alice selected (a) : 227
Bob selected (b) : 170
Eve selectd private number for Alice (c) : 65
Eve selectd private number for Bob (d) : 175
Alice published (ga): 14
Bob published (gb): 101
Eve published value for Alice (gc): 41
Eve published value for Bob (gd): 32
Alice computed (S1) : 41
Eve computed key for Alice (S1) : 41
Bob computed (S2) : 167
Eve computed key for Bob (S2) : 167
cryptography
Python
cryptography
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n18 Jul, 2021"
},
{
"code": null,
"e": 68,
"s": 28,
"text": "Prerequisite: Diffie-Hellman Algorithm "
},
{
"code": null,
"e": 409,
"s": 68,
"text": "Diffie-Hellman Key Exchange algorithm is an advanced cryptographic method used to establish a shared secret (or shared secret key) that can be used to perform secret communication on a public network between Alice and Bob while preventing Eve (eavesdropper), who can eavesdrop on all their communication, from learning the generated secret."
},
{
"code": null,
"e": 452,
"s": 409,
"text": "The key exchange procedure has two steps :"
},
{
"code": null,
"e": 716,
"s": 452,
"text": "One-time setup: We define some public parameters that are used by everyone forever.Protocol: To generate new secret keys, run a two-message key exchange protocol. This process is done using some simple algebra, prime numbers, and properties of modular arithmetic."
},
{
"code": null,
"e": 800,
"s": 716,
"text": "One-time setup: We define some public parameters that are used by everyone forever."
},
{
"code": null,
"e": 981,
"s": 800,
"text": "Protocol: To generate new secret keys, run a two-message key exchange protocol. This process is done using some simple algebra, prime numbers, and properties of modular arithmetic."
},
{
"code": null,
"e": 1333,
"s": 981,
"text": "Let’s assume that the eavesdropper EVE knows the public values p and g like everyone else, and from her eavesdropping, she learns the values exchanged by Alice and Bob, ga mod p and gb mod p, as well. With all her knowledge, she still can’t compute the secret key S, as it turns out, if p and g are properly chosen, it’s very, very hard for her to do."
},
{
"code": null,
"e": 1677,
"s": 1333,
"text": "For instance, you could brute force it and try all the options, but The calculations (mod p) make the discrete log calculation super slow when the numbers are large. If p and g have thousands of bits, then the best-known algorithms to compute discrete logs, although faster than plain brute force, will still take millions of years to compute."
},
{
"code": null,
"e": 1770,
"s": 1677,
"text": "Even with its immunity to brute force, it’s vulnerable to MITM (man in the middle position)."
},
{
"code": null,
"e": 1937,
"s": 1770,
"text": "A malicious Malory, that has a MitM (man in the middle) position, can manipulate the communications between Alice and Bob, and break the security of the key exchange."
},
{
"code": null,
"e": 1979,
"s": 1937,
"text": "Step by Step explanation of this process:"
},
{
"code": null,
"e": 2088,
"s": 1979,
"text": "Step 1: Selected public numbers p and g, p is a prime number, called the “modulus” and g is called the base."
},
{
"code": null,
"e": 2123,
"s": 2088,
"text": "Step 2: Selecting private numbers."
},
{
"code": null,
"e": 2247,
"s": 2123,
"text": "let Alice pick a private random number a and let Bob pick a private random number b, Malory picks 2 random numbers c and d."
},
{
"code": null,
"e": 2283,
"s": 2247,
"text": "Step 3: Intercepting public values,"
},
{
"code": null,
"e": 2558,
"s": 2283,
"text": "Malory intercepts Alice’s public value (ga(mod p)), block it from reaching Bob, and instead sends Bob her own public value (gc(modp)) and Malory intercepts Bob’s public value (gb(mod p)), block it from reaching Alice, and instead sends Alice her own public value (gd (modp))"
},
{
"code": null,
"e": 2587,
"s": 2558,
"text": "Step 4: Computing secret key"
},
{
"code": null,
"e": 2679,
"s": 2587,
"text": "Alice will compute a key S1=gda(mod p), and Bob will compute a different key, S2=gcb(mod p)"
},
{
"code": null,
"e": 2998,
"s": 2679,
"text": "Step 5: If Alice uses S1 as a key to encrypt a later message to Bob, Malory can decrypt it, re-encrypt it using S2, and send it to Bob. Bob and Alice won’t notice any problem and may assume their communication is encrypted, but in reality, Malory can decrypt, read, modify, and then re-encrypt all their conversations."
},
{
"code": null,
"e": 3027,
"s": 2998,
"text": "Below is the implementation:"
},
{
"code": null,
"e": 3035,
"s": 3027,
"text": "Python3"
},
{
"code": "import random # public keys are taken# p is a prime number# g is a primitive root of pp = int(input('Enter a prime number : '))g = int(input('Enter a number : ')) class A: def __init__(self): # Generating a random private number selected by alice self.n = random.randint(1, p) def publish(self): # generating public values return (g**self.n)%p def compute_secret(self, gb): # computing secret key return (gb**self.n)%p class B: def __init__(self): # Generating a random private number selected for alice self.a = random.randint(1, p) # Generating a random private number selected for bob self.b = random.randint(1, p) self.arr = [self.a,self.b] def publish(self, i): # generating public values return (g**self.arr[i])%p def compute_secret(self, ga, i): # computing secret key return (ga**self.arr[i])%p alice = A()bob = A()eve = B() # Printing out the private selected number by Alice and Bobprint(f'Alice selected (a) : {alice.n}')print(f'Bob selected (b) : {bob.n}')print(f'Eve selectd private number for Alice (c) : {eve.a}')print(f'Eve selectd private number for Bob (d) : {eve.b}') # Generating public values ga = alice.publish()gb = bob.publish()gea = eve.publish(0)geb = eve.publish(1)print(f'Alice published (ga): {ga}')print(f'Bob published (gb): {gb}')print(f'Eve published value for Alice (gc): {gea}')print(f'Eve published value for Bob (gd): {geb}') # Computing the secret keysa = alice.compute_secret(gea)sea = eve.compute_secret(ga,0)sb = bob.compute_secret(geb)seb = eve.compute_secret(gb,1)print(f'Alice computed (S1) : {sa}')print(f'Eve computed key for Alice (S1) : {sea}')print(f'Bob computed (S2) : {sb}')print(f'Eve computed key for Bob (S2) : {seb}')",
"e": 4858,
"s": 3035,
"text": null
},
{
"code": null,
"e": 4866,
"s": 4858,
"text": "Output:"
},
{
"code": null,
"e": 5313,
"s": 4866,
"text": "Enter a prime number (p) : 227\nEnter a number (g) : 14\n\nAlice selected (a) : 227\nBob selected (b) : 170\n\nEve selectd private number for Alice (c) : 65\nEve selectd private number for Bob (d) : 175\n\nAlice published (ga): 14\nBob published (gb): 101\n\nEve published value for Alice (gc): 41\nEve published value for Bob (gd): 32\n\nAlice computed (S1) : 41\nEve computed key for Alice (S1) : 41\n\nBob computed (S2) : 167\nEve computed key for Bob (S2) : 167"
},
{
"code": null,
"e": 5326,
"s": 5313,
"text": "cryptography"
},
{
"code": null,
"e": 5333,
"s": 5326,
"text": "Python"
},
{
"code": null,
"e": 5346,
"s": 5333,
"text": "cryptography"
}
] |
Count number of increasing subsequences of size k - GeeksforGeeks | 01 Oct, 2021
Given an array arr[] containing n integers. The problem is to count number of increasing subsequences in the array of size k.
Examples:
Input : arr[] = {2, 6, 4, 5, 7},
k = 3
Output : 5
The subsequences of size '3' are:
{2, 6, 7}, {2, 4, 5}, {2, 4, 7},
{2, 5, 7} and {4, 5, 7}.
Input : arr[] = {12, 8, 11, 13, 10, 15, 14, 16, 20},
k = 4
Output : 39
Approach: The idea is to use Dynamic Programming by define 2D matrix, say dp[][]. dp[i][j] stores the count of increasing subsequences of size i ending with element arr[j]. So dp[i][j] can be defined as:
dp[i][j] = 1, where i = 1 and 1 <= j <= n dp[i][j] = sum(dp[i-1][j]), where 1 < i <= k, i <= j <= n and arr[m] < arr[j] for (i-1) <= m < j.
Below is the implementation of above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation to count number of// increasing subsequences of size k#include <bits/stdc++.h> using namespace std; // function to count number of increasing// subsequences of size kint numOfIncSubseqOfSizeK(int arr[], int n, int k){ int dp[k][n], sum = 0; memset(dp, 0, sizeof(dp)); // count of increasing subsequences of size 1 // ending at each arr[i] for (int i = 0; i < n; i++) dp[0][i] = 1; // building up the matrix dp[][] // Here 'l' signifies the size of // increasing subsequence of size (l+1). for (int l = 1; l < k; l++) { // for each increasing subsequence of size 'l' // ending with element arr[i] for (int i = l; i < n; i++) { // count of increasing subsequences of size 'l' // ending with element arr[i] dp[l][i] = 0; for (int j = l - 1; j < i; j++) { if (arr[j] < arr[i]) dp[l][i] += dp[l - 1][j]; } } } // sum up the count of increasing subsequences of // size 'k' ending at each element arr[i] for (int i = k - 1; i < n; i++) sum += dp[k - 1][i]; // required number of increasing // subsequences of size k return sum;} // Driver program to test aboveint main(){ int arr[] = { 12, 8, 11, 13, 10, 15, 14, 16, 20 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 4; cout << "Number of Increasing Subsequences of size " << k << " = " << numOfIncSubseqOfSizeK(arr, n, k); return 0;}
//Java implementation to count number of// increasing subsequences of size k class GFG { // function to count number of increasing// subsequences of size k static int numOfIncSubseqOfSizeK(int arr[], int n, int k) { int dp[][] = new int[k][n], sum = 0; // count of increasing subsequences of size 1 // ending at each arr[i] for (int i = 0; i < n; i++) { dp[0][i] = 1; } // building up the matrix dp[][] // Here 'l' signifies the size of // increasing subsequence of size (l+1). for (int l = 1; l < k; l++) { // for each increasing subsequence of size 'l' // ending with element arr[i] for (int i = l; i < n; i++) { // count of increasing subsequences of size 'l' // ending with element arr[i] dp[l][i] = 0; for (int j = l - 1; j < i; j++) { if (arr[j] < arr[i]) { dp[l][i] += dp[l - 1][j]; } } } } // sum up the count of increasing subsequences of // size 'k' ending at each element arr[i] for (int i = k - 1; i < n; i++) { sum += dp[k - 1][i]; } // required number of increasing // subsequences of size k return sum; } // Driver program to test above public static void main(String[] args) { int arr[] = {12, 8, 11, 13, 10, 15, 14, 16, 20}; int n = arr.length; int k = 4; System.out.print("Number of Increasing Subsequences of size " + k + " = " + numOfIncSubseqOfSizeK(arr, n, k)); }}// This code is contributed by 29AjayKumar
# Python3 implementation to count number# of increasing subsequences of size kimport math as mt # function to count number of increasing# subsequences of size kdef numOfIncSubseqOfSizeK(arr, n, k): dp = [[0 for i in range(n)] for i in range(k)] # count of increasing subsequences # of size 1 ending at each arr[i] for i in range(n): dp[0][i] = 1 # building up the matrix dp[][] # Here 'l' signifies the size of # increasing subsequence of size (l+1). for l in range(1, k): # for each increasing subsequence of # size 'l' ending with element arr[i] for i in range(l, n): # count of increasing subsequences of # size 'l' ending with element arr[i] dp[l][i] = 0 for j in range(l - 1, i): if (arr[j] < arr[i]): dp[l][i] += dp[l - 1][j] # Sum up the count of increasing subsequences # of size 'k' ending at each element arr[i] Sum = 0 for i in range(k - 1, n): Sum += dp[k - 1][i] # required number of increasing # subsequences of size k return Sum # Driver Codearr = [12, 8, 11, 13, 10, 15, 14, 16, 20 ]n = len(arr)k = 4 print("Number of Increasing Subsequences of size", k, "=", numOfIncSubseqOfSizeK(arr, n, k)) # This code is contributed by# Mohit kumar 29
// C# implementation to count number of// increasing subsequences of size k using System; public class GFG { // function to count number of increasing// subsequences of size k static int numOfIncSubseqOfSizeK(int []arr, int n, int k) { int [,]dp = new int[k,n]; int sum = 0; // count of increasing subsequences of size 1 // ending at each arr[i] for (int i = 0; i < n; i++) { dp[0,i] = 1; } // building up the matrix dp[,] // Here 'l' signifies the size of // increasing subsequence of size (l+1). for (int l = 1; l < k; l++) { // for each increasing subsequence of size 'l' // ending with element arr[i] for (int i = l; i < n; i++) { // count of increasing subsequences of size 'l' // ending with element arr[i] dp[l,i] = 0; for (int j = l - 1; j < i; j++) { if (arr[j] < arr[i]) { dp[l,i] += dp[l - 1,j]; } } } } // sum up the count of increasing subsequences of // size 'k' ending at each element arr[i] for (int i = k - 1; i < n; i++) { sum += dp[k - 1,i]; } // required number of increasing // subsequences of size k return sum; } // Driver program to test above public static void Main() { int []arr = {12, 8, 11, 13, 10, 15, 14, 16, 20}; int n = arr.Length; int k = 4; Console.Write("Number of Increasing Subsequences of size " + k + " = " + numOfIncSubseqOfSizeK(arr, n, k)); }}// This code is contributed by 29AjayKumar
<?php// PHP implementation to count// number of increasing// subsequences of size k // function to count number// of increasing subsequences// of size kfunction numOfIncSubseqOfSizeK($arr, $n, $k){ $dp = array(array()); $sum = 0; $dp = array_fill(0, $n + 1, false); // count of increasing // subsequences of size 1 // ending at each arr[i] for ($i = 0; $i < $n; $i++) $dp[0][$i] = 1; // building up the matrix // dp[][]. Here 'l' signifies // the size of increasing // subsequence of size (l+1). for ($l = 1; $l < $k; $l++) { // for each increasing // subsequence of size 'l' // ending with element arr[i] for ($i = $l; $i < $n; $i++) { // count of increasing // subsequences of size 'l' // ending with element arr[i] $dp[$l][$i] = 0; for ($j = $l - 1; $j < $i; $j++) { if ($arr[$j] < $arr[$i]) $dp[$l][$i] += $dp[$l - 1][$j]; } } } // sum up the count of increasing // subsequences of size 'k' ending // at each element arr[i] for ($i = $k - 1; $i < $n; $i++) $sum += $dp[$k - 1][$i]; // required number of increasing // subsequences of size k return $sum;} // Driver Code$arr = array(12, 8, 11, 13, 10, 15, 14, 16, 20);$n = sizeof($arr);$k = 4; echo "Number of Increasing ". "Subsequences of size ", $k , " = " , numOfIncSubseqOfSizeK($arr, $n, $k); // This code is contributed// by akt_mit?>
<script> // JavaScript implementation to count number of// increasing subsequences of size k // function to count number of increasing// subsequences of size k function numOfIncSubseqOfSizeK(arr, n, k) { let dp = new Array(k), sum = 0; // Loop to create 2D array using 1D array for (let i = 0; i < dp.length; i++) { dp[i] = new Array(2); } // count of increasing subsequences of size 1 // ending at each arr[i] for (let i = 0; i < n; i++) { dp[0][i] = 1; } // building up the matrix dp[][] // Here 'l' signifies the size of // increasing subsequence of size (l+1). for (let l = 1; l < k; l++) { // for each increasing subsequence of size 'l' // ending with element arr[i] for (let i = l; i < n; i++) { // count of increasing subsequences of size 'l' // ending with element arr[i] dp[l][i] = 0; for (let j = l - 1; j < i; j++) { if (arr[j] < arr[i]) { dp[l][i] += dp[l - 1][j]; } } } } // sum up the count of increasing subsequences of // size 'k' ending at each element arr[i] for (let i = k - 1; i < n; i++) { sum += dp[k - 1][i]; } // required number of increasing // subsequences of size k return sum; } // Driver code let arr = [12, 8, 11, 13, 10, 15, 14, 16, 20]; let n = arr.length; let k = 4; document.write("Number of Increasing Subsequences of size " + k + " = " + numOfIncSubseqOfSizeK(arr, n, k)); </script>
Output:
Number of Increasing Subsequences of size 4 = 39
Time Complexity: O(kn2). Auxiliary Space: O(kn).
jit_t
29AjayKumar
mohit kumar 29
ManasChhabra2
splevel62
surindertarika1234
LIS
Arrays
Dynamic Programming
Arrays
Dynamic Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Arrays
Multidimensional Arrays in Java
Linear Search
Linked List vs Array
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
0-1 Knapsack Problem | DP-10
Program for Fibonacci numbers
Longest Common Subsequence | DP-4
Bellman–Ford Algorithm | DP-23
Floyd Warshall Algorithm | DP-16 | [
{
"code": null,
"e": 26507,
"s": 26479,
"text": "\n01 Oct, 2021"
},
{
"code": null,
"e": 26633,
"s": 26507,
"text": "Given an array arr[] containing n integers. The problem is to count number of increasing subsequences in the array of size k."
},
{
"code": null,
"e": 26644,
"s": 26633,
"text": "Examples: "
},
{
"code": null,
"e": 26884,
"s": 26644,
"text": "Input : arr[] = {2, 6, 4, 5, 7}, \n k = 3\nOutput : 5\nThe subsequences of size '3' are:\n{2, 6, 7}, {2, 4, 5}, {2, 4, 7},\n{2, 5, 7} and {4, 5, 7}.\n\nInput : arr[] = {12, 8, 11, 13, 10, 15, 14, 16, 20}, \n k = 4\nOutput : 39"
},
{
"code": null,
"e": 27089,
"s": 26884,
"text": "Approach: The idea is to use Dynamic Programming by define 2D matrix, say dp[][]. dp[i][j] stores the count of increasing subsequences of size i ending with element arr[j]. So dp[i][j] can be defined as: "
},
{
"code": null,
"e": 27229,
"s": 27089,
"text": "dp[i][j] = 1, where i = 1 and 1 <= j <= n dp[i][j] = sum(dp[i-1][j]), where 1 < i <= k, i <= j <= n and arr[m] < arr[j] for (i-1) <= m < j."
},
{
"code": null,
"e": 27277,
"s": 27229,
"text": "Below is the implementation of above approach: "
},
{
"code": null,
"e": 27281,
"s": 27277,
"text": "C++"
},
{
"code": null,
"e": 27286,
"s": 27281,
"text": "Java"
},
{
"code": null,
"e": 27294,
"s": 27286,
"text": "Python3"
},
{
"code": null,
"e": 27297,
"s": 27294,
"text": "C#"
},
{
"code": null,
"e": 27301,
"s": 27297,
"text": "PHP"
},
{
"code": null,
"e": 27312,
"s": 27301,
"text": "Javascript"
},
{
"code": "// C++ implementation to count number of// increasing subsequences of size k#include <bits/stdc++.h> using namespace std; // function to count number of increasing// subsequences of size kint numOfIncSubseqOfSizeK(int arr[], int n, int k){ int dp[k][n], sum = 0; memset(dp, 0, sizeof(dp)); // count of increasing subsequences of size 1 // ending at each arr[i] for (int i = 0; i < n; i++) dp[0][i] = 1; // building up the matrix dp[][] // Here 'l' signifies the size of // increasing subsequence of size (l+1). for (int l = 1; l < k; l++) { // for each increasing subsequence of size 'l' // ending with element arr[i] for (int i = l; i < n; i++) { // count of increasing subsequences of size 'l' // ending with element arr[i] dp[l][i] = 0; for (int j = l - 1; j < i; j++) { if (arr[j] < arr[i]) dp[l][i] += dp[l - 1][j]; } } } // sum up the count of increasing subsequences of // size 'k' ending at each element arr[i] for (int i = k - 1; i < n; i++) sum += dp[k - 1][i]; // required number of increasing // subsequences of size k return sum;} // Driver program to test aboveint main(){ int arr[] = { 12, 8, 11, 13, 10, 15, 14, 16, 20 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 4; cout << \"Number of Increasing Subsequences of size \" << k << \" = \" << numOfIncSubseqOfSizeK(arr, n, k); return 0;}",
"e": 28824,
"s": 27312,
"text": null
},
{
"code": "//Java implementation to count number of// increasing subsequences of size k class GFG { // function to count number of increasing// subsequences of size k static int numOfIncSubseqOfSizeK(int arr[], int n, int k) { int dp[][] = new int[k][n], sum = 0; // count of increasing subsequences of size 1 // ending at each arr[i] for (int i = 0; i < n; i++) { dp[0][i] = 1; } // building up the matrix dp[][] // Here 'l' signifies the size of // increasing subsequence of size (l+1). for (int l = 1; l < k; l++) { // for each increasing subsequence of size 'l' // ending with element arr[i] for (int i = l; i < n; i++) { // count of increasing subsequences of size 'l' // ending with element arr[i] dp[l][i] = 0; for (int j = l - 1; j < i; j++) { if (arr[j] < arr[i]) { dp[l][i] += dp[l - 1][j]; } } } } // sum up the count of increasing subsequences of // size 'k' ending at each element arr[i] for (int i = k - 1; i < n; i++) { sum += dp[k - 1][i]; } // required number of increasing // subsequences of size k return sum; } // Driver program to test above public static void main(String[] args) { int arr[] = {12, 8, 11, 13, 10, 15, 14, 16, 20}; int n = arr.length; int k = 4; System.out.print(\"Number of Increasing Subsequences of size \" + k + \" = \" + numOfIncSubseqOfSizeK(arr, n, k)); }}// This code is contributed by 29AjayKumar",
"e": 30537,
"s": 28824,
"text": null
},
{
"code": "# Python3 implementation to count number# of increasing subsequences of size kimport math as mt # function to count number of increasing# subsequences of size kdef numOfIncSubseqOfSizeK(arr, n, k): dp = [[0 for i in range(n)] for i in range(k)] # count of increasing subsequences # of size 1 ending at each arr[i] for i in range(n): dp[0][i] = 1 # building up the matrix dp[][] # Here 'l' signifies the size of # increasing subsequence of size (l+1). for l in range(1, k): # for each increasing subsequence of # size 'l' ending with element arr[i] for i in range(l, n): # count of increasing subsequences of # size 'l' ending with element arr[i] dp[l][i] = 0 for j in range(l - 1, i): if (arr[j] < arr[i]): dp[l][i] += dp[l - 1][j] # Sum up the count of increasing subsequences # of size 'k' ending at each element arr[i] Sum = 0 for i in range(k - 1, n): Sum += dp[k - 1][i] # required number of increasing # subsequences of size k return Sum # Driver Codearr = [12, 8, 11, 13, 10, 15, 14, 16, 20 ]n = len(arr)k = 4 print(\"Number of Increasing Subsequences of size\", k, \"=\", numOfIncSubseqOfSizeK(arr, n, k)) # This code is contributed by# Mohit kumar 29",
"e": 31912,
"s": 30537,
"text": null
},
{
"code": "// C# implementation to count number of// increasing subsequences of size k using System; public class GFG { // function to count number of increasing// subsequences of size k static int numOfIncSubseqOfSizeK(int []arr, int n, int k) { int [,]dp = new int[k,n]; int sum = 0; // count of increasing subsequences of size 1 // ending at each arr[i] for (int i = 0; i < n; i++) { dp[0,i] = 1; } // building up the matrix dp[,] // Here 'l' signifies the size of // increasing subsequence of size (l+1). for (int l = 1; l < k; l++) { // for each increasing subsequence of size 'l' // ending with element arr[i] for (int i = l; i < n; i++) { // count of increasing subsequences of size 'l' // ending with element arr[i] dp[l,i] = 0; for (int j = l - 1; j < i; j++) { if (arr[j] < arr[i]) { dp[l,i] += dp[l - 1,j]; } } } } // sum up the count of increasing subsequences of // size 'k' ending at each element arr[i] for (int i = k - 1; i < n; i++) { sum += dp[k - 1,i]; } // required number of increasing // subsequences of size k return sum; } // Driver program to test above public static void Main() { int []arr = {12, 8, 11, 13, 10, 15, 14, 16, 20}; int n = arr.Length; int k = 4; Console.Write(\"Number of Increasing Subsequences of size \" + k + \" = \" + numOfIncSubseqOfSizeK(arr, n, k)); }}// This code is contributed by 29AjayKumar",
"e": 33656,
"s": 31912,
"text": null
},
{
"code": "<?php// PHP implementation to count// number of increasing// subsequences of size k // function to count number// of increasing subsequences// of size kfunction numOfIncSubseqOfSizeK($arr, $n, $k){ $dp = array(array()); $sum = 0; $dp = array_fill(0, $n + 1, false); // count of increasing // subsequences of size 1 // ending at each arr[i] for ($i = 0; $i < $n; $i++) $dp[0][$i] = 1; // building up the matrix // dp[][]. Here 'l' signifies // the size of increasing // subsequence of size (l+1). for ($l = 1; $l < $k; $l++) { // for each increasing // subsequence of size 'l' // ending with element arr[i] for ($i = $l; $i < $n; $i++) { // count of increasing // subsequences of size 'l' // ending with element arr[i] $dp[$l][$i] = 0; for ($j = $l - 1; $j < $i; $j++) { if ($arr[$j] < $arr[$i]) $dp[$l][$i] += $dp[$l - 1][$j]; } } } // sum up the count of increasing // subsequences of size 'k' ending // at each element arr[i] for ($i = $k - 1; $i < $n; $i++) $sum += $dp[$k - 1][$i]; // required number of increasing // subsequences of size k return $sum;} // Driver Code$arr = array(12, 8, 11, 13, 10, 15, 14, 16, 20);$n = sizeof($arr);$k = 4; echo \"Number of Increasing \". \"Subsequences of size \", $k , \" = \" , numOfIncSubseqOfSizeK($arr, $n, $k); // This code is contributed// by akt_mit?>",
"e": 35279,
"s": 33656,
"text": null
},
{
"code": "<script> // JavaScript implementation to count number of// increasing subsequences of size k // function to count number of increasing// subsequences of size k function numOfIncSubseqOfSizeK(arr, n, k) { let dp = new Array(k), sum = 0; // Loop to create 2D array using 1D array for (let i = 0; i < dp.length; i++) { dp[i] = new Array(2); } // count of increasing subsequences of size 1 // ending at each arr[i] for (let i = 0; i < n; i++) { dp[0][i] = 1; } // building up the matrix dp[][] // Here 'l' signifies the size of // increasing subsequence of size (l+1). for (let l = 1; l < k; l++) { // for each increasing subsequence of size 'l' // ending with element arr[i] for (let i = l; i < n; i++) { // count of increasing subsequences of size 'l' // ending with element arr[i] dp[l][i] = 0; for (let j = l - 1; j < i; j++) { if (arr[j] < arr[i]) { dp[l][i] += dp[l - 1][j]; } } } } // sum up the count of increasing subsequences of // size 'k' ending at each element arr[i] for (let i = k - 1; i < n; i++) { sum += dp[k - 1][i]; } // required number of increasing // subsequences of size k return sum; } // Driver code let arr = [12, 8, 11, 13, 10, 15, 14, 16, 20]; let n = arr.length; let k = 4; document.write(\"Number of Increasing Subsequences of size \" + k + \" = \" + numOfIncSubseqOfSizeK(arr, n, k)); </script>",
"e": 37058,
"s": 35279,
"text": null
},
{
"code": null,
"e": 37067,
"s": 37058,
"text": "Output: "
},
{
"code": null,
"e": 37116,
"s": 37067,
"text": "Number of Increasing Subsequences of size 4 = 39"
},
{
"code": null,
"e": 37166,
"s": 37116,
"text": "Time Complexity: O(kn2). Auxiliary Space: O(kn). "
},
{
"code": null,
"e": 37172,
"s": 37166,
"text": "jit_t"
},
{
"code": null,
"e": 37184,
"s": 37172,
"text": "29AjayKumar"
},
{
"code": null,
"e": 37199,
"s": 37184,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 37213,
"s": 37199,
"text": "ManasChhabra2"
},
{
"code": null,
"e": 37223,
"s": 37213,
"text": "splevel62"
},
{
"code": null,
"e": 37242,
"s": 37223,
"text": "surindertarika1234"
},
{
"code": null,
"e": 37246,
"s": 37242,
"text": "LIS"
},
{
"code": null,
"e": 37253,
"s": 37246,
"text": "Arrays"
},
{
"code": null,
"e": 37273,
"s": 37253,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 37280,
"s": 37273,
"text": "Arrays"
},
{
"code": null,
"e": 37300,
"s": 37280,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 37398,
"s": 37300,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37421,
"s": 37398,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 37453,
"s": 37421,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 37467,
"s": 37453,
"text": "Linear Search"
},
{
"code": null,
"e": 37488,
"s": 37467,
"text": "Linked List vs Array"
},
{
"code": null,
"e": 37573,
"s": 37488,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 37602,
"s": 37573,
"text": "0-1 Knapsack Problem | DP-10"
},
{
"code": null,
"e": 37632,
"s": 37602,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 37666,
"s": 37632,
"text": "Longest Common Subsequence | DP-4"
},
{
"code": null,
"e": 37697,
"s": 37666,
"text": "Bellman–Ford Algorithm | DP-23"
}
] |
Check if any anagram of a string is palindrome or not - GeeksforGeeks | 26 May, 2021
We have given an anagram string and we have to check whether it can be made palindrome o not. Examples:
Input : geeksforgeeks
Output : No
There is no palindrome anagram of
given string
Input : geeksgeeks
Output : Yes
There are palindrome anagrams of
given string. For example kgeesseegk
This problem is basically the same as Check if characters of a given string can be rearranged to form a palindrome. We can do it in O(n) time using a count array. Following are detailed steps. 1) Create a count array of alphabet size which is typically 256. Initialize all values of count array as 0. 2) Traverse the given string and increment count of every character. 3) Traverse the count array and if the count array has more than one odd values, return false. Otherwise, return true.
C++
Java
Python
C#
Javascript
#include <iostream>using namespace std;#define NO_OF_CHARS 256 /* function to check whether characters of a string can form a palindrome */bool canFormPalindrome(string str){ // Create a count array and initialize all // values as 0 int count[NO_OF_CHARS] = { 0 }; // For each character in input strings, // increment count in the corresponding // count array for (int i = 0; str[i]; i++) count[str[i]]++; // Count odd occurring characters int odd = 0; for (int i = 0; i < NO_OF_CHARS; i++) { if (count[i] & 1) odd++; if (odd > 1) return false; } // Return true if odd count is 0 or 1, return true;} /* Driver program to test to print printDups*/int main(){ canFormPalindrome("geeksforgeeks") ? cout << "Yes\n" : cout << "No\n"; canFormPalindrome("geeksogeeks") ? cout << "Yes\n" : cout << "No\n"; return 0;}
// Java program to Check if any anagram// of a string is palindrome or notpublic class GFG { static final int NO_OF_CHARS = 256; /* function to check whether characters of a string can form a palindrome */ static boolean canFormPalindrome(String str) { // Create a count array and initialize // all values as 0 int[] count = new int[NO_OF_CHARS]; // For each character in input strings, // increment count in the corresponding // count array for (int i = 0; i < str.length(); i++) count[str.charAt(i)]++; // Count odd occurring characters int odd = 0; for (int i = 0; i < NO_OF_CHARS; i++) { if ((count[i] & 1) != 0) odd++; if (odd > 1) return false; } // Return true if odd count is 0 or 1, return true; } /* Driver program to test to print printDups*/ public static void main(String args[]) { System.out.println(canFormPalindrome("geeksforgeeks") ? "Yes" : "No"); System.out.println(canFormPalindrome("geeksogeeks") ? "Yes" : "No"); }}// This code is contributed by Sumit Ghosh
NO_OF_CHARS = 256 """ function to check whether characters of a string can form a palindrome """def canFormPalindrome(string): # Create a count array and initialize all # values as 0 count = [0 for i in range(NO_OF_CHARS)] # For each character in input strings, # increment count in the corresponding # count array for i in string: count[ord(i)] += 1 # Count odd occurring characters odd = 0 for i in range(NO_OF_CHARS): if (count[i] & 1): odd += 1 if (odd > 1): return False # Return true if odd count is 0 or 1, return True # Driver program to test to print printDupsif(canFormPalindrome("geeksforgeeks")): print "Yes"else: print "No"if(canFormPalindrome("geeksogeeks")): print "Yes"else: print "NO" # This code is contributed by Sachin Bisht
// C# program to Check if any anagram// of a string is palindrome or notusing System; public class GFG { static int NO_OF_CHARS = 256; /* function to check whether characters of a string can form a palindrome */ static bool canFormPalindrome(string str) { // Create a count array and // initialize all values as 0 int[] count = new int[NO_OF_CHARS]; // For each character in input // strings, increment count in // the corresponding count array for (int i = 0; i < str.Length; i++) count[str[i]]++; // Count odd occurring characters int odd = 0; for (int i = 0; i < NO_OF_CHARS; i++) { if ((count[i] & 1) != 0) odd++; if (odd > 1) return false; } // Return true if odd count // is 0 or 1, return true; } // Driver program public static void Main() { Console.WriteLine( canFormPalindrome("geeksforgeeks") ? "Yes" : "No"); Console.WriteLine( canFormPalindrome("geeksogeeks") ? "Yes" : "No"); }} // This code is contributed by vt_m.
<script> // Javascript program to Check if any anagram // of a string is palindrome or not let NO_OF_CHARS = 256; /* function to check whether characters of a string can form a palindrome */ function canFormPalindrome(str) { // Create a count array and // initialize all values as 0 let count = new Array(NO_OF_CHARS); count.fill(0); // For each character in input // strings, increment count in // the corresponding count array for (let i = 0; i < str.length; i++) count[str[i].charCodeAt()]++; // Count odd occurring characters let odd = 0; for (let i = 0; i < NO_OF_CHARS; i++) { if ((count[i] & 1) != 0) odd++; if (odd > 1) return false; } // Return true if odd count // is 0 or 1, return true; } document.write(canFormPalindrome("geeksforgeeks")? "Yes" + "</br>" : "No" + "</br>"); document.write(canFormPalindrome("geeksogeeks")? "Yes" : "No"); // This code is contributed by divyeshrabadiya07.</script>
Output:
No
Yes
This article is contributed by Rishabh Jain. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
vt_m
Veluri Mithun
divyeshrabadiya07
anagram
palindrome
Snapdeal
Hash
Strings
Snapdeal
Hash
Strings
palindrome
anagram
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Hashing | Set 2 (Separate Chaining)
Sort string of characters
Counting frequencies of array elements
Double Hashing
Most frequent element in an array
Write a program to reverse an array or string
Reverse a string in Java
C++ Data Types
Longest Common Subsequence | DP-4
Check for Balanced Brackets in an expression (well-formedness) using Stack | [
{
"code": null,
"e": 25212,
"s": 25184,
"text": "\n26 May, 2021"
},
{
"code": null,
"e": 25317,
"s": 25212,
"text": "We have given an anagram string and we have to check whether it can be made palindrome o not. Examples: "
},
{
"code": null,
"e": 25504,
"s": 25317,
"text": "Input : geeksforgeeks \nOutput : No\nThere is no palindrome anagram of \ngiven string\n\nInput : geeksgeeks\nOutput : Yes\nThere are palindrome anagrams of\ngiven string. For example kgeesseegk"
},
{
"code": null,
"e": 25994,
"s": 25504,
"text": "This problem is basically the same as Check if characters of a given string can be rearranged to form a palindrome. We can do it in O(n) time using a count array. Following are detailed steps. 1) Create a count array of alphabet size which is typically 256. Initialize all values of count array as 0. 2) Traverse the given string and increment count of every character. 3) Traverse the count array and if the count array has more than one odd values, return false. Otherwise, return true. "
},
{
"code": null,
"e": 25998,
"s": 25994,
"text": "C++"
},
{
"code": null,
"e": 26003,
"s": 25998,
"text": "Java"
},
{
"code": null,
"e": 26010,
"s": 26003,
"text": "Python"
},
{
"code": null,
"e": 26013,
"s": 26010,
"text": "C#"
},
{
"code": null,
"e": 26024,
"s": 26013,
"text": "Javascript"
},
{
"code": "#include <iostream>using namespace std;#define NO_OF_CHARS 256 /* function to check whether characters of a string can form a palindrome */bool canFormPalindrome(string str){ // Create a count array and initialize all // values as 0 int count[NO_OF_CHARS] = { 0 }; // For each character in input strings, // increment count in the corresponding // count array for (int i = 0; str[i]; i++) count[str[i]]++; // Count odd occurring characters int odd = 0; for (int i = 0; i < NO_OF_CHARS; i++) { if (count[i] & 1) odd++; if (odd > 1) return false; } // Return true if odd count is 0 or 1, return true;} /* Driver program to test to print printDups*/int main(){ canFormPalindrome(\"geeksforgeeks\") ? cout << \"Yes\\n\" : cout << \"No\\n\"; canFormPalindrome(\"geeksogeeks\") ? cout << \"Yes\\n\" : cout << \"No\\n\"; return 0;}",
"e": 26930,
"s": 26024,
"text": null
},
{
"code": "// Java program to Check if any anagram// of a string is palindrome or notpublic class GFG { static final int NO_OF_CHARS = 256; /* function to check whether characters of a string can form a palindrome */ static boolean canFormPalindrome(String str) { // Create a count array and initialize // all values as 0 int[] count = new int[NO_OF_CHARS]; // For each character in input strings, // increment count in the corresponding // count array for (int i = 0; i < str.length(); i++) count[str.charAt(i)]++; // Count odd occurring characters int odd = 0; for (int i = 0; i < NO_OF_CHARS; i++) { if ((count[i] & 1) != 0) odd++; if (odd > 1) return false; } // Return true if odd count is 0 or 1, return true; } /* Driver program to test to print printDups*/ public static void main(String args[]) { System.out.println(canFormPalindrome(\"geeksforgeeks\") ? \"Yes\" : \"No\"); System.out.println(canFormPalindrome(\"geeksogeeks\") ? \"Yes\" : \"No\"); }}// This code is contributed by Sumit Ghosh",
"e": 28236,
"s": 26930,
"text": null
},
{
"code": "NO_OF_CHARS = 256 \"\"\" function to check whether characters of a string can form a palindrome \"\"\"def canFormPalindrome(string): # Create a count array and initialize all # values as 0 count = [0 for i in range(NO_OF_CHARS)] # For each character in input strings, # increment count in the corresponding # count array for i in string: count[ord(i)] += 1 # Count odd occurring characters odd = 0 for i in range(NO_OF_CHARS): if (count[i] & 1): odd += 1 if (odd > 1): return False # Return true if odd count is 0 or 1, return True # Driver program to test to print printDupsif(canFormPalindrome(\"geeksforgeeks\")): print \"Yes\"else: print \"No\"if(canFormPalindrome(\"geeksogeeks\")): print \"Yes\"else: print \"NO\" # This code is contributed by Sachin Bisht",
"e": 29094,
"s": 28236,
"text": null
},
{
"code": "// C# program to Check if any anagram// of a string is palindrome or notusing System; public class GFG { static int NO_OF_CHARS = 256; /* function to check whether characters of a string can form a palindrome */ static bool canFormPalindrome(string str) { // Create a count array and // initialize all values as 0 int[] count = new int[NO_OF_CHARS]; // For each character in input // strings, increment count in // the corresponding count array for (int i = 0; i < str.Length; i++) count[str[i]]++; // Count odd occurring characters int odd = 0; for (int i = 0; i < NO_OF_CHARS; i++) { if ((count[i] & 1) != 0) odd++; if (odd > 1) return false; } // Return true if odd count // is 0 or 1, return true; } // Driver program public static void Main() { Console.WriteLine( canFormPalindrome(\"geeksforgeeks\") ? \"Yes\" : \"No\"); Console.WriteLine( canFormPalindrome(\"geeksogeeks\") ? \"Yes\" : \"No\"); }} // This code is contributed by vt_m.",
"e": 30363,
"s": 29094,
"text": null
},
{
"code": "<script> // Javascript program to Check if any anagram // of a string is palindrome or not let NO_OF_CHARS = 256; /* function to check whether characters of a string can form a palindrome */ function canFormPalindrome(str) { // Create a count array and // initialize all values as 0 let count = new Array(NO_OF_CHARS); count.fill(0); // For each character in input // strings, increment count in // the corresponding count array for (let i = 0; i < str.length; i++) count[str[i].charCodeAt()]++; // Count odd occurring characters let odd = 0; for (let i = 0; i < NO_OF_CHARS; i++) { if ((count[i] & 1) != 0) odd++; if (odd > 1) return false; } // Return true if odd count // is 0 or 1, return true; } document.write(canFormPalindrome(\"geeksforgeeks\")? \"Yes\" + \"</br>\" : \"No\" + \"</br>\"); document.write(canFormPalindrome(\"geeksogeeks\")? \"Yes\" : \"No\"); // This code is contributed by divyeshrabadiya07.</script>",
"e": 31538,
"s": 30363,
"text": null
},
{
"code": null,
"e": 31547,
"s": 31538,
"text": "Output: "
},
{
"code": null,
"e": 31554,
"s": 31547,
"text": "No\nYes"
},
{
"code": null,
"e": 31974,
"s": 31554,
"text": "This article is contributed by Rishabh Jain. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 31979,
"s": 31974,
"text": "vt_m"
},
{
"code": null,
"e": 31993,
"s": 31979,
"text": "Veluri Mithun"
},
{
"code": null,
"e": 32011,
"s": 31993,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 32019,
"s": 32011,
"text": "anagram"
},
{
"code": null,
"e": 32030,
"s": 32019,
"text": "palindrome"
},
{
"code": null,
"e": 32039,
"s": 32030,
"text": "Snapdeal"
},
{
"code": null,
"e": 32044,
"s": 32039,
"text": "Hash"
},
{
"code": null,
"e": 32052,
"s": 32044,
"text": "Strings"
},
{
"code": null,
"e": 32061,
"s": 32052,
"text": "Snapdeal"
},
{
"code": null,
"e": 32066,
"s": 32061,
"text": "Hash"
},
{
"code": null,
"e": 32074,
"s": 32066,
"text": "Strings"
},
{
"code": null,
"e": 32085,
"s": 32074,
"text": "palindrome"
},
{
"code": null,
"e": 32093,
"s": 32085,
"text": "anagram"
},
{
"code": null,
"e": 32191,
"s": 32093,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32227,
"s": 32191,
"text": "Hashing | Set 2 (Separate Chaining)"
},
{
"code": null,
"e": 32253,
"s": 32227,
"text": "Sort string of characters"
},
{
"code": null,
"e": 32292,
"s": 32253,
"text": "Counting frequencies of array elements"
},
{
"code": null,
"e": 32307,
"s": 32292,
"text": "Double Hashing"
},
{
"code": null,
"e": 32341,
"s": 32307,
"text": "Most frequent element in an array"
},
{
"code": null,
"e": 32387,
"s": 32341,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 32412,
"s": 32387,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 32427,
"s": 32412,
"text": "C++ Data Types"
},
{
"code": null,
"e": 32461,
"s": 32427,
"text": "Longest Common Subsequence | DP-4"
}
] |
Android imageView Zoom-in and Zoom-Out? | This example demonstrates how do I Zoom In and Zoom Out an android ImageView.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"
android:gravity="center"
tools:context=".MainActivity">
<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/image" />
</LinearLayout>
Step 3 − Add the following code to src/MainActivity.java
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
private ScaleGestureDetector scaleGestureDetector;
private float mScaleFactor = 1.0f;
private ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView=findViewById(R.id.imageView);
scaleGestureDetector = new ScaleGestureDetector(this, new ScaleListener());
}
@Override
public boolean onTouchEvent(MotionEvent motionEvent) {
scaleGestureDetector.onTouchEvent(motionEvent);
return true;
}
private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
@Override
public boolean onScale(ScaleGestureDetector scaleGestureDetector) {
mScaleFactor *= scaleGestureDetector.getScaleFactor();
mScaleFactor = Math.max(0.1f, Math.min(mScaleFactor, 10.0f));
imageView.setScaleX(mScaleFactor);
imageView.setScaleY(mScaleFactor);
return true;
}
}
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen − | [
{
"code": null,
"e": 1140,
"s": 1062,
"text": "This example demonstrates how do I Zoom In and Zoom Out an android ImageView."
},
{
"code": null,
"e": 1269,
"s": 1140,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1334,
"s": 1269,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 1882,
"s": 1334,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:orientation=\"vertical\"\n android:padding=\"16dp\"\n android:gravity=\"center\"\n tools:context=\".MainActivity\">\n <ImageView\n android:id=\"@+id/imageView\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:src=\"@drawable/image\" />\n</LinearLayout>"
},
{
"code": null,
"e": 1939,
"s": 1882,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 3182,
"s": 1939,
"text": "import androidx.appcompat.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.view.MotionEvent;\nimport android.view.ScaleGestureDetector;\nimport android.widget.ImageView;\npublic class MainActivity extends AppCompatActivity {\n private ScaleGestureDetector scaleGestureDetector;\n private float mScaleFactor = 1.0f;\n private ImageView imageView; \n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n imageView=findViewById(R.id.imageView);\n scaleGestureDetector = new ScaleGestureDetector(this, new ScaleListener());\n }\n @Override\n public boolean onTouchEvent(MotionEvent motionEvent) {\n scaleGestureDetector.onTouchEvent(motionEvent);\n return true;\n }\n private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {\n @Override\n public boolean onScale(ScaleGestureDetector scaleGestureDetector) {\n mScaleFactor *= scaleGestureDetector.getScaleFactor();\n mScaleFactor = Math.max(0.1f, Math.min(mScaleFactor, 10.0f));\n imageView.setScaleX(mScaleFactor);\n imageView.setScaleY(mScaleFactor);\n return true;\n }\n }\n}"
},
{
"code": null,
"e": 3237,
"s": 3182,
"text": "Step 4 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 3907,
"s": 3237,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 4255,
"s": 3907,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −"
}
] |
Wand rectangle() function in Python - GeeksforGeeks | 10 May, 2020
rectangle() function, as the name describes this function is used to draw a circle using wand.drawing object in Python. rectangle takes many arguments like left, top, right, bottom, width, height etc.
Syntax : wand.drawing.rectangle(left, top, right, bottom, width, height, radius, xradius, yradius)
Parameters :
Example #1:
# Import different modules of wandfrom wand.image import Imagefrom wand.drawing import Drawingfrom wand.color import Colorimport math with Drawing() as draw: draw.fill_color = Color('GREEN') draw.rectangle(left = 25, top = 50, right = 175, bottom = 150) with Image(width = 200, height = 200, background = Color('lightgreen')) as image: draw(image) image.save(filename = "rectangle.png")
Output:
Example #2:setting corner-radius for the rectangle.
# Import different modules of wandfrom wand.image import Imagefrom wand.drawing import Drawingfrom wand.color import Colorimport math with Drawing() as draw: draw.fill_color = Color('GREEN') draw.rectangle(left = 25, top = 50, right = 175, bottom = 150, radius = 25) with Image(width = 200, height = 200, background = Color('lightgreen')) as image: draw(image) image.save(filename = "rectangle.png")
Output:
Python-wand
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
Reading and Writing to text files in Python
*args and **kwargs in Python
Create a Pandas DataFrame from Lists | [
{
"code": null,
"e": 26495,
"s": 26467,
"text": "\n10 May, 2020"
},
{
"code": null,
"e": 26696,
"s": 26495,
"text": "rectangle() function, as the name describes this function is used to draw a circle using wand.drawing object in Python. rectangle takes many arguments like left, top, right, bottom, width, height etc."
},
{
"code": null,
"e": 26795,
"s": 26696,
"text": "Syntax : wand.drawing.rectangle(left, top, right, bottom, width, height, radius, xradius, yradius)"
},
{
"code": null,
"e": 26808,
"s": 26795,
"text": "Parameters :"
},
{
"code": null,
"e": 26820,
"s": 26808,
"text": "Example #1:"
},
{
"code": "# Import different modules of wandfrom wand.image import Imagefrom wand.drawing import Drawingfrom wand.color import Colorimport math with Drawing() as draw: draw.fill_color = Color('GREEN') draw.rectangle(left = 25, top = 50, right = 175, bottom = 150) with Image(width = 200, height = 200, background = Color('lightgreen')) as image: draw(image) image.save(filename = \"rectangle.png\")",
"e": 27253,
"s": 26820,
"text": null
},
{
"code": null,
"e": 27261,
"s": 27253,
"text": "Output:"
},
{
"code": null,
"e": 27313,
"s": 27261,
"text": "Example #2:setting corner-radius for the rectangle."
},
{
"code": "# Import different modules of wandfrom wand.image import Imagefrom wand.drawing import Drawingfrom wand.color import Colorimport math with Drawing() as draw: draw.fill_color = Color('GREEN') draw.rectangle(left = 25, top = 50, right = 175, bottom = 150, radius = 25) with Image(width = 200, height = 200, background = Color('lightgreen')) as image: draw(image) image.save(filename = \"rectangle.png\")",
"e": 27765,
"s": 27313,
"text": null
},
{
"code": null,
"e": 27773,
"s": 27765,
"text": "Output:"
},
{
"code": null,
"e": 27785,
"s": 27773,
"text": "Python-wand"
},
{
"code": null,
"e": 27792,
"s": 27785,
"text": "Python"
},
{
"code": null,
"e": 27890,
"s": 27792,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27908,
"s": 27890,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27943,
"s": 27908,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 27975,
"s": 27943,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27997,
"s": 27975,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28039,
"s": 27997,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28069,
"s": 28039,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 28095,
"s": 28069,
"text": "Python String | replace()"
},
{
"code": null,
"e": 28139,
"s": 28095,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 28168,
"s": 28139,
"text": "*args and **kwargs in Python"
}
] |
Print a 2 D Array or Matrix in Java - GeeksforGeeks | 19 Feb, 2021
Prerequisites: Arrays in Java, Array Declarations in Java (Single and Multidimensional)
Method 1 (Simple Traversal)
We can find the number of rows in a matrix mat[][] using mat.length. To find the number of columns in i-th row, we use mat[i].length.
Java
// Java program to print the elements of// a 2 D array or matriximport java.io.*;class GFG { public static void print2D(int mat[][]) { // Loop through all rows for (int i = 0; i < mat.length; i++) // Loop through all elements of current row for (int j = 0; j < mat[i].length; j++) System.out.print(mat[i][j] + " "); } public static void main(String args[]) throws IOException { int mat[][] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } }; print2D(mat); }}
1 2 3 4 5 6 7 8 9 10 11 12
Method 2 (Using for-each loop)
This is similar to the above. Instead of simple for loops, we use for each loop here.
Java
// Java program to print the elements of// a 2 D array or matrix using for-eachimport java.io.*;class GFG { public static void print2D(int mat[][]) { // Loop through all rows for (int[] row : mat) // Loop through all columns of current row for (int x : row) System.out.print(x + " "); } public static void main(String args[]) throws IOException { int mat[][] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } }; print2D(mat); }}
1 2 3 4 5 6 7 8 9 10 11 12
Method 3 (Prints in matrix style Using Arrays.toString())
Arrays.toString(row) converts the complete row is converted as a string and then each row is printed in a separate line.
Java
// Java program to print the elements of// a 2 D array or matrix using toString()import java.io.*;import java.util.*;class GFG { public static void print2D(int mat[][]) { // Loop through all rows for (int[] row : mat) // converting each row as string // and then printing in a separate line System.out.println(Arrays.toString(row)); } public static void main(String args[]) throws IOException { int mat[][] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } }; print2D(mat); }}
[1, 2, 3, 4]
[5, 6, 7, 8]
[9, 10, 11, 12]
Method 4 (Prints in matrix style Using Arrays.deepToString())
Arrays.deepToString(int[][]) converts 2D array to string in a single step.
Java
// Java program to print the elements of// a 2 D array or matrix using deepToString()import java.io.*;import java.util.*;class GFG { public static void print2D(int mat[][]) { System.out.println(Arrays.deepToString(mat)); } public static void main(String args[]) throws IOException { int mat[][] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } }; print2D(mat); }}
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
This article is contributed by Nikita Tiwari & Lovesh Dongre. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
loveshdongre57
Java-Array-Programs
Java-Arrays
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
Stream In Java
HashMap in Java with Examples
Interfaces in Java
How to iterate any Map in Java
Initialize an ArrayList in Java
ArrayList in Java
Stack Class in Java
Singleton Class in Java
Set in Java | [
{
"code": null,
"e": 26257,
"s": 26229,
"text": "\n19 Feb, 2021"
},
{
"code": null,
"e": 26345,
"s": 26257,
"text": "Prerequisites: Arrays in Java, Array Declarations in Java (Single and Multidimensional)"
},
{
"code": null,
"e": 26374,
"s": 26345,
"text": "Method 1 (Simple Traversal) "
},
{
"code": null,
"e": 26508,
"s": 26374,
"text": "We can find the number of rows in a matrix mat[][] using mat.length. To find the number of columns in i-th row, we use mat[i].length."
},
{
"code": null,
"e": 26513,
"s": 26508,
"text": "Java"
},
{
"code": "// Java program to print the elements of// a 2 D array or matriximport java.io.*;class GFG { public static void print2D(int mat[][]) { // Loop through all rows for (int i = 0; i < mat.length; i++) // Loop through all elements of current row for (int j = 0; j < mat[i].length; j++) System.out.print(mat[i][j] + \" \"); } public static void main(String args[]) throws IOException { int mat[][] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } }; print2D(mat); }}",
"e": 27116,
"s": 26513,
"text": null
},
{
"code": null,
"e": 27144,
"s": 27116,
"text": "1 2 3 4 5 6 7 8 9 10 11 12 "
},
{
"code": null,
"e": 27176,
"s": 27144,
"text": "Method 2 (Using for-each loop) "
},
{
"code": null,
"e": 27263,
"s": 27176,
"text": "This is similar to the above. Instead of simple for loops, we use for each loop here. "
},
{
"code": null,
"e": 27268,
"s": 27263,
"text": "Java"
},
{
"code": "// Java program to print the elements of// a 2 D array or matrix using for-eachimport java.io.*;class GFG { public static void print2D(int mat[][]) { // Loop through all rows for (int[] row : mat) // Loop through all columns of current row for (int x : row) System.out.print(x + \" \"); } public static void main(String args[]) throws IOException { int mat[][] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } }; print2D(mat); }}",
"e": 27840,
"s": 27268,
"text": null
},
{
"code": null,
"e": 27868,
"s": 27840,
"text": "1 2 3 4 5 6 7 8 9 10 11 12 "
},
{
"code": null,
"e": 27927,
"s": 27868,
"text": "Method 3 (Prints in matrix style Using Arrays.toString()) "
},
{
"code": null,
"e": 28049,
"s": 27927,
"text": "Arrays.toString(row) converts the complete row is converted as a string and then each row is printed in a separate line. "
},
{
"code": null,
"e": 28054,
"s": 28049,
"text": "Java"
},
{
"code": "// Java program to print the elements of// a 2 D array or matrix using toString()import java.io.*;import java.util.*;class GFG { public static void print2D(int mat[][]) { // Loop through all rows for (int[] row : mat) // converting each row as string // and then printing in a separate line System.out.println(Arrays.toString(row)); } public static void main(String args[]) throws IOException { int mat[][] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } }; print2D(mat); }}",
"e": 28670,
"s": 28054,
"text": null
},
{
"code": null,
"e": 28712,
"s": 28670,
"text": "[1, 2, 3, 4]\n[5, 6, 7, 8]\n[9, 10, 11, 12]"
},
{
"code": null,
"e": 28774,
"s": 28712,
"text": "Method 4 (Prints in matrix style Using Arrays.deepToString())"
},
{
"code": null,
"e": 28850,
"s": 28774,
"text": "Arrays.deepToString(int[][]) converts 2D array to string in a single step."
},
{
"code": null,
"e": 28855,
"s": 28850,
"text": "Java"
},
{
"code": "// Java program to print the elements of// a 2 D array or matrix using deepToString()import java.io.*;import java.util.*;class GFG { public static void print2D(int mat[][]) { System.out.println(Arrays.deepToString(mat)); } public static void main(String args[]) throws IOException { int mat[][] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } }; print2D(mat); }}",
"e": 29318,
"s": 28855,
"text": null
},
{
"code": null,
"e": 29364,
"s": 29318,
"text": "[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]"
},
{
"code": null,
"e": 29805,
"s": 29364,
"text": "This article is contributed by Nikita Tiwari & Lovesh Dongre. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 29820,
"s": 29805,
"text": "loveshdongre57"
},
{
"code": null,
"e": 29840,
"s": 29820,
"text": "Java-Array-Programs"
},
{
"code": null,
"e": 29852,
"s": 29840,
"text": "Java-Arrays"
},
{
"code": null,
"e": 29857,
"s": 29852,
"text": "Java"
},
{
"code": null,
"e": 29862,
"s": 29857,
"text": "Java"
},
{
"code": null,
"e": 29960,
"s": 29862,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30011,
"s": 29960,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 30026,
"s": 30011,
"text": "Stream In Java"
},
{
"code": null,
"e": 30056,
"s": 30026,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 30075,
"s": 30056,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 30106,
"s": 30075,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 30138,
"s": 30106,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 30156,
"s": 30138,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 30176,
"s": 30156,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 30200,
"s": 30176,
"text": "Singleton Class in Java"
}
] |
Convert a Binary Tree into Doubly Linked List in spiral fashion - GeeksforGeeks | 02 Mar, 2022
Given a Binary Tree, convert it into Doubly Linked List where the nodes are represented Spirally. The left pointer of the binary tree node should act as a previous node for created DLL and right pointer should act as next node. The solution should not allocate extra memory for DLL nodes. It should use binary tree nodes for creating DLL i.e. only change of pointers is allowed
For example, for the tree on left side, Doubly Linked List can be,1 2 3 7 6 5 4 8 9 10 11 13 14 or1 3 2 4 5 6 7 14 13 11 10 9 8.We strongly recommend you to minimize your browser and try this yourself first.We can do this by doing a spiral order traversal in O(n) time and O(n) extra space. The idea is to use deque (Double-ended queue) that can be expanded or contracted on both ends (either its front or its back). We do something similar to level order traversal but to maintain spiral order, for every odd level, we dequeue node from the front and inserts its left and right children in the back of the deque data structure. And for each even level, we dequeue node from the back and inserts its right and left children in the front of deque. We also maintain a stack to store Binary Tree nodes. Whenever we pop nodes from deque, we push that node into stack. Later, we pop all nodes from stack and push the nodes in the beginning of the list. We can avoid use of stack if we maintain a tail pointer that always points to last node of DLL and inserts nodes in O(1) time in the end.Below is the implementation of above idea
C++
Java
Python3
C#
Javascript
/* c++ program to convert Binary Tree into Doubly Linked List where the nodes are represented spirally. */#include <bits/stdc++.h>using namespace std; // A Binary Tree Nodestruct Node{ int data; struct Node *left, *right;}; /* Given a reference to the head of a list and a node,inserts the node on the front of the list. */void push(Node** head_ref, Node* node){ // Make right of given node as head and left as // NULL node->right = (*head_ref); node->left = NULL; // change left of head node to given node if ((*head_ref) != NULL) (*head_ref)->left = node ; // move the head to point to the given node (*head_ref) = node;} // Function to prints contents of DLLvoid printList(Node *node){ while (node != NULL) { cout << node->data << " "; node = node->right; }} /* Function to print corner node at each level */void spiralLevelOrder(Node *root){ // Base Case if (root == NULL) return; // Create an empty deque for doing spiral // level order traversal and enqueue root deque<Node*> q; q.push_front(root); // create a stack to store Binary Tree nodes // to insert into DLL later stack<Node*> stk; int level = 0; while (!q.empty()) { // nodeCount indicates number of Nodes // at current level. int nodeCount = q.size(); // Dequeue all Nodes of current level and // Enqueue all Nodes of next level if (level&1) //odd level { while (nodeCount > 0) { // dequeue node from front & push it to // stack Node *node = q.front(); q.pop_front(); stk.push(node); // insert its left and right children // in the back of the deque if (node->left != NULL) q.push_back(node->left); if (node->right != NULL) q.push_back(node->right); nodeCount--; } } else //even level { while (nodeCount > 0) { // dequeue node from the back & push it // to stack Node *node = q.back(); q.pop_back(); stk.push(node); // inserts its right and left children // in the front of the deque if (node->right != NULL) q.push_front(node->right); if (node->left != NULL) q.push_front(node->left); nodeCount--; } } level++; } // head pointer for DLL Node* head = NULL; // pop all nodes from stack and // push them in the beginning of the list while (!stk.empty()) { push(&head, stk.top()); stk.pop(); } cout << "Created DLL is:\n"; printList(head);} // Utility function to create a new tree NodeNode* newNode(int data){ Node *temp = new Node; temp->data = data; temp->left = temp->right = NULL; return temp;} // Driver program to test above functionsint main(){ // Let us create binary tree shown in above diagram Node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(6); root->right->right = newNode(7); root->left->left->left = newNode(8); root->left->left->right = newNode(9); root->left->right->left = newNode(10); root->left->right->right = newNode(11); //root->right->left->left = newNode(12); root->right->left->right = newNode(13); root->right->right->left = newNode(14); //root->right->right->right = newNode(15); spiralLevelOrder(root); return 0;}
/* Java program to convert Binary Tree into Doubly Linked List where the nodes are represented spirally */ import java.util.*; // A binary tree nodeclass Node{ int data; Node left, right; public Node(int data) { this.data = data; left = right = null; }} class BinaryTree{ Node root; Node head; /* Given a reference to a node, inserts the node on the front of the list. */ void push(Node node) { // Make right of given node as head and left as // NULL node.right = head; node.left = null; // change left of head node to given node if (head != null) head.left = node; // move the head to point to the given node head = node; } // Function to prints contents of DLL void printList(Node node) { while (node != null) { System.out.print(node.data + " "); node = node.right; } } /* Function to print corner node at each level */ void spiralLevelOrder(Node root) { // Base Case if (root == null) return; // Create an empty deque for doing spiral // level order traversal and enqueue root Deque<Node> q = new LinkedList<Node>(); q.addFirst(root); // create a stack to store Binary Tree nodes // to insert into DLL later Stack<Node> stk = new Stack<Node>(); int level = 0; while (!q.isEmpty()) { // nodeCount indicates number of Nodes // at current level. int nodeCount = q.size(); // Dequeue all Nodes of current level and // Enqueue all Nodes of next level if ((level & 1) %2 != 0) //odd level { while (nodeCount > 0) { // dequeue node from front & push it to // stack Node node = q.peekFirst(); q.pollFirst(); stk.push(node); // insert its left and right children // in the back of the deque if (node.left != null) q.addLast(node.left); if (node.right != null) q.addLast(node.right); nodeCount--; } } else //even level { while (nodeCount > 0) { // dequeue node from the back & push it // to stack Node node = q.peekLast(); q.pollLast(); stk.push(node); // inserts its right and left children // in the front of the deque if (node.right != null) q.addFirst(node.right); if (node.left != null) q.addFirst(node.left); nodeCount--; } } level++; } // pop all nodes from stack and // push them in the beginning of the list while (!stk.empty()) { push(stk.peek()); stk.pop(); } System.out.println("Created DLL is : "); printList(head); } // Driver program to test above functions public static void main(String[] args) { // Let us create binary tree as shown in above diagram BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); tree.root.right.left = new Node(6); tree.root.right.right = new Node(7); tree.root.left.left.left = new Node(8); tree.root.left.left.right = new Node(9); tree.root.left.right.left = new Node(10); tree.root.left.right.right = new Node(11); // tree.root.right.left.left = new Node(12); tree.root.right.left.right = new Node(13); tree.root.right.right.left = new Node(14); // tree.root.right.right.right = new Node(15); tree.spiralLevelOrder(tree.root); }} // This code has been contributed by Mayank Jaiswal(mayank_24)
# Python3 program to convert Binary Tree# into Doubly Linked List where the nodes# are represented spirally. # Binary tree nodeclass newNode: # Constructor to create a newNode def __init__(self, data): self.data = data self.left = None self.right = None """ Given a reference to the head of a list and a node, inserts the node on the front of the list. """def push(head_ref, node): # Make right of given node as # head and left as None node.right = (head_ref) node.left = None # change left of head node to # given node if ((head_ref) != None): (head_ref).left = node # move the head to point to # the given node (head_ref) = node # Function to prints contents of DLLdef printList(node): i = 0 while (i < len(node)): print(node[i].data, end = " ") i += 1 """ Function to print corner node at each level """def spiralLevelOrder(root): # Base Case if (root == None): return # Create an empty deque for doing spiral # level order traversal and enqueue root q = [] q.append(root) # create a stack to store Binary # Tree nodes to insert into DLL later stk = [] level = 0 while (len(q)): # nodeCount indicates number of # Nodes at current level. nodeCount = len(q) # Dequeue all Nodes of current level # and Enqueue all Nodes of next level if (level&1): # odd level while (nodeCount > 0): # dequeue node from front & # push it to stack node = q[0] q.pop(0) stk.append(node) # insert its left and right children # in the back of the deque if (node.left != None): q.append(node.left) if (node.right != None): q.append(node.right) nodeCount -= 1 else: # even level while (nodeCount > 0): # dequeue node from the back & # push it to stack node = q[-1] q.pop(-1) stk.append(node) # inserts its right and left # children in the front of # the deque if (node.right != None): q.insert(0, node.right) if (node.left != None): q.insert(0, node.left) nodeCount -= 1 level += 1 # head pointer for DLL head = [] # pop all nodes from stack and push # them in the beginning of the list while (len(stk)): head.append(stk[0]) stk.pop(0) print("Created DLL is:") printList(head) # Driver Codeif __name__ == '__main__': """Let us create Binary Tree as shown in above example """ root = newNode(1) root.left = newNode(2) root.right = newNode(3) root.left.left = newNode(4) root.left.right = newNode(5) root.right.left = newNode(6) root.right.right = newNode(7) root.left.left.left = newNode(8) root.left.left.right = newNode(9) root.left.right.left = newNode(10) root.left.right.right = newNode(11) #root.right.left.left = newNode(12) root.right.left.right = newNode(13) root.right.right.left = newNode(14) #root.right.right.right = newNode(15) spiralLevelOrder(root) # This code is contributed# by SHUBHAMSINGH10
/* C# program to convert Binary Tree into Doubly Linked Listwhere the nodes are represented spirally */using System;using System.Collections.Generic; // A binary tree nodepublic class Node{ public int data; public Node left, right; public Node(int data) { this.data = data; left = right = null; }} public class BinaryTree{ Node root; Node head; /* Given a reference to a node, inserts the node on the front of the list. */ void push(Node node) { // Make right of given node as head and left as // NULL node.right = head; node.left = null; // change left of head node to given node if (head != null) head.left = node; // move the head to point to the given node head = node; } // Function to prints contents of DLL void printList(Node node) { while (node != null) { Console.Write(node.data + " "); node = node.right; } } /* Function to print corner node at each level */ void spiralLevelOrder(Node root) { // Base Case if (root == null) return; // Create an empty deque for doing spiral // level order traversal and enqueue root LinkedList<Node> q = new LinkedList<Node>(); q.AddFirst(root); // create a stack to store Binary Tree nodes // to insert into DLL later Stack<Node> stk = new Stack<Node>(); int level = 0; while (q.Count != 0) { // nodeCount indicates number of Nodes // at current level. int nodeCount = q.Count; // Dequeue all Nodes of current level and // Enqueue all Nodes of next level if ((level & 1) % 2 != 0) //odd level { while (nodeCount > 0) { // dequeue node from front & push it to // stack Node node = q.First.Value; q.RemoveFirst(); stk.Push(node); // insert its left and right children // in the back of the deque if (node.left != null) q.AddLast(node.left); if (node.right != null) q.AddLast(node.right); nodeCount--; } } else //even level { while (nodeCount > 0) { // dequeue node from the back & push it // to stack Node node = q.Last.Value; q.RemoveLast(); stk.Push(node); // inserts its right and left children // in the front of the deque if (node.right != null) q.AddFirst(node.right); if (node.left != null) q.AddFirst(node.left); nodeCount--; } } level++; } // pop all nodes from stack and // push them in the beginning of the list while (stk.Count != 0) { push(stk.Peek()); stk.Pop(); } Console.WriteLine("Created DLL is : "); printList(head); } // Driver program to test above functions public static void Main(String[] args) { // Let us create binary tree as shown in above diagram BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); tree.root.right.left = new Node(6); tree.root.right.right = new Node(7); tree.root.left.left.left = new Node(8); tree.root.left.left.right = new Node(9); tree.root.left.right.left = new Node(10); tree.root.left.right.right = new Node(11); // tree.root.right.left.left = new Node(12); tree.root.right.left.right = new Node(13); tree.root.right.right.left = new Node(14); // tree.root.right.right.right = new Node(15); tree.spiralLevelOrder(tree.root); }} /* This code contributed by PrinciRaj1992 */
<script> /* Javascript program to convert Binary Tree into Doubly Linked Listwhere the nodes are represented spirally */ // A binary tree nodeclass Node{ constructor(data) { this.data = data; this.left = null; this.right = null; }} var root = null;var head = null;/* Given a reference to a node,inserts the node on the front of the list. */function push(node){ // Make right of given node as head and left as // NULL node.right = head; node.left = null; // change left of head node to given node if (head != null) head.left = node; // move the head to point to the given node head = node;}// Function to prints contents of DLLfunction printList(node){ while (node != null) { document.write(node.data + " "); node = node.right; }}/* Function to print corner node at each level */function spiralLevelOrder(root){ // Base Case if (root == null) return; // Create an empty deque for doing spiral // level order traversal and enqueue root var q = []; q.unshift(root); // create a stack to store Binary Tree nodes // to insert into DLL later var stk = []; var level = 0; while (q.length != 0) { // nodeCount indicates number of Nodes // at current level. var nodeCount = q.length; // Dequeue all Nodes of current level and // Enqueue all Nodes of next level if ((level & 1) % 2 != 0) //odd level { while (nodeCount > 0) { // dequeue node from front & push it to // stack var node = q[0]; q.shift(); stk.push(node); // insert its left and right children // in the back of the deque if (node.left != null) q.push(node.left); if (node.right != null) q.push(node.right); nodeCount--; } } else //even level { while (nodeCount > 0) { // dequeue node from the back & push it // to stack var node = q[q.length-1]; q.pop(); stk.push(node); // inserts its right and left children // in the front of the deque if (node.right != null) q.unshift(node.right); if (node.left != null) q.unshift(node.left); nodeCount--; } } level++; } // pop all nodes from stack and // push them in the beginning of the list while (stk.length != 0) { push(stk[stk.length-1]); stk.pop(); } document.write("Created DLL is :<br>"); printList(head);} // Driver program to test above functions// Let us create binary tree as shown in above diagramroot = new Node(1);root.left = new Node(2);root.right = new Node(3);root.left.left = new Node(4);root.left.right = new Node(5);root.right.left = new Node(6);root.right.right = new Node(7);root.left.left.left = new Node(8);root.left.left.right = new Node(9);root.left.right.left = new Node(10);root.left.right.right = new Node(11);// tree.root.right.left.left = new Node(12);root.right.left.right = new Node(13);root.right.right.left = new Node(14);// tree.root.right.right.right = new Node(15);spiralLevelOrder(root); // This code is contributed by itsok. </script>
Output :
Created DLL is:
1 2 3 7 6 5 4 8 9 10 11 13 14
YouTubeGeeksforGeeks506K subscribersConvert a Binary Tree into Doubly Linked List in spiral fashion | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 6:08•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=aYWzBYa_QxI" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
SHUBHAMSINGH10
princiraj1992
itsok
surinderdawra388
doubly linked list
spiral
Tree
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Tree Traversals (Inorder, Preorder and Postorder)
AVL Tree | Set 1 (Insertion)
Binary Tree | Set 1 (Introduction)
Level Order Binary Tree Traversal
Binary Tree | Set 3 (Types of Binary Tree)
Inorder Tree Traversal without Recursion
Binary Tree | Set 2 (Properties)
Write a Program to Find the Maximum Depth or Height of a Tree
Decision Tree
A program to check if a binary tree is BST or not | [
{
"code": null,
"e": 37644,
"s": 37616,
"text": "\n02 Mar, 2022"
},
{
"code": null,
"e": 38024,
"s": 37644,
"text": "Given a Binary Tree, convert it into Doubly Linked List where the nodes are represented Spirally. The left pointer of the binary tree node should act as a previous node for created DLL and right pointer should act as next node. The solution should not allocate extra memory for DLL nodes. It should use binary tree nodes for creating DLL i.e. only change of pointers is allowed "
},
{
"code": null,
"e": 39153,
"s": 38024,
"text": "For example, for the tree on left side, Doubly Linked List can be,1 2 3 7 6 5 4 8 9 10 11 13 14 or1 3 2 4 5 6 7 14 13 11 10 9 8.We strongly recommend you to minimize your browser and try this yourself first.We can do this by doing a spiral order traversal in O(n) time and O(n) extra space. The idea is to use deque (Double-ended queue) that can be expanded or contracted on both ends (either its front or its back). We do something similar to level order traversal but to maintain spiral order, for every odd level, we dequeue node from the front and inserts its left and right children in the back of the deque data structure. And for each even level, we dequeue node from the back and inserts its right and left children in the front of deque. We also maintain a stack to store Binary Tree nodes. Whenever we pop nodes from deque, we push that node into stack. Later, we pop all nodes from stack and push the nodes in the beginning of the list. We can avoid use of stack if we maintain a tail pointer that always points to last node of DLL and inserts nodes in O(1) time in the end.Below is the implementation of above idea "
},
{
"code": null,
"e": 39157,
"s": 39153,
"text": "C++"
},
{
"code": null,
"e": 39162,
"s": 39157,
"text": "Java"
},
{
"code": null,
"e": 39170,
"s": 39162,
"text": "Python3"
},
{
"code": null,
"e": 39173,
"s": 39170,
"text": "C#"
},
{
"code": null,
"e": 39184,
"s": 39173,
"text": "Javascript"
},
{
"code": "/* c++ program to convert Binary Tree into Doubly Linked List where the nodes are represented spirally. */#include <bits/stdc++.h>using namespace std; // A Binary Tree Nodestruct Node{ int data; struct Node *left, *right;}; /* Given a reference to the head of a list and a node,inserts the node on the front of the list. */void push(Node** head_ref, Node* node){ // Make right of given node as head and left as // NULL node->right = (*head_ref); node->left = NULL; // change left of head node to given node if ((*head_ref) != NULL) (*head_ref)->left = node ; // move the head to point to the given node (*head_ref) = node;} // Function to prints contents of DLLvoid printList(Node *node){ while (node != NULL) { cout << node->data << \" \"; node = node->right; }} /* Function to print corner node at each level */void spiralLevelOrder(Node *root){ // Base Case if (root == NULL) return; // Create an empty deque for doing spiral // level order traversal and enqueue root deque<Node*> q; q.push_front(root); // create a stack to store Binary Tree nodes // to insert into DLL later stack<Node*> stk; int level = 0; while (!q.empty()) { // nodeCount indicates number of Nodes // at current level. int nodeCount = q.size(); // Dequeue all Nodes of current level and // Enqueue all Nodes of next level if (level&1) //odd level { while (nodeCount > 0) { // dequeue node from front & push it to // stack Node *node = q.front(); q.pop_front(); stk.push(node); // insert its left and right children // in the back of the deque if (node->left != NULL) q.push_back(node->left); if (node->right != NULL) q.push_back(node->right); nodeCount--; } } else //even level { while (nodeCount > 0) { // dequeue node from the back & push it // to stack Node *node = q.back(); q.pop_back(); stk.push(node); // inserts its right and left children // in the front of the deque if (node->right != NULL) q.push_front(node->right); if (node->left != NULL) q.push_front(node->left); nodeCount--; } } level++; } // head pointer for DLL Node* head = NULL; // pop all nodes from stack and // push them in the beginning of the list while (!stk.empty()) { push(&head, stk.top()); stk.pop(); } cout << \"Created DLL is:\\n\"; printList(head);} // Utility function to create a new tree NodeNode* newNode(int data){ Node *temp = new Node; temp->data = data; temp->left = temp->right = NULL; return temp;} // Driver program to test above functionsint main(){ // Let us create binary tree shown in above diagram Node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(6); root->right->right = newNode(7); root->left->left->left = newNode(8); root->left->left->right = newNode(9); root->left->right->left = newNode(10); root->left->right->right = newNode(11); //root->right->left->left = newNode(12); root->right->left->right = newNode(13); root->right->right->left = newNode(14); //root->right->right->right = newNode(15); spiralLevelOrder(root); return 0;}",
"e": 42986,
"s": 39184,
"text": null
},
{
"code": "/* Java program to convert Binary Tree into Doubly Linked List where the nodes are represented spirally */ import java.util.*; // A binary tree nodeclass Node{ int data; Node left, right; public Node(int data) { this.data = data; left = right = null; }} class BinaryTree{ Node root; Node head; /* Given a reference to a node, inserts the node on the front of the list. */ void push(Node node) { // Make right of given node as head and left as // NULL node.right = head; node.left = null; // change left of head node to given node if (head != null) head.left = node; // move the head to point to the given node head = node; } // Function to prints contents of DLL void printList(Node node) { while (node != null) { System.out.print(node.data + \" \"); node = node.right; } } /* Function to print corner node at each level */ void spiralLevelOrder(Node root) { // Base Case if (root == null) return; // Create an empty deque for doing spiral // level order traversal and enqueue root Deque<Node> q = new LinkedList<Node>(); q.addFirst(root); // create a stack to store Binary Tree nodes // to insert into DLL later Stack<Node> stk = new Stack<Node>(); int level = 0; while (!q.isEmpty()) { // nodeCount indicates number of Nodes // at current level. int nodeCount = q.size(); // Dequeue all Nodes of current level and // Enqueue all Nodes of next level if ((level & 1) %2 != 0) //odd level { while (nodeCount > 0) { // dequeue node from front & push it to // stack Node node = q.peekFirst(); q.pollFirst(); stk.push(node); // insert its left and right children // in the back of the deque if (node.left != null) q.addLast(node.left); if (node.right != null) q.addLast(node.right); nodeCount--; } } else //even level { while (nodeCount > 0) { // dequeue node from the back & push it // to stack Node node = q.peekLast(); q.pollLast(); stk.push(node); // inserts its right and left children // in the front of the deque if (node.right != null) q.addFirst(node.right); if (node.left != null) q.addFirst(node.left); nodeCount--; } } level++; } // pop all nodes from stack and // push them in the beginning of the list while (!stk.empty()) { push(stk.peek()); stk.pop(); } System.out.println(\"Created DLL is : \"); printList(head); } // Driver program to test above functions public static void main(String[] args) { // Let us create binary tree as shown in above diagram BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); tree.root.right.left = new Node(6); tree.root.right.right = new Node(7); tree.root.left.left.left = new Node(8); tree.root.left.left.right = new Node(9); tree.root.left.right.left = new Node(10); tree.root.left.right.right = new Node(11); // tree.root.right.left.left = new Node(12); tree.root.right.left.right = new Node(13); tree.root.right.right.left = new Node(14); // tree.root.right.right.right = new Node(15); tree.spiralLevelOrder(tree.root); }} // This code has been contributed by Mayank Jaiswal(mayank_24)",
"e": 47282,
"s": 42986,
"text": null
},
{
"code": "# Python3 program to convert Binary Tree# into Doubly Linked List where the nodes# are represented spirally. # Binary tree nodeclass newNode: # Constructor to create a newNode def __init__(self, data): self.data = data self.left = None self.right = None \"\"\" Given a reference to the head of a list and a node, inserts the node on the front of the list. \"\"\"def push(head_ref, node): # Make right of given node as # head and left as None node.right = (head_ref) node.left = None # change left of head node to # given node if ((head_ref) != None): (head_ref).left = node # move the head to point to # the given node (head_ref) = node # Function to prints contents of DLLdef printList(node): i = 0 while (i < len(node)): print(node[i].data, end = \" \") i += 1 \"\"\" Function to print corner node at each level \"\"\"def spiralLevelOrder(root): # Base Case if (root == None): return # Create an empty deque for doing spiral # level order traversal and enqueue root q = [] q.append(root) # create a stack to store Binary # Tree nodes to insert into DLL later stk = [] level = 0 while (len(q)): # nodeCount indicates number of # Nodes at current level. nodeCount = len(q) # Dequeue all Nodes of current level # and Enqueue all Nodes of next level if (level&1): # odd level while (nodeCount > 0): # dequeue node from front & # push it to stack node = q[0] q.pop(0) stk.append(node) # insert its left and right children # in the back of the deque if (node.left != None): q.append(node.left) if (node.right != None): q.append(node.right) nodeCount -= 1 else: # even level while (nodeCount > 0): # dequeue node from the back & # push it to stack node = q[-1] q.pop(-1) stk.append(node) # inserts its right and left # children in the front of # the deque if (node.right != None): q.insert(0, node.right) if (node.left != None): q.insert(0, node.left) nodeCount -= 1 level += 1 # head pointer for DLL head = [] # pop all nodes from stack and push # them in the beginning of the list while (len(stk)): head.append(stk[0]) stk.pop(0) print(\"Created DLL is:\") printList(head) # Driver Codeif __name__ == '__main__': \"\"\"Let us create Binary Tree as shown in above example \"\"\" root = newNode(1) root.left = newNode(2) root.right = newNode(3) root.left.left = newNode(4) root.left.right = newNode(5) root.right.left = newNode(6) root.right.right = newNode(7) root.left.left.left = newNode(8) root.left.left.right = newNode(9) root.left.right.left = newNode(10) root.left.right.right = newNode(11) #root.right.left.left = newNode(12) root.right.left.right = newNode(13) root.right.right.left = newNode(14) #root.right.right.right = newNode(15) spiralLevelOrder(root) # This code is contributed# by SHUBHAMSINGH10",
"e": 50783,
"s": 47282,
"text": null
},
{
"code": "/* C# program to convert Binary Tree into Doubly Linked Listwhere the nodes are represented spirally */using System;using System.Collections.Generic; // A binary tree nodepublic class Node{ public int data; public Node left, right; public Node(int data) { this.data = data; left = right = null; }} public class BinaryTree{ Node root; Node head; /* Given a reference to a node, inserts the node on the front of the list. */ void push(Node node) { // Make right of given node as head and left as // NULL node.right = head; node.left = null; // change left of head node to given node if (head != null) head.left = node; // move the head to point to the given node head = node; } // Function to prints contents of DLL void printList(Node node) { while (node != null) { Console.Write(node.data + \" \"); node = node.right; } } /* Function to print corner node at each level */ void spiralLevelOrder(Node root) { // Base Case if (root == null) return; // Create an empty deque for doing spiral // level order traversal and enqueue root LinkedList<Node> q = new LinkedList<Node>(); q.AddFirst(root); // create a stack to store Binary Tree nodes // to insert into DLL later Stack<Node> stk = new Stack<Node>(); int level = 0; while (q.Count != 0) { // nodeCount indicates number of Nodes // at current level. int nodeCount = q.Count; // Dequeue all Nodes of current level and // Enqueue all Nodes of next level if ((level & 1) % 2 != 0) //odd level { while (nodeCount > 0) { // dequeue node from front & push it to // stack Node node = q.First.Value; q.RemoveFirst(); stk.Push(node); // insert its left and right children // in the back of the deque if (node.left != null) q.AddLast(node.left); if (node.right != null) q.AddLast(node.right); nodeCount--; } } else //even level { while (nodeCount > 0) { // dequeue node from the back & push it // to stack Node node = q.Last.Value; q.RemoveLast(); stk.Push(node); // inserts its right and left children // in the front of the deque if (node.right != null) q.AddFirst(node.right); if (node.left != null) q.AddFirst(node.left); nodeCount--; } } level++; } // pop all nodes from stack and // push them in the beginning of the list while (stk.Count != 0) { push(stk.Peek()); stk.Pop(); } Console.WriteLine(\"Created DLL is : \"); printList(head); } // Driver program to test above functions public static void Main(String[] args) { // Let us create binary tree as shown in above diagram BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); tree.root.right.left = new Node(6); tree.root.right.right = new Node(7); tree.root.left.left.left = new Node(8); tree.root.left.left.right = new Node(9); tree.root.left.right.left = new Node(10); tree.root.left.right.right = new Node(11); // tree.root.right.left.left = new Node(12); tree.root.right.left.right = new Node(13); tree.root.right.right.left = new Node(14); // tree.root.right.right.right = new Node(15); tree.spiralLevelOrder(tree.root); }} /* This code contributed by PrinciRaj1992 */",
"e": 55114,
"s": 50783,
"text": null
},
{
"code": "<script> /* Javascript program to convert Binary Tree into Doubly Linked Listwhere the nodes are represented spirally */ // A binary tree nodeclass Node{ constructor(data) { this.data = data; this.left = null; this.right = null; }} var root = null;var head = null;/* Given a reference to a node,inserts the node on the front of the list. */function push(node){ // Make right of given node as head and left as // NULL node.right = head; node.left = null; // change left of head node to given node if (head != null) head.left = node; // move the head to point to the given node head = node;}// Function to prints contents of DLLfunction printList(node){ while (node != null) { document.write(node.data + \" \"); node = node.right; }}/* Function to print corner node at each level */function spiralLevelOrder(root){ // Base Case if (root == null) return; // Create an empty deque for doing spiral // level order traversal and enqueue root var q = []; q.unshift(root); // create a stack to store Binary Tree nodes // to insert into DLL later var stk = []; var level = 0; while (q.length != 0) { // nodeCount indicates number of Nodes // at current level. var nodeCount = q.length; // Dequeue all Nodes of current level and // Enqueue all Nodes of next level if ((level & 1) % 2 != 0) //odd level { while (nodeCount > 0) { // dequeue node from front & push it to // stack var node = q[0]; q.shift(); stk.push(node); // insert its left and right children // in the back of the deque if (node.left != null) q.push(node.left); if (node.right != null) q.push(node.right); nodeCount--; } } else //even level { while (nodeCount > 0) { // dequeue node from the back & push it // to stack var node = q[q.length-1]; q.pop(); stk.push(node); // inserts its right and left children // in the front of the deque if (node.right != null) q.unshift(node.right); if (node.left != null) q.unshift(node.left); nodeCount--; } } level++; } // pop all nodes from stack and // push them in the beginning of the list while (stk.length != 0) { push(stk[stk.length-1]); stk.pop(); } document.write(\"Created DLL is :<br>\"); printList(head);} // Driver program to test above functions// Let us create binary tree as shown in above diagramroot = new Node(1);root.left = new Node(2);root.right = new Node(3);root.left.left = new Node(4);root.left.right = new Node(5);root.right.left = new Node(6);root.right.right = new Node(7);root.left.left.left = new Node(8);root.left.left.right = new Node(9);root.left.right.left = new Node(10);root.left.right.right = new Node(11);// tree.root.right.left.left = new Node(12);root.right.left.right = new Node(13);root.right.right.left = new Node(14);// tree.root.right.right.right = new Node(15);spiralLevelOrder(root); // This code is contributed by itsok. </script>",
"e": 58573,
"s": 55114,
"text": null
},
{
"code": null,
"e": 58583,
"s": 58573,
"text": "Output : "
},
{
"code": null,
"e": 58630,
"s": 58583,
"text": "Created DLL is:\n1 2 3 7 6 5 4 8 9 10 11 13 14 "
},
{
"code": null,
"e": 59494,
"s": 58632,
"text": "YouTubeGeeksforGeeks506K subscribersConvert a Binary Tree into Doubly Linked List in spiral fashion | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 6:08•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=aYWzBYa_QxI\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>"
},
{
"code": null,
"e": 59884,
"s": 59494,
"text": "This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 59899,
"s": 59884,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 59913,
"s": 59899,
"text": "princiraj1992"
},
{
"code": null,
"e": 59919,
"s": 59913,
"text": "itsok"
},
{
"code": null,
"e": 59936,
"s": 59919,
"text": "surinderdawra388"
},
{
"code": null,
"e": 59955,
"s": 59936,
"text": "doubly linked list"
},
{
"code": null,
"e": 59962,
"s": 59955,
"text": "spiral"
},
{
"code": null,
"e": 59967,
"s": 59962,
"text": "Tree"
},
{
"code": null,
"e": 59972,
"s": 59967,
"text": "Tree"
},
{
"code": null,
"e": 60070,
"s": 59972,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 60120,
"s": 60070,
"text": "Tree Traversals (Inorder, Preorder and Postorder)"
},
{
"code": null,
"e": 60149,
"s": 60120,
"text": "AVL Tree | Set 1 (Insertion)"
},
{
"code": null,
"e": 60184,
"s": 60149,
"text": "Binary Tree | Set 1 (Introduction)"
},
{
"code": null,
"e": 60218,
"s": 60184,
"text": "Level Order Binary Tree Traversal"
},
{
"code": null,
"e": 60261,
"s": 60218,
"text": "Binary Tree | Set 3 (Types of Binary Tree)"
},
{
"code": null,
"e": 60302,
"s": 60261,
"text": "Inorder Tree Traversal without Recursion"
},
{
"code": null,
"e": 60335,
"s": 60302,
"text": "Binary Tree | Set 2 (Properties)"
},
{
"code": null,
"e": 60397,
"s": 60335,
"text": "Write a Program to Find the Maximum Depth or Height of a Tree"
},
{
"code": null,
"e": 60411,
"s": 60397,
"text": "Decision Tree"
}
] |
NumPy Sorting Arrays | Sorting means putting elements in an ordered sequence.
Ordered sequence is any sequence that has an order corresponding to elements, like numeric or alphabetical, ascending or descending.
The NumPy ndarray object has a function called sort(),
that will sort a specified array.
Sort the array:
Note: This method returns a copy of the array, leaving the
original array unchanged.
You can also sort arrays of strings, or any other data type:
Sort the array alphabetically:
Sort a boolean array:
If you use the sort() method on a 2-D array, both arrays will be sorted:
Sort a 2-D array:
Use the correct NumPy method to return a sorted array.
arr = np.array([3, 2, 0, 1])
x = np.(arr)
Start the Exercise
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. | [
{
"code": null,
"e": 55,
"s": 0,
"text": "Sorting means putting elements in an ordered sequence."
},
{
"code": null,
"e": 188,
"s": 55,
"text": "Ordered sequence is any sequence that has an order corresponding to elements, like numeric or alphabetical, ascending or descending."
},
{
"code": null,
"e": 278,
"s": 188,
"text": "The NumPy ndarray object has a function called sort(), \nthat will sort a specified array."
},
{
"code": null,
"e": 294,
"s": 278,
"text": "Sort the array:"
},
{
"code": null,
"e": 382,
"s": 294,
"text": "Note: This method returns a copy of the array, leaving the \n original array unchanged."
},
{
"code": null,
"e": 443,
"s": 382,
"text": "You can also sort arrays of strings, or any other data type:"
},
{
"code": null,
"e": 474,
"s": 443,
"text": "Sort the array alphabetically:"
},
{
"code": null,
"e": 496,
"s": 474,
"text": "Sort a boolean array:"
},
{
"code": null,
"e": 569,
"s": 496,
"text": "If you use the sort() method on a 2-D array, both arrays will be sorted:"
},
{
"code": null,
"e": 587,
"s": 569,
"text": "Sort a 2-D array:"
},
{
"code": null,
"e": 642,
"s": 587,
"text": "Use the correct NumPy method to return a sorted array."
},
{
"code": null,
"e": 686,
"s": 642,
"text": "arr = np.array([3, 2, 0, 1])\n\nx = np.(arr)\n"
},
{
"code": null,
"e": 705,
"s": 686,
"text": "Start the Exercise"
},
{
"code": null,
"e": 738,
"s": 705,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 780,
"s": 738,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 887,
"s": 780,
"text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:"
},
{
"code": null,
"e": 906,
"s": 887,
"text": "help@w3schools.com"
}
] |
Sentiment analysis on the tweets about distance learning with TextBlob | by Barış Hasdemir | Towards Data Science | Hi everyone,
The Covid19 Pandemic brought about distance learning in the 2020 academic term. Although some people could adapt easily, some of them found it inefficient. Nowadays, the re-opening of schools is being discussed. Most experts suggest that at least one semester should be online again. As a student who passed the last semester with distance learning, I could find a lot of time to spend on learning natural language processing. Finally, I decided to explore what people think about distance learning.
I am planning this story as an end-to-end project. We are going to explore the tweets related to distance learning to understand people’s opinions (a.k.a opinion mining) and to discover facts. I will use the lexicon-based approach to determine the tweets’ polarities (I’ll explain it later). TextBlob will be our tool to do that. We will also build a machine learning model to predict the positivity and the negativity of the tweets by using Bernoulli Naive Bayes Classifier.
Our workflow is the following:
Data Gathering- Twitter API- Retrieve tweets with tweepyPreprocessing and Cleaning- Drop duplicates- Data type conversions- Drop uninformative columns- Get rid of stop words, hashtags, punctuation, and one or two-letter words- Tokenize the words- Apply lemmatization- Term frequency-inverse document frequency vectorizationExploratory Data Analysis- Visualize the data- Compare word counts- Investigate the creation times distribution- Investigate the locations of tweets- Look at the popular tweets and the most frequent words- Make a word cloudSentiment AnalysisMachine LearningSummary
Data Gathering- Twitter API- Retrieve tweets with tweepy
Preprocessing and Cleaning- Drop duplicates- Data type conversions- Drop uninformative columns- Get rid of stop words, hashtags, punctuation, and one or two-letter words- Tokenize the words- Apply lemmatization- Term frequency-inverse document frequency vectorization
Exploratory Data Analysis- Visualize the data- Compare word counts- Investigate the creation times distribution- Investigate the locations of tweets- Look at the popular tweets and the most frequent words- Make a word cloud
Sentiment Analysis
Machine Learning
Summary
Before starting, please make sure that the following libraries are available in your workspace.
pandasnumpymatplotlibseabornTextBlobwordcloudsklearnnltkpickle
You can use the following commands to install non-built-in libraries.
pip install pycountrypip install nltkpip install textblobpip install wordcloudpip install scikit-learnpip install pickle
You can find the entire code here.
First of all, we need a Twitter Developer Account to be allowed to use Twitter API. You can get the account here. It can take a few days to be approved. I have already completed those steps. Once I got the account, I created a text file that contains API information. It is located on the upward directory of the project. The content of the text file is the following. If you want to use it you have to replace the information with yours.
CONSUMER KEY=your_consumer_keyCONSUMER KEY SECRET=your_consumer_key_secretACCESS TOKEN=your_access_tokenACCESS TOKEN SECRET=your_access_token_secret
After that, I created a py file called get_tweets.py to collect tweets (in English only) related to distance learning. You can see the entire code below.
The code above, searches the tweets contain the following hashtags
#distancelearning, #onlineschool, #onlineteaching, #virtuallearning, #onlineducation, #distanceeducation, #OnlineClasses, #DigitalLearning, #elearning, #onlinelearning
and the following keywords
“distance learning”, “online teaching”, “online education”, “online course”, “online semester”, “distance course”, “distance education”, “online class”,” e-learning”, “e learning”
It also filters the retweets to avoid duplication.
The get_tweets function stores the tweets retrieved in a temporary pandas DataFrame and saves as CSV files in the output directory. It approximately took 40 hours to collect 202.645 tweets. After that, It gave me the following files
To concatenate all CSV files into one, I created the concatenate.py file that contains the following code.
Ultimately, we have tweets_raw.csv file. Let’s look at how it looks like.
# Load the tweetstweets_raw = pd.read_csv("tweets_raw.csv")# Display the first five rowsdisplay(tweets_raw.head())# Print the summary statisticsprint(tweets_raw.describe())# Print the infoprint(tweets_raw.info())
At a first glance, we can see that there are 202.645 tweets including the content, location, username, Retweet count, Favorites count, and the creation time features in the DataFrame. There are also some missing values in the Location column. We’ll deal with them in the next step.
According to the information above, Unnamed: 0 and Unnamed: 0.1 columns are not informative to us so we’ll drop them out. The data type of Created at column also should be datetime. As well as we need to get rid of duplicated tweets if there are some.
# We do not need first two columns. Let's drop them out.tweets_raw.drop(columns=["Unnamed: 0", "Unnamed: 0.1"], axis=1, inplace=True)# Drop duplicated rowstweets_raw.drop_duplicates(inplace=True)# Created at column's type should be datatimetweets_raw["Created at"] = pd.to_datetime(tweets_raw["Created at"])# Print the info againprint(tweets_raw.info())
The tweets count has been reduced to 187.052 (There were 15.593 duplicated rows). “Created at” column’s data type is also changed to datatime64[ns].
Now, let’s tidy the tweets’ contents up. We need to get rid of stopwords, punctuation, hashtags, mentions, links, and one or two-letter words. As well as we need to tokenize the tweets.
Tokenization is the splitting of a sentence into words and punctuation marks. The sentence “This is an example.” can be tokenized like [“This”, “is”, “an”, “example”, “.”]
Stopwords are the words that are commonly used and they don’t contribute to the meaning of a sentence such as “a”, “an”, “the”, “on”, “in” and so forth.
Lemmatization is the process of reducing a word to its root form. This root form called a lemma. For example, the lemma of words running runs, and ran is run
Let’s define a function to do all of these operations.
After the function call, our Processed column will be like the following. You see that the tweets are tokenized and they do not contain stopwords, hashtags, links, and one or two-letter words. We also applied the lemmatization operation on them.
We got what we want. Do not worry about words such as learning, online, education, etc. We will deal with them later.
Tweet lengths and number of words in the tweets might be also interesting in the exploratory data analysis. Let’s get them!
# Get the tweet lengthstweets_raw["Length"] = tweets_raw["Content"].str.len()# Get the number of words in tweetstweets_raw["Words"] = tweets_raw["Content"].str.split().str.len()# Display the new columnsdisplay(tweets_raw[["Length", "Words"]])
Notice that we did not use the Processed tweets.
What about the locations?
When we called the info function of tweets_raw DataFrame, we saw that there were some missing values in the “Location” columns. The missing values are indicated as NaN. We’ll fill the missing values with the “unknown” tag.
# Fill the missing values with unknown tagtweets_raw["Location"].fillna("unknown", inplace=True)
How many unique locations we have?
# Print the unique locations and number of unique locationsprint("Unique Values:",tweets_raw["Location"].unique())print("Unique Value count:",len(tweets_raw["Location"].unique()))
The outputs show us the location information is messy. There are 37.119 unique locations. We need to group them by country. To achieve this, we will use the pycountry package in python. If you are interested, you can find further information here.
Let’s define a function called get_countries which returns the country codes of the given locations.
It worked! Now we have 156 unique country codes. We will use them for the exploratory data analysis part.
Now it’s time to vectorize the tweets. We’ll use tf-idf (term frequency-inverse document term frequency) vectorization.
Tf-idf (Term Frequency — Inverse Term Frequency) is a statistical concept to be used to get the frequency of words in the corpus. We’ll use scikit-learn’s TfidfVectorizer. The vectorizer will calculate the weight of each word in the corpus and will return a tf-idf matrix. You can find further information here
td = Term frequency (number of occurrences each i in j)df = Document frequencyN = Number of documentsw = tf-idf weight for each i and j (document).
We are going to select only the top 5000 words for tf-idf vectorization due to memory constraints. You can experiment with more by using other approaches like hashing.
# Create our contextual stop wordstfidf_stops = ["online","class","course","learning","learn",\"teach","teaching","distance","distancelearning","education",\"teacher","student","grade","classes","computer","onlineeducation",\ "onlinelearning", "school", "students","class","virtual","eschool",\ "virtuallearning", "educated", "educates", "teaches", "studies",\ "study", "semester", "elearning","teachers", "lecturer", "lecture",\ "amp","academic", "admission", "academician", "account", "action" \"add", "app", "announcement", "application", "adult", "classroom", "system", "video", "essay", "homework","work","assignment","paper",\ "get", "math", "project", "science", "physics", "lesson","courses",\ "assignments", "know", "instruction","email", "discussion","home",\ "college","exam""use","fall","term","proposal","one","review",\"proposal", "calculus", "search", "research", "algebra"]# Initialize a Tf-idf Vectorizervectorizer = TfidfVectorizer(max_features=5000, stop_words= tfidf_stops)# Fit and transform the vectorizertfidf_matrix = vectorizer.fit_transform(tweets_processed["Processed"])# Let's see what we havedisplay(tfidf_matrix)# Create a DataFrame for tf-idf vectors and display the first rowstfidf_df = pd.DataFrame(tfidf_matrix.toarray(), columns= vectorizer.get_feature_names())display(tfidf_df.head())
It returned us a sparse matrix. You can look at its content below.
PAfter all, we save the new DataFrame as a CSV file to use later without performing whole operations again.
# Save the processed data as a csv filetweets_raw.to_csv("tweets_processed.csv")
Exploratory data analysis is an indispensable part of data science projects. We can build our models as long as we understand what our data tell us.
# Load the processed DataFrametweets_processed = pd.read_csv("tweets_processed.csv", parse_dates=["Created at"])
First of all, let’s look at the oldest and the newest tweets creation time in our data set.
# Print the minimum datetimeprint("Since:",tweets_processed["Created at"].min())# Print the maximum datetimeprint("Until",tweets_processed["Created at"].max())
The tweets have been created between 23 July and 14 August 2020. What about the creation hours?
# Set the seaborn stylesns.set()# Plot the histogram of hourssns.distplot(tweets_processed["Created at"].dt.hour, bins=24)plt.title("Hourly Distribution of Tweets")plt.show()
The histogram demonstrates that most of the tweets are created between 12 am-17 pm in a day. The most popular hour is about 15 pm.
Let’s look at the locations that we have already processed.
# Print the value counts of Country columnprint(tweets_processed["Country"].value_counts())
Apparently, the locations will be noninformative for us because we have 169.734 unknown locations. But we can still check the top tweeting countries.
According to the bar plot above, United States, United Kingdom, and India are the top 3 countries in our dataset.
Now, let’s look at the most popular tweets (in terms of retweets and favorites).
# Display the most popular tweetsdisplay(tweets_processed.sort_values(by=["Favorites","Retweet-Count", ], axis=0, ascending=False)[["Content","Retweet-Count","Favorites"]].head(20))
The frequent words in the tweets can also tell us a lot. Let’s get them from our Tf-idf matrix.
# Create a new DataFrame called frequenciesfrequencies = pd.DataFrame(tfidf_matrix.sum(axis=0).T,index=vectorizer.get_feature_names(),columns=['total frequency'])# Display the most 20 frequent wordsdisplay(frequencies.sort_values(by='total frequency',ascending=False).head(20))
Word clouds would be nicer.
Apparently, people talk about “payment”. “Help” is one of the most frequent words. We can say that people are looking for help a lot :)
After preprocessing and EDA, we can finally focus on our main aim in this project. We are going to calculate the tweets’ sentimental features such as polarity and subjectivity by using TextBlob. It gives us these values by using the predefined word scores. You can check the documentation for more information.
polarity is a value changes between -1 to 1. It shows us how positive or negative the sentence given is.
subjectivity is another value changes between 0 to 1 which shows us whether the sentence is about a fact or opinion (objective or subjective).
Let’s calculate the polarity and subjectivity scores with TextBlob
We need to classify the polarities as positive, neutral, and negative.
We can also count them up like the following.
# Print the value counts of the Label columnprint(tweets_processed["Label"].value_counts())
The results are different than what I expected. Positive tweets are significantly more than negative ones.
We tagged the tweets as positive, neutral, and negative so far. Let’s go over our findings deeply. I will start with label counts.
# Change the datatype as "category"tweets_processed["Label"] = tweets_processed["Label"].astype("category")# Visualize the Label countssns.countplot(tweets_processed["Label"])plt.title("Label Counts")plt.show()# Visualize the Polarity scoresplt.figure(figsize = (10, 10)) sns.scatterplot(x="Polarity", y="Subjectivity", hue="Label", data=tweets_processed)plt.title("Subjectivity vs Polarity")plt.show()
Since the lexicon-based analysis is not always reliable, we have to check the results manually. Let’s see the popular (in terms of retweets and favorites) tweets that have the highest/lowest polarity scores.
# Display the positive tweetsdisplay(tweets_processed.sort_values(by=["Polarity", "Retweet-Count", "Favorites"], axis=0, ascending=False)[["Content","Retweet-Count","Favorites","Polarity"]].head(20))# Display the negative tweetsdisplay(tweets_processed.sort_values(by=["Polarity", "Retweet-Count", "Favorites"], axis=0, ascending=[True, False, False])[["Content","Retweet-Count","Favorites","Polarity"]].head(20))
According to the results above, TextBlob has done its job correctly! We can make word clouds for each label as we did above. To do this, I will define a function. The function will take a DataFrame and a label as arguments and vectorized the Processed tweets with tf-idf vectorizer. Finally, it will make the word clouds for us. We will only look at the most popular 50 tweets because of the computational constraints. You can try with more data.
Apparently, people whose tweets are negative find distance learning is boring, horrible, and terrible. On the other hand, some people like options for distance learning.
Let’s look at the positive and negative tweet counts by country.
Is there any relationship between the time and tweets’ polarities?
positive = tweets_processed.loc[tweets_processed.Label=="Positive"]["Created at"].dt.hournegative = tweets_processed.loc[tweets_processed.Label=="Negative"]["Created at"].dt.hourplt.hist(positive, alpha=0.5, bins=24, label="Positive", density=True)plt.hist(negative, alpha=0.5, bins=24, label="Negative", density=True)plt.xlabel("Hour")plt.ylabel("PDF")plt.title("Hourly Distribution of Tweets")plt.legend(loc='upper right')plt.show()
The histogram above demonstrates that there is no relationship between the time and tweets’ polarities.
I want to finish my exploration here to keep this story short.
We have labeled the tweets according to their polarity scores. Let’s build a Machine Learning model by using a Multinomial Naive Bayes Classifier. We will use our tf-idf vectors as the features and the labels as the target.
# Encode the labelsle = LabelEncoder()tweets_processed["Label_enc"] = le.fit_transform(tweets_processed["Label"])# Display the encoded labelsdisplay(tweets_processed[["Label_enc"]].head())
We have encoded the labels.
“Positive” = 2
“Neutral” = 1
“Negative” = 0
# Select the features and the targetX = tweets_processed['Processed']y = tweets_processed["Label_enc"]
Now, we need to split our data into train and test sets. We’ll use the stratify parameter of train_test_split since our data is unbalanced.
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=34, stratify=y)
Now, we can create our model. Since our earlier tf-idf vectorizer fit by the entire dataset, we have to initialize a new one. Otherwise, our model can learn by the test set.
# Create the tf-idf vectorizermodel_vectorizer = TfidfVectorizer()# First fit the vectorizer with our training settfidf_train = vectorizer.fit_transform(X_train)# Now we can fit our test data with the same vectorizertfidf_test = vectorizer.transform(X_test)# Initialize the Bernoulli Naive Bayes classifiernb = BernoulliNB()# Fit the modelnb.fit(tfidf_train, y_train)# Print the accuracy scorebest_accuracy = cross_val_score(nb, tfidf_test, y_test, cv=10, scoring='accuracy').max()print("Accuracy:",best_accuracy)
Although we did not do any hyperparameter tuning, the accuracy is not bad. Let’s look at the confusion matrix and classification report.
# Predict the labelsy_pred = nb.predict(tfidf_test)# Print the Confusion Matrixcm = confusion_matrix(y_test, y_pred)print("Confusion Matrix\n")print(cm)# Print the Classification Reportcr = classification_report(y_test, y_pred)print("\n\nClassification Report\n")print(cr)
There is still a lot to do for improving the model’s performance on negative tweets but I keep it for another story :)
Finally, we can save the model to use later.
# Save the modelpickle.dump(nb, open("model.pkl", 'wb'))
In summary, let’s remember what we did together. Firstly, we have collected the Tweets about distance learning by using Twitter API and the tweepy library. After that we applied common preprocessing steps on them such as tokenization, lemmatization, removing stopwords, and so forth. We explored the data by using summary statistics and visualization tools. After all, we used TextBlob to get polarity scores of the tweets and interpreted our findings. Consequently, we found that in our dataset most of the tweets have positive opinions about distance learning. Do not forget the fact that we only used a lexicon-based approach which is not very reliable. I hope this story will be helpful for you to understand the sentiment analysis of tweets.
[1] (Tutorial) simplifying sentiment analysis in Python. (n.d.). DataCamp Community. https://www.datacamp.com/community/tutorials/simplifying-sentiment-analysis-python
[2] Lee, J. (2020, May 19). Twitter sentiment analysis | NLP | Text analytics. Medium. https://towardsdatascience.com/twitter-sentiment-analysis-nlp-text-analytics-b7b296d71fce
[3] Li, C. (2019, September 20). Real-time Twitter sentiment analysis for brand improvement and topic tracking (Chapter 1/3). Medium. https://towardsdatascience.com/real-time-twitter-sentiment-analysis-for-brand-improvement-and-topic-tracking-chapter-1-3-e02f7652d8ff
[4] Randerson112358. (2020, July 18). How to do sentiment analysis on a Twitter account in Python. Medium. https://medium.com/better-programming/twitter-sentiment-analysis-15d8892c0082
[5] Stemming and Lemmatization in Python. (n.d.). DataCamp Community. https://www.datacamp.com/community/tutorials/stemming-lemmatization-python | [
{
"code": null,
"e": 185,
"s": 172,
"text": "Hi everyone,"
},
{
"code": null,
"e": 685,
"s": 185,
"text": "The Covid19 Pandemic brought about distance learning in the 2020 academic term. Although some people could adapt easily, some of them found it inefficient. Nowadays, the re-opening of schools is being discussed. Most experts suggest that at least one semester should be online again. As a student who passed the last semester with distance learning, I could find a lot of time to spend on learning natural language processing. Finally, I decided to explore what people think about distance learning."
},
{
"code": null,
"e": 1161,
"s": 685,
"text": "I am planning this story as an end-to-end project. We are going to explore the tweets related to distance learning to understand people’s opinions (a.k.a opinion mining) and to discover facts. I will use the lexicon-based approach to determine the tweets’ polarities (I’ll explain it later). TextBlob will be our tool to do that. We will also build a machine learning model to predict the positivity and the negativity of the tweets by using Bernoulli Naive Bayes Classifier."
},
{
"code": null,
"e": 1192,
"s": 1161,
"text": "Our workflow is the following:"
},
{
"code": null,
"e": 1780,
"s": 1192,
"text": "Data Gathering- Twitter API- Retrieve tweets with tweepyPreprocessing and Cleaning- Drop duplicates- Data type conversions- Drop uninformative columns- Get rid of stop words, hashtags, punctuation, and one or two-letter words- Tokenize the words- Apply lemmatization- Term frequency-inverse document frequency vectorizationExploratory Data Analysis- Visualize the data- Compare word counts- Investigate the creation times distribution- Investigate the locations of tweets- Look at the popular tweets and the most frequent words- Make a word cloudSentiment AnalysisMachine LearningSummary"
},
{
"code": null,
"e": 1837,
"s": 1780,
"text": "Data Gathering- Twitter API- Retrieve tweets with tweepy"
},
{
"code": null,
"e": 2105,
"s": 1837,
"text": "Preprocessing and Cleaning- Drop duplicates- Data type conversions- Drop uninformative columns- Get rid of stop words, hashtags, punctuation, and one or two-letter words- Tokenize the words- Apply lemmatization- Term frequency-inverse document frequency vectorization"
},
{
"code": null,
"e": 2329,
"s": 2105,
"text": "Exploratory Data Analysis- Visualize the data- Compare word counts- Investigate the creation times distribution- Investigate the locations of tweets- Look at the popular tweets and the most frequent words- Make a word cloud"
},
{
"code": null,
"e": 2348,
"s": 2329,
"text": "Sentiment Analysis"
},
{
"code": null,
"e": 2365,
"s": 2348,
"text": "Machine Learning"
},
{
"code": null,
"e": 2373,
"s": 2365,
"text": "Summary"
},
{
"code": null,
"e": 2469,
"s": 2373,
"text": "Before starting, please make sure that the following libraries are available in your workspace."
},
{
"code": null,
"e": 2532,
"s": 2469,
"text": "pandasnumpymatplotlibseabornTextBlobwordcloudsklearnnltkpickle"
},
{
"code": null,
"e": 2602,
"s": 2532,
"text": "You can use the following commands to install non-built-in libraries."
},
{
"code": null,
"e": 2723,
"s": 2602,
"text": "pip install pycountrypip install nltkpip install textblobpip install wordcloudpip install scikit-learnpip install pickle"
},
{
"code": null,
"e": 2758,
"s": 2723,
"text": "You can find the entire code here."
},
{
"code": null,
"e": 3197,
"s": 2758,
"text": "First of all, we need a Twitter Developer Account to be allowed to use Twitter API. You can get the account here. It can take a few days to be approved. I have already completed those steps. Once I got the account, I created a text file that contains API information. It is located on the upward directory of the project. The content of the text file is the following. If you want to use it you have to replace the information with yours."
},
{
"code": null,
"e": 3346,
"s": 3197,
"text": "CONSUMER KEY=your_consumer_keyCONSUMER KEY SECRET=your_consumer_key_secretACCESS TOKEN=your_access_tokenACCESS TOKEN SECRET=your_access_token_secret"
},
{
"code": null,
"e": 3500,
"s": 3346,
"text": "After that, I created a py file called get_tweets.py to collect tweets (in English only) related to distance learning. You can see the entire code below."
},
{
"code": null,
"e": 3567,
"s": 3500,
"text": "The code above, searches the tweets contain the following hashtags"
},
{
"code": null,
"e": 3735,
"s": 3567,
"text": "#distancelearning, #onlineschool, #onlineteaching, #virtuallearning, #onlineducation, #distanceeducation, #OnlineClasses, #DigitalLearning, #elearning, #onlinelearning"
},
{
"code": null,
"e": 3762,
"s": 3735,
"text": "and the following keywords"
},
{
"code": null,
"e": 3942,
"s": 3762,
"text": "“distance learning”, “online teaching”, “online education”, “online course”, “online semester”, “distance course”, “distance education”, “online class”,” e-learning”, “e learning”"
},
{
"code": null,
"e": 3993,
"s": 3942,
"text": "It also filters the retweets to avoid duplication."
},
{
"code": null,
"e": 4226,
"s": 3993,
"text": "The get_tweets function stores the tweets retrieved in a temporary pandas DataFrame and saves as CSV files in the output directory. It approximately took 40 hours to collect 202.645 tweets. After that, It gave me the following files"
},
{
"code": null,
"e": 4333,
"s": 4226,
"text": "To concatenate all CSV files into one, I created the concatenate.py file that contains the following code."
},
{
"code": null,
"e": 4407,
"s": 4333,
"text": "Ultimately, we have tweets_raw.csv file. Let’s look at how it looks like."
},
{
"code": null,
"e": 4620,
"s": 4407,
"text": "# Load the tweetstweets_raw = pd.read_csv(\"tweets_raw.csv\")# Display the first five rowsdisplay(tweets_raw.head())# Print the summary statisticsprint(tweets_raw.describe())# Print the infoprint(tweets_raw.info())"
},
{
"code": null,
"e": 4902,
"s": 4620,
"text": "At a first glance, we can see that there are 202.645 tweets including the content, location, username, Retweet count, Favorites count, and the creation time features in the DataFrame. There are also some missing values in the Location column. We’ll deal with them in the next step."
},
{
"code": null,
"e": 5154,
"s": 4902,
"text": "According to the information above, Unnamed: 0 and Unnamed: 0.1 columns are not informative to us so we’ll drop them out. The data type of Created at column also should be datetime. As well as we need to get rid of duplicated tweets if there are some."
},
{
"code": null,
"e": 5508,
"s": 5154,
"text": "# We do not need first two columns. Let's drop them out.tweets_raw.drop(columns=[\"Unnamed: 0\", \"Unnamed: 0.1\"], axis=1, inplace=True)# Drop duplicated rowstweets_raw.drop_duplicates(inplace=True)# Created at column's type should be datatimetweets_raw[\"Created at\"] = pd.to_datetime(tweets_raw[\"Created at\"])# Print the info againprint(tweets_raw.info())"
},
{
"code": null,
"e": 5657,
"s": 5508,
"text": "The tweets count has been reduced to 187.052 (There were 15.593 duplicated rows). “Created at” column’s data type is also changed to datatime64[ns]."
},
{
"code": null,
"e": 5843,
"s": 5657,
"text": "Now, let’s tidy the tweets’ contents up. We need to get rid of stopwords, punctuation, hashtags, mentions, links, and one or two-letter words. As well as we need to tokenize the tweets."
},
{
"code": null,
"e": 6015,
"s": 5843,
"text": "Tokenization is the splitting of a sentence into words and punctuation marks. The sentence “This is an example.” can be tokenized like [“This”, “is”, “an”, “example”, “.”]"
},
{
"code": null,
"e": 6168,
"s": 6015,
"text": "Stopwords are the words that are commonly used and they don’t contribute to the meaning of a sentence such as “a”, “an”, “the”, “on”, “in” and so forth."
},
{
"code": null,
"e": 6326,
"s": 6168,
"text": "Lemmatization is the process of reducing a word to its root form. This root form called a lemma. For example, the lemma of words running runs, and ran is run"
},
{
"code": null,
"e": 6381,
"s": 6326,
"text": "Let’s define a function to do all of these operations."
},
{
"code": null,
"e": 6627,
"s": 6381,
"text": "After the function call, our Processed column will be like the following. You see that the tweets are tokenized and they do not contain stopwords, hashtags, links, and one or two-letter words. We also applied the lemmatization operation on them."
},
{
"code": null,
"e": 6745,
"s": 6627,
"text": "We got what we want. Do not worry about words such as learning, online, education, etc. We will deal with them later."
},
{
"code": null,
"e": 6869,
"s": 6745,
"text": "Tweet lengths and number of words in the tweets might be also interesting in the exploratory data analysis. Let’s get them!"
},
{
"code": null,
"e": 7112,
"s": 6869,
"text": "# Get the tweet lengthstweets_raw[\"Length\"] = tweets_raw[\"Content\"].str.len()# Get the number of words in tweetstweets_raw[\"Words\"] = tweets_raw[\"Content\"].str.split().str.len()# Display the new columnsdisplay(tweets_raw[[\"Length\", \"Words\"]])"
},
{
"code": null,
"e": 7161,
"s": 7112,
"text": "Notice that we did not use the Processed tweets."
},
{
"code": null,
"e": 7187,
"s": 7161,
"text": "What about the locations?"
},
{
"code": null,
"e": 7410,
"s": 7187,
"text": "When we called the info function of tweets_raw DataFrame, we saw that there were some missing values in the “Location” columns. The missing values are indicated as NaN. We’ll fill the missing values with the “unknown” tag."
},
{
"code": null,
"e": 7507,
"s": 7410,
"text": "# Fill the missing values with unknown tagtweets_raw[\"Location\"].fillna(\"unknown\", inplace=True)"
},
{
"code": null,
"e": 7542,
"s": 7507,
"text": "How many unique locations we have?"
},
{
"code": null,
"e": 7722,
"s": 7542,
"text": "# Print the unique locations and number of unique locationsprint(\"Unique Values:\",tweets_raw[\"Location\"].unique())print(\"Unique Value count:\",len(tweets_raw[\"Location\"].unique()))"
},
{
"code": null,
"e": 7970,
"s": 7722,
"text": "The outputs show us the location information is messy. There are 37.119 unique locations. We need to group them by country. To achieve this, we will use the pycountry package in python. If you are interested, you can find further information here."
},
{
"code": null,
"e": 8071,
"s": 7970,
"text": "Let’s define a function called get_countries which returns the country codes of the given locations."
},
{
"code": null,
"e": 8177,
"s": 8071,
"text": "It worked! Now we have 156 unique country codes. We will use them for the exploratory data analysis part."
},
{
"code": null,
"e": 8297,
"s": 8177,
"text": "Now it’s time to vectorize the tweets. We’ll use tf-idf (term frequency-inverse document term frequency) vectorization."
},
{
"code": null,
"e": 8608,
"s": 8297,
"text": "Tf-idf (Term Frequency — Inverse Term Frequency) is a statistical concept to be used to get the frequency of words in the corpus. We’ll use scikit-learn’s TfidfVectorizer. The vectorizer will calculate the weight of each word in the corpus and will return a tf-idf matrix. You can find further information here"
},
{
"code": null,
"e": 8756,
"s": 8608,
"text": "td = Term frequency (number of occurrences each i in j)df = Document frequencyN = Number of documentsw = tf-idf weight for each i and j (document)."
},
{
"code": null,
"e": 8924,
"s": 8756,
"text": "We are going to select only the top 5000 words for tf-idf vectorization due to memory constraints. You can experiment with more by using other approaches like hashing."
},
{
"code": null,
"e": 10245,
"s": 8924,
"text": "# Create our contextual stop wordstfidf_stops = [\"online\",\"class\",\"course\",\"learning\",\"learn\",\\\"teach\",\"teaching\",\"distance\",\"distancelearning\",\"education\",\\\"teacher\",\"student\",\"grade\",\"classes\",\"computer\",\"onlineeducation\",\\ \"onlinelearning\", \"school\", \"students\",\"class\",\"virtual\",\"eschool\",\\ \"virtuallearning\", \"educated\", \"educates\", \"teaches\", \"studies\",\\ \"study\", \"semester\", \"elearning\",\"teachers\", \"lecturer\", \"lecture\",\\ \"amp\",\"academic\", \"admission\", \"academician\", \"account\", \"action\" \\\"add\", \"app\", \"announcement\", \"application\", \"adult\", \"classroom\", \"system\", \"video\", \"essay\", \"homework\",\"work\",\"assignment\",\"paper\",\\ \"get\", \"math\", \"project\", \"science\", \"physics\", \"lesson\",\"courses\",\\ \"assignments\", \"know\", \"instruction\",\"email\", \"discussion\",\"home\",\\ \"college\",\"exam\"\"use\",\"fall\",\"term\",\"proposal\",\"one\",\"review\",\\\"proposal\", \"calculus\", \"search\", \"research\", \"algebra\"]# Initialize a Tf-idf Vectorizervectorizer = TfidfVectorizer(max_features=5000, stop_words= tfidf_stops)# Fit and transform the vectorizertfidf_matrix = vectorizer.fit_transform(tweets_processed[\"Processed\"])# Let's see what we havedisplay(tfidf_matrix)# Create a DataFrame for tf-idf vectors and display the first rowstfidf_df = pd.DataFrame(tfidf_matrix.toarray(), columns= vectorizer.get_feature_names())display(tfidf_df.head())"
},
{
"code": null,
"e": 10312,
"s": 10245,
"text": "It returned us a sparse matrix. You can look at its content below."
},
{
"code": null,
"e": 10420,
"s": 10312,
"text": "PAfter all, we save the new DataFrame as a CSV file to use later without performing whole operations again."
},
{
"code": null,
"e": 10501,
"s": 10420,
"text": "# Save the processed data as a csv filetweets_raw.to_csv(\"tweets_processed.csv\")"
},
{
"code": null,
"e": 10650,
"s": 10501,
"text": "Exploratory data analysis is an indispensable part of data science projects. We can build our models as long as we understand what our data tell us."
},
{
"code": null,
"e": 10763,
"s": 10650,
"text": "# Load the processed DataFrametweets_processed = pd.read_csv(\"tweets_processed.csv\", parse_dates=[\"Created at\"])"
},
{
"code": null,
"e": 10855,
"s": 10763,
"text": "First of all, let’s look at the oldest and the newest tweets creation time in our data set."
},
{
"code": null,
"e": 11015,
"s": 10855,
"text": "# Print the minimum datetimeprint(\"Since:\",tweets_processed[\"Created at\"].min())# Print the maximum datetimeprint(\"Until\",tweets_processed[\"Created at\"].max())"
},
{
"code": null,
"e": 11111,
"s": 11015,
"text": "The tweets have been created between 23 July and 14 August 2020. What about the creation hours?"
},
{
"code": null,
"e": 11286,
"s": 11111,
"text": "# Set the seaborn stylesns.set()# Plot the histogram of hourssns.distplot(tweets_processed[\"Created at\"].dt.hour, bins=24)plt.title(\"Hourly Distribution of Tweets\")plt.show()"
},
{
"code": null,
"e": 11417,
"s": 11286,
"text": "The histogram demonstrates that most of the tweets are created between 12 am-17 pm in a day. The most popular hour is about 15 pm."
},
{
"code": null,
"e": 11477,
"s": 11417,
"text": "Let’s look at the locations that we have already processed."
},
{
"code": null,
"e": 11569,
"s": 11477,
"text": "# Print the value counts of Country columnprint(tweets_processed[\"Country\"].value_counts())"
},
{
"code": null,
"e": 11719,
"s": 11569,
"text": "Apparently, the locations will be noninformative for us because we have 169.734 unknown locations. But we can still check the top tweeting countries."
},
{
"code": null,
"e": 11833,
"s": 11719,
"text": "According to the bar plot above, United States, United Kingdom, and India are the top 3 countries in our dataset."
},
{
"code": null,
"e": 11914,
"s": 11833,
"text": "Now, let’s look at the most popular tweets (in terms of retweets and favorites)."
},
{
"code": null,
"e": 12096,
"s": 11914,
"text": "# Display the most popular tweetsdisplay(tweets_processed.sort_values(by=[\"Favorites\",\"Retweet-Count\", ], axis=0, ascending=False)[[\"Content\",\"Retweet-Count\",\"Favorites\"]].head(20))"
},
{
"code": null,
"e": 12192,
"s": 12096,
"text": "The frequent words in the tweets can also tell us a lot. Let’s get them from our Tf-idf matrix."
},
{
"code": null,
"e": 12470,
"s": 12192,
"text": "# Create a new DataFrame called frequenciesfrequencies = pd.DataFrame(tfidf_matrix.sum(axis=0).T,index=vectorizer.get_feature_names(),columns=['total frequency'])# Display the most 20 frequent wordsdisplay(frequencies.sort_values(by='total frequency',ascending=False).head(20))"
},
{
"code": null,
"e": 12498,
"s": 12470,
"text": "Word clouds would be nicer."
},
{
"code": null,
"e": 12634,
"s": 12498,
"text": "Apparently, people talk about “payment”. “Help” is one of the most frequent words. We can say that people are looking for help a lot :)"
},
{
"code": null,
"e": 12945,
"s": 12634,
"text": "After preprocessing and EDA, we can finally focus on our main aim in this project. We are going to calculate the tweets’ sentimental features such as polarity and subjectivity by using TextBlob. It gives us these values by using the predefined word scores. You can check the documentation for more information."
},
{
"code": null,
"e": 13050,
"s": 12945,
"text": "polarity is a value changes between -1 to 1. It shows us how positive or negative the sentence given is."
},
{
"code": null,
"e": 13193,
"s": 13050,
"text": "subjectivity is another value changes between 0 to 1 which shows us whether the sentence is about a fact or opinion (objective or subjective)."
},
{
"code": null,
"e": 13260,
"s": 13193,
"text": "Let’s calculate the polarity and subjectivity scores with TextBlob"
},
{
"code": null,
"e": 13331,
"s": 13260,
"text": "We need to classify the polarities as positive, neutral, and negative."
},
{
"code": null,
"e": 13377,
"s": 13331,
"text": "We can also count them up like the following."
},
{
"code": null,
"e": 13469,
"s": 13377,
"text": "# Print the value counts of the Label columnprint(tweets_processed[\"Label\"].value_counts())"
},
{
"code": null,
"e": 13576,
"s": 13469,
"text": "The results are different than what I expected. Positive tweets are significantly more than negative ones."
},
{
"code": null,
"e": 13707,
"s": 13576,
"text": "We tagged the tweets as positive, neutral, and negative so far. Let’s go over our findings deeply. I will start with label counts."
},
{
"code": null,
"e": 14110,
"s": 13707,
"text": "# Change the datatype as \"category\"tweets_processed[\"Label\"] = tweets_processed[\"Label\"].astype(\"category\")# Visualize the Label countssns.countplot(tweets_processed[\"Label\"])plt.title(\"Label Counts\")plt.show()# Visualize the Polarity scoresplt.figure(figsize = (10, 10)) sns.scatterplot(x=\"Polarity\", y=\"Subjectivity\", hue=\"Label\", data=tweets_processed)plt.title(\"Subjectivity vs Polarity\")plt.show()"
},
{
"code": null,
"e": 14318,
"s": 14110,
"text": "Since the lexicon-based analysis is not always reliable, we have to check the results manually. Let’s see the popular (in terms of retweets and favorites) tweets that have the highest/lowest polarity scores."
},
{
"code": null,
"e": 14732,
"s": 14318,
"text": "# Display the positive tweetsdisplay(tweets_processed.sort_values(by=[\"Polarity\", \"Retweet-Count\", \"Favorites\"], axis=0, ascending=False)[[\"Content\",\"Retweet-Count\",\"Favorites\",\"Polarity\"]].head(20))# Display the negative tweetsdisplay(tweets_processed.sort_values(by=[\"Polarity\", \"Retweet-Count\", \"Favorites\"], axis=0, ascending=[True, False, False])[[\"Content\",\"Retweet-Count\",\"Favorites\",\"Polarity\"]].head(20))"
},
{
"code": null,
"e": 15179,
"s": 14732,
"text": "According to the results above, TextBlob has done its job correctly! We can make word clouds for each label as we did above. To do this, I will define a function. The function will take a DataFrame and a label as arguments and vectorized the Processed tweets with tf-idf vectorizer. Finally, it will make the word clouds for us. We will only look at the most popular 50 tweets because of the computational constraints. You can try with more data."
},
{
"code": null,
"e": 15349,
"s": 15179,
"text": "Apparently, people whose tweets are negative find distance learning is boring, horrible, and terrible. On the other hand, some people like options for distance learning."
},
{
"code": null,
"e": 15414,
"s": 15349,
"text": "Let’s look at the positive and negative tweet counts by country."
},
{
"code": null,
"e": 15481,
"s": 15414,
"text": "Is there any relationship between the time and tweets’ polarities?"
},
{
"code": null,
"e": 15916,
"s": 15481,
"text": "positive = tweets_processed.loc[tweets_processed.Label==\"Positive\"][\"Created at\"].dt.hournegative = tweets_processed.loc[tweets_processed.Label==\"Negative\"][\"Created at\"].dt.hourplt.hist(positive, alpha=0.5, bins=24, label=\"Positive\", density=True)plt.hist(negative, alpha=0.5, bins=24, label=\"Negative\", density=True)plt.xlabel(\"Hour\")plt.ylabel(\"PDF\")plt.title(\"Hourly Distribution of Tweets\")plt.legend(loc='upper right')plt.show()"
},
{
"code": null,
"e": 16020,
"s": 15916,
"text": "The histogram above demonstrates that there is no relationship between the time and tweets’ polarities."
},
{
"code": null,
"e": 16083,
"s": 16020,
"text": "I want to finish my exploration here to keep this story short."
},
{
"code": null,
"e": 16307,
"s": 16083,
"text": "We have labeled the tweets according to their polarity scores. Let’s build a Machine Learning model by using a Multinomial Naive Bayes Classifier. We will use our tf-idf vectors as the features and the labels as the target."
},
{
"code": null,
"e": 16496,
"s": 16307,
"text": "# Encode the labelsle = LabelEncoder()tweets_processed[\"Label_enc\"] = le.fit_transform(tweets_processed[\"Label\"])# Display the encoded labelsdisplay(tweets_processed[[\"Label_enc\"]].head())"
},
{
"code": null,
"e": 16524,
"s": 16496,
"text": "We have encoded the labels."
},
{
"code": null,
"e": 16539,
"s": 16524,
"text": "“Positive” = 2"
},
{
"code": null,
"e": 16553,
"s": 16539,
"text": "“Neutral” = 1"
},
{
"code": null,
"e": 16568,
"s": 16553,
"text": "“Negative” = 0"
},
{
"code": null,
"e": 16671,
"s": 16568,
"text": "# Select the features and the targetX = tweets_processed['Processed']y = tweets_processed[\"Label_enc\"]"
},
{
"code": null,
"e": 16811,
"s": 16671,
"text": "Now, we need to split our data into train and test sets. We’ll use the stratify parameter of train_test_split since our data is unbalanced."
},
{
"code": null,
"e": 16913,
"s": 16811,
"text": "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=34, stratify=y)"
},
{
"code": null,
"e": 17087,
"s": 16913,
"text": "Now, we can create our model. Since our earlier tf-idf vectorizer fit by the entire dataset, we have to initialize a new one. Otherwise, our model can learn by the test set."
},
{
"code": null,
"e": 17601,
"s": 17087,
"text": "# Create the tf-idf vectorizermodel_vectorizer = TfidfVectorizer()# First fit the vectorizer with our training settfidf_train = vectorizer.fit_transform(X_train)# Now we can fit our test data with the same vectorizertfidf_test = vectorizer.transform(X_test)# Initialize the Bernoulli Naive Bayes classifiernb = BernoulliNB()# Fit the modelnb.fit(tfidf_train, y_train)# Print the accuracy scorebest_accuracy = cross_val_score(nb, tfidf_test, y_test, cv=10, scoring='accuracy').max()print(\"Accuracy:\",best_accuracy)"
},
{
"code": null,
"e": 17738,
"s": 17601,
"text": "Although we did not do any hyperparameter tuning, the accuracy is not bad. Let’s look at the confusion matrix and classification report."
},
{
"code": null,
"e": 18011,
"s": 17738,
"text": "# Predict the labelsy_pred = nb.predict(tfidf_test)# Print the Confusion Matrixcm = confusion_matrix(y_test, y_pred)print(\"Confusion Matrix\\n\")print(cm)# Print the Classification Reportcr = classification_report(y_test, y_pred)print(\"\\n\\nClassification Report\\n\")print(cr)"
},
{
"code": null,
"e": 18130,
"s": 18011,
"text": "There is still a lot to do for improving the model’s performance on negative tweets but I keep it for another story :)"
},
{
"code": null,
"e": 18175,
"s": 18130,
"text": "Finally, we can save the model to use later."
},
{
"code": null,
"e": 18232,
"s": 18175,
"text": "# Save the modelpickle.dump(nb, open(\"model.pkl\", 'wb'))"
},
{
"code": null,
"e": 18979,
"s": 18232,
"text": "In summary, let’s remember what we did together. Firstly, we have collected the Tweets about distance learning by using Twitter API and the tweepy library. After that we applied common preprocessing steps on them such as tokenization, lemmatization, removing stopwords, and so forth. We explored the data by using summary statistics and visualization tools. After all, we used TextBlob to get polarity scores of the tweets and interpreted our findings. Consequently, we found that in our dataset most of the tweets have positive opinions about distance learning. Do not forget the fact that we only used a lexicon-based approach which is not very reliable. I hope this story will be helpful for you to understand the sentiment analysis of tweets."
},
{
"code": null,
"e": 19147,
"s": 18979,
"text": "[1] (Tutorial) simplifying sentiment analysis in Python. (n.d.). DataCamp Community. https://www.datacamp.com/community/tutorials/simplifying-sentiment-analysis-python"
},
{
"code": null,
"e": 19324,
"s": 19147,
"text": "[2] Lee, J. (2020, May 19). Twitter sentiment analysis | NLP | Text analytics. Medium. https://towardsdatascience.com/twitter-sentiment-analysis-nlp-text-analytics-b7b296d71fce"
},
{
"code": null,
"e": 19592,
"s": 19324,
"text": "[3] Li, C. (2019, September 20). Real-time Twitter sentiment analysis for brand improvement and topic tracking (Chapter 1/3). Medium. https://towardsdatascience.com/real-time-twitter-sentiment-analysis-for-brand-improvement-and-topic-tracking-chapter-1-3-e02f7652d8ff"
},
{
"code": null,
"e": 19777,
"s": 19592,
"text": "[4] Randerson112358. (2020, July 18). How to do sentiment analysis on a Twitter account in Python. Medium. https://medium.com/better-programming/twitter-sentiment-analysis-15d8892c0082"
}
] |
Apache POI PPT - Slide Layouts | In the previous chapter, you have seen how to create empty slides and how to add slides to it. In this chapter, you will learn how to get the list of available slides, and how to create a slide with different layouts.
PowerPoint presentations have slide layouts, and you can choose a desired layout to edit a slide. First of all, let us find out the list of all the slide layouts available.
There are different slide masters and in each slide master, there are several slide layouts.
There are different slide masters and in each slide master, there are several slide layouts.
You can get the list of the slide masters using the getSlideMasters() method of the XMLSlideShow class.
You can get the list of the slide masters using the getSlideMasters() method of the XMLSlideShow class.
You can get the list of the slide layouts from each slide master using the getSlideLayouts() method of the XSLFSlideMaster class.
You can get the list of the slide layouts from each slide master using the getSlideLayouts() method of the XSLFSlideMaster class.
You can get the name of the slide layout from the layout object using the getType() method of the XSLFSlideLayout class.
You can get the name of the slide layout from the layout object using the getType() method of the XSLFSlideLayout class.
Note − All these classes belongs to org.poi.xslf.usermodel package.
Given below is the complete program to get the list of available slide layouts in the PPT −
import java.io.IOException;
import org.apache.poi.xslf.usermodel.XMLSlideShow;
import org.apache.poi.xslf.usermodel.XSLFSlideLayout;
import org.apache.poi.xslf.usermodel.XSLFSlideMaster;
public class SlideLayouts {
public static void main(String args[]) throws IOException {
//create an empty presentation
XMLSlideShow ppt = new XMLSlideShow();
System.out.println("Available slide layouts:");
//getting the list of all slide masters
for(XSLFSlideMaster master : ppt.getSlideMasters()) {
//getting the list of the layouts in each slide master
for(XSLFSlideLayout layout : master.getSlideLayouts()) {
//getting the list of available slides
System.out.println(layout.getType());
}
}
}
}
Save the above Java code as SlideLayouts.java , and then compile and execute it from the command prompt as follows −
$javac SlideLayouts.java
$java SlideLayouts
It will compile and execute to generate the following output −
Available slide layouts:
TITLE
PIC_TX
VERT_TX
TWO_TX_TWO_OBJ
BLANK
VERT_TITLE_AND_TX
TITLE_AND_CONTENT
TITLE_ONLY
SECTION_HEADER
TWO_OBJ
OBJ_TX
Shown below are some of the sample slide layouts available with MS-Office 360, 2013 edition.
Let us create a slide in a PPT using Title layout. Follow the steps given below −
Step 1 − Create an empty presentation by instantiating the XMLSlideShow class as shown below.
XMLSlideShow ppt = new XMLSlideShow();
Step 2 − Get the list of slide masters using the getSlideMasters() method. Thereafter, select the desired slide master using the index as shown below.
XSLFSlideMaster slideMaster = ppt.getSlideMasters()[0];
Here we are getting the default slide master which is in the 0th location of the slide masters array.
Step 3 − Get the desired layout using the getLayout() method of the XSLFSlideMaster class. This method accepts a parameter where you have to pass one of the static variable of the SlideLayoutclass, which represents our desired layout. There are several variables in this class where each variable represents a slide layout.
The code snippet given below shows how to create a title layout −
XSLFSlideLayout titleLayout = slideMaster.getLayout(SlideLayout.TITLE);
Step 4 − Create a new slide by passing a slide layout object as parameter.
XSLFSlide slide = ppt.createSlide(titleLayout);
Step 5 − Select a placeholder using the getPlaceholder() method of the XSLFSlide class. This method accepts an integer parameter. By passing 0 to it, you will get the XSLFTextShape object, using which you can access the title text area of the slide. Set the title using the setText() method as shown below.
XSLFTextShape title1 = slide.getPlaceholder(0);
//setting the title init
title1.setText("Tutorials point");
Given below is the complete program to create a slide with Title layout in a presentation −
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.xslf.usermodel.SlideLayout;
import org.apache.poi.xslf.usermodel.XMLSlideShow;
import org.apache.poi.xslf.usermodel.XSLFSlide;
import org.apache.poi.xslf.usermodel.XSLFSlideLayout;
import org.apache.poi.xslf.usermodel.XSLFSlideMaster;
import org.apache.poi.xslf.usermodel.XSLFTextShape;
public class TitleLayout {
public static void main(String args[]) throws IOException {
//creating presentation
XMLSlideShow ppt = new XMLSlideShow();
//getting the slide master object
XSLFSlideMaster slideMaster = ppt.getSlideMasters().get(0);
//get the desired slide layout
XSLFSlideLayout titleLayout = slideMaster.getLayout(SlideLayout.TITLE);
//creating a slide with title layout
XSLFSlide slide1 = ppt.createSlide(titleLayout);
//selecting the place holder in it
XSLFTextShape title1 = slide1.getPlaceholder(0);
//setting the title init
title1.setText("Tutorials point");
//create a file object
File file = new File("F://Titlelayout.pptx");
FileOutputStream out = new FileOutputStream(file);
//save the changes in a PPt document
ppt.write(out);
System.out.println("slide cretated successfully");
out.close();
}
}
Save the above Java code as TitleLayout.java, and then compile and execute it from the command prompt as follows −
$javac TitleLayout.java
$java TitleLayout
It will compile and execute to generate the following output.
slide created successfully
The PPT document with newly added Title layout slide appears as follows −
Let us create a slide in a PPT using Title and content layout. Follow the steps given below.
Step 1 − Create an empty presentation by instantiating the XMLSlideShow class as shown below.
XMLSlideShow ppt = new XMLSlideShow();
Step 2 − Get the list of slide masters using the getSlideMasters() method. Select the desired slide master using the index as shown below.
XSLFSlideMaster slideMaster = ppt.getSlideMasters()[0];
Here we are getting the default slide master which is in the 0th location of the slide masters array.
Step 3 − Get the desired layout using the getLayout() method of the XSLFSlideMaster class. This method accepts a parameter where you have to pass one of the static variable of the SlideLayout class which represents our desired layout. There are several variables in this class that represent slide layouts.
The following code snippet shows how to create title and content layout −
XSLFSlideLayout contentlayout = slideMaster.getLayout(SlideLayout.TITLE_AND_CONTENT);
Step 4 − Create a new slide by passing the slide layout object as parameter.
XSLFSlide slide = ppt.createSlide(SlideLayout.TITLE_AND_CONTENT);
Step 5 − Select a placeholder using the getPlaceholder() method of the XSLFSlide class. This method accepts an integer parameter. By passing 1 to it, you will get the XSLFTextShape object, using which you can access the content area of the slide. Set the title using the setText() method as shown below.
XSLFTextShape title1 = slide1.getPlaceholder(1);
//setting the title init
title1.setText("Introduction");
Step 6 − Clear the existing text in the slide using the clearText() method of the XSLFTextShape class.
body.clearText();
Step 7 − Add new paragraph using the addNewTextParagraph() method. Now add a new text run to the paragraph using the addNewTextRun() method. Now to the text run, add text using the setText() method as shown below.
body.addNewTextParagraph().addNewTextRun().setText("this is my first slide body");
Given below is the complete program to create a slide with Title layout in a presentation −
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.xslf.usermodel.SlideLayout;
import org.apache.poi.xslf.usermodel.XMLSlideShow;
import org.apache.poi.xslf.usermodel.XSLFSlide;
import org.apache.poi.xslf.usermodel.XSLFSlideLayout;
import org.apache.poi.xslf.usermodel.XSLFSlideMaster;
import org.apache.poi.xslf.usermodel.XSLFTextShape;
public class TitleAndBodyLayout {
public static void main(String args[]) throws IOException {
//creating presentation
XMLSlideShow ppt = new XMLSlideShow();
//getting the slide master object
XSLFSlideMaster slideMaster = ppt.getSlideMasters().get(0);
//select a layout from specified list
XSLFSlideLayout slidelayout = slideMaster.getLayout(SlideLayout.TITLE_AND_CONTENT);
//creating a slide with title and content layout
XSLFSlide slide = ppt.createSlide(slidelayout);
//selection of title place holder
XSLFTextShape title = slide.getPlaceholder(0);
//setting the title in it
title.setText("introduction");
//selection of body placeholder
XSLFTextShape body = slide.getPlaceholder(1);
//clear the existing text in the slide
body.clearText();
//adding new paragraph
body.addNewTextParagraph().addNewTextRun().setText("this is my first slide body");
//create a file object
File file = new File("contentlayout.pptx");
FileOutputStream out = new FileOutputStream(file);
//save the changes in a file
ppt.write(out);
System.out.println("slide cretated successfully");
out.close();
}
}
Save the above Java code as TitleLayout.java, and then compile and execute it from the command prompt as follows −
$javac TitleLayout.java
$java TitleLayout
It will compile and execute to generate the following output −
slide created successfully
The PPT document with newly added Title layout slide appears as follows −
In the same way, you can create slides with different layouts as well.
46 Lectures
3.5 hours
Arnab Chakraborty
23 Lectures
1.5 hours
Mukund Kumar Mishra
16 Lectures
1 hours
Nilay Mehta
52 Lectures
1.5 hours
Bigdata Engineer
14 Lectures
1 hours
Bigdata Engineer
23 Lectures
1 hours
Bigdata Engineer
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2235,
"s": 2017,
"text": "In the previous chapter, you have seen how to create empty slides and how to add slides to it. In this chapter, you will learn how to get the list of available slides, and how to create a slide with different layouts."
},
{
"code": null,
"e": 2408,
"s": 2235,
"text": "PowerPoint presentations have slide layouts, and you can choose a desired layout to edit a slide. First of all, let us find out the list of all the slide layouts available."
},
{
"code": null,
"e": 2501,
"s": 2408,
"text": "There are different slide masters and in each slide master, there are several slide layouts."
},
{
"code": null,
"e": 2594,
"s": 2501,
"text": "There are different slide masters and in each slide master, there are several slide layouts."
},
{
"code": null,
"e": 2698,
"s": 2594,
"text": "You can get the list of the slide masters using the getSlideMasters() method of the XMLSlideShow class."
},
{
"code": null,
"e": 2802,
"s": 2698,
"text": "You can get the list of the slide masters using the getSlideMasters() method of the XMLSlideShow class."
},
{
"code": null,
"e": 2932,
"s": 2802,
"text": "You can get the list of the slide layouts from each slide master using the getSlideLayouts() method of the XSLFSlideMaster class."
},
{
"code": null,
"e": 3062,
"s": 2932,
"text": "You can get the list of the slide layouts from each slide master using the getSlideLayouts() method of the XSLFSlideMaster class."
},
{
"code": null,
"e": 3183,
"s": 3062,
"text": "You can get the name of the slide layout from the layout object using the getType() method of the XSLFSlideLayout class."
},
{
"code": null,
"e": 3304,
"s": 3183,
"text": "You can get the name of the slide layout from the layout object using the getType() method of the XSLFSlideLayout class."
},
{
"code": null,
"e": 3372,
"s": 3304,
"text": "Note − All these classes belongs to org.poi.xslf.usermodel package."
},
{
"code": null,
"e": 3464,
"s": 3372,
"text": "Given below is the complete program to get the list of available slide layouts in the PPT −"
},
{
"code": null,
"e": 4246,
"s": 3464,
"text": "import java.io.IOException;\nimport org.apache.poi.xslf.usermodel.XMLSlideShow;\nimport org.apache.poi.xslf.usermodel.XSLFSlideLayout;\nimport org.apache.poi.xslf.usermodel.XSLFSlideMaster;\n\npublic class SlideLayouts {\n public static void main(String args[]) throws IOException {\n //create an empty presentation\n XMLSlideShow ppt = new XMLSlideShow();\n System.out.println(\"Available slide layouts:\");\n \n //getting the list of all slide masters\n for(XSLFSlideMaster master : ppt.getSlideMasters()) {\n //getting the list of the layouts in each slide master\n for(XSLFSlideLayout layout : master.getSlideLayouts()) {\n //getting the list of available slides\n System.out.println(layout.getType());\n }\n }\n }\n}"
},
{
"code": null,
"e": 4363,
"s": 4246,
"text": "Save the above Java code as SlideLayouts.java , and then compile and execute it from the command prompt as follows −"
},
{
"code": null,
"e": 4408,
"s": 4363,
"text": "$javac SlideLayouts.java\n$java SlideLayouts\n"
},
{
"code": null,
"e": 4471,
"s": 4408,
"text": "It will compile and execute to generate the following output −"
},
{
"code": null,
"e": 4616,
"s": 4471,
"text": "Available slide layouts:\nTITLE\nPIC_TX\nVERT_TX\nTWO_TX_TWO_OBJ\nBLANK\nVERT_TITLE_AND_TX\nTITLE_AND_CONTENT\nTITLE_ONLY\nSECTION_HEADER\nTWO_OBJ\nOBJ_TX\n"
},
{
"code": null,
"e": 4709,
"s": 4616,
"text": "Shown below are some of the sample slide layouts available with MS-Office 360, 2013 edition."
},
{
"code": null,
"e": 4791,
"s": 4709,
"text": "Let us create a slide in a PPT using Title layout. Follow the steps given below −"
},
{
"code": null,
"e": 4885,
"s": 4791,
"text": "Step 1 − Create an empty presentation by instantiating the XMLSlideShow class as shown below."
},
{
"code": null,
"e": 4925,
"s": 4885,
"text": "XMLSlideShow ppt = new XMLSlideShow();\n"
},
{
"code": null,
"e": 5076,
"s": 4925,
"text": "Step 2 − Get the list of slide masters using the getSlideMasters() method. Thereafter, select the desired slide master using the index as shown below."
},
{
"code": null,
"e": 5133,
"s": 5076,
"text": "XSLFSlideMaster slideMaster = ppt.getSlideMasters()[0];\n"
},
{
"code": null,
"e": 5235,
"s": 5133,
"text": "Here we are getting the default slide master which is in the 0th location of the slide masters array."
},
{
"code": null,
"e": 5559,
"s": 5235,
"text": "Step 3 − Get the desired layout using the getLayout() method of the XSLFSlideMaster class. This method accepts a parameter where you have to pass one of the static variable of the SlideLayoutclass, which represents our desired layout. There are several variables in this class where each variable represents a slide layout."
},
{
"code": null,
"e": 5625,
"s": 5559,
"text": "The code snippet given below shows how to create a title layout −"
},
{
"code": null,
"e": 5698,
"s": 5625,
"text": "XSLFSlideLayout titleLayout = slideMaster.getLayout(SlideLayout.TITLE);\n"
},
{
"code": null,
"e": 5773,
"s": 5698,
"text": "Step 4 − Create a new slide by passing a slide layout object as parameter."
},
{
"code": null,
"e": 5822,
"s": 5773,
"text": "XSLFSlide slide = ppt.createSlide(titleLayout);\n"
},
{
"code": null,
"e": 6129,
"s": 5822,
"text": "Step 5 − Select a placeholder using the getPlaceholder() method of the XSLFSlide class. This method accepts an integer parameter. By passing 0 to it, you will get the XSLFTextShape object, using which you can access the title text area of the slide. Set the title using the setText() method as shown below."
},
{
"code": null,
"e": 6238,
"s": 6129,
"text": "XSLFTextShape title1 = slide.getPlaceholder(0);\n//setting the title init\ntitle1.setText(\"Tutorials point\");\n"
},
{
"code": null,
"e": 6330,
"s": 6238,
"text": "Given below is the complete program to create a slide with Title layout in a presentation −"
},
{
"code": null,
"e": 7768,
"s": 6330,
"text": "import java.io.File;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport org.apache.poi.xslf.usermodel.SlideLayout;\nimport org.apache.poi.xslf.usermodel.XMLSlideShow;\nimport org.apache.poi.xslf.usermodel.XSLFSlide;\nimport org.apache.poi.xslf.usermodel.XSLFSlideLayout;\nimport org.apache.poi.xslf.usermodel.XSLFSlideMaster;\nimport org.apache.poi.xslf.usermodel.XSLFTextShape;\n\npublic class TitleLayout {\n public static void main(String args[]) throws IOException {\n //creating presentation\n XMLSlideShow ppt = new XMLSlideShow();\t \t\n \n //getting the slide master object\n XSLFSlideMaster slideMaster = ppt.getSlideMasters().get(0);\n \n //get the desired slide layout \n XSLFSlideLayout titleLayout = slideMaster.getLayout(SlideLayout.TITLE);\n \n //creating a slide with title layout\n XSLFSlide slide1 = ppt.createSlide(titleLayout);\n \n //selecting the place holder in it \n XSLFTextShape title1 = slide1.getPlaceholder(0); \n \n //setting the title init \n title1.setText(\"Tutorials point\");\n \n //create a file object\n File file = new File(\"F://Titlelayout.pptx\");\n FileOutputStream out = new FileOutputStream(file);\n \n //save the changes in a PPt document\n ppt.write(out);\n System.out.println(\"slide cretated successfully\");\n out.close(); \n }\n}"
},
{
"code": null,
"e": 7883,
"s": 7768,
"text": "Save the above Java code as TitleLayout.java, and then compile and execute it from the command prompt as follows −"
},
{
"code": null,
"e": 7926,
"s": 7883,
"text": "$javac TitleLayout.java\n$java TitleLayout\n"
},
{
"code": null,
"e": 7988,
"s": 7926,
"text": "It will compile and execute to generate the following output."
},
{
"code": null,
"e": 8016,
"s": 7988,
"text": "slide created successfully\n"
},
{
"code": null,
"e": 8090,
"s": 8016,
"text": "The PPT document with newly added Title layout slide appears as follows −"
},
{
"code": null,
"e": 8183,
"s": 8090,
"text": "Let us create a slide in a PPT using Title and content layout. Follow the steps given below."
},
{
"code": null,
"e": 8277,
"s": 8183,
"text": "Step 1 − Create an empty presentation by instantiating the XMLSlideShow class as shown below."
},
{
"code": null,
"e": 8317,
"s": 8277,
"text": "XMLSlideShow ppt = new XMLSlideShow();\n"
},
{
"code": null,
"e": 8456,
"s": 8317,
"text": "Step 2 − Get the list of slide masters using the getSlideMasters() method. Select the desired slide master using the index as shown below."
},
{
"code": null,
"e": 8513,
"s": 8456,
"text": "XSLFSlideMaster slideMaster = ppt.getSlideMasters()[0];\n"
},
{
"code": null,
"e": 8615,
"s": 8513,
"text": "Here we are getting the default slide master which is in the 0th location of the slide masters array."
},
{
"code": null,
"e": 8922,
"s": 8615,
"text": "Step 3 − Get the desired layout using the getLayout() method of the XSLFSlideMaster class. This method accepts a parameter where you have to pass one of the static variable of the SlideLayout class which represents our desired layout. There are several variables in this class that represent slide layouts."
},
{
"code": null,
"e": 8996,
"s": 8922,
"text": "The following code snippet shows how to create title and content layout −"
},
{
"code": null,
"e": 9083,
"s": 8996,
"text": "XSLFSlideLayout contentlayout = slideMaster.getLayout(SlideLayout.TITLE_AND_CONTENT);\n"
},
{
"code": null,
"e": 9160,
"s": 9083,
"text": "Step 4 − Create a new slide by passing the slide layout object as parameter."
},
{
"code": null,
"e": 9227,
"s": 9160,
"text": "XSLFSlide slide = ppt.createSlide(SlideLayout.TITLE_AND_CONTENT);\n"
},
{
"code": null,
"e": 9531,
"s": 9227,
"text": "Step 5 − Select a placeholder using the getPlaceholder() method of the XSLFSlide class. This method accepts an integer parameter. By passing 1 to it, you will get the XSLFTextShape object, using which you can access the content area of the slide. Set the title using the setText() method as shown below."
},
{
"code": null,
"e": 9639,
"s": 9531,
"text": "XSLFTextShape title1 = slide1.getPlaceholder(1);\n//setting the title init \ntitle1.setText(\"Introduction\");\n"
},
{
"code": null,
"e": 9742,
"s": 9639,
"text": "Step 6 − Clear the existing text in the slide using the clearText() method of the XSLFTextShape class."
},
{
"code": null,
"e": 9761,
"s": 9742,
"text": "body.clearText();\n"
},
{
"code": null,
"e": 9975,
"s": 9761,
"text": "Step 7 − Add new paragraph using the addNewTextParagraph() method. Now add a new text run to the paragraph using the addNewTextRun() method. Now to the text run, add text using the setText() method as shown below."
},
{
"code": null,
"e": 10060,
"s": 9975,
"text": "body.addNewTextParagraph().addNewTextRun().setText(\"this is my first slide body\");\n"
},
{
"code": null,
"e": 10152,
"s": 10060,
"text": "Given below is the complete program to create a slide with Title layout in a presentation −"
},
{
"code": null,
"e": 11867,
"s": 10152,
"text": "import java.io.File;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport org.apache.poi.xslf.usermodel.SlideLayout;\nimport org.apache.poi.xslf.usermodel.XMLSlideShow;\nimport org.apache.poi.xslf.usermodel.XSLFSlide;\nimport org.apache.poi.xslf.usermodel.XSLFSlideLayout;\nimport org.apache.poi.xslf.usermodel.XSLFSlideMaster;\nimport org.apache.poi.xslf.usermodel.XSLFTextShape;\n\npublic class TitleAndBodyLayout {\n public static void main(String args[]) throws IOException {\n //creating presentation\n XMLSlideShow ppt = new XMLSlideShow();\n \n //getting the slide master object\n XSLFSlideMaster slideMaster = ppt.getSlideMasters().get(0);\n \n //select a layout from specified list\n XSLFSlideLayout slidelayout = slideMaster.getLayout(SlideLayout.TITLE_AND_CONTENT);\n \n //creating a slide with title and content layout\n XSLFSlide slide = ppt.createSlide(slidelayout);\n \n //selection of title place holder\n XSLFTextShape title = slide.getPlaceholder(0);\n \n //setting the title in it\n title.setText(\"introduction\");\n \n //selection of body placeholder\n XSLFTextShape body = slide.getPlaceholder(1);\n \n //clear the existing text in the slide\n body.clearText();\n \n //adding new paragraph\n body.addNewTextParagraph().addNewTextRun().setText(\"this is my first slide body\");\n \n //create a file object\n File file = new File(\"contentlayout.pptx\");\n FileOutputStream out = new FileOutputStream(file);\n \n //save the changes in a file\n ppt.write(out);\n System.out.println(\"slide cretated successfully\");\n out.close(); \n }\n}"
},
{
"code": null,
"e": 11982,
"s": 11867,
"text": "Save the above Java code as TitleLayout.java, and then compile and execute it from the command prompt as follows −"
},
{
"code": null,
"e": 12025,
"s": 11982,
"text": "$javac TitleLayout.java\n$java TitleLayout\n"
},
{
"code": null,
"e": 12088,
"s": 12025,
"text": "It will compile and execute to generate the following output −"
},
{
"code": null,
"e": 12116,
"s": 12088,
"text": "slide created successfully\n"
},
{
"code": null,
"e": 12190,
"s": 12116,
"text": "The PPT document with newly added Title layout slide appears as follows −"
},
{
"code": null,
"e": 12261,
"s": 12190,
"text": "In the same way, you can create slides with different layouts as well."
},
{
"code": null,
"e": 12296,
"s": 12261,
"text": "\n 46 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 12315,
"s": 12296,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 12350,
"s": 12315,
"text": "\n 23 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 12371,
"s": 12350,
"text": " Mukund Kumar Mishra"
},
{
"code": null,
"e": 12404,
"s": 12371,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 12417,
"s": 12404,
"text": " Nilay Mehta"
},
{
"code": null,
"e": 12452,
"s": 12417,
"text": "\n 52 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 12470,
"s": 12452,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 12503,
"s": 12470,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 12521,
"s": 12503,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 12554,
"s": 12521,
"text": "\n 23 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 12572,
"s": 12554,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 12579,
"s": 12572,
"text": " Print"
},
{
"code": null,
"e": 12590,
"s": 12579,
"text": " Add Notes"
}
] |
Difference between the largest and the smallest primes in an array in Java | With a given array of integers where all elements are less than 1000000. Find the difference between the largest and the smallest primes in an array.
Array: [ 1, 2, 3, 4, 5 ]
Largest Prime Number = 5
Smallest Prime Number = 2
Difference = 5 - 3 = 2.
Use Sieve of Eratosthenes approach, which is an efficient way to find out all prime numbers smaller than a given number. Then we will figure out the largest and smallest prime number to get the required difference.
Live Demo
Following is the program in Java to find the required output.
public class JavaTester {
static int MAX = 1000000;
static boolean prime[] = new boolean[MAX + 1];
public static void runSieveOfEratosthenes(){
//reset prime flags to be true
for(int i=0; i< MAX+1; i++) prime[i] = true;
//set 1 as non-prime
prime[1] = false;
for (int p = 2; p * p <= MAX; p++) {
// If prime[p] is not modified, then it is a prime
if (prime[p]) {
// Update all multiples of p
for (int i = p * 2; i <= MAX; i += p) prime[i] = false;
}
}
}
public static int difference(int arr[]){
int min = MAX + 2;
int max = -1;
for (int i = 0; i < arr.length; i++) {
// check if the number is prime or not
if (prime[arr[i]] == true) {
// set the max and min values
if (arr[i] > max) max = arr[i];
if (arr[i] < min) min = arr[i];
}
}
return max - min;
}
public static void main(String args[]){
// run the sieve
runSieveOfEratosthenes();
int arr[] = { 1, 2, 3, 4, 5 };
System.out.println(difference(arr));
}
}
3 | [
{
"code": null,
"e": 1212,
"s": 1062,
"text": "With a given array of integers where all elements are less than 1000000. Find the difference between the largest and the smallest primes in an array."
},
{
"code": null,
"e": 1314,
"s": 1212,
"text": "Array: [ 1, 2, 3, 4, 5 ]\n\nLargest Prime Number = 5\nSmallest Prime Number = 2\n\nDifference = 5 - 3 = 2."
},
{
"code": null,
"e": 1529,
"s": 1314,
"text": "Use Sieve of Eratosthenes approach, which is an efficient way to find out all prime numbers smaller than a given number. Then we will figure out the largest and smallest prime number to get the required difference."
},
{
"code": null,
"e": 1540,
"s": 1529,
"text": " Live Demo"
},
{
"code": null,
"e": 1602,
"s": 1540,
"text": "Following is the program in Java to find the required output."
},
{
"code": null,
"e": 2743,
"s": 1602,
"text": "public class JavaTester {\n\n static int MAX = 1000000;\n static boolean prime[] = new boolean[MAX + 1];\n\n public static void runSieveOfEratosthenes(){\n //reset prime flags to be true\n for(int i=0; i< MAX+1; i++) prime[i] = true;\n //set 1 as non-prime\n prime[1] = false;\n\n for (int p = 2; p * p <= MAX; p++) {\n // If prime[p] is not modified, then it is a prime\n if (prime[p]) {\n // Update all multiples of p\n for (int i = p * 2; i <= MAX; i += p) prime[i] = false;\n }\n }\n }\n\n public static int difference(int arr[]){\n int min = MAX + 2;\n int max = -1;\n for (int i = 0; i < arr.length; i++) {\n // check if the number is prime or not\n if (prime[arr[i]] == true) {\n // set the max and min values\n if (arr[i] > max) max = arr[i];\n if (arr[i] < min) min = arr[i];\n }\n }\n return max - min;\n }\n\n public static void main(String args[]){\n // run the sieve\n runSieveOfEratosthenes();\n int arr[] = { 1, 2, 3, 4, 5 };\n System.out.println(difference(arr));\n }\n}"
},
{
"code": null,
"e": 2745,
"s": 2743,
"text": "3"
}
] |
CSS - background-image | background-image defines a pointer to an image resource which is to be placed in the background of an element.
uri − URL of the image.
uri − URL of the image.
none − Setting background-image to none means that no background image should be used for matching elements.
none − Setting background-image to none means that no background image should be used for matching elements.
transparent
transparent
All the HTML elements.
object.style.backgroundImage = "Any value as defined above";
Following is the example which demonstrates how to set the background image for an element.
<html>
<head>
<style>
body {
background-image: url("/css/images/css.jpg");
background-color: #cccccc;
}
</style>
</head>
<body>
<h1>Hello World!</h1>
</body>
<html>
It will produce the following result −
33 Lectures
2.5 hours
Anadi Sharma
26 Lectures
2.5 hours
Frahaan Hussain
44 Lectures
4.5 hours
DigiFisk (Programming Is Fun)
21 Lectures
2.5 hours
DigiFisk (Programming Is Fun)
51 Lectures
7.5 hours
DigiFisk (Programming Is Fun)
52 Lectures
4 hours
DigiFisk (Programming Is Fun)
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2737,
"s": 2626,
"text": "background-image defines a pointer to an image resource which is to be placed in the background of an element."
},
{
"code": null,
"e": 2761,
"s": 2737,
"text": "uri − URL of the image."
},
{
"code": null,
"e": 2785,
"s": 2761,
"text": "uri − URL of the image."
},
{
"code": null,
"e": 2894,
"s": 2785,
"text": "none − Setting background-image to none means that no background image should be used for matching elements."
},
{
"code": null,
"e": 3003,
"s": 2894,
"text": "none − Setting background-image to none means that no background image should be used for matching elements."
},
{
"code": null,
"e": 3015,
"s": 3003,
"text": "transparent"
},
{
"code": null,
"e": 3027,
"s": 3015,
"text": "transparent"
},
{
"code": null,
"e": 3050,
"s": 3027,
"text": "All the HTML elements."
},
{
"code": null,
"e": 3112,
"s": 3050,
"text": "object.style.backgroundImage = \"Any value as defined above\";\n"
},
{
"code": null,
"e": 3204,
"s": 3112,
"text": "Following is the example which demonstrates how to set the background image for an element."
},
{
"code": null,
"e": 3445,
"s": 3204,
"text": "<html>\n <head>\n <style>\n body {\n background-image: url(\"/css/images/css.jpg\");\n background-color: #cccccc;\n }\n </style>\n </head>\n \n <body>\n <h1>Hello World!</h1>\n </body>\n<html>"
},
{
"code": null,
"e": 3484,
"s": 3445,
"text": "It will produce the following result −"
},
{
"code": null,
"e": 3519,
"s": 3484,
"text": "\n 33 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3533,
"s": 3519,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3568,
"s": 3533,
"text": "\n 26 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3585,
"s": 3568,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3620,
"s": 3585,
"text": "\n 44 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3651,
"s": 3620,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 3686,
"s": 3651,
"text": "\n 21 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3717,
"s": 3686,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 3752,
"s": 3717,
"text": "\n 51 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 3783,
"s": 3752,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 3816,
"s": 3783,
"text": "\n 52 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 3847,
"s": 3816,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 3854,
"s": 3847,
"text": " Print"
},
{
"code": null,
"e": 3865,
"s": 3854,
"text": " Add Notes"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.