title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
How does Duff’s Device work?
09 Feb, 2018 Duff’s device is a trick to express loop unrolling directly in C or C++ without extra code to treat the leftover partial loop.The trick is to use a switch statement where all but one of the cases labels are in the middle of a while loop. Further, all cases fall through to the end of the while loop. Despite the impression, it makes Duff’s device is legal C and C++ code (however, it is not valid in Java). How is it useful? There are two key things to Duff’s device. First, the loop is unrolled. We get more speed by avoiding some of the overhead involved in checking whether the loop is finished and jumping back to the top of the loop. The CPU can run faster when it’s executing straight-line code instead of jumping. However code size becomes larger.The second aspect is the switch statement. It allows the code to jump into the middle of the loop the first time through. The surprising part to most people is that such a thing is allowed. Well, it’s allowed. First, the loop is unrolled. We get more speed by avoiding some of the overhead involved in checking whether the loop is finished and jumping back to the top of the loop. The CPU can run faster when it’s executing straight-line code instead of jumping. However code size becomes larger. The second aspect is the switch statement. It allows the code to jump into the middle of the loop the first time through. The surprising part to most people is that such a thing is allowed. Well, it’s allowed. Example // C program to illustrate the working of// Duff's Device. The program copies given// number of elements bool array src[] to// dest[]#include<stdio.h>#include<string.h>#include <stdlib.h> // Copies size bits from src[] to dest[]void copyBoolArray(bool src[], bool dest[], int size){ // Do copy in rounds of size 8. int rounds = size / 8; int i = 0; switch (size % 8) { case 0: while (!(rounds == 0)) { rounds = rounds - 1; dest[i] = src[i]; i = i + 1; // An important point is, the switch // control can directly reach below labels case 7: dest[i] = src[i]; i = i + 1; case 6: dest[i] = src[i]; i = i + 1; case 5: dest[i] = src[i]; i = i + 1; case 4: dest[i] = src[i]; i = i + 1; case 3: dest[i] = src[i]; i = i + 1; case 2: dest[i] = src[i]; i = i + 1; case 1: dest[i] = src[i]; i = i + 1; }; }} // Driver codeint main(){ int size = 20; bool dest[size], src[size]; // Assign some random values to src[] int i; for (i=0; i<size; i++) src[i] = rand()%2; copyBoolArray(src, dest, size); for (i=0; i<size ; i++) printf("%d\t%d\n", src[i], dest[i]);} Output: 1 1 0 0 1 1 1 1 1 1 1 1 0 0 0 0 1 1 1 1 0 0 1 1 0 0 1 1 1 1 0 0 0 0 0 0 0 0 1 1 How does the above program work?In the above example, we are dealing with 20 bytes and copying these 20 random bits from src array to destination array. A number of passes for which it will run also depends on the size of the source array. For the first pass, execution starts at the calculated case label, and then it falls through to each successive assignment statement, just like any other switch statement. After the last case label, execution reaches the bottom of the loop, at which point it jumps back to the top. The top of the loop is inside the switch statement, so the switch is not re-evaluated anymore. The original loop is unwound eight times, so the number of iterations is divided by eight. If the number of bytes to be copied isn’t a multiple of eight, then there are some bytes left over. Most algorithms that copy blocks of bytes at a time will handle the remainder bytes at the end, but Duff’s device handles them at the beginning. The function calculates count % 8 for the switch statement to figure what the remainder will be, jumps to the case label for that many bytes, and copies them. Then the loop continues to copy groups of eight bytes in the left passes. For first pass: rounds = count / 8; // rounds = 2 for count =20 i = 0; switch(count % 8) { // The remainder is 4 (20 modulo 8) // so jump to the case 4 case 0: while( !(rounds == 0) ) { //[skipped] rounds = rounds - 1; dest[i] = src[i]; i = i + 1; case 7: dest[i] = src[i]; i = i + 1; //[skipped] case 6: dest[i] = src[i]; i = i + 1; //[skipped] case 5: dest[i] = src[i]; i = i + 1; //[skipped] case 4: dest[i] = src[i]; i = i + 1; //Start here. Copy 1 byte (total 1) case 3: dest[i] = src[i]; i = i + 1; //Copy 1 byte (total 2) case 2: dest[i] = src[i]; i = i + 1; //Copy 1 byte (total 3) case 1: dest[i] = src[i]; i = i + 1; //Copy 1 byte (total 4) }; } For second pass: rounds = count / 8; i = 0; switch(count % 8) { case 0: while( !(rounds == 0) ) { // rounds is decremented by 1 as while // loop works, now rounds=1 rounds = rounds - 1; dest[i] = src[i]; i = i + 1; // Copy 1 byte (total 5) case 7: dest[i] = src[i]; i = i + 1; // Copy 1 byte (total 6) case 6: dest[i] = src[i]; i = i + 1; // Copy 1 byte (total 7) case 5: dest[i] = src[i]; i = i + 1; // Copy 1 byte (total 8) case 4: dest[i] = src[i]; i = i + 1; // Copy 1 byte (total 9) case 3: dest[i] = src[i]; i = i + 1; // Copy 1 byte (total 10) case 2: dest[i] = src[i]; i = i + 1; // Copy 1 byte (total 11) case 1: dest[i] = src[i]; i = i + 1; // Copy 1 byte (total 12) } } For third pass: rounds = count / 8; i = 0; switch(count % 8) { case 0: while( !(rounds == 0) ) { //now while loop works rounds = rounds - 1; //rounds is decremented by 1, now rounds=0 dest[i] = src[i]; i = i + 1; // Copy 1 byte (total 13) case 7: dest[i] = src[i]; i = i + 1; // Copy 1 byte (total 14) case 6: dest[i] = src[i]; i = i + 1; // Copy 1 byte (total 15) case 5: dest[i] = src[i]; i = i + 1; // Copy 1 byte (total 16) case 4: dest[i] = src[i]; i = i + 1; // Copy 1 byte (total 17) case 3: dest[i] = src[i]; i = i + 1; // Copy 1 byte (total 18) case 2: dest[i] = src[i]; i = i + 1; // Copy 1 byte (total 19) case 1: dest[i] = src[i]; i = i + 1; // Copy 1 byte (total 20) }; } References:Wikipediahttp://www.lysator.liu.se/c/duffs-device.html This article is contributed by Nikhil Kumar Sharma. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. 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 Language C++ Technical Scripter CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n09 Feb, 2018" }, { "code": null, "e": 461, "s": 54, "text": "Duff’s device is a trick to express loop unrolling directly in C or C++ without extra code to treat the leftover partial loop.The trick is to use a switch statement where all but one of the cases labels are in the middle of a while loop. Further, all cases fall through to the end of the while loop. Despite the impression, it makes Duff’s device is legal C and C++ code (however, it is not valid in Java)." }, { "code": null, "e": 479, "s": 461, "text": "How is it useful?" }, { "code": null, "e": 522, "s": 479, "text": "There are two key things to Duff’s device." }, { "code": null, "e": 1018, "s": 522, "text": "First, the loop is unrolled. We get more speed by avoiding some of the overhead involved in checking whether the loop is finished and jumping back to the top of the loop. The CPU can run faster when it’s executing straight-line code instead of jumping. However code size becomes larger.The second aspect is the switch statement. It allows the code to jump into the middle of the loop the first time through. The surprising part to most people is that such a thing is allowed. Well, it’s allowed." }, { "code": null, "e": 1305, "s": 1018, "text": "First, the loop is unrolled. We get more speed by avoiding some of the overhead involved in checking whether the loop is finished and jumping back to the top of the loop. The CPU can run faster when it’s executing straight-line code instead of jumping. However code size becomes larger." }, { "code": null, "e": 1515, "s": 1305, "text": "The second aspect is the switch statement. It allows the code to jump into the middle of the loop the first time through. The surprising part to most people is that such a thing is allowed. Well, it’s allowed." }, { "code": null, "e": 1523, "s": 1515, "text": "Example" }, { "code": "// C program to illustrate the working of// Duff's Device. The program copies given// number of elements bool array src[] to// dest[]#include<stdio.h>#include<string.h>#include <stdlib.h> // Copies size bits from src[] to dest[]void copyBoolArray(bool src[], bool dest[], int size){ // Do copy in rounds of size 8. int rounds = size / 8; int i = 0; switch (size % 8) { case 0: while (!(rounds == 0)) { rounds = rounds - 1; dest[i] = src[i]; i = i + 1; // An important point is, the switch // control can directly reach below labels case 7: dest[i] = src[i]; i = i + 1; case 6: dest[i] = src[i]; i = i + 1; case 5: dest[i] = src[i]; i = i + 1; case 4: dest[i] = src[i]; i = i + 1; case 3: dest[i] = src[i]; i = i + 1; case 2: dest[i] = src[i]; i = i + 1; case 1: dest[i] = src[i]; i = i + 1; }; }} // Driver codeint main(){ int size = 20; bool dest[size], src[size]; // Assign some random values to src[] int i; for (i=0; i<size; i++) src[i] = rand()%2; copyBoolArray(src, dest, size); for (i=0; i<size ; i++) printf(\"%d\\t%d\\n\", src[i], dest[i]);}", "e": 2939, "s": 1523, "text": null }, { "code": null, "e": 2947, "s": 2939, "text": "Output:" }, { "code": null, "e": 3091, "s": 2947, "text": "1 1\n0 0\n1 1\n1 1\n1 1\n1 1\n0 0\n0 0\n1 1\n1 1\n0 0\n1 1\n0 0\n1 1\n1 1\n0 0\n0 0\n0 0\n0 0\n1 1\n" }, { "code": null, "e": 3331, "s": 3091, "text": "How does the above program work?In the above example, we are dealing with 20 bytes and copying these 20 random bits from src array to destination array. A number of passes for which it will run also depends on the size of the source array." }, { "code": null, "e": 3708, "s": 3331, "text": "For the first pass, execution starts at the calculated case label, and then it falls through to each successive assignment statement, just like any other switch statement. After the last case label, execution reaches the bottom of the loop, at which point it jumps back to the top. The top of the loop is inside the switch statement, so the switch is not re-evaluated anymore." }, { "code": null, "e": 4277, "s": 3708, "text": "The original loop is unwound eight times, so the number of iterations is divided by eight. If the number of bytes to be copied isn’t a multiple of eight, then there are some bytes left over. Most algorithms that copy blocks of bytes at a time will handle the remainder bytes at the end, but Duff’s device handles them at the beginning. The function calculates count % 8 for the switch statement to figure what the remainder will be, jumps to the case label for that many bytes, and copies them. Then the loop continues to copy groups of eight bytes in the left passes." }, { "code": null, "e": 4293, "s": 4277, "text": "For first pass:" }, { "code": null, "e": 5150, "s": 4293, "text": "rounds = count / 8;\n\n// rounds = 2 for count =20\ni = 0;\nswitch(count % 8)\n{\n\n// The remainder is 4 (20 modulo 8)\n// so jump to the case 4\ncase 0:\n while( !(rounds == 0) )\n {\n //[skipped]\n rounds = rounds - 1;\n dest[i] = src[i];\n i = i + 1;\n\n case 7:\n dest[i] = src[i];\n i = i + 1; //[skipped]\n case 6:\n dest[i] = src[i];\n i = i + 1; //[skipped]\n case 5:\n dest[i] = src[i];\n i = i + 1; //[skipped]\n\n case 4:\n dest[i] = src[i];\n i = i + 1; //Start here. Copy 1 byte (total 1)\n case 3:\n dest[i] = src[i];\n i = i + 1; //Copy 1 byte (total 2)\n case 2:\n dest[i] = src[i];\n i = i + 1; //Copy 1 byte (total 3)\n case 1:\n dest[i] = src[i];\n i = i + 1; //Copy 1 byte (total 4)\n };\n}\n" }, { "code": null, "e": 5167, "s": 5150, "text": "For second pass:" }, { "code": null, "e": 6028, "s": 5167, "text": "rounds = count / 8;\ni = 0;\nswitch(count % 8)\n{\ncase 0:\n while( !(rounds == 0) )\n {\n // rounds is decremented by 1 as while\n // loop works, now rounds=1\n rounds = rounds - 1;\n dest[i] = src[i];\n i = i + 1; // Copy 1 byte (total 5)\n case 7:\n dest[i] = src[i];\n i = i + 1; // Copy 1 byte (total 6)\n case 6:\n dest[i] = src[i];\n i = i + 1; // Copy 1 byte (total 7)\n case 5:\n dest[i] = src[i];\n i = i + 1; // Copy 1 byte (total 8)\n case 4:\n dest[i] = src[i];\n i = i + 1; // Copy 1 byte (total 9)\n case 3:\n dest[i] = src[i];\n i = i + 1; // Copy 1 byte (total 10)\n case 2:\n dest[i] = src[i];\n i = i + 1; // Copy 1 byte (total 11)\n case 1:\n dest[i] = src[i];\n i = i + 1; // Copy 1 byte (total 12)\n }\n}\n" }, { "code": null, "e": 6044, "s": 6028, "text": "For third pass:" }, { "code": null, "e": 6934, "s": 6044, "text": "rounds = count / 8;\ni = 0;\nswitch(count % 8)\n{\ncase 0:\n while( !(rounds == 0) )\n {\n //now while loop works\n rounds = rounds - 1; //rounds is decremented by 1, now rounds=0\n dest[i] = src[i];\n i = i + 1; // Copy 1 byte (total 13)\n\n case 7:\n dest[i] = src[i];\n i = i + 1; // Copy 1 byte (total 14)\n case 6:\n dest[i] = src[i];\n i = i + 1; // Copy 1 byte (total 15)\n case 5:\n dest[i] = src[i];\n i = i + 1; // Copy 1 byte (total 16)\n case 4:\n dest[i] = src[i];\n i = i + 1; // Copy 1 byte (total 17)\n case 3:\n dest[i] = src[i];\n i = i + 1; // Copy 1 byte (total 18)\n case 2:\n dest[i] = src[i];\n i = i + 1; // Copy 1 byte (total 19)\n case 1:\n dest[i] = src[i];\n i = i + 1; // Copy 1 byte (total 20)\n };\n}\n" }, { "code": null, "e": 7000, "s": 6934, "text": "References:Wikipediahttp://www.lysator.liu.se/c/duffs-device.html" }, { "code": null, "e": 7307, "s": 7000, "text": "This article is contributed by Nikhil Kumar Sharma. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 7432, "s": 7307, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 7443, "s": 7432, "text": "C Language" }, { "code": null, "e": 7447, "s": 7443, "text": "C++" }, { "code": null, "e": 7466, "s": 7447, "text": "Technical Scripter" }, { "code": null, "e": 7470, "s": 7466, "text": "CPP" } ]
GATE | GATE CS Mock 2018 | Question 59
10 Jan, 2018 Consider a database with the following schema: Person ( name, age, gender ) name is a key Frequents ( name, pizzeria ) (name, pizzeria) is a key Eats ( name, pizza ) (name, pizza) is a key Serves ( pizzeria, pizza, price ) (pizzeria, pizza) is a key Relational algebra expression for query “Names of all people who frequent only pizzeria’s serving at least one pizza they eat” is (A) (B) (C) (D) None of the aboveAnswer: (B)Explanation: Find names of all people who frequent only pizzerias serving at least one pizza they eat : Option (B) is correct.Quiz of this Question GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n10 Jan, 2018" }, { "code": null, "e": 75, "s": 28, "text": "Consider a database with the following schema:" }, { "code": null, "e": 279, "s": 75, "text": "Person ( name, age, gender )\nname is a key\nFrequents ( name, pizzeria )\n(name, pizzeria) is a key\nEats ( name, pizza )\n(name, pizza) is a key\nServes ( pizzeria, pizza, price )\n(pizzeria, pizza) is a key\n" }, { "code": null, "e": 409, "s": 279, "text": "Relational algebra expression for query “Names of all people who frequent only pizzeria’s serving at least one pizza they eat” is" }, { "code": null, "e": 414, "s": 409, "text": "(A) " }, { "code": null, "e": 558, "s": 414, "text": "(B) (C) (D) None of the aboveAnswer: (B)Explanation: Find names of all people who frequent only pizzerias serving at least one pizza they eat :" }, { "code": null, "e": 602, "s": 558, "text": "Option (B) is correct.Quiz of this Question" }, { "code": null, "e": 607, "s": 602, "text": "GATE" } ]
Find a number x such that sum of x and its digits is equal to given n.
28 Apr, 2021 Given a positive number n. We need to find a number x such that sum of digits of x to itself is equal to n. If no such x is possible print -1.Examples: Input : n = 21 Output : x = 15 Explanation : x + its digit sum = 15 + 1 + 5 = 21 Input : n = 5 Output : -1 We iterate from 1 to n and for each intermediate number, x find its digit sum and then add that to x, if that is equal to n then x will be our required answer. // iterate from 1 to n. For every no. // check if its digit sum with it is // equal to n. for (int i = 0; i <= n; i++) if (i + digSum(i) == n) return i; return -1; C++ Java Python3 C# PHP Javascript // CPP program to find x such that x +// digSum(x) is equal to n.#include <bits/stdc++.h>using namespace std; // utility function for digit sumint digSum(int n){ int sum = 0, rem = 0; while (n) { rem = n % 10; sum += rem; n /= 10; } return sum;} // function for finding xint findX(int n){ // iterate from 1 to n. For every no. // check if its digit sum with it is // equal to n. for (int i = 0; i <= n; i++) if (i + digSum(i) == n) return i; // if no such i found return -1 return -1;} // driver functionint main(){ int n = 43; cout << "x = " << findX(n); return 0;} // Java program to find x such that x +// digSum(x) is equal to n.class GFG{ // utility function for digit sum static int digSum(int n) { int sum = 0, rem = 0; while (n>0) { rem = n % 10; sum += rem; n /= 10; } return sum; } // function for finding x static int findX(int n) { // iterate from 1 to n. For every no. // check if its digit sum with it is // equal to n. for (int i = 0; i <= n; i++) if (i + digSum(i) == n) return i; // if no such i found return -1 return -1; } // Driver code public static void main (String[] args) { int n = 43; System.out.println("x = "+findX(n)); }} // This code is contributed by Anant Agarwal. # Python3 program to find# x such that dx + igSum(x)# is equal to n. # utility function# for digit sumdef digSum(n): sum = 0; rem = 0; while(n): rem = n % 10; sum = sum + rem; n = int(n / 10); return sum; # function for finding xdef findX(n): # iterate from 1 to n. # For every no. # check if its digit # sum with it is# equal to n. for i in range(n + 1): if (i + digSum(i) == n): return i; # if no such i # found return -1 return -1; # Driver Coden = 43;print("x = ", findX(n)); # This code is contributed by mits // C# program to find x such that// x + digSum(x) is equal to n.using System; class GFG { // utility function for digit sum static int digSum(int n) { int sum = 0, rem = 0; while (n > 0) { rem = n % 10; sum += rem; n /= 10; } return sum; } // function for finding x static int findX(int n) { // iterate from 1 to n. For every no. // check if its digit sum with it is // equal to n. for (int i = 0; i <= n; i++) if (i + digSum(i) == n) return i; // if no such i found return -1 return -1; } // Driver code public static void Main() { int n = 43; Console.Write("x = " + findX(n)); }} // This code is contributed by vt_m. <?php// PHP program to find x such that// dx + igSum(x) is equal to n. // utility function// for digit sumfunction digSum($n){ $sum = 0; $rem = 0; while ($n) { $rem = $n % 10; $sum += $rem; $n /= 10; } return $sum;} // function for finding xfunction findX($n){ // iterate from 1 to n. // For every no. // check if its digit // sum with it is // equal to n. for ($i = 0; $i <= $n; $i++) if ($i + digSum($i) == $n) return $i; // if no such i // found return -1 return -1;} // Driver Code $n = 43; echo "x = " , findX($n); // This code is contributed by vt_m.?> <script> // Javascript program to find x such that x +// digSum(x) is equal to n. // utility function for digit sum function digSum(n) { let sum = 0, rem = 0; while (n>0) { rem = n % 10; sum += rem; n = Math.floor(n / 10); } return sum; } // function for finding x function findX(n) { // iterate from 1 to n. For every no. // check if its digit sum with it is // equal to n. for (let i = 0; i <= n; i++) if (i + digSum(i) == n) return i; // if no such i found return -1 return -1; } // driver program let n = 43; document.write("x = "+findX(n)); </script> Output: x = 35 This article is contributed by Shivam Pradhan (anuj_charm). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. 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 Mithun Kumar splevel62 number-digits Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n28 Apr, 2021" }, { "code": null, "e": 206, "s": 52, "text": "Given a positive number n. We need to find a number x such that sum of digits of x to itself is equal to n. If no such x is possible print -1.Examples: " }, { "code": null, "e": 315, "s": 206, "text": "Input : n = 21\nOutput : x = 15\nExplanation : x + its digit sum = 15 + 1 + 5 = 21 \n\nInput : n = 5\nOutput : -1" }, { "code": null, "e": 479, "s": 317, "text": "We iterate from 1 to n and for each intermediate number, x find its digit sum and then add that to x, if that is equal to n then x will be our required answer. " }, { "code": null, "e": 685, "s": 479, "text": " // iterate from 1 to n. For every no.\n // check if its digit sum with it is\n // equal to n.\n for (int i = 0; i <= n; i++)\n if (i + digSum(i) == n)\n return i;\n\n return -1;" }, { "code": null, "e": 691, "s": 687, "text": "C++" }, { "code": null, "e": 696, "s": 691, "text": "Java" }, { "code": null, "e": 704, "s": 696, "text": "Python3" }, { "code": null, "e": 707, "s": 704, "text": "C#" }, { "code": null, "e": 711, "s": 707, "text": "PHP" }, { "code": null, "e": 722, "s": 711, "text": "Javascript" }, { "code": "// CPP program to find x such that x +// digSum(x) is equal to n.#include <bits/stdc++.h>using namespace std; // utility function for digit sumint digSum(int n){ int sum = 0, rem = 0; while (n) { rem = n % 10; sum += rem; n /= 10; } return sum;} // function for finding xint findX(int n){ // iterate from 1 to n. For every no. // check if its digit sum with it is // equal to n. for (int i = 0; i <= n; i++) if (i + digSum(i) == n) return i; // if no such i found return -1 return -1;} // driver functionint main(){ int n = 43; cout << \"x = \" << findX(n); return 0;}", "e": 1372, "s": 722, "text": null }, { "code": "// Java program to find x such that x +// digSum(x) is equal to n.class GFG{ // utility function for digit sum static int digSum(int n) { int sum = 0, rem = 0; while (n>0) { rem = n % 10; sum += rem; n /= 10; } return sum; } // function for finding x static int findX(int n) { // iterate from 1 to n. For every no. // check if its digit sum with it is // equal to n. for (int i = 0; i <= n; i++) if (i + digSum(i) == n) return i; // if no such i found return -1 return -1; } // Driver code public static void main (String[] args) { int n = 43; System.out.println(\"x = \"+findX(n)); }} // This code is contributed by Anant Agarwal.", "e": 2241, "s": 1372, "text": null }, { "code": "# Python3 program to find# x such that dx + igSum(x)# is equal to n. # utility function# for digit sumdef digSum(n): sum = 0; rem = 0; while(n): rem = n % 10; sum = sum + rem; n = int(n / 10); return sum; # function for finding xdef findX(n): # iterate from 1 to n. # For every no. # check if its digit # sum with it is# equal to n. for i in range(n + 1): if (i + digSum(i) == n): return i; # if no such i # found return -1 return -1; # Driver Coden = 43;print(\"x = \", findX(n)); # This code is contributed by mits", "e": 2841, "s": 2241, "text": null }, { "code": "// C# program to find x such that// x + digSum(x) is equal to n.using System; class GFG { // utility function for digit sum static int digSum(int n) { int sum = 0, rem = 0; while (n > 0) { rem = n % 10; sum += rem; n /= 10; } return sum; } // function for finding x static int findX(int n) { // iterate from 1 to n. For every no. // check if its digit sum with it is // equal to n. for (int i = 0; i <= n; i++) if (i + digSum(i) == n) return i; // if no such i found return -1 return -1; } // Driver code public static void Main() { int n = 43; Console.Write(\"x = \" + findX(n)); }} // This code is contributed by vt_m.", "e": 3706, "s": 2841, "text": null }, { "code": "<?php// PHP program to find x such that// dx + igSum(x) is equal to n. // utility function// for digit sumfunction digSum($n){ $sum = 0; $rem = 0; while ($n) { $rem = $n % 10; $sum += $rem; $n /= 10; } return $sum;} // function for finding xfunction findX($n){ // iterate from 1 to n. // For every no. // check if its digit // sum with it is // equal to n. for ($i = 0; $i <= $n; $i++) if ($i + digSum($i) == $n) return $i; // if no such i // found return -1 return -1;} // Driver Code $n = 43; echo \"x = \" , findX($n); // This code is contributed by vt_m.?>", "e": 4366, "s": 3706, "text": null }, { "code": "<script> // Javascript program to find x such that x +// digSum(x) is equal to n. // utility function for digit sum function digSum(n) { let sum = 0, rem = 0; while (n>0) { rem = n % 10; sum += rem; n = Math.floor(n / 10); } return sum; } // function for finding x function findX(n) { // iterate from 1 to n. For every no. // check if its digit sum with it is // equal to n. for (let i = 0; i <= n; i++) if (i + digSum(i) == n) return i; // if no such i found return -1 return -1; } // driver program let n = 43; document.write(\"x = \"+findX(n)); </script>", "e": 5150, "s": 4366, "text": null }, { "code": null, "e": 5160, "s": 5150, "text": "Output: " }, { "code": null, "e": 5167, "s": 5160, "text": "x = 35" }, { "code": null, "e": 5607, "s": 5167, "text": "This article is contributed by Shivam Pradhan (anuj_charm). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. 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": 5612, "s": 5607, "text": "vt_m" }, { "code": null, "e": 5625, "s": 5612, "text": "Mithun Kumar" }, { "code": null, "e": 5635, "s": 5625, "text": "splevel62" }, { "code": null, "e": 5649, "s": 5635, "text": "number-digits" }, { "code": null, "e": 5662, "s": 5649, "text": "Mathematical" }, { "code": null, "e": 5675, "s": 5662, "text": "Mathematical" } ]
How to define multiline String Literal in C#?
Let’s say the string is − Welcome User, Kindly wait for the image to load For multiline String Literal, firstly set it like the following statement using@ prefix − string str = @"Welcome User, Kindly wait for the image to load"; Now let us display the result. The string is a multi-line string now − Live Demo using System; namespace Demo { class Program { static void Main(string[] args) { string str = @"Welcome User, Kindly wait for the image to load"; Console.WriteLine(str); } } } Welcome User, Kindly wait for the image to load
[ { "code": null, "e": 1088, "s": 1062, "text": "Let’s say the string is −" }, { "code": null, "e": 1136, "s": 1088, "text": "Welcome User, Kindly wait for the image to load" }, { "code": null, "e": 1226, "s": 1136, "text": "For multiline String Literal, firstly set it like the following statement using@ prefix −" }, { "code": null, "e": 1291, "s": 1226, "text": "string str = @\"Welcome User,\nKindly wait for the image to\nload\";" }, { "code": null, "e": 1362, "s": 1291, "text": "Now let us display the result. The string is a multi-line string now −" }, { "code": null, "e": 1373, "s": 1362, "text": " Live Demo" }, { "code": null, "e": 1607, "s": 1373, "text": "using System;\n\nnamespace Demo {\n\n class Program {\n\n static void Main(string[] args) {\n string str = @\"Welcome User,\n Kindly wait for the image to\n load\";\n\n Console.WriteLine(str);\n }\n }\n}" }, { "code": null, "e": 1655, "s": 1607, "text": "Welcome User,\nKindly wait for the image to\nload" } ]
The Perils of Palette Transfer. Explore the depths of algorithmic... | by Syafiq Kamarul Azman | Towards Data Science
A few weekends ago, I wanted to brush up on my clustering techniques. I recall —from an image processing class back in college — that you can reduce the number of unique colors in an image down to a few colors while keeping the important ones. This is achieved by doing k-means clustering on the RGB values of the pixels in an image. The number of colors that you want in your reduced palette is the k value in k-means clustering; in other words the number of cluster centers in RGB space that your image inhabit. This was particularly useful in the old days of video game graphics if an image needed to be rendered in a device with limited memory. By reducing the palette, you can conform to the limited color palette of PAL or SECAM, etc. since only 8 bits or 16 bits are allocated to the entire color palette (in contrast to the 24-bit RGB that is ubiquitous now). Today’s use? Well, if you’re particularly nostalgic about the artistry of low-bit graphics or building something to display on a LED matrix, this could be the use case. While playing around, I casually thought: “what if we transferred the reduced palette of one image into another?” It’s a seemingly innocuous question that expanded my knowledge of colors and parallel-processing toolbox. In this article, I’m going to explain how this artificial task of palette transfer can be done and how to take it further. Get ready to use tools from numpy, scikit-learn and dask. Look for the code on a prepared Colab notebook containing everything explained in this article. So let’s get some definitions in place before anything else. What I mean by palette is the set of RGB pixel values in an image. This number is usually in the tens of thousands for a small photographic image. Palette reduction is the algorithmic selection of a subset of the original palette of an image and mapping of all pixel values in the original palette to the closest values in the reduced palette. The code for this is relatively straightforward: run k-means clustering on all the pixels of an image and the resulting cluster centers are your reduced palette. We have to be careful as the cluster centers are not np.uint8 type but rather np.float64. When we call kmn.predict(src), the output values are all floats. The simple solution to this is just to round up these values to the nearest integer and cast it to np.uint8 type before displaying it. Here's what a reduced palette class could look like: The class definition is pretty basic: it contains the number of colors in the reduced palette and a sklearn.clustering.KMeans instance. First, we have a preprocessing function that makes sure the image is shaped up (pun intended) for the KMeans operations. The reshaping reforms the 3-dimensional matrix of W×H×C into a 2-dimensional matrix of WH×C where W is the width of the image, H is the height of the image and C is the three RGB color channels. Then, the KMeansReducedPalette.fit() function works as a wrapper to the KMeans.fit() function that creates the cluster centers in RGB space. Finally, the recolor() function transforms the original palette of an image into the reduced palette of the fitted image. Let's look at some examples of a palette reduction: Pretty, right? Even with the reduced palette, there is still a lot of charm to the image. Says a lot about the photographer’s chops, I’d say. One way to visualize these clusters is just to scatter plot them. Our data here is the unique RGB values of the image which is in 3-dimensions: one dimension for each color channel. This lends itself quite well to a 3D scatter plot: At 8 colors, there are relatively loose clusters but comparing the clusters colored by the centroid in comparison to the original colors, I think the clusters are pretty good. The colors do not diverge far although there are some light greens that are being cast grayish-green. With more points, the clusters would be more representative of the salient colors. Now, let’s tackle the second problem: transferring one image’s reduced palette into another. Turns out, this is relatively easy, we don’t need any further programming aside from passing a target image into the palette recolor() function. Let's look at some transfers: What happens here is that the distance of each pixel in the new image is measured against the reduced palette (i.e. the cluster centers). The RGB values of the transferring pixel are then swapped with the closest cluster center in the palette. This is why in situations where the source image doesn’t have many colors, or the reduced palette is too small, we get some cartoon-like effects in the overall image. It’s because the colors in the transferring image don’t get a good enough color to swap with but instead takes the nearest cluster center despite it being very distant to the transferring pixel value. Let’s experiment a bit with this before moving on. We did clustering based on all the pixels in the image but in reality, not all the pixels are unique. Chances are, around a particular region of an image, there are maybe tens or hundreds of the same pixel RGB value (particularly for static backgrounds, skies, and the like). Naturally, this will skew cluster centers around more abundant colors in the image; these are the colors that would immediately pop in the original image making them visually salient. For fun, let’s hack around and do clustering only on the unique pixels in the image (instead of all the pixels) and give them each equal opportunity. We will create a new class to enable this: The new class inherits the KMeansReducedPalette class which makes things much easier down the line: any further functionality that we add to the KMeansReducedPalette will be included in the UniqueKMeansReducedPalette class. The fit() function is overridden to fit the palette onto the set of unique pixels in the image. This doesn't add that much more to the overall computation since k-means clustering takes O(nk) time which is more expensive than finding unique pixels which only takes O(n) for an image with n pixels. Let's compare the results: From afar, there are very small differences: there seems to be about the same distribution of colors in the reduced palettes which can be attributed to the initial conditions of the k-means clustering algorithm. To my eyes, there is a subtle difference in the quality of the colors. Clustering on the entire image resulted in a slightly more saturated reduced palette in comparison to the clustering of the unique pixels which is more muted. There is subtly more contrast in the top row compared to the bottom rows. I attribute this to the result of clustering in the space of unique colors: essentially averaging the pixel values surrounding a locus without weighing colors that are more prevalent. We could go into a numerical analysis into color metrics to verify this (which I did, endlessly) but that would stray too far from the original intent of this article which is just to experiment with palette transfers so I will leave this as an exercise to the courageous among you. Here are some resources that I read through: color vision, chroma calculation. Let’s revisit what k-means clustering results in. After clustering, we are provided with k cluster centers which determine the label of other pixels surrounding it. If a point is in proximity to one centroid in comparison to all other centroids, the point is grouped into that centroid. Essentially, this creates k partitions in the data space; the boundaries of which can be visualized using a Voronoi diagram. In the scatter plot earlier, we can partially see the boundaries of the partitioning in 3D space. Since plotting a 3D Voronoi diagram is difficult, let’s turn to PCA and reduce the space to 2D and plot the Voronoi tessellation. What is clear from the plot is that the partitions are 2D geometric polygons. In the original 3D space, these partitions would be 3D polyhedrons. Also, the PCA “lies” about some of the points, especially at the boundaries, as the points have been projected down to a lower dimension (hence losing information). Try not to scrutinize the 2D Voronoi diagram too hard. Knowing the boundaries, we can randomly select RGB values within the partition as the recoloring of our new image rather than depending solely on the centroid’s RGB value. This gives us more variety to recolor our images. As we already have the centroids, we can start there and take small steps to reach random RGB values. This process is called a random walk. Let’s understand one variation of a random walk which is to move by 1 intensity unit in any RGB direction. This random walk can potentially explore the entirety of the 16,777,216 colors (if you take enough steps). Let’s code this up: The random_walk_recolor() function takes an image and the maximum number of steps to walk away from the cluster center. First, we recolor pixels as we did in the recolor() function which is stored as the starting points (start). Then we initialize a difference array (diff) which will determine the distance from the starting points for each color channel. Then we loop up to the max number of steps we want to take and take a walk of 1 unit in a single channel randomly. This is stored in walk: we randomly index a 3x3 identity matrix using np.eye() andnp.random.randint() for each pixel. For example an image with 9 pixels: walk = [[ 0, 0, 1], [ 0, 0, 1], [ 1, 0, 0], [ 0, 1, 0], [ 0, 0, 1], [ 0, 1, 0], [ 1, 0, 0], [ 1, 0, 0], [ 1, 0, 0]] Then we need to randomly select the sign of the walk (either in a positive or negative direction) using np.random.choice() on the set {-1, 1} which then transforms the walk array into: walk = [[ 0, 0, 1], [ 0, 0,-1], [-1, 0, 0], [ 0,-1, 0], [ 0, 0, 1], [ 0,-1, 0], [ 1, 0, 0], [-1, 0, 0], [-1, 0, 0]] Finally, we add the walk into the diff array. If we repeat this enough times, we get some random distribution of steps away from the cluster centers that is at most the maximum number of steps that we desire. The final random walk diff might be something like so for a maximum step size of 3: walk = [[ 0, 0, 1], [ 0, 0,-2], [-1, 1, 0], [ 0,-1,-1], [ 0, 0, 3], [ 0,-1, 0], [ 2, 0, 1], [ 0, 0, 0], [-1,-1, 1]] Due to the randomness of random walk, we might not even move away from the cluster center; this is highly unlikely for a large step size though. The final recoloring is simply the starting points of the k-means recoloring plus the walk. How does a recoloring of different step values look like with a 32-color palette on a different transferring image? For this example, I will transfer the palette of Rabada’s seaside to Gozha’s flower. Well, looks like we just applied some noise to it but we maintain the general transfer. The noise does get rather overwhelming at very high distances. But it’s cool nonetheless. The first random walk variant is not guaranteed to visit the unique pixels we have in the original image. In fact, it may even transcend the boundaries of the partitioning that we mentioned earlier. What if we instead wanted to only walk around the neighboring pixels to the cluster center? Also, we would want to stay within a partition; we don’t want to be wandering around the wrong neighborhood now, do we? To find a random pixel that neighbors a centroid, we would need to calculate the distance of each of the pixels in a cluster to the centroid and randomly pick the closest neighbors up to some max walking step. One optimization we can make in this particular scenario is to precalculate these distances as they will never change once clustering is done. The strategy here is to perform all distance calculations for all pixels within each cluster to its nearest centroid during the fit() stage, sort the pixels based on their distance to the centroid in ascending order, and store it so it can be used later. Here's the code for that: What this does is loop through the number of clusters in the palette and store the distances for each pixel to the cluster center. First, we get all the pixels from the original image that is in the current cluster (pixels_ci) and calculate the Euclidean distance to the cluster center (distances_ci). Then we use np.argsort() to get the sorted indices for the distances and then use it to index pixels_ci. Now we are just left with a matrix of pixels in ascending order of distance down the rows. To do a random walk, we just select a random number up to the maximum index value (the random number represents the number of steps). We would also need to make sure that the index does not exceed the size of the cluster. Here’s the code to recolor with this neighborhood random walk: The code is relatively simple: we first recolor as we would for the other random walk and then iterate through each cluster and pick a random nearest neighbor. We used np.random.randint() to generate random indices to select the nearest neighbor. Since the random function is maxed at the max_steps, we won't explore beyond the neighbor that is ranked below the max_steps value. Additionally, setting the maximum random number to the minimum value between n_neighbors and max_steps ensures that you are within the confines of the neighborhood. The resulting random walks are as shown below: The noise is a lot more subtle and unnoticeable in the lower distances. The “semantic” of the noise also more sensible: it doesn’t stray too far away from what the original pixel is meant to represent. It’s almost as if you got a photo from a DSLR with a bad sensor or some high ISO value. Nice! All the techniques we’ve seen reduces the palette before making a transfer. Arguably, this is a much easier transfer to make as we only need to compare n pixels with k cluster centers. What if instead, we wanted to do a palette transfer of the all unique pixels? Well, if we assumed we had an equal palette size in the source image and the transferring image, we will need to do an O(n2) comparison to find the nearest pixel of the transferring image and the source image. This is problematic: our 320 by 480 pixels working images have an order of 105 unique pixels. A pairwise comparison would yield a matrix that is in the order of (105)2 or 1010 during the computation. Clearly, this cannot fit into memory unless you have a massive amount of memory (and most commodity computers don’t). We could go with looping but Python loops are notoriously slow. An ideal middle ground can be achieved if we deployed some form of vectorized computation (which is faster than loops) along with array chunking. Chunking divides a large vectorized computation into smaller manageable computations and collects the pieces to form the final output array. The library dask is a popular implementation in Python that will allow us to this while keeping the numpy syntax flavor in the code. dask enables parallelization too, which means we can defer these computations potentially to different machines or completely exploit all the cores of a computer. Here's what the code looks like: The entire palette transfer class has a very basic constructor. The constructor requires a chunk size value (defaulted at 1024). This trades off computation memory and parallelization in a small computer but you can adjust to larger values if you have more memory. The fitting step just stores all the unique pixels in an image. We only take the unique pixels in the source image to minimize computation since we can map all pixels in the transferring image to a subset of the source pixels. This mapping will be created when we perform recolor(). The meat of the class is the recolor() function. First, we preprocess the transferring image and collect all the unique pixels. Then we create a dask.array.core.Array object for the unique pixels in the source image and the transferring image. The transferring image is reshaped to a 3D array for vectorization of the pairwise difference calculation. Let’s pause here and understand the computational burden that we are bearing. dask has a feature of visualizing the memory allocated for a computation step in a notebook environment. If you place the following code for a source and transferring image: We get the following images displayed in the notebook output cell: Clearly, the source and transferring dask array of unique pixels occupy very little memory. However, the moment, we execute the pairwise difference, we would need to allocate 77.29 GB of memory. In a traditional NumPy setting, this would either crash or NumPy will yield an error message saying it cannot allocate that much memory. This is when dask shines for its chunking capabilities to enable the computation of such massive arrays without actually allocating all that memory. Ultimately, we don’t need the pairwise distances, we only need the transferring pixels that has the smallest distance to the source pixels. Returning back to the code, we perform the Euclidean distance calculation and only keep the index of the transferring pixel which has the smallest distance to the source pixels, thus leaving a much smaller output array. To actually run the computation, we must call idxs_da.compute() and we will make use of the built-in ProgressBar() that comes with dask to display the progress of the calculation. Once we have the indices calculated, we create a dictionary mapping from one RGB source pixel to the closest RGB transferring pixel. Python dictionaries use hashing which means that lookups are very fast (theoretically, it takes constant time). Finally, to transfer the pixels, we loop over all pixels in the transferring image and use the pixel mapping to swap the RGB pixel values. Let’s view some of the transfers! This time I will use Ito’s flowers and transfer the palette to the rest of the images. Beautiful outputs. The transferred images have a more natural coloring, less blockiness, and look very similar to their originals. While doing this transfer, I couldn’t help but notice that Gozha’s flower really could’ve had some better transfers. There are definitely some pinks or reddish hues in Ito’s flower that would’ve been better for the transfer but perhaps was just too far away. What I did not realize was the weakness of our method: the Euclidean distance. Here’s the problem: the Euclidean distance assumes that colors are distributed equally around a 255 by 255 by 255 3D cube. The distances between those points would determine how far the colors were from one another. However, perceptually, we perceive the distances differently. It’s a very profound question to ask “how far is one red hue to another?”, but it suffices to say that the Euclidean distance does not do our differential perception justice. So I went scouring the web for an answer for a distance measure that is simple to compute and yet does the job to some extent. This site details the calculation using RGB space for a more “correct” perceptual color distance. I’ll leave the discourse to the site itself but in summary, the author compromises between converting into another color space (like YUV or CIELAB) and considered correctional factors that would affect the distance measure. Also, it is “more stable” in terms of the values of distance that the algorithm spits out. The distance calculation is as follows (adapted from the site): In the equation, C is the RGB vector of a pixel, the subscript number indicates which pixel we are referring to (comparing pixel 1 and pixel 2) and the subscript letter is the color channel of the pixel. The calculation first makes an average of the red values between the two pixels. Then, we calculate the difference between each color component of the pixels. The final distance is basically a weighted Euclidean distance with the weights being determined differently for each color component. We can adapt the code from the site that leverages some bitwise operation hacks into Python. For reference, here is the C++ function definition from the site: To keep computations fast, I will forego the square root at the end without breaking the distance calculation. This is because the square root is a monotonically increasing function for all positive numbers. Since values in the square root of ΔC are always positive, all we need to compare to get the closest pixel is the summation term within the square root. Also, since we are using dask, we will need to code the vectorizations too. Note that we typecast into np.long type so we can deal with the squares of ΔR, ΔG, and ΔB. I hope the code is self-explanatory if you can make the connections to the C++ code above and the original equations. The gist of it is that we vectorized the difference calculation between each color channel and also implemented the bitwise operations per the original code. What do the outputs look like? That did the trick for Gozha’s flower, a more reddish hue is now transferred instead of that bland tan-brown color that the Euclidean distance gave. Otherwise, the colors of Rabada’s seaside and Roe’s mountains are about the same, there are very subtle differences in color tones but nothing sticks out. I’ll leave you with this: our visual perception of color is definitely different to the data structures that we have chosen to embody them. That is it from me on palette transfer. I enjoy doing fun weekend projects like these a documenting them thoroughly. This palette transfer exercise has given me a chance to explore weird ideas I have in a programmatic way and also to discover new tools and learn new skills. My main future exploration would be is how complex the digital representation of colors are. Color spaces are very intriguing and there is a lot that I don’t yet fully understand. Nevertheless, I hope you enjoyed reading it as much as I did writing it. Until next time!
[ { "code": null, "e": 685, "s": 171, "text": "A few weekends ago, I wanted to brush up on my clustering techniques. I recall —from an image processing class back in college — that you can reduce the number of unique colors in an image down to a few colors while keeping the important ones. This is achieved by doing k-means clustering on the RGB values of the pixels in an image. The number of colors that you want in your reduced palette is the k value in k-means clustering; in other words the number of cluster centers in RGB space that your image inhabit." }, { "code": null, "e": 1208, "s": 685, "text": "This was particularly useful in the old days of video game graphics if an image needed to be rendered in a device with limited memory. By reducing the palette, you can conform to the limited color palette of PAL or SECAM, etc. since only 8 bits or 16 bits are allocated to the entire color palette (in contrast to the 24-bit RGB that is ubiquitous now). Today’s use? Well, if you’re particularly nostalgic about the artistry of low-bit graphics or building something to display on a LED matrix, this could be the use case." }, { "code": null, "e": 1705, "s": 1208, "text": "While playing around, I casually thought: “what if we transferred the reduced palette of one image into another?” It’s a seemingly innocuous question that expanded my knowledge of colors and parallel-processing toolbox. In this article, I’m going to explain how this artificial task of palette transfer can be done and how to take it further. Get ready to use tools from numpy, scikit-learn and dask. Look for the code on a prepared Colab notebook containing everything explained in this article." }, { "code": null, "e": 2110, "s": 1705, "text": "So let’s get some definitions in place before anything else. What I mean by palette is the set of RGB pixel values in an image. This number is usually in the tens of thousands for a small photographic image. Palette reduction is the algorithmic selection of a subset of the original palette of an image and mapping of all pixel values in the original palette to the closest values in the reduced palette." }, { "code": null, "e": 2615, "s": 2110, "text": "The code for this is relatively straightforward: run k-means clustering on all the pixels of an image and the resulting cluster centers are your reduced palette. We have to be careful as the cluster centers are not np.uint8 type but rather np.float64. When we call kmn.predict(src), the output values are all floats. The simple solution to this is just to round up these values to the nearest integer and cast it to np.uint8 type before displaying it. Here's what a reduced palette class could look like:" }, { "code": null, "e": 3382, "s": 2615, "text": "The class definition is pretty basic: it contains the number of colors in the reduced palette and a sklearn.clustering.KMeans instance. First, we have a preprocessing function that makes sure the image is shaped up (pun intended) for the KMeans operations. The reshaping reforms the 3-dimensional matrix of W×H×C into a 2-dimensional matrix of WH×C where W is the width of the image, H is the height of the image and C is the three RGB color channels. Then, the KMeansReducedPalette.fit() function works as a wrapper to the KMeans.fit() function that creates the cluster centers in RGB space. Finally, the recolor() function transforms the original palette of an image into the reduced palette of the fitted image. Let's look at some examples of a palette reduction:" }, { "code": null, "e": 3757, "s": 3382, "text": "Pretty, right? Even with the reduced palette, there is still a lot of charm to the image. Says a lot about the photographer’s chops, I’d say. One way to visualize these clusters is just to scatter plot them. Our data here is the unique RGB values of the image which is in 3-dimensions: one dimension for each color channel. This lends itself quite well to a 3D scatter plot:" }, { "code": null, "e": 4118, "s": 3757, "text": "At 8 colors, there are relatively loose clusters but comparing the clusters colored by the centroid in comparison to the original colors, I think the clusters are pretty good. The colors do not diverge far although there are some light greens that are being cast grayish-green. With more points, the clusters would be more representative of the salient colors." }, { "code": null, "e": 4386, "s": 4118, "text": "Now, let’s tackle the second problem: transferring one image’s reduced palette into another. Turns out, this is relatively easy, we don’t need any further programming aside from passing a target image into the palette recolor() function. Let's look at some transfers:" }, { "code": null, "e": 4998, "s": 4386, "text": "What happens here is that the distance of each pixel in the new image is measured against the reduced palette (i.e. the cluster centers). The RGB values of the transferring pixel are then swapped with the closest cluster center in the palette. This is why in situations where the source image doesn’t have many colors, or the reduced palette is too small, we get some cartoon-like effects in the overall image. It’s because the colors in the transferring image don’t get a good enough color to swap with but instead takes the nearest cluster center despite it being very distant to the transferring pixel value." }, { "code": null, "e": 5702, "s": 4998, "text": "Let’s experiment a bit with this before moving on. We did clustering based on all the pixels in the image but in reality, not all the pixels are unique. Chances are, around a particular region of an image, there are maybe tens or hundreds of the same pixel RGB value (particularly for static backgrounds, skies, and the like). Naturally, this will skew cluster centers around more abundant colors in the image; these are the colors that would immediately pop in the original image making them visually salient. For fun, let’s hack around and do clustering only on the unique pixels in the image (instead of all the pixels) and give them each equal opportunity. We will create a new class to enable this:" }, { "code": null, "e": 6251, "s": 5702, "text": "The new class inherits the KMeansReducedPalette class which makes things much easier down the line: any further functionality that we add to the KMeansReducedPalette will be included in the UniqueKMeansReducedPalette class. The fit() function is overridden to fit the palette onto the set of unique pixels in the image. This doesn't add that much more to the overall computation since k-means clustering takes O(nk) time which is more expensive than finding unique pixels which only takes O(n) for an image with n pixels. Let's compare the results:" }, { "code": null, "e": 6463, "s": 6251, "text": "From afar, there are very small differences: there seems to be about the same distribution of colors in the reduced palettes which can be attributed to the initial conditions of the k-means clustering algorithm." }, { "code": null, "e": 6951, "s": 6463, "text": "To my eyes, there is a subtle difference in the quality of the colors. Clustering on the entire image resulted in a slightly more saturated reduced palette in comparison to the clustering of the unique pixels which is more muted. There is subtly more contrast in the top row compared to the bottom rows. I attribute this to the result of clustering in the space of unique colors: essentially averaging the pixel values surrounding a locus without weighing colors that are more prevalent." }, { "code": null, "e": 7313, "s": 6951, "text": "We could go into a numerical analysis into color metrics to verify this (which I did, endlessly) but that would stray too far from the original intent of this article which is just to experiment with palette transfers so I will leave this as an exercise to the courageous among you. Here are some resources that I read through: color vision, chroma calculation." }, { "code": null, "e": 7953, "s": 7313, "text": "Let’s revisit what k-means clustering results in. After clustering, we are provided with k cluster centers which determine the label of other pixels surrounding it. If a point is in proximity to one centroid in comparison to all other centroids, the point is grouped into that centroid. Essentially, this creates k partitions in the data space; the boundaries of which can be visualized using a Voronoi diagram. In the scatter plot earlier, we can partially see the boundaries of the partitioning in 3D space. Since plotting a 3D Voronoi diagram is difficult, let’s turn to PCA and reduce the space to 2D and plot the Voronoi tessellation." }, { "code": null, "e": 8319, "s": 7953, "text": "What is clear from the plot is that the partitions are 2D geometric polygons. In the original 3D space, these partitions would be 3D polyhedrons. Also, the PCA “lies” about some of the points, especially at the boundaries, as the points have been projected down to a lower dimension (hence losing information). Try not to scrutinize the 2D Voronoi diagram too hard." }, { "code": null, "e": 8681, "s": 8319, "text": "Knowing the boundaries, we can randomly select RGB values within the partition as the recoloring of our new image rather than depending solely on the centroid’s RGB value. This gives us more variety to recolor our images. As we already have the centroids, we can start there and take small steps to reach random RGB values. This process is called a random walk." }, { "code": null, "e": 8915, "s": 8681, "text": "Let’s understand one variation of a random walk which is to move by 1 intensity unit in any RGB direction. This random walk can potentially explore the entirety of the 16,777,216 colors (if you take enough steps). Let’s code this up:" }, { "code": null, "e": 9272, "s": 8915, "text": "The random_walk_recolor() function takes an image and the maximum number of steps to walk away from the cluster center. First, we recolor pixels as we did in the recolor() function which is stored as the starting points (start). Then we initialize a difference array (diff) which will determine the distance from the starting points for each color channel." }, { "code": null, "e": 9541, "s": 9272, "text": "Then we loop up to the max number of steps we want to take and take a walk of 1 unit in a single channel randomly. This is stored in walk: we randomly index a 3x3 identity matrix using np.eye() andnp.random.randint() for each pixel. For example an image with 9 pixels:" }, { "code": null, "e": 9731, "s": 9541, "text": "walk = [[ 0, 0, 1], [ 0, 0, 1], [ 1, 0, 0], [ 0, 1, 0], [ 0, 0, 1], [ 0, 1, 0], [ 1, 0, 0], [ 1, 0, 0], [ 1, 0, 0]]" }, { "code": null, "e": 9916, "s": 9731, "text": "Then we need to randomly select the sign of the walk (either in a positive or negative direction) using np.random.choice() on the set {-1, 1} which then transforms the walk array into:" }, { "code": null, "e": 10088, "s": 9916, "text": "walk = [[ 0, 0, 1], [ 0, 0,-1], [-1, 0, 0], [ 0,-1, 0], [ 0, 0, 1], [ 0,-1, 0], [ 1, 0, 0], [-1, 0, 0], [-1, 0, 0]]" }, { "code": null, "e": 10381, "s": 10088, "text": "Finally, we add the walk into the diff array. If we repeat this enough times, we get some random distribution of steps away from the cluster centers that is at most the maximum number of steps that we desire. The final random walk diff might be something like so for a maximum step size of 3:" }, { "code": null, "e": 10553, "s": 10381, "text": "walk = [[ 0, 0, 1], [ 0, 0,-2], [-1, 1, 0], [ 0,-1,-1], [ 0, 0, 3], [ 0,-1, 0], [ 2, 0, 1], [ 0, 0, 0], [-1,-1, 1]]" }, { "code": null, "e": 10991, "s": 10553, "text": "Due to the randomness of random walk, we might not even move away from the cluster center; this is highly unlikely for a large step size though. The final recoloring is simply the starting points of the k-means recoloring plus the walk. How does a recoloring of different step values look like with a 32-color palette on a different transferring image? For this example, I will transfer the palette of Rabada’s seaside to Gozha’s flower." }, { "code": null, "e": 11169, "s": 10991, "text": "Well, looks like we just applied some noise to it but we maintain the general transfer. The noise does get rather overwhelming at very high distances. But it’s cool nonetheless." }, { "code": null, "e": 11580, "s": 11169, "text": "The first random walk variant is not guaranteed to visit the unique pixels we have in the original image. In fact, it may even transcend the boundaries of the partitioning that we mentioned earlier. What if we instead wanted to only walk around the neighboring pixels to the cluster center? Also, we would want to stay within a partition; we don’t want to be wandering around the wrong neighborhood now, do we?" }, { "code": null, "e": 11933, "s": 11580, "text": "To find a random pixel that neighbors a centroid, we would need to calculate the distance of each of the pixels in a cluster to the centroid and randomly pick the closest neighbors up to some max walking step. One optimization we can make in this particular scenario is to precalculate these distances as they will never change once clustering is done." }, { "code": null, "e": 12214, "s": 11933, "text": "The strategy here is to perform all distance calculations for all pixels within each cluster to its nearest centroid during the fit() stage, sort the pixels based on their distance to the centroid in ascending order, and store it so it can be used later. Here's the code for that:" }, { "code": null, "e": 12712, "s": 12214, "text": "What this does is loop through the number of clusters in the palette and store the distances for each pixel to the cluster center. First, we get all the pixels from the original image that is in the current cluster (pixels_ci) and calculate the Euclidean distance to the cluster center (distances_ci). Then we use np.argsort() to get the sorted indices for the distances and then use it to index pixels_ci. Now we are just left with a matrix of pixels in ascending order of distance down the rows." }, { "code": null, "e": 12997, "s": 12712, "text": "To do a random walk, we just select a random number up to the maximum index value (the random number represents the number of steps). We would also need to make sure that the index does not exceed the size of the cluster. Here’s the code to recolor with this neighborhood random walk:" }, { "code": null, "e": 13588, "s": 12997, "text": "The code is relatively simple: we first recolor as we would for the other random walk and then iterate through each cluster and pick a random nearest neighbor. We used np.random.randint() to generate random indices to select the nearest neighbor. Since the random function is maxed at the max_steps, we won't explore beyond the neighbor that is ranked below the max_steps value. Additionally, setting the maximum random number to the minimum value between n_neighbors and max_steps ensures that you are within the confines of the neighborhood. The resulting random walks are as shown below:" }, { "code": null, "e": 13884, "s": 13588, "text": "The noise is a lot more subtle and unnoticeable in the lower distances. The “semantic” of the noise also more sensible: it doesn’t stray too far away from what the original pixel is meant to represent. It’s almost as if you got a photo from a DSLR with a bad sensor or some high ISO value. Nice!" }, { "code": null, "e": 14357, "s": 13884, "text": "All the techniques we’ve seen reduces the palette before making a transfer. Arguably, this is a much easier transfer to make as we only need to compare n pixels with k cluster centers. What if instead, we wanted to do a palette transfer of the all unique pixels? Well, if we assumed we had an equal palette size in the source image and the transferring image, we will need to do an O(n2) comparison to find the nearest pixel of the transferring image and the source image." }, { "code": null, "e": 14739, "s": 14357, "text": "This is problematic: our 320 by 480 pixels working images have an order of 105 unique pixels. A pairwise comparison would yield a matrix that is in the order of (105)2 or 1010 during the computation. Clearly, this cannot fit into memory unless you have a massive amount of memory (and most commodity computers don’t). We could go with looping but Python loops are notoriously slow." }, { "code": null, "e": 15355, "s": 14739, "text": "An ideal middle ground can be achieved if we deployed some form of vectorized computation (which is faster than loops) along with array chunking. Chunking divides a large vectorized computation into smaller manageable computations and collects the pieces to form the final output array. The library dask is a popular implementation in Python that will allow us to this while keeping the numpy syntax flavor in the code. dask enables parallelization too, which means we can defer these computations potentially to different machines or completely exploit all the cores of a computer. Here's what the code looks like:" }, { "code": null, "e": 15903, "s": 15355, "text": "The entire palette transfer class has a very basic constructor. The constructor requires a chunk size value (defaulted at 1024). This trades off computation memory and parallelization in a small computer but you can adjust to larger values if you have more memory. The fitting step just stores all the unique pixels in an image. We only take the unique pixels in the source image to minimize computation since we can map all pixels in the transferring image to a subset of the source pixels. This mapping will be created when we perform recolor()." }, { "code": null, "e": 16254, "s": 15903, "text": "The meat of the class is the recolor() function. First, we preprocess the transferring image and collect all the unique pixels. Then we create a dask.array.core.Array object for the unique pixels in the source image and the transferring image. The transferring image is reshaped to a 3D array for vectorization of the pairwise difference calculation." }, { "code": null, "e": 16506, "s": 16254, "text": "Let’s pause here and understand the computational burden that we are bearing. dask has a feature of visualizing the memory allocated for a computation step in a notebook environment. If you place the following code for a source and transferring image:" }, { "code": null, "e": 16573, "s": 16506, "text": "We get the following images displayed in the notebook output cell:" }, { "code": null, "e": 17054, "s": 16573, "text": "Clearly, the source and transferring dask array of unique pixels occupy very little memory. However, the moment, we execute the pairwise difference, we would need to allocate 77.29 GB of memory. In a traditional NumPy setting, this would either crash or NumPy will yield an error message saying it cannot allocate that much memory. This is when dask shines for its chunking capabilities to enable the computation of such massive arrays without actually allocating all that memory." }, { "code": null, "e": 17414, "s": 17054, "text": "Ultimately, we don’t need the pairwise distances, we only need the transferring pixels that has the smallest distance to the source pixels. Returning back to the code, we perform the Euclidean distance calculation and only keep the index of the transferring pixel which has the smallest distance to the source pixels, thus leaving a much smaller output array." }, { "code": null, "e": 17978, "s": 17414, "text": "To actually run the computation, we must call idxs_da.compute() and we will make use of the built-in ProgressBar() that comes with dask to display the progress of the calculation. Once we have the indices calculated, we create a dictionary mapping from one RGB source pixel to the closest RGB transferring pixel. Python dictionaries use hashing which means that lookups are very fast (theoretically, it takes constant time). Finally, to transfer the pixels, we loop over all pixels in the transferring image and use the pixel mapping to swap the RGB pixel values." }, { "code": null, "e": 18099, "s": 17978, "text": "Let’s view some of the transfers! This time I will use Ito’s flowers and transfer the palette to the rest of the images." }, { "code": null, "e": 18568, "s": 18099, "text": "Beautiful outputs. The transferred images have a more natural coloring, less blockiness, and look very similar to their originals. While doing this transfer, I couldn’t help but notice that Gozha’s flower really could’ve had some better transfers. There are definitely some pinks or reddish hues in Ito’s flower that would’ve been better for the transfer but perhaps was just too far away. What I did not realize was the weakness of our method: the Euclidean distance." }, { "code": null, "e": 19021, "s": 18568, "text": "Here’s the problem: the Euclidean distance assumes that colors are distributed equally around a 255 by 255 by 255 3D cube. The distances between those points would determine how far the colors were from one another. However, perceptually, we perceive the distances differently. It’s a very profound question to ask “how far is one red hue to another?”, but it suffices to say that the Euclidean distance does not do our differential perception justice." }, { "code": null, "e": 19625, "s": 19021, "text": "So I went scouring the web for an answer for a distance measure that is simple to compute and yet does the job to some extent. This site details the calculation using RGB space for a more “correct” perceptual color distance. I’ll leave the discourse to the site itself but in summary, the author compromises between converting into another color space (like YUV or CIELAB) and considered correctional factors that would affect the distance measure. Also, it is “more stable” in terms of the values of distance that the algorithm spits out. The distance calculation is as follows (adapted from the site):" }, { "code": null, "e": 20122, "s": 19625, "text": "In the equation, C is the RGB vector of a pixel, the subscript number indicates which pixel we are referring to (comparing pixel 1 and pixel 2) and the subscript letter is the color channel of the pixel. The calculation first makes an average of the red values between the two pixels. Then, we calculate the difference between each color component of the pixels. The final distance is basically a weighted Euclidean distance with the weights being determined differently for each color component." }, { "code": null, "e": 20281, "s": 20122, "text": "We can adapt the code from the site that leverages some bitwise operation hacks into Python. For reference, here is the C++ function definition from the site:" }, { "code": null, "e": 20809, "s": 20281, "text": "To keep computations fast, I will forego the square root at the end without breaking the distance calculation. This is because the square root is a monotonically increasing function for all positive numbers. Since values in the square root of ΔC are always positive, all we need to compare to get the closest pixel is the summation term within the square root. Also, since we are using dask, we will need to code the vectorizations too. Note that we typecast into np.long type so we can deal with the squares of ΔR, ΔG, and ΔB." }, { "code": null, "e": 21116, "s": 20809, "text": "I hope the code is self-explanatory if you can make the connections to the C++ code above and the original equations. The gist of it is that we vectorized the difference calculation between each color channel and also implemented the bitwise operations per the original code. What do the outputs look like?" }, { "code": null, "e": 21560, "s": 21116, "text": "That did the trick for Gozha’s flower, a more reddish hue is now transferred instead of that bland tan-brown color that the Euclidean distance gave. Otherwise, the colors of Rabada’s seaside and Roe’s mountains are about the same, there are very subtle differences in color tones but nothing sticks out. I’ll leave you with this: our visual perception of color is definitely different to the data structures that we have chosen to embody them." }, { "code": null, "e": 21835, "s": 21560, "text": "That is it from me on palette transfer. I enjoy doing fun weekend projects like these a documenting them thoroughly. This palette transfer exercise has given me a chance to explore weird ideas I have in a programmatic way and also to discover new tools and learn new skills." } ]
Access Control Lists(ACL) in Linux - GeeksforGeeks
02 May, 2018 What is ACL ?Access control list (ACL) provides an additional, more flexible permission mechanism for file systems. It is designed to assist with UNIX file permissions. ACL allows you to give permissions for any user or group to any disc resource. Use of ACL :Think of a scenario in which a particular user is not a member of group created by you but still you want to give some read or write access, how can you do it without making user a member of group, here comes in picture Access Control Lists, ACL helps us to do this trick. Basically, ACLs are used to make a flexible permission mechanism in Linux. From Linux man pages, ACLs are used to define more fine-grained discretionary access rights for files and directories. setfacl and getfacl are used for setting up ACL and showing ACL respectively. For example : getfacl test/declarations.h Output: # file: test/declarations.h # owner: mandeep # group: mandeep user::rw- group::rw- other::r-- List of commands for setting up ACL : 1) To add permission for user setfacl -m "u:user:permissions" /path/to/file 2) To add permissions for a group setfacl -m "g:group:permissions" /path/to/file 3) To allow all files or directories to inherit ACL entries from the directory it is within setfacl -dm "entry" /path/to/dir 4) To remove a specific entry setfacl -x "entry" /path/to/file 5) To remove all entries setfacl -b path/to/file For example : setfacl -m u:mandeep:rwx test/declarations.h Modifying ACL using setfacl :To add permissions for a user (user is either the user name or ID): # setfacl -m "u:user:permissions" To add permissions for a group (group is either the group name or ID): # setfacl -m "g:group:permissions" To allow all files or directories to inherit ACL entries from the directory it is within: # setfacl -dm "entry" Example : setfacl -m u:mandeep:r-x test/declarations.h See below image for output : setfacl and getfacl View ACL :To show permissions : # getfacl filename Observe the difference between output of getfacl command before and after setting up ACL permissions using setfacl command.There is one extra line added for user mandeep which is highlighted in image above. Output: change permissions The above command change permissions from rwx to r-x Remove ACL :If you want to remove the set ACL permissions, use setfacl command with -b option.For example : remove set permissions If you compare output of getfacl command before and after using setfacl command with -b option, you can observe that there is no particular entry for user mandeep in later output. You can also check if there are any extra permissions set through ACL using ls command. check set acl with ls Observe the first command output in image, there is extra “+” sign after the permissions like -rw-rwxr–+, this indicates there are extra ACL permissions set which you can check by getfacl command. Using Default ACL :The default ACL is a specific type of permission assigned to a directory, that doesn’t change the permissions of the directory itself, but makes so that specified ACLs are set by default on all the files created inside of it. Let’s demonstrate it : first we are going to create a directory and assign default ACL to it by using the -d option: $ mkdir test && setfacl -d -m u:dummy:rw test Articles Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Time Complexity and Space Complexity Docker - COPY Instruction Time complexities of different data structures Difference between Min Heap and Max Heap SQL | Date functions Difference between Class and Object Implementation of LinkedList in Javascript Deploy Python Flask App on Heroku How compare() method works in Java SQL | CREATE
[ { "code": null, "e": 24029, "s": 24001, "text": "\n02 May, 2018" }, { "code": null, "e": 24277, "s": 24029, "text": "What is ACL ?Access control list (ACL) provides an additional, more flexible permission mechanism for file systems. It is designed to assist with UNIX file permissions. ACL allows you to give permissions for any user or group to any disc resource." }, { "code": null, "e": 24562, "s": 24277, "text": "Use of ACL :Think of a scenario in which a particular user is not a member of group created by you but still you want to give some read or write access, how can you do it without making user a member of group, here comes in picture Access Control Lists, ACL helps us to do this trick." }, { "code": null, "e": 24637, "s": 24562, "text": "Basically, ACLs are used to make a flexible permission mechanism in Linux." }, { "code": null, "e": 24756, "s": 24637, "text": "From Linux man pages, ACLs are used to define more fine-grained discretionary access rights for files and directories." }, { "code": null, "e": 24834, "s": 24756, "text": "setfacl and getfacl are used for setting up ACL and showing ACL respectively." }, { "code": null, "e": 24848, "s": 24834, "text": "For example :" }, { "code": null, "e": 24877, "s": 24848, "text": "getfacl test/declarations.h\n" }, { "code": null, "e": 24885, "s": 24877, "text": "Output:" }, { "code": null, "e": 24980, "s": 24885, "text": "# file: test/declarations.h\n# owner: mandeep\n# group: mandeep\nuser::rw-\ngroup::rw-\nother::r--\n" }, { "code": null, "e": 25018, "s": 24980, "text": "List of commands for setting up ACL :" }, { "code": null, "e": 25418, "s": 25018, "text": "1) To add permission for user\nsetfacl -m \"u:user:permissions\" /path/to/file\n\n2) To add permissions for a group\nsetfacl -m \"g:group:permissions\" /path/to/file \n\n3) To allow all files or directories to inherit ACL entries from the directory it is within\nsetfacl -dm \"entry\" /path/to/dir\n\n4) To remove a specific entry\nsetfacl -x \"entry\" /path/to/file\n\n5) To remove all entries\nsetfacl -b path/to/file\n" }, { "code": null, "e": 25432, "s": 25418, "text": "For example :" }, { "code": null, "e": 25478, "s": 25432, "text": "setfacl -m u:mandeep:rwx test/declarations.h\n" }, { "code": null, "e": 25575, "s": 25478, "text": "Modifying ACL using setfacl :To add permissions for a user (user is either the user name or ID):" }, { "code": null, "e": 25611, "s": 25575, "text": "# setfacl -m \"u:user:permissions\" \n" }, { "code": null, "e": 25682, "s": 25611, "text": "To add permissions for a group (group is either the group name or ID):" }, { "code": null, "e": 25719, "s": 25682, "text": "# setfacl -m \"g:group:permissions\" \n" }, { "code": null, "e": 25809, "s": 25719, "text": "To allow all files or directories to inherit ACL entries from the directory it is within:" }, { "code": null, "e": 25833, "s": 25809, "text": "# setfacl -dm \"entry\" \n" }, { "code": null, "e": 25843, "s": 25833, "text": "Example :" }, { "code": null, "e": 25889, "s": 25843, "text": "setfacl -m u:mandeep:r-x test/declarations.h\n" }, { "code": null, "e": 25918, "s": 25889, "text": "See below image for output :" }, { "code": null, "e": 25938, "s": 25918, "text": "setfacl and getfacl" }, { "code": null, "e": 25970, "s": 25938, "text": "View ACL :To show permissions :" }, { "code": null, "e": 25990, "s": 25970, "text": "# getfacl filename\n" }, { "code": null, "e": 26197, "s": 25990, "text": "Observe the difference between output of getfacl command before and after setting up ACL permissions using setfacl command.There is one extra line added for user mandeep which is highlighted in image above." }, { "code": null, "e": 26205, "s": 26197, "text": "Output:" }, { "code": null, "e": 26224, "s": 26205, "text": "change permissions" }, { "code": null, "e": 26277, "s": 26224, "text": "The above command change permissions from rwx to r-x" }, { "code": null, "e": 26385, "s": 26277, "text": "Remove ACL :If you want to remove the set ACL permissions, use setfacl command with -b option.For example :" }, { "code": null, "e": 26408, "s": 26385, "text": "remove set permissions" }, { "code": null, "e": 26588, "s": 26408, "text": "If you compare output of getfacl command before and after using setfacl command with -b option, you can observe that there is no particular entry for user mandeep in later output." }, { "code": null, "e": 26676, "s": 26588, "text": "You can also check if there are any extra permissions set through ACL using ls command." }, { "code": null, "e": 26698, "s": 26676, "text": "check set acl with ls" }, { "code": null, "e": 26895, "s": 26698, "text": "Observe the first command output in image, there is extra “+” sign after the permissions like -rw-rwxr–+, this indicates there are extra ACL permissions set which you can check by getfacl command." }, { "code": null, "e": 27257, "s": 26895, "text": "Using Default ACL :The default ACL is a specific type of permission assigned to a directory, that doesn’t change the permissions of the directory itself, but makes so that specified ACLs are set by default on all the files created inside of it. Let’s demonstrate it : first we are going to create a directory and assign default ACL to it by using the -d option:" }, { "code": null, "e": 27304, "s": 27257, "text": "$ mkdir test && setfacl -d -m u:dummy:rw test\n" }, { "code": null, "e": 27313, "s": 27304, "text": "Articles" }, { "code": null, "e": 27411, "s": 27313, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27420, "s": 27411, "text": "Comments" }, { "code": null, "e": 27433, "s": 27420, "text": "Old Comments" }, { "code": null, "e": 27470, "s": 27433, "text": "Time Complexity and Space Complexity" }, { "code": null, "e": 27496, "s": 27470, "text": "Docker - COPY Instruction" }, { "code": null, "e": 27543, "s": 27496, "text": "Time complexities of different data structures" }, { "code": null, "e": 27584, "s": 27543, "text": "Difference between Min Heap and Max Heap" }, { "code": null, "e": 27605, "s": 27584, "text": "SQL | Date functions" }, { "code": null, "e": 27641, "s": 27605, "text": "Difference between Class and Object" }, { "code": null, "e": 27684, "s": 27641, "text": "Implementation of LinkedList in Javascript" }, { "code": null, "e": 27718, "s": 27684, "text": "Deploy Python Flask App on Heroku" }, { "code": null, "e": 27753, "s": 27718, "text": "How compare() method works in Java" } ]
Next Optimal Move in Tic Tac Toe | Practice | GeeksforGeeks
You are given a middle game situation of the game Tic Tac Toe. It is given that it is player "X's" turn and you need to give to most optimal position for the turn. The situation is given as a 3 x 3 character matrix board. '_' refers to the place is empty. 'o' refers that player O marked it in his turn at some time and 'x' refers that player X marked it in his turn at some time. It is player X's turn. Tell him the most optimal solution.(Assume player O played first). Example 1: Input: board = {{o, _, _}, {_, _, _}, {_, _, _}} Output: 1 1 Explaination: Placing a 'x' in the (1, 1) that is the center of the board is the most optimal approach for x. Your Task: You do not need to read input or print anything. Your task is to complete the function findBestMove() which takes board as input parameter and returns the best optimal move in a list where the first one is the row index and the second one is the column index. Expected Time Complexity: O(29) Expected Auxiliary Space: O(1) Constraints: board[i][j] = 'o' / 'x' / '_' 0 trautmannmartonbence19952 days ago a1 0 Partha Sarathi Bhunia This comment was deleted. 0 joya2 years ago joya here reference 0 Soumya Sengupta4 years ago Soumya Sengupta Exhaustive recursive solution----------------------------------------1> Start with each free position and calculate the number of combinations for winning , losing & drawing from this position. (While evaluating this, Play O's turn across all available empty spaces too so that all combinations are covered) 2>Compare the results for all the positions and choose the one which gives the maximum benefit. 0 Aniket4 years ago Aniket Many of the given expected solutions are wrong. The next optimal move isn't concerned with preventing the opposition from winning the game. 0 Kerem Gürbey4 years ago Kerem Gürbey https://uploads.disquscdn.c... I think there is a problem with the expected solution for this case. If the player does not make move on 2,2, then the next player will, and they will win. 0 th y4 years ago th y I'm wondering why the AC rate is more than 20%... Apparently there are many wrong test cases and even the solution suggested in Editorial is problematic in terms of how to take the remaining steps into consideration 0 Pranav Arora5 years ago Pranav Arora http://ide.geeksforgeeks.or... plz help! 0 sdarcius5 years ago sdarcius Lets consider the following case , _ o _o x _x o _ the most optimal solution is 0 2, which is wining case, but the expected out put is 0 0, could you please resolve it? 0 CNatka5 years ago CNatka Incorrect expected answers. Kindly fix the issue.Below is one example -Input:1o x __ o __ _ _ Expected Output : 0 2Correct Output : 2 2 We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 710, "s": 238, "text": "You are given a middle game situation of the game Tic Tac Toe. It is given that it is player \"X's\" turn and you need to give to most optimal position for the turn. The situation is given as a 3 x 3 character matrix board. '_' refers to the place is empty. 'o' refers that player O marked it in his turn at some time and 'x' refers that player X marked it in his turn at some time. It is player X's turn. Tell him the most optimal solution.(Assume player O played first). " }, { "code": null, "e": 721, "s": 710, "text": "Example 1:" }, { "code": null, "e": 928, "s": 721, "text": "Input: board = {{o, _, _}, \n {_, _, _}, \n {_, _, _}}\nOutput: 1 1\nExplaination: Placing a 'x' in the (1, 1) \nthat is the center of the board is the most \noptimal approach for x." }, { "code": null, "e": 1199, "s": 928, "text": "Your Task:\nYou do not need to read input or print anything. Your task is to complete the function findBestMove() which takes board as input parameter and returns the best optimal move in a list where the first one is the row index and the second one is the column index." }, { "code": null, "e": 1262, "s": 1199, "text": "Expected Time Complexity: O(29)\nExpected Auxiliary Space: O(1)" }, { "code": null, "e": 1307, "s": 1262, "text": "Constraints:\nboard[i][j] = 'o' / 'x' / '_' " }, { "code": null, "e": 1309, "s": 1307, "text": "0" }, { "code": null, "e": 1344, "s": 1309, "text": "trautmannmartonbence19952 days ago" }, { "code": null, "e": 1347, "s": 1344, "text": "a1" }, { "code": null, "e": 1349, "s": 1347, "text": "0" }, { "code": null, "e": 1371, "s": 1349, "text": "Partha Sarathi Bhunia" }, { "code": null, "e": 1397, "s": 1371, "text": "This comment was deleted." }, { "code": null, "e": 1399, "s": 1397, "text": "0" }, { "code": null, "e": 1415, "s": 1399, "text": "joya2 years ago" }, { "code": null, "e": 1420, "s": 1415, "text": "joya" }, { "code": null, "e": 1436, "s": 1420, "text": "here reference " }, { "code": null, "e": 1438, "s": 1436, "text": "0" }, { "code": null, "e": 1465, "s": 1438, "text": "Soumya Sengupta4 years ago" }, { "code": null, "e": 1481, "s": 1465, "text": "Soumya Sengupta" }, { "code": null, "e": 1679, "s": 1481, "text": "Exhaustive recursive solution----------------------------------------1> Start with each free position and calculate the number of combinations for winning , losing & drawing from this position." }, { "code": null, "e": 1797, "s": 1679, "text": " (While evaluating this, Play O's turn across all available empty spaces too so that all combinations are covered)" }, { "code": null, "e": 1893, "s": 1797, "text": "2>Compare the results for all the positions and choose the one which gives the maximum benefit." }, { "code": null, "e": 1895, "s": 1893, "text": "0" }, { "code": null, "e": 1913, "s": 1895, "text": "Aniket4 years ago" }, { "code": null, "e": 1920, "s": 1913, "text": "Aniket" }, { "code": null, "e": 2060, "s": 1920, "text": "Many of the given expected solutions are wrong. The next optimal move isn't concerned with preventing the opposition from winning the game." }, { "code": null, "e": 2062, "s": 2060, "text": "0" }, { "code": null, "e": 2087, "s": 2062, "text": "Kerem Gürbey4 years ago" }, { "code": null, "e": 2101, "s": 2087, "text": "Kerem Gürbey" }, { "code": null, "e": 2132, "s": 2101, "text": "https://uploads.disquscdn.c..." }, { "code": null, "e": 2288, "s": 2132, "text": "I think there is a problem with the expected solution for this case. If the player does not make move on 2,2, then the next player will, and they will win." }, { "code": null, "e": 2290, "s": 2288, "text": "0" }, { "code": null, "e": 2306, "s": 2290, "text": "th y4 years ago" }, { "code": null, "e": 2311, "s": 2306, "text": "th y" }, { "code": null, "e": 2527, "s": 2311, "text": "I'm wondering why the AC rate is more than 20%... Apparently there are many wrong test cases and even the solution suggested in Editorial is problematic in terms of how to take the remaining steps into consideration" }, { "code": null, "e": 2529, "s": 2527, "text": "0" }, { "code": null, "e": 2553, "s": 2529, "text": "Pranav Arora5 years ago" }, { "code": null, "e": 2566, "s": 2553, "text": "Pranav Arora" }, { "code": null, "e": 2607, "s": 2566, "text": "http://ide.geeksforgeeks.or... plz help!" }, { "code": null, "e": 2609, "s": 2607, "text": "0" }, { "code": null, "e": 2629, "s": 2609, "text": "sdarcius5 years ago" }, { "code": null, "e": 2638, "s": 2629, "text": "sdarcius" }, { "code": null, "e": 2808, "s": 2638, "text": "Lets consider the following case , _ o _o x _x o _ the most optimal solution is 0 2, which is wining case, but the expected out put is 0 0, could you please resolve it?" }, { "code": null, "e": 2810, "s": 2808, "text": "0" }, { "code": null, "e": 2828, "s": 2810, "text": "CNatka5 years ago" }, { "code": null, "e": 2835, "s": 2828, "text": "CNatka" }, { "code": null, "e": 2929, "s": 2835, "text": "Incorrect expected answers. Kindly fix the issue.Below is one example -Input:1o x __ o __ _ _" }, { "code": null, "e": 2974, "s": 2929, "text": "Expected Output : 0 2Correct Output : 2 2" }, { "code": null, "e": 3120, "s": 2974, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 3156, "s": 3120, "text": " Login to access your submissions. " }, { "code": null, "e": 3166, "s": 3156, "text": "\nProblem\n" }, { "code": null, "e": 3176, "s": 3166, "text": "\nContest\n" }, { "code": null, "e": 3239, "s": 3176, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 3387, "s": 3239, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 3595, "s": 3387, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 3701, "s": 3595, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Materialize - DatePicker
The following example demonstrates Materialize DatePicker control. materialize_datepicker.htm <html> <head> <title>The Materialize Range Example</title> <meta name = "viewport" content = "width = device-width, initial-scale = 1"> <link rel = "stylesheet" href = "https://fonts.googleapis.com/icon?family=Material+Icons"> <link rel = "stylesheet" href = "https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/css/materialize.min.css"> <script type = "text/javascript" src = "https://code.jquery.com/jquery-2.1.1.min.js">></script> <script src = "https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/js/materialize.min.js"> </script> </head> <body class = "container"> <div class = "row"> <form class = "col s12"> <div class = "row"> <label>Materialize DatePicker</label> <input type = "date" class = "datepicker" /> </div> </form> </div> </body> </html> Verify the result. Print Add Notes Bookmark this page
[ { "code": null, "e": 2254, "s": 2187, "text": "The following example demonstrates Materialize DatePicker control." }, { "code": null, "e": 2281, "s": 2254, "text": "materialize_datepicker.htm" }, { "code": null, "e": 3271, "s": 2281, "text": "<html>\n <head>\n <title>The Materialize Range Example</title>\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1\"> \n <link rel = \"stylesheet\"\n href = \"https://fonts.googleapis.com/icon?family=Material+Icons\">\n <link rel = \"stylesheet\"\n href = \"https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/css/materialize.min.css\">\n <script type = \"text/javascript\"\n src = \"https://code.jquery.com/jquery-2.1.1.min.js\">></script> \n <script src = \"https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/js/materialize.min.js\">\n </script> \n </head>\n <body class = \"container\"> \n <div class = \"row\">\n <form class = \"col s12\">\n <div class = \"row\"> <label>Materialize DatePicker</label> \n <input type = \"date\" class = \"datepicker\" /> \n </div> \n </form> \n </div>\n </body> \n</html>" }, { "code": null, "e": 3290, "s": 3271, "text": "Verify the result." }, { "code": null, "e": 3297, "s": 3290, "text": " Print" }, { "code": null, "e": 3308, "s": 3297, "text": " Add Notes" } ]
How to use TypeScript to build Node.js API with Express ? - GeeksforGeeks
23 Jan, 2022 In this article, we will discuss how to create an Express Route and API in TypeScript and help us with the default type checking mechanism. And we will create some Fake API endpoints with the help of TypeScript with ExpressJS configuration and understand how to use TypeScript in our ExpressJS project. TypeScript is a superset of JavaScript with some additional features that JavaScript doesn’t have such as type notation and static type changing or using es6’s code in older codebases. Typescript provides all the features. If you want to create an API service in typescript use of express with NodeJS, you must first set up your project with typescript. If you have no idea about how to set up express in typescript refer to this article. I hope you have set up your express project with typescript using the above article now we will start to create our first API in Typescript. Basic knowledge about NodeJs. Basic knowledge about Express Js and their routes management techniques. Basic knowledge about TypeScript and its uses. Approach: Setup directory Structure according to the above-mentioned article. Initiate ExpressJs with TypeScript. Will create two fake API to create a user and get user data with ExpressJs TypeScript configuration. See the final codebase file. Will test our API endpoints with the help of the Postman API Testing Tool and see our API output. Step 1: If you are set up the project in the use of the above article your directory looks like this. Step 2: Open the index.ts file and write the below code. First of all, create an ExpressJs code in TypeScript and flow the good practices. Filename: index.js Javascript // Import the express with express nameimport express from 'express'; // Initialize the express module with app variableconst app: express.Application = express(); // Define the port for the application is runconst port: number = 3000; // Handle the coming data.app.use(express.json()); // Handle '/', path of the api.app.get('/', (_req, _res): void => { _res.json({ 'name': 'typescitp_api', 'path': '/', 'work': 'search_other_apis' });}); // Server the api endpoints.app.listen(port, (): void => { console.log(`Typescript API server http://localhost:${port}/`);}); Step 3: In this step, we create two API endpoints for creating the user and getting the users’ data. Firstly create a global array to treat as a fake database. Syntax: let fake_db: any = []; Then create a first API endpoint to create the users and store the user data in the fake database. We are working with API endpoint so data are passed through the post method or JSON data format. In the below code, we firstly handle a post request and create a ‘/create’ route the manage or create user API endpoint and after that assign the coming body data to our fake database and return appropriate output. Filename: index.js Javascript // Handle '/create', path for create userapp.post('/create', (_req, _res): void => { // Fetched the user using body data const user: object = _req.body; // Assign the user in fake_db with id as a index fake_db.push(user); _res.json({ "success": true, "data": user });}); After writing all codes lets, move to the test phase and look at what our API makes output. Step 5: Now the final step is to test all the created routes using Postman. If you don’t know about the postman refer to this article. 1. Test ‘/’ root path using postman. The root path working properly, so we are moving to another API endpoint. 2. Test ‘/create’ path in post request using postman. We pass raw JSON data directly. 3. Test ‘/users’ path using postman. abhishek0719kadiyan kashishsoda gabaa406 adnanirshad158 saurabh1990aror JSON NodeJS-Questions Picked TypeScript 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 build a basic CRUD app with Node.js and ReactJS ? How to connect Node.js with React.js ? Mongoose Populate() Method Express.js req.params Property Mongoose find() 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": 24557, "s": 24529, "text": "\n23 Jan, 2022" }, { "code": null, "e": 24860, "s": 24557, "text": "In this article, we will discuss how to create an Express Route and API in TypeScript and help us with the default type checking mechanism. And we will create some Fake API endpoints with the help of TypeScript with ExpressJS configuration and understand how to use TypeScript in our ExpressJS project." }, { "code": null, "e": 25299, "s": 24860, "text": "TypeScript is a superset of JavaScript with some additional features that JavaScript doesn’t have such as type notation and static type changing or using es6’s code in older codebases. Typescript provides all the features. If you want to create an API service in typescript use of express with NodeJS, you must first set up your project with typescript. If you have no idea about how to set up express in typescript refer to this article." }, { "code": null, "e": 25441, "s": 25299, "text": "I hope you have set up your express project with typescript using the above article now we will start to create our first API in Typescript. " }, { "code": null, "e": 25471, "s": 25441, "text": "Basic knowledge about NodeJs." }, { "code": null, "e": 25544, "s": 25471, "text": "Basic knowledge about Express Js and their routes management techniques." }, { "code": null, "e": 25591, "s": 25544, "text": "Basic knowledge about TypeScript and its uses." }, { "code": null, "e": 25934, "s": 25591, "text": "Approach: Setup directory Structure according to the above-mentioned article. Initiate ExpressJs with TypeScript. Will create two fake API to create a user and get user data with ExpressJs TypeScript configuration. See the final codebase file. Will test our API endpoints with the help of the Postman API Testing Tool and see our API output." }, { "code": null, "e": 26036, "s": 25934, "text": "Step 1: If you are set up the project in the use of the above article your directory looks like this." }, { "code": null, "e": 26175, "s": 26036, "text": "Step 2: Open the index.ts file and write the below code. First of all, create an ExpressJs code in TypeScript and flow the good practices." }, { "code": null, "e": 26195, "s": 26175, "text": "Filename: index.js " }, { "code": null, "e": 26206, "s": 26195, "text": "Javascript" }, { "code": "// Import the express with express nameimport express from 'express'; // Initialize the express module with app variableconst app: express.Application = express(); // Define the port for the application is runconst port: number = 3000; // Handle the coming data.app.use(express.json()); // Handle '/', path of the api.app.get('/', (_req, _res): void => { _res.json({ 'name': 'typescitp_api', 'path': '/', 'work': 'search_other_apis' });}); // Server the api endpoints.app.listen(port, (): void => { console.log(`Typescript API server http://localhost:${port}/`);});", "e": 26803, "s": 26206, "text": null }, { "code": null, "e": 26964, "s": 26803, "text": " Step 3: In this step, we create two API endpoints for creating the user and getting the users’ data. Firstly create a global array to treat as a fake database." }, { "code": null, "e": 26973, "s": 26964, "text": "Syntax: " }, { "code": null, "e": 26996, "s": 26973, "text": "let fake_db: any = [];" }, { "code": null, "e": 27408, "s": 26996, "text": "Then create a first API endpoint to create the users and store the user data in the fake database. We are working with API endpoint so data are passed through the post method or JSON data format. In the below code, we firstly handle a post request and create a ‘/create’ route the manage or create user API endpoint and after that assign the coming body data to our fake database and return appropriate output." }, { "code": null, "e": 27427, "s": 27408, "text": "Filename: index.js" }, { "code": null, "e": 27438, "s": 27427, "text": "Javascript" }, { "code": "// Handle '/create', path for create userapp.post('/create', (_req, _res): void => { // Fetched the user using body data const user: object = _req.body; // Assign the user in fake_db with id as a index fake_db.push(user); _res.json({ \"success\": true, \"data\": user });});", "e": 27744, "s": 27438, "text": null }, { "code": null, "e": 27836, "s": 27744, "text": "After writing all codes lets, move to the test phase and look at what our API makes output." }, { "code": null, "e": 27971, "s": 27836, "text": "Step 5: Now the final step is to test all the created routes using Postman. If you don’t know about the postman refer to this article." }, { "code": null, "e": 28008, "s": 27971, "text": "1. Test ‘/’ root path using postman." }, { "code": null, "e": 28082, "s": 28008, "text": "The root path working properly, so we are moving to another API endpoint." }, { "code": null, "e": 28136, "s": 28082, "text": "2. Test ‘/create’ path in post request using postman." }, { "code": null, "e": 28168, "s": 28136, "text": "We pass raw JSON data directly." }, { "code": null, "e": 28205, "s": 28168, "text": "3. Test ‘/users’ path using postman." }, { "code": null, "e": 28225, "s": 28205, "text": "abhishek0719kadiyan" }, { "code": null, "e": 28237, "s": 28225, "text": "kashishsoda" }, { "code": null, "e": 28246, "s": 28237, "text": "gabaa406" }, { "code": null, "e": 28261, "s": 28246, "text": "adnanirshad158" }, { "code": null, "e": 28277, "s": 28261, "text": "saurabh1990aror" }, { "code": null, "e": 28282, "s": 28277, "text": "JSON" }, { "code": null, "e": 28299, "s": 28282, "text": "NodeJS-Questions" }, { "code": null, "e": 28306, "s": 28299, "text": "Picked" }, { "code": null, "e": 28317, "s": 28306, "text": "TypeScript" }, { "code": null, "e": 28325, "s": 28317, "text": "Node.js" }, { "code": null, "e": 28342, "s": 28325, "text": "Web Technologies" }, { "code": null, "e": 28440, "s": 28342, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28449, "s": 28440, "text": "Comments" }, { "code": null, "e": 28462, "s": 28449, "text": "Old Comments" }, { "code": null, "e": 28519, "s": 28462, "text": "How to build a basic CRUD app with Node.js and ReactJS ?" }, { "code": null, "e": 28558, "s": 28519, "text": "How to connect Node.js with React.js ?" }, { "code": null, "e": 28585, "s": 28558, "text": "Mongoose Populate() Method" }, { "code": null, "e": 28616, "s": 28585, "text": "Express.js req.params Property" }, { "code": null, "e": 28641, "s": 28616, "text": "Mongoose find() Function" }, { "code": null, "e": 28697, "s": 28641, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 28759, "s": 28697, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 28802, "s": 28759, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 28852, "s": 28802, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Java program to check palindrome
Palindrome number is a number which remains the same when reversed, for example, 121, 313, 525, etc. Let us now see an example to check palindrome − public class Palindrome { public static void main(String[] args) { int a = 525, revVal = 0, remainder, val; val = a; System.out.println("Number to be checked = "+a); while( a != 0 ) { remainder = a % 10; revVal = revVal * 10 + remainder; a /= 10; } if (val == revVal) System.out.println("Palindrome!"); else System.out.println("Not a palindrome!"); } } Number to be checked = 525 Palindrome! Let us now check for palindrome string such as “aba”, “wow”, etc − public class Demo { public static void main (String[] args) { String str = "ABA"; String strRev = new StringBuffer(str).reverse().toString(); if (str.equals(strRev)) System.out.println("Palindrome!"); else System.out.println("Not a Palindrome!"); } } Palindrome!
[ { "code": null, "e": 1163, "s": 1062, "text": "Palindrome number is a number which remains the same when reversed, for example, 121, 313, 525, etc." }, { "code": null, "e": 1211, "s": 1163, "text": "Let us now see an example to check palindrome −" }, { "code": null, "e": 1657, "s": 1211, "text": "public class Palindrome {\n public static void main(String[] args) {\n int a = 525, revVal = 0, remainder, val;\n val = a;\n System.out.println(\"Number to be checked = \"+a);\n while( a != 0 ) {\n remainder = a % 10;\n revVal = revVal * 10 + remainder;\n a /= 10;\n }\n if (val == revVal)\n System.out.println(\"Palindrome!\");\n else\n System.out.println(\"Not a palindrome!\");\n }\n}" }, { "code": null, "e": 1696, "s": 1657, "text": "Number to be checked = 525\nPalindrome!" }, { "code": null, "e": 1763, "s": 1696, "text": "Let us now check for palindrome string such as “aba”, “wow”, etc −" }, { "code": null, "e": 2062, "s": 1763, "text": "public class Demo {\n public static void main (String[] args) {\n String str = \"ABA\";\n String strRev = new StringBuffer(str).reverse().toString();\n if (str.equals(strRev))\n System.out.println(\"Palindrome!\");\n else\n System.out.println(\"Not a Palindrome!\");\n }\n}" }, { "code": null, "e": 2074, "s": 2062, "text": "Palindrome!" } ]
How to create Message Pop-Ups with Java?
To create Message Pop-ups, use the following JOptionPane − JOptionPane.showMessageDialog We are displaying a tree inside the message pop-ups. The following is an example to create Message Pop-Ups with Java − package my; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JScrollPane; import javax.swing.JTree; import javax.swing.tree.DefaultMutableTreeNode; public class SwingDemo { public static void main(String[] args) throws Exception { JFrame frame = new JFrame("Demo"); DefaultMutableTreeNode node = new DefaultMutableTreeNode("Project"); DefaultMutableTreeNode node1 = new DefaultMutableTreeNode("App"); DefaultMutableTreeNode node2 = new DefaultMutableTreeNode("Website"); DefaultMutableTreeNode node3 = new DefaultMutableTreeNode("WebApp"); node.add(node1); node.add(node2); node.add(node3); DefaultMutableTreeNode one = new DefaultMutableTreeNode("Learning website"); DefaultMutableTreeNode two = new DefaultMutableTreeNode("Business website"); DefaultMutableTreeNode three = new DefaultMutableTreeNode("News publishing website"); DefaultMutableTreeNode four = new DefaultMutableTreeNode("Android app"); DefaultMutableTreeNode five = new DefaultMutableTreeNode("iOS app"); DefaultMutableTreeNode six = new DefaultMutableTreeNode("Editor WebApp"); node1.add(one); node1.add(two); node1.add(three); node2.add(four); node2.add(five); node3.add(six); JTree tree = new JTree(node); frame.add(tree); tree.setVisibleRowCount(8); JOptionPane.showMessageDialog(null, new JScrollPane(tree)); } }
[ { "code": null, "e": 1121, "s": 1062, "text": "To create Message Pop-ups, use the following JOptionPane −" }, { "code": null, "e": 1151, "s": 1121, "text": "JOptionPane.showMessageDialog" }, { "code": null, "e": 1270, "s": 1151, "text": "We are displaying a tree inside the message pop-ups. The following is an example to create Message Pop-Ups with Java −" }, { "code": null, "e": 2735, "s": 1270, "text": "package my;\nimport javax.swing.JFrame;\nimport javax.swing.JOptionPane;\nimport javax.swing.JScrollPane;\nimport javax.swing.JTree;\nimport javax.swing.tree.DefaultMutableTreeNode;\npublic class SwingDemo {\n public static void main(String[] args) throws Exception {\n JFrame frame = new JFrame(\"Demo\");\n DefaultMutableTreeNode node = new DefaultMutableTreeNode(\"Project\");\n DefaultMutableTreeNode node1 = new DefaultMutableTreeNode(\"App\");\n DefaultMutableTreeNode node2 = new DefaultMutableTreeNode(\"Website\");\n DefaultMutableTreeNode node3 = new DefaultMutableTreeNode(\"WebApp\");\n node.add(node1);\n node.add(node2);\n node.add(node3);\n DefaultMutableTreeNode one = new DefaultMutableTreeNode(\"Learning website\");\n DefaultMutableTreeNode two = new DefaultMutableTreeNode(\"Business website\");\n DefaultMutableTreeNode three = new DefaultMutableTreeNode(\"News publishing website\");\n DefaultMutableTreeNode four = new DefaultMutableTreeNode(\"Android app\");\n DefaultMutableTreeNode five = new DefaultMutableTreeNode(\"iOS app\");\n DefaultMutableTreeNode six = new DefaultMutableTreeNode(\"Editor WebApp\");\n node1.add(one);\n node1.add(two);\n node1.add(three);\n node2.add(four);\n node2.add(five);\n node3.add(six);\n JTree tree = new JTree(node);\n frame.add(tree);\n tree.setVisibleRowCount(8);\n JOptionPane.showMessageDialog(null, new JScrollPane(tree));\n }\n}" } ]
How to open an Excel file with PHPExcel for both reading and writing?
There is no concept of opening a file for read and write in PHPExcel since it is not aware of the source of the PHPExcel object. Irrespective of the source from where the file was loaded or the type of file, the file can be read based on its named and saved with the same name. This way, the file will be overwritten, and new changes will be reflected in the file. error_reporting(E_ALL); set_time_limit(0); date_default_timezone_set('Europe/London'); set_include_path(get_include_path() . PATH_SEPARATOR . './Classes/'); include 'PHPExcel/IOFactory.php'; $fileType = 'Excel5'; $fileName = name_of_file.xls'; // Read the file $objReader = PHPExcel_IOFactory::createReader($fileType); $objPHPExcel = $objReader->load($fileName); // Change the file $objPHPExcel->setActiveSheetIndex(0) ->setCellValue('A1', 'Hello') ->setCellValue('B1', 'World!'); // Write the file $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, $fileType); $objWriter->save($fileName); This will produce the following output − Changes to cell A1, B1 are reflected in the name_of_file.xls file. The time limit is set to 0 and the timezone is set to Europe/London. The filetype is known to be Excel and filename is assigned to the variable ‘fileName’. The ‘PHPExcel_IOFactory’ class ‘createReader’ is used to create the object and it is loaded using the ‘load’ function. Two cell values of the ‘xls’ sheet are changed and it is saved with the same named.
[ { "code": null, "e": 1427, "s": 1062, "text": "There is no concept of opening a file for read and write in PHPExcel since it is not aware of the source of the PHPExcel object. Irrespective of the source from where the file was loaded or the type of file, the file can be read based on its named and saved with the same name. This way, the file will be overwritten, and new changes will be reflected in the file." }, { "code": null, "e": 2033, "s": 1427, "text": "error_reporting(E_ALL);\nset_time_limit(0);\ndate_default_timezone_set('Europe/London');\nset_include_path(get_include_path() . PATH_SEPARATOR . './Classes/');\ninclude 'PHPExcel/IOFactory.php';\n$fileType = 'Excel5';\n$fileName = name_of_file.xls';\n// Read the file\n$objReader = PHPExcel_IOFactory::createReader($fileType);\n$objPHPExcel = $objReader->load($fileName);\n// Change the file\n$objPHPExcel->setActiveSheetIndex(0)\n ->setCellValue('A1', 'Hello')\n ->setCellValue('B1', 'World!');\n// Write the file\n$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, $fileType);\n$objWriter->save($fileName);" }, { "code": null, "e": 2074, "s": 2033, "text": "This will produce the following output −" }, { "code": null, "e": 2141, "s": 2074, "text": "Changes to cell A1, B1 are reflected in the name_of_file.xls file." }, { "code": null, "e": 2500, "s": 2141, "text": "The time limit is set to 0 and the timezone is set to Europe/London. The filetype is known to be Excel and filename is assigned to the variable ‘fileName’. The ‘PHPExcel_IOFactory’ class ‘createReader’ is used to create the object and it is loaded using the ‘load’ function. Two cell values of the ‘xls’ sheet are changed and it is saved with the same named." } ]
Count the number of possible triangles - GeeksforGeeks
19 Apr, 2022 Given an unsorted array of positive integers, find the number of triangles that can be formed with three different array elements as three sides of triangles. For a triangle to be possible from 3 values, the sum of any of the two values (or sides) must be greater than the third value (or third side). Examples: Input: arr= {4, 6, 3, 7} Output: 3 Explanation: There are three triangles possible {3, 4, 6}, {4, 6, 7} and {3, 6, 7}. Note that {3, 4, 7} is not a possible triangle. Input: arr= {10, 21, 22, 100, 101, 200, 300}. Output: 6 Explanation: There can be 6 possible triangles: {10, 21, 22}, {21, 100, 101}, {22, 100, 101}, {10, 100, 101}, {100, 101, 200} and {101, 200, 300} Method 1(Brute Force) Approach: The brute force method is to run three loops and keep track of the number of triangles possible so far. The three loops select three different values from an array. The innermost loop checks for the triangle property which specifies the sum of any two sides must be greater than the value of the third side). Algorithm: Run three nested loops each loop starting from the index of the previous loop to end of array i.e run first loop from 0 to n, loop j from i to n and k from j to n.Sort the array first. Check if array[i] + array[j] > array[k], i.e. sum of two sides is greater than the thirdIf all three conditions match, increase the count.Print the count Run three nested loops each loop starting from the index of the previous loop to end of array i.e run first loop from 0 to n, loop j from i to n and k from j to n.Sort the array first. Check if array[i] + array[j] > array[k], i.e. sum of two sides is greater than the thirdIf all three conditions match, increase the count.Print the count Run three nested loops each loop starting from the index of the previous loop to end of array i.e run first loop from 0 to n, loop j from i to n and k from j to n. Sort the array first. Check if array[i] + array[j] > array[k], i.e. sum of two sides is greater than the third If all three conditions match, increase the count. Print the count Implementation: C++ C Java Python3 C# Javascript // C++ code to count the number of possible triangles using// brute force approach#include <bits/stdc++.h>using namespace std; // Function to count all possible triangles with arr[]// elementsint findNumberOfTriangles(int arr[], int n){ // Count of triangles int count = 0; // The three loops select three different values from // array for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { // The innermost loop checks for the triangle // property for (int k = j + 1; k < n; k++) // Sum of two sides is greater than the // third if (arr[i] + arr[j] > arr[k] && arr[i] + arr[k] > arr[j] && arr[k] + arr[j] > arr[i]) count++; } } return count;} // Driver codeint main(){ int arr[] = { 10, 21, 22, 100, 101, 200, 300 }; int size = sizeof(arr) / sizeof(arr[0]); cout << "Total number of triangles possible is " << findNumberOfTriangles(arr, size); return 0;} // This code is contributed by Sania Kumari Gupta // C++ code to count the number of possible triangles using// brute force approach#include <stdio.h> // Function to count all possible triangles with arr[]// elementsint findNumberOfTriangles(int arr[], int n){ // Count of triangles int count = 0; // The three loops select three different values from // array for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { // The innermost loop checks for the triangle // property for (int k = j + 1; k < n; k++) // Sum of two sides is greater than the // third if (arr[i] + arr[j] > arr[k] && arr[i] + arr[k] > arr[j] && arr[k] + arr[j] > arr[i]) count++; } } return count;} // Driver codeint main(){ int arr[] = { 10, 21, 22, 100, 101, 200, 300 }; int size = sizeof(arr) / sizeof(arr[0]); printf("Total number of triangles possible is %d ", findNumberOfTriangles(arr, size)); return 0;} // This code is contributed by Sania Kumari Gupta // Java code to count the number of possible triangles using// brute force approachimport java.io.*;import java.util.*; class GFG { // Function to count all possible triangles with arr[] // elements static int findNumberOfTriangles(int arr[], int n) { // Sort the array Arrays.sort(arr); // Count of triangles int count = 0; // The three loops select three different values // from array for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) for (int k = j + 1; k < n; k++) if (arr[i] + arr[j] > arr[k]) count++; return count; } // Driver code public static void main(String[] args) { int arr[] = { 10, 21, 22, 100, 101, 200, 300 }; int size = arr.length; System.out.println( "Total number of triangles possible is " + findNumberOfTriangles(arr, size)); }} // This code is contributed by Sania Kumari Gupta # Python3 code to count the number of# possible triangles using brute# force approach # Function to count all possible# triangles with arr[] elementsdef findNumberOfTriangles(arr, n): # Count of triangles count = 0 # The three loops select three # different values from array for i in range(n): for j in range(i + 1, n): # The innermost loop checks for # the triangle property for k in range(j + 1, n): # Sum of two sides is greater # than the third if (arr[i] + arr[j] > arr[k] and arr[i] + arr[k] > arr[j] and arr[k] + arr[j] > arr[i]): count += 1 return count # Driver codearr = [ 10, 21, 22, 100, 101, 200, 300 ]size = len(arr) print("Total number of triangles possible is", findNumberOfTriangles(arr, size)) # This code is contributed by shubhamsingh10 // C# code to count the number of// possible triangles using brute// force approachusing System; class GFG{ // Function to count all possible // triangles with arr[] elements static int findNumberOfTriangles(int[] arr, int n) { // Count of triangles int count = 0; // The three loops select three // different values from array for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { // The innermost loop checks for // the triangle property for (int k = j + 1; k < n; k++) // Sum of two sides is greater // than the third if ( arr[i] + arr[j] > arr[k] && arr[i] + arr[k] > arr[j] && arr[k] + arr[j] > arr[i]) count++; } } return count; } // Driver code static public void Main () { int[] arr = { 10, 21, 22, 100, 101, 200, 300 }; int size = arr.Length; Console.WriteLine("Total number of triangles possible is "+findNumberOfTriangles(arr, size)); }} // This code is contributed by shubhamsingh10 <script>// Javascript program for the above approach // Function to count all possible// triangles with arr[] elementsfunction findNumberOfTriangles(arr, n){ // Count of triangles let count = 0; // The three loops select three // different values from array for (let i = 0; i < n; i++) { for (let j = i + 1; j < n; j++) { // The innermost loop checks for // the triangle property for (let k = j + 1; k < n; k++) // Sum of two sides is greater // than the third if ( arr[i] + arr[j] > arr[k] && arr[i] + arr[k] > arr[j] && arr[k] + arr[j] > arr[i]) count++; } } return count;} // Driver Code let arr = [ 10, 21, 22, 100, 101, 200, 300 ]; let size = arr.length; document.write( "Total number of triangles possible is "+ findNumberOfTriangles(arr, size)); // This code is contributed by souravghosh0416.</script> Total number of triangles possible is 6 Complexity Analysis: Time Complexity: O(N^3) where N is the size of input array.Space Complexity: O(1) Time Complexity: O(N^3) where N is the size of input array. Space Complexity: O(1) Method 2: This is a tricky and efficient approach to reduce the time complexity from O(n^3) to O(n^2)where two sides of the triangles are fixed and the count can be found using those two sides. Approach: First sort the array in ascending order. Then use two loops. The outer loop to fix the first side and inner loop to fix the second side and then find the farthest index of the third side (greater than indices of both sides) whose length is less than sum of the other two sides. So a range of values third sides can be found, where it is guaranteed that its length if greater than the other individual sides but less than the sum of both sides. Algorithm: Let a, b and c be three sides. The below condition must hold for a triangle (sum of two sides is greater than the third side) i) a + b > c ii) b + c > a iii) a + c > bFollowing are steps to count triangle. Sort the array in ascending order.Now run a nested loop. The outer loop runs from start to end and the inner loop runs from index + 1 of the first loop to the end. Take the loop counter of first loop as i and second loop as j. Take another variable k = i + 2Now there is two pointers i and j, where array[i] and array[j] represents two sides of the triangles. For a fixed i and j, find the count of third sides which will satisfy the conditions of a triangle. i.e find the largest value of array[k] such that array[i] + array[j] > array[k]So when we get the largest value, then the count of third side is k – j, add it to the total count.Now sum up for all valid pairs of i and j where i < j Sort the array in ascending order.Now run a nested loop. The outer loop runs from start to end and the inner loop runs from index + 1 of the first loop to the end. Take the loop counter of first loop as i and second loop as j. Take another variable k = i + 2Now there is two pointers i and j, where array[i] and array[j] represents two sides of the triangles. For a fixed i and j, find the count of third sides which will satisfy the conditions of a triangle. i.e find the largest value of array[k] such that array[i] + array[j] > array[k]So when we get the largest value, then the count of third side is k – j, add it to the total count.Now sum up for all valid pairs of i and j where i < j Sort the array in ascending order. Now run a nested loop. The outer loop runs from start to end and the inner loop runs from index + 1 of the first loop to the end. Take the loop counter of first loop as i and second loop as j. Take another variable k = i + 2 Now there is two pointers i and j, where array[i] and array[j] represents two sides of the triangles. For a fixed i and j, find the count of third sides which will satisfy the conditions of a triangle. i.e find the largest value of array[k] such that array[i] + array[j] > array[k] So when we get the largest value, then the count of third side is k – j, add it to the total count. Now sum up for all valid pairs of i and j where i < j Implementation: C++ C Java Python3 C# PHP Javascript // C++ program to count number of triangles that can be// formed from given array#include <bits/stdc++.h>using namespace std; // Function to count all possible triangles with arr[]// elementsint findNumberOfTriangles(int arr[], int n){ // Sort the array elements in non-decreasing order sort(arr, arr + n); // Initialize count of triangles int count = 0; // Fix the first element. We need to run till n-3 // as the other two elements are selected from // arr[i+1...n-1] for (int i = 0; i < n - 2; ++i) { // Initialize index of the rightmost third // element int k = i + 2; // Fix the second element for (int j = i + 1; j < n; ++j) { // Find the rightmost element which is smaller // than the sum of two fixed elements The // important thing to note here is, we use the // previous value of k. If value of arr[i] + // arr[j-1] was greater than arr[k], then arr[i] // + arr[j] must be greater than k, because the // array is sorted. while (k < n && arr[i] + arr[j] > arr[k]) ++k; // Total number of possible triangles that can // be formed with the two fixed elements is // k - j - 1. The two fixed elements are arr[i] // and arr[j]. All elements between arr[j+1]/ to // arr[k-1] can form a triangle with arr[i] and // arr[j]. One is subtracted from k because k is // incremented one extra in above while loop. k // will always be greater than j. If j becomes // equal to k, then above loop will increment k, // because arr[k] // + arr[i] is always greater than arr[k] if (k > j) count += k - j - 1; } } return count;} // Driver codeint main(){ int arr[] = { 10, 21, 22, 100, 101, 200, 300 }; int size = sizeof(arr) / sizeof(arr[0]); cout << "Total number of triangles possible is " << findNumberOfTriangles(arr, size); return 0;} // This code is contributed by Sania Kumari Gupta // C program to count number of triangles that can be// formed from given array#include <stdio.h>#include <stdlib.h> /* Following function is needed for library functionqsort(). Referhttp:// www.cplusplus.com/reference/clibrary/cstdlib/qsort/ */int comp(const void* a, const void* b){ return *(int*)a > *(int*)b;} // Function to count all possible triangles with arr[]// elementsint findNumberOfTriangles(int arr[], int n){ // Sort the array elements in non-decreasing order qsort(arr, n, sizeof(arr[0]), comp); // Initialize count of triangles int count = 0; // Fix the first element. We need to run till n-3 // as the other two elements are selected from // arr[i+1...n-1] for (int i = 0; i < n - 2; ++i) { // Initialize index of the rightmost third // element int k = i + 2; // Fix the second element for (int j = i + 1; j < n; ++j) { // Find the rightmost element which is // smaller than the sum of two fixed elements // The important thing to note here is, we // use the previous value of k. If value of // arr[i] + arr[j-1] was greater than arr[k], // then arr[i] + arr[j] must be greater than k, // because the array is sorted. while (k < n && arr[i] + arr[j] > arr[k]) ++k; // Total number of possible triangles that can // be formed with the two fixed elements is // k - j - 1. The two fixed elements are arr[i] // and arr[j]. All elements between arr[j+1]/ to // arr[k-1] can form a triangle with arr[i] and arr[j]. // One is subtracted from k because k is incremented // one extra in above while loop. // k will always be greater than j. If j becomes equal // to k, then above loop will increment k, because arr[k] // + arr[i] is always greater than arr[k] if (k > j) count += k - j - 1; } } return count;} // Driver program to test above functionarr[j+1]int main(){ int arr[] = { 10, 21, 22, 100, 101, 200, 300 }; int size = sizeof(arr) / sizeof(arr[0]); printf("Total number of triangles possible is %d ", findNumberOfTriangles(arr, size)); return 0;} // This code is contributed by Sania Kumari Gupta // Java program to count number of triangles that can be// formed from given arrayimport java.io.*;import java.util.*; class CountTriangles { // Function to count all possible triangles with arr[] // elements static int findNumberOfTriangles(int arr[]) { int n = arr.length; // Sort the array elements in non-decreasing order Arrays.sort(arr); // Initialize count of triangles int count = 0; // Fix the first element. We need to run till n-3 as // the other two elements are selected from // arr[i+1...n-1] for (int i = 0; i < n - 2; ++i) { // Initialize index of the rightmost third // element int k = i + 2; // Fix the second element for (int j = i + 1; j < n; ++j) { // Find the rightmost element which is // smaller than the sum of two fixed // elements The important thing to note here // is, we use the previous value of k. If // value of arr[i] + arr[j-1] was greater // than arr[k], then arr[i] + arr[j] must be // greater than k, because the array is // sorted. while (k < n && arr[i] + arr[j] > arr[k]) ++k; // Total number of possible triangles that // can be formed with the two fixed elements // is k - j - 1. The two fixed elements are // arr[i] and arr[j]. All elements between // arr[j+1] to arr[k-1] can form a triangle // with arr[i] and arr[j]. One is subtracted // from k because k is incremented one extra // in above while loop. k will always be // greater than j. If j becomes equal to k, // then above loop will increment k, because // arr[k] + arr[i] is always/ greater than // arr[k] if (k > j) count += k - j - 1; } } return count; } public static void main(String[] args) { int arr[] = { 10, 21, 22, 100, 101, 200, 300 }; System.out.println("Total number of triangles is " + findNumberOfTriangles(arr)); }} // This code is contributed by Sania Kumari Gupta # Python function to count all possible triangles with arr[]# elements def findnumberofTriangles(arr): # Sort array and initialize count as 0 n = len(arr) arr.sort() count = 0 # Fix the first element. We need to run till n-3 as # the other two elements are selected from arr[i + 1...n-1] for i in range(0, n-2): # Initialize index of the rightmost third element k = i + 2 # Fix the second element for j in range(i + 1, n): # Find the rightmost element which is smaller # than the sum of two fixed elements # The important thing to note here is, we use # the previous value of k. If value of arr[i] + # arr[j-1] was greater than arr[k], then arr[i] + # arr[j] must be greater than k, because the array # is sorted. while (k < n and arr[i] + arr[j] > arr[k]): k += 1 # Total number of possible triangles that can be # formed with the two fixed elements is k - j - 1. # The two fixed elements are arr[i] and arr[j]. All # elements between arr[j + 1] to arr[k-1] can form a # triangle with arr[i] and arr[j]. One is subtracted # from k because k is incremented one extra in above # while loop. k will always be greater than j. If j # becomes equal to k, then above loop will increment k, # because arr[k] + arr[i] is always greater than arr[k] if(k>j): count += k - j - 1 return count # Driver function to test above functionarr = [10, 21, 22, 100, 101, 200, 300]print ("Number of Triangles:", findnumberofTriangles(arr)) # This code is contributed by Devesh Agrawal // C# program to count number// of triangles that can be// formed from given arrayusing System; class GFG { // Function to count all // possible triangles // with arr[] elements static int findNumberOfTriangles(int[] arr) { int n = arr.Length; // Sort the array elements // in non-decreasing order Array.Sort(arr); // Initialize count // of triangles int count = 0; // Fix the first element. We // need to run till n-3 as // the other two elements are // selected from arr[i+1...n-1] for (int i = 0; i < n - 2; ++i) { // Initialize index of the // rightmost third element int k = i + 2; // Fix the second element for (int j = i + 1; j < n; ++j) { /* Find the rightmost element which is smaller than the sum of two fixed elements. The important thing to note here is, we use the previous value of k. If value of arr[i] + arr[j-1] was greater than arr[k], then arr[i] + arr[j] must be greater than k, because the array is sorted. */ while (k < n && arr[i] + arr[j] > arr[k]) ++k; /* Total number of possible triangles that can be formed with the two fixed elements is k - j - 1. The two fixed elements are arr[i] and arr[j]. All elements between arr[j+1] to arr[k-1] can form a triangle with arr[i] and arr[j]. One is subtracted from k because k is incremented one extra in above while loop. k will always be greater than j. If j becomes equal to k, then above loop will increment k, because arr[k] + arr[i] is always/ greater than arr[k] */ if (k > j) count += k - j - 1; } } return count; } // Driver Code public static void Main() { int[] arr = { 10, 21, 22, 100, 101, 200, 300 }; Console.WriteLine("Total number of triangles is " + findNumberOfTriangles(arr)); }} // This code is contributed by anuj_67. <?php// PHP program to count number// of triangles that can be// formed from given array // Function to count all// possible triangles with// arr[] elementfunction findNumberOfTriangles($arr){ $n = count($arr); // Sort the array elements // in non-decreasing order sort($arr); // Initialize count // of triangles $count = 0; // Fix the first element. // We need to run till n-3 // as the other two elements // are selected from // arr[i+1...n-1] for ($i = 0; $i < $n - 2; ++$i) { // Initialize index of the // rightmost third element $k = $i + 2; // Fix the second element for ($j = $i + 1; $j < $n; ++$j) { /* Find the rightmost element which is smaller than the sum of two fixed elements. The important thing to note here is, we use the previous value of k. If value of arr[i] + arr[j-1] was greater than arr[k], then arr[i] + arr[j] must be greater than k, because the array is sorted. */ while ($k < $n && $arr[$i] + $arr[$j] > $arr[$k]) ++$k; /* Total number of possible triangles that can be formed with the two fixed elements is k - j - 1. The two fixed elements are arr[i] and arr[j]. All elements between arr[j+1] to arr[k-1] can form a triangle with arr[i] and arr[j]. One is subtracted from k because k is incremented one extra in above while loop. k will always be greater than j. If j becomes equal to k, then above loop will increment k, because arr[k] + arr[i] is always/ greater than arr[k] */ if($k>$j) $count += $k - $j - 1; } } return $count;} // Driver code$arr = array(10, 21, 22, 100, 101, 200, 300);echo"Total number of triangles is ", findNumberOfTriangles($arr); // This code is contributed by anuj_67.?> <script> // Javascript program to count number of triangles that can be// formed from given array // Function to count all possible triangles with arr[]// elementsfunction findNumberOfTriangles(arr){ let n = arr.length; // Sort the array elements in non-decreasing order arr.sort((a, b) => a-b); // Initialize count of triangles let count = 0; // Fix the first element. We // need to run till n-3 as // the other two elements are // selected from arr[i+1...n-1] for (let i = 0; i < n - 2; ++i) { // Initialize index of the // rightmost third element let k = i + 2; // Fix the second element for (let j = i + 1; j < n; ++j) { // Find the rightmost element which is // smaller than the sum of two fixed elements // The important thing to note here is, we // use the previous value of k. If value of // arr[i] + arr[j-1] was greater than arr[k], // then arr[i] + arr[j] must be greater than k, // because the array is sorted. while (k < n && arr[i] + arr[j] > arr[k]) ++k; // Total number of possible triangles that can // be formed with the two fixed elements is // k - j - 1. The two fixed elements are arr[i] // and arr[j]. All elements between arr[j+1]/ to // arr[k-1] can form a triangle with arr[i] and arr[j]. // One is subtracted from k because k is incremented // one extra in above while loop. // k will always be greater than j. If j becomes equal // to k, then above loop will increment k, because arr[k] // + arr[i] is always greater than arr[k] if (k > j) count += k - j - 1; } } return count;} // Driver code let arr = [ 10, 21, 22, 100, 101, 200, 300 ]; let size = arr.length; document.write("Total number of triangles possible is " + findNumberOfTriangles(arr, size)); // This code is contributed by Manoj </script> Total number of triangles possible is 6 Complexity Analysis: Time Complexity: O(n^2). The time complexity looks more because of 3 nested loops. It can be observed that k is initialized only once in the outermost loop. The innermost loop executes at most O(n) time for every iteration of the outermost loop, because k starts from i+2 and goes up to n for all values of j. Therefore, the time complexity is O(n^2).Space Complexity: O(1). No extra space is required. So space complexity is constant Time Complexity: O(n^2). The time complexity looks more because of 3 nested loops. It can be observed that k is initialized only once in the outermost loop. The innermost loop executes at most O(n) time for every iteration of the outermost loop, because k starts from i+2 and goes up to n for all values of j. Therefore, the time complexity is O(n^2). Space Complexity: O(1). No extra space is required. So space complexity is constant Method 3: The time complexity can be greatly reduced using Two Pointer methods in just two nested loops. Approach: First sort the array, and run a nested loop, fix an index and then try to fix an upper and lower index within which we can use all the lengths to form a triangle with that fixed index. Algorithm:Sort the array and then take three variables l, r and i, pointing to start, end-1 and array element starting from end of the array.Traverse the array from end (n-1 to 1), and for each iteration keep the value of l = 0 and r = i-1Now if a triangle can be formed using arr[l] and arr[r] then triangles can obviously formed from a[l+1], a[l+2].....a[r-1], arr[r] and a[i], because the array is sorted , which can be directly calculated using (r-l). and then decrement the value of r and continue the loop till l is less than rIf a triangle cannot be formed using arr[l] and arr[r] then increment the value of l and continue the loop till l is less than r So the overall complexity of iterating through all array elements reduces. Sort the array and then take three variables l, r and i, pointing to start, end-1 and array element starting from end of the array.Traverse the array from end (n-1 to 1), and for each iteration keep the value of l = 0 and r = i-1Now if a triangle can be formed using arr[l] and arr[r] then triangles can obviously formed from a[l+1], a[l+2].....a[r-1], arr[r] and a[i], because the array is sorted , which can be directly calculated using (r-l). and then decrement the value of r and continue the loop till l is less than rIf a triangle cannot be formed using arr[l] and arr[r] then increment the value of l and continue the loop till l is less than r So the overall complexity of iterating through all array elements reduces. Sort the array and then take three variables l, r and i, pointing to start, end-1 and array element starting from end of the array. Traverse the array from end (n-1 to 1), and for each iteration keep the value of l = 0 and r = i-1 Now if a triangle can be formed using arr[l] and arr[r] then triangles can obviously formed from a[l+1], a[l+2].....a[r-1], arr[r] and a[i], because the array is sorted , which can be directly calculated using (r-l). and then decrement the value of r and continue the loop till l is less than r If a triangle cannot be formed using arr[l] and arr[r] then increment the value of l and continue the loop till l is less than r So the overall complexity of iterating through all array elements reduces. Implementation: C++ Java Python3 C# Javascript // C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; void CountTriangles(vector<int> A){ int n = A.size(); sort(A.begin(), A.end()); int count = 0; for (int i = n - 1; i >= 1; i--) { int l = 0, r = i - 1; while (l < r) { if (A[l] + A[r] > A[i]) { // If it is possible with a[l], a[r] // and a[i] then it is also possible // with a[l+1]..a[r-1], a[r] and a[i] count += r - l; // checking for more possible solutions r--; } else // if not possible check for // higher values of arr[l] l++; } } cout << "No of possible solutions: " << count;}int main(){ vector<int> A = { 4, 3, 5, 7, 6 }; CountTriangles(A);} // Java implementation of the above approachimport java.util.*; class GFG { static void CountTriangles(int[] A) { int n = A.length; Arrays.sort(A); int count = 0; for (int i = n - 1; i >= 1; i--) { int l = 0, r = i - 1; while (l < r) { if (A[l] + A[r] > A[i]) { // If it is possible with a[l], a[r] // and a[i] then it is also possible // with a[l+1]..a[r-1], a[r] and a[i] count += r - l; // checking for more possible solutions r--; } else // if not possible check for // higher values of arr[l] { l++; } } } System.out.print("No of possible solutions: " + count); } // Driver Code public static void main(String[] args) { int[] A = { 4, 3, 5, 7, 6 }; CountTriangles(A); }} // This code is contributed by PrinciRaj1992 # Python implementation of the above approachdef CountTriangles( A): n = len(A); A.sort(); count = 0; for i in range(n - 1, 0, -1): l = 0; r = i - 1; while(l < r): if(A[l] + A[r] > A[i]): # If it is possible with a[l], a[r] # and a[i] then it is also possible # with a[l + 1]..a[r-1], a[r] and a[i] count += r - l; # checking for more possible solutions r -= 1; else: # if not possible check for # higher values of arr[l] l += 1; print("No of possible solutions: ", count); # Driver Codeif __name__ == '__main__': A = [ 4, 3, 5, 7, 6 ]; CountTriangles(A); # This code is contributed by PrinciRaj1992 // C# implementation of the above approachusing System; class GFG { static void CountTriangles(int[] A) { int n = A.Length; Array.Sort(A); int count = 0; for (int i = n - 1; i >= 1; i--) { int l = 0, r = i - 1; while (l < r) { if (A[l] + A[r] > A[i]) { // If it is possible with a[l], a[r] // and a[i] then it is also possible // with a[l+1]..a[r-1], a[r] and a[i] count += r - l; // checking for more possible solutions r--; } else // if not possible check for // higher values of arr[l] { l++; } } } Console.Write("No of possible solutions: " + count); } // Driver Code public static void Main(String[] args) { int[] A = { 4, 3, 5, 7, 6 }; CountTriangles(A); }} // This code is contributed by Rajput-Ji <script>// javascript implementation of the above approach function CountTriangles(A) { var n = A.length; A.sort(); var count = 0; for (i = n - 1; i >= 1; i--) { var l = 0, r = i - 1; while (l < r) { if (A[l] + A[r] > A[i]) { // If it is possible with a[l], a[r] // and a[i] then it is also possible // with a[l+1]..a[r-1], a[r] and a[i] count += r - l; // checking for more possible solutions r--; } else // if not possible check for // higher values of arr[l] { l++; } } } document.write("No of possible solutions: " + count); } // Driver Code var A = [ 4, 3, 5, 7, 6 ]; CountTriangles(A); // This code is contributed by aashish1995</script> No of possible solutions: 9 Complexity Analysis: Time complexity: O(n^2). As two nested loops are used, but overall iterations in comparison to the above method reduces greatly.Space Complexity: O(1). As no extra space is required, so space complexity is constant Time complexity: O(n^2). As two nested loops are used, but overall iterations in comparison to the above method reduces greatly. Space Complexity: O(1). As no extra space is required, so space complexity is constant vt_m cds91 md1844 rathbhupendra princiraj1992 Rajput-Ji andrew1234 SHUBHAMSINGH10 winter_soldier souravghosh0416 aashish1995 mank1083 swetakb15 surindertarika1234 rajatsangrame amartyaghoshgfg krisania804 Amazon Linkedin triangle Wipro Arrays Mathematical Amazon Wipro Linkedin Arrays Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Arrays in Java Arrays in C/C++ Write a program to reverse an array or string Stack Data Structure (Introduction and Program) Program for array rotation Program for Fibonacci numbers Write a program to print all permutations of a given string C++ Data Types Set in C++ Standard Template Library (STL) Coin Change | DP-7
[ { "code": null, "e": 41276, "s": 41248, "text": "\n19 Apr, 2022" }, { "code": null, "e": 41590, "s": 41276, "text": "Given an unsorted array of positive integers, find the number of triangles that can be formed with three different array elements as three sides of triangles. For a triangle to be possible from 3 values, the sum of any of the two values (or sides) must be greater than the third value (or third side). Examples: " }, { "code": null, "e": 41966, "s": 41590, "text": "Input: arr= {4, 6, 3, 7}\nOutput: 3\nExplanation: There are three triangles \npossible {3, 4, 6}, {4, 6, 7} and {3, 6, 7}. \nNote that {3, 4, 7} is not a possible triangle. \n\nInput: arr= {10, 21, 22, 100, 101, 200, 300}.\nOutput: 6\n\nExplanation: There can be 6 possible triangles:\n{10, 21, 22}, {21, 100, 101}, {22, 100, 101}, \n{10, 100, 101}, {100, 101, 200} and {101, 200, 300}" }, { "code": null, "e": 41990, "s": 41966, "text": "Method 1(Brute Force) " }, { "code": null, "e": 42309, "s": 41990, "text": "Approach: The brute force method is to run three loops and keep track of the number of triangles possible so far. The three loops select three different values from an array. The innermost loop checks for the triangle property which specifies the sum of any two sides must be greater than the value of the third side)." }, { "code": null, "e": 42659, "s": 42309, "text": "Algorithm: Run three nested loops each loop starting from the index of the previous loop to end of array i.e run first loop from 0 to n, loop j from i to n and k from j to n.Sort the array first. Check if array[i] + array[j] > array[k], i.e. sum of two sides is greater than the thirdIf all three conditions match, increase the count.Print the count" }, { "code": null, "e": 42998, "s": 42659, "text": "Run three nested loops each loop starting from the index of the previous loop to end of array i.e run first loop from 0 to n, loop j from i to n and k from j to n.Sort the array first. Check if array[i] + array[j] > array[k], i.e. sum of two sides is greater than the thirdIf all three conditions match, increase the count.Print the count" }, { "code": null, "e": 43162, "s": 42998, "text": "Run three nested loops each loop starting from the index of the previous loop to end of array i.e run first loop from 0 to n, loop j from i to n and k from j to n." }, { "code": null, "e": 43273, "s": 43162, "text": "Sort the array first. Check if array[i] + array[j] > array[k], i.e. sum of two sides is greater than the third" }, { "code": null, "e": 43324, "s": 43273, "text": "If all three conditions match, increase the count." }, { "code": null, "e": 43340, "s": 43324, "text": "Print the count" }, { "code": null, "e": 43356, "s": 43340, "text": "Implementation:" }, { "code": null, "e": 43360, "s": 43356, "text": "C++" }, { "code": null, "e": 43362, "s": 43360, "text": "C" }, { "code": null, "e": 43367, "s": 43362, "text": "Java" }, { "code": null, "e": 43375, "s": 43367, "text": "Python3" }, { "code": null, "e": 43378, "s": 43375, "text": "C#" }, { "code": null, "e": 43389, "s": 43378, "text": "Javascript" }, { "code": "// C++ code to count the number of possible triangles using// brute force approach#include <bits/stdc++.h>using namespace std; // Function to count all possible triangles with arr[]// elementsint findNumberOfTriangles(int arr[], int n){ // Count of triangles int count = 0; // The three loops select three different values from // array for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { // The innermost loop checks for the triangle // property for (int k = j + 1; k < n; k++) // Sum of two sides is greater than the // third if (arr[i] + arr[j] > arr[k] && arr[i] + arr[k] > arr[j] && arr[k] + arr[j] > arr[i]) count++; } } return count;} // Driver codeint main(){ int arr[] = { 10, 21, 22, 100, 101, 200, 300 }; int size = sizeof(arr) / sizeof(arr[0]); cout << \"Total number of triangles possible is \" << findNumberOfTriangles(arr, size); return 0;} // This code is contributed by Sania Kumari Gupta", "e": 44498, "s": 43389, "text": null }, { "code": "// C++ code to count the number of possible triangles using// brute force approach#include <stdio.h> // Function to count all possible triangles with arr[]// elementsint findNumberOfTriangles(int arr[], int n){ // Count of triangles int count = 0; // The three loops select three different values from // array for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { // The innermost loop checks for the triangle // property for (int k = j + 1; k < n; k++) // Sum of two sides is greater than the // third if (arr[i] + arr[j] > arr[k] && arr[i] + arr[k] > arr[j] && arr[k] + arr[j] > arr[i]) count++; } } return count;} // Driver codeint main(){ int arr[] = { 10, 21, 22, 100, 101, 200, 300 }; int size = sizeof(arr) / sizeof(arr[0]); printf(\"Total number of triangles possible is %d \", findNumberOfTriangles(arr, size)); return 0;} // This code is contributed by Sania Kumari Gupta", "e": 45584, "s": 44498, "text": null }, { "code": "// Java code to count the number of possible triangles using// brute force approachimport java.io.*;import java.util.*; class GFG { // Function to count all possible triangles with arr[] // elements static int findNumberOfTriangles(int arr[], int n) { // Sort the array Arrays.sort(arr); // Count of triangles int count = 0; // The three loops select three different values // from array for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) for (int k = j + 1; k < n; k++) if (arr[i] + arr[j] > arr[k]) count++; return count; } // Driver code public static void main(String[] args) { int arr[] = { 10, 21, 22, 100, 101, 200, 300 }; int size = arr.length; System.out.println( \"Total number of triangles possible is \" + findNumberOfTriangles(arr, size)); }} // This code is contributed by Sania Kumari Gupta", "e": 46593, "s": 45584, "text": null }, { "code": "# Python3 code to count the number of# possible triangles using brute# force approach # Function to count all possible# triangles with arr[] elementsdef findNumberOfTriangles(arr, n): # Count of triangles count = 0 # The three loops select three # different values from array for i in range(n): for j in range(i + 1, n): # The innermost loop checks for # the triangle property for k in range(j + 1, n): # Sum of two sides is greater # than the third if (arr[i] + arr[j] > arr[k] and arr[i] + arr[k] > arr[j] and arr[k] + arr[j] > arr[i]): count += 1 return count # Driver codearr = [ 10, 21, 22, 100, 101, 200, 300 ]size = len(arr) print(\"Total number of triangles possible is\", findNumberOfTriangles(arr, size)) # This code is contributed by shubhamsingh10", "e": 47563, "s": 46593, "text": null }, { "code": "// C# code to count the number of// possible triangles using brute// force approachusing System; class GFG{ // Function to count all possible // triangles with arr[] elements static int findNumberOfTriangles(int[] arr, int n) { // Count of triangles int count = 0; // The three loops select three // different values from array for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { // The innermost loop checks for // the triangle property for (int k = j + 1; k < n; k++) // Sum of two sides is greater // than the third if ( arr[i] + arr[j] > arr[k] && arr[i] + arr[k] > arr[j] && arr[k] + arr[j] > arr[i]) count++; } } return count; } // Driver code static public void Main () { int[] arr = { 10, 21, 22, 100, 101, 200, 300 }; int size = arr.Length; Console.WriteLine(\"Total number of triangles possible is \"+findNumberOfTriangles(arr, size)); }} // This code is contributed by shubhamsingh10", "e": 48807, "s": 47563, "text": null }, { "code": "<script>// Javascript program for the above approach // Function to count all possible// triangles with arr[] elementsfunction findNumberOfTriangles(arr, n){ // Count of triangles let count = 0; // The three loops select three // different values from array for (let i = 0; i < n; i++) { for (let j = i + 1; j < n; j++) { // The innermost loop checks for // the triangle property for (let k = j + 1; k < n; k++) // Sum of two sides is greater // than the third if ( arr[i] + arr[j] > arr[k] && arr[i] + arr[k] > arr[j] && arr[k] + arr[j] > arr[i]) count++; } } return count;} // Driver Code let arr = [ 10, 21, 22, 100, 101, 200, 300 ]; let size = arr.length; document.write( \"Total number of triangles possible is \"+ findNumberOfTriangles(arr, size)); // This code is contributed by souravghosh0416.</script>", "e": 49839, "s": 48807, "text": null }, { "code": null, "e": 49879, "s": 49839, "text": "Total number of triangles possible is 6" }, { "code": null, "e": 49984, "s": 49881, "text": "Complexity Analysis: Time Complexity: O(N^3) where N is the size of input array.Space Complexity: O(1)" }, { "code": null, "e": 50044, "s": 49984, "text": "Time Complexity: O(N^3) where N is the size of input array." }, { "code": null, "e": 50067, "s": 50044, "text": "Space Complexity: O(1)" }, { "code": null, "e": 50262, "s": 50067, "text": "Method 2: This is a tricky and efficient approach to reduce the time complexity from O(n^3) to O(n^2)where two sides of the triangles are fixed and the count can be found using those two sides. " }, { "code": null, "e": 50716, "s": 50262, "text": "Approach: First sort the array in ascending order. Then use two loops. The outer loop to fix the first side and inner loop to fix the second side and then find the farthest index of the third side (greater than indices of both sides) whose length is less than sum of the other two sides. So a range of values third sides can be found, where it is guaranteed that its length if greater than the other individual sides but less than the sum of both sides." }, { "code": null, "e": 51625, "s": 50716, "text": "Algorithm: Let a, b and c be three sides. The below condition must hold for a triangle (sum of two sides is greater than the third side) i) a + b > c ii) b + c > a iii) a + c > bFollowing are steps to count triangle. Sort the array in ascending order.Now run a nested loop. The outer loop runs from start to end and the inner loop runs from index + 1 of the first loop to the end. Take the loop counter of first loop as i and second loop as j. Take another variable k = i + 2Now there is two pointers i and j, where array[i] and array[j] represents two sides of the triangles. For a fixed i and j, find the count of third sides which will satisfy the conditions of a triangle. i.e find the largest value of array[k] such that array[i] + array[j] > array[k]So when we get the largest value, then the count of third side is k – j, add it to the total count.Now sum up for all valid pairs of i and j where i < j" }, { "code": null, "e": 52317, "s": 51625, "text": "Sort the array in ascending order.Now run a nested loop. The outer loop runs from start to end and the inner loop runs from index + 1 of the first loop to the end. Take the loop counter of first loop as i and second loop as j. Take another variable k = i + 2Now there is two pointers i and j, where array[i] and array[j] represents two sides of the triangles. For a fixed i and j, find the count of third sides which will satisfy the conditions of a triangle. i.e find the largest value of array[k] such that array[i] + array[j] > array[k]So when we get the largest value, then the count of third side is k – j, add it to the total count.Now sum up for all valid pairs of i and j where i < j" }, { "code": null, "e": 52352, "s": 52317, "text": "Sort the array in ascending order." }, { "code": null, "e": 52577, "s": 52352, "text": "Now run a nested loop. The outer loop runs from start to end and the inner loop runs from index + 1 of the first loop to the end. Take the loop counter of first loop as i and second loop as j. Take another variable k = i + 2" }, { "code": null, "e": 52859, "s": 52577, "text": "Now there is two pointers i and j, where array[i] and array[j] represents two sides of the triangles. For a fixed i and j, find the count of third sides which will satisfy the conditions of a triangle. i.e find the largest value of array[k] such that array[i] + array[j] > array[k]" }, { "code": null, "e": 52959, "s": 52859, "text": "So when we get the largest value, then the count of third side is k – j, add it to the total count." }, { "code": null, "e": 53013, "s": 52959, "text": "Now sum up for all valid pairs of i and j where i < j" }, { "code": null, "e": 53031, "s": 53013, "text": "Implementation: " }, { "code": null, "e": 53035, "s": 53031, "text": "C++" }, { "code": null, "e": 53037, "s": 53035, "text": "C" }, { "code": null, "e": 53042, "s": 53037, "text": "Java" }, { "code": null, "e": 53050, "s": 53042, "text": "Python3" }, { "code": null, "e": 53053, "s": 53050, "text": "C#" }, { "code": null, "e": 53057, "s": 53053, "text": "PHP" }, { "code": null, "e": 53068, "s": 53057, "text": "Javascript" }, { "code": "// C++ program to count number of triangles that can be// formed from given array#include <bits/stdc++.h>using namespace std; // Function to count all possible triangles with arr[]// elementsint findNumberOfTriangles(int arr[], int n){ // Sort the array elements in non-decreasing order sort(arr, arr + n); // Initialize count of triangles int count = 0; // Fix the first element. We need to run till n-3 // as the other two elements are selected from // arr[i+1...n-1] for (int i = 0; i < n - 2; ++i) { // Initialize index of the rightmost third // element int k = i + 2; // Fix the second element for (int j = i + 1; j < n; ++j) { // Find the rightmost element which is smaller // than the sum of two fixed elements The // important thing to note here is, we use the // previous value of k. If value of arr[i] + // arr[j-1] was greater than arr[k], then arr[i] // + arr[j] must be greater than k, because the // array is sorted. while (k < n && arr[i] + arr[j] > arr[k]) ++k; // Total number of possible triangles that can // be formed with the two fixed elements is // k - j - 1. The two fixed elements are arr[i] // and arr[j]. All elements between arr[j+1]/ to // arr[k-1] can form a triangle with arr[i] and // arr[j]. One is subtracted from k because k is // incremented one extra in above while loop. k // will always be greater than j. If j becomes // equal to k, then above loop will increment k, // because arr[k] // + arr[i] is always greater than arr[k] if (k > j) count += k - j - 1; } } return count;} // Driver codeint main(){ int arr[] = { 10, 21, 22, 100, 101, 200, 300 }; int size = sizeof(arr) / sizeof(arr[0]); cout << \"Total number of triangles possible is \" << findNumberOfTriangles(arr, size); return 0;} // This code is contributed by Sania Kumari Gupta", "e": 55192, "s": 53068, "text": null }, { "code": "// C program to count number of triangles that can be// formed from given array#include <stdio.h>#include <stdlib.h> /* Following function is needed for library functionqsort(). Referhttp:// www.cplusplus.com/reference/clibrary/cstdlib/qsort/ */int comp(const void* a, const void* b){ return *(int*)a > *(int*)b;} // Function to count all possible triangles with arr[]// elementsint findNumberOfTriangles(int arr[], int n){ // Sort the array elements in non-decreasing order qsort(arr, n, sizeof(arr[0]), comp); // Initialize count of triangles int count = 0; // Fix the first element. We need to run till n-3 // as the other two elements are selected from // arr[i+1...n-1] for (int i = 0; i < n - 2; ++i) { // Initialize index of the rightmost third // element int k = i + 2; // Fix the second element for (int j = i + 1; j < n; ++j) { // Find the rightmost element which is // smaller than the sum of two fixed elements // The important thing to note here is, we // use the previous value of k. If value of // arr[i] + arr[j-1] was greater than arr[k], // then arr[i] + arr[j] must be greater than k, // because the array is sorted. while (k < n && arr[i] + arr[j] > arr[k]) ++k; // Total number of possible triangles that can // be formed with the two fixed elements is // k - j - 1. The two fixed elements are arr[i] // and arr[j]. All elements between arr[j+1]/ to // arr[k-1] can form a triangle with arr[i] and arr[j]. // One is subtracted from k because k is incremented // one extra in above while loop. // k will always be greater than j. If j becomes equal // to k, then above loop will increment k, because arr[k] // + arr[i] is always greater than arr[k] if (k > j) count += k - j - 1; } } return count;} // Driver program to test above functionarr[j+1]int main(){ int arr[] = { 10, 21, 22, 100, 101, 200, 300 }; int size = sizeof(arr) / sizeof(arr[0]); printf(\"Total number of triangles possible is %d \", findNumberOfTriangles(arr, size)); return 0;} // This code is contributed by Sania Kumari Gupta", "e": 57549, "s": 55192, "text": null }, { "code": "// Java program to count number of triangles that can be// formed from given arrayimport java.io.*;import java.util.*; class CountTriangles { // Function to count all possible triangles with arr[] // elements static int findNumberOfTriangles(int arr[]) { int n = arr.length; // Sort the array elements in non-decreasing order Arrays.sort(arr); // Initialize count of triangles int count = 0; // Fix the first element. We need to run till n-3 as // the other two elements are selected from // arr[i+1...n-1] for (int i = 0; i < n - 2; ++i) { // Initialize index of the rightmost third // element int k = i + 2; // Fix the second element for (int j = i + 1; j < n; ++j) { // Find the rightmost element which is // smaller than the sum of two fixed // elements The important thing to note here // is, we use the previous value of k. If // value of arr[i] + arr[j-1] was greater // than arr[k], then arr[i] + arr[j] must be // greater than k, because the array is // sorted. while (k < n && arr[i] + arr[j] > arr[k]) ++k; // Total number of possible triangles that // can be formed with the two fixed elements // is k - j - 1. The two fixed elements are // arr[i] and arr[j]. All elements between // arr[j+1] to arr[k-1] can form a triangle // with arr[i] and arr[j]. One is subtracted // from k because k is incremented one extra // in above while loop. k will always be // greater than j. If j becomes equal to k, // then above loop will increment k, because // arr[k] + arr[i] is always/ greater than // arr[k] if (k > j) count += k - j - 1; } } return count; } public static void main(String[] args) { int arr[] = { 10, 21, 22, 100, 101, 200, 300 }; System.out.println(\"Total number of triangles is \" + findNumberOfTriangles(arr)); }} // This code is contributed by Sania Kumari Gupta", "e": 59914, "s": 57549, "text": null }, { "code": "# Python function to count all possible triangles with arr[]# elements def findnumberofTriangles(arr): # Sort array and initialize count as 0 n = len(arr) arr.sort() count = 0 # Fix the first element. We need to run till n-3 as # the other two elements are selected from arr[i + 1...n-1] for i in range(0, n-2): # Initialize index of the rightmost third element k = i + 2 # Fix the second element for j in range(i + 1, n): # Find the rightmost element which is smaller # than the sum of two fixed elements # The important thing to note here is, we use # the previous value of k. If value of arr[i] + # arr[j-1] was greater than arr[k], then arr[i] + # arr[j] must be greater than k, because the array # is sorted. while (k < n and arr[i] + arr[j] > arr[k]): k += 1 # Total number of possible triangles that can be # formed with the two fixed elements is k - j - 1. # The two fixed elements are arr[i] and arr[j]. All # elements between arr[j + 1] to arr[k-1] can form a # triangle with arr[i] and arr[j]. One is subtracted # from k because k is incremented one extra in above # while loop. k will always be greater than j. If j # becomes equal to k, then above loop will increment k, # because arr[k] + arr[i] is always greater than arr[k] if(k>j): count += k - j - 1 return count # Driver function to test above functionarr = [10, 21, 22, 100, 101, 200, 300]print (\"Number of Triangles:\", findnumberofTriangles(arr)) # This code is contributed by Devesh Agrawal", "e": 61664, "s": 59914, "text": null }, { "code": "// C# program to count number// of triangles that can be// formed from given arrayusing System; class GFG { // Function to count all // possible triangles // with arr[] elements static int findNumberOfTriangles(int[] arr) { int n = arr.Length; // Sort the array elements // in non-decreasing order Array.Sort(arr); // Initialize count // of triangles int count = 0; // Fix the first element. We // need to run till n-3 as // the other two elements are // selected from arr[i+1...n-1] for (int i = 0; i < n - 2; ++i) { // Initialize index of the // rightmost third element int k = i + 2; // Fix the second element for (int j = i + 1; j < n; ++j) { /* Find the rightmost element which is smaller than the sum of two fixed elements. The important thing to note here is, we use the previous value of k. If value of arr[i] + arr[j-1] was greater than arr[k], then arr[i] + arr[j] must be greater than k, because the array is sorted. */ while (k < n && arr[i] + arr[j] > arr[k]) ++k; /* Total number of possible triangles that can be formed with the two fixed elements is k - j - 1. The two fixed elements are arr[i] and arr[j]. All elements between arr[j+1] to arr[k-1] can form a triangle with arr[i] and arr[j]. One is subtracted from k because k is incremented one extra in above while loop. k will always be greater than j. If j becomes equal to k, then above loop will increment k, because arr[k] + arr[i] is always/ greater than arr[k] */ if (k > j) count += k - j - 1; } } return count; } // Driver Code public static void Main() { int[] arr = { 10, 21, 22, 100, 101, 200, 300 }; Console.WriteLine(\"Total number of triangles is \" + findNumberOfTriangles(arr)); }} // This code is contributed by anuj_67.", "e": 64018, "s": 61664, "text": null }, { "code": "<?php// PHP program to count number// of triangles that can be// formed from given array // Function to count all// possible triangles with// arr[] elementfunction findNumberOfTriangles($arr){ $n = count($arr); // Sort the array elements // in non-decreasing order sort($arr); // Initialize count // of triangles $count = 0; // Fix the first element. // We need to run till n-3 // as the other two elements // are selected from // arr[i+1...n-1] for ($i = 0; $i < $n - 2; ++$i) { // Initialize index of the // rightmost third element $k = $i + 2; // Fix the second element for ($j = $i + 1; $j < $n; ++$j) { /* Find the rightmost element which is smaller than the sum of two fixed elements. The important thing to note here is, we use the previous value of k. If value of arr[i] + arr[j-1] was greater than arr[k], then arr[i] + arr[j] must be greater than k, because the array is sorted. */ while ($k < $n && $arr[$i] + $arr[$j] > $arr[$k]) ++$k; /* Total number of possible triangles that can be formed with the two fixed elements is k - j - 1. The two fixed elements are arr[i] and arr[j]. All elements between arr[j+1] to arr[k-1] can form a triangle with arr[i] and arr[j]. One is subtracted from k because k is incremented one extra in above while loop. k will always be greater than j. If j becomes equal to k, then above loop will increment k, because arr[k] + arr[i] is always/ greater than arr[k] */ if($k>$j) $count += $k - $j - 1; } } return $count;} // Driver code$arr = array(10, 21, 22, 100, 101, 200, 300);echo\"Total number of triangles is \", findNumberOfTriangles($arr); // This code is contributed by anuj_67.?>", "e": 66140, "s": 64018, "text": null }, { "code": "<script> // Javascript program to count number of triangles that can be// formed from given array // Function to count all possible triangles with arr[]// elementsfunction findNumberOfTriangles(arr){ let n = arr.length; // Sort the array elements in non-decreasing order arr.sort((a, b) => a-b); // Initialize count of triangles let count = 0; // Fix the first element. We // need to run till n-3 as // the other two elements are // selected from arr[i+1...n-1] for (let i = 0; i < n - 2; ++i) { // Initialize index of the // rightmost third element let k = i + 2; // Fix the second element for (let j = i + 1; j < n; ++j) { // Find the rightmost element which is // smaller than the sum of two fixed elements // The important thing to note here is, we // use the previous value of k. If value of // arr[i] + arr[j-1] was greater than arr[k], // then arr[i] + arr[j] must be greater than k, // because the array is sorted. while (k < n && arr[i] + arr[j] > arr[k]) ++k; // Total number of possible triangles that can // be formed with the two fixed elements is // k - j - 1. The two fixed elements are arr[i] // and arr[j]. All elements between arr[j+1]/ to // arr[k-1] can form a triangle with arr[i] and arr[j]. // One is subtracted from k because k is incremented // one extra in above while loop. // k will always be greater than j. If j becomes equal // to k, then above loop will increment k, because arr[k] // + arr[i] is always greater than arr[k] if (k > j) count += k - j - 1; } } return count;} // Driver code let arr = [ 10, 21, 22, 100, 101, 200, 300 ]; let size = arr.length; document.write(\"Total number of triangles possible is \" + findNumberOfTriangles(arr, size)); // This code is contributed by Manoj </script>", "e": 68231, "s": 66140, "text": null }, { "code": null, "e": 68271, "s": 68231, "text": "Total number of triangles possible is 6" }, { "code": null, "e": 68729, "s": 68273, "text": "Complexity Analysis: Time Complexity: O(n^2). The time complexity looks more because of 3 nested loops. It can be observed that k is initialized only once in the outermost loop. The innermost loop executes at most O(n) time for every iteration of the outermost loop, because k starts from i+2 and goes up to n for all values of j. Therefore, the time complexity is O(n^2).Space Complexity: O(1). No extra space is required. So space complexity is constant" }, { "code": null, "e": 69081, "s": 68729, "text": "Time Complexity: O(n^2). The time complexity looks more because of 3 nested loops. It can be observed that k is initialized only once in the outermost loop. The innermost loop executes at most O(n) time for every iteration of the outermost loop, because k starts from i+2 and goes up to n for all values of j. Therefore, the time complexity is O(n^2)." }, { "code": null, "e": 69165, "s": 69081, "text": "Space Complexity: O(1). No extra space is required. So space complexity is constant" }, { "code": null, "e": 69271, "s": 69165, "text": "Method 3: The time complexity can be greatly reduced using Two Pointer methods in just two nested loops. " }, { "code": null, "e": 69466, "s": 69271, "text": "Approach: First sort the array, and run a nested loop, fix an index and then try to fix an upper and lower index within which we can use all the lengths to form a triangle with that fixed index." }, { "code": null, "e": 70204, "s": 69466, "text": "Algorithm:Sort the array and then take three variables l, r and i, pointing to start, end-1 and array element starting from end of the array.Traverse the array from end (n-1 to 1), and for each iteration keep the value of l = 0 and r = i-1Now if a triangle can be formed using arr[l] and arr[r] then triangles can obviously formed from a[l+1], a[l+2].....a[r-1], arr[r] and a[i], because the array is sorted , which can be directly calculated using (r-l). and then decrement the value of r and continue the loop till l is less than rIf a triangle cannot be formed using arr[l] and arr[r] then increment the value of l and continue the loop till l is less than r So the overall complexity of iterating through all array elements reduces." }, { "code": null, "e": 70932, "s": 70204, "text": "Sort the array and then take three variables l, r and i, pointing to start, end-1 and array element starting from end of the array.Traverse the array from end (n-1 to 1), and for each iteration keep the value of l = 0 and r = i-1Now if a triangle can be formed using arr[l] and arr[r] then triangles can obviously formed from a[l+1], a[l+2].....a[r-1], arr[r] and a[i], because the array is sorted , which can be directly calculated using (r-l). and then decrement the value of r and continue the loop till l is less than rIf a triangle cannot be formed using arr[l] and arr[r] then increment the value of l and continue the loop till l is less than r So the overall complexity of iterating through all array elements reduces." }, { "code": null, "e": 71064, "s": 70932, "text": "Sort the array and then take three variables l, r and i, pointing to start, end-1 and array element starting from end of the array." }, { "code": null, "e": 71163, "s": 71064, "text": "Traverse the array from end (n-1 to 1), and for each iteration keep the value of l = 0 and r = i-1" }, { "code": null, "e": 71458, "s": 71163, "text": "Now if a triangle can be formed using arr[l] and arr[r] then triangles can obviously formed from a[l+1], a[l+2].....a[r-1], arr[r] and a[i], because the array is sorted , which can be directly calculated using (r-l). and then decrement the value of r and continue the loop till l is less than r" }, { "code": null, "e": 71589, "s": 71458, "text": "If a triangle cannot be formed using arr[l] and arr[r] then increment the value of l and continue the loop till l is less than r " }, { "code": null, "e": 71664, "s": 71589, "text": "So the overall complexity of iterating through all array elements reduces." }, { "code": null, "e": 71680, "s": 71664, "text": "Implementation:" }, { "code": null, "e": 71684, "s": 71680, "text": "C++" }, { "code": null, "e": 71689, "s": 71684, "text": "Java" }, { "code": null, "e": 71697, "s": 71689, "text": "Python3" }, { "code": null, "e": 71700, "s": 71697, "text": "C#" }, { "code": null, "e": 71711, "s": 71700, "text": "Javascript" }, { "code": "// C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; void CountTriangles(vector<int> A){ int n = A.size(); sort(A.begin(), A.end()); int count = 0; for (int i = n - 1; i >= 1; i--) { int l = 0, r = i - 1; while (l < r) { if (A[l] + A[r] > A[i]) { // If it is possible with a[l], a[r] // and a[i] then it is also possible // with a[l+1]..a[r-1], a[r] and a[i] count += r - l; // checking for more possible solutions r--; } else // if not possible check for // higher values of arr[l] l++; } } cout << \"No of possible solutions: \" << count;}int main(){ vector<int> A = { 4, 3, 5, 7, 6 }; CountTriangles(A);}", "e": 72574, "s": 71711, "text": null }, { "code": "// Java implementation of the above approachimport java.util.*; class GFG { static void CountTriangles(int[] A) { int n = A.length; Arrays.sort(A); int count = 0; for (int i = n - 1; i >= 1; i--) { int l = 0, r = i - 1; while (l < r) { if (A[l] + A[r] > A[i]) { // If it is possible with a[l], a[r] // and a[i] then it is also possible // with a[l+1]..a[r-1], a[r] and a[i] count += r - l; // checking for more possible solutions r--; } else // if not possible check for // higher values of arr[l] { l++; } } } System.out.print(\"No of possible solutions: \" + count); } // Driver Code public static void main(String[] args) { int[] A = { 4, 3, 5, 7, 6 }; CountTriangles(A); }} // This code is contributed by PrinciRaj1992", "e": 73635, "s": 72574, "text": null }, { "code": "# Python implementation of the above approachdef CountTriangles( A): n = len(A); A.sort(); count = 0; for i in range(n - 1, 0, -1): l = 0; r = i - 1; while(l < r): if(A[l] + A[r] > A[i]): # If it is possible with a[l], a[r] # and a[i] then it is also possible # with a[l + 1]..a[r-1], a[r] and a[i] count += r - l; # checking for more possible solutions r -= 1; else: # if not possible check for # higher values of arr[l] l += 1; print(\"No of possible solutions: \", count); # Driver Codeif __name__ == '__main__': A = [ 4, 3, 5, 7, 6 ]; CountTriangles(A); # This code is contributed by PrinciRaj1992", "e": 74464, "s": 73635, "text": null }, { "code": "// C# implementation of the above approachusing System; class GFG { static void CountTriangles(int[] A) { int n = A.Length; Array.Sort(A); int count = 0; for (int i = n - 1; i >= 1; i--) { int l = 0, r = i - 1; while (l < r) { if (A[l] + A[r] > A[i]) { // If it is possible with a[l], a[r] // and a[i] then it is also possible // with a[l+1]..a[r-1], a[r] and a[i] count += r - l; // checking for more possible solutions r--; } else // if not possible check for // higher values of arr[l] { l++; } } } Console.Write(\"No of possible solutions: \" + count); } // Driver Code public static void Main(String[] args) { int[] A = { 4, 3, 5, 7, 6 }; CountTriangles(A); }} // This code is contributed by Rajput-Ji", "e": 75509, "s": 74464, "text": null }, { "code": "<script>// javascript implementation of the above approach function CountTriangles(A) { var n = A.length; A.sort(); var count = 0; for (i = n - 1; i >= 1; i--) { var l = 0, r = i - 1; while (l < r) { if (A[l] + A[r] > A[i]) { // If it is possible with a[l], a[r] // and a[i] then it is also possible // with a[l+1]..a[r-1], a[r] and a[i] count += r - l; // checking for more possible solutions r--; } else // if not possible check for // higher values of arr[l] { l++; } } } document.write(\"No of possible solutions: \" + count); } // Driver Code var A = [ 4, 3, 5, 7, 6 ]; CountTriangles(A); // This code is contributed by aashish1995</script>", "e": 76465, "s": 75509, "text": null }, { "code": null, "e": 76493, "s": 76465, "text": "No of possible solutions: 9" }, { "code": null, "e": 76731, "s": 76495, "text": "Complexity Analysis: Time complexity: O(n^2). As two nested loops are used, but overall iterations in comparison to the above method reduces greatly.Space Complexity: O(1). As no extra space is required, so space complexity is constant" }, { "code": null, "e": 76860, "s": 76731, "text": "Time complexity: O(n^2). As two nested loops are used, but overall iterations in comparison to the above method reduces greatly." }, { "code": null, "e": 76947, "s": 76860, "text": "Space Complexity: O(1). As no extra space is required, so space complexity is constant" }, { "code": null, "e": 76952, "s": 76947, "text": "vt_m" }, { "code": null, "e": 76958, "s": 76952, "text": "cds91" }, { "code": null, "e": 76965, "s": 76958, "text": "md1844" }, { "code": null, "e": 76979, "s": 76965, "text": "rathbhupendra" }, { "code": null, "e": 76993, "s": 76979, "text": "princiraj1992" }, { "code": null, "e": 77003, "s": 76993, "text": "Rajput-Ji" }, { "code": null, "e": 77014, "s": 77003, "text": "andrew1234" }, { "code": null, "e": 77029, "s": 77014, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 77044, "s": 77029, "text": "winter_soldier" }, { "code": null, "e": 77060, "s": 77044, "text": "souravghosh0416" }, { "code": null, "e": 77072, "s": 77060, "text": "aashish1995" }, { "code": null, "e": 77081, "s": 77072, "text": "mank1083" }, { "code": null, "e": 77091, "s": 77081, "text": "swetakb15" }, { "code": null, "e": 77110, "s": 77091, "text": "surindertarika1234" }, { "code": null, "e": 77124, "s": 77110, "text": "rajatsangrame" }, { "code": null, "e": 77140, "s": 77124, "text": "amartyaghoshgfg" }, { "code": null, "e": 77152, "s": 77140, "text": "krisania804" }, { "code": null, "e": 77159, "s": 77152, "text": "Amazon" }, { "code": null, "e": 77168, "s": 77159, "text": "Linkedin" }, { "code": null, "e": 77177, "s": 77168, "text": "triangle" }, { "code": null, "e": 77183, "s": 77177, "text": "Wipro" }, { "code": null, "e": 77190, "s": 77183, "text": "Arrays" }, { "code": null, "e": 77203, "s": 77190, "text": "Mathematical" }, { "code": null, "e": 77210, "s": 77203, "text": "Amazon" }, { "code": null, "e": 77216, "s": 77210, "text": "Wipro" }, { "code": null, "e": 77225, "s": 77216, "text": "Linkedin" }, { "code": null, "e": 77232, "s": 77225, "text": "Arrays" }, { "code": null, "e": 77245, "s": 77232, "text": "Mathematical" }, { "code": null, "e": 77343, "s": 77245, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 77358, "s": 77343, "text": "Arrays in Java" }, { "code": null, "e": 77374, "s": 77358, "text": "Arrays in C/C++" }, { "code": null, "e": 77420, "s": 77374, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 77468, "s": 77420, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 77495, "s": 77468, "text": "Program for array rotation" }, { "code": null, "e": 77525, "s": 77495, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 77585, "s": 77525, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 77600, "s": 77585, "text": "C++ Data Types" }, { "code": null, "e": 77643, "s": 77600, "text": "Set in C++ Standard Template Library (STL)" } ]
Feature Reduction using Genetic Algorithm with Python | by Ahmed Gad | Towards Data Science
Using the raw data for training a machine learning algorithm might not be the suitable choice in some situations. The algorithm, when trained by raw data, has to do feature mining by itself for detecting the different groups from each other. But this requires large amounts of data for doing feature mining automatically. For small datasets, it is preferred that the data scientist do the feature mining step on its own and just tell the machine learning algorithm which feature set to use. The used feature set has to be representative of the data samples and thus we have to take care of selecting the best features. The data scientist suggests using some types of features that seems helpful in representing the data samples based on the previous experience. Some features might prove their robustness in representing the samples and others not. There might be some types of feature that might affect the results of the trained model wither by reducing the accuracy for classification problems or increasing the error for regression problems. For example, there might be some noise elements in the feature vector and thus they should get removed. The feature vector might also include 2 or more correlated elements. Just using one element will substitute for the other. In order to remove such types of elements, there are 2 helpful steps which are feature selection and reduction. This tutorial focuses on feature reduction. Assuming there are 3 features F1, F2, and F3 and each one has 3 feature elements. Thus, the feature vector length is 3x3=9. Feature selection just selects specific types of features and excludes the others. For example, just select F1 and F2 and remove F3. The feature vector length is now 6 rather than 9. In feature reduction, specific elements from each feature might be excluded. For example, this step might remove the first and third elements from F3 while keeping the second element. Thus, the feature vector length is reduced from 9 to just 7. Before starting in this tutorial, it is worth mentioning that it is an extension to a previously published 2 tutorials in my LinkedIn profile. The first tutorial is titled “Artificial Neural Network Implementation using NumPy and Classification of the Fruits360 Image Dataset”. It starts by extracting a feature vector of length 360 from 4 classes of the Fruits360 dataset. Then, it builds an artificial neural network (ANN) using NumPy from scratch in order to classify the dataset. It is available here https://www.linkedin.com/pulse/artificial-neural-network-implementation-using-numpy-fruits360-gad. Its GitHub project is available here: https://github.com/ahmedfgad/NumPyANN. The second tutorial is titled “Artificial Neural Networks Optimization using Genetic Algorithm”. It builds and uses the GA for optimizing the ANN parameters in order to increase the classification accuracy. It is available here https://www.linkedin.com/pulse/artificial-neural-networks-optimization-using-genetic-ahmed-gad. Its GitHub project is also available here: https://github.com/ahmedfgad/NeuralGenetic. This tutorial discusses how to use the genetic algorithm (GA) for reducing the feature vector extracted from the Fruits360 dataset of length 360. This tutorial starts by discussing the steps to be followed. After that, the steps are implemented in Python mainly using NumPy and Sklearn. The implementation of this tutorial is available in my GitHub page here: https://github.com/ahmedfgad/FeatureReductionGenetic GA starts from an initial population which consists of a number of chromosomes (i.e. solutions) where each chromosome has a sequence of genes. Using a fitness function, the GA selects the best solutions as parents for creating a new population. The new solutions in such a new population are created by applying 2 operations over the parents which are the crossover and the mutation. When applying GA to a given problem, we have to determine the representation of the gene, the suitable fitness function, and how the crossover and the mutation are applied. Let’s see how things work. You can read more about GA from the following resources I prepared: Introduction to Optimization with Genetic Algorithm https://www.linkedin.com/pulse/introduction-optimization-genetic-algorithm-ahmed-gad/ https://www.kdnuggets.com/2018/03/introduction-optimization-with-genetic-algorithm.html https://towardsdatascience.com/introduction-to-optimization-with-genetic-algorithm-2f5001d9964b Genetic Algorithm (GA) Optimization — Step-by-Step Example https://www.slideshare.net/AhmedGadFCIT/genetic-algorithm-ga-optimization-stepbystep-example Genetic Algorithm Implementation in Python https://www.linkedin.com/pulse/genetic-algorithm-implementation-python-ahmed-gad/ https://www.kdnuggets.com/2018/07/genetic-algorithm-implementation-python.html https://towardsdatascience.com/genetic-algorithm-implementation-in-python-5ab67bb124a6 https://github.com/ahmedfgad/GeneticAlgorithmPython I also wrote a book in 2018 that covers GA in one of its chapters. The book is cited as “Ahmed Fawzy Gad ‘Practical Computer Vision Applications Using Deep Learning with CNNs’. Dec. 2018, Apress, 978–1–4842–4167–7” which is available here at Springer https://www.springer.com/us/book/9781484241660. The gene in GA is the building block for the chromosome. At first, we need to determine what genes are inside the chromosome. To do that, take into regard that every property that may affect the results should be regarded as a gene. Because the target of our problem is selecting the best set of feature elements, thus every feature element might affect the results if selected or not. Thus, every feature element is regarded as a gene. The chromosome will consist of all genes (i.e. all feature elements). Because there are 360 feature elements, then there will be 360 genes. A good piece of information is now clear that the length of the chromosome is 360. After determining what are the selected genes, next is to determine the gene representation. There are different representations such as decimal, binary, float, string, and others. Our target is to know whether the gene (i.e. feature element) is selected or not in the reduced set of features. Thus, the value assigned to the gene should reflect whether it is selected or not. Based on this description, it is very clear that there are 2 possible values for each gene. One value signifies that the gene is selected and another when it is not selected. Thus, the binary representation is the best choice. When the gene value is 1, then it will be selected in the reduced feature set. When 0, then it will be neglected. As a summary, the chromosome will consist of 360 genes represented in binary. There is a one-to-one mapping between the feature vector and the chromosome according to the next figure. That is the first gene in the chromosome is linked to the first element in the feature vector. When the value for that gene is 1, this means the first element in the feature vector is selected. By getting how to create the chromosome, the initial population can be initialized randomly easily is NumPy. After being initialized, the parents are selected. GA is based on Darwin’s theory “Survival of the Fittest”. That is the best solutions in the current population are selected for mating in order to produce better solutions. By keeping the good solutions and killing the bad solutions, we can reach an optimal or semi-optimal solution. The criterion used for selecting the parents is the fitness value associated with each solution (i.e. chromosome). The higher the fitness value the better the solution. The fitness value is calculated using a fitness function. So, what is the best function for use in our problem? The target of our problem is creating a reduced feature vector that increases the classification accuracy. Thus, the criterion that judges whether a solution is good or not is the classification accuracy. As a result, the fitness function will return a number that specifies the classification accuracy for each solution. The higher the accuracy the better the solution. In order to return a classification accuracy, there must be a machine learning model to get trained by the feature elements returned by each solution. We will use the support vector classifier (SVC) for this case. The dataset is divided into train and test samples. Based on the train data, the SVC will be trained using the selected feature elements by each solution in the population. After being trained, it will be tested according to the test data. Based on the fitness value of each solution, we can select the best of them as parents. These parents are placed together in the mating pool for generating offspring which will be the members of the new population of the next generation. Such offspring are created by applying the crossover and mutation operations over the selected parents. Let’s configure such operations as discussed next. Based on the fitness function, we can filter the solutions in the current population for selecting the best of them which are called the parents. GA assumes that mating 2 good solutions will produce a third better solution. Mating means exchanging some genes from 2 parents. The genes are exchanged using the crossover operation. There are different ways in which such an operation can be applied. This tutorial uses the single-point crossover in which a point divides the chromosome. Genes before the point are taken from one solution and genes after the point are taken from the other solution. By just applying crossover, all genes are taken from the previous parents. There is no new gene introduced in the new offspring. If there is a bad gene in all parents, then this gene will be transferred to the offspring. For such a reason, the mutation operation is applied in order to introduce new genes in the offspring. In the binary representation of the genes, the mutation is applied by flipping the values of some randomly selected genes. If the gene value is 1, then it will be 0 and vice versa. After generating the offspring, we can create the new population of the next generation. This population consists of the previous parents in addition to the offspring. At this point, all steps are discussed. Next is to implement them in Python. Note that I wrote a previous tutorial titled “Genetic Algorithm Implementation in Python” for implementing the GA in Python which I will just modify its code for working with our problem. It is better to read it. The project is organized into 2 files. One file is named “GA.py” which holds the implementation of the GA steps as functions. Another file, which is the main file, just imports this file and calls its function within a loop that iterates through the generations. The main file starts by reading the features extracted from the Fruits360 dataset according to the code below. The features are returned into the data_inputs variable. Details about extracting these features are available in the 2 tutorials referred to at the beginning of the tutorial. The file also reads the class labels associated with the samples in the variable data_outputs. Some samples are selected for training with their indices stored in the train_indices variable. Similarly, the test samples indices are stored in the test_indices variable. import numpyimport GAimport pickleimport matplotlib.pyplotf = open("dataset_features.pkl", "rb")data_inputs = pickle.load(f)f.close()f = open("outputs.pkl", "rb")data_outputs = pickle.load(f)f.close()num_samples = data_inputs.shape[0]num_feature_elements = data_inputs.shape[1]train_indices = numpy.arange(1, num_samples, 4)test_indices = numpy.arange(0, num_samples, 4)print("Number of training samples: ", train_indices.shape[0])print("Number of test samples: ", test_indices.shape[0])"""Genetic algorithm parameters: Population size Mating pool size Number of mutations"""sol_per_pop = 8 # Population size.num_parents_mating = 4 # Number of parents inside the mating pool.num_mutations = 3 # Number of elements to mutate.# Defining the population shape.pop_shape = (sol_per_pop, num_feature_elements) # Creating the initial population.new_population = numpy.random.randint(low=0, high=2, size=pop_shape)print(new_population.shape) best_outputs = []num_generations = 100 It initializes all parameters of GA. This includes the number of solutions per population which is set to 8 according to the sol_per_pop variable, number of offspring which is set to 4 in the num_parents_mating variable, and number of mutations which is set to 3 in the num_mutations variable. After that, it creates the initial population randomly in a variable called new_population. There is an empty list named best_outputs which holds the best result after each generation. This helps to visualize the progress of the GA after finishing all generations. The number of generations is set to 100 in the num_generations variable. Note that you can change all of these parameters which might give better results. After preparing the features, class labels, and the GA parameters, we can go through the iterations of the GA according to the next code. At first, the fitness value for all solutions is calculated by calling the fitness function named cal_pop_fitness() defined in the GA file. This function accepts the current population, the extracted features, the class labels, the train indices, and the test indices. The function returns the fitness value for all solutions in a variable named fitness. Remember that the fitness value represents the classification accuracy. The best (i.e. highest) classification accuracy is saved into the best_outputs list. Based on the calculated fitness values, the best solutions which has the highest classification accuracies are selected as parents in the mating pool using the select_mating_pool() function defined in the GA.py file. It accepts the current population, fitness values, and the number of parents to return. It returns the selected parents into the parents variable. for generation in range(num_generations): print("Generation : ", generation) # Measuring the fitness of each chromosome in the population. fitness = GA.cal_pop_fitness(new_population, data_inputs, data_outputs, train_indices, test_indices) best_outputs.append(numpy.max(fitness)) # The best result in the current iteration. print("Best result : ", best_outputs[-1]) # Selecting the best parents in the population for mating. parents = GA.select_mating_pool(new_population, fitness, num_parents_mating) # Generating next generation using crossover. offspring_crossover = GA.crossover(parents, offspring_size=(pop_shape[0]-parents.shape[0], num_feature_elements)) # Adding some variations to the offspring using mutation. offspring_mutation = GA.mutation(offspring_crossover, num_mutations=num_mutations) # Creating the new population based on the parents and offspring. new_population[0:parents.shape[0], :] = parents new_population[parents.shape[0]:, :] = offspring_mutation Next is to apply the crossover operation over the selected parents to create the offspring. This is done inside the crossover() function defined in the GA.py file. It accepts the parents and the shape of the offspring array to be returned later into the offspring_crossover variable. The mutation operation is then applied over that array using the mutation() function which is also available within the GA.py file. In addition to the crossover results, this function accepts the number of mutations. Because the new population consists of the selected parents in addition to the offspring, both the parents and the offspring_mutation arrays are saved into the new_population variable. After that, a new generation is applied over the new population. After all generations complete, the next code is executed in order to return the best selected set of feature elements and the number of selected elements. After the 100 generations complete, the algorithm used 174 feature elements in order to reach an accuracy of 99.59%. fitness = GA.cal_pop_fitness(new_population, data_inputs, data_outputs, train_indices, test_indices)# Then return the index of that solution corresponding to the best fitness.best_match_idx = numpy.where(fitness == numpy.max(fitness))[0]best_match_idx = best_match_idx[0]best_solution = new_population[best_match_idx, :]best_solution_indices = numpy.where(best_solution == 1)[0]best_solution_num_elements = best_solution_indices.shape[0]best_solution_fitness = fitness[best_match_idx]print("best_match_idx : ", best_match_idx)print("best_solution : ", best_solution)print("Selected indices : ", best_solution_indices)print("Number of selected elements : ", best_solution_num_elements)print("Best solution fitness : ", best_solution_fitness)matplotlib.pyplot.plot(best_outputs)matplotlib.pyplot.xlabel("Iteration")matplotlib.pyplot.ylabel("Fitness")matplotlib.pyplot.show() The above code also displays a figure showing the progress of the GA over all generations which is shown below. Here is the complete code of the main file. import numpyimport GAimport pickleimport matplotlib.pyplotf = open("dataset_features.pkl", "rb")data_inputs = pickle.load(f)f.close()f = open("outputs.pkl", "rb")data_outputs = pickle.load(f)f.close()num_samples = data_inputs.shape[0]num_feature_elements = data_inputs.shape[1]train_indices = numpy.arange(1, num_samples, 4)test_indices = numpy.arange(0, num_samples, 4)print("Number of training samples: ", train_indices.shape[0])print("Number of test samples: ", test_indices.shape[0])"""Genetic algorithm parameters: Population size Mating pool size Number of mutations"""sol_per_pop = 8 # Population size.num_parents_mating = 4 # Number of parents inside the mating pool.num_mutations = 3 # Number of elements to mutate.# Defining the population shape.pop_shape = (sol_per_pop, num_feature_elements)# Creating the initial population.new_population = numpy.random.randint(low=0, high=2, size=pop_shape)print(new_population.shape)best_outputs = []num_generations = 100for generation in range(num_generations): print("Generation : ", generation) # Measuring the fitness of each chromosome in the population. fitness = GA.cal_pop_fitness(new_population, data_inputs, data_outputs, train_indices, test_indices) best_outputs.append(numpy.max(fitness)) # The best result in the current iteration. print("Best result : ", best_outputs[-1]) # Selecting the best parents in the population for mating. parents = GA.select_mating_pool(new_population, fitness, num_parents_mating) # Generating next generation using crossover. offspring_crossover = GA.crossover(parents, offspring_size=(pop_shape[0]-parents.shape[0], num_feature_elements)) # Adding some variations to the offspring using mutation. offspring_mutation = GA.mutation(offspring_crossover, num_mutations=num_mutations) # Creating the new population based on the parents and offspring. new_population[0:parents.shape[0], :] = parents new_population[parents.shape[0]:, :] = offspring_mutation# Getting the best solution after iterating finishing all generations.# At first, the fitness is calculated for each solution in the final generation.fitness = GA.cal_pop_fitness(new_population, data_inputs, data_outputs, train_indices, test_indices)# Then return the index of that solution corresponding to the best fitness.best_match_idx = numpy.where(fitness == numpy.max(fitness))[0]best_match_idx = best_match_idx[0]best_solution = new_population[best_match_idx, :]best_solution_indices = numpy.where(best_solution == 1)[0]best_solution_num_elements = best_solution_indices.shape[0]best_solution_fitness = fitness[best_match_idx]print("best_match_idx : ", best_match_idx)print("best_solution : ", best_solution)print("Selected indices : ", best_solution_indices)print("Number of selected elements : ", best_solution_num_elements)print("Best solution fitness : ", best_solution_fitness)matplotlib.pyplot.plot(best_outputs)matplotlib.pyplot.xlabel("Iteration")matplotlib.pyplot.ylabel("Fitness")matplotlib.pyplot.show() The implementation of the GA.py file is listed below. Within the cal_pop_fitness() function, the SVC is trained according to the selected feature elements by each solution. Before being trained, the features are filtered according to the selected elements whose genes are given a value of 1. This is done inside the reduce_features() function. It accepts the current solution in addition to the complete features for all samples. After being trained, its classification accuracy is calculated using the classification_accuracy() function. This function returns the accuracy which is stored into an array named accuracies within the cal_pop_fitness() function. The implementation of the crossover() and mutation() functions are very similar to what is discussed in my previous tutorial titled “Genetic Algorithm Implementation in Python”. One major difference is that the mutation() function changes the randomly selected genes by flipping their values because we are using binary representation. import numpyimport sklearn.svmdef reduce_features(solution, features): selected_elements_indices = numpy.where(solution == 1)[0] reduced_features = features[:, selected_elements_indices] return reduced_featuresdef classification_accuracy(labels, predictions): correct = numpy.where(labels == predictions)[0] accuracy = correct.shape[0]/labels.shape[0] return accuracydef cal_pop_fitness(pop, features, labels, train_indices, test_indices): accuracies = numpy.zeros(pop.shape[0]) idx = 0 for curr_solution in pop: reduced_features = reduce_features(curr_solution, features) train_data = reduced_features[train_indices, :] test_data = reduced_features[test_indices, :] train_labels = labels[train_indices] test_labels = labels[test_indices] SV_classifier = sklearn.svm.SVC(gamma='scale') SV_classifier.fit(X=train_data, y=train_labels) predictions = SV_classifier.predict(test_data) accuracies[idx] = classification_accuracy(test_labels, predictions) idx = idx + 1 return accuraciesdef select_mating_pool(pop, fitness, num_parents): # Selecting the best individuals in the current generation as parents for producing the offspring of the next generation. parents = numpy.empty((num_parents, pop.shape[1])) for parent_num in range(num_parents): max_fitness_idx = numpy.where(fitness == numpy.max(fitness)) max_fitness_idx = max_fitness_idx[0][0] parents[parent_num, :] = pop[max_fitness_idx, :] fitness[max_fitness_idx] = -99999999999 return parentsdef crossover(parents, offspring_size): offspring = numpy.empty(offspring_size) # The point at which crossover takes place between two parents. Usually, it is at the center. crossover_point = numpy.uint8(offspring_size[1]/2) for k in range(offspring_size[0]): # Index of the first parent to mate. parent1_idx = k%parents.shape[0] # Index of the second parent to mate. parent2_idx = (k+1)%parents.shape[0] # The new offspring will have its first half of its genes taken from the first parent. offspring[k, 0:crossover_point] = parents[parent1_idx, 0:crossover_point] # The new offspring will have its second half of its genes taken from the second parent. offspring[k, crossover_point:] = parents[parent2_idx, crossover_point:] return offspringdef mutation(offspring_crossover, num_mutations=2): mutation_idx = numpy.random.randint(low=0, high=offspring_crossover.shape[1], size=num_mutations) # Mutation changes a single gene in each offspring randomly. for idx in range(offspring_crossover.shape[0]): # The random value to be added to the gene. offspring_crossover[idx, mutation_idx] = 1 - offspring_crossover[idx, mutation_idx] return offspring_crossover
[ { "code": null, "e": 662, "s": 171, "text": "Using the raw data for training a machine learning algorithm might not be the suitable choice in some situations. The algorithm, when trained by raw data, has to do feature mining by itself for detecting the different groups from each other. But this requires large amounts of data for doing feature mining automatically. For small datasets, it is preferred that the data scientist do the feature mining step on its own and just tell the machine learning algorithm which feature set to use." }, { "code": null, "e": 1020, "s": 662, "text": "The used feature set has to be representative of the data samples and thus we have to take care of selecting the best features. The data scientist suggests using some types of features that seems helpful in representing the data samples based on the previous experience. Some features might prove their robustness in representing the samples and others not." }, { "code": null, "e": 1600, "s": 1020, "text": "There might be some types of feature that might affect the results of the trained model wither by reducing the accuracy for classification problems or increasing the error for regression problems. For example, there might be some noise elements in the feature vector and thus they should get removed. The feature vector might also include 2 or more correlated elements. Just using one element will substitute for the other. In order to remove such types of elements, there are 2 helpful steps which are feature selection and reduction. This tutorial focuses on feature reduction." }, { "code": null, "e": 2152, "s": 1600, "text": "Assuming there are 3 features F1, F2, and F3 and each one has 3 feature elements. Thus, the feature vector length is 3x3=9. Feature selection just selects specific types of features and excludes the others. For example, just select F1 and F2 and remove F3. The feature vector length is now 6 rather than 9. In feature reduction, specific elements from each feature might be excluded. For example, this step might remove the first and third elements from F3 while keeping the second element. Thus, the feature vector length is reduced from 9 to just 7." }, { "code": null, "e": 2295, "s": 2152, "text": "Before starting in this tutorial, it is worth mentioning that it is an extension to a previously published 2 tutorials in my LinkedIn profile." }, { "code": null, "e": 2833, "s": 2295, "text": "The first tutorial is titled “Artificial Neural Network Implementation using NumPy and Classification of the Fruits360 Image Dataset”. It starts by extracting a feature vector of length 360 from 4 classes of the Fruits360 dataset. Then, it builds an artificial neural network (ANN) using NumPy from scratch in order to classify the dataset. It is available here https://www.linkedin.com/pulse/artificial-neural-network-implementation-using-numpy-fruits360-gad. Its GitHub project is available here: https://github.com/ahmedfgad/NumPyANN." }, { "code": null, "e": 3244, "s": 2833, "text": "The second tutorial is titled “Artificial Neural Networks Optimization using Genetic Algorithm”. It builds and uses the GA for optimizing the ANN parameters in order to increase the classification accuracy. It is available here https://www.linkedin.com/pulse/artificial-neural-networks-optimization-using-genetic-ahmed-gad. Its GitHub project is also available here: https://github.com/ahmedfgad/NeuralGenetic." }, { "code": null, "e": 3531, "s": 3244, "text": "This tutorial discusses how to use the genetic algorithm (GA) for reducing the feature vector extracted from the Fruits360 dataset of length 360. This tutorial starts by discussing the steps to be followed. After that, the steps are implemented in Python mainly using NumPy and Sklearn." }, { "code": null, "e": 3657, "s": 3531, "text": "The implementation of this tutorial is available in my GitHub page here: https://github.com/ahmedfgad/FeatureReductionGenetic" }, { "code": null, "e": 4241, "s": 3657, "text": "GA starts from an initial population which consists of a number of chromosomes (i.e. solutions) where each chromosome has a sequence of genes. Using a fitness function, the GA selects the best solutions as parents for creating a new population. The new solutions in such a new population are created by applying 2 operations over the parents which are the crossover and the mutation. When applying GA to a given problem, we have to determine the representation of the gene, the suitable fitness function, and how the crossover and the mutation are applied. Let’s see how things work." }, { "code": null, "e": 4309, "s": 4241, "text": "You can read more about GA from the following resources I prepared:" }, { "code": null, "e": 4361, "s": 4309, "text": "Introduction to Optimization with Genetic Algorithm" }, { "code": null, "e": 4447, "s": 4361, "text": "https://www.linkedin.com/pulse/introduction-optimization-genetic-algorithm-ahmed-gad/" }, { "code": null, "e": 4535, "s": 4447, "text": "https://www.kdnuggets.com/2018/03/introduction-optimization-with-genetic-algorithm.html" }, { "code": null, "e": 4631, "s": 4535, "text": "https://towardsdatascience.com/introduction-to-optimization-with-genetic-algorithm-2f5001d9964b" }, { "code": null, "e": 4690, "s": 4631, "text": "Genetic Algorithm (GA) Optimization — Step-by-Step Example" }, { "code": null, "e": 4783, "s": 4690, "text": "https://www.slideshare.net/AhmedGadFCIT/genetic-algorithm-ga-optimization-stepbystep-example" }, { "code": null, "e": 4826, "s": 4783, "text": "Genetic Algorithm Implementation in Python" }, { "code": null, "e": 4908, "s": 4826, "text": "https://www.linkedin.com/pulse/genetic-algorithm-implementation-python-ahmed-gad/" }, { "code": null, "e": 4987, "s": 4908, "text": "https://www.kdnuggets.com/2018/07/genetic-algorithm-implementation-python.html" }, { "code": null, "e": 5074, "s": 4987, "text": "https://towardsdatascience.com/genetic-algorithm-implementation-in-python-5ab67bb124a6" }, { "code": null, "e": 5126, "s": 5074, "text": "https://github.com/ahmedfgad/GeneticAlgorithmPython" }, { "code": null, "e": 5425, "s": 5126, "text": "I also wrote a book in 2018 that covers GA in one of its chapters. The book is cited as “Ahmed Fawzy Gad ‘Practical Computer Vision Applications Using Deep Learning with CNNs’. Dec. 2018, Apress, 978–1–4842–4167–7” which is available here at Springer https://www.springer.com/us/book/9781484241660." }, { "code": null, "e": 6085, "s": 5425, "text": "The gene in GA is the building block for the chromosome. At first, we need to determine what genes are inside the chromosome. To do that, take into regard that every property that may affect the results should be regarded as a gene. Because the target of our problem is selecting the best set of feature elements, thus every feature element might affect the results if selected or not. Thus, every feature element is regarded as a gene. The chromosome will consist of all genes (i.e. all feature elements). Because there are 360 feature elements, then there will be 360 genes. A good piece of information is now clear that the length of the chromosome is 360." }, { "code": null, "e": 6803, "s": 6085, "text": "After determining what are the selected genes, next is to determine the gene representation. There are different representations such as decimal, binary, float, string, and others. Our target is to know whether the gene (i.e. feature element) is selected or not in the reduced set of features. Thus, the value assigned to the gene should reflect whether it is selected or not. Based on this description, it is very clear that there are 2 possible values for each gene. One value signifies that the gene is selected and another when it is not selected. Thus, the binary representation is the best choice. When the gene value is 1, then it will be selected in the reduced feature set. When 0, then it will be neglected." }, { "code": null, "e": 7181, "s": 6803, "text": "As a summary, the chromosome will consist of 360 genes represented in binary. There is a one-to-one mapping between the feature vector and the chromosome according to the next figure. That is the first gene in the chromosome is linked to the first element in the feature vector. When the value for that gene is 1, this means the first element in the feature vector is selected." }, { "code": null, "e": 7625, "s": 7181, "text": "By getting how to create the chromosome, the initial population can be initialized randomly easily is NumPy. After being initialized, the parents are selected. GA is based on Darwin’s theory “Survival of the Fittest”. That is the best solutions in the current population are selected for mating in order to produce better solutions. By keeping the good solutions and killing the bad solutions, we can reach an optimal or semi-optimal solution." }, { "code": null, "e": 8277, "s": 7625, "text": "The criterion used for selecting the parents is the fitness value associated with each solution (i.e. chromosome). The higher the fitness value the better the solution. The fitness value is calculated using a fitness function. So, what is the best function for use in our problem? The target of our problem is creating a reduced feature vector that increases the classification accuracy. Thus, the criterion that judges whether a solution is good or not is the classification accuracy. As a result, the fitness function will return a number that specifies the classification accuracy for each solution. The higher the accuracy the better the solution." }, { "code": null, "e": 8491, "s": 8277, "text": "In order to return a classification accuracy, there must be a machine learning model to get trained by the feature elements returned by each solution. We will use the support vector classifier (SVC) for this case." }, { "code": null, "e": 8731, "s": 8491, "text": "The dataset is divided into train and test samples. Based on the train data, the SVC will be trained using the selected feature elements by each solution in the population. After being trained, it will be tested according to the test data." }, { "code": null, "e": 9124, "s": 8731, "text": "Based on the fitness value of each solution, we can select the best of them as parents. These parents are placed together in the mating pool for generating offspring which will be the members of the new population of the next generation. Such offspring are created by applying the crossover and mutation operations over the selected parents. Let’s configure such operations as discussed next." }, { "code": null, "e": 9721, "s": 9124, "text": "Based on the fitness function, we can filter the solutions in the current population for selecting the best of them which are called the parents. GA assumes that mating 2 good solutions will produce a third better solution. Mating means exchanging some genes from 2 parents. The genes are exchanged using the crossover operation. There are different ways in which such an operation can be applied. This tutorial uses the single-point crossover in which a point divides the chromosome. Genes before the point are taken from one solution and genes after the point are taken from the other solution." }, { "code": null, "e": 10226, "s": 9721, "text": "By just applying crossover, all genes are taken from the previous parents. There is no new gene introduced in the new offspring. If there is a bad gene in all parents, then this gene will be transferred to the offspring. For such a reason, the mutation operation is applied in order to introduce new genes in the offspring. In the binary representation of the genes, the mutation is applied by flipping the values of some randomly selected genes. If the gene value is 1, then it will be 0 and vice versa." }, { "code": null, "e": 10394, "s": 10226, "text": "After generating the offspring, we can create the new population of the next generation. This population consists of the previous parents in addition to the offspring." }, { "code": null, "e": 10684, "s": 10394, "text": "At this point, all steps are discussed. Next is to implement them in Python. Note that I wrote a previous tutorial titled “Genetic Algorithm Implementation in Python” for implementing the GA in Python which I will just modify its code for working with our problem. It is better to read it." }, { "code": null, "e": 10947, "s": 10684, "text": "The project is organized into 2 files. One file is named “GA.py” which holds the implementation of the GA steps as functions. Another file, which is the main file, just imports this file and calls its function within a loop that iterates through the generations." }, { "code": null, "e": 11329, "s": 10947, "text": "The main file starts by reading the features extracted from the Fruits360 dataset according to the code below. The features are returned into the data_inputs variable. Details about extracting these features are available in the 2 tutorials referred to at the beginning of the tutorial. The file also reads the class labels associated with the samples in the variable data_outputs." }, { "code": null, "e": 11502, "s": 11329, "text": "Some samples are selected for training with their indices stored in the train_indices variable. Similarly, the test samples indices are stored in the test_indices variable." }, { "code": null, "e": 12484, "s": 11502, "text": "import numpyimport GAimport pickleimport matplotlib.pyplotf = open(\"dataset_features.pkl\", \"rb\")data_inputs = pickle.load(f)f.close()f = open(\"outputs.pkl\", \"rb\")data_outputs = pickle.load(f)f.close()num_samples = data_inputs.shape[0]num_feature_elements = data_inputs.shape[1]train_indices = numpy.arange(1, num_samples, 4)test_indices = numpy.arange(0, num_samples, 4)print(\"Number of training samples: \", train_indices.shape[0])print(\"Number of test samples: \", test_indices.shape[0])\"\"\"Genetic algorithm parameters: Population size Mating pool size Number of mutations\"\"\"sol_per_pop = 8 # Population size.num_parents_mating = 4 # Number of parents inside the mating pool.num_mutations = 3 # Number of elements to mutate.# Defining the population shape.pop_shape = (sol_per_pop, num_feature_elements) # Creating the initial population.new_population = numpy.random.randint(low=0, high=2, size=pop_shape)print(new_population.shape) best_outputs = []num_generations = 100" }, { "code": null, "e": 12870, "s": 12484, "text": "It initializes all parameters of GA. This includes the number of solutions per population which is set to 8 according to the sol_per_pop variable, number of offspring which is set to 4 in the num_parents_mating variable, and number of mutations which is set to 3 in the num_mutations variable. After that, it creates the initial population randomly in a variable called new_population." }, { "code": null, "e": 13198, "s": 12870, "text": "There is an empty list named best_outputs which holds the best result after each generation. This helps to visualize the progress of the GA after finishing all generations. The number of generations is set to 100 in the num_generations variable. Note that you can change all of these parameters which might give better results." }, { "code": null, "e": 13848, "s": 13198, "text": "After preparing the features, class labels, and the GA parameters, we can go through the iterations of the GA according to the next code. At first, the fitness value for all solutions is calculated by calling the fitness function named cal_pop_fitness() defined in the GA file. This function accepts the current population, the extracted features, the class labels, the train indices, and the test indices. The function returns the fitness value for all solutions in a variable named fitness. Remember that the fitness value represents the classification accuracy. The best (i.e. highest) classification accuracy is saved into the best_outputs list." }, { "code": null, "e": 14212, "s": 13848, "text": "Based on the calculated fitness values, the best solutions which has the highest classification accuracies are selected as parents in the mating pool using the select_mating_pool() function defined in the GA.py file. It accepts the current population, fitness values, and the number of parents to return. It returns the selected parents into the parents variable." }, { "code": null, "e": 15232, "s": 14212, "text": "for generation in range(num_generations): print(\"Generation : \", generation) # Measuring the fitness of each chromosome in the population. fitness = GA.cal_pop_fitness(new_population, data_inputs, data_outputs, train_indices, test_indices) best_outputs.append(numpy.max(fitness)) # The best result in the current iteration. print(\"Best result : \", best_outputs[-1]) # Selecting the best parents in the population for mating. parents = GA.select_mating_pool(new_population, fitness, num_parents_mating) # Generating next generation using crossover. offspring_crossover = GA.crossover(parents, offspring_size=(pop_shape[0]-parents.shape[0], num_feature_elements)) # Adding some variations to the offspring using mutation. offspring_mutation = GA.mutation(offspring_crossover, num_mutations=num_mutations) # Creating the new population based on the parents and offspring. new_population[0:parents.shape[0], :] = parents new_population[parents.shape[0]:, :] = offspring_mutation" }, { "code": null, "e": 15733, "s": 15232, "text": "Next is to apply the crossover operation over the selected parents to create the offspring. This is done inside the crossover() function defined in the GA.py file. It accepts the parents and the shape of the offspring array to be returned later into the offspring_crossover variable. The mutation operation is then applied over that array using the mutation() function which is also available within the GA.py file. In addition to the crossover results, this function accepts the number of mutations." }, { "code": null, "e": 15983, "s": 15733, "text": "Because the new population consists of the selected parents in addition to the offspring, both the parents and the offspring_mutation arrays are saved into the new_population variable. After that, a new generation is applied over the new population." }, { "code": null, "e": 16256, "s": 15983, "text": "After all generations complete, the next code is executed in order to return the best selected set of feature elements and the number of selected elements. After the 100 generations complete, the algorithm used 174 feature elements in order to reach an accuracy of 99.59%." }, { "code": null, "e": 17129, "s": 16256, "text": "fitness = GA.cal_pop_fitness(new_population, data_inputs, data_outputs, train_indices, test_indices)# Then return the index of that solution corresponding to the best fitness.best_match_idx = numpy.where(fitness == numpy.max(fitness))[0]best_match_idx = best_match_idx[0]best_solution = new_population[best_match_idx, :]best_solution_indices = numpy.where(best_solution == 1)[0]best_solution_num_elements = best_solution_indices.shape[0]best_solution_fitness = fitness[best_match_idx]print(\"best_match_idx : \", best_match_idx)print(\"best_solution : \", best_solution)print(\"Selected indices : \", best_solution_indices)print(\"Number of selected elements : \", best_solution_num_elements)print(\"Best solution fitness : \", best_solution_fitness)matplotlib.pyplot.plot(best_outputs)matplotlib.pyplot.xlabel(\"Iteration\")matplotlib.pyplot.ylabel(\"Fitness\")matplotlib.pyplot.show()" }, { "code": null, "e": 17241, "s": 17129, "text": "The above code also displays a figure showing the progress of the GA over all generations which is shown below." }, { "code": null, "e": 17285, "s": 17241, "text": "Here is the complete code of the main file." }, { "code": null, "e": 20306, "s": 17285, "text": "import numpyimport GAimport pickleimport matplotlib.pyplotf = open(\"dataset_features.pkl\", \"rb\")data_inputs = pickle.load(f)f.close()f = open(\"outputs.pkl\", \"rb\")data_outputs = pickle.load(f)f.close()num_samples = data_inputs.shape[0]num_feature_elements = data_inputs.shape[1]train_indices = numpy.arange(1, num_samples, 4)test_indices = numpy.arange(0, num_samples, 4)print(\"Number of training samples: \", train_indices.shape[0])print(\"Number of test samples: \", test_indices.shape[0])\"\"\"Genetic algorithm parameters: Population size Mating pool size Number of mutations\"\"\"sol_per_pop = 8 # Population size.num_parents_mating = 4 # Number of parents inside the mating pool.num_mutations = 3 # Number of elements to mutate.# Defining the population shape.pop_shape = (sol_per_pop, num_feature_elements)# Creating the initial population.new_population = numpy.random.randint(low=0, high=2, size=pop_shape)print(new_population.shape)best_outputs = []num_generations = 100for generation in range(num_generations): print(\"Generation : \", generation) # Measuring the fitness of each chromosome in the population. fitness = GA.cal_pop_fitness(new_population, data_inputs, data_outputs, train_indices, test_indices) best_outputs.append(numpy.max(fitness)) # The best result in the current iteration. print(\"Best result : \", best_outputs[-1]) # Selecting the best parents in the population for mating. parents = GA.select_mating_pool(new_population, fitness, num_parents_mating) # Generating next generation using crossover. offspring_crossover = GA.crossover(parents, offspring_size=(pop_shape[0]-parents.shape[0], num_feature_elements)) # Adding some variations to the offspring using mutation. offspring_mutation = GA.mutation(offspring_crossover, num_mutations=num_mutations) # Creating the new population based on the parents and offspring. new_population[0:parents.shape[0], :] = parents new_population[parents.shape[0]:, :] = offspring_mutation# Getting the best solution after iterating finishing all generations.# At first, the fitness is calculated for each solution in the final generation.fitness = GA.cal_pop_fitness(new_population, data_inputs, data_outputs, train_indices, test_indices)# Then return the index of that solution corresponding to the best fitness.best_match_idx = numpy.where(fitness == numpy.max(fitness))[0]best_match_idx = best_match_idx[0]best_solution = new_population[best_match_idx, :]best_solution_indices = numpy.where(best_solution == 1)[0]best_solution_num_elements = best_solution_indices.shape[0]best_solution_fitness = fitness[best_match_idx]print(\"best_match_idx : \", best_match_idx)print(\"best_solution : \", best_solution)print(\"Selected indices : \", best_solution_indices)print(\"Number of selected elements : \", best_solution_num_elements)print(\"Best solution fitness : \", best_solution_fitness)matplotlib.pyplot.plot(best_outputs)matplotlib.pyplot.xlabel(\"Iteration\")matplotlib.pyplot.ylabel(\"Fitness\")matplotlib.pyplot.show()" }, { "code": null, "e": 20736, "s": 20306, "text": "The implementation of the GA.py file is listed below. Within the cal_pop_fitness() function, the SVC is trained according to the selected feature elements by each solution. Before being trained, the features are filtered according to the selected elements whose genes are given a value of 1. This is done inside the reduce_features() function. It accepts the current solution in addition to the complete features for all samples." }, { "code": null, "e": 20966, "s": 20736, "text": "After being trained, its classification accuracy is calculated using the classification_accuracy() function. This function returns the accuracy which is stored into an array named accuracies within the cal_pop_fitness() function." }, { "code": null, "e": 21302, "s": 20966, "text": "The implementation of the crossover() and mutation() functions are very similar to what is discussed in my previous tutorial titled “Genetic Algorithm Implementation in Python”. One major difference is that the mutation() function changes the randomly selected genes by flipping their values because we are using binary representation." } ]
What is the cause of NoSuchElementException and how can we fix it in java?
What is the cause of NoSuchElementException and how can we fix it in java? An exception is an issue (run time error) occurred during the execution of a program. When an exception occurred the program gets terminated abruptly and, the code past the line that generated the exception never gets executed. Each exception is represented by its respective class. This is a Runtime exception i.e. it occurs at the execution time. While accessing the contents of a collection, array or other objects using the accessor methods of an Enumeration, Iterator or, tokenizer, such as next() or nextElement(), if you try to get the elements from an empty object, or if you try to get the next element after reaching the end of the object (collection, array, or other) a NoSuchElementException is generated. For example, If you call the nextElement() method of the Enumeration class on an empty enumeration object or, if the current position is at the end of the Enumeration, a NosuchElementException is generated at run time. If you nextElement() and nextToken() methods of the StringTokenizer class on an empty StringTokenizer object or, if the current position is at the end of the StringTokenizer, a NosuchElementException is generated at run time. If the next() methods of the Iterator or ListIterator classes, invoked on an empty Iterator/ListIterator or, if the current position is at the end, the Iterator/listIterator NosuchElementException is generated at run time. Similarly if the previous() method of the ListIterator class is invoked on an empty ListIterator object, or if the current position is the start of the ListIterator a NosuchElementException is generated at run time. import java.util.StringTokenizer; public class StringTokenizerExample{ public static void main(String args[]) { String str = "Hello how are you"; //Instantiating the StringTokenizer class StringTokenizer tokenizer = new StringTokenizer(str, " "); //Printing all the tokens System.out.println(tokenizer.nextToken()); System.out.println(tokenizer.nextToken()); System.out.println(tokenizer.nextToken()); System.out.println(tokenizer.nextToken()); //Getting the next token after reaching the end tokenizer.nextToken(); tokenizer.nextElement(); } } Hello how are you Exception in thread "main" java.util.NoSuchElementException at java.util.StringTokenizer.nextToken(Unknown Source) at MyPackage.StringTokenizerExample.main(StringTokenizerExample.java:16) Almost all the classes whose accessor method causes NoSuchElementException contains their respective methods to verify whether the object (collection, tokenizer etc.) contains more elements. For example − The Enumeration class contains a method named hasMoreElements() which returns true if the current object contains more elements after the current position (else it returns false). The StringTokenizer class contains methods named hasMoreTokens() and hasMoreElements() which returns true if the current object contains more elements after the current position (else it returns false). The Iterator class contains hasNext() method this also returns true if the current iterator contains more elements next to the current position (else it returns false). The ListIterator class contains hasPrevious() method this also returns true if the current iterator contains more elements previously to the current position (else it returns false). In the while loop verify whether the respective object contains more elements using these methods, print/access elements only, if the condition is true. This prevents the access of elements using accessor methods when there are no elements in the object or, if it reaches the end. hasMoreElements() method of the Enumeration class import java.util.Enumeration; import java.util.Vector; public class EnumExample { public static void main(String args[]) { //instantiating a Vector Vector<Integer> vec = new Vector<Integer>( ); //Populating the vector vec.add(1254); vec.add(4587); //Retrieving the elements using the Enumeration Enumeration<Integer> en = vec.elements(); while(en.hasMoreElements()) { System.out.println(en.nextElement()); } } } 1254 4587 nextMoreTokens() method of the StringTokenizer class − import java.util.StringTokenizer; public class StringTokenizerExample{ public static void main(String args[]) { String str = "Hello how are you"; //Instantiating the StringTokenizer class StringTokenizer tokenizer = new StringTokenizer(str, " "); //Printing all the tokens while(tokenizer.hasMoreTokens()) { System.out.println(tokenizer.nextToken()); } } } Hello how are you hasNext() method of the Iterator class − import java.util.ArrayList; import java.util.Iterator; public class NextElementExample{ public static void main(String args[]) { //Instantiating an ArrayList object ArrayList<String> list = new ArrayList<String>(); //populating the ArrayList list.add("apples"); list.add("mangoes"); list.add("oranges"); //Getting the Iterator object of the ArrayList Iterator it = list.iterator(); while(it.hasNext()) { System.out.println(it.next()); } } } apples mangoes oranges hasPrevious() method of the ListIterator class − import java.util.ArrayList; import java.util.ListIterator; public class NextElementExample{ public static void main(String args[]) { //Instantiating an ArrayList object ArrayList<String> list = new ArrayList<String>(); //populating the ArrayList list.add("apples"); list.add("mangoes"); list.add("oranges"); //Getting the Iterator object of the ArrayList ListIterator<String> it = list.listIterator(); while(it.hasNext()) { it.next(); } while(it.hasPrevious()) { System.out.println(it.previous()); } } } oranges mangoes apples
[ { "code": null, "e": 1137, "s": 1062, "text": "What is the cause of NoSuchElementException and how can we fix it in java?" }, { "code": null, "e": 1420, "s": 1137, "text": "An exception is an issue (run time error) occurred during the execution of a program. When an exception occurred the program gets terminated abruptly and, the code past the line that generated the exception never gets executed. Each exception is represented by its respective class." }, { "code": null, "e": 1486, "s": 1420, "text": "This is a Runtime exception i.e. it occurs at the execution time." }, { "code": null, "e": 1855, "s": 1486, "text": "While accessing the contents of a collection, array or other objects using the accessor methods of an Enumeration, Iterator or, tokenizer, such as next() or nextElement(), if you try to get the elements from an empty object, or if you try to get the next element after reaching the end of the object (collection, array, or other) a NoSuchElementException is generated." }, { "code": null, "e": 1868, "s": 1855, "text": "For example," }, { "code": null, "e": 2074, "s": 1868, "text": "If you call the nextElement() method of the Enumeration class on an empty enumeration object or, if the current position is at the end of the Enumeration, a NosuchElementException is generated at run time." }, { "code": null, "e": 2300, "s": 2074, "text": "If you nextElement() and nextToken() methods of the StringTokenizer class on an empty StringTokenizer object or, if the current position is at the end of the StringTokenizer, a NosuchElementException is generated at run time." }, { "code": null, "e": 2523, "s": 2300, "text": "If the next() methods of the Iterator or ListIterator classes, invoked on an empty Iterator/ListIterator or, if the current position is at the end, the Iterator/listIterator NosuchElementException is generated at run time." }, { "code": null, "e": 2739, "s": 2523, "text": "Similarly if the previous() method of the ListIterator class is invoked on an empty ListIterator object, or if the current position is the start of the ListIterator a NosuchElementException is generated at run time." }, { "code": null, "e": 3356, "s": 2739, "text": "import java.util.StringTokenizer;\npublic class StringTokenizerExample{\n public static void main(String args[]) {\n String str = \"Hello how are you\";\n //Instantiating the StringTokenizer class\n StringTokenizer tokenizer = new StringTokenizer(str, \" \");\n //Printing all the tokens\n System.out.println(tokenizer.nextToken());\n System.out.println(tokenizer.nextToken());\n System.out.println(tokenizer.nextToken());\n System.out.println(tokenizer.nextToken());\n //Getting the next token after reaching the end\n tokenizer.nextToken();\n tokenizer.nextElement();\n }\n}" }, { "code": null, "e": 3568, "s": 3356, "text": "Hello\nhow\nare\nyou\nException in thread \"main\" java.util.NoSuchElementException\n at java.util.StringTokenizer.nextToken(Unknown Source)\n at MyPackage.StringTokenizerExample.main(StringTokenizerExample.java:16)" }, { "code": null, "e": 3759, "s": 3568, "text": "Almost all the classes whose accessor method causes NoSuchElementException contains their respective methods to verify whether the object (collection, tokenizer etc.) contains more elements." }, { "code": null, "e": 3773, "s": 3759, "text": "For example −" }, { "code": null, "e": 3953, "s": 3773, "text": "The Enumeration class contains a method named hasMoreElements() which returns true if the current object contains more elements after the current position (else it returns false)." }, { "code": null, "e": 4156, "s": 3953, "text": "The StringTokenizer class contains methods named hasMoreTokens() and hasMoreElements() which returns true if the current object contains more elements after the current position (else it returns false)." }, { "code": null, "e": 4325, "s": 4156, "text": "The Iterator class contains hasNext() method this also returns true if the current iterator contains more elements next to the current position (else it returns false)." }, { "code": null, "e": 4508, "s": 4325, "text": "The ListIterator class contains hasPrevious() method this also returns true if the current iterator contains more elements previously to the current position (else it returns false)." }, { "code": null, "e": 4789, "s": 4508, "text": "In the while loop verify whether the respective object contains more elements using these methods, print/access elements only, if the condition is true. This prevents the access of elements using accessor methods when there are no elements in the object or, if it reaches the end." }, { "code": null, "e": 4839, "s": 4789, "text": "hasMoreElements() method of the Enumeration class" }, { "code": null, "e": 5320, "s": 4839, "text": "import java.util.Enumeration;\nimport java.util.Vector;\npublic class EnumExample {\n public static void main(String args[]) {\n //instantiating a Vector\n Vector<Integer> vec = new Vector<Integer>( );\n //Populating the vector\n vec.add(1254);\n vec.add(4587);\n //Retrieving the elements using the Enumeration\n Enumeration<Integer> en = vec.elements();\n while(en.hasMoreElements()) {\n System.out.println(en.nextElement());\n }\n }\n}" }, { "code": null, "e": 5330, "s": 5320, "text": "1254\n4587" }, { "code": null, "e": 5385, "s": 5330, "text": "nextMoreTokens() method of the StringTokenizer class −" }, { "code": null, "e": 5793, "s": 5385, "text": "import java.util.StringTokenizer;\npublic class StringTokenizerExample{\n public static void main(String args[]) {\n String str = \"Hello how are you\";\n //Instantiating the StringTokenizer class\n StringTokenizer tokenizer = new StringTokenizer(str, \" \");\n //Printing all the tokens\n while(tokenizer.hasMoreTokens()) {\n System.out.println(tokenizer.nextToken());\n }\n }\n}" }, { "code": null, "e": 5811, "s": 5793, "text": "Hello\nhow\nare\nyou" }, { "code": null, "e": 5852, "s": 5811, "text": "hasNext() method of the Iterator class −" }, { "code": null, "e": 6368, "s": 5852, "text": "import java.util.ArrayList;\nimport java.util.Iterator;\npublic class NextElementExample{\n public static void main(String args[]) {\n //Instantiating an ArrayList object\n ArrayList<String> list = new ArrayList<String>();\n //populating the ArrayList\n list.add(\"apples\");\n list.add(\"mangoes\");\n list.add(\"oranges\");\n //Getting the Iterator object of the ArrayList\n Iterator it = list.iterator();\n while(it.hasNext()) {\n System.out.println(it.next());\n }\n }\n}" }, { "code": null, "e": 6391, "s": 6368, "text": "apples\nmangoes\noranges" }, { "code": null, "e": 6440, "s": 6391, "text": "hasPrevious() method of the ListIterator class −" }, { "code": null, "e": 7040, "s": 6440, "text": "import java.util.ArrayList;\nimport java.util.ListIterator;\npublic class NextElementExample{\n public static void main(String args[]) {\n //Instantiating an ArrayList object\n ArrayList<String> list = new ArrayList<String>();\n //populating the ArrayList\n list.add(\"apples\");\n list.add(\"mangoes\");\n list.add(\"oranges\");\n //Getting the Iterator object of the ArrayList\n ListIterator<String> it = list.listIterator();\n while(it.hasNext()) {\n it.next();\n }\n while(it.hasPrevious()) {\n System.out.println(it.previous());\n }\n }\n}" }, { "code": null, "e": 7063, "s": 7040, "text": "oranges\nmangoes\napples" } ]
Version Control With Jupyter Notebook | by Shinichi Okada | Towards Data Science
Table of ContentsIntroduction1. Creating a demo repo2. Jupytext setup3. Converting to a python file4. Converting multiple files5. Converted file6. Adding ipynb to .gitignore7. Converting to ipynb files8. Other commands9. Paired notebooksConclusion Jupyter notebook generates files that contain metadata, source code, formatted text, and rich media. Only one word of change results in thousands of letters in git diff. Jupytext can save Jupyter Notebook to a git-friendly and human-friendly file format, including Markdown, Python, Julia, Bash, Clojure, Matlab, TypeScript, Javascript, etc. It also converts these documents into Jupyter Notebooks. In this article, I am going through a step-by-step guide to version control for Jupyter Notebook using Jupytext. If you are not using Github’s ipynb rendering, Nbviewer or Binder, then Jupytext should be your choice of version control. Supported extensions are: levelup.gitconnected.com towardsdatascience.com towardsdatascience.com First, let’s create a new Jupyter Notebook file with the following codes. x = np.arange(-3, 3, 0.1)y = np.sin(x)plt.plot(x, y)plt.show() Please create a Github repo. echo "# jupyter_notebook_version_control" >> README.mdgit initgit add README.mdgit commit -m "first commit"git remote add origin [email protected]:username/jupyter_notebook_version_control.gitgit push -u origin master I change the word `sin` to `cos` in an ipynb file. y = np.cos(x) This link is the result of `git diff`. It generated thousands of letters for three letters. Let’s install and setup the Jupytext. pip install jupytext --upgrade Or for conda users conda install -c conda-forge jupytext RESTART Jupyter Notebook. You can convert an ipynb file to one of the supported files. I will use a python file in this article. In your terminal, you can run like this. jupytext --to py <your-file-name>.ipynb For my case: jupytext --to py Version_control.ipynb Outputs: [jupytext] Reading ./Version_control.ipynb[jupytext] Writing ./Version_control.py towardsdatascience.com Let’s convert all ipynb files at once. Please create more files in your directory. jupytext --to py *.ipynb Output: [jupytext] Reading Version_control.ipynb[jupytext] Writing Version_control.py[jupytext] Reading sine.ipynb[jupytext] Writing sine.py[jupytext] Reading tangent.ipynb[jupytext] Writing tangent.py You can convert a file into a directory. Jupytext will create a new directory if it does not exist. jupytext --to destination_folder//py *.ipynb If you prefer you can run jupytext in one of the cells. But this cell will be in your converted file as well. !jupytext --to py <your-file-name>.ipynb Let’s see the converted file in your terminal. cat Version_control.py My output: # ---# jupyter:# jupytext:# text_representation:# extension: .py# format_name: light# format_version: '1.5'# jupytext_version: 1.3.3# kernelspec:# display_name: Python 3# language: python# name: python3# ---x = np.arange(-3, 3, 0.1)y = np.cos(x)plt.plot(x, y)plt.show() It is very compact and the file size is very small. Nice 😃 👏👏👏👏. Since we are not tracking ipynb files, we can add it to a .gitignore file. Please create a .gitignore in your project root directory where you have .git directory. touch .gitignore Please add *.ipynb and ` .ipynb_checkpoints` to ignore all Jupyter Notebook files. Or add this complete list to your gitignore. # for Jupytext ignoring ipynb files*.ipynb At this stage, git will still track changes in .ipynb files. To fix this you need to remove git cache and add all files again. git rm -r --cached .git add .git commit -m "fixed untracked files" After changing a line in your Jupyter Notebook to see if .gitignore is working. # change whatever you wanty = np.arange(-2,2,0.1) Check it in your terminal: git status It should not return a modified file. Let’s run Jupytext one more time to reflect on our change. Please run the following in your terminal. jupytext --to py Version_control.ipynb The converted file will be replaced. 😃 [jupytext] Reading ./Version_control.ipynb[jupytext] Writing ./Version_control.py (destination file replaced) Let’s check the git status. git statusOn branch masterYour branch is up to date with 'origin/master'.Changes not staged for commit: (use "git add <file>..." to update what will be committed) (use "git checkout -- <file>..." to discard changes in working directory) modified: Version_control.pyno changes added to commit (use "git add" and/or "git commit -a") It tracked only the python file, not ipynb. Please run git diff. git diffdiff --git a/Version_control.py b/Version_control.pyindex 02d91ea..6522717 100644--- a/Version_control.py+++ b/Version_control.py@@ -14,6 +14,7 @@ # --- x = np.arange(-3, 3, 0.1)+y = np.arange(-2,2,0.1) y = np.cos(x) plt.plot(x, y) plt.show() Please add, commit and push the change. git add .git commit -m "Update"git push We are going to clone this repo to another directory and convert it to an ipynb file. cd ..git clone [email protected]:shinokada/jupyter_notebook_version_control.git my-new-dir I cloned my repo to a directory called my-new-dir. cd my-new-dirlsREADME.md Version_control.py sine.py tangent.py Or if you have the tree. tree.├── README.md├── Version_control.py├── sine.py└── tangent.py0 directories, 4 files We have all the files we need. Let’s convert it to ipynb file. From your terminal: jupytext --to ipynb *.py Output: [jupytext] Reading Version_control.py[jupytext] Writing Version_control.ipynb[jupytext] Sync timestamp of 'Version_control.py'[jupytext] Reading sine.py[jupytext] Writing sine.ipynb[jupytext] Reading tangent.py[jupytext] Writing tangent.ipynblsREADME.md Version_control.py sine.py tangent.py. Version_control.ipynb sine.ipynb tangent.ipynb These are other commands you can use. # convert notebook.md to an .ipynb file and run itjupytext --to notebook --execute notebook.md# update the input cells in the .ipynb file and preserve outputs and metadata jupytext --update --to notebook notebook.py# Turn notebook.ipynb into a paired ipynb/py notebookjupytext --set-formats ipynb,py notebook.ipynb # Update all paired representations of notebook.ipynbjupytext --sync notebook.ipynb Jupytext can write a given notebook to multiple files. In addition to the original notebook file, Jupytext can save the input cells to a text file — either a script or a Markdown document. Please read more details if you are interested. Jupytext is easy to use and create human-friendly files which you can edit in another editor as well. If you are using git diff , this is an excellent tool to have. I think this is the most complete open-source tool for version control with Jupyter Notebook at the moment. Get full access to every story on Medium by becoming a member. towardsdatascience.com https://github.com/mwouts/jupytext https://jupytext.readthedocs.io/en/latest/index.html https://jupytext.readthedocs.io/en/latest/introduction.html#demo-time Hello. You made it to the end. Now that you’re here, please help me spread this article. You can also follow me for more Jupyter, Statistics and tech articles.
[ { "code": null, "e": 420, "s": 172, "text": "Table of ContentsIntroduction1. Creating a demo repo2. Jupytext setup3. Converting to a python file4. Converting multiple files5. Converted file6. Adding ipynb to .gitignore7. Converting to ipynb files8. Other commands9. Paired notebooksConclusion" }, { "code": null, "e": 590, "s": 420, "text": "Jupyter notebook generates files that contain metadata, source code, formatted text, and rich media. Only one word of change results in thousands of letters in git diff." }, { "code": null, "e": 762, "s": 590, "text": "Jupytext can save Jupyter Notebook to a git-friendly and human-friendly file format, including Markdown, Python, Julia, Bash, Clojure, Matlab, TypeScript, Javascript, etc." }, { "code": null, "e": 932, "s": 762, "text": "It also converts these documents into Jupyter Notebooks. In this article, I am going through a step-by-step guide to version control for Jupyter Notebook using Jupytext." }, { "code": null, "e": 1055, "s": 932, "text": "If you are not using Github’s ipynb rendering, Nbviewer or Binder, then Jupytext should be your choice of version control." }, { "code": null, "e": 1081, "s": 1055, "text": "Supported extensions are:" }, { "code": null, "e": 1106, "s": 1081, "text": "levelup.gitconnected.com" }, { "code": null, "e": 1129, "s": 1106, "text": "towardsdatascience.com" }, { "code": null, "e": 1152, "s": 1129, "text": "towardsdatascience.com" }, { "code": null, "e": 1226, "s": 1152, "text": "First, let’s create a new Jupyter Notebook file with the following codes." }, { "code": null, "e": 1289, "s": 1226, "text": "x = np.arange(-3, 3, 0.1)y = np.sin(x)plt.plot(x, y)plt.show()" }, { "code": null, "e": 1318, "s": 1289, "text": "Please create a Github repo." }, { "code": null, "e": 1533, "s": 1318, "text": "echo \"# jupyter_notebook_version_control\" >> README.mdgit initgit add README.mdgit commit -m \"first commit\"git remote add origin [email protected]:username/jupyter_notebook_version_control.gitgit push -u origin master" }, { "code": null, "e": 1584, "s": 1533, "text": "I change the word `sin` to `cos` in an ipynb file." }, { "code": null, "e": 1598, "s": 1584, "text": "y = np.cos(x)" }, { "code": null, "e": 1690, "s": 1598, "text": "This link is the result of `git diff`. It generated thousands of letters for three letters." }, { "code": null, "e": 1728, "s": 1690, "text": "Let’s install and setup the Jupytext." }, { "code": null, "e": 1759, "s": 1728, "text": "pip install jupytext --upgrade" }, { "code": null, "e": 1778, "s": 1759, "text": "Or for conda users" }, { "code": null, "e": 1816, "s": 1778, "text": "conda install -c conda-forge jupytext" }, { "code": null, "e": 1842, "s": 1816, "text": "RESTART Jupyter Notebook." }, { "code": null, "e": 1945, "s": 1842, "text": "You can convert an ipynb file to one of the supported files. I will use a python file in this article." }, { "code": null, "e": 1986, "s": 1945, "text": "In your terminal, you can run like this." }, { "code": null, "e": 2026, "s": 1986, "text": "jupytext --to py <your-file-name>.ipynb" }, { "code": null, "e": 2039, "s": 2026, "text": "For my case:" }, { "code": null, "e": 2078, "s": 2039, "text": "jupytext --to py Version_control.ipynb" }, { "code": null, "e": 2087, "s": 2078, "text": "Outputs:" }, { "code": null, "e": 2169, "s": 2087, "text": "[jupytext] Reading ./Version_control.ipynb[jupytext] Writing ./Version_control.py" }, { "code": null, "e": 2192, "s": 2169, "text": "towardsdatascience.com" }, { "code": null, "e": 2275, "s": 2192, "text": "Let’s convert all ipynb files at once. Please create more files in your directory." }, { "code": null, "e": 2300, "s": 2275, "text": "jupytext --to py *.ipynb" }, { "code": null, "e": 2308, "s": 2300, "text": "Output:" }, { "code": null, "e": 2502, "s": 2308, "text": "[jupytext] Reading Version_control.ipynb[jupytext] Writing Version_control.py[jupytext] Reading sine.ipynb[jupytext] Writing sine.py[jupytext] Reading tangent.ipynb[jupytext] Writing tangent.py" }, { "code": null, "e": 2602, "s": 2502, "text": "You can convert a file into a directory. Jupytext will create a new directory if it does not exist." }, { "code": null, "e": 2647, "s": 2602, "text": "jupytext --to destination_folder//py *.ipynb" }, { "code": null, "e": 2757, "s": 2647, "text": "If you prefer you can run jupytext in one of the cells. But this cell will be in your converted file as well." }, { "code": null, "e": 2798, "s": 2757, "text": "!jupytext --to py <your-file-name>.ipynb" }, { "code": null, "e": 2845, "s": 2798, "text": "Let’s see the converted file in your terminal." }, { "code": null, "e": 2868, "s": 2845, "text": "cat Version_control.py" }, { "code": null, "e": 2879, "s": 2868, "text": "My output:" }, { "code": null, "e": 3193, "s": 2879, "text": "# ---# jupyter:# jupytext:# text_representation:# extension: .py# format_name: light# format_version: '1.5'# jupytext_version: 1.3.3# kernelspec:# display_name: Python 3# language: python# name: python3# ---x = np.arange(-3, 3, 0.1)y = np.cos(x)plt.plot(x, y)plt.show()" }, { "code": null, "e": 3258, "s": 3193, "text": "It is very compact and the file size is very small. Nice 😃 👏👏👏👏." }, { "code": null, "e": 3422, "s": 3258, "text": "Since we are not tracking ipynb files, we can add it to a .gitignore file. Please create a .gitignore in your project root directory where you have .git directory." }, { "code": null, "e": 3439, "s": 3422, "text": "touch .gitignore" }, { "code": null, "e": 3567, "s": 3439, "text": "Please add *.ipynb and ` .ipynb_checkpoints` to ignore all Jupyter Notebook files. Or add this complete list to your gitignore." }, { "code": null, "e": 3610, "s": 3567, "text": "# for Jupytext ignoring ipynb files*.ipynb" }, { "code": null, "e": 3737, "s": 3610, "text": "At this stage, git will still track changes in .ipynb files. To fix this you need to remove git cache and add all files again." }, { "code": null, "e": 3804, "s": 3737, "text": "git rm -r --cached .git add .git commit -m \"fixed untracked files\"" }, { "code": null, "e": 3884, "s": 3804, "text": "After changing a line in your Jupyter Notebook to see if .gitignore is working." }, { "code": null, "e": 3934, "s": 3884, "text": "# change whatever you wanty = np.arange(-2,2,0.1)" }, { "code": null, "e": 3961, "s": 3934, "text": "Check it in your terminal:" }, { "code": null, "e": 3972, "s": 3961, "text": "git status" }, { "code": null, "e": 4112, "s": 3972, "text": "It should not return a modified file. Let’s run Jupytext one more time to reflect on our change. Please run the following in your terminal." }, { "code": null, "e": 4151, "s": 4112, "text": "jupytext --to py Version_control.ipynb" }, { "code": null, "e": 4190, "s": 4151, "text": "The converted file will be replaced. 😃" }, { "code": null, "e": 4300, "s": 4190, "text": "[jupytext] Reading ./Version_control.ipynb[jupytext] Writing ./Version_control.py (destination file replaced)" }, { "code": null, "e": 4328, "s": 4300, "text": "Let’s check the git status." }, { "code": null, "e": 4666, "s": 4328, "text": "git statusOn branch masterYour branch is up to date with 'origin/master'.Changes not staged for commit: (use \"git add <file>...\" to update what will be committed) (use \"git checkout -- <file>...\" to discard changes in working directory) modified: Version_control.pyno changes added to commit (use \"git add\" and/or \"git commit -a\")" }, { "code": null, "e": 4731, "s": 4666, "text": "It tracked only the python file, not ipynb. Please run git diff." }, { "code": null, "e": 4982, "s": 4731, "text": "git diffdiff --git a/Version_control.py b/Version_control.pyindex 02d91ea..6522717 100644--- a/Version_control.py+++ b/Version_control.py@@ -14,6 +14,7 @@ # --- x = np.arange(-3, 3, 0.1)+y = np.arange(-2,2,0.1) y = np.cos(x) plt.plot(x, y) plt.show()" }, { "code": null, "e": 5022, "s": 4982, "text": "Please add, commit and push the change." }, { "code": null, "e": 5062, "s": 5022, "text": "git add .git commit -m \"Update\"git push" }, { "code": null, "e": 5148, "s": 5062, "text": "We are going to clone this repo to another directory and convert it to an ipynb file." }, { "code": null, "e": 5236, "s": 5148, "text": "cd ..git clone [email protected]:shinokada/jupyter_notebook_version_control.git my-new-dir" }, { "code": null, "e": 5287, "s": 5236, "text": "I cloned my repo to a directory called my-new-dir." }, { "code": null, "e": 5356, "s": 5287, "text": "cd my-new-dirlsREADME.md Version_control.py sine.py tangent.py" }, { "code": null, "e": 5381, "s": 5356, "text": "Or if you have the tree." }, { "code": null, "e": 5469, "s": 5381, "text": "tree.├── README.md├── Version_control.py├── sine.py└── tangent.py0 directories, 4 files" }, { "code": null, "e": 5532, "s": 5469, "text": "We have all the files we need. Let’s convert it to ipynb file." }, { "code": null, "e": 5552, "s": 5532, "text": "From your terminal:" }, { "code": null, "e": 5577, "s": 5552, "text": "jupytext --to ipynb *.py" }, { "code": null, "e": 5585, "s": 5577, "text": "Output:" }, { "code": null, "e": 5940, "s": 5585, "text": "[jupytext] Reading Version_control.py[jupytext] Writing Version_control.ipynb[jupytext] Sync timestamp of 'Version_control.py'[jupytext] Reading sine.py[jupytext] Writing sine.ipynb[jupytext] Reading tangent.py[jupytext] Writing tangent.ipynblsREADME.md Version_control.py sine.py tangent.py. Version_control.ipynb sine.ipynb tangent.ipynb" }, { "code": null, "e": 5978, "s": 5940, "text": "These are other commands you can use." }, { "code": null, "e": 6377, "s": 5978, "text": "# convert notebook.md to an .ipynb file and run itjupytext --to notebook --execute notebook.md# update the input cells in the .ipynb file and preserve outputs and metadata jupytext --update --to notebook notebook.py# Turn notebook.ipynb into a paired ipynb/py notebookjupytext --set-formats ipynb,py notebook.ipynb # Update all paired representations of notebook.ipynbjupytext --sync notebook.ipynb" }, { "code": null, "e": 6614, "s": 6377, "text": "Jupytext can write a given notebook to multiple files. In addition to the original notebook file, Jupytext can save the input cells to a text file — either a script or a Markdown document. Please read more details if you are interested." }, { "code": null, "e": 6887, "s": 6614, "text": "Jupytext is easy to use and create human-friendly files which you can edit in another editor as well. If you are using git diff , this is an excellent tool to have. I think this is the most complete open-source tool for version control with Jupyter Notebook at the moment." }, { "code": null, "e": 6950, "s": 6887, "text": "Get full access to every story on Medium by becoming a member." }, { "code": null, "e": 6973, "s": 6950, "text": "towardsdatascience.com" }, { "code": null, "e": 7008, "s": 6973, "text": "https://github.com/mwouts/jupytext" }, { "code": null, "e": 7061, "s": 7008, "text": "https://jupytext.readthedocs.io/en/latest/index.html" }, { "code": null, "e": 7131, "s": 7061, "text": "https://jupytext.readthedocs.io/en/latest/introduction.html#demo-time" } ]
SQLSERVER Tryit Editor v1.0
Edit the SQL Statement, and click "Run SQL" to see the result. This SQL-Statement is not supported in the WebSQL Database. The example still works, because it uses a modified version of SQL. Your browser does not support WebSQL. Your are now using a light-version of the Try-SQL Editor, with a read-only Database. If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time. Our Try-SQL Editor uses WebSQL to demonstrate SQL. A Database-object is created in your browser, for testing purposes. You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button. WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object. WebSQL is supported in Chrome, Safari, and Opera. If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data.
[ { "code": null, "e": 98, "s": 35, "text": "Edit the SQL Statement, and click \"Run SQL\" to see the result." }, { "code": null, "e": 158, "s": 98, "text": "This SQL-Statement is not supported in the WebSQL Database." }, { "code": null, "e": 226, "s": 158, "text": "The example still works, because it uses a modified version of SQL." }, { "code": null, "e": 264, "s": 226, "text": "Your browser does not support WebSQL." }, { "code": null, "e": 349, "s": 264, "text": "Your are now using a light-version of the Try-SQL Editor, with a read-only Database." }, { "code": null, "e": 523, "s": 349, "text": "If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time." }, { "code": null, "e": 574, "s": 523, "text": "Our Try-SQL Editor uses WebSQL to demonstrate SQL." }, { "code": null, "e": 642, "s": 574, "text": "A Database-object is created in your browser, for testing purposes." }, { "code": null, "e": 813, "s": 642, "text": "You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the \"Restore Database\" button." }, { "code": null, "e": 913, "s": 813, "text": "WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object." }, { "code": null, "e": 963, "s": 913, "text": "WebSQL is supported in Chrome, Safari, and Opera." } ]
Length of Longest Subarray with same elements in atmost K increments - GeeksforGeeks
10 Jun, 2021 Given an integer array arr and a number K, the task is to find the length of the longest subarray such that all the elements in this subarray can be made the same in atmost K increments. Examples: Input: arr[] = {2, 0, 4, 6, 7}, K = 6 Output: 3 The longest subarray is {2, 0, 4} which can be made as {4, 4, 4} with total increments = 6 ( ≤ K ) Input: arr[] = {12, 10, 16, 20, 7, 11}, K = 25 Output: 4 The longest subarray is {12, 10, 16, 20} which can be made as {20, 20, 20, 20} with total increments = 22 ( ≤ K ) Approach: A variable i will be used to store the start point of the required longest subarray, and a variable j for the endpoint. Hence, the range will be [i, j] Initially, assume the valid range to be [0, N). The actual range [i, j] will be computed using binary search. For each search performed: A Segment Tree can be used to find the maximum element in the range [i, j]Make all the elements in the range [i, j] equal to the found max element.Then, use a prefix sum array to get the sum of elements in the range [i, j].Then, the number of increments required in this range can be calculated as: A Segment Tree can be used to find the maximum element in the range [i, j] Make all the elements in the range [i, j] equal to the found max element. Then, use a prefix sum array to get the sum of elements in the range [i, j]. Then, the number of increments required in this range can be calculated as: Total number of increments = (j - i + 1) * (max_value) - Σ(i, j) where i = index of the starting point of the subarray j = index of end point of subarray max_value = maximum value from index i to j Σ(i, j) = sum of all elements from index i to j If the number of increments required is less than or equal to K, it is a valid subarray, else it is invalid. For invalid subarray, update the start and end points accordingly for the next Binary Search Return the length of the longest such subarray range. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to find the length of// Longest Subarray with same elements// in atmost K increments #include <bits/stdc++.h>using namespace std; // Initialize array for segment treeint segment_tree[4 * 1000000]; // Function that builds the segment// tree to return the max element// in a rangeint build(int* A, int start, int end, int node){ if (start == end) // update the value in segment // tree from given array segment_tree[node] = A[start]; else { // find the middle index int mid = (start + end) / 2; // If there are more than one // elements, then recur for left // and right subtrees and // store the max of values in this node segment_tree[node] = max( build(A, start, mid, 2 * node + 1), build(A, mid + 1, end, 2 * node + 2)); } return segment_tree[node];} // Function to return the max// element in the given rangeint query(int start, int end, int l, int r, int node){ // If the range is out of bounds, // return -1 if (start > r || end < l) return -1; if (start >= l && end <= r) return segment_tree[node]; int mid = (start + end) / 2; return max(query(start, mid, l, r, 2 * node + 1), query(mid + 1, end, l, r, 2 * node + 2));} // Function that returns length of longest// subarray with same elements in atmost// K increments.int longestSubArray(int* A, int N, int K){ // Initialize the result variable // Even though the K is 0, // the required longest subarray, // in that case, will also be of length 1 int res = 1; // Initialize the prefix sum array int preSum[N + 1]; // Build the prefix sum array preSum[0] = A[0]; for (int i = 0; i < N; i++) preSum[i + 1] = preSum[i] + A[i]; // Build the segment tree // for range max query build(A, 0, N - 1, 0); // Loop through the array // with a starting point as i // for the required subarray till // the longest subarray is found for (int i = 0; i < N; i++) { int start = i, end = N - 1, mid, max_index = i; // Performing the binary search // to find the endpoint // for the selected range while (start <= end) { // Find the mid for binary search mid = (start + end) / 2; // Find the max element // in the range [i, mid] // using Segment Tree int max_element = query(0, N - 1, i, mid, 0); // Total sum of subarray after increments int expected_sum = (mid - i + 1) * max_element; // Actual sum of elements // before increments int actual_sum = preSum[mid + 1] - preSum[i]; // Check if such increment is possible // If true, then current i // is the actual starting point // of the required longest subarray if (expected_sum - actual_sum <= K) { // Now for finding the endpoint // for this range // Perform the Binary search again // with the updated start start = mid + 1; // Store max end point for the range // to give longest subarray max_index = max(max_index, mid); } // If false, it means that // the selected range is invalid else { // Perform the Binary Search again // with the updated end end = mid - 1; } } // Store the length of longest subarray res = max(res, max_index - i + 1); } // Return result return res;} // Driver codeint main(){ int arr[] = { 2, 0, 4, 6, 7 }, K = 6; int N = sizeof(arr) / sizeof(arr[0]); cout << longestSubArray(arr, N, K); return 0;} // Java program to find the length of// Longest Subarray with same elements// in atmost K incrementsclass GFG{ // Initialize array for segment tree static int segment_tree[] = new int[4 * 1000000]; // Function that builds the segment // tree to return the max element // in a range static int build(int A[], int start, int end, int node) { if (start == end) // update the value in segment // tree from given array segment_tree[node] = A[start]; else { // find the middle index int mid = (start + end) / 2; // If there are more than one // elements, then recur for left // and right subtrees and // store the max of values in this node segment_tree[node] = Math.max( build(A, start, mid, 2 * node + 1), build(A, mid + 1, end, 2 * node + 2)); } return segment_tree[node]; } // Function to return the max // element in the given range static int query(int start, int end, int l, int r, int node) { // If the range is out of bounds, // return -1 if (start > r || end < l) return -1; if (start >= l && end <= r) return segment_tree[node]; int mid = (start + end) / 2; return Math.max(query(start, mid, l, r, 2 * node + 1), query(mid + 1, end, l, r, 2 * node + 2)); } // Function that returns length of longest // subarray with same elements in atmost // K increments. static int longestSubArray(int A[], int N, int K) { // Initialize the result variable // Even though the K is 0, // the required longest subarray, // in that case, will also be of length 1 int res = 1; // Initialize the prefix sum array int preSum[] = new int[N + 1]; // Build the prefix sum array preSum[0] = A[0]; for (int i = 0; i < N; i++) preSum[i + 1] = preSum[i] + A[i]; // Build the segment tree // for range max query build(A, 0, N - 1, 0); // Loop through the array // with a starting point as i // for the required subarray till // the longest subarray is found for (int i = 0; i < N; i++) { int start = i, end = N - 1, mid, max_index = i; // Performing the binary search // to find the endpoint // for the selected range while (start <= end) { // Find the mid for binary search mid = (start + end) / 2; // Find the max element // in the range [i, mid] // using Segment Tree int max_element = query(0, N - 1, i, mid, 0); // Total sum of subarray after increments int expected_sum = (mid - i + 1) * max_element; // Actual sum of elements // before increments int actual_sum = preSum[mid + 1] - preSum[i]; // Check if such increment is possible // If true, then current i // is the actual starting point // of the required longest subarray if (expected_sum - actual_sum <= K) { // Now for finding the endpoint // for this range // Perform the Binary search again // with the updated start start = mid + 1; // Store max end point for the range // to give longest subarray max_index = Math.max(max_index, mid); } // If false, it means that // the selected range is invalid else { // Perform the Binary Search again // with the updated end end = mid - 1; } } // Store the length of longest subarray res = Math.max(res, max_index - i + 1); } // Return result return res; } // Driver code public static void main (String[] args) { int arr[] = { 2, 0, 4, 6, 7 }, K = 6; int N = arr.length; System.out.println(longestSubArray(arr, N, K)); }} // This code is contributed by AnkitRai01 # Python3 program to find the length of# Longest Subarray with same elements# in atmost K increments # Initialize array for segment treesegment_tree = [0]*(4 * 1000000); # Function that builds the segment# tree to return the max element# in a rangedef build(A, start, end, node) : if (start == end) : # update the value in segment # tree from given array segment_tree[node] = A[start]; else : # find the middle index mid = (start + end) // 2; # If there are more than one # elements, then recur for left # and right subtrees and # store the max of values in this node segment_tree[node] = max( build(A, start, mid, 2 * node + 1), build(A, mid + 1, end, 2 * node + 2)); return segment_tree[node]; # Function to return the max# element in the given rangedef query(start, end, l, r, node) : # If the range is out of bounds, # return -1 if (start > r or end < l) : return -1; if (start >= l and end <= r) : return segment_tree[node]; mid = (start + end) // 2; return max(query(start, mid, l, r, 2 * node + 1), query(mid + 1, end, l, r, 2 * node + 2)); # Function that returns length of longest# subarray with same elements in atmost# K increments.def longestSubArray(A, N, K) : # Initialize the result variable # Even though the K is 0, # the required longest subarray, # in that case, will also be of length 1 res = 1; # Initialize the prefix sum array preSum = [0] * (N + 1); # Build the prefix sum array preSum[0] = A[0]; for i in range(N) : preSum[i + 1] = preSum[i] + A[i]; # Build the segment tree # for range max query build(A, 0, N - 1, 0); # Loop through the array # with a starting point as i # for the required subarray till # the longest subarray is found for i in range(N) : start = i; end = N - 1; max_index = i; # Performing the binary search # to find the endpoint # for the selected range while (start <= end) : # Find the mid for binary search mid = (start + end) // 2; # Find the max element # in the range [i, mid] # using Segment Tree max_element = query(0, N - 1, i, mid, 0); # Total sum of subarray after increments expected_sum = (mid - i + 1) * max_element; # Actual sum of elements # before increments actual_sum = preSum[mid + 1] - preSum[i]; # Check if such increment is possible # If true, then current i # is the actual starting point # of the required longest subarray if (expected_sum - actual_sum <= K) : # Now for finding the endpoint # for this range # Perform the Binary search again # with the updated start start = mid + 1; # Store max end point for the range # to give longest subarray max_index = max(max_index, mid); # If false, it means that # the selected range is invalid else : # Perform the Binary Search again # with the updated end end = mid - 1; # Store the length of longest subarray res = max(res, max_index - i + 1); # Return result return res; # Driver codeif __name__ == "__main__" : arr = [ 2, 0, 4, 6, 7 ]; K = 6; N = len(arr); print(longestSubArray(arr, N, K)); # This code is contributed by AnkitRai01 // C# program to find the length of// longest Subarray with same elements// in atmost K incrementsusing System; class GFG{ // Initialize array for segment tree static int []segment_tree = new int[4 * 1000000]; // Function that builds the segment // tree to return the max element // in a range static int build(int []A, int start, int end, int node) { if (start == end) // update the value in segment // tree from given array segment_tree[node] = A[start]; else { // find the middle index int mid = (start + end) / 2; // If there are more than one // elements, then recur for left // and right subtrees and // store the max of values in this node segment_tree[node] = Math.Max( build(A, start, mid, 2 * node + 1), build(A, mid + 1, end, 2 * node + 2)); } return segment_tree[node]; } // Function to return the max // element in the given range static int query(int start, int end, int l, int r, int node) { // If the range is out of bounds, // return -1 if (start > r || end < l) return -1; if (start >= l && end <= r) return segment_tree[node]; int mid = (start + end) / 2; return Math.Max(query(start, mid, l, r, 2 * node + 1), query(mid + 1, end, l, r, 2 * node + 2)); } // Function that returns length of longest // subarray with same elements in atmost // K increments. static int longestSubArray(int []A, int N, int K) { // Initialize the result variable // Even though the K is 0, // the required longest subarray, // in that case, will also be of length 1 int res = 1; // Initialize the prefix sum array int []preSum = new int[N + 1]; // Build the prefix sum array preSum[0] = A[0]; for (int i = 0; i < N; i++) preSum[i + 1] = preSum[i] + A[i]; // Build the segment tree // for range max query build(A, 0, N - 1, 0); // Loop through the array // with a starting point as i // for the required subarray till // the longest subarray is found for (int i = 0; i < N; i++) { int start = i, end = N - 1, mid, max_index = i; // Performing the binary search // to find the endpoint // for the selected range while (start <= end) { // Find the mid for binary search mid = (start + end) / 2; // Find the max element // in the range [i, mid] // using Segment Tree int max_element = query(0, N - 1, i, mid, 0); // Total sum of subarray after increments int expected_sum = (mid - i + 1) * max_element; // Actual sum of elements // before increments int actual_sum = preSum[mid + 1] - preSum[i]; // Check if such increment is possible // If true, then current i // is the actual starting point // of the required longest subarray if (expected_sum - actual_sum <= K) { // Now for finding the endpoint // for this range // Perform the Binary search again // with the updated start start = mid + 1; // Store max end point for the range // to give longest subarray max_index = Math.Max(max_index, mid); } // If false, it means that // the selected range is invalid else { // Perform the Binary Search again // with the updated end end = mid - 1; } } // Store the length of longest subarray res = Math.Max(res, max_index - i + 1); } // Return result return res; } // Driver code public static void Main(String[] args) { int []arr = { 2, 0, 4, 6, 7 }; int K = 6; int N = arr.Length; Console.WriteLine(longestSubArray(arr, N, K)); }} // This code is contributed by PrinciRaj1992 <script> // Javascript program to find the length of // Longest Subarray with same elements // in atmost K increments // Initialize array for segment tree let segment_tree = new Array(4 * 1000000); // Function that builds the segment // tree to return the max element // in a range function build(A, start, end, node) { if (start == end) // update the value in segment // tree from given array segment_tree[node] = A[start]; else { // find the middle index let mid = parseInt((start + end) / 2, 10); // If there are more than one // elements, then recur for left // and right subtrees and // store the max of values in this node segment_tree[node] = Math.max( build(A, start, mid, 2 * node + 1), build(A, mid + 1, end, 2 * node + 2)); } return segment_tree[node]; } // Function to return the max // element in the given range function query(start, end, l, r, node) { // If the range is out of bounds, // return -1 if (start > r || end < l) return -1; if (start >= l && end <= r) return segment_tree[node]; let mid = parseInt((start + end) / 2, 10); return Math.max(query(start, mid, l, r, 2 * node + 1), query(mid + 1, end, l, r, 2 * node + 2)); } // Function that returns length of longest // subarray with same elements in atmost // K increments. function longestSubArray(A, N, K) { // Initialize the result variable // Even though the K is 0, // the required longest subarray, // in that case, will also be of length 1 let res = 1; // Initialize the prefix sum array let preSum = new Array(N + 1); // Build the prefix sum array preSum[0] = A[0]; for (let i = 0; i < N; i++) preSum[i + 1] = preSum[i] + A[i]; // Build the segment tree // for range max query build(A, 0, N - 1, 0); // Loop through the array // with a starting point as i // for the required subarray till // the longest subarray is found for (let i = 0; i < N; i++) { let start = i, end = N - 1, mid, max_index = i; // Performing the binary search // to find the endpoint // for the selected range while (start <= end) { // Find the mid for binary search mid = parseInt((start + end) / 2, 10); // Find the max element // in the range [i, mid] // using Segment Tree let max_element = query(0, N - 1, i, mid, 0); // Total sum of subarray after increments let expected_sum = (mid - i + 1) * max_element; // Actual sum of elements // before increments let actual_sum = preSum[mid + 1] - preSum[i]; // Check if such increment is possible // If true, then current i // is the actual starting point // of the required longest subarray if (expected_sum - actual_sum <= K) { // Now for finding the endpoint // for this range // Perform the Binary search again // with the updated start start = mid + 1; // Store max end point for the range // to give longest subarray max_index = Math.max(max_index, mid); } // If false, it means that // the selected range is invalid else { // Perform the Binary Search again // with the updated end end = mid - 1; } } // Store the length of longest subarray res = Math.max(res, max_index - i + 1); } // Return result return res; } let arr = [ 2, 0, 4, 6, 7 ], K = 6; let N = arr.length; document.write(longestSubArray(arr, N, K)); </script> 3 Time Complexity: O(N*(log(N))2) ankthon princiraj1992 decode2207 Binary Search prefix-sum Segment-Tree subarray Arrays Searching Tree prefix-sum Arrays Searching Tree Segment-Tree Binary Search Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Introduction to Arrays Maximum and minimum of an array using minimum number of comparisons Multidimensional Arrays in Java Queue | Set 1 (Introduction and Array Implementation) Linked List vs Array Binary Search Maximum and minimum of an array using minimum number of comparisons Find the Missing Number K'th Smallest/Largest Element in Unsorted Array | Set 1 Program to find largest element in an array
[ { "code": null, "e": 24952, "s": 24924, "text": "\n10 Jun, 2021" }, { "code": null, "e": 25139, "s": 24952, "text": "Given an integer array arr and a number K, the task is to find the length of the longest subarray such that all the elements in this subarray can be made the same in atmost K increments." }, { "code": null, "e": 25150, "s": 25139, "text": "Examples: " }, { "code": null, "e": 25297, "s": 25150, "text": "Input: arr[] = {2, 0, 4, 6, 7}, K = 6 Output: 3 The longest subarray is {2, 0, 4} which can be made as {4, 4, 4} with total increments = 6 ( ≤ K )" }, { "code": null, "e": 25469, "s": 25297, "text": "Input: arr[] = {12, 10, 16, 20, 7, 11}, K = 25 Output: 4 The longest subarray is {12, 10, 16, 20} which can be made as {20, 20, 20, 20} with total increments = 22 ( ≤ K ) " }, { "code": null, "e": 25481, "s": 25469, "text": "Approach: " }, { "code": null, "e": 25633, "s": 25481, "text": "A variable i will be used to store the start point of the required longest subarray, and a variable j for the endpoint. Hence, the range will be [i, j]" }, { "code": null, "e": 25681, "s": 25633, "text": "Initially, assume the valid range to be [0, N)." }, { "code": null, "e": 26070, "s": 25681, "text": "The actual range [i, j] will be computed using binary search. For each search performed: A Segment Tree can be used to find the maximum element in the range [i, j]Make all the elements in the range [i, j] equal to the found max element.Then, use a prefix sum array to get the sum of elements in the range [i, j].Then, the number of increments required in this range can be calculated as: " }, { "code": null, "e": 26145, "s": 26070, "text": "A Segment Tree can be used to find the maximum element in the range [i, j]" }, { "code": null, "e": 26219, "s": 26145, "text": "Make all the elements in the range [i, j] equal to the found max element." }, { "code": null, "e": 26296, "s": 26219, "text": "Then, use a prefix sum array to get the sum of elements in the range [i, j]." }, { "code": null, "e": 26373, "s": 26296, "text": "Then, the number of increments required in this range can be calculated as: " }, { "code": null, "e": 26639, "s": 26373, "text": "Total number of increments\n = (j - i + 1) * (max_value) - Σ(i, j)\n\nwhere i = index of the starting point of the subarray\n j = index of end point of subarray\n max_value = maximum value from index i to j\n Σ(i, j) = sum of all elements from index i to j" }, { "code": null, "e": 26748, "s": 26639, "text": "If the number of increments required is less than or equal to K, it is a valid subarray, else it is invalid." }, { "code": null, "e": 26841, "s": 26748, "text": "For invalid subarray, update the start and end points accordingly for the next Binary Search" }, { "code": null, "e": 26895, "s": 26841, "text": "Return the length of the longest such subarray range." }, { "code": null, "e": 26946, "s": 26895, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 26950, "s": 26946, "text": "C++" }, { "code": null, "e": 26955, "s": 26950, "text": "Java" }, { "code": null, "e": 26963, "s": 26955, "text": "Python3" }, { "code": null, "e": 26966, "s": 26963, "text": "C#" }, { "code": null, "e": 26977, "s": 26966, "text": "Javascript" }, { "code": "// C++ program to find the length of// Longest Subarray with same elements// in atmost K increments #include <bits/stdc++.h>using namespace std; // Initialize array for segment treeint segment_tree[4 * 1000000]; // Function that builds the segment// tree to return the max element// in a rangeint build(int* A, int start, int end, int node){ if (start == end) // update the value in segment // tree from given array segment_tree[node] = A[start]; else { // find the middle index int mid = (start + end) / 2; // If there are more than one // elements, then recur for left // and right subtrees and // store the max of values in this node segment_tree[node] = max( build(A, start, mid, 2 * node + 1), build(A, mid + 1, end, 2 * node + 2)); } return segment_tree[node];} // Function to return the max// element in the given rangeint query(int start, int end, int l, int r, int node){ // If the range is out of bounds, // return -1 if (start > r || end < l) return -1; if (start >= l && end <= r) return segment_tree[node]; int mid = (start + end) / 2; return max(query(start, mid, l, r, 2 * node + 1), query(mid + 1, end, l, r, 2 * node + 2));} // Function that returns length of longest// subarray with same elements in atmost// K increments.int longestSubArray(int* A, int N, int K){ // Initialize the result variable // Even though the K is 0, // the required longest subarray, // in that case, will also be of length 1 int res = 1; // Initialize the prefix sum array int preSum[N + 1]; // Build the prefix sum array preSum[0] = A[0]; for (int i = 0; i < N; i++) preSum[i + 1] = preSum[i] + A[i]; // Build the segment tree // for range max query build(A, 0, N - 1, 0); // Loop through the array // with a starting point as i // for the required subarray till // the longest subarray is found for (int i = 0; i < N; i++) { int start = i, end = N - 1, mid, max_index = i; // Performing the binary search // to find the endpoint // for the selected range while (start <= end) { // Find the mid for binary search mid = (start + end) / 2; // Find the max element // in the range [i, mid] // using Segment Tree int max_element = query(0, N - 1, i, mid, 0); // Total sum of subarray after increments int expected_sum = (mid - i + 1) * max_element; // Actual sum of elements // before increments int actual_sum = preSum[mid + 1] - preSum[i]; // Check if such increment is possible // If true, then current i // is the actual starting point // of the required longest subarray if (expected_sum - actual_sum <= K) { // Now for finding the endpoint // for this range // Perform the Binary search again // with the updated start start = mid + 1; // Store max end point for the range // to give longest subarray max_index = max(max_index, mid); } // If false, it means that // the selected range is invalid else { // Perform the Binary Search again // with the updated end end = mid - 1; } } // Store the length of longest subarray res = max(res, max_index - i + 1); } // Return result return res;} // Driver codeint main(){ int arr[] = { 2, 0, 4, 6, 7 }, K = 6; int N = sizeof(arr) / sizeof(arr[0]); cout << longestSubArray(arr, N, K); return 0;}", "e": 31004, "s": 26977, "text": null }, { "code": "// Java program to find the length of// Longest Subarray with same elements// in atmost K incrementsclass GFG{ // Initialize array for segment tree static int segment_tree[] = new int[4 * 1000000]; // Function that builds the segment // tree to return the max element // in a range static int build(int A[], int start, int end, int node) { if (start == end) // update the value in segment // tree from given array segment_tree[node] = A[start]; else { // find the middle index int mid = (start + end) / 2; // If there are more than one // elements, then recur for left // and right subtrees and // store the max of values in this node segment_tree[node] = Math.max( build(A, start, mid, 2 * node + 1), build(A, mid + 1, end, 2 * node + 2)); } return segment_tree[node]; } // Function to return the max // element in the given range static int query(int start, int end, int l, int r, int node) { // If the range is out of bounds, // return -1 if (start > r || end < l) return -1; if (start >= l && end <= r) return segment_tree[node]; int mid = (start + end) / 2; return Math.max(query(start, mid, l, r, 2 * node + 1), query(mid + 1, end, l, r, 2 * node + 2)); } // Function that returns length of longest // subarray with same elements in atmost // K increments. static int longestSubArray(int A[], int N, int K) { // Initialize the result variable // Even though the K is 0, // the required longest subarray, // in that case, will also be of length 1 int res = 1; // Initialize the prefix sum array int preSum[] = new int[N + 1]; // Build the prefix sum array preSum[0] = A[0]; for (int i = 0; i < N; i++) preSum[i + 1] = preSum[i] + A[i]; // Build the segment tree // for range max query build(A, 0, N - 1, 0); // Loop through the array // with a starting point as i // for the required subarray till // the longest subarray is found for (int i = 0; i < N; i++) { int start = i, end = N - 1, mid, max_index = i; // Performing the binary search // to find the endpoint // for the selected range while (start <= end) { // Find the mid for binary search mid = (start + end) / 2; // Find the max element // in the range [i, mid] // using Segment Tree int max_element = query(0, N - 1, i, mid, 0); // Total sum of subarray after increments int expected_sum = (mid - i + 1) * max_element; // Actual sum of elements // before increments int actual_sum = preSum[mid + 1] - preSum[i]; // Check if such increment is possible // If true, then current i // is the actual starting point // of the required longest subarray if (expected_sum - actual_sum <= K) { // Now for finding the endpoint // for this range // Perform the Binary search again // with the updated start start = mid + 1; // Store max end point for the range // to give longest subarray max_index = Math.max(max_index, mid); } // If false, it means that // the selected range is invalid else { // Perform the Binary Search again // with the updated end end = mid - 1; } } // Store the length of longest subarray res = Math.max(res, max_index - i + 1); } // Return result return res; } // Driver code public static void main (String[] args) { int arr[] = { 2, 0, 4, 6, 7 }, K = 6; int N = arr.length; System.out.println(longestSubArray(arr, N, K)); }} // This code is contributed by AnkitRai01", "e": 35790, "s": 31004, "text": null }, { "code": "# Python3 program to find the length of# Longest Subarray with same elements# in atmost K increments # Initialize array for segment treesegment_tree = [0]*(4 * 1000000); # Function that builds the segment# tree to return the max element# in a rangedef build(A, start, end, node) : if (start == end) : # update the value in segment # tree from given array segment_tree[node] = A[start]; else : # find the middle index mid = (start + end) // 2; # If there are more than one # elements, then recur for left # and right subtrees and # store the max of values in this node segment_tree[node] = max( build(A, start, mid, 2 * node + 1), build(A, mid + 1, end, 2 * node + 2)); return segment_tree[node]; # Function to return the max# element in the given rangedef query(start, end, l, r, node) : # If the range is out of bounds, # return -1 if (start > r or end < l) : return -1; if (start >= l and end <= r) : return segment_tree[node]; mid = (start + end) // 2; return max(query(start, mid, l, r, 2 * node + 1), query(mid + 1, end, l, r, 2 * node + 2)); # Function that returns length of longest# subarray with same elements in atmost# K increments.def longestSubArray(A, N, K) : # Initialize the result variable # Even though the K is 0, # the required longest subarray, # in that case, will also be of length 1 res = 1; # Initialize the prefix sum array preSum = [0] * (N + 1); # Build the prefix sum array preSum[0] = A[0]; for i in range(N) : preSum[i + 1] = preSum[i] + A[i]; # Build the segment tree # for range max query build(A, 0, N - 1, 0); # Loop through the array # with a starting point as i # for the required subarray till # the longest subarray is found for i in range(N) : start = i; end = N - 1; max_index = i; # Performing the binary search # to find the endpoint # for the selected range while (start <= end) : # Find the mid for binary search mid = (start + end) // 2; # Find the max element # in the range [i, mid] # using Segment Tree max_element = query(0, N - 1, i, mid, 0); # Total sum of subarray after increments expected_sum = (mid - i + 1) * max_element; # Actual sum of elements # before increments actual_sum = preSum[mid + 1] - preSum[i]; # Check if such increment is possible # If true, then current i # is the actual starting point # of the required longest subarray if (expected_sum - actual_sum <= K) : # Now for finding the endpoint # for this range # Perform the Binary search again # with the updated start start = mid + 1; # Store max end point for the range # to give longest subarray max_index = max(max_index, mid); # If false, it means that # the selected range is invalid else : # Perform the Binary Search again # with the updated end end = mid - 1; # Store the length of longest subarray res = max(res, max_index - i + 1); # Return result return res; # Driver codeif __name__ == \"__main__\" : arr = [ 2, 0, 4, 6, 7 ]; K = 6; N = len(arr); print(longestSubArray(arr, N, K)); # This code is contributed by AnkitRai01", "e": 39511, "s": 35790, "text": null }, { "code": "// C# program to find the length of// longest Subarray with same elements// in atmost K incrementsusing System; class GFG{ // Initialize array for segment tree static int []segment_tree = new int[4 * 1000000]; // Function that builds the segment // tree to return the max element // in a range static int build(int []A, int start, int end, int node) { if (start == end) // update the value in segment // tree from given array segment_tree[node] = A[start]; else { // find the middle index int mid = (start + end) / 2; // If there are more than one // elements, then recur for left // and right subtrees and // store the max of values in this node segment_tree[node] = Math.Max( build(A, start, mid, 2 * node + 1), build(A, mid + 1, end, 2 * node + 2)); } return segment_tree[node]; } // Function to return the max // element in the given range static int query(int start, int end, int l, int r, int node) { // If the range is out of bounds, // return -1 if (start > r || end < l) return -1; if (start >= l && end <= r) return segment_tree[node]; int mid = (start + end) / 2; return Math.Max(query(start, mid, l, r, 2 * node + 1), query(mid + 1, end, l, r, 2 * node + 2)); } // Function that returns length of longest // subarray with same elements in atmost // K increments. static int longestSubArray(int []A, int N, int K) { // Initialize the result variable // Even though the K is 0, // the required longest subarray, // in that case, will also be of length 1 int res = 1; // Initialize the prefix sum array int []preSum = new int[N + 1]; // Build the prefix sum array preSum[0] = A[0]; for (int i = 0; i < N; i++) preSum[i + 1] = preSum[i] + A[i]; // Build the segment tree // for range max query build(A, 0, N - 1, 0); // Loop through the array // with a starting point as i // for the required subarray till // the longest subarray is found for (int i = 0; i < N; i++) { int start = i, end = N - 1, mid, max_index = i; // Performing the binary search // to find the endpoint // for the selected range while (start <= end) { // Find the mid for binary search mid = (start + end) / 2; // Find the max element // in the range [i, mid] // using Segment Tree int max_element = query(0, N - 1, i, mid, 0); // Total sum of subarray after increments int expected_sum = (mid - i + 1) * max_element; // Actual sum of elements // before increments int actual_sum = preSum[mid + 1] - preSum[i]; // Check if such increment is possible // If true, then current i // is the actual starting point // of the required longest subarray if (expected_sum - actual_sum <= K) { // Now for finding the endpoint // for this range // Perform the Binary search again // with the updated start start = mid + 1; // Store max end point for the range // to give longest subarray max_index = Math.Max(max_index, mid); } // If false, it means that // the selected range is invalid else { // Perform the Binary Search again // with the updated end end = mid - 1; } } // Store the length of longest subarray res = Math.Max(res, max_index - i + 1); } // Return result return res; } // Driver code public static void Main(String[] args) { int []arr = { 2, 0, 4, 6, 7 }; int K = 6; int N = arr.Length; Console.WriteLine(longestSubArray(arr, N, K)); }} // This code is contributed by PrinciRaj1992", "e": 44319, "s": 39511, "text": null }, { "code": "<script> // Javascript program to find the length of // Longest Subarray with same elements // in atmost K increments // Initialize array for segment tree let segment_tree = new Array(4 * 1000000); // Function that builds the segment // tree to return the max element // in a range function build(A, start, end, node) { if (start == end) // update the value in segment // tree from given array segment_tree[node] = A[start]; else { // find the middle index let mid = parseInt((start + end) / 2, 10); // If there are more than one // elements, then recur for left // and right subtrees and // store the max of values in this node segment_tree[node] = Math.max( build(A, start, mid, 2 * node + 1), build(A, mid + 1, end, 2 * node + 2)); } return segment_tree[node]; } // Function to return the max // element in the given range function query(start, end, l, r, node) { // If the range is out of bounds, // return -1 if (start > r || end < l) return -1; if (start >= l && end <= r) return segment_tree[node]; let mid = parseInt((start + end) / 2, 10); return Math.max(query(start, mid, l, r, 2 * node + 1), query(mid + 1, end, l, r, 2 * node + 2)); } // Function that returns length of longest // subarray with same elements in atmost // K increments. function longestSubArray(A, N, K) { // Initialize the result variable // Even though the K is 0, // the required longest subarray, // in that case, will also be of length 1 let res = 1; // Initialize the prefix sum array let preSum = new Array(N + 1); // Build the prefix sum array preSum[0] = A[0]; for (let i = 0; i < N; i++) preSum[i + 1] = preSum[i] + A[i]; // Build the segment tree // for range max query build(A, 0, N - 1, 0); // Loop through the array // with a starting point as i // for the required subarray till // the longest subarray is found for (let i = 0; i < N; i++) { let start = i, end = N - 1, mid, max_index = i; // Performing the binary search // to find the endpoint // for the selected range while (start <= end) { // Find the mid for binary search mid = parseInt((start + end) / 2, 10); // Find the max element // in the range [i, mid] // using Segment Tree let max_element = query(0, N - 1, i, mid, 0); // Total sum of subarray after increments let expected_sum = (mid - i + 1) * max_element; // Actual sum of elements // before increments let actual_sum = preSum[mid + 1] - preSum[i]; // Check if such increment is possible // If true, then current i // is the actual starting point // of the required longest subarray if (expected_sum - actual_sum <= K) { // Now for finding the endpoint // for this range // Perform the Binary search again // with the updated start start = mid + 1; // Store max end point for the range // to give longest subarray max_index = Math.max(max_index, mid); } // If false, it means that // the selected range is invalid else { // Perform the Binary Search again // with the updated end end = mid - 1; } } // Store the length of longest subarray res = Math.max(res, max_index - i + 1); } // Return result return res; } let arr = [ 2, 0, 4, 6, 7 ], K = 6; let N = arr.length; document.write(longestSubArray(arr, N, K)); </script>", "e": 48872, "s": 44319, "text": null }, { "code": null, "e": 48874, "s": 48872, "text": "3" }, { "code": null, "e": 48909, "s": 48876, "text": "Time Complexity: O(N*(log(N))2) " }, { "code": null, "e": 48917, "s": 48909, "text": "ankthon" }, { "code": null, "e": 48931, "s": 48917, "text": "princiraj1992" }, { "code": null, "e": 48942, "s": 48931, "text": "decode2207" }, { "code": null, "e": 48956, "s": 48942, "text": "Binary Search" }, { "code": null, "e": 48967, "s": 48956, "text": "prefix-sum" }, { "code": null, "e": 48980, "s": 48967, "text": "Segment-Tree" }, { "code": null, "e": 48989, "s": 48980, "text": "subarray" }, { "code": null, "e": 48996, "s": 48989, "text": "Arrays" }, { "code": null, "e": 49006, "s": 48996, "text": "Searching" }, { "code": null, "e": 49011, "s": 49006, "text": "Tree" }, { "code": null, "e": 49022, "s": 49011, "text": "prefix-sum" }, { "code": null, "e": 49029, "s": 49022, "text": "Arrays" }, { "code": null, "e": 49039, "s": 49029, "text": "Searching" }, { "code": null, "e": 49044, "s": 49039, "text": "Tree" }, { "code": null, "e": 49057, "s": 49044, "text": "Segment-Tree" }, { "code": null, "e": 49071, "s": 49057, "text": "Binary Search" }, { "code": null, "e": 49169, "s": 49071, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 49178, "s": 49169, "text": "Comments" }, { "code": null, "e": 49191, "s": 49178, "text": "Old Comments" }, { "code": null, "e": 49214, "s": 49191, "text": "Introduction to Arrays" }, { "code": null, "e": 49282, "s": 49214, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 49314, "s": 49282, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 49368, "s": 49314, "text": "Queue | Set 1 (Introduction and Array Implementation)" }, { "code": null, "e": 49389, "s": 49368, "text": "Linked List vs Array" }, { "code": null, "e": 49403, "s": 49389, "text": "Binary Search" }, { "code": null, "e": 49471, "s": 49403, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 49495, "s": 49471, "text": "Find the Missing Number" }, { "code": null, "e": 49551, "s": 49495, "text": "K'th Smallest/Largest Element in Unsorted Array | Set 1" } ]
Missing SAP Java Connector libraries JCo- librfc32.dll, com.sap.utils and com.sap.mw
Please note that all these library files - librfc32.dll, com.sap.utils and com.sap.mw come under JCo 2.1. With release of JCo 3.0, it’s classes were also relocated from packages com.sap.mw.jco.* to com.sap.conn.jco.* For running with SAP JCo 3.0, you need these files at runtime - sapjco3.jar and sapjco3.dll (on Windows). You can follow below procedure for installation of JCo files: In Windows OS, you have to copy sapjco3.jar file into ITDI_HOME/jars/3rdparty/others. Copy the sapjco3.dll file into ITDI_HOME/libs. On Windows, JCo 3 requires additional Microsoft Visual C++ 2005 libraries to be installed. Installation details for the package that contains these libraries are specified in Microsoft Knowledge Base article 973544. Restart the adapter service. Create a symbolic link to the sapjco3.jar file in ITDI_HOME/jars/3rdparty/others: ln -s <sapjco_install_dir>/sapjco3.jar ITDI_HOME/jars/3rdparty/others/sapjco3.jar Next is to add SAP JCo installation directory to the dynamic library path by following below steps: export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:<sapjco_install_dir> export LIBPATH=$LIBPATH:<sapjco_install_dir> Restart the Dispatcher.
[ { "code": null, "e": 1279, "s": 1062, "text": "Please note that all these library files - librfc32.dll, com.sap.utils and com.sap.mw come under JCo 2.1. With release of JCo 3.0, it’s classes were also relocated from packages com.sap.mw.jco.* to com.sap.conn.jco.*" }, { "code": null, "e": 1447, "s": 1279, "text": "For running with SAP JCo 3.0, you need these files at runtime - sapjco3.jar and sapjco3.dll (on Windows). You can follow below procedure for installation of JCo files:" }, { "code": null, "e": 1533, "s": 1447, "text": "In Windows OS, you have to copy sapjco3.jar file into ITDI_HOME/jars/3rdparty/others." }, { "code": null, "e": 1796, "s": 1533, "text": "Copy the sapjco3.dll file into ITDI_HOME/libs. On Windows, JCo 3 requires additional Microsoft Visual C++ 2005 libraries to be installed. Installation details for the package that contains these libraries are specified in Microsoft Knowledge Base article 973544." }, { "code": null, "e": 1825, "s": 1796, "text": "Restart the adapter service." }, { "code": null, "e": 1907, "s": 1825, "text": "Create a symbolic link to the sapjco3.jar file in ITDI_HOME/jars/3rdparty/others:" }, { "code": null, "e": 1989, "s": 1907, "text": "ln -s <sapjco_install_dir>/sapjco3.jar\nITDI_HOME/jars/3rdparty/others/sapjco3.jar" }, { "code": null, "e": 2089, "s": 1989, "text": "Next is to add SAP JCo installation directory to the dynamic library path by following below steps:" }, { "code": null, "e": 2195, "s": 2089, "text": "export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:<sapjco_install_dir>\nexport LIBPATH=$LIBPATH:<sapjco_install_dir>" }, { "code": null, "e": 2219, "s": 2195, "text": "Restart the Dispatcher." } ]
JavaFX | Tooltip - GeeksforGeeks
24 Oct, 2019 Tooltip is a part of JavaFx package. Tooltip is used to show additional information to the user when the mouse is hovered over the component. All the components can be associated with a tooltip and it can be also associated with a part of screen. Constructors of the Tooltip class: Tooltip(): Creates a tooltip with an empty string for its text.Tooltip(String t): Creates a tooltip with the specified text. Tooltip(): Creates a tooltip with an empty string for its text. Tooltip(String t): Creates a tooltip with the specified text. Commonly used methods: Below program illustrate the use of Tooltip in Java: Program to create a label and add Tooltip text to the labels: We will create 3 tooltip objects t, t1, t2 for labels l, l1 l2. Then we will set the font for two labels t1 and t2. For t we will set Arial font and for t1 Tooltip we will set Verdana font. We will set the textAlignment for text of t1 and t2 to Left and Right respectively and we can set the tooltip to a label using two ways: The first is by using setTooltip() function and other using install() function. After that a Tile-pane is created, on which addChildren() method is called to attach the labels inside the scene, along with the resolution specified by (200, 200) in the code. Finally the show() method is called to display the final results. // Java program to create label and add Tooltip text to the labelsimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.collections.*;import javafx.stage.Stage;import javafx.scene.text.Text.*;import javafx.scene.text.*;public class tooltip extends Application { // labels Label l, l1, l2; // tooltip Tooltip t, t1, t2; // launch the application public void start(Stage s) { // set title for the stage s.setTitle("creating Tooltip"); // create a tile pane TilePane r = new TilePane(); // create a label l = new Label("This is a label 1 "); l1 = new Label("This is a label 2 "); l2 = new Label("This is a label 3 "); // create tooltip for labels t = new Tooltip(); t1 = new Tooltip("tooltip for label 2"); t2 = new Tooltip("tooltip for label 3"); // set text for label 1 t.setText("tooltip for label 1"); // set font for tooltip t.setFont(Font.font("Arial", FontPosture.ITALIC, 15)); t1.setFont(Font.font("Verdana", FontPosture.REGULAR, 10)); // set alignment for tooltip text t1.setTextAlignment(TextAlignment.LEFT); t2.setTextAlignment(TextAlignment.RIGHT); // set the tooltip for labels l.setTooltip(t); l1.setTooltip(t1); Tooltip.install(l2, t2); // add label r.getChildren().add(l); r.getChildren().add(l1); r.getChildren().add(l2); // create a scene Scene sc = new Scene(r, 200, 200); // set the scene s.setScene(sc); s.show(); } public static void main(String args[]) { // launch the application launch(args); }} Output: Note: The above programs might not run in an online IDE please use an offline compiler. Reference: https://docs.oracle.com/javase/8/javafx/api/javafx/scene/control/Tooltip.html ManasChhabra2 JavaFX Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Different ways of Reading a text file in Java Constructors in Java Exceptions in Java Functional Interfaces in Java Generics in Java Comparator Interface in Java with Examples HashMap get() Method in Java Introduction to Java Difference between Abstract Class and Interface in Java
[ { "code": null, "e": 23948, "s": 23920, "text": "\n24 Oct, 2019" }, { "code": null, "e": 24195, "s": 23948, "text": "Tooltip is a part of JavaFx package. Tooltip is used to show additional information to the user when the mouse is hovered over the component. All the components can be associated with a tooltip and it can be also associated with a part of screen." }, { "code": null, "e": 24230, "s": 24195, "text": "Constructors of the Tooltip class:" }, { "code": null, "e": 24355, "s": 24230, "text": "Tooltip(): Creates a tooltip with an empty string for its text.Tooltip(String t): Creates a tooltip with the specified text." }, { "code": null, "e": 24419, "s": 24355, "text": "Tooltip(): Creates a tooltip with an empty string for its text." }, { "code": null, "e": 24481, "s": 24419, "text": "Tooltip(String t): Creates a tooltip with the specified text." }, { "code": null, "e": 24504, "s": 24481, "text": "Commonly used methods:" }, { "code": null, "e": 24557, "s": 24504, "text": "Below program illustrate the use of Tooltip in Java:" }, { "code": null, "e": 25269, "s": 24557, "text": "Program to create a label and add Tooltip text to the labels: We will create 3 tooltip objects t, t1, t2 for labels l, l1 l2. Then we will set the font for two labels t1 and t2. For t we will set Arial font and for t1 Tooltip we will set Verdana font. We will set the textAlignment for text of t1 and t2 to Left and Right respectively and we can set the tooltip to a label using two ways: The first is by using setTooltip() function and other using install() function. After that a Tile-pane is created, on which addChildren() method is called to attach the labels inside the scene, along with the resolution specified by (200, 200) in the code. Finally the show() method is called to display the final results." }, { "code": "// Java program to create label and add Tooltip text to the labelsimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.collections.*;import javafx.stage.Stage;import javafx.scene.text.Text.*;import javafx.scene.text.*;public class tooltip extends Application { // labels Label l, l1, l2; // tooltip Tooltip t, t1, t2; // launch the application public void start(Stage s) { // set title for the stage s.setTitle(\"creating Tooltip\"); // create a tile pane TilePane r = new TilePane(); // create a label l = new Label(\"This is a label 1 \"); l1 = new Label(\"This is a label 2 \"); l2 = new Label(\"This is a label 3 \"); // create tooltip for labels t = new Tooltip(); t1 = new Tooltip(\"tooltip for label 2\"); t2 = new Tooltip(\"tooltip for label 3\"); // set text for label 1 t.setText(\"tooltip for label 1\"); // set font for tooltip t.setFont(Font.font(\"Arial\", FontPosture.ITALIC, 15)); t1.setFont(Font.font(\"Verdana\", FontPosture.REGULAR, 10)); // set alignment for tooltip text t1.setTextAlignment(TextAlignment.LEFT); t2.setTextAlignment(TextAlignment.RIGHT); // set the tooltip for labels l.setTooltip(t); l1.setTooltip(t1); Tooltip.install(l2, t2); // add label r.getChildren().add(l); r.getChildren().add(l1); r.getChildren().add(l2); // create a scene Scene sc = new Scene(r, 200, 200); // set the scene s.setScene(sc); s.show(); } public static void main(String args[]) { // launch the application launch(args); }}", "e": 27141, "s": 25269, "text": null }, { "code": null, "e": 27149, "s": 27141, "text": "Output:" }, { "code": null, "e": 27237, "s": 27149, "text": "Note: The above programs might not run in an online IDE please use an offline compiler." }, { "code": null, "e": 27326, "s": 27237, "text": "Reference: https://docs.oracle.com/javase/8/javafx/api/javafx/scene/control/Tooltip.html" }, { "code": null, "e": 27340, "s": 27326, "text": "ManasChhabra2" }, { "code": null, "e": 27347, "s": 27340, "text": "JavaFX" }, { "code": null, "e": 27352, "s": 27347, "text": "Java" }, { "code": null, "e": 27357, "s": 27352, "text": "Java" }, { "code": null, "e": 27455, "s": 27357, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27470, "s": 27455, "text": "Stream In Java" }, { "code": null, "e": 27516, "s": 27470, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 27537, "s": 27516, "text": "Constructors in Java" }, { "code": null, "e": 27556, "s": 27537, "text": "Exceptions in Java" }, { "code": null, "e": 27586, "s": 27556, "text": "Functional Interfaces in Java" }, { "code": null, "e": 27603, "s": 27586, "text": "Generics in Java" }, { "code": null, "e": 27646, "s": 27603, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 27675, "s": 27646, "text": "HashMap get() Method in Java" }, { "code": null, "e": 27696, "s": 27675, "text": "Introduction to Java" } ]
Pascal - Arrays
Pascal programming language provides a data structure called the array, which can store a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type. Instead of declaring individual variables, such as number1, number2, ..., and number100, you declare one array variable such as numbers and use numbers[1], numbers[2], and ..., numbers[100] to represent individual variables. A specific element in an array is accessed by an index. All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element. Please note that if you want a C style array starting from index 0, you just need to start the index from 0, instead of 1. To declare an array in Pascal, a programmer may either declare the type and then create variables of that array or directly declare the array variable. The general form of type declaration of one-dimensional array is − type array-identifier = array[index-type] of element-type; Where, array-identifier − indicates the name of the array type. array-identifier − indicates the name of the array type. index-type − specifies the subscript of the array; it can be any scalar data type except real index-type − specifies the subscript of the array; it can be any scalar data type except real element-type − specifies the types of values that are going to be stored element-type − specifies the types of values that are going to be stored For example, type vector = array [ 1..25] of real; var velocity: vector; Now, velocity is a variable array of vector type, which is sufficient to hold up to 25 real numbers. To start the array from 0 index, the declaration would be − type vector = array [ 0..24] of real; var velocity: vector; In Pascal, an array subscript could be of any scalar type like, integer, Boolean, enumerated or subrange, except real. Array subscripts could have negative values too. For example, type temperature = array [-10 .. 50] of real; var day_temp, night_temp: temperature; Let us take up another example where the subscript is of character type − type ch_array = array[char] of 1..26; var alphabet: ch_array; Subscript could be of enumerated type − type color = ( red, black, blue, silver, beige); car_color = array of [color] of boolean; var car_body: car_color; In Pascal, arrays are initialized through assignment, either by specifying a particular subscript or using a for-do loop. For example − type ch_array = array[char] of 1..26; var alphabet: ch_array; c: char; begin ... for c:= 'A' to 'Z' do alphabet[c] := ord[m]; (* the ord() function returns the ordinal values *) An element is accessed by indexing the array name. This is done by placing the index of the element within square brackets after the name of the array. For example − a: integer; a: = alphabet['A']; The above statement will take the first element from the array named alphabet and assign the value to the variable a. Following is an example, which will use all the above-mentioned three concepts viz. declaration, assignment and accessing arrays − program exArrays; var n: array [1..10] of integer; (* n is an array of 10 integers *) i, j: integer; begin (* initialize elements of array n to 0 *) for i := 1 to 10 do n[ i ] := i + 100; (* set element at location i to i + 100 *) (* output each array element's value *) for j:= 1 to 10 do writeln('Element[', j, '] = ', n[j] ); end. When the above code is compiled and executed, it produces the following result − Element[1] = 101 Element[2] = 102 Element[3] = 103 Element[4] = 104 Element[5] = 105 Element[6] = 106 Element[7] = 107 Element[8] = 108 Element[9] = 109 Element[10] = 110 Arrays are important to Pascal and should need lots of more details. There are following few important concepts related to array which should be clear to a Pascal programmer − Pascal supports multidimensional arrays. The simplest form of the multidimensional array is the two-dimensional array. In this type of arrays, the initial length is zero. The actual length of the array must be set with the standard SetLength function. These arrays are bit-packed, i.e., each character or truth values are stored in consecutive bytes instead of using one storage unit, usually a word (4 bytes or more). You can pass to a subprogram a pointer to an array by specifying the array's name without an index. 94 Lectures 8.5 hours Stone River ELearning Print Add Notes Bookmark this page
[ { "code": null, "e": 2380, "s": 2083, "text": "Pascal programming language provides a data structure called the array, which can store a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type." }, { "code": null, "e": 2661, "s": 2380, "text": "Instead of declaring individual variables, such as number1, number2, ..., and number100, you declare one array variable such as numbers and use numbers[1], numbers[2], and ..., numbers[100] to represent individual variables. A specific element in an array is accessed by an index." }, { "code": null, "e": 2809, "s": 2661, "text": "All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element." }, { "code": null, "e": 2932, "s": 2809, "text": "Please note that if you want a C style array starting from index 0, you just need to start the index from 0, instead of 1." }, { "code": null, "e": 3084, "s": 2932, "text": "To declare an array in Pascal, a programmer may either declare the type and then create variables of that array or directly declare the array variable." }, { "code": null, "e": 3151, "s": 3084, "text": "The general form of type declaration of one-dimensional array is −" }, { "code": null, "e": 3213, "s": 3151, "text": "type\n array-identifier = array[index-type] of element-type;" }, { "code": null, "e": 3220, "s": 3213, "text": "Where," }, { "code": null, "e": 3277, "s": 3220, "text": "array-identifier − indicates the name of the array type." }, { "code": null, "e": 3334, "s": 3277, "text": "array-identifier − indicates the name of the array type." }, { "code": null, "e": 3428, "s": 3334, "text": "index-type − specifies the subscript of the array; it can be any scalar data type except real" }, { "code": null, "e": 3522, "s": 3428, "text": "index-type − specifies the subscript of the array; it can be any scalar data type except real" }, { "code": null, "e": 3595, "s": 3522, "text": "element-type − specifies the types of values that are going to be stored" }, { "code": null, "e": 3668, "s": 3595, "text": "element-type − specifies the types of values that are going to be stored" }, { "code": null, "e": 3681, "s": 3668, "text": "For example," }, { "code": null, "e": 3747, "s": 3681, "text": "type\n vector = array [ 1..25] of real;\nvar\n velocity: vector;" }, { "code": null, "e": 3848, "s": 3747, "text": "Now, velocity is a variable array of vector type, which is sufficient to hold up to 25 real numbers." }, { "code": null, "e": 3908, "s": 3848, "text": "To start the array from 0 index, the declaration would be −" }, { "code": null, "e": 3974, "s": 3908, "text": "type\n vector = array [ 0..24] of real;\nvar\n velocity: vector;" }, { "code": null, "e": 4142, "s": 3974, "text": "In Pascal, an array subscript could be of any scalar type like, integer, Boolean, enumerated or subrange, except real. Array subscripts could have negative values too." }, { "code": null, "e": 4155, "s": 4142, "text": "For example," }, { "code": null, "e": 4246, "s": 4155, "text": "type\n temperature = array [-10 .. 50] of real;\nvar\n day_temp, night_temp: temperature;" }, { "code": null, "e": 4320, "s": 4246, "text": "Let us take up another example where the subscript is of character type −" }, { "code": null, "e": 4388, "s": 4320, "text": "type\n ch_array = array[char] of 1..26;\nvar\n alphabet: ch_array;" }, { "code": null, "e": 4428, "s": 4388, "text": "Subscript could be of enumerated type −" }, { "code": null, "e": 4552, "s": 4428, "text": "type\n color = ( red, black, blue, silver, beige);\n car_color = array of [color] of boolean;\nvar\n car_body: car_color;" }, { "code": null, "e": 4674, "s": 4552, "text": "In Pascal, arrays are initialized through assignment, either by specifying a particular subscript or using a for-do loop." }, { "code": null, "e": 4688, "s": 4674, "text": "For example −" }, { "code": null, "e": 4890, "s": 4688, "text": "type\n ch_array = array[char] of 1..26;\nvar\n alphabet: ch_array;\n c: char;\n\nbegin\n ...\n for c:= 'A' to 'Z' do\n alphabet[c] := ord[m]; \n (* the ord() function returns the ordinal values *)" }, { "code": null, "e": 5056, "s": 4890, "text": "An element is accessed by indexing the array name. This is done by placing the index of the element within square brackets after the name of the array. For example −" }, { "code": null, "e": 5088, "s": 5056, "text": "a: integer;\na: = alphabet['A'];" }, { "code": null, "e": 5206, "s": 5088, "text": "The above statement will take the first element from the array named alphabet and assign the value to the variable a." }, { "code": null, "e": 5337, "s": 5206, "text": "Following is an example, which will use all the above-mentioned three concepts viz. declaration, assignment and accessing arrays −" }, { "code": null, "e": 5720, "s": 5337, "text": "program exArrays;\nvar\n n: array [1..10] of integer; (* n is an array of 10 integers *)\n i, j: integer;\n\nbegin\n (* initialize elements of array n to 0 *) \n for i := 1 to 10 do\n n[ i ] := i + 100; (* set element at location i to i + 100 *)\n (* output each array element's value *)\n \n for j:= 1 to 10 do\n writeln('Element[', j, '] = ', n[j] );\nend." }, { "code": null, "e": 5801, "s": 5720, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 5973, "s": 5801, "text": "Element[1] = 101\nElement[2] = 102\nElement[3] = 103\nElement[4] = 104\nElement[5] = 105\nElement[6] = 106\nElement[7] = 107\nElement[8] = 108\nElement[9] = 109\nElement[10] = 110\n" }, { "code": null, "e": 6149, "s": 5973, "text": "Arrays are important to Pascal and should need lots of more details. There are following few important concepts related to array which should be clear to a Pascal programmer −" }, { "code": null, "e": 6268, "s": 6149, "text": "Pascal supports multidimensional arrays. The simplest form of the multidimensional array is the two-dimensional array." }, { "code": null, "e": 6401, "s": 6268, "text": "In this type of arrays, the initial length is zero. The actual length of the array must be set with the standard SetLength function." }, { "code": null, "e": 6568, "s": 6401, "text": "These arrays are bit-packed, i.e., each character or truth values are stored in consecutive bytes instead of using one storage unit, usually a word (4 bytes or more)." }, { "code": null, "e": 6668, "s": 6568, "text": "You can pass to a subprogram a pointer to an array by specifying the array's name without an index." }, { "code": null, "e": 6703, "s": 6668, "text": "\n 94 Lectures \n 8.5 hours \n" }, { "code": null, "e": 6726, "s": 6703, "text": " Stone River ELearning" }, { "code": null, "e": 6733, "s": 6726, "text": " Print" }, { "code": null, "e": 6744, "s": 6733, "text": " Add Notes" } ]
Physical Computing using Jupyter Notebook | by Marcelo Rovai | Towards Data Science
Learn how to install Jupyter Notebook on a Raspberry Pi, and directly on it, read sensors and act on actuators. We all know that Jupyter Notebook is a fantastic tool, or better, an open-source web application that allows you to create and share documents that contain live code, equations, visualizations and narrative text. Jupyter Notebook is largely used in Data Science, cleaning and transforming data, doing numerical simulation, statistical modeling, data visualization, machine learning, and much more! But, how about to use Jupyter Notebooks to control Raspberry Pi GPIOs? That’s is what we will do in this tutorial. We will learn how to install Jupyter Notebook on a Raspberry Pi, and directly on it, we will read sensors and act on actuators. The diagram gives us an an overview about the project: And the movie can give you a hint of what is possible to get when the Pi meets Jupyter! Raspberry Pi V3 DHT22 Temperature and Relative Humidity Sensor DS18B20 Waterproof Temperature Sensor BMP180 Barometric Pressure, Temperature and Altitude Sensor LEDS (3x) Push Button (1x) Resistor 4K7 ohm (2x) Resistor 1K ohm (1x) Resistor 330 ohm (3x) Protoboard and cables Let’s follow the above electrical diagram and connect all 3 sensors, buttons and LEDs to Raspberry Pi. The sensors used here in this project, are the same used on my tutorial: IoT Weather Station With RPi and ESP8266 I suggest that you give a look on that tutorial, where I explain one by one, how to install the sensors and their libraries, testing them individually before running the complete program. To install Jupyter on your Raspberry (that will run with Python 3), open Terminal and enter with following commands: sudo pip3 install jupytersudo ipython3 kernelspec install-self Now on your terminal, run the command: jupyter notebook And that’s it!!!! Amazing! very simple and easy. The Jupyter Notebook will be running as a server on: http:localhost:8888 But, this is not really important for you to know, because, automatically your default browser will be opened on that address, running a “Home Page”. To stop the server and close the “kernels” (the Jupyter notebooks), you must use [Ctrl] + [C] from your keyboard. From now one, any time that you start your Pi and want use Jupyter Notebook, just type the command “Jupyter notebook” on your terminal and keep it running all the time. This is very important! If you need to use the terminal for another task, as run a program, for example, open a new Terminal window. We are assuming that you are familiar with Jupyter Notebook. It will work on your Pi exactly as it works on your desktop. There are “tons” of good Jupyter Notebook tutorials available on the web, just goggle it and you certainly will find one more suitable for you. Let’s play with a notebook that I have already created for this tutorial. Download it from my GitHub: Weather Station Sensors — Actuators Save the notebook on your Raspberry Pi. In my case, I save it on my main directory (see the homepage printscreen above). Observe that exist 4 notebooks in my main directory (notebooks have a “small notebook” as an icon). Just click on it. The notebook will be loaded and will appear as the one above. If you see the homepage again, you will realize that the “notebook icon” is now “green”, that means that it is running. Also, note that there is a picture of the HW at first cell of my notebook. For the picture to appear correctly, you must or have it in the same directory (that is my case) or change its path on the notebook if you uses another directory to store the picture. You can enter with Unix commands directlly on a Notebook cell, same as you do in your Terminal For example, the command: ls Will list all your files in the current directory where the notebook is running, as you can see here: So, the idea is to start writing your script in the same way (and order) that you are used to do with a Python IDE. I will split my notebook into 3 phases, where we will do: Initialization Initialization Import Libraries Define GPIOs Initialize GPIOs Create important functions 2. Reading Sensors 3. Reading and Acting on GPIOs (Button and LEDs) Important to note that usually, you will run the Initialization phase only once. After that, you can play with your sensors and GPIOs, running only the pertinent cells created for Phase 2 and 3, as in this example. For phase 1 better understand, you can follow the introduction movie. Running the Cell [11] you will get all sensors data: Widgets Here it is important to call attention to the “Widgets”. Widgets are eventful python objects that have a representation in the browser, often as a control like a slider, textbox, etc. You can use widgets to build interactive GUIs for your notebooks. You can also use widgets to synchronize stateful and stateless information between Python and JavaScript. Here in this example, we are using widgets (“Sliders”) to on cell [12}, control in REAL TIME the state of actuators, in this case, turning on or off the LEDs. Widgets are great to add more dynamic behavior on Jupyter Notebooks. As you saw, on the code, we must run the cell [11] any time that we want an update value of sensors, but of course, a widget could also be implemented here to do it automatically, or by pressing a button, for example. I will leave it as a challenge for you! ;-) Installation In order to use Widgets, you must install the Ipywidgets library. For that use below commands: sudo pip3 install ipywidgetsjupyter nbextension enable --py widgetsnbextension After installation, only call the library on your Jupyter Notebook. Note that we have done it, in the beginning, at initialization phase : # widget libraryfrom ipywidgets import interactiveimport ipywidgets as widgetsfrom IPython.display import display This Widget, “interactive”, is simple to be implemented and very powerful. You can learn more about Interactive on this link: Interactive Widget. I am starting new journeys on this fascinating world of technology. Everything that we see today has data related and knowing better those data can be key to relevant projects that can help people. You will see more and more, here and on my blog MJRoBot.org, tutorials where DataScience is mixed with Physical Computing, Computer Vision, Machine Learning and IoT. As an example, I played with data from a previous IoT project, the ArduFarmBot : Using the data that was logged on a IoT Platform, the ThingSpeak and appliyng Machine Learn on those data, was possible to predict (in fact confirm) when the lamp and the pump should be turned on. The results were amazing!!!!!! You can see the Jupyter Notebook and the final report on my GitHub: ArduFarmBot_Data_Analysis That’s all, folks! ;-) As always, I hope this project can help others find their way into the exciting world of electronics! For details and final code, please visit my GitHub depository: Pyhon4DS/RaspberryPi For more projects, please visit my blog: MJRoBot.org Stay tuned! Next tutorial we will send data from a remote weather station to a central one, based on a Raspberry Pi Flask Web server: Saludos from the south of the world! See you in my next tutorial! Thank you, Marcelo No rights reserved by the author.
[ { "code": null, "e": 283, "s": 171, "text": "Learn how to install Jupyter Notebook on a Raspberry Pi, and directly on it, read sensors and act on actuators." }, { "code": null, "e": 496, "s": 283, "text": "We all know that Jupyter Notebook is a fantastic tool, or better, an open-source web application that allows you to create and share documents that contain live code, equations, visualizations and narrative text." }, { "code": null, "e": 681, "s": 496, "text": "Jupyter Notebook is largely used in Data Science, cleaning and transforming data, doing numerical simulation, statistical modeling, data visualization, machine learning, and much more!" }, { "code": null, "e": 752, "s": 681, "text": "But, how about to use Jupyter Notebooks to control Raspberry Pi GPIOs?" }, { "code": null, "e": 924, "s": 752, "text": "That’s is what we will do in this tutorial. We will learn how to install Jupyter Notebook on a Raspberry Pi, and directly on it, we will read sensors and act on actuators." }, { "code": null, "e": 979, "s": 924, "text": "The diagram gives us an an overview about the project:" }, { "code": null, "e": 1067, "s": 979, "text": "And the movie can give you a hint of what is possible to get when the Pi meets Jupyter!" }, { "code": null, "e": 1083, "s": 1067, "text": "Raspberry Pi V3" }, { "code": null, "e": 1130, "s": 1083, "text": "DHT22 Temperature and Relative Humidity Sensor" }, { "code": null, "e": 1168, "s": 1130, "text": "DS18B20 Waterproof Temperature Sensor" }, { "code": null, "e": 1228, "s": 1168, "text": "BMP180 Barometric Pressure, Temperature and Altitude Sensor" }, { "code": null, "e": 1238, "s": 1228, "text": "LEDS (3x)" }, { "code": null, "e": 1255, "s": 1238, "text": "Push Button (1x)" }, { "code": null, "e": 1277, "s": 1255, "text": "Resistor 4K7 ohm (2x)" }, { "code": null, "e": 1298, "s": 1277, "text": "Resistor 1K ohm (1x)" }, { "code": null, "e": 1320, "s": 1298, "text": "Resistor 330 ohm (3x)" }, { "code": null, "e": 1342, "s": 1320, "text": "Protoboard and cables" }, { "code": null, "e": 1445, "s": 1342, "text": "Let’s follow the above electrical diagram and connect all 3 sensors, buttons and LEDs to Raspberry Pi." }, { "code": null, "e": 1518, "s": 1445, "text": "The sensors used here in this project, are the same used on my tutorial:" }, { "code": null, "e": 1559, "s": 1518, "text": "IoT Weather Station With RPi and ESP8266" }, { "code": null, "e": 1747, "s": 1559, "text": "I suggest that you give a look on that tutorial, where I explain one by one, how to install the sensors and their libraries, testing them individually before running the complete program." }, { "code": null, "e": 1864, "s": 1747, "text": "To install Jupyter on your Raspberry (that will run with Python 3), open Terminal and enter with following commands:" }, { "code": null, "e": 1927, "s": 1864, "text": "sudo pip3 install jupytersudo ipython3 kernelspec install-self" }, { "code": null, "e": 1966, "s": 1927, "text": "Now on your terminal, run the command:" }, { "code": null, "e": 1983, "s": 1966, "text": "jupyter notebook" }, { "code": null, "e": 2085, "s": 1983, "text": "And that’s it!!!! Amazing! very simple and easy. The Jupyter Notebook will be running as a server on:" }, { "code": null, "e": 2105, "s": 2085, "text": "http:localhost:8888" }, { "code": null, "e": 2255, "s": 2105, "text": "But, this is not really important for you to know, because, automatically your default browser will be opened on that address, running a “Home Page”." }, { "code": null, "e": 2369, "s": 2255, "text": "To stop the server and close the “kernels” (the Jupyter notebooks), you must use [Ctrl] + [C] from your keyboard." }, { "code": null, "e": 2671, "s": 2369, "text": "From now one, any time that you start your Pi and want use Jupyter Notebook, just type the command “Jupyter notebook” on your terminal and keep it running all the time. This is very important! If you need to use the terminal for another task, as run a program, for example, open a new Terminal window." }, { "code": null, "e": 2793, "s": 2671, "text": "We are assuming that you are familiar with Jupyter Notebook. It will work on your Pi exactly as it works on your desktop." }, { "code": null, "e": 2937, "s": 2793, "text": "There are “tons” of good Jupyter Notebook tutorials available on the web, just goggle it and you certainly will find one more suitable for you." }, { "code": null, "e": 3011, "s": 2937, "text": "Let’s play with a notebook that I have already created for this tutorial." }, { "code": null, "e": 3075, "s": 3011, "text": "Download it from my GitHub: Weather Station Sensors — Actuators" }, { "code": null, "e": 3496, "s": 3075, "text": "Save the notebook on your Raspberry Pi. In my case, I save it on my main directory (see the homepage printscreen above). Observe that exist 4 notebooks in my main directory (notebooks have a “small notebook” as an icon). Just click on it. The notebook will be loaded and will appear as the one above. If you see the homepage again, you will realize that the “notebook icon” is now “green”, that means that it is running." }, { "code": null, "e": 3755, "s": 3496, "text": "Also, note that there is a picture of the HW at first cell of my notebook. For the picture to appear correctly, you must or have it in the same directory (that is my case) or change its path on the notebook if you uses another directory to store the picture." }, { "code": null, "e": 3850, "s": 3755, "text": "You can enter with Unix commands directlly on a Notebook cell, same as you do in your Terminal" }, { "code": null, "e": 3876, "s": 3850, "text": "For example, the command:" }, { "code": null, "e": 3879, "s": 3876, "text": "ls" }, { "code": null, "e": 3981, "s": 3879, "text": "Will list all your files in the current directory where the notebook is running, as you can see here:" }, { "code": null, "e": 4097, "s": 3981, "text": "So, the idea is to start writing your script in the same way (and order) that you are used to do with a Python IDE." }, { "code": null, "e": 4155, "s": 4097, "text": "I will split my notebook into 3 phases, where we will do:" }, { "code": null, "e": 4170, "s": 4155, "text": "Initialization" }, { "code": null, "e": 4185, "s": 4170, "text": "Initialization" }, { "code": null, "e": 4202, "s": 4185, "text": "Import Libraries" }, { "code": null, "e": 4215, "s": 4202, "text": "Define GPIOs" }, { "code": null, "e": 4232, "s": 4215, "text": "Initialize GPIOs" }, { "code": null, "e": 4259, "s": 4232, "text": "Create important functions" }, { "code": null, "e": 4278, "s": 4259, "text": "2. Reading Sensors" }, { "code": null, "e": 4327, "s": 4278, "text": "3. Reading and Acting on GPIOs (Button and LEDs)" }, { "code": null, "e": 4542, "s": 4327, "text": "Important to note that usually, you will run the Initialization phase only once. After that, you can play with your sensors and GPIOs, running only the pertinent cells created for Phase 2 and 3, as in this example." }, { "code": null, "e": 4612, "s": 4542, "text": "For phase 1 better understand, you can follow the introduction movie." }, { "code": null, "e": 4665, "s": 4612, "text": "Running the Cell [11] you will get all sensors data:" }, { "code": null, "e": 4673, "s": 4665, "text": "Widgets" }, { "code": null, "e": 4730, "s": 4673, "text": "Here it is important to call attention to the “Widgets”." }, { "code": null, "e": 5029, "s": 4730, "text": "Widgets are eventful python objects that have a representation in the browser, often as a control like a slider, textbox, etc. You can use widgets to build interactive GUIs for your notebooks. You can also use widgets to synchronize stateful and stateless information between Python and JavaScript." }, { "code": null, "e": 5257, "s": 5029, "text": "Here in this example, we are using widgets (“Sliders”) to on cell [12}, control in REAL TIME the state of actuators, in this case, turning on or off the LEDs. Widgets are great to add more dynamic behavior on Jupyter Notebooks." }, { "code": null, "e": 5519, "s": 5257, "text": "As you saw, on the code, we must run the cell [11] any time that we want an update value of sensors, but of course, a widget could also be implemented here to do it automatically, or by pressing a button, for example. I will leave it as a challenge for you! ;-)" }, { "code": null, "e": 5532, "s": 5519, "text": "Installation" }, { "code": null, "e": 5627, "s": 5532, "text": "In order to use Widgets, you must install the Ipywidgets library. For that use below commands:" }, { "code": null, "e": 5706, "s": 5627, "text": "sudo pip3 install ipywidgetsjupyter nbextension enable --py widgetsnbextension" }, { "code": null, "e": 5774, "s": 5706, "text": "After installation, only call the library on your Jupyter Notebook." }, { "code": null, "e": 5845, "s": 5774, "text": "Note that we have done it, in the beginning, at initialization phase :" }, { "code": null, "e": 5959, "s": 5845, "text": "# widget libraryfrom ipywidgets import interactiveimport ipywidgets as widgetsfrom IPython.display import display" }, { "code": null, "e": 6105, "s": 5959, "text": "This Widget, “interactive”, is simple to be implemented and very powerful. You can learn more about Interactive on this link: Interactive Widget." }, { "code": null, "e": 6469, "s": 6105, "text": "I am starting new journeys on this fascinating world of technology. Everything that we see today has data related and knowing better those data can be key to relevant projects that can help people. You will see more and more, here and on my blog MJRoBot.org, tutorials where DataScience is mixed with Physical Computing, Computer Vision, Machine Learning and IoT." }, { "code": null, "e": 6550, "s": 6469, "text": "As an example, I played with data from a previous IoT project, the ArduFarmBot :" }, { "code": null, "e": 6747, "s": 6550, "text": "Using the data that was logged on a IoT Platform, the ThingSpeak and appliyng Machine Learn on those data, was possible to predict (in fact confirm) when the lamp and the pump should be turned on." }, { "code": null, "e": 6778, "s": 6747, "text": "The results were amazing!!!!!!" }, { "code": null, "e": 6872, "s": 6778, "text": "You can see the Jupyter Notebook and the final report on my GitHub: ArduFarmBot_Data_Analysis" }, { "code": null, "e": 6895, "s": 6872, "text": "That’s all, folks! ;-)" }, { "code": null, "e": 6997, "s": 6895, "text": "As always, I hope this project can help others find their way into the exciting world of electronics!" }, { "code": null, "e": 7081, "s": 6997, "text": "For details and final code, please visit my GitHub depository: Pyhon4DS/RaspberryPi" }, { "code": null, "e": 7134, "s": 7081, "text": "For more projects, please visit my blog: MJRoBot.org" }, { "code": null, "e": 7268, "s": 7134, "text": "Stay tuned! Next tutorial we will send data from a remote weather station to a central one, based on a Raspberry Pi Flask Web server:" }, { "code": null, "e": 7305, "s": 7268, "text": "Saludos from the south of the world!" }, { "code": null, "e": 7334, "s": 7305, "text": "See you in my next tutorial!" }, { "code": null, "e": 7345, "s": 7334, "text": "Thank you," }, { "code": null, "e": 7353, "s": 7345, "text": "Marcelo" }, { "code": null, "e": 7372, "s": 7353, "text": "No rights reserved" } ]
Send keys without specifying element in Python Selenium webdriver
We can send keys without specifying elements in Python with Selenium webdriver. The tagname input is used for all the edit boxes. We shall use the find_element_by_tag_name method and pass input as a parameter to that method. Thus we need not mention element attributes explicitly. Let us investigate the html code of an element which can be identified with tagname input. from selenium import webdriver #set geckodriver.exe path driver = webdriver.Firefox(executable_path="C:\\geckodriver.exe") driver.implicitly_wait(0.5) driver.get("https://www.tutorialspoint.com/index.htm") #identify element with tagname l = driver.find_element_by_tag_name("input") l.send_keys("Selenium") #obtain value obtained print("Value entered: ") print(l.get_attribute('value')) driver.quit()
[ { "code": null, "e": 1287, "s": 1062, "text": "We can send keys without specifying elements in Python with Selenium webdriver. The tagname input is used for all the edit boxes. We shall use the find_element_by_tag_name method and pass input as a parameter to that method." }, { "code": null, "e": 1434, "s": 1287, "text": "Thus we need not mention element attributes explicitly. Let us investigate the html code of an element which can be identified with tagname input." }, { "code": null, "e": 1834, "s": 1434, "text": "from selenium import webdriver\n#set geckodriver.exe path\ndriver = webdriver.Firefox(executable_path=\"C:\\\\geckodriver.exe\")\ndriver.implicitly_wait(0.5)\ndriver.get(\"https://www.tutorialspoint.com/index.htm\")\n#identify element with tagname\nl = driver.find_element_by_tag_name(\"input\")\nl.send_keys(\"Selenium\")\n#obtain value obtained\nprint(\"Value entered: \")\nprint(l.get_attribute('value'))\ndriver.quit()" } ]
Program to loop on every character in string in C++
Here in this program we will see how to iterate through each characters of a string in C++. To loop on each character, we can use loops starting from 0 to (string length – 1). For accessing the character we can either use subscript operator "[ ]" or at() function of string object. Input: A string “Hello World” Output: “Hello World” Step 1: Get the string Step 2: Use R before string to make it raw string Step 3: End Live Demo #include<iostream> using namespace std; main() { string my_str = "Hello World"; for(int i = 0; i<my_str.length(); i++) { cout << my_str.at(i) << endl; //get character at position i } } H e l l o W o r l d
[ { "code": null, "e": 1344, "s": 1062, "text": "Here in this program we will see how to iterate through each characters of a string in C++. To loop on each character, we can use loops starting from 0 to (string length – 1). For accessing the character we can either use subscript operator \"[ ]\" or at() function of string object." }, { "code": null, "e": 1396, "s": 1344, "text": "Input: A string “Hello World”\nOutput: “Hello World”" }, { "code": null, "e": 1481, "s": 1396, "text": "Step 1: Get the string\nStep 2: Use R before string to make it raw string\nStep 3: End" }, { "code": null, "e": 1492, "s": 1481, "text": " Live Demo" }, { "code": null, "e": 1692, "s": 1492, "text": "#include<iostream>\nusing namespace std;\nmain() {\n string my_str = \"Hello World\";\n for(int i = 0; i<my_str.length(); i++) {\n cout << my_str.at(i) << endl; //get character at position i\n }\n}" }, { "code": null, "e": 1713, "s": 1692, "text": "H\ne\nl\nl\no\n\nW\no\nr\nl\nd" } ]
jQuery - serialize( ) Method
The serialize( ) method serializes a set of input elements into a string of data. Here is the simple syntax to use this method − $.serialize( ) Here is the description of all the parameters used by this method − NA NA Assuming we have following PHP content in serialize.php file − <?php if( $_REQUEST["name"] ) { $name = $_REQUEST['name']; echo "Welcome ". $name; $age = $_REQUEST['age']; echo "<br />Your age : ". $age; $sex = $_REQUEST['sex']; echo "<br />Your gender : ". $sex; } ?> Following is a simple example a simple showing the usage of this method − <html> <head> <title>The jQuery Example</title> <script type = "text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script> <script type = "text/javascript" language = "javascript"> $(document).ready(function() { $("#driver").click(function(event){ $.post( "/jquery/serialize.php", $("#testform").serialize(), function(data) { $('#stage1').html(data); } ); var str = $("#testform").serialize(); $("#stage2").text(str); }); }); </script> </head> <body> <p>Click on the button to load result.html file:</p> <div id = "stage1" style = "background-color:blue;"> STAGE - 1 </div> <br /> <div id = "stage2" style = "background-color:blue;"> STAGE - 2 </div> <form id = "testform"> <table> <tr> <td><p>Name:</p></td> <td><input type = "text" name = "name" size = "40" /></td> </tr> <tr> <td><p>Age:</p></td> <td><input type = "text" name = "age" size = "40" /></td> </tr> <tr> <td><p>Sex:</p></td> <td> <select name = "sex"> <option value = "Male" selected>Male</option> <option value = "Female" selected>Female</option> </select></td> </tr> <tr> <td colspan = "2"> <input type = "button" id = "driver" value = "Load Data" /> </td> </tr> </table> </form> </body> </html> This will produce following result − Click on the button to load result.html file − Name − Age − Sex − 27 Lectures 1 hours Mahesh Kumar 27 Lectures 1.5 hours Pratik Singh 72 Lectures 4.5 hours Frahaan Hussain 60 Lectures 9 hours Eduonix Learning Solutions 17 Lectures 2 hours Sandip Bhattacharya 12 Lectures 53 mins Laurence Svekis Print Add Notes Bookmark this page
[ { "code": null, "e": 2404, "s": 2322, "text": "The serialize( ) method serializes a set of input elements into a string of data." }, { "code": null, "e": 2451, "s": 2404, "text": "Here is the simple syntax to use this method −" }, { "code": null, "e": 2467, "s": 2451, "text": "$.serialize( )\n" }, { "code": null, "e": 2535, "s": 2467, "text": "Here is the description of all the parameters used by this method −" }, { "code": null, "e": 2538, "s": 2535, "text": "NA" }, { "code": null, "e": 2541, "s": 2538, "text": "NA" }, { "code": null, "e": 2604, "s": 2541, "text": "Assuming we have following PHP content in serialize.php file −" }, { "code": null, "e": 2828, "s": 2604, "text": "<?php\nif( $_REQUEST[\"name\"] ) {\n\n $name = $_REQUEST['name'];\n echo \"Welcome \". $name;\n $age = $_REQUEST['age'];\n echo \"<br />Your age : \". $age;\n $sex = $_REQUEST['sex'];\n echo \"<br />Your gender : \". $sex;\n}\n?>" }, { "code": null, "e": 2902, "s": 2828, "text": "Following is a simple example a simple showing the usage of this method −" }, { "code": null, "e": 4787, "s": 2902, "text": "<html>\n <head>\n <title>The jQuery Example</title>\n <script type = \"text/javascript\" \n src = \"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\">\n </script>\n\t\t\n <script type = \"text/javascript\" language = \"javascript\">\n $(document).ready(function() {\n\t\t\t\n $(\"#driver\").click(function(event){\n\t\t\t\t\n $.post( \n \"/jquery/serialize.php\",\n $(\"#testform\").serialize(),\n\t\t\t\t\t\t\n function(data) {\n $('#stage1').html(data);\n }\n\t\t\t\t\t\t\n );\n\t\t\t\t\t\n var str = $(\"#testform\").serialize();\n $(\"#stage2\").text(str);\n });\n\t\t\t\t\n });\n </script>\n </head>\n\t\n <body>\n <p>Click on the button to load result.html file:</p>\n\t\t\n <div id = \"stage1\" style = \"background-color:blue;\">\n STAGE - 1\n </div>\n <br />\n\t\t\n <div id = \"stage2\" style = \"background-color:blue;\">\n STAGE - 2\n </div>\n\t\t\n <form id = \"testform\">\n <table>\n <tr>\n <td><p>Name:</p></td>\n <td><input type = \"text\" name = \"name\" size = \"40\" /></td>\n </tr>\n\t\t\t\t\n <tr>\n <td><p>Age:</p></td>\n <td><input type = \"text\" name = \"age\" size = \"40\" /></td>\n </tr>\n\t\t\t\t\n <tr>\n <td><p>Sex:</p></td>\n <td> <select name = \"sex\">\n <option value = \"Male\" selected>Male</option>\n <option value = \"Female\" selected>Female</option>\n </select></td>\n </tr>\n\t\t\t\t\n <tr>\n <td colspan = \"2\">\n <input type = \"button\" id = \"driver\" value = \"Load Data\" />\n </td>\n </tr>\n </table>\n </form>\n </body>\n</html>" }, { "code": null, "e": 4824, "s": 4787, "text": "This will produce following result −" }, { "code": null, "e": 4871, "s": 4824, "text": "Click on the button to load result.html file −" }, { "code": null, "e": 4878, "s": 4871, "text": "Name −" }, { "code": null, "e": 4884, "s": 4878, "text": "Age −" }, { "code": null, "e": 4890, "s": 4884, "text": "Sex −" }, { "code": null, "e": 4923, "s": 4890, "text": "\n 27 Lectures \n 1 hours \n" }, { "code": null, "e": 4937, "s": 4923, "text": " Mahesh Kumar" }, { "code": null, "e": 4972, "s": 4937, "text": "\n 27 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4986, "s": 4972, "text": " Pratik Singh" }, { "code": null, "e": 5021, "s": 4986, "text": "\n 72 Lectures \n 4.5 hours \n" }, { "code": null, "e": 5038, "s": 5021, "text": " Frahaan Hussain" }, { "code": null, "e": 5071, "s": 5038, "text": "\n 60 Lectures \n 9 hours \n" }, { "code": null, "e": 5099, "s": 5071, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 5132, "s": 5099, "text": "\n 17 Lectures \n 2 hours \n" }, { "code": null, "e": 5153, "s": 5132, "text": " Sandip Bhattacharya" }, { "code": null, "e": 5185, "s": 5153, "text": "\n 12 Lectures \n 53 mins\n" }, { "code": null, "e": 5202, "s": 5185, "text": " Laurence Svekis" }, { "code": null, "e": 5209, "s": 5202, "text": " Print" }, { "code": null, "e": 5220, "s": 5209, "text": " Add Notes" } ]
3D Line Plots using Plotly in Python - GeeksforGeeks
10 Jul, 2020 Plotly is a Python library that is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library Line plot in plotly is much accessible and illustrious annexation to plotly which manage a variety of types of data and assemble easy-to-style statistic. With px.line_3d each data position is represented as a vertex (which location is given by the x, y and z columns) of a polyline mark in 3D space. Line chart Displays a series of numerical data as points which are connected by lines. It visualizes to show two data trends. The main productive feature is it can display thousands of data points without scrolling. It can be created using the line_3d() method of plotly.express class. Syntax: plotly.express.line_3d(data_frame=None, x=None, y=None, z=None, color=None, line_dash=None, text=None, line_group=None, hover_name=None, hover_data=None, custom_data=None, error_x=None, error_x_minus=None, error_y=None, error_y_minus=None, error_z=None, error_z_minus=None, animation_frame=None, animation_group=None, category_orders={}, labels={}, color_discrete_sequence=None, color_discrete_map={}, line_dash_sequence=None, line_dash_map={}, log_x=False, log_y=False, log_z=False, range_x=None, range_y=None, range_z=None, title=None, template=None, width=None, height=None Parameters: data_frame: This argument needs to be passed for column names (and not keyword names) to be used. x, y, z: Either a name of a column in data_frame, or a pandas Series or array_like object. Values from this column or array_like are used to position marks along the x, y and z axis respectively in cartesian coordinates. color: Either a name of a column in data_frame, or a pandas Series or array_like object. Values from this column or array_like are used to assign color to marks. Example 1: Using Iris dataset Python3 import plotly.express as px df = px.data.iris() fig = px.line_3d(df, x="sepal_width", y="petal_length", z="petal_width")fig.show() Output: Example 2: Iris dataset with color argument Python3 import plotly.express as px df = px.data.iris() fig = px.line_3d(df, x="sepal_width", y="petal_length", z="petal_width", color="species")fig.show() Output: Example 3: Using tips dataset Python3 import plotly.express as px df = px.data.tips() fig = px.line_3d(df, x="total_bill", y="day", z="time")fig.show() Output: Example 4: Tips dataset with color argument. Python3 import plotly.express as px df = px.data.tips() fig = px.line_3d(df, x="total_bill", y="day", z="time")fig.show() Output: Python-Plotly Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe Python Dictionary Taking input in Python Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python
[ { "code": null, "e": 23723, "s": 23695, "text": "\n10 Jul, 2020" }, { "code": null, "e": 24023, "s": 23723, "text": "Plotly is a Python library that is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library" }, { "code": null, "e": 24610, "s": 24023, "text": "Line plot in plotly is much accessible and illustrious annexation to plotly which manage a variety of types of data and assemble easy-to-style statistic. With px.line_3d each data position is represented as a vertex (which location is given by the x, y and z columns) of a polyline mark in 3D space. Line chart Displays a series of numerical data as points which are connected by lines. It visualizes to show two data trends. The main productive feature is it can display thousands of data points without scrolling. It can be created using the line_3d() method of plotly.express class." }, { "code": null, "e": 25195, "s": 24610, "text": "Syntax: plotly.express.line_3d(data_frame=None, x=None, y=None, z=None, color=None, line_dash=None, text=None, line_group=None, hover_name=None, hover_data=None, custom_data=None, error_x=None, error_x_minus=None, error_y=None, error_y_minus=None, error_z=None, error_z_minus=None, animation_frame=None, animation_group=None, category_orders={}, labels={}, color_discrete_sequence=None, color_discrete_map={}, line_dash_sequence=None, line_dash_map={}, log_x=False, log_y=False, log_z=False, range_x=None, range_y=None, range_z=None, title=None, template=None, width=None, height=None" }, { "code": null, "e": 25207, "s": 25195, "text": "Parameters:" }, { "code": null, "e": 25306, "s": 25207, "text": "data_frame: This argument needs to be passed for column names (and not keyword names) to be used. " }, { "code": null, "e": 25527, "s": 25306, "text": "x, y, z: Either a name of a column in data_frame, or a pandas Series or array_like object. Values from this column or array_like are used to position marks along the x, y and z axis respectively in cartesian coordinates." }, { "code": null, "e": 25689, "s": 25527, "text": "color: Either a name of a column in data_frame, or a pandas Series or array_like object. Values from this column or array_like are used to assign color to marks." }, { "code": null, "e": 25719, "s": 25689, "text": "Example 1: Using Iris dataset" }, { "code": null, "e": 25727, "s": 25719, "text": "Python3" }, { "code": "import plotly.express as px df = px.data.iris() fig = px.line_3d(df, x=\"sepal_width\", y=\"petal_length\", z=\"petal_width\")fig.show()", "e": 25895, "s": 25727, "text": null }, { "code": null, "e": 25903, "s": 25895, "text": "Output:" }, { "code": null, "e": 25947, "s": 25903, "text": "Example 2: Iris dataset with color argument" }, { "code": null, "e": 25955, "s": 25947, "text": "Python3" }, { "code": "import plotly.express as px df = px.data.iris() fig = px.line_3d(df, x=\"sepal_width\", y=\"petal_length\", z=\"petal_width\", color=\"species\")fig.show()", "e": 26157, "s": 25955, "text": null }, { "code": null, "e": 26165, "s": 26157, "text": "Output:" }, { "code": null, "e": 26195, "s": 26165, "text": "Example 3: Using tips dataset" }, { "code": null, "e": 26203, "s": 26195, "text": "Python3" }, { "code": "import plotly.express as px df = px.data.tips() fig = px.line_3d(df, x=\"total_bill\", y=\"day\", z=\"time\")fig.show()", "e": 26338, "s": 26203, "text": null }, { "code": null, "e": 26346, "s": 26338, "text": "Output:" }, { "code": null, "e": 26391, "s": 26346, "text": "Example 4: Tips dataset with color argument." }, { "code": null, "e": 26399, "s": 26391, "text": "Python3" }, { "code": "import plotly.express as px df = px.data.tips() fig = px.line_3d(df, x=\"total_bill\", y=\"day\", z=\"time\")fig.show()", "e": 26517, "s": 26399, "text": null }, { "code": null, "e": 26525, "s": 26517, "text": "Output:" }, { "code": null, "e": 26539, "s": 26525, "text": "Python-Plotly" }, { "code": null, "e": 26546, "s": 26539, "text": "Python" }, { "code": null, "e": 26644, "s": 26546, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26653, "s": 26644, "text": "Comments" }, { "code": null, "e": 26666, "s": 26653, "text": "Old Comments" }, { "code": null, "e": 26694, "s": 26666, "text": "Read JSON file using Python" }, { "code": null, "e": 26744, "s": 26694, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 26766, "s": 26744, "text": "Python map() function" }, { "code": null, "e": 26810, "s": 26766, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 26828, "s": 26810, "text": "Python Dictionary" }, { "code": null, "e": 26851, "s": 26828, "text": "Taking input in Python" }, { "code": null, "e": 26886, "s": 26851, "text": "Read a file line by line in Python" }, { "code": null, "e": 26908, "s": 26886, "text": "Enumerate() in Python" }, { "code": null, "e": 26940, "s": 26908, "text": "How to Install PIP on Windows ?" } ]
StringBuffer replace() Method in Java with Examples
13 Dec, 2021 The StringBuffer.replace() is the inbuilt method which is used to replace the characters in a substring of this sequence with the characters in the specified String. Here simply the characters in the substring are removed and other char is inserted at the start.Syntax : public StringBuffer replace(int first, int last, String st) Parameters : The method accepts three parameters. first : This is of integer type which refers to the starting index. last : This is of integer type which refers to the ending index. st : This is of string type which refer to the String that will replace previous contents. Return Value : The method returns this object after performing the above mentioned operations.Exception : If the first is negative, greater than length(), or greater than last then StringIndexOutOfBoundsException.Examples : Input: StringBuffer= "The first planet of solar system is merrhxy" first = 39 last = 42 st = "cur" Output: The first planet of solar system is mercury Below programs illustrate the java.lang.StringBuffer.replace() method: Program 1: java // Java program to illustrate the// java.lang.StringBuffer.replace() import java.lang.*; public class Geeks { public static void main(String[] args) { StringBuffer sbf = new StringBuffer("Welcome to Geekshssgeeks"); System.out.println("string buffer = " + sbf); // Replacing substring from index 15 to index 18 sbf.replace(15, 18, "for"); System.out.println("After replacing string buffer= " + sbf); }} string buffer = Welcome to Geekshssgeeks After replacing string buffer= Welcome to Geekforsgeeks Program 2: When negative index is passed: java // Java program to illustrate the// java.lang.StringBuffer.replace() import java.lang.*; public class Geeks { public static void main(String[] args) { StringBuffer sbf = new StringBuffer("Welcome to Geekshssgeeks"); System.out.println("string buffer = " + sbf); // Replacing substring from index -15 to index -18 sbf.replace(-15, -18, "for"); System.out.println("After replacing string buffer= " + sbf); }} Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -15 at java.lang.AbstractStringBuilder.replace(AbstractStringBuilder.java:851) at java.lang.StringBuffer.replace(StringBuffer.java:452) at Geeks.main(Geeks.java:14) Program 3: When index passed is greater than length java // Java program to illustrate the// java.lang.StringBuffer.replace() import java.lang.*; public class Geeks { public static void main(String[] args) { StringBuffer sbf = new StringBuffer("Welcome to Geekshssgeeks"); System.out.println("string buffer = " + sbf); // Replacing substring from index 215 to index 218 sbf.replace(215, 218, "for"); System.out.println("After replacing string buffer= " + sbf); }} Exception in thread "main" java.lang.StringIndexOutOfBoundsException: start > length() at java.lang.AbstractStringBuilder.replace(AbstractStringBuilder.java:853) at java.lang.StringBuffer.replace(StringBuffer.java:452) at Geeks.main(Geeks.java:14) Akanksha_Rai adnanirshad158 Java-Functions Java-lang package java-StringBuffer Java-Strings Java Java-Strings Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n13 Dec, 2021" }, { "code": null, "e": 325, "s": 53, "text": "The StringBuffer.replace() is the inbuilt method which is used to replace the characters in a substring of this sequence with the characters in the specified String. Here simply the characters in the substring are removed and other char is inserted at the start.Syntax : " }, { "code": null, "e": 385, "s": 325, "text": "public StringBuffer replace(int first, int last, String st)" }, { "code": null, "e": 437, "s": 385, "text": "Parameters : The method accepts three parameters. " }, { "code": null, "e": 505, "s": 437, "text": "first : This is of integer type which refers to the starting index." }, { "code": null, "e": 570, "s": 505, "text": "last : This is of integer type which refers to the ending index." }, { "code": null, "e": 661, "s": 570, "text": "st : This is of string type which refer to the String that will replace previous contents." }, { "code": null, "e": 886, "s": 661, "text": "Return Value : The method returns this object after performing the above mentioned operations.Exception : If the first is negative, greater than length(), or greater than last then StringIndexOutOfBoundsException.Examples : " }, { "code": null, "e": 1038, "s": 886, "text": "Input:\nStringBuffer= \"The first planet of solar system is merrhxy\"\nfirst = 39\nlast = 42\nst = \"cur\"\n\nOutput: The first planet of solar system is mercury" }, { "code": null, "e": 1121, "s": 1038, "text": "Below programs illustrate the java.lang.StringBuffer.replace() method: Program 1: " }, { "code": null, "e": 1126, "s": 1121, "text": "java" }, { "code": "// Java program to illustrate the// java.lang.StringBuffer.replace() import java.lang.*; public class Geeks { public static void main(String[] args) { StringBuffer sbf = new StringBuffer(\"Welcome to Geekshssgeeks\"); System.out.println(\"string buffer = \" + sbf); // Replacing substring from index 15 to index 18 sbf.replace(15, 18, \"for\"); System.out.println(\"After replacing string buffer= \" + sbf); }}", "e": 1577, "s": 1126, "text": null }, { "code": null, "e": 1674, "s": 1577, "text": "string buffer = Welcome to Geekshssgeeks\nAfter replacing string buffer= Welcome to Geekforsgeeks" }, { "code": null, "e": 1719, "s": 1676, "text": "Program 2: When negative index is passed: " }, { "code": null, "e": 1724, "s": 1719, "text": "java" }, { "code": "// Java program to illustrate the// java.lang.StringBuffer.replace() import java.lang.*; public class Geeks { public static void main(String[] args) { StringBuffer sbf = new StringBuffer(\"Welcome to Geekshssgeeks\"); System.out.println(\"string buffer = \" + sbf); // Replacing substring from index -15 to index -18 sbf.replace(-15, -18, \"for\"); System.out.println(\"After replacing string buffer= \" + sbf); }}", "e": 2179, "s": 1724, "text": null }, { "code": null, "e": 2442, "s": 2179, "text": "Exception in thread \"main\" java.lang.StringIndexOutOfBoundsException: \nString index out of range: -15\nat java.lang.AbstractStringBuilder.replace(AbstractStringBuilder.java:851)\nat java.lang.StringBuffer.replace(StringBuffer.java:452)\nat Geeks.main(Geeks.java:14)" }, { "code": null, "e": 2498, "s": 2444, "text": "Program 3: When index passed is greater than length " }, { "code": null, "e": 2503, "s": 2498, "text": "java" }, { "code": "// Java program to illustrate the// java.lang.StringBuffer.replace() import java.lang.*; public class Geeks { public static void main(String[] args) { StringBuffer sbf = new StringBuffer(\"Welcome to Geekshssgeeks\"); System.out.println(\"string buffer = \" + sbf); // Replacing substring from index 215 to index 218 sbf.replace(215, 218, \"for\"); System.out.println(\"After replacing string buffer= \" + sbf); }}", "e": 2958, "s": 2503, "text": null }, { "code": null, "e": 3207, "s": 2958, "text": "Exception in thread \"main\" java.lang.StringIndexOutOfBoundsException: \nstart > length()\nat java.lang.AbstractStringBuilder.replace(AbstractStringBuilder.java:853)\nat java.lang.StringBuffer.replace(StringBuffer.java:452)\nat Geeks.main(Geeks.java:14)" }, { "code": null, "e": 3222, "s": 3209, "text": "Akanksha_Rai" }, { "code": null, "e": 3237, "s": 3222, "text": "adnanirshad158" }, { "code": null, "e": 3252, "s": 3237, "text": "Java-Functions" }, { "code": null, "e": 3270, "s": 3252, "text": "Java-lang package" }, { "code": null, "e": 3288, "s": 3270, "text": "java-StringBuffer" }, { "code": null, "e": 3301, "s": 3288, "text": "Java-Strings" }, { "code": null, "e": 3306, "s": 3301, "text": "Java" }, { "code": null, "e": 3319, "s": 3306, "text": "Java-Strings" }, { "code": null, "e": 3324, "s": 3319, "text": "Java" } ]
Python Pillow – Creating a Watermark
05 Apr, 2021 In this article, we will see how the creation of a watermark is done using the Pillow library in Python. Pillow is a Python Image Library(PIL) that is used for manipulating images and working on the different formats of images like (‘jpeg’, ‘png’, ‘gif’, ‘tiff’ etc.). There are various image processing you can do using pillow library like resizing, creating watermarks, rotation of the image, merging various images, blurring the image, etc. PIL displays the image in a photo viewer. Installation: To install the library, run the below command in your command prompt. python -m pip install pip or python -m pip install pillow If pip and pillow are already installed in your device, the system would mention “Requirement already satisfied:” There are two types of watermark: Text watermark,Image watermark. Text watermark, Image watermark. It is an approach for text documentation copyright protection. In an image, we can place some simple custom text on images in different fonts and formats. Step 1: Import all the libraries Python3 # importing the libraryfrom PIL import Imageimport matplotlib.pyplot as pltimport numpy as np Step 2: Open the image using a photo viewer. Python3 image = Image.open("puppy.jpg") # this open the photo viewerimage.show() plt.imshow(image) Output: Step 3: Creation of Text watermark Python # text Watermarkfrom PIL import ImageFontfrom PIL import ImageDrawwatermark_image = image.copy() draw = ImageDraw.Draw(watermark_image)font = ImageFont.truetype("arial.ttf", 50) # add watermarkdraw.text((0, 0), "puppy", (0, 0, 0), font=font)plt.subplot(1, 2, 1)plt.title("black text")plt.imshow(watermark_image) # add watermarkdraw.text((0, 0), "puppy", (255, 255, 255), font=font)plt.subplot(1, 2, 2)plt.title("white text")plt.imshow(watermark_image) Output: Below is the complete program based on the above approach: Python3 # import all the librariesfrom PIL import Imagefrom PIL import ImageFontfrom PIL import ImageDrawimport matplotlib.pyplot as pltimport numpy as np # image openingimage = Image.open("puppy.jpg")# this open the photo viewerimage.show() plt.imshow(image) # text Watermarkwatermark_image = image.copy() draw = ImageDraw.Draw(watermark_image)# ("font type",font size)font = ImageFont.truetype("arial.ttf", 50) # add Watermark# (0,0,0)-black color textdraw.text((0, 0), "puppy", (0, 0, 0), font=font)plt.subplot(1, 2, 1)plt.title("black text")plt.imshow(watermark_image) # add Watermark# (255,255,255)-White color textdraw.text((0, 0), "puppy", (255, 255, 255), font=font)plt.subplot(1, 2, 2)plt.title("white text")plt.imshow(watermark_image) Output: Explanation: Import all the libraries for image processing.Use Image.open() for the opening of image and image.show() for the photo viewer to open.plt.imshow() is used to open the image in the IDE.Make a copy of an image for the creation of watermark image.Make the image editable using ImageDraw.Use ImageFont to specify font and font size.Create a draw method of ImageDraw module and passed the image as a parameter in the function.Create a Font using ImageFont module function truetype() as it needs two parameters that is(“font type”,size)Then used text() function of draw object and passed the 4 parameters(Point of starting for text, “sample text”, Color, ImageFont object).plt.Imshow(watermark_image) for the output. Import all the libraries for image processing. Use Image.open() for the opening of image and image.show() for the photo viewer to open. plt.imshow() is used to open the image in the IDE. Make a copy of an image for the creation of watermark image. Make the image editable using ImageDraw. Use ImageFont to specify font and font size. Create a draw method of ImageDraw module and passed the image as a parameter in the function. Create a Font using ImageFont module function truetype() as it needs two parameters that is(“font type”,size) Then used text() function of draw object and passed the 4 parameters(Point of starting for text, “sample text”, Color, ImageFont object). plt.Imshow(watermark_image) for the output. It is a method used to paste an image onto another image. It takes two parameters one the image is to be pasted and the other where the image is to be pasted. Step1: Import the libraries Python # importing the libraryfrom PIL import Imageimport matplotlib.pyplot as pltimport numpy as np Step 2: Open the image using a photo viewer Python3 # read imageimage=Image.open("lion.jpg")image.show() plt.imshow(image) Step 3: Creation of Image watermark Python3 # image watermarksize = (500, 100)crop_image = image.copy()crop_image.thumbnail(size) # add watermarkcopied_image = image.copy()copied_image.paste(crop_image, (500, 200))plt.imshow(copied_image) Below is the complete program based on the above approach: Python3 # import all the librariesfrom PIL import Imageimport matplotlib.pyplot as pltimport numpy as np # to open the imageimage = Image.open("lion.jpg")# this open the photo viewerimage.show()plt.imshow(image) # image watermarksize = (500, 100)crop_image = image.copy()# to keep the aspect ration in intactcrop_image.thumbnail(size) # add watermarkcopied_image = image.copy()# base imagecopied_image.paste(crop_image, (500, 200))# pasted the crop image onto the base imageplt.imshow(copied_image) Output: Step-wise Explanation: Import all the libraries for image processing.Use open () for the opening of image and show() for the photo viewer to open.plt.imshow() is used to open the image in the IDE.Use copy() module to copy the image in the crop_imageCrop_image.thumbnail(size) -thumbnail is used to keep the aspect ratio intact.copied_image=image1.copy() is used to keep the base for the image onto which we would paste the image.paste() is used to paste the image into the copied_image the 2 parameters used are the (crop_image, and the position to be pasted).plt.imshow() to show the image. Import all the libraries for image processing. Use open () for the opening of image and show() for the photo viewer to open. plt.imshow() is used to open the image in the IDE. Use copy() module to copy the image in the crop_image Crop_image.thumbnail(size) -thumbnail is used to keep the aspect ratio intact. copied_image=image1.copy() is used to keep the base for the image onto which we would paste the image. paste() is used to paste the image into the copied_image the 2 parameters used are the (crop_image, and the position to be pasted). plt.imshow() to show the image. Picked Python-pil Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n05 Apr, 2021" }, { "code": null, "e": 539, "s": 53, "text": "In this article, we will see how the creation of a watermark is done using the Pillow library in Python. Pillow is a Python Image Library(PIL) that is used for manipulating images and working on the different formats of images like (‘jpeg’, ‘png’, ‘gif’, ‘tiff’ etc.). There are various image processing you can do using pillow library like resizing, creating watermarks, rotation of the image, merging various images, blurring the image, etc. PIL displays the image in a photo viewer." }, { "code": null, "e": 553, "s": 539, "text": "Installation:" }, { "code": null, "e": 623, "s": 553, "text": "To install the library, run the below command in your command prompt." }, { "code": null, "e": 649, "s": 623, "text": "python -m pip install pip" }, { "code": null, "e": 652, "s": 649, "text": "or" }, { "code": null, "e": 681, "s": 652, "text": "python -m pip install pillow" }, { "code": null, "e": 795, "s": 681, "text": "If pip and pillow are already installed in your device, the system would mention “Requirement already satisfied:”" }, { "code": null, "e": 829, "s": 795, "text": "There are two types of watermark:" }, { "code": null, "e": 861, "s": 829, "text": "Text watermark,Image watermark." }, { "code": null, "e": 877, "s": 861, "text": "Text watermark," }, { "code": null, "e": 894, "s": 877, "text": "Image watermark." }, { "code": null, "e": 1049, "s": 894, "text": "It is an approach for text documentation copyright protection. In an image, we can place some simple custom text on images in different fonts and formats." }, { "code": null, "e": 1082, "s": 1049, "text": "Step 1: Import all the libraries" }, { "code": null, "e": 1090, "s": 1082, "text": "Python3" }, { "code": "# importing the libraryfrom PIL import Imageimport matplotlib.pyplot as pltimport numpy as np", "e": 1184, "s": 1090, "text": null }, { "code": null, "e": 1231, "s": 1186, "text": "Step 2: Open the image using a photo viewer." }, { "code": null, "e": 1239, "s": 1231, "text": "Python3" }, { "code": "image = Image.open(\"puppy.jpg\") # this open the photo viewerimage.show() plt.imshow(image)", "e": 1331, "s": 1239, "text": null }, { "code": null, "e": 1339, "s": 1331, "text": "Output:" }, { "code": null, "e": 1374, "s": 1339, "text": "Step 3: Creation of Text watermark" }, { "code": null, "e": 1381, "s": 1374, "text": "Python" }, { "code": "# text Watermarkfrom PIL import ImageFontfrom PIL import ImageDrawwatermark_image = image.copy() draw = ImageDraw.Draw(watermark_image)font = ImageFont.truetype(\"arial.ttf\", 50) # add watermarkdraw.text((0, 0), \"puppy\", (0, 0, 0), font=font)plt.subplot(1, 2, 1)plt.title(\"black text\")plt.imshow(watermark_image) # add watermarkdraw.text((0, 0), \"puppy\", (255, 255, 255), font=font)plt.subplot(1, 2, 2)plt.title(\"white text\")plt.imshow(watermark_image)", "e": 1856, "s": 1381, "text": null }, { "code": null, "e": 1864, "s": 1856, "text": "Output:" }, { "code": null, "e": 1923, "s": 1864, "text": "Below is the complete program based on the above approach:" }, { "code": null, "e": 1931, "s": 1923, "text": "Python3" }, { "code": "# import all the librariesfrom PIL import Imagefrom PIL import ImageFontfrom PIL import ImageDrawimport matplotlib.pyplot as pltimport numpy as np # image openingimage = Image.open(\"puppy.jpg\")# this open the photo viewerimage.show() plt.imshow(image) # text Watermarkwatermark_image = image.copy() draw = ImageDraw.Draw(watermark_image)# (\"font type\",font size)font = ImageFont.truetype(\"arial.ttf\", 50) # add Watermark# (0,0,0)-black color textdraw.text((0, 0), \"puppy\", (0, 0, 0), font=font)plt.subplot(1, 2, 1)plt.title(\"black text\")plt.imshow(watermark_image) # add Watermark# (255,255,255)-White color textdraw.text((0, 0), \"puppy\", (255, 255, 255), font=font)plt.subplot(1, 2, 2)plt.title(\"white text\")plt.imshow(watermark_image)", "e": 2674, "s": 1931, "text": null }, { "code": null, "e": 2682, "s": 2674, "text": "Output:" }, { "code": null, "e": 2695, "s": 2682, "text": "Explanation:" }, { "code": null, "e": 3406, "s": 2695, "text": "Import all the libraries for image processing.Use Image.open() for the opening of image and image.show() for the photo viewer to open.plt.imshow() is used to open the image in the IDE.Make a copy of an image for the creation of watermark image.Make the image editable using ImageDraw.Use ImageFont to specify font and font size.Create a draw method of ImageDraw module and passed the image as a parameter in the function.Create a Font using ImageFont module function truetype() as it needs two parameters that is(“font type”,size)Then used text() function of draw object and passed the 4 parameters(Point of starting for text, “sample text”, Color, ImageFont object).plt.Imshow(watermark_image) for the output." }, { "code": null, "e": 3453, "s": 3406, "text": "Import all the libraries for image processing." }, { "code": null, "e": 3542, "s": 3453, "text": "Use Image.open() for the opening of image and image.show() for the photo viewer to open." }, { "code": null, "e": 3593, "s": 3542, "text": "plt.imshow() is used to open the image in the IDE." }, { "code": null, "e": 3654, "s": 3593, "text": "Make a copy of an image for the creation of watermark image." }, { "code": null, "e": 3695, "s": 3654, "text": "Make the image editable using ImageDraw." }, { "code": null, "e": 3740, "s": 3695, "text": "Use ImageFont to specify font and font size." }, { "code": null, "e": 3834, "s": 3740, "text": "Create a draw method of ImageDraw module and passed the image as a parameter in the function." }, { "code": null, "e": 3944, "s": 3834, "text": "Create a Font using ImageFont module function truetype() as it needs two parameters that is(“font type”,size)" }, { "code": null, "e": 4082, "s": 3944, "text": "Then used text() function of draw object and passed the 4 parameters(Point of starting for text, “sample text”, Color, ImageFont object)." }, { "code": null, "e": 4126, "s": 4082, "text": "plt.Imshow(watermark_image) for the output." }, { "code": null, "e": 4285, "s": 4126, "text": "It is a method used to paste an image onto another image. It takes two parameters one the image is to be pasted and the other where the image is to be pasted." }, { "code": null, "e": 4314, "s": 4285, "text": "Step1: Import the libraries " }, { "code": null, "e": 4321, "s": 4314, "text": "Python" }, { "code": "# importing the libraryfrom PIL import Imageimport matplotlib.pyplot as pltimport numpy as np", "e": 4415, "s": 4321, "text": null }, { "code": null, "e": 4459, "s": 4415, "text": "Step 2: Open the image using a photo viewer" }, { "code": null, "e": 4467, "s": 4459, "text": "Python3" }, { "code": "# read imageimage=Image.open(\"lion.jpg\")image.show() plt.imshow(image)", "e": 4538, "s": 4467, "text": null }, { "code": null, "e": 4574, "s": 4538, "text": "Step 3: Creation of Image watermark" }, { "code": null, "e": 4582, "s": 4574, "text": "Python3" }, { "code": "# image watermarksize = (500, 100)crop_image = image.copy()crop_image.thumbnail(size) # add watermarkcopied_image = image.copy()copied_image.paste(crop_image, (500, 200))plt.imshow(copied_image)", "e": 4778, "s": 4582, "text": null }, { "code": null, "e": 4837, "s": 4778, "text": "Below is the complete program based on the above approach:" }, { "code": null, "e": 4845, "s": 4837, "text": "Python3" }, { "code": "# import all the librariesfrom PIL import Imageimport matplotlib.pyplot as pltimport numpy as np # to open the imageimage = Image.open(\"lion.jpg\")# this open the photo viewerimage.show()plt.imshow(image) # image watermarksize = (500, 100)crop_image = image.copy()# to keep the aspect ration in intactcrop_image.thumbnail(size) # add watermarkcopied_image = image.copy()# base imagecopied_image.paste(crop_image, (500, 200))# pasted the crop image onto the base imageplt.imshow(copied_image)", "e": 5339, "s": 4845, "text": null }, { "code": null, "e": 5347, "s": 5339, "text": "Output:" }, { "code": null, "e": 5370, "s": 5347, "text": "Step-wise Explanation:" }, { "code": null, "e": 5939, "s": 5370, "text": "Import all the libraries for image processing.Use open () for the opening of image and show() for the photo viewer to open.plt.imshow() is used to open the image in the IDE.Use copy() module to copy the image in the crop_imageCrop_image.thumbnail(size) -thumbnail is used to keep the aspect ratio intact.copied_image=image1.copy() is used to keep the base for the image onto which we would paste the image.paste() is used to paste the image into the copied_image the 2 parameters used are the (crop_image, and the position to be pasted).plt.imshow() to show the image." }, { "code": null, "e": 5986, "s": 5939, "text": "Import all the libraries for image processing." }, { "code": null, "e": 6064, "s": 5986, "text": "Use open () for the opening of image and show() for the photo viewer to open." }, { "code": null, "e": 6115, "s": 6064, "text": "plt.imshow() is used to open the image in the IDE." }, { "code": null, "e": 6169, "s": 6115, "text": "Use copy() module to copy the image in the crop_image" }, { "code": null, "e": 6248, "s": 6169, "text": "Crop_image.thumbnail(size) -thumbnail is used to keep the aspect ratio intact." }, { "code": null, "e": 6351, "s": 6248, "text": "copied_image=image1.copy() is used to keep the base for the image onto which we would paste the image." }, { "code": null, "e": 6483, "s": 6351, "text": "paste() is used to paste the image into the copied_image the 2 parameters used are the (crop_image, and the position to be pasted)." }, { "code": null, "e": 6515, "s": 6483, "text": "plt.imshow() to show the image." }, { "code": null, "e": 6522, "s": 6515, "text": "Picked" }, { "code": null, "e": 6533, "s": 6522, "text": "Python-pil" }, { "code": null, "e": 6540, "s": 6533, "text": "Python" } ]
Find maximum difference between nearest left and right smaller elements
06 Jul, 2022 Given an array of integers, the task is to find the maximum absolute difference between the nearest left and the right smaller element of every element in the array. Note: If there is no smaller element on right side or left side of any element then we take zero as the smaller element. For example for the leftmost element, the nearest smaller element on the left side is considered as 0. Similarly, for rightmost elements, the smaller element on the right side is considered as 0. Examples: Input : arr[] = {2, 1, 8} Output : 1 Left smaller LS[] {0, 0, 1} Right smaller RS[] {1, 0, 0} Maximum Diff of abs(LS[i] - RS[i]) = 1 Input : arr[] = {2, 4, 8, 7, 7, 9, 3} Output : 4 Left smaller LS[] = {0, 2, 4, 4, 4, 7, 2} Right smaller RS[] = {0, 3, 7, 3, 3, 3, 0} Maximum Diff of abs(LS[i] - RS[i]) = 7 - 3 = 4 Input : arr[] = {5, 1, 9, 2, 5, 1, 7} Output : 1 A simple solution is to find the nearest left and right smaller elements for every element and then update the maximum difference between left and right smaller element, this takes O(n^2) time. An efficient solution takes O(n) time. We use a stack. The idea is based on the approach discussed in next greater element article. The interesting part here is we compute both left smaller and right smaller using same function. Let input array be 'arr[]' and size of array be 'n' Find all smaller element on left side 1. Create a new empty stack S and an array LS[] 2. For every element 'arr[i]' in the input arr[], where 'i' goes from 0 to n-1. a) while S is nonempty and the top element of S is greater than or equal to 'arr[i]': pop S b) if S is empty: 'arr[i]' has no preceding smaller value LS[i] = 0 c) else: the nearest smaller value to 'arr[i]' is top of stack LS[i] = s.top() d) push 'arr[i]' onto S Find all smaller element on right side 3. First reverse array arr[]. After reversing the array, right smaller become left smaller. 4. Create an array RRS[] and repeat steps 1 and 2 to fill RRS (in-place of LS). 5. Initialize result as -1 and do following for every element arr[i]. In the reversed array right smaller for arr[i] is stored at RRS[n-i-1] return result = max(result, LS[i]-RRS[n-i-1]) Below is implementation of above idea C++ Java Python3 C# PHP Javascript // C++ program to find the difference b/w left and// right smaller element of every element in array#include<bits/stdc++.h>using namespace std; // Function to fill left smaller element for every// element of arr[0..n-1]. These values are filled// in SE[0..n-1]void leftSmaller(int arr[], int n, int SE[]){ // Create an empty stack stack<int>S; // Traverse all array elements // compute nearest smaller elements of every element for (int i=0; i<n; i++) { // Keep removing top element from S while the top // element is greater than or equal to arr[i] while (!S.empty() && S.top() >= arr[i]) S.pop(); // Store the smaller element of current element if (!S.empty()) SE[i] = S.top(); // If all elements in S were greater than arr[i] else SE[i] = 0; // Push this element S.push(arr[i]); }} // Function returns maximum difference b/w Left &// right smaller elementint findMaxDiff(int arr[], int n){ int LS[n]; // To store left smaller elements // find left smaller element of every element leftSmaller(arr, n, LS); // find right smaller element of every element // first reverse the array and do the same process int RRS[n]; // To store right smaller elements in // reverse array reverse(arr, arr + n); leftSmaller(arr, n, RRS); // find maximum absolute difference b/w LS & RRS // In the reversed array right smaller for arr[i] is // stored at RRS[n-i-1] int result = -1; for (int i=0 ; i< n ; i++) result = max(result, abs(LS[i] - RRS[n-1-i])); // return maximum difference b/w LS & RRS return result;} // Driver programint main(){ int arr[] = {2, 4, 8, 7, 7, 9, 3}; int n = sizeof(arr)/sizeof(arr[0]); cout << "Maximum diff : " << findMaxDiff(arr, n) << endl; return 0;} // Java program to find the difference b/w left and// right smaller element of every element in arrayimport java.util.*; class GFG{ // Function to fill left smaller element for every // element of arr[0..n-1]. These values are filled // in SE[0..n-1] static void leftSmaller(int arr[], int n, int SE[]) { // Create an empty stack Stack<Integer> S = new Stack<>(); // Traverse all array elements // compute nearest smaller elements of every element for (int i = 0; i < n; i++) { // Keep removing top element from S while the top // element is greater than or equal to arr[i] while (!S.empty() && S.peek() >= arr[i]) { S.pop(); } // Store the smaller element of current element if (!S.empty()) { SE[i] = S.peek(); } // If all elements in S were greater than arr[i] else { SE[i] = 0; } // Push this element S.push(arr[i]); } } // Function returns maximum difference b/w Left & // right smaller element static int findMaxDiff(int arr[], int n) { int[] LS = new int[n]; // To store left smaller elements // find left smaller element of every element leftSmaller(arr, n, LS); // find right smaller element of every element // first reverse the array and do the same process int[] RRS = new int[n]; // To store right smaller elements in // reverse array reverse(arr); leftSmaller(arr, n, RRS); // find maximum absolute difference b/w LS & RRS // In the reversed array right smaller for arr[i] is // stored at RRS[n-i-1] int result = -1; for (int i = 0; i < n; i++) { result = Math.max(result, Math.abs(LS[i] - RRS[n - 1 - i])); } // return maximum difference b/w LS & RRS return result; } static void reverse(int a[]) { int i, k, n = a.length; int t; for (i = 0; i < n / 2; i++) { t = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = t; } } // Driver code public static void main(String args[]) { int arr[] = {2, 4, 8, 7, 7, 9, 3}; int n = arr.length; System.out.println("Maximum diff : " + findMaxDiff(arr, n)); }} // This code is contributed by Princi Singh # Python program to find the difference b/w left and# right smaller element of every element in the array # Function to fill left smaller element for every# element of arr[0..n-1]. These values are filled# in SE[0..n-1]def leftsmaller(arr, n, SE): # create an empty stack sta = [] # Traverse all array elements # compute nearest smaller elements of every element for i in range(n): # Keep removing top element from S while the top # element is greater than or equal to arr[i] while(sta != [] and sta[len(sta)-1] >= arr[i]): sta.pop() # Store the smaller element of current element if(sta != []): SE[i]=sta[len(sta)-1] # If all elements in S were greater than arr[i] else: SE[i]=0 # push this element sta.append(arr[i]) # Function returns maximum difference b/w Left &# right smaller elementdef findMaxDiff(arr, n): ls=[0]*n # to store left smaller elements rs=[0]*n # to store right smaller elements # find left smaller elements of every element leftsmaller(arr, n, ls) # find right smaller element of every element # by sending reverse of array leftsmaller(arr[::-1], n, rs) # find maximum absolute difference b/w LS & RRS # In the reversed array right smaller for arr[i] is # stored at RRS[n-i-1] res = -1 for i in range(n): res = max(res, abs(ls[i] - rs[n-1-i])) # return maximum difference b/w LS & RRS return res # Driver Programif __name__=='__main__': arr = [2, 4, 8, 7, 7, 9, 3] print "Maximum Diff :", findMaxDiff(arr, len(arr)) #Contributed By: Harshit Sidhwa // C# program to find the difference b/w left and// right smaller element of every element in arrayusing System;using System.Collections.Generic; class GFG{ // Function to fill left smaller element for every // element of arr[0..n-1]. These values are filled // in SE[0..n-1] static void leftSmaller(int []arr, int n, int []SE) { // Create an empty stack Stack<int> S = new Stack<int>(); // Traverse all array elements // compute nearest smaller elements of every element for (int i = 0; i < n; i++) { // Keep removing top element from S while the top // element is greater than or equal to arr[i] while (S.Count != 0 && S.Peek() >= arr[i]) { S.Pop(); } // Store the smaller element of current element if (S.Count != 0) { SE[i] = S.Peek(); } // If all elements in S were greater than arr[i] else { SE[i] = 0; } // Push this element S.Push(arr[i]); } } // Function returns maximum difference b/w Left & // right smaller element static int findMaxDiff(int []arr, int n) { int[] LS = new int[n]; // To store left smaller elements // find left smaller element of every element leftSmaller(arr, n, LS); // find right smaller element of every element // first reverse the array and do the same process int[] RRS = new int[n]; // To store right smaller elements in // reverse array reverse(arr); leftSmaller(arr, n, RRS); // find maximum absolute difference b/w LS & RRS // In the reversed array right smaller for arr[i] is // stored at RRS[n-i-1] int result = -1; for (int i = 0; i < n; i++) { result = Math.Max(result, Math.Abs(LS[i] - RRS[n - 1 - i])); } // return maximum difference b/w LS & RRS return result; } static void reverse(int[] a) { int i, k, n = a.Length; int t; for (i = 0; i < n / 2; i++) { t = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = t; } } // Driver code public static void Main(String []args) { int []arr = {2, 4, 8, 7, 7, 9, 3}; int n = arr.Length; Console.WriteLine("Maximum diff : " + findMaxDiff(arr, n)); }} // This code is contributed by 29AjayKumar <?php// Function to fill left smaller// element for every element of// arr[0..n-1]. These values are// filled in SE[0..n-1]function leftSmaller(&$arr, $n, &$SE){ $S = array(); // Traverse all array elements // compute nearest smaller // elements of every element for ($i = 0; $i < $n; $i++) { // Keep removing top element // from S while the top element // is greater than or equal to arr[i] while (!empty($S) && max($S) >= $arr[$i]) array_pop($S); // Store the smaller element // of current element if (!empty($S)) $SE[$i] = max($S); // If all elements in S were // greater than arr[i] else $SE[$i] = 0; // Push this element array_push($S, $arr[$i]); }} // Function returns maximum// difference b/w Left &// right smaller elementfunction findMaxDiff(&$arr, $n){ // To store left smaller elements $LS = array_fill(0, $n, NULL); // find left smaller element // of every element leftSmaller($arr, $n, $LS); // find right smaller element // of every element first reverse // the array and do the same process // To store right smaller // elements in reverse array $RRS = array_fill(0, $n, NULL); $k = 0; for($i = $n - 1; $i >= 0; $i--) $x[$k++] = $arr[$i]; leftSmaller($x, $n, $RRS); // find maximum absolute difference // b/w LS & RRS. In the reversed // array right smaller for arr[i] // is stored at RRS[n-i-1] $result = -1; for ($i = 0 ; $i < $n ; $i++) $result = max($result, abs($LS[$i] - $RRS[$n - 1 - $i])); // return maximum difference // b/w LS & RRS return $result;} // Driver Code$arr = array(2, 4, 8, 7, 7, 9, 3);$n = sizeof($arr);echo "Maximum diff : " . findMaxDiff($arr, $n) . "\n"; // This code is contributed// by ChitraNayal?> <script>// Javascript program to find the difference b/w left and// right smaller element of every element in array // Function to fill left smaller element for every // element of arr[0..n-1]. These values are filled // in SE[0..n-1] function leftSmaller(arr,n,SE) { // Create an empty stack let S=[] // Traverse all array elements // compute nearest smaller elements of every element for (let i = 0; i < n; i++) { // Keep removing top element from S while the top // element is greater than or equal to arr[i] while (S.length!=0 && S[S.length-1] >= arr[i]) { S.pop(); } // Store the smaller element of current element if (S.length!=0) { SE[i] = S[S.length-1]; } // If all elements in S were greater than arr[i] else { SE[i] = 0; } // Push this element S.push(arr[i]); } } // Function returns maximum difference b/w Left & // right smaller element function findMaxDiff(arr,n) { // To store left smaller elements let LS = new Array(n); for(let i=0;i<n;i++) { LS[i]=0; } // find left smaller element of every element leftSmaller(arr, n, LS); // find right smaller element of every element // first reverse the array and do the same process let RRS = new Array(n); // To store right smaller elements in for(let i=0;i<n;i++) { RRS[i]=0; } // reverse array reverse(arr); leftSmaller(arr, n, RRS); // find maximum absolute difference b/w LS & RRS // In the reversed array right smaller for arr[i] is // stored at RRS[n-i-1] let result = -1; for (let i = 0; i < n; i++) { result = Math.max(result, Math.abs(LS[i] - RRS[n - 1 - i])); } // return maximum difference b/w LS & RRS return result; } function reverse(a) { let i, k, n = a.length; let t; for (i = 0; i < Math.floor(n / 2); i++) { t = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = t; } } // Driver code let arr=[2, 4, 8, 7, 7, 9, 3]; let n = arr.length; document.write("Maximum diff : " + findMaxDiff(arr, n)); // This code is contributed by rag2127</script> Maximum diff : 4 Time complexity: O(n)Auxiliary Space: O(n). This article is contributed by Nishant_singh(pintu). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. ukasp princi singh 29AjayKumar rag2127 sweetyty anandkumarshivam2266 hardikkoriintern Arrays Stack Arrays Stack Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n06 Jul, 2022" }, { "code": null, "e": 221, "s": 54, "text": "Given an array of integers, the task is to find the maximum absolute difference between the nearest left and the right smaller element of every element in the array. " }, { "code": null, "e": 538, "s": 221, "text": "Note: If there is no smaller element on right side or left side of any element then we take zero as the smaller element. For example for the leftmost element, the nearest smaller element on the left side is considered as 0. Similarly, for rightmost elements, the smaller element on the right side is considered as 0." }, { "code": null, "e": 549, "s": 538, "text": "Examples: " }, { "code": null, "e": 921, "s": 549, "text": "Input : arr[] = {2, 1, 8}\nOutput : 1\nLeft smaller LS[] {0, 0, 1}\nRight smaller RS[] {1, 0, 0}\nMaximum Diff of abs(LS[i] - RS[i]) = 1 \n\nInput : arr[] = {2, 4, 8, 7, 7, 9, 3}\nOutput : 4\nLeft smaller LS[] = {0, 2, 4, 4, 4, 7, 2}\nRight smaller RS[] = {0, 3, 7, 3, 3, 3, 0}\nMaximum Diff of abs(LS[i] - RS[i]) = 7 - 3 = 4 \n\nInput : arr[] = {5, 1, 9, 2, 5, 1, 7}\nOutput : 1" }, { "code": null, "e": 1116, "s": 921, "text": "A simple solution is to find the nearest left and right smaller elements for every element and then update the maximum difference between left and right smaller element, this takes O(n^2) time. " }, { "code": null, "e": 1346, "s": 1116, "text": "An efficient solution takes O(n) time. We use a stack. The idea is based on the approach discussed in next greater element article. The interesting part here is we compute both left smaller and right smaller using same function. " }, { "code": null, "e": 2438, "s": 1346, "text": "Let input array be 'arr[]' and size of array be 'n'\n\nFind all smaller element on left side\n 1. Create a new empty stack S and an array LS[]\n 2. For every element 'arr[i]' in the input arr[],\n where 'i' goes from 0 to n-1.\n a) while S is nonempty and the top element of \n S is greater than or equal to 'arr[i]':\n pop S\n \n b) if S is empty:\n 'arr[i]' has no preceding smaller value \n LS[i] = 0 \n \n c) else:\n the nearest smaller value to 'arr[i]' is top\n of stack\n LS[i] = s.top()\n\n d) push 'arr[i]' onto S \n\nFind all smaller element on right side\n 3. First reverse array arr[]. After reversing the array, \n right smaller become left smaller.\n 4. Create an array RRS[] and repeat steps 1 and 2 to \n fill RRS (in-place of LS).\n \n5. Initialize result as -1 and do following for every element\n arr[i]. In the reversed array right smaller for arr[i] is\n stored at RRS[n-i-1]\n return result = max(result, LS[i]-RRS[n-i-1])" }, { "code": null, "e": 2478, "s": 2438, "text": "Below is implementation of above idea " }, { "code": null, "e": 2482, "s": 2478, "text": "C++" }, { "code": null, "e": 2487, "s": 2482, "text": "Java" }, { "code": null, "e": 2495, "s": 2487, "text": "Python3" }, { "code": null, "e": 2498, "s": 2495, "text": "C#" }, { "code": null, "e": 2502, "s": 2498, "text": "PHP" }, { "code": null, "e": 2513, "s": 2502, "text": "Javascript" }, { "code": "// C++ program to find the difference b/w left and// right smaller element of every element in array#include<bits/stdc++.h>using namespace std; // Function to fill left smaller element for every// element of arr[0..n-1]. These values are filled// in SE[0..n-1]void leftSmaller(int arr[], int n, int SE[]){ // Create an empty stack stack<int>S; // Traverse all array elements // compute nearest smaller elements of every element for (int i=0; i<n; i++) { // Keep removing top element from S while the top // element is greater than or equal to arr[i] while (!S.empty() && S.top() >= arr[i]) S.pop(); // Store the smaller element of current element if (!S.empty()) SE[i] = S.top(); // If all elements in S were greater than arr[i] else SE[i] = 0; // Push this element S.push(arr[i]); }} // Function returns maximum difference b/w Left &// right smaller elementint findMaxDiff(int arr[], int n){ int LS[n]; // To store left smaller elements // find left smaller element of every element leftSmaller(arr, n, LS); // find right smaller element of every element // first reverse the array and do the same process int RRS[n]; // To store right smaller elements in // reverse array reverse(arr, arr + n); leftSmaller(arr, n, RRS); // find maximum absolute difference b/w LS & RRS // In the reversed array right smaller for arr[i] is // stored at RRS[n-i-1] int result = -1; for (int i=0 ; i< n ; i++) result = max(result, abs(LS[i] - RRS[n-1-i])); // return maximum difference b/w LS & RRS return result;} // Driver programint main(){ int arr[] = {2, 4, 8, 7, 7, 9, 3}; int n = sizeof(arr)/sizeof(arr[0]); cout << \"Maximum diff : \" << findMaxDiff(arr, n) << endl; return 0;}", "e": 4391, "s": 2513, "text": null }, { "code": "// Java program to find the difference b/w left and// right smaller element of every element in arrayimport java.util.*; class GFG{ // Function to fill left smaller element for every // element of arr[0..n-1]. These values are filled // in SE[0..n-1] static void leftSmaller(int arr[], int n, int SE[]) { // Create an empty stack Stack<Integer> S = new Stack<>(); // Traverse all array elements // compute nearest smaller elements of every element for (int i = 0; i < n; i++) { // Keep removing top element from S while the top // element is greater than or equal to arr[i] while (!S.empty() && S.peek() >= arr[i]) { S.pop(); } // Store the smaller element of current element if (!S.empty()) { SE[i] = S.peek(); } // If all elements in S were greater than arr[i] else { SE[i] = 0; } // Push this element S.push(arr[i]); } } // Function returns maximum difference b/w Left & // right smaller element static int findMaxDiff(int arr[], int n) { int[] LS = new int[n]; // To store left smaller elements // find left smaller element of every element leftSmaller(arr, n, LS); // find right smaller element of every element // first reverse the array and do the same process int[] RRS = new int[n]; // To store right smaller elements in // reverse array reverse(arr); leftSmaller(arr, n, RRS); // find maximum absolute difference b/w LS & RRS // In the reversed array right smaller for arr[i] is // stored at RRS[n-i-1] int result = -1; for (int i = 0; i < n; i++) { result = Math.max(result, Math.abs(LS[i] - RRS[n - 1 - i])); } // return maximum difference b/w LS & RRS return result; } static void reverse(int a[]) { int i, k, n = a.length; int t; for (i = 0; i < n / 2; i++) { t = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = t; } } // Driver code public static void main(String args[]) { int arr[] = {2, 4, 8, 7, 7, 9, 3}; int n = arr.length; System.out.println(\"Maximum diff : \" + findMaxDiff(arr, n)); }} // This code is contributed by Princi Singh", "e": 6915, "s": 4391, "text": null }, { "code": "# Python program to find the difference b/w left and# right smaller element of every element in the array # Function to fill left smaller element for every# element of arr[0..n-1]. These values are filled# in SE[0..n-1]def leftsmaller(arr, n, SE): # create an empty stack sta = [] # Traverse all array elements # compute nearest smaller elements of every element for i in range(n): # Keep removing top element from S while the top # element is greater than or equal to arr[i] while(sta != [] and sta[len(sta)-1] >= arr[i]): sta.pop() # Store the smaller element of current element if(sta != []): SE[i]=sta[len(sta)-1] # If all elements in S were greater than arr[i] else: SE[i]=0 # push this element sta.append(arr[i]) # Function returns maximum difference b/w Left &# right smaller elementdef findMaxDiff(arr, n): ls=[0]*n # to store left smaller elements rs=[0]*n # to store right smaller elements # find left smaller elements of every element leftsmaller(arr, n, ls) # find right smaller element of every element # by sending reverse of array leftsmaller(arr[::-1], n, rs) # find maximum absolute difference b/w LS & RRS # In the reversed array right smaller for arr[i] is # stored at RRS[n-i-1] res = -1 for i in range(n): res = max(res, abs(ls[i] - rs[n-1-i])) # return maximum difference b/w LS & RRS return res # Driver Programif __name__=='__main__': arr = [2, 4, 8, 7, 7, 9, 3] print \"Maximum Diff :\", findMaxDiff(arr, len(arr)) #Contributed By: Harshit Sidhwa", "e": 8583, "s": 6915, "text": null }, { "code": "// C# program to find the difference b/w left and// right smaller element of every element in arrayusing System;using System.Collections.Generic; class GFG{ // Function to fill left smaller element for every // element of arr[0..n-1]. These values are filled // in SE[0..n-1] static void leftSmaller(int []arr, int n, int []SE) { // Create an empty stack Stack<int> S = new Stack<int>(); // Traverse all array elements // compute nearest smaller elements of every element for (int i = 0; i < n; i++) { // Keep removing top element from S while the top // element is greater than or equal to arr[i] while (S.Count != 0 && S.Peek() >= arr[i]) { S.Pop(); } // Store the smaller element of current element if (S.Count != 0) { SE[i] = S.Peek(); } // If all elements in S were greater than arr[i] else { SE[i] = 0; } // Push this element S.Push(arr[i]); } } // Function returns maximum difference b/w Left & // right smaller element static int findMaxDiff(int []arr, int n) { int[] LS = new int[n]; // To store left smaller elements // find left smaller element of every element leftSmaller(arr, n, LS); // find right smaller element of every element // first reverse the array and do the same process int[] RRS = new int[n]; // To store right smaller elements in // reverse array reverse(arr); leftSmaller(arr, n, RRS); // find maximum absolute difference b/w LS & RRS // In the reversed array right smaller for arr[i] is // stored at RRS[n-i-1] int result = -1; for (int i = 0; i < n; i++) { result = Math.Max(result, Math.Abs(LS[i] - RRS[n - 1 - i])); } // return maximum difference b/w LS & RRS return result; } static void reverse(int[] a) { int i, k, n = a.Length; int t; for (i = 0; i < n / 2; i++) { t = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = t; } } // Driver code public static void Main(String []args) { int []arr = {2, 4, 8, 7, 7, 9, 3}; int n = arr.Length; Console.WriteLine(\"Maximum diff : \" + findMaxDiff(arr, n)); }} // This code is contributed by 29AjayKumar", "e": 11218, "s": 8583, "text": null }, { "code": "<?php// Function to fill left smaller// element for every element of// arr[0..n-1]. These values are// filled in SE[0..n-1]function leftSmaller(&$arr, $n, &$SE){ $S = array(); // Traverse all array elements // compute nearest smaller // elements of every element for ($i = 0; $i < $n; $i++) { // Keep removing top element // from S while the top element // is greater than or equal to arr[i] while (!empty($S) && max($S) >= $arr[$i]) array_pop($S); // Store the smaller element // of current element if (!empty($S)) $SE[$i] = max($S); // If all elements in S were // greater than arr[i] else $SE[$i] = 0; // Push this element array_push($S, $arr[$i]); }} // Function returns maximum// difference b/w Left &// right smaller elementfunction findMaxDiff(&$arr, $n){ // To store left smaller elements $LS = array_fill(0, $n, NULL); // find left smaller element // of every element leftSmaller($arr, $n, $LS); // find right smaller element // of every element first reverse // the array and do the same process // To store right smaller // elements in reverse array $RRS = array_fill(0, $n, NULL); $k = 0; for($i = $n - 1; $i >= 0; $i--) $x[$k++] = $arr[$i]; leftSmaller($x, $n, $RRS); // find maximum absolute difference // b/w LS & RRS. In the reversed // array right smaller for arr[i] // is stored at RRS[n-i-1] $result = -1; for ($i = 0 ; $i < $n ; $i++) $result = max($result, abs($LS[$i] - $RRS[$n - 1 - $i])); // return maximum difference // b/w LS & RRS return $result;} // Driver Code$arr = array(2, 4, 8, 7, 7, 9, 3);$n = sizeof($arr);echo \"Maximum diff : \" . findMaxDiff($arr, $n) . \"\\n\"; // This code is contributed// by ChitraNayal?>", "e": 13138, "s": 11218, "text": null }, { "code": "<script>// Javascript program to find the difference b/w left and// right smaller element of every element in array // Function to fill left smaller element for every // element of arr[0..n-1]. These values are filled // in SE[0..n-1] function leftSmaller(arr,n,SE) { // Create an empty stack let S=[] // Traverse all array elements // compute nearest smaller elements of every element for (let i = 0; i < n; i++) { // Keep removing top element from S while the top // element is greater than or equal to arr[i] while (S.length!=0 && S[S.length-1] >= arr[i]) { S.pop(); } // Store the smaller element of current element if (S.length!=0) { SE[i] = S[S.length-1]; } // If all elements in S were greater than arr[i] else { SE[i] = 0; } // Push this element S.push(arr[i]); } } // Function returns maximum difference b/w Left & // right smaller element function findMaxDiff(arr,n) { // To store left smaller elements let LS = new Array(n); for(let i=0;i<n;i++) { LS[i]=0; } // find left smaller element of every element leftSmaller(arr, n, LS); // find right smaller element of every element // first reverse the array and do the same process let RRS = new Array(n); // To store right smaller elements in for(let i=0;i<n;i++) { RRS[i]=0; } // reverse array reverse(arr); leftSmaller(arr, n, RRS); // find maximum absolute difference b/w LS & RRS // In the reversed array right smaller for arr[i] is // stored at RRS[n-i-1] let result = -1; for (let i = 0; i < n; i++) { result = Math.max(result, Math.abs(LS[i] - RRS[n - 1 - i])); } // return maximum difference b/w LS & RRS return result; } function reverse(a) { let i, k, n = a.length; let t; for (i = 0; i < Math.floor(n / 2); i++) { t = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = t; } } // Driver code let arr=[2, 4, 8, 7, 7, 9, 3]; let n = arr.length; document.write(\"Maximum diff : \" + findMaxDiff(arr, n)); // This code is contributed by rag2127</script>", "e": 15721, "s": 13138, "text": null }, { "code": null, "e": 15739, "s": 15721, "text": "Maximum diff : 4\n" }, { "code": null, "e": 15783, "s": 15739, "text": "Time complexity: O(n)Auxiliary Space: O(n)." }, { "code": null, "e": 16088, "s": 15783, "text": "This article is contributed by Nishant_singh(pintu). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. " }, { "code": null, "e": 16094, "s": 16088, "text": "ukasp" }, { "code": null, "e": 16107, "s": 16094, "text": "princi singh" }, { "code": null, "e": 16119, "s": 16107, "text": "29AjayKumar" }, { "code": null, "e": 16127, "s": 16119, "text": "rag2127" }, { "code": null, "e": 16136, "s": 16127, "text": "sweetyty" }, { "code": null, "e": 16157, "s": 16136, "text": "anandkumarshivam2266" }, { "code": null, "e": 16174, "s": 16157, "text": "hardikkoriintern" }, { "code": null, "e": 16181, "s": 16174, "text": "Arrays" }, { "code": null, "e": 16187, "s": 16181, "text": "Stack" }, { "code": null, "e": 16194, "s": 16187, "text": "Arrays" }, { "code": null, "e": 16200, "s": 16194, "text": "Stack" } ]
ERROR 1396 (HY000): Operation CREATE USER failed for 'root'@'localhost'?
In the system, the root is defined by another name as well as password. Then the user is created as a root with the help of the create command. This will result in the ERROR 1396. The query for this is given as follows − mysql> create user 'root'@'localhost' identified by 'root123'; After executing the above query, the following error is obtained − ERROR 1396 (HY000): Operation CREATE USER failed for 'root'@'localhost' The user can be created with another name and password successfully. This is given as follows − mysql> create user 'John'@'localhost' identified by 'john123'; Query OK, 0 rows affected (0.14 sec) Now, the user John has been created successfully with the given password.
[ { "code": null, "e": 1242, "s": 1062, "text": "In the system, the root is defined by another name as well as password. Then the user is\ncreated as a root with the help of the create command. This will result in the ERROR 1396." }, { "code": null, "e": 1283, "s": 1242, "text": "The query for this is given as follows −" }, { "code": null, "e": 1347, "s": 1283, "text": "mysql> create user 'root'@'localhost' identified by 'root123';\n" }, { "code": null, "e": 1414, "s": 1347, "text": "After executing the above query, the following error is obtained −" }, { "code": null, "e": 1487, "s": 1414, "text": "ERROR 1396 (HY000): Operation CREATE USER failed for 'root'@'localhost'\n" }, { "code": null, "e": 1583, "s": 1487, "text": "The user can be created with another name and password successfully. This is given as\nfollows −" }, { "code": null, "e": 1684, "s": 1583, "text": "mysql> create user 'John'@'localhost' identified by 'john123';\nQuery OK, 0 rows affected (0.14 sec)\n" }, { "code": null, "e": 1758, "s": 1684, "text": "Now, the user John has been created successfully with the given password." } ]
Mirror Reflection in C++
Suppose there is a special square room with mirrors on each of the four walls. In each corner except the southwest corner, there are receptors. These are numbered as 0, 1, and 2. Now the square room has walls of length p, and a laser ray from the southwest corner first meets the east wall at a distance q from the 0th receptor. We have to find the number of the receptor that the ray meets first. So if p = 2, and q = 1, then the case will be like − So the output will be 2, as the ray meets receptor 2 the first time it gets reflected back to the left wall. To solve this, we will follow these steps − while p and q both are even,p := p/2q := q / 2 p := p/2 q := q / 2 if p is even, then return 2 if q is even, then return 0 return 1. Let us see the following implementation to get better understanding − Live Demo #include <bits/stdc++.h> using namespace std; class Solution { public: int mirrorReflection(int p, int q) { while(p % 2 == 0 && q % 2 == 0){ p >>= 1; q >>= 1; } if(p % 2 == 0) return 2; if(q % 2 == 0) return 0; return 1; } }; main(){ Solution ob; cout << (ob.mirrorReflection(2, 1)); } 2 1 2
[ { "code": null, "e": 1460, "s": 1062, "text": "Suppose there is a special square room with mirrors on each of the four walls. In each corner except the southwest corner, there are receptors. These are numbered as 0, 1, and 2. Now the square room has walls of length p, and a laser ray from the southwest corner first meets the east wall at a distance q from the 0th receptor. We have to find the number of the receptor that the ray meets first." }, { "code": null, "e": 1513, "s": 1460, "text": "So if p = 2, and q = 1, then the case will be like −" }, { "code": null, "e": 1622, "s": 1513, "text": "So the output will be 2, as the ray meets receptor 2 the first time it gets reflected back to the left wall." }, { "code": null, "e": 1666, "s": 1622, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1713, "s": 1666, "text": "while p and q both are even,p := p/2q := q / 2" }, { "code": null, "e": 1722, "s": 1713, "text": "p := p/2" }, { "code": null, "e": 1733, "s": 1722, "text": "q := q / 2" }, { "code": null, "e": 1761, "s": 1733, "text": "if p is even, then return 2" }, { "code": null, "e": 1789, "s": 1761, "text": "if q is even, then return 0" }, { "code": null, "e": 1799, "s": 1789, "text": "return 1." }, { "code": null, "e": 1869, "s": 1799, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 1880, "s": 1869, "text": " Live Demo" }, { "code": null, "e": 2226, "s": 1880, "text": "#include <bits/stdc++.h>\nusing namespace std;\nclass Solution {\npublic:\n int mirrorReflection(int p, int q) {\n while(p % 2 == 0 && q % 2 == 0){\n p >>= 1;\n q >>= 1;\n }\n if(p % 2 == 0) return 2;\n if(q % 2 == 0) return 0;\n return 1;\n }\n};\nmain(){\n Solution ob;\n cout << (ob.mirrorReflection(2, 1));\n}" }, { "code": null, "e": 2230, "s": 2226, "text": "2\n1" }, { "code": null, "e": 2232, "s": 2230, "text": "2" } ]
Pandas Groupby: Summarising, Aggregating, and Grouping data in Python
03 Mar, 2021 GroupBy is a pretty simple concept. We can create a grouping of categories and apply a function to the categories. It’s a simple concept, but it’s an extremely valuable technique that’s widely used in data science. In real data science projects, you’ll be dealing with large amounts of data and trying things over and over, so for efficiency, we use Groupby concept. Groupby concept is really important because of its ability to summarize, aggregate, and group data efficiently. Summarization includes counting, describing all the data present in data frame. We can summarize the data present in the data frame using describe() method. This method is used to get min, max, sum, count values from the data frame along with data types of that particular column. describe(): This method elaborates the type of data and its attributes. Syntax: dataframe_name.describe() unique(): This method is used to get all unique values from the given column. Syntax: dataframe[‘column_name].unique() nunique(): This method is similar to unique but it will return the count the unique values. Syntax: dataframe_name[‘column_name].nunique() info(): This command is used to get the data types and columns information Syntax: dataframe.info() columns: This command is used to display all the column names present in data frame Syntax: dataframe.columns Example: We are going to analyze the student marks data in this example. Python3 # importing pandas as pd for using data frameimport pandas as pd # creating dataframe with student detailsdataframe = pd.DataFrame({'id': [7058, 4511, 7014, 7033], 'name': ['sravan', 'manoj', 'aditya', 'bhanu'], 'Maths_marks': [99, 97, 88, 90], 'Chemistry_marks': [89, 99, 99, 90], 'telugu_marks': [99, 97, 88, 80], 'hindi_marks': [99, 97, 56, 67], 'social_marks': [79, 97, 78, 90], }) # display dataframedataframe Output: Python3 # describing the data frameprint(dataframe.describe()) print("-----------------------------")# finding unique valuesprint(dataframe['Maths_marks'].unique()) print("-----------------------------")# counting unique valuesprint(dataframe['Maths_marks'].nunique()) print("-----------------------------")# display the columns in the data frameprint(dataframe.columns) print("-----------------------------")# information about dataframeprint(dataframe.info()) Output: Aggregation is used to get the mean, average, variance and standard deviation of all column in a dataframe or particular column in a data frame. sum(): It returns the sum of the data frame Syntax: dataframe[‘column].sum() mean(): It returns the mean of the particular column in a data frame Syntax: dataframe[‘column].mean() std(): It returns the standard deviation of that column. Syntax: dataframe[‘column].std() var(): It returns the variance of that column dataframe[‘column’].var() min(): It returns the minimum value in column Syntax: dataframe[‘column’].min() max(): It returns maximum value in column Syntax: dataframe[‘column’].max() Example: In the below program we will aggregate data. Python3 # importing pandas as pd for using data frameimport pandas as pd # creating dataframe with student detailsdataframe = pd.DataFrame({'id': [7058, 4511, 7014, 7033], 'name': ['sravan', 'manoj', 'aditya', 'bhanu'], 'Maths_marks': [99, 97, 88, 90], 'Chemistry_marks': [89, 99, 99, 90], 'telugu_marks': [99, 97, 88, 80], 'hindi_marks': [99, 97, 56, 67], 'social_marks': [79, 97, 78, 90], }) # display dataframedataframe Output: Python3 # getting all minimum values from # all columns in a dataframeprint(dataframe.min())print("-----------------------------------------") # minimum value from a particular # column in a data frameprint(dataframe['Maths_marks'].min())print("-----------------------------------------") # computing maximum valuesprint(dataframe.max())print("-----------------------------------------") # computing sumprint(dataframe.sum())print("-----------------------------------------") # finding countprint(dataframe.count())print("-----------------------------------------") # computing standard deviationprint(dataframe.std())print("-----------------------------------------") # computing varianceprint(dataframe.var()) Output: It is used to group one or more columns in a dataframe by using the groupby() method. Groupby mainly refers to a process involving one or more of the following steps they are: Splitting: It is a process in which we split data into group by applying some conditions on datasets. Applying: It is a process in which we apply a function to each group independently Combining: It is a process in which we combine different datasets after applying groupby and results in a data structure Example 1: Python3 # importing pandas as pd for using data frameimport pandas as pd # creating dataframe with student detailsdataframe = pd.DataFrame({'id': [7058, 4511, 7014, 7033], 'name': ['sravan', 'manoj', 'aditya', 'bhanu'], 'Maths_marks': [99, 97, 88, 90], 'Chemistry_marks': [89, 99, 99, 90], 'telugu_marks': [99, 97, 88, 80], 'hindi_marks': [99, 97, 56, 67], 'social_marks': [79, 97, 78, 90], }) # group by nameprint(dataframe.groupby('name').first()) print("---------------------------------")# group by name with soxial_marks sumprint(dataframe.groupby('name')['social_marks'].sum())print("---------------------------------") # group by name with maths_marks countprint(dataframe.groupby('name')['Maths_marks'].count())print("---------------------------------") # group by name with maths_marksprint(dataframe.groupby('name')['Maths_marks']) Output: Example 2: Python3 # importing pandas as pd for using data frameimport pandas as pd # creating dataframe with student detailsdataframe = pd.DataFrame({'id': [7058, 4511, 7014, 7033], 'name': ['sravan', 'manoj', 'aditya', 'bhanu'], 'Maths_marks': [99, 97, 88, 90], 'Chemistry_marks': [89, 99, 99, 90], 'telugu_marks': [99, 97, 88, 80], 'hindi_marks': [99, 97, 56, 67], 'social_marks': [79, 97, 78, 90], }) # group by nameprint(dataframe.groupby('name').first()) print("------------------------")# group by name with soxial_marks sumprint(dataframe.groupby('name')['social_marks'].sum())print("------------------------")# group by name with maths_marks countprint(dataframe.groupby('name')['Maths_marks'].count()) Output: Picked Python pandas-groupby Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python | os.path.join() method Python OOPs Concepts How to drop one or multiple columns in Pandas Dataframe Introduction To PYTHON How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | datetime.timedelta() function Python | Get unique values from a list
[ { "code": null, "e": 28, "s": 0, "text": "\n03 Mar, 2021" }, { "code": null, "e": 507, "s": 28, "text": "GroupBy is a pretty simple concept. We can create a grouping of categories and apply a function to the categories. It’s a simple concept, but it’s an extremely valuable technique that’s widely used in data science. In real data science projects, you’ll be dealing with large amounts of data and trying things over and over, so for efficiency, we use Groupby concept. Groupby concept is really important because of its ability to summarize, aggregate, and group data efficiently." }, { "code": null, "e": 788, "s": 507, "text": "Summarization includes counting, describing all the data present in data frame. We can summarize the data present in the data frame using describe() method. This method is used to get min, max, sum, count values from the data frame along with data types of that particular column." }, { "code": null, "e": 860, "s": 788, "text": "describe(): This method elaborates the type of data and its attributes." }, { "code": null, "e": 868, "s": 860, "text": "Syntax:" }, { "code": null, "e": 894, "s": 868, "text": "dataframe_name.describe()" }, { "code": null, "e": 972, "s": 894, "text": "unique(): This method is used to get all unique values from the given column." }, { "code": null, "e": 980, "s": 972, "text": "Syntax:" }, { "code": null, "e": 1013, "s": 980, "text": "dataframe[‘column_name].unique()" }, { "code": null, "e": 1105, "s": 1013, "text": "nunique(): This method is similar to unique but it will return the count the unique values." }, { "code": null, "e": 1113, "s": 1105, "text": "Syntax:" }, { "code": null, "e": 1152, "s": 1113, "text": "dataframe_name[‘column_name].nunique()" }, { "code": null, "e": 1227, "s": 1152, "text": "info(): This command is used to get the data types and columns information" }, { "code": null, "e": 1235, "s": 1227, "text": "Syntax:" }, { "code": null, "e": 1252, "s": 1235, "text": "dataframe.info()" }, { "code": null, "e": 1336, "s": 1252, "text": "columns: This command is used to display all the column names present in data frame" }, { "code": null, "e": 1344, "s": 1336, "text": "Syntax:" }, { "code": null, "e": 1362, "s": 1344, "text": "dataframe.columns" }, { "code": null, "e": 1371, "s": 1362, "text": "Example:" }, { "code": null, "e": 1435, "s": 1371, "text": "We are going to analyze the student marks data in this example." }, { "code": null, "e": 1443, "s": 1435, "text": "Python3" }, { "code": "# importing pandas as pd for using data frameimport pandas as pd # creating dataframe with student detailsdataframe = pd.DataFrame({'id': [7058, 4511, 7014, 7033], 'name': ['sravan', 'manoj', 'aditya', 'bhanu'], 'Maths_marks': [99, 97, 88, 90], 'Chemistry_marks': [89, 99, 99, 90], 'telugu_marks': [99, 97, 88, 80], 'hindi_marks': [99, 97, 56, 67], 'social_marks': [79, 97, 78, 90], }) # display dataframedataframe", "e": 2010, "s": 1443, "text": null }, { "code": null, "e": 2018, "s": 2010, "text": "Output:" }, { "code": null, "e": 2026, "s": 2018, "text": "Python3" }, { "code": "# describing the data frameprint(dataframe.describe()) print(\"-----------------------------\")# finding unique valuesprint(dataframe['Maths_marks'].unique()) print(\"-----------------------------\")# counting unique valuesprint(dataframe['Maths_marks'].nunique()) print(\"-----------------------------\")# display the columns in the data frameprint(dataframe.columns) print(\"-----------------------------\")# information about dataframeprint(dataframe.info())", "e": 2484, "s": 2026, "text": null }, { "code": null, "e": 2492, "s": 2484, "text": "Output:" }, { "code": null, "e": 2637, "s": 2492, "text": "Aggregation is used to get the mean, average, variance and standard deviation of all column in a dataframe or particular column in a data frame." }, { "code": null, "e": 2681, "s": 2637, "text": "sum(): It returns the sum of the data frame" }, { "code": null, "e": 2689, "s": 2681, "text": "Syntax:" }, { "code": null, "e": 2714, "s": 2689, "text": "dataframe[‘column].sum()" }, { "code": null, "e": 2783, "s": 2714, "text": "mean(): It returns the mean of the particular column in a data frame" }, { "code": null, "e": 2791, "s": 2783, "text": "Syntax:" }, { "code": null, "e": 2817, "s": 2791, "text": "dataframe[‘column].mean()" }, { "code": null, "e": 2874, "s": 2817, "text": "std(): It returns the standard deviation of that column." }, { "code": null, "e": 2882, "s": 2874, "text": "Syntax:" }, { "code": null, "e": 2907, "s": 2882, "text": "dataframe[‘column].std()" }, { "code": null, "e": 2953, "s": 2907, "text": "var(): It returns the variance of that column" }, { "code": null, "e": 2979, "s": 2953, "text": "dataframe[‘column’].var()" }, { "code": null, "e": 3025, "s": 2979, "text": "min(): It returns the minimum value in column" }, { "code": null, "e": 3033, "s": 3025, "text": "Syntax:" }, { "code": null, "e": 3059, "s": 3033, "text": "dataframe[‘column’].min()" }, { "code": null, "e": 3101, "s": 3059, "text": "max(): It returns maximum value in column" }, { "code": null, "e": 3109, "s": 3101, "text": "Syntax:" }, { "code": null, "e": 3135, "s": 3109, "text": "dataframe[‘column’].max()" }, { "code": null, "e": 3144, "s": 3135, "text": "Example:" }, { "code": null, "e": 3189, "s": 3144, "text": "In the below program we will aggregate data." }, { "code": null, "e": 3197, "s": 3189, "text": "Python3" }, { "code": "# importing pandas as pd for using data frameimport pandas as pd # creating dataframe with student detailsdataframe = pd.DataFrame({'id': [7058, 4511, 7014, 7033], 'name': ['sravan', 'manoj', 'aditya', 'bhanu'], 'Maths_marks': [99, 97, 88, 90], 'Chemistry_marks': [89, 99, 99, 90], 'telugu_marks': [99, 97, 88, 80], 'hindi_marks': [99, 97, 56, 67], 'social_marks': [79, 97, 78, 90], }) # display dataframedataframe", "e": 3764, "s": 3197, "text": null }, { "code": null, "e": 3772, "s": 3764, "text": "Output:" }, { "code": null, "e": 3780, "s": 3772, "text": "Python3" }, { "code": "# getting all minimum values from # all columns in a dataframeprint(dataframe.min())print(\"-----------------------------------------\") # minimum value from a particular # column in a data frameprint(dataframe['Maths_marks'].min())print(\"-----------------------------------------\") # computing maximum valuesprint(dataframe.max())print(\"-----------------------------------------\") # computing sumprint(dataframe.sum())print(\"-----------------------------------------\") # finding countprint(dataframe.count())print(\"-----------------------------------------\") # computing standard deviationprint(dataframe.std())print(\"-----------------------------------------\") # computing varianceprint(dataframe.var())", "e": 4492, "s": 3780, "text": null }, { "code": null, "e": 4500, "s": 4492, "text": "Output:" }, { "code": null, "e": 4676, "s": 4500, "text": "It is used to group one or more columns in a dataframe by using the groupby() method. Groupby mainly refers to a process involving one or more of the following steps they are:" }, { "code": null, "e": 4778, "s": 4676, "text": "Splitting: It is a process in which we split data into group by applying some conditions on datasets." }, { "code": null, "e": 4861, "s": 4778, "text": "Applying: It is a process in which we apply a function to each group independently" }, { "code": null, "e": 4982, "s": 4861, "text": "Combining: It is a process in which we combine different datasets after applying groupby and results in a data structure" }, { "code": null, "e": 4993, "s": 4982, "text": "Example 1:" }, { "code": null, "e": 5001, "s": 4993, "text": "Python3" }, { "code": "# importing pandas as pd for using data frameimport pandas as pd # creating dataframe with student detailsdataframe = pd.DataFrame({'id': [7058, 4511, 7014, 7033], 'name': ['sravan', 'manoj', 'aditya', 'bhanu'], 'Maths_marks': [99, 97, 88, 90], 'Chemistry_marks': [89, 99, 99, 90], 'telugu_marks': [99, 97, 88, 80], 'hindi_marks': [99, 97, 56, 67], 'social_marks': [79, 97, 78, 90], }) # group by nameprint(dataframe.groupby('name').first()) print(\"---------------------------------\")# group by name with soxial_marks sumprint(dataframe.groupby('name')['social_marks'].sum())print(\"---------------------------------\") # group by name with maths_marks countprint(dataframe.groupby('name')['Maths_marks'].count())print(\"---------------------------------\") # group by name with maths_marksprint(dataframe.groupby('name')['Maths_marks'])", "e": 5992, "s": 5001, "text": null }, { "code": null, "e": 6000, "s": 5992, "text": "Output:" }, { "code": null, "e": 6011, "s": 6000, "text": "Example 2:" }, { "code": null, "e": 6019, "s": 6011, "text": "Python3" }, { "code": "# importing pandas as pd for using data frameimport pandas as pd # creating dataframe with student detailsdataframe = pd.DataFrame({'id': [7058, 4511, 7014, 7033], 'name': ['sravan', 'manoj', 'aditya', 'bhanu'], 'Maths_marks': [99, 97, 88, 90], 'Chemistry_marks': [89, 99, 99, 90], 'telugu_marks': [99, 97, 88, 80], 'hindi_marks': [99, 97, 56, 67], 'social_marks': [79, 97, 78, 90], }) # group by nameprint(dataframe.groupby('name').first()) print(\"------------------------\")# group by name with soxial_marks sumprint(dataframe.groupby('name')['social_marks'].sum())print(\"------------------------\")# group by name with maths_marks countprint(dataframe.groupby('name')['Maths_marks'].count())", "e": 6865, "s": 6019, "text": null }, { "code": null, "e": 6873, "s": 6865, "text": "Output:" }, { "code": null, "e": 6880, "s": 6873, "text": "Picked" }, { "code": null, "e": 6902, "s": 6880, "text": "Python pandas-groupby" }, { "code": null, "e": 6916, "s": 6902, "text": "Python-pandas" }, { "code": null, "e": 6923, "s": 6916, "text": "Python" }, { "code": null, "e": 7021, "s": 6923, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7053, "s": 7021, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 7080, "s": 7053, "text": "Python Classes and Objects" }, { "code": null, "e": 7111, "s": 7080, "text": "Python | os.path.join() method" }, { "code": null, "e": 7132, "s": 7111, "text": "Python OOPs Concepts" }, { "code": null, "e": 7188, "s": 7132, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 7211, "s": 7188, "text": "Introduction To PYTHON" }, { "code": null, "e": 7253, "s": 7211, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 7295, "s": 7253, "text": "Check if element exists in list in Python" }, { "code": null, "e": 7334, "s": 7295, "text": "Python | datetime.timedelta() function" } ]
SVG Element.innerHTML Property
30 Mar, 2022 The SVG Element.innerHTML property returns innerHTML of the given element. Syntax: const content = element.innerHTML Return value: This property returns innerHTML of the element. Example 1: <!DOCTYPE html><html> <body> <svg width="350" height="100" xmlns="http://www.w3.org/2000/svg"> <a href="https://www.geeksforgeeks.org" id="gfg"> <text x='100' y='50' font-size="50px"> GfG </text> </a> <script> var g = document.getElementById('gfg'); console.log(g.innerHTML); </script> </svg></body> </html> Output: Example 2: <!DOCTYPE html><html> <body> <svg width="350" height="100" xmlns="http://www.w3.org/2000/svg"> <a href="https://www.geeksforgeeks.org" id="gfg"> <circle cx='100' cy='50' r="50"> </circle> </a> <script> var g = document.getElementById('gfg'); console.log(g.innerHTML); </script> </svg></body> </html> Output: HTML-SVG SVG-Property HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. REST API (Introduction) Design a Tribute Page using HTML & CSS Build a Survey Form using HTML and CSS Angular File Upload Form validation using jQuery Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Mar, 2022" }, { "code": null, "e": 103, "s": 28, "text": "The SVG Element.innerHTML property returns innerHTML of the given element." }, { "code": null, "e": 111, "s": 103, "text": "Syntax:" }, { "code": null, "e": 145, "s": 111, "text": "const content = element.innerHTML" }, { "code": null, "e": 207, "s": 145, "text": "Return value: This property returns innerHTML of the element." }, { "code": null, "e": 219, "s": 207, "text": "Example 1: " }, { "code": "<!DOCTYPE html><html> <body> <svg width=\"350\" height=\"100\" xmlns=\"http://www.w3.org/2000/svg\"> <a href=\"https://www.geeksforgeeks.org\" id=\"gfg\"> <text x='100' y='50' font-size=\"50px\"> GfG </text> </a> <script> var g = document.getElementById('gfg'); console.log(g.innerHTML); </script> </svg></body> </html>", "e": 664, "s": 219, "text": null }, { "code": null, "e": 672, "s": 664, "text": "Output:" }, { "code": null, "e": 684, "s": 672, "text": "Example 2: " }, { "code": "<!DOCTYPE html><html> <body> <svg width=\"350\" height=\"100\" xmlns=\"http://www.w3.org/2000/svg\"> <a href=\"https://www.geeksforgeeks.org\" id=\"gfg\"> <circle cx='100' cy='50' r=\"50\"> </circle> </a> <script> var g = document.getElementById('gfg'); console.log(g.innerHTML); </script> </svg></body> </html>", "e": 1081, "s": 684, "text": null }, { "code": null, "e": 1089, "s": 1081, "text": "Output:" }, { "code": null, "e": 1098, "s": 1089, "text": "HTML-SVG" }, { "code": null, "e": 1111, "s": 1098, "text": "SVG-Property" }, { "code": null, "e": 1116, "s": 1111, "text": "HTML" }, { "code": null, "e": 1133, "s": 1116, "text": "Web Technologies" }, { "code": null, "e": 1138, "s": 1133, "text": "HTML" }, { "code": null, "e": 1236, "s": 1138, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1260, "s": 1236, "text": "REST API (Introduction)" }, { "code": null, "e": 1299, "s": 1260, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 1338, "s": 1299, "text": "Build a Survey Form using HTML and CSS" }, { "code": null, "e": 1358, "s": 1338, "text": "Angular File Upload" }, { "code": null, "e": 1387, "s": 1358, "text": "Form validation using jQuery" }, { "code": null, "e": 1420, "s": 1387, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 1481, "s": 1420, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 1524, "s": 1481, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 1596, "s": 1524, "text": "Differences between Functional Components and Class Components in React" } ]
YAML - Syntax Characters
Various types of characters are used for various functionalities. This chapter talks in detail about syntax used in YAML and focuses on character manipulation. Indicator characters include a special semantics used to describe the content of YAML document. The following table shows this in detail. _ It denotes a block sequence entry ? It denotes a mapping key : It denotes a mapping value , It denotes flow collection entry [ It starts a flow sequence ] It ends a flow sequence { It starts a flow mapping } It ends a flow mapping # It denotes the comments & It denotes node’s anchor property * It denotes alias node ! It denotes node’s tag | It denotes a literal block scalar > It denotes a folded block scalar ` Single quote surrounds a quoted flow scalar " Double quote surrounds double quoted flow scalar % It denotes the directive used The following example shows the characters used in syntax − %YAML 1.1 --- !!map { ? !!str "sequence" : !!seq [ !!str "one", !!str "two" ], ? !!str "mapping" : !!map { ? !!str "sky" : !!str "blue", ? !!str "sea" : !!str "green", } } # This represents # only comments. --- !!map1 { ? !!str "anchored" : !local &A1 "value", ? !!str "alias"
[ { "code": null, "e": 2342, "s": 2182, "text": "Various types of characters are used for various functionalities. This chapter talks in detail about syntax used in YAML and focuses on character manipulation." }, { "code": null, "e": 2480, "s": 2342, "text": "Indicator characters include a special semantics used to describe the content of YAML document. The following table shows this in detail." }, { "code": null, "e": 2482, "s": 2480, "text": "_" }, { "code": null, "e": 2516, "s": 2482, "text": "It denotes a block sequence entry" }, { "code": null, "e": 2518, "s": 2516, "text": "?" }, { "code": null, "e": 2543, "s": 2518, "text": "It denotes a mapping key" }, { "code": null, "e": 2545, "s": 2543, "text": ":" }, { "code": null, "e": 2572, "s": 2545, "text": "It denotes a mapping value" }, { "code": null, "e": 2574, "s": 2572, "text": "," }, { "code": null, "e": 2607, "s": 2574, "text": "It denotes flow collection entry" }, { "code": null, "e": 2609, "s": 2607, "text": "[" }, { "code": null, "e": 2635, "s": 2609, "text": "It starts a flow sequence" }, { "code": null, "e": 2637, "s": 2635, "text": "]" }, { "code": null, "e": 2661, "s": 2637, "text": "It ends a flow sequence" }, { "code": null, "e": 2663, "s": 2661, "text": "{" }, { "code": null, "e": 2688, "s": 2663, "text": "It starts a flow mapping" }, { "code": null, "e": 2690, "s": 2688, "text": "}" }, { "code": null, "e": 2713, "s": 2690, "text": "It ends a flow mapping" }, { "code": null, "e": 2715, "s": 2713, "text": "#" }, { "code": null, "e": 2739, "s": 2715, "text": "It denotes the comments" }, { "code": null, "e": 2741, "s": 2739, "text": "&" }, { "code": null, "e": 2775, "s": 2741, "text": "It denotes node’s anchor property" }, { "code": null, "e": 2777, "s": 2775, "text": "*" }, { "code": null, "e": 2799, "s": 2777, "text": "It denotes alias node" }, { "code": null, "e": 2801, "s": 2799, "text": "!" }, { "code": null, "e": 2823, "s": 2801, "text": "It denotes node’s tag" }, { "code": null, "e": 2825, "s": 2823, "text": "|" }, { "code": null, "e": 2859, "s": 2825, "text": "It denotes a literal block scalar" }, { "code": null, "e": 2861, "s": 2859, "text": ">" }, { "code": null, "e": 2894, "s": 2861, "text": "It denotes a folded block scalar" }, { "code": null, "e": 2896, "s": 2894, "text": "`" }, { "code": null, "e": 2940, "s": 2896, "text": "Single quote surrounds a quoted flow scalar" }, { "code": null, "e": 2942, "s": 2940, "text": "\"" }, { "code": null, "e": 2991, "s": 2942, "text": "Double quote surrounds double quoted flow scalar" }, { "code": null, "e": 2993, "s": 2991, "text": "%" }, { "code": null, "e": 3023, "s": 2993, "text": "It denotes the directive used" }, { "code": null, "e": 3083, "s": 3023, "text": "The following example shows the characters used in syntax −" } ]
What are Python dictionary view objects?
Dictionary methods items(), keys() and values() return view objects. The items() method returns a dict_items object containing list of key-value pairs in the dictionary >>> D1={"pen":25, "pencil":10, "book":100, "sharpner":5, "eraser":5} >>> i=D1.items() >>> i dict_items([('pen', 25), ('pencil', 10), ('book', 100), ('sharpner', 5), ('eraser', 5)]) The keys() method returns a view object of the type dict_keys that holds a list of all keys >>> k=D1.keys() >>> k dict_keys(['pen', 'pencil', 'book', 'sharpner', 'eraser']) Similarly, values() method returns dict_values object >>> v=D1.values() >>> v dict_values([25, 10, 100, 5, 5]) These view objects are updated dynamically. In changes in the underlying dictionary object are reflected in the view. For instance, if ‘book’ key is deleted from the dictionary, the respective view objects will also not show related entries. >>> del D1['book'] >>> k dict_keys(['pen', 'pencil', 'sharpner', 'eraser']) >>> i dict_items([('pen', 25), ('pencil', 10), ('sharpner', 5), ('eraser', 5)]) >>> v dict_values([25, 10, 5, 5])
[ { "code": null, "e": 1356, "s": 1187, "text": "Dictionary methods items(), keys() and values() return view objects. The items() method returns a dict_items object containing list of key-value pairs in the dictionary" }, { "code": null, "e": 1537, "s": 1356, "text": ">>> D1={\"pen\":25, \"pencil\":10, \"book\":100, \"sharpner\":5, \"eraser\":5}\n>>> i=D1.items()\n>>> i\ndict_items([('pen', 25), ('pencil', 10), ('book', 100), ('sharpner', 5), ('eraser', 5)])" }, { "code": null, "e": 1629, "s": 1537, "text": "The keys() method returns a view object of the type dict_keys that holds a list of all keys" }, { "code": null, "e": 1710, "s": 1629, "text": ">>> k=D1.keys()\n>>> k\ndict_keys(['pen', 'pencil', 'book', 'sharpner', 'eraser'])" }, { "code": null, "e": 1764, "s": 1710, "text": "Similarly, values() method returns dict_values object" }, { "code": null, "e": 1821, "s": 1764, "text": ">>> v=D1.values()\n>>> v\ndict_values([25, 10, 100, 5, 5])" }, { "code": null, "e": 2063, "s": 1821, "text": "These view objects are updated dynamically. In changes in the underlying dictionary object are reflected in the view. For instance, if ‘book’ key is deleted from the dictionary, the respective view objects will also not show related entries." }, { "code": null, "e": 2253, "s": 2063, "text": ">>> del D1['book']\n>>> k\ndict_keys(['pen', 'pencil', 'sharpner', 'eraser'])\n>>> i\ndict_items([('pen', 25), ('pencil', 10), ('sharpner', 5), ('eraser', 5)])\n>>> v\ndict_values([25, 10, 5, 5])" } ]
Create a real time voice translator using Python
05 Nov, 2021 In this article, we are going to create a real-time voice translator in Python. playsound: This module is used to play sound in Python pip install playsound Speech Recognition Module: It is a library with the help of which Python can recognize the command given. We have to use pip for Speech Recognition. pip install SpeechRecognition googletrans: Googletrans is a free and unlimited python library that implemented Google Translate API pip install googletrans gTTs: The gTTS API supports several languages including English, Hindi, Tamil, French, German and many more. pip install gTTs pip install gTTS-token A real-time voice translator that can translate voice input and give translated voice output generated from it. It is created using google’s googleTrans API and speech_recognition library of python. It converts text from one language to another language and saves its mp3 recorded file. The playsound module is then used to play the generated mp3 file, After that, the generated mp3 file is deleted using the os module. Step 1: Importing Necessary Modules Python3 # Importing necessary modules required from playsound import playsoundimport speech_recognition as sr from googletrans import Translator from gtts import gTTS import os Step 2: A tuple of all the languages mapped with their code Python3 dic=('afrikaans', 'af', 'albanian', 'sq', 'amharic', 'am', 'arabic', 'ar', 'armenian', 'hy', 'azerbaijani', 'az', 'basque', 'eu', 'belarusian', 'be', 'bengali', 'bn', 'bosnian', 'bs', 'bulgarian', 'bg', 'catalan', 'ca', 'cebuano', 'ceb', 'chichewa', 'ny', 'chinese (simplified)', 'zh-cn', 'chinese (traditional)', 'zh-tw', 'corsican', 'co', 'croatian', 'hr', 'czech', 'cs', 'danish', 'da', 'dutch', 'nl', 'english', 'en', 'esperanto', 'eo', 'estonian', 'et', 'filipino', 'tl', 'finnish', 'fi', 'french', 'fr', 'frisian', 'fy', 'galician', 'gl', 'georgian', 'ka', 'german', 'de', 'greek', 'el', 'gujarati', 'gu', 'haitian creole', 'ht', 'hausa', 'ha', 'hawaiian', 'haw', 'hebrew', 'he', 'hindi', 'hi', 'hmong', 'hmn', 'hungarian', 'hu', 'icelandic', 'is', 'igbo', 'ig', 'indonesian', 'id', 'irish', 'ga', 'italian', 'it', 'japanese', 'ja', 'javanese', 'jw', 'kannada', 'kn', 'kazakh', 'kk', 'khmer', 'km', 'korean', 'ko', 'kurdish (kurmanji)', 'ku', 'kyrgyz', 'ky', 'lao', 'lo', 'latin', 'la', 'latvian', 'lv', 'lithuanian', 'lt', 'luxembourgish', 'lb', 'macedonian', 'mk', 'malagasy', 'mg', 'malay', 'ms', 'malayalam', 'ml', 'maltese', 'mt', 'maori', 'mi', 'marathi', 'mr', 'mongolian', 'mn', 'myanmar (burmese)', 'my', 'nepali', 'ne', 'norwegian', 'no', 'odia', 'or', 'pashto', 'ps', 'persian', 'fa', 'polish', 'pl', 'portuguese', 'pt', 'punjabi', 'pa', 'romanian', 'ro', 'russian', 'ru', 'samoan', 'sm', 'scots gaelic', 'gd', 'serbian', 'sr', 'sesotho', 'st', 'shona', 'sn', 'sindhi', 'sd', 'sinhala', 'si', 'slovak', 'sk', 'slovenian', 'sl', 'somali', 'so', 'spanish', 'es', 'sundanese', 'su', 'swahili', 'sw', 'swedish', 'sv', 'tajik', 'tg', 'tamil', 'ta', 'telugu', 'te', 'thai', 'th', 'turkish', 'tr', 'ukrainian', 'uk', 'urdu', 'ur', 'uyghur', 'ug', 'uzbek', 'uz', 'vietnamese', 'vi', 'welsh', 'cy', 'xhosa', 'xh', 'yiddish', 'yi', 'yoruba', 'yo', 'zulu', 'zu') Step 3: Taking voice commands from the user Python3 # Capture Voice# takes command through microphonedef takecommand(): r = sr.Recognizer() with sr.Microphone() as source: print("listening.....") r.pause_threshold = 1 audio = r.listen(source) try: print("Recognizing.....") query = r.recognize_google(audio, language='en-in') print(f"user said {query}\n") except Exception as e: print("say that again please.....") return "None" return query Step 4: Taking voice input from the user Python3 # Taking voice input from the userquery = takecommand()while (query == "None"): query = takecommand() Step 5: Input destination language from the user, Mapping user input with the language code Python3 def destination_language(): print("Enter the language in which you want to convert \ : Ex. Hindi , English , etc.") print() # Input destination language in which the user # wants to translate to_lang = takecommand() while (to_lang == "None"): to_lang = takecommand() to_lang = to_lang.lower() return to_lang to_lang = destination_language() # Mapping it with the codewhile (to_lang not in dic): print("Language in which you are trying to convert\ is currently not available ,please input some other language") print() to_lang = destination_language() to_lang = dic[dic.index(to_lang)+1] Step 6: Invoking Translator Python3 # invoking Translatortranslator = Translator() Step 7: Translating from src to dest Python3 # Translating from src to desttext_to_translate = translator.translate(query, dest=to_lang)text = text_to_translate.text Step 8: Saving Translated files and deleting them after playing Python3 # Using Google-Text-to-Speech ie, gTTS() method# to speak the translated text into the# destination language which is stored in to_lang.# Also, we have given 3rd argument as False because# by default it speaks very slowlyspeak = gTTS(text=text, lang=to_lang, slow=False) # Using save() method to save the translated# speech in capture_voice.mp3speak.save("captured_voice.mp3") # Using OS module to run the translated voice.playsound('captured_voice.mp3')os.remove('captured_voice.mp3')print(text) Below is the full implementation: Python3 # Importing necessary modules requiredfrom playsound import playsoundimport speech_recognition as srfrom googletrans import Translatorfrom gtts import gTTSimport osflag = 0 # A tuple containing all the language and# codes of the language will be detcteddic = ('afrikaans', 'af', 'albanian', 'sq', 'amharic', 'am', 'arabic', 'ar', 'armenian', 'hy', 'azerbaijani', 'az', 'basque', 'eu', 'belarusian', 'be', 'bengali', 'bn', 'bosnian', 'bs', 'bulgarian', 'bg', 'catalan', 'ca', 'cebuano', 'ceb', 'chichewa', 'ny', 'chinese (simplified)', 'zh-cn', 'chinese (traditional)', 'zh-tw', 'corsican', 'co', 'croatian', 'hr', 'czech', 'cs', 'danish', 'da', 'dutch', 'nl', 'english', 'en', 'esperanto', 'eo', 'estonian', 'et', 'filipino', 'tl', 'finnish', 'fi', 'french', 'fr', 'frisian', 'fy', 'galician', 'gl', 'georgian', 'ka', 'german', 'de', 'greek', 'el', 'gujarati', 'gu', 'haitian creole', 'ht', 'hausa', 'ha', 'hawaiian', 'haw', 'hebrew', 'he', 'hindi', 'hi', 'hmong', 'hmn', 'hungarian', 'hu', 'icelandic', 'is', 'igbo', 'ig', 'indonesian', 'id', 'irish', 'ga', 'italian', 'it', 'japanese', 'ja', 'javanese', 'jw', 'kannada', 'kn', 'kazakh', 'kk', 'khmer', 'km', 'korean', 'ko', 'kurdish (kurmanji)', 'ku', 'kyrgyz', 'ky', 'lao', 'lo', 'latin', 'la', 'latvian', 'lv', 'lithuanian', 'lt', 'luxembourgish', 'lb', 'macedonian', 'mk', 'malagasy', 'mg', 'malay', 'ms', 'malayalam', 'ml', 'maltese', 'mt', 'maori', 'mi', 'marathi', 'mr', 'mongolian', 'mn', 'myanmar (burmese)', 'my', 'nepali', 'ne', 'norwegian', 'no', 'odia', 'or', 'pashto', 'ps', 'persian', 'fa', 'polish', 'pl', 'portuguese', 'pt', 'punjabi', 'pa', 'romanian', 'ro', 'russian', 'ru', 'samoan', 'sm', 'scots gaelic', 'gd', 'serbian', 'sr', 'sesotho', 'st', 'shona', 'sn', 'sindhi', 'sd', 'sinhala', 'si', 'slovak', 'sk', 'slovenian', 'sl', 'somali', 'so', 'spanish', 'es', 'sundanese', 'su', 'swahili', 'sw', 'swedish', 'sv', 'tajik', 'tg', 'tamil', 'ta', 'telugu', 'te', 'thai', 'th', 'turkish', 'tr', 'ukrainian', 'uk', 'urdu', 'ur', 'uyghur', 'ug', 'uzbek', 'uz', 'vietnamese', 'vi', 'welsh', 'cy', 'xhosa', 'xh', 'yiddish', 'yi', 'yoruba', 'yo', 'zulu', 'zu') # Capture Voice# takes command through microphonedef takecommand(): r = sr.Recognizer() with sr.Microphone() as source: print("listening.....") r.pause_threshold = 1 audio = r.listen(source) try: print("Recognizing.....") query = r.recognize_google(audio, language='en-in') print(f"The User said {query}\n") except Exception as e: print("say that again please.....") return "None" return query # Input from user# Make input to lowercasequery = takecommand()while (query == "None"): query = takecommand() def destination_language(): print("Enter the language in which you\ want to convert : Ex. Hindi , English , etc.") print() # Input destination language in # which the user wants to translate to_lang = takecommand() while (to_lang == "None"): to_lang = takecommand() to_lang = to_lang.lower() return to_lang to_lang = destination_language() # Mapping it with the codewhile (to_lang not in dic): print("Language in which you are trying\ to convert is currently not available ,\ please input some other language") print() to_lang = destination_language() to_lang = dic[dic.index(to_lang)+1] # invoking Translatortranslator = Translator() # Translating from src to desttext_to_translate = translator.translate(query, dest=to_lang) text = text_to_translate.text # Using Google-Text-to-Speech ie, gTTS() method# to speak the translated text into the# destination language which is stored in to_lang.# Also, we have given 3rd argument as False because# by default it speaks very slowlyspeak = gTTS(text=text, lang=to_lang, slow=False) # Using save() method to save the translated# speech in capture_voice.mp3speak.save("captured_voice.mp3") # Using OS module to run the translated voice.playsound('captured_voice.mp3')os.remove('captured_voice.mp3') # Printing Outputprint(text) Output: Media error: Format(s) not supported or source(s) not found Python-projects python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n05 Nov, 2021" }, { "code": null, "e": 134, "s": 54, "text": "In this article, we are going to create a real-time voice translator in Python." }, { "code": null, "e": 189, "s": 134, "text": "playsound: This module is used to play sound in Python" }, { "code": null, "e": 211, "s": 189, "text": "pip install playsound" }, { "code": null, "e": 360, "s": 211, "text": "Speech Recognition Module: It is a library with the help of which Python can recognize the command given. We have to use pip for Speech Recognition." }, { "code": null, "e": 390, "s": 360, "text": "pip install SpeechRecognition" }, { "code": null, "e": 492, "s": 390, "text": "googletrans: Googletrans is a free and unlimited python library that implemented Google Translate API" }, { "code": null, "e": 516, "s": 492, "text": "pip install googletrans" }, { "code": null, "e": 626, "s": 516, "text": "gTTs: The gTTS API supports several languages including English, Hindi, Tamil, French, German and many more. " }, { "code": null, "e": 666, "s": 626, "text": "pip install gTTs\npip install gTTS-token" }, { "code": null, "e": 1086, "s": 666, "text": "A real-time voice translator that can translate voice input and give translated voice output generated from it. It is created using google’s googleTrans API and speech_recognition library of python. It converts text from one language to another language and saves its mp3 recorded file. The playsound module is then used to play the generated mp3 file, After that, the generated mp3 file is deleted using the os module." }, { "code": null, "e": 1122, "s": 1086, "text": "Step 1: Importing Necessary Modules" }, { "code": null, "e": 1130, "s": 1122, "text": "Python3" }, { "code": "# Importing necessary modules required from playsound import playsoundimport speech_recognition as sr from googletrans import Translator from gtts import gTTS import os", "e": 1299, "s": 1130, "text": null }, { "code": null, "e": 1359, "s": 1299, "text": "Step 2: A tuple of all the languages mapped with their code" }, { "code": null, "e": 1367, "s": 1359, "text": "Python3" }, { "code": "dic=('afrikaans', 'af', 'albanian', 'sq', 'amharic', 'am', 'arabic', 'ar', 'armenian', 'hy', 'azerbaijani', 'az', 'basque', 'eu', 'belarusian', 'be', 'bengali', 'bn', 'bosnian', 'bs', 'bulgarian', 'bg', 'catalan', 'ca', 'cebuano', 'ceb', 'chichewa', 'ny', 'chinese (simplified)', 'zh-cn', 'chinese (traditional)', 'zh-tw', 'corsican', 'co', 'croatian', 'hr', 'czech', 'cs', 'danish', 'da', 'dutch', 'nl', 'english', 'en', 'esperanto', 'eo', 'estonian', 'et', 'filipino', 'tl', 'finnish', 'fi', 'french', 'fr', 'frisian', 'fy', 'galician', 'gl', 'georgian', 'ka', 'german', 'de', 'greek', 'el', 'gujarati', 'gu', 'haitian creole', 'ht', 'hausa', 'ha', 'hawaiian', 'haw', 'hebrew', 'he', 'hindi', 'hi', 'hmong', 'hmn', 'hungarian', 'hu', 'icelandic', 'is', 'igbo', 'ig', 'indonesian', 'id', 'irish', 'ga', 'italian', 'it', 'japanese', 'ja', 'javanese', 'jw', 'kannada', 'kn', 'kazakh', 'kk', 'khmer', 'km', 'korean', 'ko', 'kurdish (kurmanji)', 'ku', 'kyrgyz', 'ky', 'lao', 'lo', 'latin', 'la', 'latvian', 'lv', 'lithuanian', 'lt', 'luxembourgish', 'lb', 'macedonian', 'mk', 'malagasy', 'mg', 'malay', 'ms', 'malayalam', 'ml', 'maltese', 'mt', 'maori', 'mi', 'marathi', 'mr', 'mongolian', 'mn', 'myanmar (burmese)', 'my', 'nepali', 'ne', 'norwegian', 'no', 'odia', 'or', 'pashto', 'ps', 'persian', 'fa', 'polish', 'pl', 'portuguese', 'pt', 'punjabi', 'pa', 'romanian', 'ro', 'russian', 'ru', 'samoan', 'sm', 'scots gaelic', 'gd', 'serbian', 'sr', 'sesotho', 'st', 'shona', 'sn', 'sindhi', 'sd', 'sinhala', 'si', 'slovak', 'sk', 'slovenian', 'sl', 'somali', 'so', 'spanish', 'es', 'sundanese', 'su', 'swahili', 'sw', 'swedish', 'sv', 'tajik', 'tg', 'tamil', 'ta', 'telugu', 'te', 'thai', 'th', 'turkish', 'tr', 'ukrainian', 'uk', 'urdu', 'ur', 'uyghur', 'ug', 'uzbek', 'uz', 'vietnamese', 'vi', 'welsh', 'cy', 'xhosa', 'xh', 'yiddish', 'yi', 'yoruba', 'yo', 'zulu', 'zu')", "e": 3334, "s": 1367, "text": null }, { "code": null, "e": 3378, "s": 3334, "text": "Step 3: Taking voice commands from the user" }, { "code": null, "e": 3386, "s": 3378, "text": "Python3" }, { "code": "# Capture Voice# takes command through microphonedef takecommand(): r = sr.Recognizer() with sr.Microphone() as source: print(\"listening.....\") r.pause_threshold = 1 audio = r.listen(source) try: print(\"Recognizing.....\") query = r.recognize_google(audio, language='en-in') print(f\"user said {query}\\n\") except Exception as e: print(\"say that again please.....\") return \"None\" return query", "e": 3849, "s": 3386, "text": null }, { "code": null, "e": 3890, "s": 3849, "text": "Step 4: Taking voice input from the user" }, { "code": null, "e": 3898, "s": 3890, "text": "Python3" }, { "code": "# Taking voice input from the userquery = takecommand()while (query == \"None\"): query = takecommand()", "e": 4003, "s": 3898, "text": null }, { "code": null, "e": 4095, "s": 4003, "text": "Step 5: Input destination language from the user, Mapping user input with the language code" }, { "code": null, "e": 4103, "s": 4095, "text": "Python3" }, { "code": "def destination_language(): print(\"Enter the language in which you want to convert \\ : Ex. Hindi , English , etc.\") print() # Input destination language in which the user # wants to translate to_lang = takecommand() while (to_lang == \"None\"): to_lang = takecommand() to_lang = to_lang.lower() return to_lang to_lang = destination_language() # Mapping it with the codewhile (to_lang not in dic): print(\"Language in which you are trying to convert\\ is currently not available ,please input some other language\") print() to_lang = destination_language() to_lang = dic[dic.index(to_lang)+1]", "e": 4742, "s": 4103, "text": null }, { "code": null, "e": 4770, "s": 4742, "text": "Step 6: Invoking Translator" }, { "code": null, "e": 4778, "s": 4770, "text": "Python3" }, { "code": "# invoking Translatortranslator = Translator()", "e": 4825, "s": 4778, "text": null }, { "code": null, "e": 4862, "s": 4825, "text": "Step 7: Translating from src to dest" }, { "code": null, "e": 4870, "s": 4862, "text": "Python3" }, { "code": "# Translating from src to desttext_to_translate = translator.translate(query, dest=to_lang)text = text_to_translate.text", "e": 4991, "s": 4870, "text": null }, { "code": null, "e": 5055, "s": 4991, "text": "Step 8: Saving Translated files and deleting them after playing" }, { "code": null, "e": 5063, "s": 5055, "text": "Python3" }, { "code": "# Using Google-Text-to-Speech ie, gTTS() method# to speak the translated text into the# destination language which is stored in to_lang.# Also, we have given 3rd argument as False because# by default it speaks very slowlyspeak = gTTS(text=text, lang=to_lang, slow=False) # Using save() method to save the translated# speech in capture_voice.mp3speak.save(\"captured_voice.mp3\") # Using OS module to run the translated voice.playsound('captured_voice.mp3')os.remove('captured_voice.mp3')print(text)", "e": 5562, "s": 5063, "text": null }, { "code": null, "e": 5596, "s": 5562, "text": "Below is the full implementation:" }, { "code": null, "e": 5604, "s": 5596, "text": "Python3" }, { "code": "# Importing necessary modules requiredfrom playsound import playsoundimport speech_recognition as srfrom googletrans import Translatorfrom gtts import gTTSimport osflag = 0 # A tuple containing all the language and# codes of the language will be detcteddic = ('afrikaans', 'af', 'albanian', 'sq', 'amharic', 'am', 'arabic', 'ar', 'armenian', 'hy', 'azerbaijani', 'az', 'basque', 'eu', 'belarusian', 'be', 'bengali', 'bn', 'bosnian', 'bs', 'bulgarian', 'bg', 'catalan', 'ca', 'cebuano', 'ceb', 'chichewa', 'ny', 'chinese (simplified)', 'zh-cn', 'chinese (traditional)', 'zh-tw', 'corsican', 'co', 'croatian', 'hr', 'czech', 'cs', 'danish', 'da', 'dutch', 'nl', 'english', 'en', 'esperanto', 'eo', 'estonian', 'et', 'filipino', 'tl', 'finnish', 'fi', 'french', 'fr', 'frisian', 'fy', 'galician', 'gl', 'georgian', 'ka', 'german', 'de', 'greek', 'el', 'gujarati', 'gu', 'haitian creole', 'ht', 'hausa', 'ha', 'hawaiian', 'haw', 'hebrew', 'he', 'hindi', 'hi', 'hmong', 'hmn', 'hungarian', 'hu', 'icelandic', 'is', 'igbo', 'ig', 'indonesian', 'id', 'irish', 'ga', 'italian', 'it', 'japanese', 'ja', 'javanese', 'jw', 'kannada', 'kn', 'kazakh', 'kk', 'khmer', 'km', 'korean', 'ko', 'kurdish (kurmanji)', 'ku', 'kyrgyz', 'ky', 'lao', 'lo', 'latin', 'la', 'latvian', 'lv', 'lithuanian', 'lt', 'luxembourgish', 'lb', 'macedonian', 'mk', 'malagasy', 'mg', 'malay', 'ms', 'malayalam', 'ml', 'maltese', 'mt', 'maori', 'mi', 'marathi', 'mr', 'mongolian', 'mn', 'myanmar (burmese)', 'my', 'nepali', 'ne', 'norwegian', 'no', 'odia', 'or', 'pashto', 'ps', 'persian', 'fa', 'polish', 'pl', 'portuguese', 'pt', 'punjabi', 'pa', 'romanian', 'ro', 'russian', 'ru', 'samoan', 'sm', 'scots gaelic', 'gd', 'serbian', 'sr', 'sesotho', 'st', 'shona', 'sn', 'sindhi', 'sd', 'sinhala', 'si', 'slovak', 'sk', 'slovenian', 'sl', 'somali', 'so', 'spanish', 'es', 'sundanese', 'su', 'swahili', 'sw', 'swedish', 'sv', 'tajik', 'tg', 'tamil', 'ta', 'telugu', 'te', 'thai', 'th', 'turkish', 'tr', 'ukrainian', 'uk', 'urdu', 'ur', 'uyghur', 'ug', 'uzbek', 'uz', 'vietnamese', 'vi', 'welsh', 'cy', 'xhosa', 'xh', 'yiddish', 'yi', 'yoruba', 'yo', 'zulu', 'zu') # Capture Voice# takes command through microphonedef takecommand(): r = sr.Recognizer() with sr.Microphone() as source: print(\"listening.....\") r.pause_threshold = 1 audio = r.listen(source) try: print(\"Recognizing.....\") query = r.recognize_google(audio, language='en-in') print(f\"The User said {query}\\n\") except Exception as e: print(\"say that again please.....\") return \"None\" return query # Input from user# Make input to lowercasequery = takecommand()while (query == \"None\"): query = takecommand() def destination_language(): print(\"Enter the language in which you\\ want to convert : Ex. Hindi , English , etc.\") print() # Input destination language in # which the user wants to translate to_lang = takecommand() while (to_lang == \"None\"): to_lang = takecommand() to_lang = to_lang.lower() return to_lang to_lang = destination_language() # Mapping it with the codewhile (to_lang not in dic): print(\"Language in which you are trying\\ to convert is currently not available ,\\ please input some other language\") print() to_lang = destination_language() to_lang = dic[dic.index(to_lang)+1] # invoking Translatortranslator = Translator() # Translating from src to desttext_to_translate = translator.translate(query, dest=to_lang) text = text_to_translate.text # Using Google-Text-to-Speech ie, gTTS() method# to speak the translated text into the# destination language which is stored in to_lang.# Also, we have given 3rd argument as False because# by default it speaks very slowlyspeak = gTTS(text=text, lang=to_lang, slow=False) # Using save() method to save the translated# speech in capture_voice.mp3speak.save(\"captured_voice.mp3\") # Using OS module to run the translated voice.playsound('captured_voice.mp3')os.remove('captured_voice.mp3') # Printing Outputprint(text)", "e": 9944, "s": 5604, "text": null }, { "code": null, "e": 9952, "s": 9944, "text": "Output:" }, { "code": null, "e": 10012, "s": 9952, "text": "Media error: Format(s) not supported or source(s) not found" }, { "code": null, "e": 10028, "s": 10012, "text": "Python-projects" }, { "code": null, "e": 10043, "s": 10028, "text": "python-utility" }, { "code": null, "e": 10050, "s": 10043, "text": "Python" } ]
numpy.empty() in Python
29 Nov, 2018 numpy.empty(shape, dtype = float, order = ‘C’) : Return a new array of given shape and type, with random values.Parameters : -> shape : Number of rows -> order : C_contiguous or F_contiguous -> dtype : [optional, float(by Default)] Data type of returned array. # Python Programming illustrating# numpy.empty method import numpy as geek b = geek.empty(2, dtype = int)print("Matrix b : \n", b) a = geek.empty([2, 2], dtype = int)print("\nMatrix a : \n", a) c = geek.empty([3, 3])print("\nMatrix c : \n", c) Output : Matrix b : [ 0 1079574528] Matrix a : [[0 0] [0 0]] Matrix a : [[ 0. 0. 0.] [ 0. 0. 0.] [ 0. 0. 0.]] Note : empty, unlike zeros, does not set the array values to zero, and may therefore be marginally faster.Also, these codes won’t run on online-ID. Please run them on your systems to explore the working This article is contributed by Mohit Gupta_OMG . If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. 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. Python numpy-arrayCreation Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Iterate over a list in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Nov, 2018" }, { "code": null, "e": 153, "s": 28, "text": "numpy.empty(shape, dtype = float, order = ‘C’) : Return a new array of given shape and type, with random values.Parameters :" }, { "code": null, "e": 292, "s": 153, "text": "-> shape : Number of rows\n-> order : C_contiguous or F_contiguous\n-> dtype : [optional, float(by Default)] Data type of returned array. \n" }, { "code": "# Python Programming illustrating# numpy.empty method import numpy as geek b = geek.empty(2, dtype = int)print(\"Matrix b : \\n\", b) a = geek.empty([2, 2], dtype = int)print(\"\\nMatrix a : \\n\", a) c = geek.empty([3, 3])print(\"\\nMatrix c : \\n\", c)", "e": 540, "s": 292, "text": null }, { "code": null, "e": 549, "s": 540, "text": "Output :" }, { "code": null, "e": 675, "s": 549, "text": "Matrix b : \n [ 0 1079574528]\n\nMatrix a : \n [[0 0]\n [0 0]]\n\nMatrix a : \n [[ 0. 0. 0.]\n [ 0. 0. 0.]\n [ 0. 0. 0.]]" }, { "code": null, "e": 878, "s": 675, "text": "Note : empty, unlike zeros, does not set the array values to zero, and may therefore be marginally faster.Also, these codes won’t run on online-ID. Please run them on your systems to explore the working" }, { "code": null, "e": 1182, "s": 878, "text": "This article is contributed by Mohit Gupta_OMG . If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 1307, "s": 1182, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 1334, "s": 1307, "text": "Python numpy-arrayCreation" }, { "code": null, "e": 1347, "s": 1334, "text": "Python-numpy" }, { "code": null, "e": 1354, "s": 1347, "text": "Python" }, { "code": null, "e": 1452, "s": 1354, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1470, "s": 1452, "text": "Python Dictionary" }, { "code": null, "e": 1512, "s": 1470, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1534, "s": 1512, "text": "Enumerate() in Python" }, { "code": null, "e": 1569, "s": 1534, "text": "Read a file line by line in Python" }, { "code": null, "e": 1595, "s": 1569, "text": "Python String | replace()" }, { "code": null, "e": 1627, "s": 1595, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1656, "s": 1627, "text": "*args and **kwargs in Python" }, { "code": null, "e": 1683, "s": 1656, "text": "Python Classes and Objects" }, { "code": null, "e": 1704, "s": 1683, "text": "Python OOPs Concepts" } ]
Python PIL | ImageOps.grayscale() method
27 Oct, 2021 PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The ImageOps module contains a number of ‘ready-made’ image processing operations. This module is somewhat experimental, and most operators only work on L and RGB images.ImageOps.grayscale() Convert the image to grayscale. The complete pixel turns to gray, no other color will be seen. Syntax: PIL.ImageOps.grayscale(image) Parameters: image – The image to convert into grayscale.Returns An image. Image Used: Python3 # Importing Image and ImageOps module from PIL packagefrom PIL import Image, ImageOps # creating a image1 objectim1 = Image.open(r"C:\Users\System-Pc\Desktop\a.JPG") # applying grayscale methodim2 = ImageOps.grayscale(im1) im2.show() Output: nidhi_biet sudiptadey1 sooda367 Python-pil Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Python OOPs Concepts
[ { "code": null, "e": 28, "s": 0, "text": "\n27 Oct, 2021" }, { "code": null, "e": 420, "s": 28, "text": "PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The ImageOps module contains a number of ‘ready-made’ image processing operations. This module is somewhat experimental, and most operators only work on L and RGB images.ImageOps.grayscale() Convert the image to grayscale. The complete pixel turns to gray, no other color will be seen. " }, { "code": null, "e": 534, "s": 420, "text": "Syntax: PIL.ImageOps.grayscale(image) Parameters: image – The image to convert into grayscale.Returns An image. " }, { "code": null, "e": 548, "s": 534, "text": "Image Used: " }, { "code": null, "e": 558, "s": 550, "text": "Python3" }, { "code": "# Importing Image and ImageOps module from PIL packagefrom PIL import Image, ImageOps # creating a image1 objectim1 = Image.open(r\"C:\\Users\\System-Pc\\Desktop\\a.JPG\") # applying grayscale methodim2 = ImageOps.grayscale(im1) im2.show()", "e": 796, "s": 558, "text": null }, { "code": null, "e": 805, "s": 796, "text": "Output: " }, { "code": null, "e": 818, "s": 807, "text": "nidhi_biet" }, { "code": null, "e": 830, "s": 818, "text": "sudiptadey1" }, { "code": null, "e": 839, "s": 830, "text": "sooda367" }, { "code": null, "e": 850, "s": 839, "text": "Python-pil" }, { "code": null, "e": 857, "s": 850, "text": "Python" }, { "code": null, "e": 955, "s": 857, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 973, "s": 955, "text": "Python Dictionary" }, { "code": null, "e": 1015, "s": 973, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1037, "s": 1015, "text": "Enumerate() in Python" }, { "code": null, "e": 1072, "s": 1037, "text": "Read a file line by line in Python" }, { "code": null, "e": 1098, "s": 1072, "text": "Python String | replace()" }, { "code": null, "e": 1130, "s": 1098, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1159, "s": 1130, "text": "*args and **kwargs in Python" }, { "code": null, "e": 1186, "s": 1159, "text": "Python Classes and Objects" }, { "code": null, "e": 1216, "s": 1186, "text": "Iterate over a list in Python" } ]
Composite Number
08 Mar, 2021 A composite number is a positive integer that is not prime. In other words, it has a positive divisor other than one or itself. First few composite numbers are 4, 6, 8, 9, 10, 12, 14, 15, 16, 18, 20, ......... Every integer greater than one is either a prime number or a composite number. The number one is a unit – it is neither prime nor composite. How to check if a given number is a composite number or not? Examples: Input : n = 21 Output: Yes The number is a composite number! Input : n = 11 Output : No The idea is simple, we can use any of the below methods used for prime checking. We just need to change return statements. Return true is changed to return false and vice versa. Primality Test | Set 1 (Introduction and School Method) Primality Test | Set 2 (Fermat Method) Primality Test | Set 3 (Miller–Rabin) In below code optimized school method is discussed. C++ Java Python 3 C# PHP Javascript // A optimized school method based C++ program to check// if a number is composite.#include <bits/stdc++.h>using namespace std; bool isComposite(int n){ // Corner cases if (n <= 1) return false; if (n <= 3) return false; // This is checked so that we can skip // middle five numbers in below loop if (n%2 == 0 || n%3 == 0) return true; for (int i=5; i*i<=n; i=i+6) if (n%i == 0 || n%(i+2) == 0) return true; return false;} // Driver Program to test above functionint main(){ isComposite(11)? cout << " true\n": cout << " false\n"; isComposite(15)? cout << " true\n": cout << " false\n"; return 0;} /// An optimized method based Java// program to check if a number// is Composite or not.import java.io.*; class Composite{ static boolean isComposite(int n) { // Corner cases if (n <= 1) System.out.println("False"); if (n <= 3) System.out.println("False"); // This is checked so that we can skip // middle five numbers in below loop if (n % 2 == 0 || n % 3 == 0) return true; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return true; return false; } // Driver Program to test above function public static void main(String args[]) { System.out.println(isComposite(11) ? "true" : "false"); System.out.println(isComposite(15) ? "true" : "false"); }} // This code is contributed by Anshika Goyal # A optimized school method based Python program to check# if a number is composite. def isComposite(n): # Corner cases if (n <= 1): return False if (n <= 3): return False # This is checked so that we can skip # middle five numbers in below loop if (n % 2 == 0 or n % 3 == 0): return True i = 5 while(i * i <= n): if (n % i == 0 or n % (i + 2) == 0): return True i = i + 6 return False # Driver Program to test above function print("true") if(isComposite(11)) else print("false")print("true") if(isComposite(15)) else print("false")# This code is contributed by Anant Agarwal. // A optimized school method based C# program// to check if a number is composite.using System; namespace Composite{public class GFG{ public static bool isComposite(int n) { // Corner cases if (n <= 1) return false; if (n <= 3) return false; // This is checked so that we can skip // middle five numbers in below loop if (n % 2 == 0 || n % 3 == 0) return true; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return true; return false; } // Driver Code public static void Main() { if(isComposite(11)) Console.WriteLine("true"); else Console.WriteLine("false"); if(isComposite(15)) Console.WriteLine("true"); else Console.WriteLine("false"); } }} // This code is contributed by Sam007 <?php// A optimized school// method based PHP// program to check// if a number is composite. function isComposite($n){ // Corner cases if ($n <= 1) return false; if ($n <= 3) return false; // This is checked so // that we can skip // middle five numbers // in below loop if ($n%2 == 0 || $n % 3 == 0) return true; for ($i = 5; $i * $i <= $n; $i = $i + 6) if ($n % $i == 0 || $n % ($i + 2) == 0) return true; return false;} // Driver Code if(isComposite(11)) echo "true"; else echo "false"; echo"\n"; if(isComposite(15)) echo "true"; else echo "false"; echo"\n"; // This code is contributed by Ajit.?> <script> // A optimized school method based Javascript program to check// if a number is composite. function isComposite(n){ // Corner cases if (n <= 1) return false; if (n <= 3) return false; // This is checked so that we can skip // middle five numbers in below loop if (n%2 == 0 || n%3 == 0) return true; for (let i=5; i*i<=n; i=i+6) if (n%i == 0 || n%(i+2) == 0) return true; return false;} // Driver Program to test above function isComposite(11)? document.write(" true" + "<br>"): document.write(" false" + "<br>"); isComposite(15)? document.write(" true" + "<br>"): document.write(" false" + "<br>"); // This code is contributed by Mayank Tyagi </script> Output: false true Program on Composite Numbers Find a range of composite numbers of given length Generate a list of n consecutive composite numbers (An interesting method) Sum and product of k smallest and k largest composite numbers in the array Product of all the Composite Numbers in an array Count and Sum of composite elements in an array Split n into maximum composite numbers Reference : https://en.wikipedia.org/wiki/Composite_numberThis article is contributed by Ajay Puri. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. 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. jit_t Akanksha_Rai mayanktyagi1709 Prime Number series Mathematical School Programming Mathematical Prime Number series Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Operators in C / C++ Sieve of Eratosthenes Prime Numbers Program to find GCD or HCF of two numbers Python Dictionary Reverse a string in Java Arrays in C/C++ Introduction To PYTHON Interfaces in Java
[ { "code": null, "e": 52, "s": 24, "text": "\n08 Mar, 2021" }, { "code": null, "e": 264, "s": 52, "text": "A composite number is a positive integer that is not prime. In other words, it has a positive divisor other than one or itself. First few composite numbers are 4, 6, 8, 9, 10, 12, 14, 15, 16, 18, 20, ......... " }, { "code": null, "e": 343, "s": 264, "text": "Every integer greater than one is either a prime number or a composite number." }, { "code": null, "e": 405, "s": 343, "text": "The number one is a unit – it is neither prime nor composite." }, { "code": null, "e": 478, "s": 405, "text": "How to check if a given number is a composite number or not? Examples: " }, { "code": null, "e": 567, "s": 478, "text": "Input : n = 21\nOutput: Yes\nThe number is a composite number!\n\nInput : n = 11\nOutput : No" }, { "code": null, "e": 749, "s": 569, "text": "The idea is simple, we can use any of the below methods used for prime checking. We just need to change return statements. Return true is changed to return false and vice versa. " }, { "code": null, "e": 805, "s": 749, "text": "Primality Test | Set 1 (Introduction and School Method)" }, { "code": null, "e": 844, "s": 805, "text": "Primality Test | Set 2 (Fermat Method)" }, { "code": null, "e": 882, "s": 844, "text": "Primality Test | Set 3 (Miller–Rabin)" }, { "code": null, "e": 936, "s": 882, "text": "In below code optimized school method is discussed. " }, { "code": null, "e": 940, "s": 936, "text": "C++" }, { "code": null, "e": 945, "s": 940, "text": "Java" }, { "code": null, "e": 954, "s": 945, "text": "Python 3" }, { "code": null, "e": 957, "s": 954, "text": "C#" }, { "code": null, "e": 961, "s": 957, "text": "PHP" }, { "code": null, "e": 972, "s": 961, "text": "Javascript" }, { "code": "// A optimized school method based C++ program to check// if a number is composite.#include <bits/stdc++.h>using namespace std; bool isComposite(int n){ // Corner cases if (n <= 1) return false; if (n <= 3) return false; // This is checked so that we can skip // middle five numbers in below loop if (n%2 == 0 || n%3 == 0) return true; for (int i=5; i*i<=n; i=i+6) if (n%i == 0 || n%(i+2) == 0) return true; return false;} // Driver Program to test above functionint main(){ isComposite(11)? cout << \" true\\n\": cout << \" false\\n\"; isComposite(15)? cout << \" true\\n\": cout << \" false\\n\"; return 0;}", "e": 1634, "s": 972, "text": null }, { "code": "/// An optimized method based Java// program to check if a number// is Composite or not.import java.io.*; class Composite{ static boolean isComposite(int n) { // Corner cases if (n <= 1) System.out.println(\"False\"); if (n <= 3) System.out.println(\"False\"); // This is checked so that we can skip // middle five numbers in below loop if (n % 2 == 0 || n % 3 == 0) return true; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return true; return false; } // Driver Program to test above function public static void main(String args[]) { System.out.println(isComposite(11) ? \"true\" : \"false\"); System.out.println(isComposite(15) ? \"true\" : \"false\"); }} // This code is contributed by Anshika Goyal", "e": 2564, "s": 1634, "text": null }, { "code": "# A optimized school method based Python program to check# if a number is composite. def isComposite(n): # Corner cases if (n <= 1): return False if (n <= 3): return False # This is checked so that we can skip # middle five numbers in below loop if (n % 2 == 0 or n % 3 == 0): return True i = 5 while(i * i <= n): if (n % i == 0 or n % (i + 2) == 0): return True i = i + 6 return False # Driver Program to test above function print(\"true\") if(isComposite(11)) else print(\"false\")print(\"true\") if(isComposite(15)) else print(\"false\")# This code is contributed by Anant Agarwal.", "e": 3234, "s": 2564, "text": null }, { "code": "// A optimized school method based C# program// to check if a number is composite.using System; namespace Composite{public class GFG{ public static bool isComposite(int n) { // Corner cases if (n <= 1) return false; if (n <= 3) return false; // This is checked so that we can skip // middle five numbers in below loop if (n % 2 == 0 || n % 3 == 0) return true; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return true; return false; } // Driver Code public static void Main() { if(isComposite(11)) Console.WriteLine(\"true\"); else Console.WriteLine(\"false\"); if(isComposite(15)) Console.WriteLine(\"true\"); else Console.WriteLine(\"false\"); } }} // This code is contributed by Sam007", "e": 4071, "s": 3234, "text": null }, { "code": "<?php// A optimized school// method based PHP// program to check// if a number is composite. function isComposite($n){ // Corner cases if ($n <= 1) return false; if ($n <= 3) return false; // This is checked so // that we can skip // middle five numbers // in below loop if ($n%2 == 0 || $n % 3 == 0) return true; for ($i = 5; $i * $i <= $n; $i = $i + 6) if ($n % $i == 0 || $n % ($i + 2) == 0) return true; return false;} // Driver Code if(isComposite(11)) echo \"true\"; else echo \"false\"; echo\"\\n\"; if(isComposite(15)) echo \"true\"; else echo \"false\"; echo\"\\n\"; // This code is contributed by Ajit.?>", "e": 4833, "s": 4071, "text": null }, { "code": "<script> // A optimized school method based Javascript program to check// if a number is composite. function isComposite(n){ // Corner cases if (n <= 1) return false; if (n <= 3) return false; // This is checked so that we can skip // middle five numbers in below loop if (n%2 == 0 || n%3 == 0) return true; for (let i=5; i*i<=n; i=i+6) if (n%i == 0 || n%(i+2) == 0) return true; return false;} // Driver Program to test above function isComposite(11)? document.write(\" true\" + \"<br>\"): document.write(\" false\" + \"<br>\"); isComposite(15)? document.write(\" true\" + \"<br>\"): document.write(\" false\" + \"<br>\"); // This code is contributed by Mayank Tyagi </script>", "e": 5551, "s": 4833, "text": null }, { "code": null, "e": 5560, "s": 5551, "text": "Output: " }, { "code": null, "e": 5571, "s": 5560, "text": "false\ntrue" }, { "code": null, "e": 5604, "s": 5571, "text": " Program on Composite Numbers " }, { "code": null, "e": 5654, "s": 5604, "text": "Find a range of composite numbers of given length" }, { "code": null, "e": 5729, "s": 5654, "text": "Generate a list of n consecutive composite numbers (An interesting method)" }, { "code": null, "e": 5804, "s": 5729, "text": "Sum and product of k smallest and k largest composite numbers in the array" }, { "code": null, "e": 5853, "s": 5804, "text": "Product of all the Composite Numbers in an array" }, { "code": null, "e": 5901, "s": 5853, "text": "Count and Sum of composite elements in an array" }, { "code": null, "e": 5940, "s": 5901, "text": "Split n into maximum composite numbers" }, { "code": null, "e": 6416, "s": 5940, "text": "Reference : https://en.wikipedia.org/wiki/Composite_numberThis article is contributed by Ajay Puri. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. 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": 6422, "s": 6416, "text": "jit_t" }, { "code": null, "e": 6435, "s": 6422, "text": "Akanksha_Rai" }, { "code": null, "e": 6451, "s": 6435, "text": "mayanktyagi1709" }, { "code": null, "e": 6464, "s": 6451, "text": "Prime Number" }, { "code": null, "e": 6471, "s": 6464, "text": "series" }, { "code": null, "e": 6484, "s": 6471, "text": "Mathematical" }, { "code": null, "e": 6503, "s": 6484, "text": "School Programming" }, { "code": null, "e": 6516, "s": 6503, "text": "Mathematical" }, { "code": null, "e": 6529, "s": 6516, "text": "Prime Number" }, { "code": null, "e": 6536, "s": 6529, "text": "series" }, { "code": null, "e": 6634, "s": 6536, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6658, "s": 6634, "text": "Merge two sorted arrays" }, { "code": null, "e": 6679, "s": 6658, "text": "Operators in C / C++" }, { "code": null, "e": 6701, "s": 6679, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 6715, "s": 6701, "text": "Prime Numbers" }, { "code": null, "e": 6757, "s": 6715, "text": "Program to find GCD or HCF of two numbers" }, { "code": null, "e": 6775, "s": 6757, "text": "Python Dictionary" }, { "code": null, "e": 6800, "s": 6775, "text": "Reverse a string in Java" }, { "code": null, "e": 6816, "s": 6800, "text": "Arrays in C/C++" }, { "code": null, "e": 6839, "s": 6816, "text": "Introduction To PYTHON" } ]
Java.lang.Enum Class in Java
24 Nov, 2021 Enum class is present in java.lang package. It is the common base class of all Java language enumeration types. For information about enums, refer enum in java Class Declaration public abstract class Enum<E extends Enum> extends Object implements Comparable, Serializable As we can see, that Enum is an abstract class, so we can not create object of class Enum. Methods in Enum Class Enum class provides 10 useful methods. Most of them are overridden from Object class. These methods are declared as final in Enum class so the programmer cannot modify any of the enum constants. final String name() : This method returns the name of this enum constant, which is exactly as declared in its enum declaration.Syntax : public final String name() Parameters : NA Returns : the name of this enum constant // Java program to demonstrate name() methodenum Color{ RED, GREEN, BLUE;} public class Test{ // Driver method public static void main(String[] args) { Color c1 = Color.RED; System.out.print("Name of enum constant: "); // name method System.out.println(c1.name()); }}Output:Name of enum constant: RED final int ordinal() : This method returns index of this enumeration constant.Syntax : public final int ordinal() Parameters : NA Returns : the ordinal of this enumeration constant // Java program to demonstrate ordinal() methodenum Color{ RED, GREEN, BLUE;} public class Test{ // Driver method public static void main(String[] args) { Color c1 = Color.GREEN; System.out.print("ordinal of enum constant "+c1.name()+" : "); // ordinal method System.out.println(c1.ordinal()); }}Output:ordinal of enum constant GREEN : 1 String toString() : This method returns a String object representing this enumeration constant. This method is same as name() method.Syntax : public String toString() Parameters : NA Returns : a string representation of this enumeration constant Overrides : toString in class Object // Java program to demonstrate toString() methodenum Color{ RED, GREEN, BLUE;} public class Test{ // Driver method public static void main(String[] args) { Color c1 = Color.GREEN; // getting string representation of enum // using toString() method String str = c1.toString(); System.out.println(str); }}Output:GREEN final boolean equals(Object obj) : This method returns true if the specified object is equal to this enum constant , otherwise return false.Syntax : public final boolean equals(Object obj) Parameters : obj - the object too be compared for equality with this enum. Returns : true if the specified object is equal to this enum constant. false otherwise Overrides : equals in class Object // Java program to demonstrate equals() methodenum Color{ RED, GREEN, BLUE;} public class Test{ // Driver method public static void main(String[] args) { Color c1 = Color.RED; Color c2 = Color.GREEN; Color c3 = Color.RED; // checking equality between enums // using equals() method boolean b1 = c1.equals(c2); boolean b2 = c1.equals(c3); boolean b3 = c2.equals(null); System.out.println("is c1 equal to c2 : " + b1); System.out.println("is c1 equal to c3 : " + b2); System.out.println("is c2 equal to null : " + b3); }}Output:is c1 equal to c2 : false is c1 equal to c3 : true is c2 equal to null : false final int hashCode() : This method returns a hash code for this enum constant. Actually this method contains just one statement, that is “return super.hashCode()” , which in turn calling Object class hashCode() method.Syntax : public final int hashCode() Parameters : NA Returns : a hash code for this enum constant. Overrides : hashCode in class Object // Java program to demonstrate hashCode() methodenum Color{ RED, GREEN, BLUE;} public class Test{ // Driver method public static void main(String[] args) { Color c1 = Color.RED; System.out.print("hashcode of enum constant "+ c1.name() +" : "); // hashcode method System.out.println(c1.hashCode()); Color c2 = Color.GREEN; System.out.print("hashcode of enum constant "+ c2.name() +" : "); // hashcode method System.out.println(c2.hashCode()); }}Output:hashcode of enum constant RED : 366712642 hashcode of enum constant GREEN : 1829164700 final int compareTo(E obj) : This method “compares” this enum with the specified object for order. Enum constants are only comparable to other enum constants of the same enum type.Syntax : public int compareTo(E obj) Parameters : obj - the object to be compared. Returns : a negative integer if this object is at less ordinal than the specified object zero if this object is at equal ordinal than the specified object a positive integer if this object is at greater ordinal than the specified object Throws : NullPointerException - if the argument is null // Java program to demonstrate compareTo() methodenum Color{ RED, GREEN, BLUE;} public class Test{ // Driver method public static void main(String[] args) { Color c1 = Color.RED; Color c2 = Color.GREEN; Color c3 = Color.RED; Color c4 = Color.BLUE; System.out.print("Comparing "+c1.name()+" with "+ c2.name() +" : "); // compareTo method System.out.println(c1.compareTo(c2)); System.out.print("Comparing "+c1.name()+" with "+ c3.name() +" : "); // compareTo method System.out.println(c1.compareTo(c3)); System.out.print("Comparing "+c4.name()+" with "+ c2.name() +" : "); // compareTo method System.out.println(c4.compareTo(c2)); // The following statement throw NullPointerException // as argument of compareTo method is null // System.out.println(c4.compareTo(null)); }}Output:Comparing RED with GREEN : -1 Comparing RED with RED : 0 Comparing BLUE with GREEN : 1 static <T extends Enum> T valueOf(Class enumType,String name) : This method returns the enum constant of the specified enum type with the specified name. The name must match exactly an identifier used to declare an enum constant in this type.Syntax : public static <T extends Enum> T valueOf(Class enumType,String name) TypeParameters : T - The enum type whose constant is to be returned Parameters : enumType - the Class object of the enum type from which to return a constant name - the name of the constant to return Returns : the enum constant of the specified enum type with the specified name Throws : IllegalArgumentException - if the specified enum type has no constant with the specified name or the specified class object does not represent an enum type NullPointerException - if enumType or name is null // Java program to demonstrate valueOf() methodenum Color{ RED, GREEN, BLUE;} public class Test{ // Driver method public static void main(String[] args) { // getting value of enum with specified String // using valueOf method Color c1 = Color.valueOf("RED"); Color c2 = Color.valueOf("GREEN"); // name method System.out.println(c1.name()); System.out.println(c2.name()); // The following statement throw IllegalArgumentException // as GrEEN is not an enum constant // Color c3 = Color.valueOf("GrEEN"); // The following statement throw NullPointerException // as argument of valueOf method is null // Color c4 = Color.valueOf(null); }}Output:RED GREEN final Class <E> getDeclaringClass() : This method returns the Class object corresponding to this enum constant’s enum type. Any Two enum constants e1 and e2 are of the same enum type if this method returns the same Class object for both.Syntax : public final Class <E> getDeclaringClass() Parameters : NA Returns : the Class object corresponding to this enum constant's enum type // Java program to demonstrate getDeclaringClass() methodenum Color{ RED, GREEN, BLUE;} enum Day{ MONDAY, TUESDAY ;} public class Test{ // Driver method public static void main(String[] args) { // getting value of enum with specified String // using valueOf method Color c1 = Color.valueOf("RED"); Color c2 = Color.valueOf("GREEN"); Day d1 = Day.valueOf("MONDAY"); Day d2 = Day.valueOf("TUESDAY"); System.out.print("Class corresponding to "+ c1.name() +" : "); // getDeclaringClass method System.out.println(c1.getDeclaringClass()); System.out.print("Class corresponding to "+ c2.name() +" : "); // getDeclaringClass method System.out.println(c2.getDeclaringClass()); System.out.print("Class corresponding to "+ d1.name() +" : "); // getDeclaringClass method System.out.println(d1.getDeclaringClass()); System.out.print("Class corresponding to "+ d2.name() +" : "); // getDeclaringClass method System.out.println(d2.getDeclaringClass()); }}Output:Class corresponding to RED : class Color Class corresponding to GREEN : class Color Class corresponding to MONDAY : class Day Class corresponding to TUESDAY : class Day final Object clone() : This method guarantees that enums are never cloned, which is necessary to preserve their “singleton” status. It is used internally by compiler to create Enum constants.Syntax : public final Object clone() throws CloneNotSupportedException Parameters : NA Returns : NA Overrides : clone in class Object Throws : CloneNotSupportedException-if the object's class does not support the Cloneable interface. // Java program to demonstrate clone() methodenum Color{ RED, GREEN, BLUE;} public class Test{ // Driver method public static void main(String[] args) throws CloneNotSupportedException { System.out.println("Enums are never cloned"); Test t = new Test() { // final clone method protected final Object clone() throws CloneNotSupportedException { return new CloneNotSupportedException(); } }; System.out.println(t.clone()); }}Output:Enums are never cloned java.lang.CloneNotSupportedException final void finalize() : This method guarantees that enum classes cannot have finalize methods.Syntax : protected final void finalize() Parameters : NA Returns : NA Overrides : finalize in class Object // Java program to demonstrate finalize() methodenum Color{ RED, GREEN, BLUE;} public class Test{ // Driver method public static void main(String[] args) throws Throwable { System.out.println("enum classes cannot have finalize methods"); Test t = new Test() { // final finalize method protected final void finalize() throws Throwable { // empty implementation }; }; }}Output:enum classes cannot have finalize methods final String name() : This method returns the name of this enum constant, which is exactly as declared in its enum declaration.Syntax : public final String name() Parameters : NA Returns : the name of this enum constant // Java program to demonstrate name() methodenum Color{ RED, GREEN, BLUE;} public class Test{ // Driver method public static void main(String[] args) { Color c1 = Color.RED; System.out.print("Name of enum constant: "); // name method System.out.println(c1.name()); }}Output:Name of enum constant: RED Syntax : public final String name() Parameters : NA Returns : the name of this enum constant // Java program to demonstrate name() methodenum Color{ RED, GREEN, BLUE;} public class Test{ // Driver method public static void main(String[] args) { Color c1 = Color.RED; System.out.print("Name of enum constant: "); // name method System.out.println(c1.name()); }} Output: Name of enum constant: RED final int ordinal() : This method returns index of this enumeration constant.Syntax : public final int ordinal() Parameters : NA Returns : the ordinal of this enumeration constant // Java program to demonstrate ordinal() methodenum Color{ RED, GREEN, BLUE;} public class Test{ // Driver method public static void main(String[] args) { Color c1 = Color.GREEN; System.out.print("ordinal of enum constant "+c1.name()+" : "); // ordinal method System.out.println(c1.ordinal()); }}Output:ordinal of enum constant GREEN : 1 Syntax : public final int ordinal() Parameters : NA Returns : the ordinal of this enumeration constant // Java program to demonstrate ordinal() methodenum Color{ RED, GREEN, BLUE;} public class Test{ // Driver method public static void main(String[] args) { Color c1 = Color.GREEN; System.out.print("ordinal of enum constant "+c1.name()+" : "); // ordinal method System.out.println(c1.ordinal()); }} Output: ordinal of enum constant GREEN : 1 String toString() : This method returns a String object representing this enumeration constant. This method is same as name() method.Syntax : public String toString() Parameters : NA Returns : a string representation of this enumeration constant Overrides : toString in class Object // Java program to demonstrate toString() methodenum Color{ RED, GREEN, BLUE;} public class Test{ // Driver method public static void main(String[] args) { Color c1 = Color.GREEN; // getting string representation of enum // using toString() method String str = c1.toString(); System.out.println(str); }}Output:GREEN Syntax : public String toString() Parameters : NA Returns : a string representation of this enumeration constant Overrides : toString in class Object // Java program to demonstrate toString() methodenum Color{ RED, GREEN, BLUE;} public class Test{ // Driver method public static void main(String[] args) { Color c1 = Color.GREEN; // getting string representation of enum // using toString() method String str = c1.toString(); System.out.println(str); }} Output: GREEN final boolean equals(Object obj) : This method returns true if the specified object is equal to this enum constant , otherwise return false.Syntax : public final boolean equals(Object obj) Parameters : obj - the object too be compared for equality with this enum. Returns : true if the specified object is equal to this enum constant. false otherwise Overrides : equals in class Object // Java program to demonstrate equals() methodenum Color{ RED, GREEN, BLUE;} public class Test{ // Driver method public static void main(String[] args) { Color c1 = Color.RED; Color c2 = Color.GREEN; Color c3 = Color.RED; // checking equality between enums // using equals() method boolean b1 = c1.equals(c2); boolean b2 = c1.equals(c3); boolean b3 = c2.equals(null); System.out.println("is c1 equal to c2 : " + b1); System.out.println("is c1 equal to c3 : " + b2); System.out.println("is c2 equal to null : " + b3); }}Output:is c1 equal to c2 : false is c1 equal to c3 : true is c2 equal to null : false Syntax : public final boolean equals(Object obj) Parameters : obj - the object too be compared for equality with this enum. Returns : true if the specified object is equal to this enum constant. false otherwise Overrides : equals in class Object // Java program to demonstrate equals() methodenum Color{ RED, GREEN, BLUE;} public class Test{ // Driver method public static void main(String[] args) { Color c1 = Color.RED; Color c2 = Color.GREEN; Color c3 = Color.RED; // checking equality between enums // using equals() method boolean b1 = c1.equals(c2); boolean b2 = c1.equals(c3); boolean b3 = c2.equals(null); System.out.println("is c1 equal to c2 : " + b1); System.out.println("is c1 equal to c3 : " + b2); System.out.println("is c2 equal to null : " + b3); }} Output: is c1 equal to c2 : false is c1 equal to c3 : true is c2 equal to null : false final int hashCode() : This method returns a hash code for this enum constant. Actually this method contains just one statement, that is “return super.hashCode()” , which in turn calling Object class hashCode() method.Syntax : public final int hashCode() Parameters : NA Returns : a hash code for this enum constant. Overrides : hashCode in class Object // Java program to demonstrate hashCode() methodenum Color{ RED, GREEN, BLUE;} public class Test{ // Driver method public static void main(String[] args) { Color c1 = Color.RED; System.out.print("hashcode of enum constant "+ c1.name() +" : "); // hashcode method System.out.println(c1.hashCode()); Color c2 = Color.GREEN; System.out.print("hashcode of enum constant "+ c2.name() +" : "); // hashcode method System.out.println(c2.hashCode()); }}Output:hashcode of enum constant RED : 366712642 hashcode of enum constant GREEN : 1829164700 Syntax : public final int hashCode() Parameters : NA Returns : a hash code for this enum constant. Overrides : hashCode in class Object // Java program to demonstrate hashCode() methodenum Color{ RED, GREEN, BLUE;} public class Test{ // Driver method public static void main(String[] args) { Color c1 = Color.RED; System.out.print("hashcode of enum constant "+ c1.name() +" : "); // hashcode method System.out.println(c1.hashCode()); Color c2 = Color.GREEN; System.out.print("hashcode of enum constant "+ c2.name() +" : "); // hashcode method System.out.println(c2.hashCode()); }} Output: hashcode of enum constant RED : 366712642 hashcode of enum constant GREEN : 1829164700 final int compareTo(E obj) : This method “compares” this enum with the specified object for order. Enum constants are only comparable to other enum constants of the same enum type.Syntax : public int compareTo(E obj) Parameters : obj - the object to be compared. Returns : a negative integer if this object is at less ordinal than the specified object zero if this object is at equal ordinal than the specified object a positive integer if this object is at greater ordinal than the specified object Throws : NullPointerException - if the argument is null // Java program to demonstrate compareTo() methodenum Color{ RED, GREEN, BLUE;} public class Test{ // Driver method public static void main(String[] args) { Color c1 = Color.RED; Color c2 = Color.GREEN; Color c3 = Color.RED; Color c4 = Color.BLUE; System.out.print("Comparing "+c1.name()+" with "+ c2.name() +" : "); // compareTo method System.out.println(c1.compareTo(c2)); System.out.print("Comparing "+c1.name()+" with "+ c3.name() +" : "); // compareTo method System.out.println(c1.compareTo(c3)); System.out.print("Comparing "+c4.name()+" with "+ c2.name() +" : "); // compareTo method System.out.println(c4.compareTo(c2)); // The following statement throw NullPointerException // as argument of compareTo method is null // System.out.println(c4.compareTo(null)); }}Output:Comparing RED with GREEN : -1 Comparing RED with RED : 0 Comparing BLUE with GREEN : 1 Syntax : public int compareTo(E obj) Parameters : obj - the object to be compared. Returns : a negative integer if this object is at less ordinal than the specified object zero if this object is at equal ordinal than the specified object a positive integer if this object is at greater ordinal than the specified object Throws : NullPointerException - if the argument is null // Java program to demonstrate compareTo() methodenum Color{ RED, GREEN, BLUE;} public class Test{ // Driver method public static void main(String[] args) { Color c1 = Color.RED; Color c2 = Color.GREEN; Color c3 = Color.RED; Color c4 = Color.BLUE; System.out.print("Comparing "+c1.name()+" with "+ c2.name() +" : "); // compareTo method System.out.println(c1.compareTo(c2)); System.out.print("Comparing "+c1.name()+" with "+ c3.name() +" : "); // compareTo method System.out.println(c1.compareTo(c3)); System.out.print("Comparing "+c4.name()+" with "+ c2.name() +" : "); // compareTo method System.out.println(c4.compareTo(c2)); // The following statement throw NullPointerException // as argument of compareTo method is null // System.out.println(c4.compareTo(null)); }} Output: Comparing RED with GREEN : -1 Comparing RED with RED : 0 Comparing BLUE with GREEN : 1 static <T extends Enum> T valueOf(Class enumType,String name) : This method returns the enum constant of the specified enum type with the specified name. The name must match exactly an identifier used to declare an enum constant in this type.Syntax : public static <T extends Enum> T valueOf(Class enumType,String name) TypeParameters : T - The enum type whose constant is to be returned Parameters : enumType - the Class object of the enum type from which to return a constant name - the name of the constant to return Returns : the enum constant of the specified enum type with the specified name Throws : IllegalArgumentException - if the specified enum type has no constant with the specified name or the specified class object does not represent an enum type NullPointerException - if enumType or name is null // Java program to demonstrate valueOf() methodenum Color{ RED, GREEN, BLUE;} public class Test{ // Driver method public static void main(String[] args) { // getting value of enum with specified String // using valueOf method Color c1 = Color.valueOf("RED"); Color c2 = Color.valueOf("GREEN"); // name method System.out.println(c1.name()); System.out.println(c2.name()); // The following statement throw IllegalArgumentException // as GrEEN is not an enum constant // Color c3 = Color.valueOf("GrEEN"); // The following statement throw NullPointerException // as argument of valueOf method is null // Color c4 = Color.valueOf(null); }}Output:RED GREEN Syntax : public static <T extends Enum> T valueOf(Class enumType,String name) TypeParameters : T - The enum type whose constant is to be returned Parameters : enumType - the Class object of the enum type from which to return a constant name - the name of the constant to return Returns : the enum constant of the specified enum type with the specified name Throws : IllegalArgumentException - if the specified enum type has no constant with the specified name or the specified class object does not represent an enum type NullPointerException - if enumType or name is null // Java program to demonstrate valueOf() methodenum Color{ RED, GREEN, BLUE;} public class Test{ // Driver method public static void main(String[] args) { // getting value of enum with specified String // using valueOf method Color c1 = Color.valueOf("RED"); Color c2 = Color.valueOf("GREEN"); // name method System.out.println(c1.name()); System.out.println(c2.name()); // The following statement throw IllegalArgumentException // as GrEEN is not an enum constant // Color c3 = Color.valueOf("GrEEN"); // The following statement throw NullPointerException // as argument of valueOf method is null // Color c4 = Color.valueOf(null); }} Output: RED GREEN final Class <E> getDeclaringClass() : This method returns the Class object corresponding to this enum constant’s enum type. Any Two enum constants e1 and e2 are of the same enum type if this method returns the same Class object for both.Syntax : public final Class <E> getDeclaringClass() Parameters : NA Returns : the Class object corresponding to this enum constant's enum type // Java program to demonstrate getDeclaringClass() methodenum Color{ RED, GREEN, BLUE;} enum Day{ MONDAY, TUESDAY ;} public class Test{ // Driver method public static void main(String[] args) { // getting value of enum with specified String // using valueOf method Color c1 = Color.valueOf("RED"); Color c2 = Color.valueOf("GREEN"); Day d1 = Day.valueOf("MONDAY"); Day d2 = Day.valueOf("TUESDAY"); System.out.print("Class corresponding to "+ c1.name() +" : "); // getDeclaringClass method System.out.println(c1.getDeclaringClass()); System.out.print("Class corresponding to "+ c2.name() +" : "); // getDeclaringClass method System.out.println(c2.getDeclaringClass()); System.out.print("Class corresponding to "+ d1.name() +" : "); // getDeclaringClass method System.out.println(d1.getDeclaringClass()); System.out.print("Class corresponding to "+ d2.name() +" : "); // getDeclaringClass method System.out.println(d2.getDeclaringClass()); }}Output:Class corresponding to RED : class Color Class corresponding to GREEN : class Color Class corresponding to MONDAY : class Day Class corresponding to TUESDAY : class Day Syntax : public final Class <E> getDeclaringClass() Parameters : NA Returns : the Class object corresponding to this enum constant's enum type // Java program to demonstrate getDeclaringClass() methodenum Color{ RED, GREEN, BLUE;} enum Day{ MONDAY, TUESDAY ;} public class Test{ // Driver method public static void main(String[] args) { // getting value of enum with specified String // using valueOf method Color c1 = Color.valueOf("RED"); Color c2 = Color.valueOf("GREEN"); Day d1 = Day.valueOf("MONDAY"); Day d2 = Day.valueOf("TUESDAY"); System.out.print("Class corresponding to "+ c1.name() +" : "); // getDeclaringClass method System.out.println(c1.getDeclaringClass()); System.out.print("Class corresponding to "+ c2.name() +" : "); // getDeclaringClass method System.out.println(c2.getDeclaringClass()); System.out.print("Class corresponding to "+ d1.name() +" : "); // getDeclaringClass method System.out.println(d1.getDeclaringClass()); System.out.print("Class corresponding to "+ d2.name() +" : "); // getDeclaringClass method System.out.println(d2.getDeclaringClass()); }} Output: Class corresponding to RED : class Color Class corresponding to GREEN : class Color Class corresponding to MONDAY : class Day Class corresponding to TUESDAY : class Day final Object clone() : This method guarantees that enums are never cloned, which is necessary to preserve their “singleton” status. It is used internally by compiler to create Enum constants.Syntax : public final Object clone() throws CloneNotSupportedException Parameters : NA Returns : NA Overrides : clone in class Object Throws : CloneNotSupportedException-if the object's class does not support the Cloneable interface. // Java program to demonstrate clone() methodenum Color{ RED, GREEN, BLUE;} public class Test{ // Driver method public static void main(String[] args) throws CloneNotSupportedException { System.out.println("Enums are never cloned"); Test t = new Test() { // final clone method protected final Object clone() throws CloneNotSupportedException { return new CloneNotSupportedException(); } }; System.out.println(t.clone()); }}Output:Enums are never cloned java.lang.CloneNotSupportedException Syntax : public final Object clone() throws CloneNotSupportedException Parameters : NA Returns : NA Overrides : clone in class Object Throws : CloneNotSupportedException-if the object's class does not support the Cloneable interface. // Java program to demonstrate clone() methodenum Color{ RED, GREEN, BLUE;} public class Test{ // Driver method public static void main(String[] args) throws CloneNotSupportedException { System.out.println("Enums are never cloned"); Test t = new Test() { // final clone method protected final Object clone() throws CloneNotSupportedException { return new CloneNotSupportedException(); } }; System.out.println(t.clone()); }} Output: Enums are never cloned java.lang.CloneNotSupportedException final void finalize() : This method guarantees that enum classes cannot have finalize methods.Syntax : protected final void finalize() Parameters : NA Returns : NA Overrides : finalize in class Object // Java program to demonstrate finalize() methodenum Color{ RED, GREEN, BLUE;} public class Test{ // Driver method public static void main(String[] args) throws Throwable { System.out.println("enum classes cannot have finalize methods"); Test t = new Test() { // final finalize method protected final void finalize() throws Throwable { // empty implementation }; }; }}Output:enum classes cannot have finalize methods Syntax : protected final void finalize() Parameters : NA Returns : NA Overrides : finalize in class Object // Java program to demonstrate finalize() methodenum Color{ RED, GREEN, BLUE;} public class Test{ // Driver method public static void main(String[] args) throws Throwable { System.out.println("enum classes cannot have finalize methods"); Test t = new Test() { // final finalize method protected final void finalize() throws Throwable { // empty implementation }; }; }} Output: enum classes cannot have finalize methods This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. 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. chhabradhanvi Java-lang package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n24 Nov, 2021" }, { "code": null, "e": 213, "s": 53, "text": "Enum class is present in java.lang package. It is the common base class of all Java language enumeration types. For information about enums, refer enum in java" }, { "code": null, "e": 231, "s": 213, "text": "Class Declaration" }, { "code": null, "e": 326, "s": 231, "text": "public abstract class Enum<E extends Enum>\nextends Object\nimplements Comparable, Serializable\n" }, { "code": null, "e": 416, "s": 326, "text": "As we can see, that Enum is an abstract class, so we can not create object of class Enum." }, { "code": null, "e": 438, "s": 416, "text": "Methods in Enum Class" }, { "code": null, "e": 633, "s": 438, "text": "Enum class provides 10 useful methods. Most of them are overridden from Object class. These methods are declared as final in Enum class so the programmer cannot modify any of the enum constants." }, { "code": null, "e": 11314, "s": 633, "text": "final String name() : This method returns the name of this enum constant, which is exactly as declared in its enum declaration.Syntax : \npublic final String name()\nParameters : \nNA\nReturns :\nthe name of this enum constant\n// Java program to demonstrate name() methodenum Color{ RED, GREEN, BLUE;} public class Test{ // Driver method public static void main(String[] args) { Color c1 = Color.RED; System.out.print(\"Name of enum constant: \"); // name method System.out.println(c1.name()); }}Output:Name of enum constant: RED\nfinal int ordinal() : This method returns index of this enumeration constant.Syntax : \npublic final int ordinal()\nParameters : \nNA\nReturns :\nthe ordinal of this enumeration constant\n// Java program to demonstrate ordinal() methodenum Color{ RED, GREEN, BLUE;} public class Test{ // Driver method public static void main(String[] args) { Color c1 = Color.GREEN; System.out.print(\"ordinal of enum constant \"+c1.name()+\" : \"); // ordinal method System.out.println(c1.ordinal()); }}Output:ordinal of enum constant GREEN : 1\nString toString() : This method returns a String object representing this enumeration constant. This method is same as name() method.Syntax : \npublic String toString()\nParameters : \nNA\nReturns :\na string representation of this enumeration constant\nOverrides :\ntoString in class Object\n// Java program to demonstrate toString() methodenum Color{ RED, GREEN, BLUE;} public class Test{ // Driver method public static void main(String[] args) { Color c1 = Color.GREEN; // getting string representation of enum // using toString() method String str = c1.toString(); System.out.println(str); }}Output:GREEN\nfinal boolean equals(Object obj) : This method returns true if the specified object is equal to this enum constant , otherwise return false.Syntax : \npublic final boolean equals(Object obj)\nParameters : \nobj - the object too be compared for equality with this enum.\nReturns :\ntrue if the specified object is equal to this enum constant. \nfalse otherwise\nOverrides :\nequals in class Object\n// Java program to demonstrate equals() methodenum Color{ RED, GREEN, BLUE;} public class Test{ // Driver method public static void main(String[] args) { Color c1 = Color.RED; Color c2 = Color.GREEN; Color c3 = Color.RED; // checking equality between enums // using equals() method boolean b1 = c1.equals(c2); boolean b2 = c1.equals(c3); boolean b3 = c2.equals(null); System.out.println(\"is c1 equal to c2 : \" + b1); System.out.println(\"is c1 equal to c3 : \" + b2); System.out.println(\"is c2 equal to null : \" + b3); }}Output:is c1 equal to c2 : false\nis c1 equal to c3 : true\nis c2 equal to null : false\nfinal int hashCode() : This method returns a hash code for this enum constant. Actually this method contains just one statement, that is “return super.hashCode()” , which in turn calling Object class hashCode() method.Syntax : \npublic final int hashCode()\nParameters : \nNA\nReturns :\na hash code for this enum constant.\nOverrides :\nhashCode in class Object\n// Java program to demonstrate hashCode() methodenum Color{ RED, GREEN, BLUE;} public class Test{ // Driver method public static void main(String[] args) { Color c1 = Color.RED; System.out.print(\"hashcode of enum constant \"+ c1.name() +\" : \"); // hashcode method System.out.println(c1.hashCode()); Color c2 = Color.GREEN; System.out.print(\"hashcode of enum constant \"+ c2.name() +\" : \"); // hashcode method System.out.println(c2.hashCode()); }}Output:hashcode of enum constant RED : 366712642\nhashcode of enum constant GREEN : 1829164700\nfinal int compareTo(E obj) : This method “compares” this enum with the specified object for order. Enum constants are only comparable to other enum constants of the same enum type.Syntax : \npublic int compareTo(E obj)\nParameters : \nobj - the object to be compared.\nReturns :\na negative integer if this object is at less ordinal than the specified object\nzero if this object is at equal ordinal than the specified object\na positive integer if this object is at greater ordinal than the specified object\nThrows :\nNullPointerException - if the argument is null\n// Java program to demonstrate compareTo() methodenum Color{ RED, GREEN, BLUE;} public class Test{ // Driver method public static void main(String[] args) { Color c1 = Color.RED; Color c2 = Color.GREEN; Color c3 = Color.RED; Color c4 = Color.BLUE; System.out.print(\"Comparing \"+c1.name()+\" with \"+ c2.name() +\" : \"); // compareTo method System.out.println(c1.compareTo(c2)); System.out.print(\"Comparing \"+c1.name()+\" with \"+ c3.name() +\" : \"); // compareTo method System.out.println(c1.compareTo(c3)); System.out.print(\"Comparing \"+c4.name()+\" with \"+ c2.name() +\" : \"); // compareTo method System.out.println(c4.compareTo(c2)); // The following statement throw NullPointerException // as argument of compareTo method is null // System.out.println(c4.compareTo(null)); }}Output:Comparing RED with GREEN : -1\nComparing RED with RED : 0\nComparing BLUE with GREEN : 1\nstatic <T extends Enum> T valueOf(Class enumType,String name) : This method returns the enum constant of the specified enum type with the specified name. The name must match exactly an identifier used to declare an enum constant in this type.Syntax : \npublic static <T extends Enum> T valueOf(Class enumType,String name)\nTypeParameters : \nT - The enum type whose constant is to be returned\nParameters : \nenumType - the Class object of the enum type from which to return a constant\nname - the name of the constant to return\nReturns :\nthe enum constant of the specified enum type with the specified name\nThrows :\nIllegalArgumentException - if the specified enum type has no \nconstant with the specified name or the specified class object\ndoes not represent an enum type\nNullPointerException - if enumType or name is null\n// Java program to demonstrate valueOf() methodenum Color{ RED, GREEN, BLUE;} public class Test{ // Driver method public static void main(String[] args) { // getting value of enum with specified String // using valueOf method Color c1 = Color.valueOf(\"RED\"); Color c2 = Color.valueOf(\"GREEN\"); // name method System.out.println(c1.name()); System.out.println(c2.name()); // The following statement throw IllegalArgumentException // as GrEEN is not an enum constant // Color c3 = Color.valueOf(\"GrEEN\"); // The following statement throw NullPointerException // as argument of valueOf method is null // Color c4 = Color.valueOf(null); }}Output:RED\nGREEN\nfinal Class <E> getDeclaringClass() : This method returns the Class object corresponding to this enum constant’s enum type. Any Two enum constants e1 and e2 are of the same enum type if this method returns the same Class object for both.Syntax : \npublic final Class <E> getDeclaringClass()\nParameters : \nNA\nReturns :\nthe Class object corresponding to this enum constant's enum type\n// Java program to demonstrate getDeclaringClass() methodenum Color{ RED, GREEN, BLUE;} enum Day{ MONDAY, TUESDAY ;} public class Test{ // Driver method public static void main(String[] args) { // getting value of enum with specified String // using valueOf method Color c1 = Color.valueOf(\"RED\"); Color c2 = Color.valueOf(\"GREEN\"); Day d1 = Day.valueOf(\"MONDAY\"); Day d2 = Day.valueOf(\"TUESDAY\"); System.out.print(\"Class corresponding to \"+ c1.name() +\" : \"); // getDeclaringClass method System.out.println(c1.getDeclaringClass()); System.out.print(\"Class corresponding to \"+ c2.name() +\" : \"); // getDeclaringClass method System.out.println(c2.getDeclaringClass()); System.out.print(\"Class corresponding to \"+ d1.name() +\" : \"); // getDeclaringClass method System.out.println(d1.getDeclaringClass()); System.out.print(\"Class corresponding to \"+ d2.name() +\" : \"); // getDeclaringClass method System.out.println(d2.getDeclaringClass()); }}Output:Class corresponding to RED : class Color\nClass corresponding to GREEN : class Color\nClass corresponding to MONDAY : class Day\nClass corresponding to TUESDAY : class Day\nfinal Object clone() : This method guarantees that enums are never cloned, which is necessary to preserve their “singleton” status. It is used internally by compiler to create Enum constants.Syntax : \npublic final Object clone() throws CloneNotSupportedException\nParameters : \nNA\nReturns :\nNA\nOverrides :\nclone in class Object\nThrows :\nCloneNotSupportedException-if the object's class does not support the Cloneable interface.\n// Java program to demonstrate clone() methodenum Color{ RED, GREEN, BLUE;} public class Test{ // Driver method public static void main(String[] args) throws CloneNotSupportedException { System.out.println(\"Enums are never cloned\"); Test t = new Test() { // final clone method protected final Object clone() throws CloneNotSupportedException { return new CloneNotSupportedException(); } }; System.out.println(t.clone()); }}Output:Enums are never cloned\njava.lang.CloneNotSupportedException\nfinal void finalize() : This method guarantees that enum classes cannot have finalize methods.Syntax : \nprotected final void finalize()\nParameters : \nNA\nReturns :\nNA\nOverrides :\nfinalize in class Object\n// Java program to demonstrate finalize() methodenum Color{ RED, GREEN, BLUE;} public class Test{ // Driver method public static void main(String[] args) throws Throwable { System.out.println(\"enum classes cannot have finalize methods\"); Test t = new Test() { // final finalize method protected final void finalize() throws Throwable { // empty implementation }; }; }}Output:enum classes cannot have finalize methods\n" }, { "code": null, "e": 11885, "s": 11314, "text": "final String name() : This method returns the name of this enum constant, which is exactly as declared in its enum declaration.Syntax : \npublic final String name()\nParameters : \nNA\nReturns :\nthe name of this enum constant\n// Java program to demonstrate name() methodenum Color{ RED, GREEN, BLUE;} public class Test{ // Driver method public static void main(String[] args) { Color c1 = Color.RED; System.out.print(\"Name of enum constant: \"); // name method System.out.println(c1.name()); }}Output:Name of enum constant: RED\n" }, { "code": null, "e": 11981, "s": 11885, "text": "Syntax : \npublic final String name()\nParameters : \nNA\nReturns :\nthe name of this enum constant\n" }, { "code": "// Java program to demonstrate name() methodenum Color{ RED, GREEN, BLUE;} public class Test{ // Driver method public static void main(String[] args) { Color c1 = Color.RED; System.out.print(\"Name of enum constant: \"); // name method System.out.println(c1.name()); }}", "e": 12296, "s": 11981, "text": null }, { "code": null, "e": 12304, "s": 12296, "text": "Output:" }, { "code": null, "e": 12332, "s": 12304, "text": "Name of enum constant: RED\n" }, { "code": null, "e": 12900, "s": 12332, "text": "final int ordinal() : This method returns index of this enumeration constant.Syntax : \npublic final int ordinal()\nParameters : \nNA\nReturns :\nthe ordinal of this enumeration constant\n// Java program to demonstrate ordinal() methodenum Color{ RED, GREEN, BLUE;} public class Test{ // Driver method public static void main(String[] args) { Color c1 = Color.GREEN; System.out.print(\"ordinal of enum constant \"+c1.name()+\" : \"); // ordinal method System.out.println(c1.ordinal()); }}Output:ordinal of enum constant GREEN : 1\n" }, { "code": null, "e": 13006, "s": 12900, "text": "Syntax : \npublic final int ordinal()\nParameters : \nNA\nReturns :\nthe ordinal of this enumeration constant\n" }, { "code": "// Java program to demonstrate ordinal() methodenum Color{ RED, GREEN, BLUE;} public class Test{ // Driver method public static void main(String[] args) { Color c1 = Color.GREEN; System.out.print(\"ordinal of enum constant \"+c1.name()+\" : \"); // ordinal method System.out.println(c1.ordinal()); }}", "e": 13350, "s": 13006, "text": null }, { "code": null, "e": 13358, "s": 13350, "text": "Output:" }, { "code": null, "e": 13394, "s": 13358, "text": "ordinal of enum constant GREEN : 1\n" }, { "code": null, "e": 14068, "s": 13394, "text": "String toString() : This method returns a String object representing this enumeration constant. This method is same as name() method.Syntax : \npublic String toString()\nParameters : \nNA\nReturns :\na string representation of this enumeration constant\nOverrides :\ntoString in class Object\n// Java program to demonstrate toString() methodenum Color{ RED, GREEN, BLUE;} public class Test{ // Driver method public static void main(String[] args) { Color c1 = Color.GREEN; // getting string representation of enum // using toString() method String str = c1.toString(); System.out.println(str); }}Output:GREEN\n" }, { "code": null, "e": 14221, "s": 14068, "text": "Syntax : \npublic String toString()\nParameters : \nNA\nReturns :\na string representation of this enumeration constant\nOverrides :\ntoString in class Object\n" }, { "code": "// Java program to demonstrate toString() methodenum Color{ RED, GREEN, BLUE;} public class Test{ // Driver method public static void main(String[] args) { Color c1 = Color.GREEN; // getting string representation of enum // using toString() method String str = c1.toString(); System.out.println(str); }}", "e": 14597, "s": 14221, "text": null }, { "code": null, "e": 14605, "s": 14597, "text": "Output:" }, { "code": null, "e": 14612, "s": 14605, "text": "GREEN\n" }, { "code": null, "e": 15731, "s": 14612, "text": "final boolean equals(Object obj) : This method returns true if the specified object is equal to this enum constant , otherwise return false.Syntax : \npublic final boolean equals(Object obj)\nParameters : \nobj - the object too be compared for equality with this enum.\nReturns :\ntrue if the specified object is equal to this enum constant. \nfalse otherwise\nOverrides :\nequals in class Object\n// Java program to demonstrate equals() methodenum Color{ RED, GREEN, BLUE;} public class Test{ // Driver method public static void main(String[] args) { Color c1 = Color.RED; Color c2 = Color.GREEN; Color c3 = Color.RED; // checking equality between enums // using equals() method boolean b1 = c1.equals(c2); boolean b2 = c1.equals(c3); boolean b3 = c2.equals(null); System.out.println(\"is c1 equal to c2 : \" + b1); System.out.println(\"is c1 equal to c3 : \" + b2); System.out.println(\"is c2 equal to null : \" + b3); }}Output:is c1 equal to c2 : false\nis c1 equal to c3 : true\nis c2 equal to null : false\n" }, { "code": null, "e": 15981, "s": 15731, "text": "Syntax : \npublic final boolean equals(Object obj)\nParameters : \nobj - the object too be compared for equality with this enum.\nReturns :\ntrue if the specified object is equal to this enum constant. \nfalse otherwise\nOverrides :\nequals in class Object\n" }, { "code": "// Java program to demonstrate equals() methodenum Color{ RED, GREEN, BLUE;} public class Test{ // Driver method public static void main(String[] args) { Color c1 = Color.RED; Color c2 = Color.GREEN; Color c3 = Color.RED; // checking equality between enums // using equals() method boolean b1 = c1.equals(c2); boolean b2 = c1.equals(c3); boolean b3 = c2.equals(null); System.out.println(\"is c1 equal to c2 : \" + b1); System.out.println(\"is c1 equal to c3 : \" + b2); System.out.println(\"is c2 equal to null : \" + b3); }}", "e": 16625, "s": 15981, "text": null }, { "code": null, "e": 16633, "s": 16625, "text": "Output:" }, { "code": null, "e": 16713, "s": 16633, "text": "is c1 equal to c2 : false\nis c1 equal to c3 : true\nis c2 equal to null : false\n" }, { "code": null, "e": 17695, "s": 16713, "text": "final int hashCode() : This method returns a hash code for this enum constant. Actually this method contains just one statement, that is “return super.hashCode()” , which in turn calling Object class hashCode() method.Syntax : \npublic final int hashCode()\nParameters : \nNA\nReturns :\na hash code for this enum constant.\nOverrides :\nhashCode in class Object\n// Java program to demonstrate hashCode() methodenum Color{ RED, GREEN, BLUE;} public class Test{ // Driver method public static void main(String[] args) { Color c1 = Color.RED; System.out.print(\"hashcode of enum constant \"+ c1.name() +\" : \"); // hashcode method System.out.println(c1.hashCode()); Color c2 = Color.GREEN; System.out.print(\"hashcode of enum constant \"+ c2.name() +\" : \"); // hashcode method System.out.println(c2.hashCode()); }}Output:hashcode of enum constant RED : 366712642\nhashcode of enum constant GREEN : 1829164700\n" }, { "code": null, "e": 17834, "s": 17695, "text": "Syntax : \npublic final int hashCode()\nParameters : \nNA\nReturns :\na hash code for this enum constant.\nOverrides :\nhashCode in class Object\n" }, { "code": "// Java program to demonstrate hashCode() methodenum Color{ RED, GREEN, BLUE;} public class Test{ // Driver method public static void main(String[] args) { Color c1 = Color.RED; System.out.print(\"hashcode of enum constant \"+ c1.name() +\" : \"); // hashcode method System.out.println(c1.hashCode()); Color c2 = Color.GREEN; System.out.print(\"hashcode of enum constant \"+ c2.name() +\" : \"); // hashcode method System.out.println(c2.hashCode()); }}", "e": 18366, "s": 17834, "text": null }, { "code": null, "e": 18374, "s": 18366, "text": "Output:" }, { "code": null, "e": 18462, "s": 18374, "text": "hashcode of enum constant RED : 366712642\nhashcode of enum constant GREEN : 1829164700\n" }, { "code": null, "e": 20094, "s": 18462, "text": "final int compareTo(E obj) : This method “compares” this enum with the specified object for order. Enum constants are only comparable to other enum constants of the same enum type.Syntax : \npublic int compareTo(E obj)\nParameters : \nobj - the object to be compared.\nReturns :\na negative integer if this object is at less ordinal than the specified object\nzero if this object is at equal ordinal than the specified object\na positive integer if this object is at greater ordinal than the specified object\nThrows :\nNullPointerException - if the argument is null\n// Java program to demonstrate compareTo() methodenum Color{ RED, GREEN, BLUE;} public class Test{ // Driver method public static void main(String[] args) { Color c1 = Color.RED; Color c2 = Color.GREEN; Color c3 = Color.RED; Color c4 = Color.BLUE; System.out.print(\"Comparing \"+c1.name()+\" with \"+ c2.name() +\" : \"); // compareTo method System.out.println(c1.compareTo(c2)); System.out.print(\"Comparing \"+c1.name()+\" with \"+ c3.name() +\" : \"); // compareTo method System.out.println(c1.compareTo(c3)); System.out.print(\"Comparing \"+c4.name()+\" with \"+ c2.name() +\" : \"); // compareTo method System.out.println(c4.compareTo(c2)); // The following statement throw NullPointerException // as argument of compareTo method is null // System.out.println(c4.compareTo(null)); }}Output:Comparing RED with GREEN : -1\nComparing RED with RED : 0\nComparing BLUE with GREEN : 1\n" }, { "code": null, "e": 20473, "s": 20094, "text": "Syntax : \npublic int compareTo(E obj)\nParameters : \nobj - the object to be compared.\nReturns :\na negative integer if this object is at less ordinal than the specified object\nzero if this object is at equal ordinal than the specified object\na positive integer if this object is at greater ordinal than the specified object\nThrows :\nNullPointerException - if the argument is null\n" }, { "code": "// Java program to demonstrate compareTo() methodenum Color{ RED, GREEN, BLUE;} public class Test{ // Driver method public static void main(String[] args) { Color c1 = Color.RED; Color c2 = Color.GREEN; Color c3 = Color.RED; Color c4 = Color.BLUE; System.out.print(\"Comparing \"+c1.name()+\" with \"+ c2.name() +\" : \"); // compareTo method System.out.println(c1.compareTo(c2)); System.out.print(\"Comparing \"+c1.name()+\" with \"+ c3.name() +\" : \"); // compareTo method System.out.println(c1.compareTo(c3)); System.out.print(\"Comparing \"+c4.name()+\" with \"+ c2.name() +\" : \"); // compareTo method System.out.println(c4.compareTo(c2)); // The following statement throw NullPointerException // as argument of compareTo method is null // System.out.println(c4.compareTo(null)); }}", "e": 21453, "s": 20473, "text": null }, { "code": null, "e": 21461, "s": 21453, "text": "Output:" }, { "code": null, "e": 21549, "s": 21461, "text": "Comparing RED with GREEN : -1\nComparing RED with RED : 0\nComparing BLUE with GREEN : 1\n" }, { "code": null, "e": 23160, "s": 21549, "text": "static <T extends Enum> T valueOf(Class enumType,String name) : This method returns the enum constant of the specified enum type with the specified name. The name must match exactly an identifier used to declare an enum constant in this type.Syntax : \npublic static <T extends Enum> T valueOf(Class enumType,String name)\nTypeParameters : \nT - The enum type whose constant is to be returned\nParameters : \nenumType - the Class object of the enum type from which to return a constant\nname - the name of the constant to return\nReturns :\nthe enum constant of the specified enum type with the specified name\nThrows :\nIllegalArgumentException - if the specified enum type has no \nconstant with the specified name or the specified class object\ndoes not represent an enum type\nNullPointerException - if enumType or name is null\n// Java program to demonstrate valueOf() methodenum Color{ RED, GREEN, BLUE;} public class Test{ // Driver method public static void main(String[] args) { // getting value of enum with specified String // using valueOf method Color c1 = Color.valueOf(\"RED\"); Color c2 = Color.valueOf(\"GREEN\"); // name method System.out.println(c1.name()); System.out.println(c2.name()); // The following statement throw IllegalArgumentException // as GrEEN is not an enum constant // Color c3 = Color.valueOf(\"GrEEN\"); // The following statement throw NullPointerException // as argument of valueOf method is null // Color c4 = Color.valueOf(null); }}Output:RED\nGREEN\n" }, { "code": null, "e": 23738, "s": 23160, "text": "Syntax : \npublic static <T extends Enum> T valueOf(Class enumType,String name)\nTypeParameters : \nT - The enum type whose constant is to be returned\nParameters : \nenumType - the Class object of the enum type from which to return a constant\nname - the name of the constant to return\nReturns :\nthe enum constant of the specified enum type with the specified name\nThrows :\nIllegalArgumentException - if the specified enum type has no \nconstant with the specified name or the specified class object\ndoes not represent an enum type\nNullPointerException - if enumType or name is null\n" }, { "code": "// Java program to demonstrate valueOf() methodenum Color{ RED, GREEN, BLUE;} public class Test{ // Driver method public static void main(String[] args) { // getting value of enum with specified String // using valueOf method Color c1 = Color.valueOf(\"RED\"); Color c2 = Color.valueOf(\"GREEN\"); // name method System.out.println(c1.name()); System.out.println(c2.name()); // The following statement throw IllegalArgumentException // as GrEEN is not an enum constant // Color c3 = Color.valueOf(\"GrEEN\"); // The following statement throw NullPointerException // as argument of valueOf method is null // Color c4 = Color.valueOf(null); }}", "e": 24513, "s": 23738, "text": null }, { "code": null, "e": 24521, "s": 24513, "text": "Output:" }, { "code": null, "e": 24532, "s": 24521, "text": "RED\nGREEN\n" }, { "code": null, "e": 26253, "s": 24532, "text": "final Class <E> getDeclaringClass() : This method returns the Class object corresponding to this enum constant’s enum type. Any Two enum constants e1 and e2 are of the same enum type if this method returns the same Class object for both.Syntax : \npublic final Class <E> getDeclaringClass()\nParameters : \nNA\nReturns :\nthe Class object corresponding to this enum constant's enum type\n// Java program to demonstrate getDeclaringClass() methodenum Color{ RED, GREEN, BLUE;} enum Day{ MONDAY, TUESDAY ;} public class Test{ // Driver method public static void main(String[] args) { // getting value of enum with specified String // using valueOf method Color c1 = Color.valueOf(\"RED\"); Color c2 = Color.valueOf(\"GREEN\"); Day d1 = Day.valueOf(\"MONDAY\"); Day d2 = Day.valueOf(\"TUESDAY\"); System.out.print(\"Class corresponding to \"+ c1.name() +\" : \"); // getDeclaringClass method System.out.println(c1.getDeclaringClass()); System.out.print(\"Class corresponding to \"+ c2.name() +\" : \"); // getDeclaringClass method System.out.println(c2.getDeclaringClass()); System.out.print(\"Class corresponding to \"+ d1.name() +\" : \"); // getDeclaringClass method System.out.println(d1.getDeclaringClass()); System.out.print(\"Class corresponding to \"+ d2.name() +\" : \"); // getDeclaringClass method System.out.println(d2.getDeclaringClass()); }}Output:Class corresponding to RED : class Color\nClass corresponding to GREEN : class Color\nClass corresponding to MONDAY : class Day\nClass corresponding to TUESDAY : class Day\n" }, { "code": null, "e": 26399, "s": 26253, "text": "Syntax : \npublic final Class <E> getDeclaringClass()\nParameters : \nNA\nReturns :\nthe Class object corresponding to this enum constant's enum type\n" }, { "code": "// Java program to demonstrate getDeclaringClass() methodenum Color{ RED, GREEN, BLUE;} enum Day{ MONDAY, TUESDAY ;} public class Test{ // Driver method public static void main(String[] args) { // getting value of enum with specified String // using valueOf method Color c1 = Color.valueOf(\"RED\"); Color c2 = Color.valueOf(\"GREEN\"); Day d1 = Day.valueOf(\"MONDAY\"); Day d2 = Day.valueOf(\"TUESDAY\"); System.out.print(\"Class corresponding to \"+ c1.name() +\" : \"); // getDeclaringClass method System.out.println(c1.getDeclaringClass()); System.out.print(\"Class corresponding to \"+ c2.name() +\" : \"); // getDeclaringClass method System.out.println(c2.getDeclaringClass()); System.out.print(\"Class corresponding to \"+ d1.name() +\" : \"); // getDeclaringClass method System.out.println(d1.getDeclaringClass()); System.out.print(\"Class corresponding to \"+ d2.name() +\" : \"); // getDeclaringClass method System.out.println(d2.getDeclaringClass()); }}", "e": 27562, "s": 26399, "text": null }, { "code": null, "e": 27570, "s": 27562, "text": "Output:" }, { "code": null, "e": 27740, "s": 27570, "text": "Class corresponding to RED : class Color\nClass corresponding to GREEN : class Color\nClass corresponding to MONDAY : class Day\nClass corresponding to TUESDAY : class Day\n" }, { "code": null, "e": 28813, "s": 27740, "text": "final Object clone() : This method guarantees that enums are never cloned, which is necessary to preserve their “singleton” status. It is used internally by compiler to create Enum constants.Syntax : \npublic final Object clone() throws CloneNotSupportedException\nParameters : \nNA\nReturns :\nNA\nOverrides :\nclone in class Object\nThrows :\nCloneNotSupportedException-if the object's class does not support the Cloneable interface.\n// Java program to demonstrate clone() methodenum Color{ RED, GREEN, BLUE;} public class Test{ // Driver method public static void main(String[] args) throws CloneNotSupportedException { System.out.println(\"Enums are never cloned\"); Test t = new Test() { // final clone method protected final Object clone() throws CloneNotSupportedException { return new CloneNotSupportedException(); } }; System.out.println(t.clone()); }}Output:Enums are never cloned\njava.lang.CloneNotSupportedException\n" }, { "code": null, "e": 29050, "s": 28813, "text": "Syntax : \npublic final Object clone() throws CloneNotSupportedException\nParameters : \nNA\nReturns :\nNA\nOverrides :\nclone in class Object\nThrows :\nCloneNotSupportedException-if the object's class does not support the Cloneable interface.\n" }, { "code": "// Java program to demonstrate clone() methodenum Color{ RED, GREEN, BLUE;} public class Test{ // Driver method public static void main(String[] args) throws CloneNotSupportedException { System.out.println(\"Enums are never cloned\"); Test t = new Test() { // final clone method protected final Object clone() throws CloneNotSupportedException { return new CloneNotSupportedException(); } }; System.out.println(t.clone()); }}", "e": 29629, "s": 29050, "text": null }, { "code": null, "e": 29637, "s": 29629, "text": "Output:" }, { "code": null, "e": 29698, "s": 29637, "text": "Enums are never cloned\njava.lang.CloneNotSupportedException\n" }, { "code": null, "e": 30437, "s": 29698, "text": "final void finalize() : This method guarantees that enum classes cannot have finalize methods.Syntax : \nprotected final void finalize()\nParameters : \nNA\nReturns :\nNA\nOverrides :\nfinalize in class Object\n// Java program to demonstrate finalize() methodenum Color{ RED, GREEN, BLUE;} public class Test{ // Driver method public static void main(String[] args) throws Throwable { System.out.println(\"enum classes cannot have finalize methods\"); Test t = new Test() { // final finalize method protected final void finalize() throws Throwable { // empty implementation }; }; }}Output:enum classes cannot have finalize methods\n" }, { "code": null, "e": 30547, "s": 30437, "text": "Syntax : \nprotected final void finalize()\nParameters : \nNA\nReturns :\nNA\nOverrides :\nfinalize in class Object\n" }, { "code": "// Java program to demonstrate finalize() methodenum Color{ RED, GREEN, BLUE;} public class Test{ // Driver method public static void main(String[] args) throws Throwable { System.out.println(\"enum classes cannot have finalize methods\"); Test t = new Test() { // final finalize method protected final void finalize() throws Throwable { // empty implementation }; }; }}", "e": 31034, "s": 30547, "text": null }, { "code": null, "e": 31042, "s": 31034, "text": "Output:" }, { "code": null, "e": 31085, "s": 31042, "text": "enum classes cannot have finalize methods\n" }, { "code": null, "e": 31383, "s": 31085, "text": "This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 31508, "s": 31383, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 31522, "s": 31508, "text": "chhabradhanvi" }, { "code": null, "e": 31540, "s": 31522, "text": "Java-lang package" }, { "code": null, "e": 31545, "s": 31540, "text": "Java" }, { "code": null, "e": 31550, "s": 31545, "text": "Java" } ]
std::allocator() in C++ with Examples
04 Jun, 2022 Allocators are objects responsible for encapsulating memory management. std::allocator is used when you want to separate allocation and do construction in two steps. It is also used when separate destruction and deallocation is done in two steps. All the STL containers in C++ have a type parameter Allocator that is by default std::allocator. The default allocator simply uses the operators new and delete to obtain and release memory. Declaration : template <class T> class allocator; Member functions associated with std::allocator() : address: It is used for obtaining the address of an object although it is removed in C++20.construct: It is used to construct an object.It is also removed in C++20.destroy: It is used to destruct an object in allocated storage.It is also removed in C++20.max_size: It returns the largest supported allocation size.It is deprecated in C++17 and removed in C++20.allocate: Used for allocation of memory.deallocate: Used for deallocation of memory. address: It is used for obtaining the address of an object although it is removed in C++20. construct: It is used to construct an object.It is also removed in C++20. destroy: It is used to destruct an object in allocated storage.It is also removed in C++20. max_size: It returns the largest supported allocation size.It is deprecated in C++17 and removed in C++20. allocate: Used for allocation of memory. deallocate: Used for deallocation of memory. Below programs illustrate the above mentioned function: Program 1: CPP // C++ program for illustration// of std::allocator() function#include <iostream>#include <memory>using namespace std;int main(){ // allocator for integer values allocator<int> myAllocator; // allocate space for five ints int* arr = myAllocator.allocate(5); // construct arr[0] and arr[3] // myAllocator.construct(arr, 100); // no longer allowed in C++20 arr[0] = 100; // do this instead arr[3] = 10; cout << arr[3] << endl; cout << arr[0] << endl; // deallocate space for five ints myAllocator.deallocate(arr, 5); return 0;} 10 100 Program 2: CPP // C++ program for illustration// of std::allocator() function#include <iostream>#include <memory>#include <string>using namespace std; int main(){ // allocator for string values allocator<string> myAllocator; // allocate space for three strings string* str = myAllocator.allocate(3); // construct these 3 strings myAllocator.construct(str, "Geeks"); myAllocator.construct(str + 1, "for"); myAllocator.construct(str + 2, "Geeks"); cout << str[0] << str[1] << str[2]; // destroy these 3 strings myAllocator.destroy(str); myAllocator.destroy(str + 1); myAllocator.destroy(str + 2); // deallocate space for 3 strings myAllocator.deallocate(str, 3);} GeeksforGeeks Advantage of using std::allocator allocator is the memory allocator for the STL containers. This container can separate the memory allocation and de-allocation from the initialization and destruction of their elements. Therefore, a call of vec.reserve(n) of a vector vec allocates only memory for at least n elements. The constructor for each element will not be executed.allocator can be adjusted according to the container of your need, for example, vector where you only want to allocate occasionally.On the contrary, new doesn’t allow to have control over which constructors are called and simply construct all objects at the same time. That’s an advantage of std:: allocator over new allocator is the memory allocator for the STL containers. This container can separate the memory allocation and de-allocation from the initialization and destruction of their elements. Therefore, a call of vec.reserve(n) of a vector vec allocates only memory for at least n elements. The constructor for each element will not be executed. allocator can be adjusted according to the container of your need, for example, vector where you only want to allocate occasionally. On the contrary, new doesn’t allow to have control over which constructors are called and simply construct all objects at the same time. That’s an advantage of std:: allocator over new rubeennsp rtiscnqjt cpp-class CPP-Functions C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n04 Jun, 2022" }, { "code": null, "e": 505, "s": 54, "text": "Allocators are objects responsible for encapsulating memory management. std::allocator is used when you want to separate allocation and do construction in two steps. It is also used when separate destruction and deallocation is done in two steps. All the STL containers in C++ have a type parameter Allocator that is by default std::allocator. The default allocator simply uses the operators new and delete to obtain and release memory. Declaration :" }, { "code": null, "e": 541, "s": 505, "text": "template <class T> class allocator;" }, { "code": null, "e": 593, "s": 541, "text": "Member functions associated with std::allocator() :" }, { "code": null, "e": 1039, "s": 593, "text": "address: It is used for obtaining the address of an object although it is removed in C++20.construct: It is used to construct an object.It is also removed in C++20.destroy: It is used to destruct an object in allocated storage.It is also removed in C++20.max_size: It returns the largest supported allocation size.It is deprecated in C++17 and removed in C++20.allocate: Used for allocation of memory.deallocate: Used for deallocation of memory." }, { "code": null, "e": 1131, "s": 1039, "text": "address: It is used for obtaining the address of an object although it is removed in C++20." }, { "code": null, "e": 1205, "s": 1131, "text": "construct: It is used to construct an object.It is also removed in C++20." }, { "code": null, "e": 1297, "s": 1205, "text": "destroy: It is used to destruct an object in allocated storage.It is also removed in C++20." }, { "code": null, "e": 1404, "s": 1297, "text": "max_size: It returns the largest supported allocation size.It is deprecated in C++17 and removed in C++20." }, { "code": null, "e": 1445, "s": 1404, "text": "allocate: Used for allocation of memory." }, { "code": null, "e": 1490, "s": 1445, "text": "deallocate: Used for deallocation of memory." }, { "code": null, "e": 1558, "s": 1490, "text": "Below programs illustrate the above mentioned function: Program 1: " }, { "code": null, "e": 1562, "s": 1558, "text": "CPP" }, { "code": "// C++ program for illustration// of std::allocator() function#include <iostream>#include <memory>using namespace std;int main(){ // allocator for integer values allocator<int> myAllocator; // allocate space for five ints int* arr = myAllocator.allocate(5); // construct arr[0] and arr[3] // myAllocator.construct(arr, 100); // no longer allowed in C++20 arr[0] = 100; // do this instead arr[3] = 10; cout << arr[3] << endl; cout << arr[0] << endl; // deallocate space for five ints myAllocator.deallocate(arr, 5); return 0;}", "e": 2133, "s": 1562, "text": null }, { "code": null, "e": 2140, "s": 2133, "text": "10\n100" }, { "code": null, "e": 2152, "s": 2140, "text": "Program 2: " }, { "code": null, "e": 2156, "s": 2152, "text": "CPP" }, { "code": "// C++ program for illustration// of std::allocator() function#include <iostream>#include <memory>#include <string>using namespace std; int main(){ // allocator for string values allocator<string> myAllocator; // allocate space for three strings string* str = myAllocator.allocate(3); // construct these 3 strings myAllocator.construct(str, \"Geeks\"); myAllocator.construct(str + 1, \"for\"); myAllocator.construct(str + 2, \"Geeks\"); cout << str[0] << str[1] << str[2]; // destroy these 3 strings myAllocator.destroy(str); myAllocator.destroy(str + 1); myAllocator.destroy(str + 2); // deallocate space for 3 strings myAllocator.deallocate(str, 3);}", "e": 2854, "s": 2156, "text": null }, { "code": null, "e": 2868, "s": 2854, "text": "GeeksforGeeks" }, { "code": null, "e": 2902, "s": 2868, "text": "Advantage of using std::allocator" }, { "code": null, "e": 3557, "s": 2902, "text": "allocator is the memory allocator for the STL containers. This container can separate the memory allocation and de-allocation from the initialization and destruction of their elements. Therefore, a call of vec.reserve(n) of a vector vec allocates only memory for at least n elements. The constructor for each element will not be executed.allocator can be adjusted according to the container of your need, for example, vector where you only want to allocate occasionally.On the contrary, new doesn’t allow to have control over which constructors are called and simply construct all objects at the same time. That’s an advantage of std:: allocator over new" }, { "code": null, "e": 3896, "s": 3557, "text": "allocator is the memory allocator for the STL containers. This container can separate the memory allocation and de-allocation from the initialization and destruction of their elements. Therefore, a call of vec.reserve(n) of a vector vec allocates only memory for at least n elements. The constructor for each element will not be executed." }, { "code": null, "e": 4029, "s": 3896, "text": "allocator can be adjusted according to the container of your need, for example, vector where you only want to allocate occasionally." }, { "code": null, "e": 4214, "s": 4029, "text": "On the contrary, new doesn’t allow to have control over which constructors are called and simply construct all objects at the same time. That’s an advantage of std:: allocator over new" }, { "code": null, "e": 4224, "s": 4214, "text": "rubeennsp" }, { "code": null, "e": 4234, "s": 4224, "text": "rtiscnqjt" }, { "code": null, "e": 4244, "s": 4234, "text": "cpp-class" }, { "code": null, "e": 4258, "s": 4244, "text": "CPP-Functions" }, { "code": null, "e": 4262, "s": 4258, "text": "C++" }, { "code": null, "e": 4266, "s": 4262, "text": "CPP" } ]
Python | Extract words from given string
28 Jul, 2021 We sometimes come through situations where we require to get all the words present in the string, this can be a tedious task done using the native method. Hence having shorthands to perform this task is always useful. Additionally, this article also includes the cases in which punctuation marks have to be ignored.Method #1 : Using split() Using the split function, we can split the string into a list of words and this is the most generic and recommended method if one wished to accomplish this particular task. But the drawback is that it fails in cases the string contains punctuation marks. Python3 # Python3 code to demonstrate# to extract words from string# using split() # initializing string test_string = "Geeksforgeeks is best Computer Science Portal" # printing original stringprint ("The original string is : " + test_string) # using split()# to extract words from stringres = test_string.split() # printing resultprint ("The list of words is : " + str(res)) Method #2 : Using regex( findall() ) In the cases which contain all the special characters and punctuation marks, as discussed above, the conventional method of finding words in string using split can fail and hence requires regular expressions to perform this task. findall function returns the list after filtering the string and extracting words ignoring punctuation marks. Python3 # Python3 code to demonstrate# to extract words from string# using regex( findall() )import re # initializing string test_string = "Geeksforgeeks, is best @# Computer Science Portal.!!!" # printing original stringprint ("The original string is : " + test_string) # using regex( findall() )# to extract words from stringres = re.findall(r'\w+', test_string) # printing resultprint ("The list of words is : " + str(res)) Method #3 : Using regex() + string.punctuation This method also used regular expressions, but string function of getting all the punctuations is used to ignore all the punctuation marks and get the filtered result string. Python3 # Python3 code to demonstrate# to extract words from string# using regex() + string.punctuationimport reimport string # initializing string test_string = "Geeksforgeeks, is best @# Computer Science Portal.!!!" # printing original stringprint ("The original string is : " + test_string) # using regex() + string.punctuation# to extract words from stringres = re.sub('['+string.punctuation+']', '', test_string).split() # printing resultprint ("The list of words is : " + str(res)) ipablo26 Python string-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python How to Install PIP on Windows ? *args and **kwargs in Python Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python Program for Fibonacci numbers
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Jul, 2021" }, { "code": null, "e": 625, "s": 28, "text": "We sometimes come through situations where we require to get all the words present in the string, this can be a tedious task done using the native method. Hence having shorthands to perform this task is always useful. Additionally, this article also includes the cases in which punctuation marks have to be ignored.Method #1 : Using split() Using the split function, we can split the string into a list of words and this is the most generic and recommended method if one wished to accomplish this particular task. But the drawback is that it fails in cases the string contains punctuation marks. " }, { "code": null, "e": 633, "s": 625, "text": "Python3" }, { "code": "# Python3 code to demonstrate# to extract words from string# using split() # initializing string test_string = \"Geeksforgeeks is best Computer Science Portal\" # printing original stringprint (\"The original string is : \" + test_string) # using split()# to extract words from stringres = test_string.split() # printing resultprint (\"The list of words is : \" + str(res))", "e": 1003, "s": 633, "text": null }, { "code": null, "e": 1383, "s": 1003, "text": " Method #2 : Using regex( findall() ) In the cases which contain all the special characters and punctuation marks, as discussed above, the conventional method of finding words in string using split can fail and hence requires regular expressions to perform this task. findall function returns the list after filtering the string and extracting words ignoring punctuation marks. " }, { "code": null, "e": 1391, "s": 1383, "text": "Python3" }, { "code": "# Python3 code to demonstrate# to extract words from string# using regex( findall() )import re # initializing string test_string = \"Geeksforgeeks, is best @# Computer Science Portal.!!!\" # printing original stringprint (\"The original string is : \" + test_string) # using regex( findall() )# to extract words from stringres = re.findall(r'\\w+', test_string) # printing resultprint (\"The list of words is : \" + str(res))", "e": 1815, "s": 1391, "text": null }, { "code": null, "e": 2040, "s": 1815, "text": " Method #3 : Using regex() + string.punctuation This method also used regular expressions, but string function of getting all the punctuations is used to ignore all the punctuation marks and get the filtered result string. " }, { "code": null, "e": 2048, "s": 2040, "text": "Python3" }, { "code": "# Python3 code to demonstrate# to extract words from string# using regex() + string.punctuationimport reimport string # initializing string test_string = \"Geeksforgeeks, is best @# Computer Science Portal.!!!\" # printing original stringprint (\"The original string is : \" + test_string) # using regex() + string.punctuation# to extract words from stringres = re.sub('['+string.punctuation+']', '', test_string).split() # printing resultprint (\"The list of words is : \" + str(res))", "e": 2533, "s": 2048, "text": null }, { "code": null, "e": 2542, "s": 2533, "text": "ipablo26" }, { "code": null, "e": 2565, "s": 2542, "text": "Python string-programs" }, { "code": null, "e": 2572, "s": 2565, "text": "Python" }, { "code": null, "e": 2588, "s": 2572, "text": "Python Programs" }, { "code": null, "e": 2686, "s": 2588, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2704, "s": 2686, "text": "Python Dictionary" }, { "code": null, "e": 2746, "s": 2704, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2768, "s": 2746, "text": "Enumerate() in Python" }, { "code": null, "e": 2800, "s": 2768, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2829, "s": 2800, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2872, "s": 2829, "text": "Python program to convert a list to string" }, { "code": null, "e": 2894, "s": 2872, "text": "Defaultdict in Python" }, { "code": null, "e": 2933, "s": 2894, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2971, "s": 2933, "text": "Python | Convert a list to dictionary" } ]
How to Load SVG from URL in Android ImageView?
08 Jun, 2022 It is seen that many Android apps require to use of high-quality images that will not get blur while zooming. So we have to use high-quality images. But if we are using PNG images then they will get blur after zooming because PNG images are made up of pixels and they will reduce their quality after zooming. So SVG images are preferable to use because SVG images are made up of vectors and they don’t reduce their quality even after zooming. Now we will look at How we can load SVG from its URL in our Android App. Step 1: Create a new Android Studio Project For creating a new Android Studio project just click on File > New > New Project. Make sure to choose your language as JAVA. You can refer to this post on How to Create New Android Studio Project. Step 2: Before moving to the coding part add these two dependencies in your build.gradle Go to Gradle Scripts > build.gradle (Module: app) section and add the following dependencies and click the “Sync Now” on the above pop-up. Add these two dependencies. implementation ‘com.squareup.okhttp3:okhttp:3.10.0’ implementation ‘com.pixplicity.sharp:library:1.1.0’ and, Add google repository in the build.gradle file of the application project if by default it is not there buildscript { repositories { google() mavenCentral() } All Jetpack components are available in the Google Maven repository, include them in the build.gradle file allprojects { repositories { google() mavenCentral() } } Step 3: Now we will move toward the design part Navigate to the app > res > layout > activity_main.xml. Below is the code for the activity_main.xml file. Note: Drawables are added in app > res > drawable folder. Example 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" tools:context=".MainActivity"> <ImageView android:id="@+id/imageview" android:layout_width="match_parent" android:layout_height="200dp" android:layout_centerHorizontal="true" android:layout_marginLeft="10dp" android:layout_marginTop="40dp" android:layout_marginRight="10dp" android:contentDescription="@string/app_name" android:src="@drawable/gfgimage" /> </RelativeLayout> Step 4: Now create a new Java class as Utils In this JAVA class, we are loading data from the URL in the form of the byte stream. The sharp library will convert this byte stream and will load the SVG image in our target ImageView. To create a new JAVA class navigate to the app > java > your apps package name >> Right-click on it and then click on it and click New > Java class. Give a name to your JAVA class. Below is the code for the Utils.java file. Comments are added inside the code to understand the code in more detail. Example Java import android.content.Context;import android.widget.ImageView;import com.pixplicity.sharp.Sharp;import java.io.IOException;import java.io.InputStream;import okhttp3.Cache;import okhttp3.Call;import okhttp3.Callback;import okhttp3.OkHttpClient;import okhttp3.Request;import okhttp3.Response; public class Utils { private static OkHttpClient httpClient; // this method is used to fetch svg and load it into // target imageview. public static void fetchSvg(Context context, String url, final ImageView target) { if (httpClient == null) { httpClient = new OkHttpClient.Builder() .cache(new Cache( context.getCacheDir(), 5 * 1024 * 1014)) .build(); } // here we are making HTTP call to fetch data from // URL. Request request = new Request.Builder().url(url).build(); httpClient.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { // we are adding a default image if we gets // any error. target.setImageResource( R.drawable.gfgimage); } @Override public void onResponse(Call call, Response response) throws IOException { // sharp is a library which will load stream // which we generated from url in our target // imageview. InputStream stream = response.body().byteStream(); Sharp.loadInputStream(stream).into(target); stream.close(); } }); }} Step 5: Now we will use this Utils class in our MainActivity.java file to load images from the URL Navigate to the app > java > your apps package name > MainActivity.java file. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail. Java import android.os.Bundle;import android.widget.ImageView;import androidx.appcompat.app.AppCompatActivity;public class MainActivity extends AppCompatActivity { ImageView imageView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initialize your imageview imageView = findViewById(R.id.imageview); // url for .svg image String url = " "; // this method will load svg // image in your imageview Utils.fetchSvg(this, url, imageView); }} Step 6: Add internet permission in your AndroidManifest file Navigate to the app > manifest and add internet permission. XML <?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.gtappdevelopers.frescoimageloading"> <!--Permission for internet--> <uses-permission android:name="android.permission.INTERNET" /> <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/Theme.FrescoImageLoading"> <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> Output: hemantjain99 android Android-View Android Java Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Android SDK and it's Components Flutter - Custom Bottom Navigation Bar How to Add Views Dynamically and Store Data in Arraylist in Android? Retrofit with Kotlin Coroutine in Android How to Post Data to API using Retrofit in Android? Arrays in Java Split() String method in Java with examples Arrays.sort() in Java with examples Object Oriented Programming (OOPs) Concept in Java Reverse a string in Java
[ { "code": null, "e": 52, "s": 24, "text": "\n08 Jun, 2022" }, { "code": null, "e": 568, "s": 52, "text": "It is seen that many Android apps require to use of high-quality images that will not get blur while zooming. So we have to use high-quality images. But if we are using PNG images then they will get blur after zooming because PNG images are made up of pixels and they will reduce their quality after zooming. So SVG images are preferable to use because SVG images are made up of vectors and they don’t reduce their quality even after zooming. Now we will look at How we can load SVG from its URL in our Android App." }, { "code": null, "e": 612, "s": 568, "text": "Step 1: Create a new Android Studio Project" }, { "code": null, "e": 814, "s": 612, "text": "For creating a new Android Studio project just click on File > New > New Project. Make sure to choose your language as JAVA. You can refer to this post on How to Create New Android Studio Project. " }, { "code": null, "e": 903, "s": 814, "text": "Step 2: Before moving to the coding part add these two dependencies in your build.gradle" }, { "code": null, "e": 1070, "s": 903, "text": "Go to Gradle Scripts > build.gradle (Module: app) section and add the following dependencies and click the “Sync Now” on the above pop-up. Add these two dependencies." }, { "code": null, "e": 1123, "s": 1070, "text": " implementation ‘com.squareup.okhttp3:okhttp:3.10.0’" }, { "code": null, "e": 1176, "s": 1123, "text": " implementation ‘com.pixplicity.sharp:library:1.1.0’" }, { "code": null, "e": 1285, "s": 1176, "text": "and, Add google repository in the build.gradle file of the application project if by default it is not there" }, { "code": null, "e": 1299, "s": 1285, "text": "buildscript {" }, { "code": null, "e": 1314, "s": 1299, "text": "repositories {" }, { "code": null, "e": 1326, "s": 1314, "text": " google()" }, { "code": null, "e": 1344, "s": 1326, "text": " mavenCentral()" }, { "code": null, "e": 1346, "s": 1344, "text": "}" }, { "code": null, "e": 1453, "s": 1346, "text": "All Jetpack components are available in the Google Maven repository, include them in the build.gradle file" }, { "code": null, "e": 1467, "s": 1453, "text": "allprojects {" }, { "code": null, "e": 1482, "s": 1467, "text": "repositories {" }, { "code": null, "e": 1494, "s": 1482, "text": " google()" }, { "code": null, "e": 1511, "s": 1494, "text": " mavenCentral()" }, { "code": null, "e": 1513, "s": 1511, "text": "}" }, { "code": null, "e": 1515, "s": 1513, "text": "}" }, { "code": null, "e": 1564, "s": 1515, "text": " Step 3: Now we will move toward the design part" }, { "code": null, "e": 1670, "s": 1564, "text": "Navigate to the app > res > layout > activity_main.xml. Below is the code for the activity_main.xml file." }, { "code": null, "e": 1729, "s": 1670, "text": "Note: Drawables are added in app > res > drawable folder. " }, { "code": null, "e": 1737, "s": 1729, "text": "Example" }, { "code": null, "e": 1741, "s": 1737, "text": "XML" }, { "code": "<?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\" tools:context=\".MainActivity\"> <ImageView android:id=\"@+id/imageview\" android:layout_width=\"match_parent\" android:layout_height=\"200dp\" android:layout_centerHorizontal=\"true\" android:layout_marginLeft=\"10dp\" android:layout_marginTop=\"40dp\" android:layout_marginRight=\"10dp\" android:contentDescription=\"@string/app_name\" android:src=\"@drawable/gfgimage\" /> </RelativeLayout>", "e": 2430, "s": 1741, "text": null }, { "code": null, "e": 2475, "s": 2430, "text": "Step 4: Now create a new Java class as Utils" }, { "code": null, "e": 2959, "s": 2475, "text": "In this JAVA class, we are loading data from the URL in the form of the byte stream. The sharp library will convert this byte stream and will load the SVG image in our target ImageView. To create a new JAVA class navigate to the app > java > your apps package name >> Right-click on it and then click on it and click New > Java class. Give a name to your JAVA class. Below is the code for the Utils.java file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 2967, "s": 2959, "text": "Example" }, { "code": null, "e": 2972, "s": 2967, "text": "Java" }, { "code": "import android.content.Context;import android.widget.ImageView;import com.pixplicity.sharp.Sharp;import java.io.IOException;import java.io.InputStream;import okhttp3.Cache;import okhttp3.Call;import okhttp3.Callback;import okhttp3.OkHttpClient;import okhttp3.Request;import okhttp3.Response; public class Utils { private static OkHttpClient httpClient; // this method is used to fetch svg and load it into // target imageview. public static void fetchSvg(Context context, String url, final ImageView target) { if (httpClient == null) { httpClient = new OkHttpClient.Builder() .cache(new Cache( context.getCacheDir(), 5 * 1024 * 1014)) .build(); } // here we are making HTTP call to fetch data from // URL. Request request = new Request.Builder().url(url).build(); httpClient.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { // we are adding a default image if we gets // any error. target.setImageResource( R.drawable.gfgimage); } @Override public void onResponse(Call call, Response response) throws IOException { // sharp is a library which will load stream // which we generated from url in our target // imageview. InputStream stream = response.body().byteStream(); Sharp.loadInputStream(stream).into(target); stream.close(); } }); }}", "e": 4818, "s": 2972, "text": null }, { "code": null, "e": 4917, "s": 4818, "text": "Step 5: Now we will use this Utils class in our MainActivity.java file to load images from the URL" }, { "code": null, "e": 5119, "s": 4917, "text": "Navigate to the app > java > your apps package name > MainActivity.java file. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 5124, "s": 5119, "text": "Java" }, { "code": "import android.os.Bundle;import android.widget.ImageView;import androidx.appcompat.app.AppCompatActivity;public class MainActivity extends AppCompatActivity { ImageView imageView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initialize your imageview imageView = findViewById(R.id.imageview); // url for .svg image String url = \" \"; // this method will load svg // image in your imageview Utils.fetchSvg(this, url, imageView); }}", "e": 5757, "s": 5124, "text": null }, { "code": null, "e": 5818, "s": 5757, "text": "Step 6: Add internet permission in your AndroidManifest file" }, { "code": null, "e": 5878, "s": 5818, "text": "Navigate to the app > manifest and add internet permission." }, { "code": null, "e": 5882, "s": 5878, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"com.gtappdevelopers.frescoimageloading\"> <!--Permission for internet--> <uses-permission android:name=\"android.permission.INTERNET\" /> <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/Theme.FrescoImageLoading\"> <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>", "e": 6719, "s": 5882, "text": null }, { "code": null, "e": 6728, "s": 6719, "text": "Output: " }, { "code": null, "e": 6741, "s": 6728, "text": "hemantjain99" }, { "code": null, "e": 6749, "s": 6741, "text": "android" }, { "code": null, "e": 6762, "s": 6749, "text": "Android-View" }, { "code": null, "e": 6770, "s": 6762, "text": "Android" }, { "code": null, "e": 6775, "s": 6770, "text": "Java" }, { "code": null, "e": 6780, "s": 6775, "text": "Java" }, { "code": null, "e": 6788, "s": 6780, "text": "Android" }, { "code": null, "e": 6886, "s": 6788, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6918, "s": 6886, "text": "Android SDK and it's Components" }, { "code": null, "e": 6957, "s": 6918, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 7026, "s": 6957, "text": "How to Add Views Dynamically and Store Data in Arraylist in Android?" }, { "code": null, "e": 7068, "s": 7026, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 7119, "s": 7068, "text": "How to Post Data to API using Retrofit in Android?" }, { "code": null, "e": 7134, "s": 7119, "text": "Arrays in Java" }, { "code": null, "e": 7178, "s": 7134, "text": "Split() String method in Java with examples" }, { "code": null, "e": 7214, "s": 7178, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 7265, "s": 7214, "text": "Object Oriented Programming (OOPs) Concept in Java" } ]
Strace command in Linux with Examples
10 May, 2020 Strace is one of the most powerful process monitoring, diagnostic, instructional tool of Linux. It also acts as a debugging tool that helps in troubleshooting issues. It is majorly used for the following purposes: Debugging Programs Troubleshooting Programs Intercept System calls by a process Record system calls by a process Signals received by a process Trace running processes In case the source code is not available, strace is used to analyze how a program interacts with the system to debug the executing of program. It returns the name of each system call along with its argument enclosed in parenthesis and its return value to standard error. To install the strace tool use the following commands as per your Linux distribution. In case of Debian/Ubuntu $sudo apt install strace In case of CentOS/RedHat $yum install strace 1. To get the system call, argument, and the result of the call. $strace ls Note: Here “ls” is the command whose system call is to be traced. As can be seen, it displays the system call, argument(in parenthesis), and result of the call of ls command. And +++ exited with 0 +++, in the last line states that exit status is 0 which means there was no error. In case of an error, the exit code is -1. 2. To count number of system calls. $strace -c ls Note: Here “ls” is the command whose system call is to be traced. As can be seen, it displays the number of times each system call was made and prints the total and even showing the number and time spent in each call. 3. To trace particular or specific system calls. $strace -e trace=write ls Note: Here “ls” is the command whose system call is to be traced. And the name of the system call which is to be traced is write. As can be seen, it only displays the name, argument, and result of write system call. 4. To trace network related system calls $strace -e trace=network nc -v -n 127.0.0.1 801 Note: Here “nc -v -n 127.0.0.1 801” is the command whose system call is to be traced. And the name of the system call which is to be traced is the network. As can be seen, it only displays the name, argument, and result of the network system call. 5. To trace signal related system calls $strace -e trace=signal nc -v -n 127.0.0.1 801 Note: Here “nc -v -n 127.0.0.1 801” is the command whose system call is to be traced. And the name of the system call which is to be traced is signal. As can be seen, it only displays the name, argument, and result of the signal system call. 6. To print timestamp of each call. $strace -r ls Note: Here “ls” is the command whose system call is to be traced. As can be seen, it displays a relative timestamp upon entry to each system call. It records the time difference between the beginning of successive system calls. 7. To print time spent on system calls. $strace -T ls Note: Here “ls” is the command whose system call is to be traced. As can be seen the time spent on each call is printed at the end of each line. 8. To print wall clock time of each system call. $strace -t ls Note: Here “ls” is the command whose system call is to be traced. As it can be seen that the prefix of each line if the wall clock time itself of the system call. 9. To print instruction pointer. $strace -i ls Note: Here “ls” is the command whose system call is to be traced. As can be seen, the instruction pointer is printed in each line of output. 10. To print output to a file $strace -o output.txt ls Note: Here “ls” is the command whose system call is to be traced. And output.txt is the name of the file in which output is to be stored. As can be seen, the output of the command is stored in the output.txt file. linux-command Linux-system-commands Linux-Unix Write From Home Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. tar command in Linux with examples Conditional Statements | Shell Script Tail command in Linux with examples Docker - COPY Instruction scp command in Linux with Examples Convert integer to string in Python Convert string to integer in Python How to set input type date in dd-mm-yyyy format using HTML ? Python infinity Factory method design pattern in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n10 May, 2020" }, { "code": null, "e": 242, "s": 28, "text": "Strace is one of the most powerful process monitoring, diagnostic, instructional tool of Linux. It also acts as a debugging tool that helps in troubleshooting issues. It is majorly used for the following purposes:" }, { "code": null, "e": 261, "s": 242, "text": "Debugging Programs" }, { "code": null, "e": 286, "s": 261, "text": "Troubleshooting Programs" }, { "code": null, "e": 322, "s": 286, "text": "Intercept System calls by a process" }, { "code": null, "e": 355, "s": 322, "text": "Record system calls by a process" }, { "code": null, "e": 385, "s": 355, "text": "Signals received by a process" }, { "code": null, "e": 409, "s": 385, "text": "Trace running processes" }, { "code": null, "e": 680, "s": 409, "text": "In case the source code is not available, strace is used to analyze how a program interacts with the system to debug the executing of program. It returns the name of each system call along with its argument enclosed in parenthesis and its return value to standard error." }, { "code": null, "e": 766, "s": 680, "text": "To install the strace tool use the following commands as per your Linux distribution." }, { "code": null, "e": 791, "s": 766, "text": "In case of Debian/Ubuntu" }, { "code": null, "e": 816, "s": 791, "text": "$sudo apt install strace" }, { "code": null, "e": 841, "s": 816, "text": "In case of CentOS/RedHat" }, { "code": null, "e": 861, "s": 841, "text": "$yum install strace" }, { "code": null, "e": 926, "s": 861, "text": "1. To get the system call, argument, and the result of the call." }, { "code": null, "e": 937, "s": 926, "text": "$strace ls" }, { "code": null, "e": 1003, "s": 937, "text": "Note: Here “ls” is the command whose system call is to be traced." }, { "code": null, "e": 1259, "s": 1003, "text": "As can be seen, it displays the system call, argument(in parenthesis), and result of the call of ls command. And +++ exited with 0 +++, in the last line states that exit status is 0 which means there was no error. In case of an error, the exit code is -1." }, { "code": null, "e": 1295, "s": 1259, "text": "2. To count number of system calls." }, { "code": null, "e": 1310, "s": 1295, "text": "$strace -c ls\n" }, { "code": null, "e": 1376, "s": 1310, "text": "Note: Here “ls” is the command whose system call is to be traced." }, { "code": null, "e": 1528, "s": 1376, "text": "As can be seen, it displays the number of times each system call was made and prints the total and even showing the number and time spent in each call." }, { "code": null, "e": 1577, "s": 1528, "text": "3. To trace particular or specific system calls." }, { "code": null, "e": 1604, "s": 1577, "text": "$strace -e trace=write ls\n" }, { "code": null, "e": 1734, "s": 1604, "text": "Note: Here “ls” is the command whose system call is to be traced. And the name of the system call which is to be traced is write." }, { "code": null, "e": 1820, "s": 1734, "text": "As can be seen, it only displays the name, argument, and result of write system call." }, { "code": null, "e": 1861, "s": 1820, "text": "4. To trace network related system calls" }, { "code": null, "e": 1910, "s": 1861, "text": "$strace -e trace=network nc -v -n 127.0.0.1 801\n" }, { "code": null, "e": 2066, "s": 1910, "text": "Note: Here “nc -v -n 127.0.0.1 801” is the command whose system call is to be traced. And the name of the system call which is to be traced is the network." }, { "code": null, "e": 2158, "s": 2066, "text": "As can be seen, it only displays the name, argument, and result of the network system call." }, { "code": null, "e": 2198, "s": 2158, "text": "5. To trace signal related system calls" }, { "code": null, "e": 2246, "s": 2198, "text": "$strace -e trace=signal nc -v -n 127.0.0.1 801\n" }, { "code": null, "e": 2397, "s": 2246, "text": "Note: Here “nc -v -n 127.0.0.1 801” is the command whose system call is to be traced. And the name of the system call which is to be traced is signal." }, { "code": null, "e": 2488, "s": 2397, "text": "As can be seen, it only displays the name, argument, and result of the signal system call." }, { "code": null, "e": 2524, "s": 2488, "text": "6. To print timestamp of each call." }, { "code": null, "e": 2539, "s": 2524, "text": "$strace -r ls\n" }, { "code": null, "e": 2605, "s": 2539, "text": "Note: Here “ls” is the command whose system call is to be traced." }, { "code": null, "e": 2767, "s": 2605, "text": "As can be seen, it displays a relative timestamp upon entry to each system call. It records the time difference between the beginning of successive system calls." }, { "code": null, "e": 2807, "s": 2767, "text": "7. To print time spent on system calls." }, { "code": null, "e": 2822, "s": 2807, "text": "$strace -T ls\n" }, { "code": null, "e": 2888, "s": 2822, "text": "Note: Here “ls” is the command whose system call is to be traced." }, { "code": null, "e": 2967, "s": 2888, "text": "As can be seen the time spent on each call is printed at the end of each line." }, { "code": null, "e": 3016, "s": 2967, "text": "8. To print wall clock time of each system call." }, { "code": null, "e": 3031, "s": 3016, "text": "$strace -t ls\n" }, { "code": null, "e": 3097, "s": 3031, "text": "Note: Here “ls” is the command whose system call is to be traced." }, { "code": null, "e": 3194, "s": 3097, "text": "As it can be seen that the prefix of each line if the wall clock time itself of the system call." }, { "code": null, "e": 3227, "s": 3194, "text": "9. To print instruction pointer." }, { "code": null, "e": 3242, "s": 3227, "text": "$strace -i ls\n" }, { "code": null, "e": 3308, "s": 3242, "text": "Note: Here “ls” is the command whose system call is to be traced." }, { "code": null, "e": 3383, "s": 3308, "text": "As can be seen, the instruction pointer is printed in each line of output." }, { "code": null, "e": 3413, "s": 3383, "text": "10. To print output to a file" }, { "code": null, "e": 3439, "s": 3413, "text": "$strace -o output.txt ls\n" }, { "code": null, "e": 3577, "s": 3439, "text": "Note: Here “ls” is the command whose system call is to be traced. And output.txt is the name of the file in which output is to be stored." }, { "code": null, "e": 3653, "s": 3577, "text": "As can be seen, the output of the command is stored in the output.txt file." }, { "code": null, "e": 3667, "s": 3653, "text": "linux-command" }, { "code": null, "e": 3689, "s": 3667, "text": "Linux-system-commands" }, { "code": null, "e": 3700, "s": 3689, "text": "Linux-Unix" }, { "code": null, "e": 3716, "s": 3700, "text": "Write From Home" }, { "code": null, "e": 3814, "s": 3716, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3849, "s": 3814, "text": "tar command in Linux with examples" }, { "code": null, "e": 3887, "s": 3849, "text": "Conditional Statements | Shell Script" }, { "code": null, "e": 3923, "s": 3887, "text": "Tail command in Linux with examples" }, { "code": null, "e": 3949, "s": 3923, "text": "Docker - COPY Instruction" }, { "code": null, "e": 3984, "s": 3949, "text": "scp command in Linux with Examples" }, { "code": null, "e": 4020, "s": 3984, "text": "Convert integer to string in Python" }, { "code": null, "e": 4056, "s": 4020, "text": "Convert string to integer in Python" }, { "code": null, "e": 4117, "s": 4056, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 4133, "s": 4117, "text": "Python infinity" } ]
BabelJS - Quick Guide
BabelJS is a JavaScript transpiler which transpiles new features into old standard. With this, the features can be run on both old and new browsers, hassle-free. An Australian developer, Sebastian McKenzie started BabelJS. JavaScript is the language that the browser understands. We use different browsers to run our applications − Chrome, Firefox, Internet Explorer, Microsoft Edge, Opera, UC browser etc. ECMA Script is the JavaScript language specification; the ECMA Script 2015 ES6 is the stable version which works fine in all new and old browsers. After ES5, we have had ES6, ES7, and ES8. ES6 released with a lot of new features which are not fully supported by all browsers. The same applies to ES7, ES8 and ESNext (next version of ECMA Script). It is now uncertain when it will be possible for all browsers to be compatible with all the ES versions that released. Incase we plan to use ES6 or ES7 or ES8 features to write our code it will tend to break in some old browsers because of lack of support of the new changes. Therefore, if we want to use new features of ECMA Script in our code and want to run it on all possible browsers available, we need a tool that will compile our final code in ES5. Babel does the same and it is called a transpiler that transpiles the code in the ECMA Script version that we want. It has features like presets and plugins, which configure the ECMA version we need to transpile our code. With Babel, developers can write their code using the new features in JavaScript. The users can get the codes transpiled using Babel; the codes can later be used in any browsers without any issues. The following table lists down the features available in ES6, ES7 and ES8 − BabelJS manages the following two parts − transpiling polyfilling Babel-transpiler converts the syntax of modern JavaScript into a form, which can be easily understood by older browsers. For example, arrow function, const, let classes will be converted to function, var, etc. Here the syntax, i.e., the arrow function is converted to a normal function keeping the functionality same in both the cases. There are new features added in JavaScript like promises, maps and includes. The features can be used on array; the same, when used and transpiled using babel will not get converted. In case the new feature is a method or object, we need to use Babel-polyfill along with transpiling to make it work on older browsers. Here is the list of ECMA Script features available in JavaScript, which can be transpiled and polyfilled − Classes Decorators Const Modules Destructing Default parameters Computed property names Object rest/spread Async functions Arrow functions Rest parameters Spread Template Literals ECMA Script features that can be polyfilled − Promises Map Set Symbol Weakmap Weakset includess Array.from, Array.of,Array#find,Array.buffer, Array#findIndex Object.assign,Object.entries,Object.values In this section, we will learn about the different features of BabelJS. Following are the most important core features of BabelJS − Plugins and Presets are config details for Babel to transpile the code. Babel supports a number of plugins, which can be used individually, if we know the environment in which the code will execute. Babel presets are a set of plugins, i.e., config details to the babel-transpiler that instruct Babel to transpile in a specific mode. We need to use presets, which has the environment in which we want the code to be converted. For example, es2015 preset will convert the code to es5. There are some features like methods and objects, which cannot be transpiled. At such instances, we can make use of babel-polyfill to facilitate the use of features in any browser. Let us consider the example of promises; for the feature to work in older browsers, we need to use polyfills. Babel-cli comes with a bunch of commands where the code can be easily compiled on the command line. It also has features like plugins and presets to be used along with the command making it easy to transpile the code at one go. In this section, we will learn about the different advantages associated with the use of BabelJS − BabelJS provides backward compatibility to all the newly added features to JavaScript and can be used in any browsers. BabelJS provides backward compatibility to all the newly added features to JavaScript and can be used in any browsers. BabelJS has the ability to transpile to take the next upcoming version of JavaScript - ES6, ES7, ESNext, etc. BabelJS has the ability to transpile to take the next upcoming version of JavaScript - ES6, ES7, ESNext, etc. BabelJS can be used along with gulp, webpack, flow, react, typescript, etc. making it very powerful and can be used with big project making developer’s life easy. BabelJS can be used along with gulp, webpack, flow, react, typescript, etc. making it very powerful and can be used with big project making developer’s life easy. BabelJS also works along with react JSX syntax and can be compiled in JSX form. BabelJS also works along with react JSX syntax and can be compiled in JSX form. BabelJS has support for plugins, polyfills, babel-cli that makes it easy to work with big projects. BabelJS has support for plugins, polyfills, babel-cli that makes it easy to work with big projects. In this section, we will learn about the different disadvantages of using BabelJS − BabelJS code changes the syntax while transpiling which makes the code difficult to understand when released on production. BabelJS code changes the syntax while transpiling which makes the code difficult to understand when released on production. The code transpiled is more in size when compared to the original code. The code transpiled is more in size when compared to the original code. Not all ES6/7/8 or the upcoming new features can be transpiled and we have to use polyfill so that it works on older browsers. Not all ES6/7/8 or the upcoming new features can be transpiled and we have to use polyfill so that it works on older browsers. Here is the official site of babeljs https://babeljs.io/. In this section, we will learn how to set up the environment for BabelJS. To work with BabelJS we need following setup − NodeJS Npm Babel-CLI Babel-Preset IDE for writing code To check if nodejs is installed on your system, type node –v in the terminal. This will help you see the version of nodejs currently installed on your system. If it does not print anything, install nodejs on your system. To install nodejs, go to the homepage https://nodejs.org/en/download/ of nodejs and install the package based on your OS. The following screenshot shows the download page of nodejs − Based on your OS, install the required package. Once nodejs is installed, npm will also be installed along with it. To check if npm is installed or not, type npm –v in the terminal. It should display the version of the npm. Babel comes with a built-in command line interface, which can be used to compile the code. Create a directory wherein you would be working. Here, we have created directory called babelproject. Let us make use of nodejs to create the project details. We have used npm init to create the project as shown below − Here is the project structure that we created. Now to work with Babel we need to instal Babel cli, Babel preset, Babel core as shown below − Execute the following command to install babel-cli − npm install --save-dev babel-cli Execute the following command to install babel-preset − npm install --save-dev babel-preset-env Execute the following command to install babel-core − npm install --save-dev babel-core After installation, here are the details available in package.json − We have installed babel plugins local to the project. This is done so that we can use babel differently on our projects based on the project requirements and also different versions of babeljs. Package.json gives the version details of babeljs used. In order to make use of babel in our project, we need to specify the same in package.json as follows − Babel is mainly used to compile JavaScript code, which will have backward compatibility. Now, we will write our code in ES6 -> ES5 or ES7 -> ES5 also ES7->ES6, etc. To provide instructions to Babel on the same, while executing, we need to create a file called .babelrc in the root folder. It contains a json object with details of the presets as shown below − We will create the JavaScript file index.js and compile it to es2015 using Babel. Before that, we need to install the es2015 preset as follows − In index.js, we have created a function using the arrow function which is a new feature added in es6. Using Babel, we will compile the code to es5. To execute to es2015, following command is used − npx babel index.js It displays the index.js code in es5 as shown above. We can store the output in the file by executing the command as shown below − npx babel index.js --out-file index_es5.js Here is the file that we created, index_es5.js − BabelJS is a JavaScript transpiler, which converts new features added to JavaScript into ES5 or to react based on the preset or plugin given. ES5 is one of the oldest form of JavaScript and is supported to run on new and old browsers without any issues. In most of the examples in this tutorial, we have transpiled the code to ES5. We have seen many features like arrow functions, classes, promises, generators, async functions, etc. added to ES6, ES7 and ES8. When any of the newly added features are used in old browsers, it throws errors. BabelJS helps in compiling the code, which is backward compatible with older browsers. We have seen that ES5 works perfectly fine on older browsers without any issues. So considering the project environment details, if it is required to be running on older browsers, we can use any new feature in our project and compile the code to ES5 using babeljs, and use it any browsers without any issues. Let us consider the following example to understand this. <!DOCTYPE html> <html> <head> <title>BabelJs Testing</title> </head> <body> <script type="text/javascript" src="index.js"></script> </body> </html> var _foo = () => { return "Hello World" }; alert(_foo()); When we run the above html in the Chrome browser, we get the following output − When the HTML is run in Firefox, it generates the following output − And when the same HTML is run in Internet Explorer, it generates the following syntax error − We have used the ES6 Arrow function; the same does not work on all browsers as seen above. To get this working, we have BabelJS to compile the code to ES5 and use it in all browsers. Will compile the js file to es5 using babeljs and check again in the browsers. In html file, we will use index_new.js as shown below − <!DOCTYPE html> <html> <head> <title>BabelJs Testing</title> </head> <body> <script type="text/javascript" src="index_new.js"></script> </body> </html> "use strict"; var _foo = function _foo() { return "Hello World"; }; alert(_foo()); In this chapter, we will see how to use babeljs inside our project. We will create a project using nodejs and use http local server to test our project. In this section, we will learn how to create project setup. Create a new directory and run the following command to create the project − npm init Upon execution, the above command generates the following output − Following is the package.json that is created − We will install the packages required to start working with babeljs. We will execute the following command to install babel-cli, babel-core, babel-preset-es2015. npm install babel-cli babel-core babel-preset-es2015 --save-dev Upon execution, the above command generates the following output − Package.json is updated as follows − We need http server to test the js file. Execute the following command to install http server − npm install lite-server --save-dev We have added the following details in package.json − In scripts, Babel takes care of transpiling the scripts.js from src folder and saves it in dev folder with name scripts.bundle.js. We have added the full command to compile the code we want in package.json. In addition, build is added which will start the lite-server to test the changes. The src/scripts.js has the JavaScript as follows − class Student { constructor(fname, lname, age, address) { this.fname = fname; this.lname = lname; this.age = age; this.address = address; } get fullname() { return this.fname +"-"+this.lname; } } We have called the transpiled script in index.html as follows − <html> lt;head></head> <body> <script type="text/javascript" src="dev/scripts.bundle.js?a=11"></script> <h1 id="displayname"></h1> <script type="text/javascript"> var a = new Student("Siya", "Kapoor", "15", "Mumbai"); var studentdet = a.fullname; document.getElementById("displayname").innerHTML = studentdet; </script> </body> </html> We need to run the following command, which will call babel and compile the code. The command will call Babel from package.json − npm run babel The scripts.bundle.js is the new js file created in dev folder − The output of dev/scripts.bundle.js is as follows − "use strict"; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var Student = function () { function Student(fname, lname, age, address) { _classCallCheck(this, Student); this.fname = fname; this.lname = lname; this.age = age; this.address = address; } _createClass(Student, [{ key: "fullname", get: function get() { return this.fname + "-" + this.lname; } }]); return Student; }(); Now let us run the following command to start the server − npm run build When the command runs, it will open the url in the browser − The above command generates the following output − The latest version of Babel, 7 released with changes to the already existing packages. The installation part remains the same as it was for Babel 6. The only difference in Babel 7 is that all the packages need to be installed with @babel/, for example @babel/core, @babel/preset-env, @babel/cli, @babel/polyfill, etc. Here is a project setup created using babel 7. Execute the following command to start the project setup − npm init npm install --save-dev @babel/core npm install --save-dev @babel/cli npm install --save-dev @babel/preset-env Here is the package.json created − Now will create a .babelrc file in the root folder − Create a folder src/ and add file main.js to it and write your code to transpile to es5. let add = (a,b) => { return a+b; } npx babel src/main.js --out-file main_es5.js "use strict"; var add = function add(a, b) { return a + b; }; The working of Babel 7 remains the same as Babel 6. The only difference is the pacakge installation with @babel. There are some presets deprecated in babel 7. The list is as follows − ES20xx presets babel-preset-env babel-preset-latest Stage presets in Babel Also the year from the packages is removed - @babel/plugin-transform-es2015-classes is now @babel/plugin-transform-classes We will see one more example of working with typescript and transpile it to Es2015 JavaScript using typescript preset and babel 7. To work with typescript, we need typescript package to be installed as follows − npm install --save-dev @babel/preset-typescript Create test.ts file in the src/ folder and write the code in typescript form − let getName = (person: string) => { return "Hello, " + person; } getName("Siya"); npx babel src/test.ts --out-file test.js "use strict"; var getName = function getName(person) { return "Hello, " + person; }; getName("Siya"); In this chapter, we will see the features added to ES6. We will also learn how to compile the features to ES5 using BabelJS. Following are the various ES6 features that we will discuss in this chapter − Let + Const Arrow Functions Classes Promises Generators Destructuring Iterators Template Literalst Enhanced Object Default, Rest & Spread Properties Let declares a block scope local variable in JavaScript. Consider the following example to understand the use of let. let a = 1; if (a == 1) { let a = 2; console.log(a); } console.log(a); 2 1 The reason the first console prints 2 is because a is declared again using let and will be available only in the if block. Any variable declared using let is just available within the declared block. We have declared variable a twice using let, but it does not overwrite the value of a. This is the difference between var and let keywords. When you declare variable using var, the variable will be available within the scope of the function or if declared will act like a global variable. Incase a variable is declared with let, the variable is available within the block scope. If declared inside the if statement, it will be available only within the if block. The same applies to switch, for-loop, etc. We will now see the code conversion in ES5 using babeljs. Let us run the following command to convert the code − npx babel let.js --out-file let_es5.js The output from es6 to es5 for the let keyword is as follows − let a = 1; if (a == 1) { let a = 2; console.log(a); } console.log(a); "use strict"; var a = 1; if (a == 1) { var _a = 2; console.log(_a); } console.log(a); If you see the ES5 code the let keyword is replaced with the var keyword. Also the variable inside the if block is renamed to _a to have the same effect as when declared with the let keyword. In this section, we will learn about the working of const keyword in ES6 and ES5. Const keyword is also available within the scope; and if outside, it will throw an error. The value of const declared variable cannot be changed once assigned. Let us consider the following example to understand how const keyword is used. let a =1; if (a == 1) { const age = 10; } console.log(age); Uncaught ReferenceError: age is not defined at :5:13 The above output throws an error as the const age is defined inside the if block and is available within the if block. We will understand the conversion to ES5 using BabelJS. let a =1; if (a == 1) { const age = 10; } console.log(age); npx babel const.js --out-file const_es5.js "use strict"; var a = 1; if (a == 1) { var _age = 10; } console.log(age); Incase of ES5, const keyword is replaced with the var keyword as shown above. An Arrow function has a shorter syntax in comparison to the variable expression. it is also called the fat arrow function or lambda function. The function does not have its own this property. In this function, the keyword function is omitted. var add = (x,y) => { return x+y; } var k = add(3,6); console.log(k); 9 Using BabelJS, we will transpile the above code to ES5. var add = (x,y) => { return x+y; } var k = add(3,6); console.log(k); npx babel arrowfunction.js --out-file arrowfunction_es5.js Using Babel the arrow function is converted to variable expression function as shown below. "use strict"; var add = function add(x, y) { return x + y; }; var k = add(3, 6); console.log(k); ES6 comes with the new Classes feature. Classes are similar to the prototype based inheritance available in ES5.The class keyword is used to define the class. Classes are like special functions and have similarities like function expression. It has a constructor, which is called inside the class. class Person { constructor(fname, lname, age, address) { this.fname = fname; this.lname = lname; this.age = age; this.address = address; } get fullname() { return this.fname +"-"+this.lname; } } var a = new Person("Siya", "Kapoor", "15", "Mumbai"); var persondet = a.fullname; Siya-Kapoor class Person { constructor(fname, lname, age, address) { this.fname = fname; this.lname = lname; this.age = age; this.address = address; } get fullname() { return this.fname +"-"+this.lname; } } var a = new Person("Siya", "Kapoor", "15", "Mumbai"); var persondet = a.fullname; npx babel class.js --out-file class_es5.js There is extra code added using babeljs to get the functionality working for classes same as in ES5.BabelJs makes sure the functionality works same as it would have done in ES6. "use strict"; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var Person = function () { function Person(fname, lname, age, address) { _classCallCheck(this, Person); this.fname = fname; this.lname = lname; this.age = age; this.address = address; } _createClass(Person, [{ key: "fullname", get: function get() { return this.fname + "-" + this.lname; } }]); return Person; }(); var a = new Person("Siya", "Kapoor", "15", "Mumbai"); var persondet = a.fullname; JavaScript promises are used to manage asynchronous requests in your code. It makes life easier and keeps code clean as you manage multiple callbacks from async requests, which have dependency. Promises provide a better way of working with callback functions. Promises are part of ES6. By default, when you create a promise, the state of the promise is pending. Promises come in three states − pending (initial state) resolved (completed successfully) rejected(failed) new Promise() is used to construct a promise. Promise constructor has one argument, which is a callback function. The callback function has two arguments - resolve and reject; both these are internal functions. The asynchronous code which you write, i.e., Ajax call, image loading, timing functions will go in the callback function. If the task performed in the callback function is a success, then the resolve function is called; otherwise, the reject function is called with the error details. The following line of code shows a promise structure call − var _promise = new Promise (function(resolve, reject) { var success = true; if (success) { resolve("success"); } else { reject("failure"); } }); _promise.then(function(value) { //once function resolve gets called it comes over here with the value passed in resolve console.log(value); //success }).catch(function(value) { //once function reject gets called it comes over here with the value passed in reject console.log(value); // failure. }); let timingpromise = new Promise((resolve, reject) => { setTimeout(function() { resolve("Promise is resolved!"); }, 1000); }); timingpromise.then((msg) => { console.log(msg); }); Promise is resolved! let timingpromise = new Promise((resolve, reject) => { setTimeout(function() { resolve("Promise is resolved!"); }, 1000); }); timingpromise.then((msg) => { console.log(msg); }); npx babel promise.js --out-file promise_es5.js "use strict"; var timingpromise = new Promise(function (resolve, reject) { setTimeout(function () { resolve("Promise is resolved!"); }, 1000); }); timingpromise.then(function (msg) { console.log(msg); }); For promises, the code is not changing when transpiled. We need to use babel-polyfill for it to work on older browsers.The details on babel-polyfills are explained in babel - poyfill chapter. Generator function is like normal function. The function has special syntax function* with * to the function and yield keyword to be used inside the function. This is meant to pause or start the function when required. Normal functions cannot be stopped in between once the execution starts. It will either execute the full function or halt when it encounters the return statement. Generator performs differently here, you can halt the function with the yield keyword and start it by calling the generator again whenever required. function* generatorfunction(a) { yield a; yield a +1 ; } let g = generatorfunction(8); console.log(g.next()); console.log(g.next()); {value: 8, done: false} {value: 9, done: false} function* generatorfunction(a) { yield a; yield a +1 ; } let g = generatorfunction(8); console.log(g.next()); console.log(g.next()); npx babel generator.js --out-file generator_es5.js "use strict"; var _marked = /*#__PURE__*/regeneratorRuntime.mark(generatorfunction); function generatorfunction(a) { return regeneratorRuntime.wrap(function generatorfunction$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: _context.next = 2; return a; case 2: _context.next = 4; return a + 1; case 4: case "end": return _context.stop(); } } }, _marked, this); } var g = generatorfunction(8); console.log(g.next()); console.log(g.next()); Iterator in JavaScript gives back a JavaScript object, which has value. The object also has a flag called done, which has true/false value. It gives false if it is not the end of the iterator. Let us consider an example and see the working of iterator on an array. let numbers = [4, 7, 3, 10]; let a = numbers[Symbol.iterator](); console.log(a.next()); console.log(a.next()); console.log(a.next()); console.log(a.next()); console.log(a.next()); In the above example, we have used an array of numbers and called a function on the array using Symbol.iterator as the index. The output that we get using the next() on the array is as follows − {value: 4, done: false} {value: 7, done: false} {value: 3, done: false} {value: 10, done: false} {value: undefined, done: true} The output gives an object with value and is done as properties. Every next() method call gives the next value from the array and is done as false. The value of done will be true only when the elements from the array are done. We can use this for iterating over arrays. There are more options available like the for-of loop which is used as follows − let numbers = [4, 7, 3, 10]; for (let n of numbers) { console.log(n); } 4 7 3 10 When the for-of loop uses the key, it gives details of the array values as shown above. We will check both the combinations and see how babeljs transpiles them to es5. let numbers = [4, 7, 3, 10]; let a = numbers[Symbol.iterator](); console.log(a.next()); console.log(a.next()); console.log(a.next()); console.log(a.next()); console.log(a.next()); let _array = [4, 7, 3, 10]; for (let n of _array) { console.log(n); } npx babel iterator.js --out-file iterator_es5.js "use strict"; var numbers = [4, 7, 3, 10]; var a = numbers[Symbol.iterator](); console.log(a.next()); console.log(a.next()); console.log(a.next()); console.log(a.next()); console.log(a.next()); var _array = [4, 7, 3, 10]; var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; try { for (var _iterator = _array[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var n = _step.value; console.log(n); } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator.return) { _iterator.return(); } } finally { if (_didIteratorError) { throw _iteratorError; } } } There are changes added for-of loop in es5. But iterator.next is left as it is. We need to use babel-polyfill to make it work in old browsers. Babel-polyfill gets installed along with babel and the same can be used from node_modules as shown below − <html> <head> <script type="text/javascript" src="node_modules/babel-polyfill/dist/polyfill.min.js"></script> <script type="text/javascript" src="iterator_es5.js"></script> </head> <body> <h1>Iterators</h1> </body> </html> Destructuring property behaves like a JavaScript expression which unpacks values from arrays, objects. Following example will explain the working of destructuring syntax. let x, y, rem; [x, y] = [10, 20]; console.log(x); console.log(y); [x, y, ...rem] = [10, 20, 30, 40, 50]; console.log(rem); let z = 0; ({ x, y } = (z) ? { x: 10, y: 20 } : { x: 1, y: 2 }); console.log(x); console.log(y); 10 20 [30, 40, 50] 1 2 The above line of code shows how values are assigned from the right side of the array to the variables on the left side. The variable with ...rem gets all the remaining values from the array. We can also assign the values from the object on the left side using conditional operator as shown below − ({ x, y } = (z) ? { x: 10, y: 20 } : { x: 1, y: 2 }); console.log(x); // 1 console.log(y); // 2 Let us convert the same to ES5 using babeljs − npx babel destructm.js --out-file destruct_es5.js "use strict"; var x = void 0, y = void 0, rem = void 0; x = 10; y = 20; console.log(x); console.log(y); x = 10; y = 20; rem = [30, 40, 50]; console.log(rem); var z = 0; var _ref = z ? { x: 10, y: 20 } : { x: 1, y: 2 }; x = _ref.x; y = _ref.y; console.log(x); console.log(y); Template literal is a string literal which allows expressions inside it. It uses backtick(``) instead of single or double quotes. When we say expression inside a string, it means we can use variables, call a function, etc. inside the string. let a = 5; let b = 10; console.log(`Using Template literal : Value is ${a + b}.`); console.log("Using normal way : Value is " + (a + b)); Using Template literal : Value is 15. Using normal way : Value is 15 let a = 5; let b = 10; console.log(`Using Template literal : Value is ${a + b}.`); console.log("Using normal way : Value is " + (a + b)); npx babel templateliteral.js --out-file templateliteral_es5.js "use strict"; var a = 5; var b = 10; console.log("Using Template literal : Value is " + (a + b) + "."); console.log("Using normal way : Value is " + (a + b)); In es6, the new features added to object literals are very good and useful. We will go through few examples of object literal in ES5 and ES6 − ES5 var red = 1, green = 2, blue = 3; var rgbes5 = { red: red, green: green, blue: blue }; console.log(rgbes5); // {red: 1, green: 2, blue: 3} ES6 let rgbes6 = { red, green, blue }; console.log(rgbes6); // {red: 1, green: 2, blue: 3} If you see the above code, the object in ES5 and ES6 differs. In ES6, we do not have to specify the key value if the variable names are same as the key. Let us see the compilation to ES5 using babel. const red = 1, green = 2, blue = 3; let rgbes5 = { red: red, green: green, blue: blue }; console.log(rgbes5); let rgbes6 = { red, green, blue }; console.log(rgbes6); let brand = "carbrand"; const cars = { [brand]: "BMW" } console.log(cars.carbrand); //"BMW" npx babel enhancedobjliteral.js --out-file enhancedobjliteral_es5.js "use strict"; function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } var red = 1, green = 2, blue = 3; var rgbes5 = { red: red, green: green, blue: blue }; console.log(rgbes5); var rgbes6 = { red: red, green: green, blue: blue }; console.log(rgbes6); var brand = "carbrand"; var cars = _defineProperty({}, brand, "BMW"); console.log(cars.carbrand); //"BMW" In this section, we will discuss the default, rest and spread properties. With ES6, we can use default parameters to the function params as follows − let add = (a, b = 3) => { return a + b; } console.log(add(10, 20)); // 30 console.log(add(10)); // 13 Let us transpile the above code to ES5 using babel. npx babel default.js --out-file default_es5.js "use strict"; var add = function add(a) { var b = arguments.length > 1 >> arguments[1] !== undefined ? arguments[1] : 3; return a + b; }; console.log(add(10, 20)); console.log(add(10)); Rest parameter starts with three dots(...) as shown in the example below − let add = (...args) => { let sum = 0; args.forEach(function (n) { sum += n; }); return sum; }; console.log(add(1, 2)); // 3 console.log(add(1, 2, 5, 6, 6, 7)); //27 In the above function we are passing n number of params to the function add. To add all those params if it was in ES5, we have to rely on arguments object to get the details of the arguments. With ES6, rest it helps to define the arguments with three dots as shown above and we can loop through it and get the sum of the numbers. Note − We cannot use additional arguments when using three dot, i.e., rest. let add = (...args, value) => { //syntax error let sum = 0; args.forEach(function (n) { sum += n; }); return sum; }; The above code will give syntax error. The compilation to es5 looks as follows − npx babel rest.js --out-file rest_es5.js "use strict"; var add = function add() { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } var sum = 0; args.forEach(function (n) { sum += n; }); return sum; }; console.log(add(1, 2)); console.log(add(1, 2, 5, 6, 6, 7)); The Spread property also has the three dots like rest. Following is a working example, which shows how to use the spread property. let add = (a, b, c) => { return a + b + c; } let arr = [11, 23, 3]; console.log(add(...arr)); //37 Let us now see how the above code is transpiled using babel − npx babel spread.js --out-file spread_es5.js "use strict"; var add = function add(a, b, c) { return a + b + c; }; var arr = [11, 23, 3]; console.log(add.apply(undefined, arr)); Proxy is an object where you can define custom behaviour for operations like property lookup, assignment, enumeration, function, invocation, etc. var a = new Proxy(target, handler); Both target and handler are objects. target is an object or can be another proxy element. target is an object or can be another proxy element. handler will be an object with its properties as functions which will give the behaviour when called. handler will be an object with its properties as functions which will give the behaviour when called. Let us try to understand these features with the help of an example − let handler = { get: function (target, name) { return name in target ? target[name] : "invalid key"; } }; let o = { name: 'Siya Kapoor', addr: 'Mumbai' } let a = new Proxy(o, handler); console.log(a.name); console.log(a.addr); console.log(a.age); We have defined target and handler in the above example and used it with proxy. Proxy returns the object with key-values. Siya Kapoor Mumbai invalid key Let us now see how to transpile the above code to ES5 using babel − npx babel proxy.js --out-file proxy_es5.js 'use strict'; var handler = { get: function get(target, name) { return name in target ? target[name] : "invalid key"; } }; var o = { name: 'Siya Kapoor', addr: 'Mumbai' }; var a = new Proxy(o, handler); console.log(a.name); console.log(a.addr); console.log(a.age); In this chapter, we will see how to transpile ES6 modules to ES5 using Babel. Consider a scenario where parts of JavaScript code need to be reused. ES6 comes to your rescue with the concept of Modules. A module is nothing more than a chunk of JavaScript code written in a file. The functions or variables in a module are not available for use, unless the module file exports them. In simpler terms, the modules help you to write the code in your module and expose only those parts of the code that should be accessed by other parts of your code. Let us consider an example to understand how to use module and how to export it to make use of it in the code. add.js var add = (x,y) => { return x+y; } module.exports=add; multiply.js var multiply = (x,y) => { return x*y; }; module.exports = multiply; main.js import add from './add'; import multiply from './multiply' let a = add(10,20); let b = multiply(40,10); console.log("%c"+a,"font-size:30px;color:green;"); console.log("%c"+b,"font-size:30px;color:green;"); I have three files add.js that adds 2 given numbers, multiply.js that multiplies two given numbers and main.js, which calls add and multiply, and consoles the output. To give add.js and multiply.js in main.js, we have to export it first as shown below − module.exports = add; module.exports = multiply; To use them in main.js, we need to import them as shown below import add from './add'; import multiply from './multiply' We need module bundler to build the files, so that we can execute them in the browser. We can do that − Using Webpack Using Gulp In this section, we will see what the ES6 modules are. We will also learn how to use webpack. Before we start, we need to install the following packages − npm install --save-dev webpack npm install --save-dev webpack-dev-server npm install --save-dev babel-core npm install --save-dev babel-loader npm install --save-dev babel-preset-env We have added pack and publish tasks to scripts to run them using npm. Here is the webpack.config.js file which will build the final file. var path = require('path'); module.exports = { entry: { app: './src/main.js' }, output: { path: path.resolve(__dirname, 'dev'), filename: 'main_bundle.js' }, mode:'development', module: { rules: [ { test: /\.js$/, include: path.resolve(__dirname, 'src'), loader: 'babel-loader', query: { presets: ['env'] } } ] } }; Run the command npm run pack to build the files. The final file will be stored in the dev/ folder. npm run pack dev/main_bundle.js common file is created. This file combines add.js, multiply.js and main.js and stores it in dev/main_bundle.js. /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // create a fake namespace object /******/ // mode & 1: value is a module id, require it /******/ // mode & 2: merge all properties of value into the ns /******/ // mode & 4: return value when already ns object /******/ // mode & 8|1: behave like require /******/ __webpack_require__.t = function(value, mode) { /******/ if(mode & 1) value = __webpack_require__(value); /******/ if(mode & 8) return value; /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; /******/ var ns = Object.create(null); /******/ __webpack_require__.r(ns); /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); /******/ return ns; /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = "./src/main.js"); /******/ }) /************************************************************************/ /******/ ({ /***/ "./src/add.js": /*!********************!*\ !*** ./src/add.js ***! \********************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; eval( "\n\nvar add = function add(x, y) {\n return x + y;\n}; \n\nmodule.exports = add; \n\n//# sourceURL = webpack:///./src/add.js?" ); /***/ }), /***/ "./src/main.js": /*!*********************!*\ !*** ./src/main.js ***! \*********************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; eval( "\n\nvar _add = __webpack_require__(/*! ./add */ \"./src/add.js\"); \n\nvar _add2 = _interopRequireDefault(_add); \n\nvar _multiply = __webpack_require__(/*! ./multiply */ \"./src/multiply.js\"); \n\nvar _multiply2 = _interopRequireDefault(_multiply); \n\nfunction _interopRequireDefault(obj) { return obj &gt;&gt; obj.__esModule ? obj : { default: obj }; } \n\nvar a = (0, _add2.default)(10, 20); \nvar b = (0, _multiply2.default)(40, 10); \n\nconsole.log(\"%c\" + a, \"font-size:30px;color:green;\"); \nconsole.log(\"%c\" + b, \"font-size:30px;color:green;\"); \n\n//# sourceURL = webpack:///./src/main.js?" ); /***/ }), /***/ "./src/multiply.js": /*!*************************!*\ !*** ./src/multiply.js ***! \*************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; eval( "\n\nvar multiply = function multiply(x, y) {\n return x * y;\n}; \n\nmodule.exports = multiply; \n\n//# sourceURL = webpack:///./src/multiply.js?" ); /***/ }) /******/ }); Following is the command to test the output in browser − npm run publish Add index.html in your project. This calls dev/main_bundle.js. <html> <head></head> <body> <script type="text/javascript" src="dev/main_bundle.js"></script> </body> </html> To use Gulp to bundle the modules into one file, we will use browserify and babelify. First, we will create project setup and install the required packages. npm init Before we start with the project setup, we need to install the following packages − npm install --save-dev gulp npm install --save-dev babelify npm install --save-dev browserify npm install --save-dev babel-preset-env npm install --save-dev babel-core npm install --save-dev gulp-connect npm install --save-dev vinyl-buffer npm install --save-dev vinyl-source-stream Let us now create the gulpfile.js, which will help run the task to bundle the modules together. We will use the same files used above with webpack. add.js var add = (x,y) => { return x+y; } module.exports=add; multiply.js var multiply = (x,y) => { return x*y; }; module.exports = multiply; main.js import add from './add'; import multiply from './multiply' let a = add(10,20); let b = multiply(40,10); console.log("%c"+a,"font-size:30px;color:green;"); console.log("%c"+b,"font-size:30px;color:green;"); The gulpfile.js is created here. A user will browserfiy and use tranform to babelify. babel-preset-env is used to transpile the code to es5. Gulpfile.js const gulp = require('gulp'); const babelify = require('babelify'); const browserify = require('browserify'); const connect = require("gulp-connect"); const source = require('vinyl-source-stream'); const buffer = require('vinyl-buffer'); gulp.task('build', () => { browserify('src/main.js') .transform('babelify', { presets: ['env'] }) .bundle() .pipe(source('main.js')) .pipe(buffer()) .pipe(gulp.dest('dev/')); }); gulp.task('default', ['es6'],() => { gulp.watch('src/app.js',['es6']) }); gulp.task('watch', () => { gulp.watch('./*.js', ['build']); }); gulp.task("connect", function () { connect.server({ root: ".", livereload: true }); }); gulp.task('start', ['build', 'watch', 'connect']); We use browserify and babelify to take care of the module export and import and combine the same to one file as follows − gulp.task('build', () => { browserify('src/main.js') .transform('babelify', { presets: ['env'] }) .bundle() .pipe(source('main.js')) .pipe(buffer()) .pipe(gulp.dest('dev/')); }); We have used transform in which babelify is called with the presets env. The src folder with the main.js is given to browserify and saved in the dev folder. We need to run the command gulp start to compile the file − npm start Here is the final file created in the dev/ folder − (function() { function r(e,n,t) { function o(i,f) { if(!n[i]) { if(!e[i]) { var c = "function"==typeof require&&require; if(!f&&c)return c(i,!0);if(u)return u(i,!0); var a = new Error("Cannot find module '"+i+"'"); throw a.code = "MODULE_NOT_FOUND",a } var p = n[i] = {exports:{}}; e[i][0].call( p.exports,function(r) { var n = e[i][1][r]; return o(n||r) } ,p,p.exports,r,e,n,t) } return n[i].exports } for(var u="function"==typeof require>>require,i = 0;i<t.length;i++)o(t[i]);return o } return r })() ({1:[function(require,module,exports) { "use strict"; var add = function add(x, y) { return x + y; }; module.exports = add; },{}],2:[function(require,module,exports) { 'use strict'; var _add = require('./add'); var _add2 = _interopRequireDefault(_add); var _multiply = require('./multiply'); var _multiply2 = _interopRequireDefault(_multiply); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var a = (0, _add2.default)(10, 20); var b = (0, _multiply2.default)(40, 10); console.log("%c" + a, "font-size:30px;color:green;"); console.log("%c" + b, "font-size:30px;color:green;"); }, {"./add":1,"./multiply":3}],3:[function(require,module,exports) { "use strict"; var multiply = function multiply(x, y) { return x * y; }; module.exports = multiply; },{}]},{},[2]); We will use the same in index.html and run the same in the browser to get the output − <html> <head></head> <body> <h1>Modules using Gulp</h1> <script type="text/javascript" src="dev/main.js"></script> </body> </html> In this chapter, we will learn how to transpile ES7 features to ES5. ECMA Script 7 has the following new features added to it − Async-Await Exponentiation Operator Array.prototype.includes() We will compile them to ES5 using babeljs. Depending on your project requirements, it is also possible to compile the code in any ecma version ie ES7 to ES6 or ES7 to ES5. Since ES5 version is the most stable and works fine on all modern and old browsers, we will compile the code to ES5. Async is an asynchronous function, which returns an implicit promise. The promise is either resolved or rejected. Async function is same as a normal standard function. The function can have await expression which pauses the execution till it returns a promise and once it gets it, the execution continues. Await will only work if the function is async. Here is a working example on async and await. let timer = () => { return new Promise(resolve => { setTimeout(() => { resolve("Promise resolved after 5 seconds"); }, 5000); }); }; let out = async () => { let msg = await timer(); console.log(msg); console.log("hello after await"); }; out(); Promise resolved after 5 seconds hello after await The await expression is added before the timer function is called. The timer function will return the promise after 5 seconds. So await will halt the execution until the promise on timer function is resolved or rejected and later continue. Let us now transpile the above code to ES5 using babel. let timer = () => { return new Promise(resolve => { setTimeout(() => { resolve("Promise resolved after 5 seconds"); }, 5000); }); }; let out = async () => { let msg = await timer(); console.log(msg); console.log("hello after await"); }; out(); npx babel asyncawait.js --out-file asyncawait_es5.js "use strict"; var timer = function timer() { return new Promise(function (resolve) { setTimeout(function () { resolve("Promise resolved after 5 seconds"); }, 5000); }); }; var out = async function out() { var msg = await timer(); console.log(msg); console.log("hello after await"); }; out(); Babeljs does not compile object or methods; so here promises used will not be transpiled and will be shown as it is. To support promises on old browsers, we need to add code, which will have support for promises. For now, let us install babel-polyfill as follows − npm install --save babel-polyfill It should be saved as a dependency and not dev-dependency. To run the code in the browser, we will use the polyfill file from node_modules\babel-polyfill\dist\polyfill.min.js and call it using the script tag as shown below − <!DOCTYPE html> <html> <head> <title>BabelJs Testing</title> </head> <body> <script src="node_modules\babel-polyfill\dist\polyfill.min.js" type="text/javascript"></script> <script type="text/javascript" src="aynscawait_es5.js"></script> </body> </html> When you run the above test page, you will see the output in the console as shown below ** is the operator used for exponentiation in ES7. Following example shows the working of the same in ES7 and the code is transpiled using babeljs. let sqr = 9 ** 2; console.log(sqr); 81 let sqr = 9 ** 2; console.log(sqr); To transpile the exponentiation operator, we need to install a plugin to be installed as follows − npm install --save-dev babel-plugin-transform-exponentiation-operator Add the plugin details to .babelrc file as follows − { "presets":[ "es2015" ], "plugins": ["transform-exponentiation-operator"] } npx babel exponeniation.js --out-file exponeniation_es5.js "use strict"; var sqr = Math.pow(9, 2); console.log(sqr); This feature gives true if the element passed to it is present in the array and false if otherwise. let arr1 = [10, 6, 3, 9, 17]; console.log(arr1.includes(9)); let names = ['Siya', 'Tom', 'Jerry', 'Bean', 'Ben']; console.log(names.includes('Tom')); console.log(names.includes('Be')); true true false We have to use babel-polyfill again here as includes is a method on an array and it will not get transpiled. We need additional step to include polyfill to make it work in older browsers. let arr1 = [10, 6, 3, 9, 17]; console.log(arr1.includes(9)); let names = ['Siya', 'Tom', 'Jerry', 'Bean', 'Ben']; console.log(names.includes('Tom')); console.log(names.includes('Be')); npx babel array_include.js --out-file array_include_es5.js 'use strict'; var arr1 = [10, 6, 3, 9, 17]; console.log(arr1.includes(9)); var names = ['Siya', 'Tom', 'Jerry', 'Bean', 'Ben']; console.log(names.includes('Tom')); console.log(names.includes('Be')); To test it in older browser, we need to use polyfill as shown below − <!DOCTYPE html> <html> <head> <title>BabelJs Testing</title> </head> <body> <script src="node_modules\babel-polyfill\dist\polyfill.min.js" type="text/javascript"></script> <script type="text/javascript" src="array_include_es5.js"></script> </body> </html> String padding is the new ES8 feature added to javascript. We will work on simple example, which will transpile string padding to ES5 using babel. String padding adds another string from the left side as per the length specified. The syntax for string padding is as shown below − str.padStart(length, string); str.padEnd(length, string); const str = 'abc'; console.log(str.padStart(8, '_')); console.log(str.padEnd(8, '_')); _____abc abc_____ const str = 'abc'; console.log(str.padStart(8, '_')); console.log(str.padEnd(8, '_')); npx babel strpad.js --out-file strpad_es5.js 'use strict'; var str = 'abc'; console.log(str.padStart(8, '_')); console.log(str.padEnd(8, '_')); The js has to be used along with babel-polyfill as shown below − <!DOCTYPE html> <html> <head> <title>BabelJs Testing</title> </head> <body> <script src="node_modules\babel-polyfill\dist\polyfill.min.js" type="text/javascript"></script> <script type="text/javascript" src="strpad_es5.js"></script> </body> </html> BabelJS is a javascript compiler that changes the syntax of the code given based on presets and plugins available. The flow of babel compilation involves the following 3 parts − parsing transforming printing The code given to babel is given back as it is with just the syntax changed. We have already seen presets being added to .babelrc file to compile code from es6 to es5 or vice-versa. Presets are nothing but a set of plugins. Babel will not change anything if presets or plugins details are not given during compilation. Let us now discuss the following plugins − transform-class-properties Transform-exponentiation-operator For-of object rest and spread async/await Now, we will create a project setup and work on few plugins, which will give clear understanding of the requirements of plugins in babel. npm init We have to install the required packages for babel – babel cli, babel core, babel-preset, etc. npm install babel-cli babel-core babel-preset-es2015 --save-dev npm install @babel/cli @babel/core @babel/preset-env --save-dev Create a js file in your project and write your js code. Observe the codes given below for this purpose − main.js class Person { constructor(fname, lname, age, address) { this.fname = fname; this.lname = lname; this.age = age; this.address = address; } get fullname() { return this.fname + "-" + this.lname; } } var a = new Person("Siya", "Kapoor", "15", "Mumbai"); var persondet = a.fullname; Right now, we have not given any preset or plugin details to babel. If we happen to transpile the code using command − npx babel main.js --out-file main_out.js main_out.js class Person { constructor(fname, lname, age, address) { this.fname = fname; this.lname = lname; this.age = age; this.address = address; } get fullname() { return this.fname + "-" + this.lname; } } var a = new Person("Siya", "Kapoor", "15", "Mumbai"); var persondet = a.fullname; We will get the code as it is. Let us now add preset to .babelrc file. Note − Create .babelrc file inside the root folder of your project. .babelrc for babel 6 .babelrc for babel 7 { "presets":["@babel/env"] } We have already installed the presets; now let us run the command again − npx babel main.js --out-file main_out.js main_out.js "use strict"; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var Person = function () { function Person(fname, lname, age, address) { _classCallCheck(this, Person); this.fname = fname; this.lname = lname; this.age = age; this.address = address; } _createClass(Person, [{ key: "fullname", get: function get() { return this.fname + "-" + this.lname; } }]); return Person; }(); var a = new Person("Siya", "Kapoor", "15", "Mumbai"); var persondet = a.fullname; In ES6, class syntax is as follows class Person { constructor(fname, lname, age, address) { this.fname = fname; this.lname = lname; this.age = age; this.address = address; } get fullname() { return this.fname + "-" + this.lname; } } There is constructor and all the properties of the class are defined inside it. Incase, we need to define class properties outside the class we cannot do so. class Person { name = "Siya Kapoor"; fullname = () => { return this.name; } } var a = new Person(); var persondet = a.fullname(); console.log("%c"+persondet, "font-size:25px;color:red;"); If we happen to compile the above code, it will throw an error in babel. This results in the code not getting compiled. To make this work the way we want, we can make use of babel plugin called babel-plugin-transform-class-properties. To make it work, we need to install it first as follows − npm install --save-dev babel-plugin-transform-class-properties npm install --save-dev @babel/plugin-proposal-class-properties Add the plugin to .babelrc file for babel 6 − .babelrc for babel 7 { "plugins": ["@babel/plugin-proposal-class-properties"] } Now, we will run the command again. npx babel main.js --out-file main_out.js main.js class Person { name = "Siya Kapoor"; fullname = () => { return this.name; } } var a = new Person(); var persondet = a.fullname(); console.log("%c"+persondet, "font-size:25px;color:red;"); Compiled to main_out.js class Person { constructor() { this.name = "Siya Kapoor"; this.fullname = () => { return this.name; }; } } var a = new Person(); var persondet = a.fullname(); console.log("%c"+persondet, "font-size:25px;color:red;"); Output Following is the output we get when used in a browser − ** is the operator used for exponentiation in ES7. Following example shows the working of same in ES7. It also shows how to transpile code using babeljs. let sqr = 9 ** 2; console.log("%c"+sqr, "font-size:25px;color:red;"); To transpile the exponentiation operator, we need a plugin to be installed as follows − Packages for babel 6 npm install --save-dev babel-plugin-transform-exponentiation-operator Packages for babel 7 npm install --save-dev @babel/plugin-transform-exponentiation-operator Add the plugin details to .babelrc file as follows for babel 6 − { "plugins": ["transform-exponentiation-operator"] } .babelrc for babel 7 { "plugins": ["@babel/plugin-transform-exponentiation-operator"] } command npx babel exponeniation.js --out-file exponeniation_out.js exponeniation_out.js let sqr = Math.pow(9, 2); console.log("%c" + sqr, "font-size:25px;color:red;"); Output The packages required for the plugins in babel6 and 7 are as follows − npm install --save-dev babel-plugin-transform-es2015-for-of npm install --save-dev @babel/plugin-transform-for-of .babelrc for babel6 { "plugins": ["transform-es2015-for-of"] } .babelrc for babel7 { "plugins": ["@babel/plugin-transform-for-of"] } forof.js let foo = ["PHP", "C++", "Mysql", "JAVA"]; for (var i of foo) { console.log(i); } npx babel forof.js --out-file forof_es5.js Forof_es5.js let foo = ["PHP", "C++", "Mysql", "JAVA"]; var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; try { for (var _iterator = foo[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var i = _step.value; console.log(i); } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator.return) { _iterator.return(); } } finally { if (_didIteratorError) { throw _iteratorError; } } } Output The packages required for the plugins in babel6 and 7 are as follows − npm install --save-dev babel-plugin-transform-object-rest-spread npm install --save-dev @babel/plugin-proposal-object-rest-spread .babelrc for babel6 { "plugins": ["transform-object-rest-spread"] } .babelrc for babel7 { "plugins": ["@babel/plugin-proposal-object-rest-spread"] } o.js let { x1, y1, ...z1 } = { x1: 11, y1: 12, a: 23, b: 24 }; console.log(x1); console.log(y1); console.log(z1); let n = { x1, y1, ...z1}; console.log(n); npx babel o.js --out-file o_es5.js o_es5.js var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } let _x1$y1$a$b = { x1: 11, y1: 12, a: 23, b: 24 }, { x1, y1 } = _x1$y1$a$b, z1 = _objectWithoutProperties(_x1$y1$a$b, ["x1", "y1"]); console.log(x1); console.log(y1); console.log(z1); let n = _extends({ x1, y1 }, z1); console.log(n); Output We need the following packages to be installed for babel 6 − npm install --save-dev babel-plugin-transform-async-to-generator npm install --save-dev @babel/plugin-transform-async-to-generator .babelrc for babel 6 { "plugins": ["transform-async-to-generator"] } .babelrc for babel 7 { "plugins": ["@babel/plugin-transform-async-to-generator"] } async.js let timer = () => { return new Promise(resolve => { setTimeout(() => { resolve("Promise resolved after 5 seconds"); }, 5000); }); }; let out = async () => { let msg = await timer(); console.log(msg); console.log("hello after await"); }; out(); npx babel async.js --out-file async_es5.js async_es5.js function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; } let timer = () => { return new Promise(resolve => { setTimeout(() => { resolve("Promise resolved after 5 seconds"); }, 5000); }); }; let out = (() => { var _ref = _asyncToGenerator(function* () { let msg = yield timer(); console.log(msg); console.log("hello after await"); }); return function out() { return _ref.apply(this, arguments); }; })(); out(); We have to make use of polyfill for the same as it will not work in browsers where promises are not supported. Output Babel Polyfill adds support to the web browsers for features, which are not available. Babel compiles the code from recent ecma version to the one, which we want. It changes the syntax as per the preset, but cannot do anything for the objects or methods used. We have to use polyfill for those features for backward compatibility. Following is the list of features that need polyfill support when used in older browsers − Promises Map Set Symbol Weakmap Weakset Array.from, Array.includes, Array.of, Array#find, Array.buffer, Array#findIndex Object.assign, Object.entries, Object.values We will create project setup and also see the working of babel polyfill. npm init We will now install the packages required for babel. npm install babel-cli babel-core babel-preset-es2015 --save-dev npm install @babel/cli @babel/core @babel/preset-env --save-dev Here is the final package.json − We will also add es2015 to the presets, as we want to compile the code to es5. .babelrc for babel 6 .babelrc for babel 7 { "presets":["@babel/env"] } We will install a lite-serve so that we can test our code in browser − npm install --save-dev lite-server Let us add babel command to compile our code in package.json − We have also added the build command which calls the lite-server. Babel-polyfill gets installed along with the babel-core package. The babel-polyfill will be available in node modules as shown below − We will further work on promises and use babel-polyfill along with it. let timingpromise = new Promise((resolve, reject) => { setTimeout(function() { resolve("Promise is resolved!"); }, 1000); }); timingpromise.then((msg) => { console.log("%c"+msg, "font-size:25px;color:red;"); }); npx babel promise.js --out-file promise_es5.js "use strict"; var timingpromise = new Promise(function (resolve, reject) { setTimeout(function () { resolve("Promise is resolved!"); }, 1000); }); timingpromise.then(function (msg) { console.log("%c"+msg, "font-size:25px;color:red;"); }); The compilation need not change anything. The code for promise has been transpiled as it is. But browsers which do not support promises will throw an error even though we have compiled the code to es5. To solve this issue, we need to add polyfill along with the final es5 compiled code. To run the code in browser, we will take the babel-polyfill file from node modules and add it to the .html file where we want to use promises as shown below − <html> <head> </head> <body> <h1>Babel Polyfill Testing</h1> <script type="text/javascript" src="node_modules/babel-polyfill/dist/polyfill.min.js"></script> <script type="text/javascript" src="promise_es5.js"></script> </body> </html> In index.html file, we have used the polyfill.min.js file from node_modules followed by promise_es5.js − <script type="text/javascript" src="node_modules/babel-polyfill/dist/polyfill.min.js"></script> <script type="text/javascript" src="promise_es5.js"></script> Note − Polyfill file has to be used at the start before the main javascript call. String padding adds another string from the left side as per the length specified. The syntax for string padding is as shown below − str.padStart(length, string); str.padEnd(length, string); const str = 'abc'; console.log(str.padStart(8, '_')); console.log(str.padEnd(8, '_')); _____abc abc_____ npx babel strpad.js --out-file strpad_es5.js 'use strict'; var str = 'abc'; console.log(str.padStart(8, '_')); console.log(str.padEnd(8, '_')); The js has to be used along with babel-polyfill as shown below − <!DOCTYPE html> <html> <head> <title>BabelJs Testing </title> </head> <body> <script src="node_modules/babel-polyfill/dist/polyfill.min.js" type="text/javascript"></script> <script type="text/javascript" src="strpad_es5.js"></script> </body> </html> In this section, we will learn aboutMap, Set, WeakSet, WeakMap. Map is a object with key / value pair. Map is a object with key / value pair. Set is also a object but with unique values. Set is also a object but with unique values. WeakMap and WeakSet iare also objects with key/value pairs. WeakMap and WeakSet iare also objects with key/value pairs. Map, Set, WeakMap and WeakSet are new features added to ES6. To transpile it to be used in older browsers, we need to make use of polyfill. We will work on an example and use polyfill to compile the code. let m = new Map(); //map example m.set("0","A"); m.set("1","B"); console.log(m); let set = new Set(); //set example set.add('A'); set.add('B'); set.add('A'); set.add('B'); console.log(set); let ws = new WeakSet(); //weakset example let x = {}; let y = {}; ws.add(x); console.log(ws.has(x)); console.log(ws.has(y)); let wm = new WeakMap(); //weakmap example let a = {}; wm.set(a, "hello"); console.log(wm.get(a)); Map(2) {"0" => "A", "1" => "B"} Set(2) {"A", "B"} true false hello npx babel set.js --out-file set_es5.js "use strict"; var m = new Map(); //map example m.set("0", "A"); m.set("1", "B"); console.log(m); var set = new Set(); //set example set.add('A'); set.add('B'); set.add('A'); set.add('B'); console.log(set); var ws = new WeakSet(); //weakset example var x = {}; var y = {}; ws.add(x); console.log(ws.has(x)); console.log(ws.has(y)); var wm = new WeakMap(); //weakmap example var a = {}; wm.set(a, "hello"); console.log(wm.get(a)); The js has to be used along with babel-polyfill as shown below − <!DOCTYPE html> <html> <head> <title>BabelJs Testing</title> </head> <body> <script src="node_modules/babel-polyfill/dist/polyfill.min.js" type="text/javascript"></script> <script type="text/javascript" src="set_es5.js"></script> </body> </html> Many properties and methods can be used on array; for example, array.from, array.includes, etc. Let us consider working on the following example to understand this better. arraymethods.js var arrNum = [1, 2, 3]; console.log(arrNum.includes(2)); console.log(Array.from([3, 4, 5], x => x + x)); Output true [6, 8, 10] npx babel arraymethods.js --out-file arraymethods_es5.js "use strict"; var arrNum = [1, 2, 3]; console.log(arrNum.includes(2)); console.log(Array.from([3, 4, 5], function (x) { return x + x; })); The methods used on the array are printed as they are. To make them work on older browsers, we need to add polyfill file at the start as shown below − <html> <head></head> <body> <h1>Babel Polyfill Testing</h1> <script type="text/javascript" src="node_modules/babel-polyfill/dist/polyfill.min.js"></script> <script type="text/javascript" src="arraymethods_es5.js"></script> </body> </html> BabelJS comes with a built-in Command Line Interface wherein, the JavaScript code can be easily compiled to the respective ECMA Script using easy to use commands. We will discuss the use of these commands in this chapter. First, we will install babel-cli for our project. We will use babeljs for compiling the code. Create a folder for your project to play around with babel-cli. npm init Package.json created for the above project − Let us run the commands to install babel-cli. npm install --save-dev babel-cli npm install --save-dev @babel/cli We have installed babel-cli and here is the updated package.json − In addition to this, we need to install babel-preset and babel-core. Let us now see the command for the installation. npm install --save-dev babel-preset-env npm install --save-dev babel-core npm install --save-dev @babel/core npm install --save-dev @babel/preset-env Here is the updated package.json for the above commands − Since we need to compile to JavaScript code that we are going to write to have backward compatibility, we will compile it to ECMA Script 5. For this, we need to instruct babel to look for the preset, i.e., es version wherein compilation will be done. We need to create a .babelrc> file in the root folder of our project created as shown below. It contains a json object with the following presets details − { "presets": ["env"] } For babel 7 the .babelrc is as follows − { "presets":["@babel/env"] } We have installed babel local to the project. In order to make use of babel in our project, we need to specify the same in package.json as follows − Now we are ready to compile our JavaScript files. Create a folder src in your project; in this folder, create a file called main.js and write a es6 javascript code as shown below − npx babel src/main.js In the above case, the code from main.js is displayed in the terminal in es5 version. The arrow function from es6 is converted to es5 as shown above. Instead of displaying the compiled code in the terminal, we will store it in a different file as shown below. We have created a folder in our project called out wherein, we want the compiled files to be stored. Following is the command which will compile and store the output where we want it. npx babel src/main.js --out-file out/main_out.js The option in the command --out-file helps us store the output in the file location of our choice. Incase we want the file to be updated every time we make changes to the main file add --watch or -w option to the command as shown below. npx babel src/main.js --watch --out-file out/main_out.js You can make the change to the main file; this change will reflect in the compiled file. In the above case, we changed the log message and the --watch option keeps checking for any change and the same changes are added in the compiled file. In our previous sections, we learnt how to compile individual files. Now, we will compile a directory and store the compiled files in another directory. In the src folder, we will create one more js file called main1.js. At present, the src folder has 2 javascript files main.js and main1.js. Following is the code in the files − main.js var arrowfunction = () => { console.log("Added changes to the log message"); } main1.js var handler = () => { console.log("Added one more file"); } Following command will compile code from the src folder and store it in the out/ folder. We have removed all the files from the out/ folder and kept it empty. We will run the command and check the output in the out/ folder. npx babel src --out-dir out We got 2 files in the out folder - main.js and main1.js main.js "use strict"; var arrowfunction = function arrowfunction() { console.log("Added changes to the log message"); }; main1.js "use strict"; var handler = function handler() { console.log("Added one more file"); }; Next, we will execute the command given below to compile both files into a single file using babeljs. npx babel src --out-file out/all.js "use strict"; var arrowfunction = function arrowfunction() { console.log("Added changes to the log message"); }; "use strict"; var handler = function handler() { console.log("Added one more file"); }; In case we want to ignore some files from being compiled, we can use the option --ignore as shown below. npx babel src --out-file out/all.js --ignore src/main1.js all.js "use strict"; var arrowfunction = function arrowfunction() { console.log("Added changes to the log message"); }; We can make use of plugins options to be used during file compilation. To make use of plugins, we need to install it as shown below. npm install --save-dev babel-plugin-transform-exponentiation-operator expo.js let sqr = 9 ** 2; console.log(sqr); npx babel expo.js --out-file expo_compiled.js --plugins=babel-plugin-transform-exponentiation-operator "use strict"; var sqr = Math.pow(9, 2); console.log(sqr); We can also use presets in the command as shown below. npx babel src/main.js --out-file main_es5.js --presets=es2015 To test the above case, we have removed presets option from .babelrc. main.js var arrowfunction = () => { console.log("Added changes to the log message"); } main_es5.js "use strict"; var arrowfunction = function arrowfunction() { console.log("Added changes to the log message"); }; We can also ignore .babelrc from the command line as follows − npx babel --no-babelrc src/main.js --out-file main_es5.js --presets=es2015 To test the above case, we have added presets back to .babelrc and the same will get ignored because of --no-babelrc that we have added in the command. The main_es5.js file details are as follows − main_es5.js "use strict"; var arrowfunction = function arrowfunction() { console.log("Added changes to the log message"); }; Babel presets are config details to the babel-transpiler telling it to transpile it in the specified mode. Here are some of the most popular presets we are going to discuss in this chapter − ES2015 Env React We need to use presets that have the environment in which we want the code to be converted. For example, es2015 preset will convert the code to es5. Preset with value env will also convert to es5. It also has additional feature, i.e., options. In case you want the feature to be supported on recent versions of browsers, babel will convert the code only if there is no support of features on those browsers. With Preset react, Babel will transpile the code when to react. To work with Presets, we need to create .babelrc file in our project root folder. To show the working, we will create a project setup as shown below. npm init We have to install the required babel preset as follows along with babel cli, babel core, etc. npm install babel-cli babel-core babel-preset-es2015 --save-dev npm install @babel/cli @babel/core @babel/preset-env --save-dev Note − babel-preset-es2015 is deprecated babel 7 onwards. es2015 or @babel/env Create .babelrc file in the root of the project (babel 6) − In .babelrc, the presets is es2015. This is the indication to the babel compiler that we want the code to be converted to es2015. For babel 7, we need to use presets as follows − { "presets":["@babel/env"] } Here is the package.json after installation − Since we have installed babel locally, we have added babel command in the scripts section in package.json. Let us work on a simple example to check for the transpiling using preset es2015. main.js let arrow = () => { return "this is es6 arrow function"; } Transpiled to es5 as shown below. npx babel main.js --out-file main_es5.js main_es5.js "use strict"; var arrow = function arrow() { return "this is es6 arrow function"; }; Using Env preset, you can specify the environment you the final code to be transpiled to. We are going to use the same project setup created above and change the presets from es2015 to env as shown below. In addition, we need to install the babel-preset-env. We will execute the command given below to install the same. npm install babel-preset-env --save-dev We will compile main.js again and see the output. main.js let arrow = () => { return "this is es6 arrow function"; } npx babel main.js --out-file main_env.js main_env.js "use strict"; var arrow = function arrow() { return "this is es6 arrow function"; }; We have seen the transpiled code is es5. Incase we know the environment in which our code is going to execute, we can use this preset to specify it. For example, if we specify the browsers as last 1 version for chrome and firefox as shown below. npx babel main.js --out-file main_env.js main_env.js "use strict"; let arrow = () => { return "this is es6 arrow function"; }; We are now getting the arrow function syntax as it is. It is not transpiled into ES5 syntax. This is because the environment which we want our code to support, already has support for the arrow function. Babel takes care of compiling the code based on environment using the babel-preset-env. We can also target the compilation based on the nodejs environment as shown below The final compilation of the code is as shown below. npx babel main.js --out-file main_env.js main_env.js "use strict"; let arrow = () => { return "this is es6 arrow function"; }; Babel compiles the code as per the current version of nodejs. We can use react preset when we are using Reactjs. We will work on a simple example and use react preset to see the output. To use the preset, we need to install babel-preset-react (babel 6) as follows − npm install --save-dev babel-preset-react For babel 7, it is as follows − npm install --save-dev @babel/preset-react Changes to .babelrc are as follows for babel6 − For babel 7 { "presets": ["@babel/preset-react"] } main.js <h1>Hello, world!</h1> npx babel main.js --out-file main_env.js main_env.js React.createElement( "h1", null, "Hello, world!" ); The code from main.js is converted to reactjs syntax with preset:react. Webpack is a module bundler which packs all modules with dependencies – js, styles, images, etc. into static assets .js, .css, .jpg , .png, etc. Webpack comes with presets which help for compilation into the required form. For example, react preset that helps to get the final output in react form, es2015 or env preset that helps to compile the code in ES5 or 6 or 7, etc. We have used babel 6 in the project setup. In case you want to switch to babel7, install the required packages of babel using @babel/babel-package-name. Here, we will discuss project setup using babel and webpack. Create a folder called and open the same in visual studio IDE. To create the project setup, run npm initbabelwebpack as follows − Here is the package.json created after npm init − Now, we will install the necessary packages we need to work with babel and webpack. npm install --save-dev webpack npm install --save-dev webpack-dev-server npm install --save-dev babel-core npm install --save-dev babel-loader npm install --save-dev babel-preset-env Here is the Package.json after installation − Now, we will create a webpack.config.js file, which will have all the details to bundle the js files. These files will be compiled it into es5 using babel. To run webpack using server, we use webpack-server. Following are the details added to it − We have added the publish command which will start the webpack-dev-server and will update the path where the final files are stored. Right now the path that we are going to use to update the final files is the /dev folder. To use webpack, we need to run the following command − npm run publish First we need to create the webpack.config.js files. These will have the configuration details for webpack to work. The details in the file are as follows − var path = require('path'); module.exports = { entry: { app: './src/main.js' }, output: { path: path.resolve(__dirname, 'dev'), filename: 'main_bundle.js' }, mode:'development', module: { rules: [ { test: /\.js$/, include: path.resolve(__dirname, 'src'), loader: 'babel-loader', query: { presets: ['env'] } } ] } }; The structure of the file is as shown above. It starts with theh path, which gives the current path details. var path = require('path'); //gives the current path Next is the module.exports object, which has properties entry, output and module. The entry is the start point. Here, we need to give the main js files that has to be compiled. entry: { app: './src/main.js' }, path.resolve(_dirname, ‘src/main.js’) -- will look for the src folder in the directory and main.js in that folder. output: { path: path.resolve(__dirname, 'dev'), filename: 'main_bundle.js' }, Output is an object with path and filename details. Path will hold the folder in which the compiled file will be kept and filename will tell the name of final file to be used in your .html file. module: { rules: [ { test: /\.js$/, include: path.resolve(__dirname, 'src'), loader: 'babel-loader', query: { presets: ['env'] } } ] } Module is an object with details of the rules. It has the following properties − Module is an object with details of the rules. It has the following properties − test include loader query Test will hold details of all the js files ending with .js. It has the pattern, which will look for .js at the end in the entry point given. Test will hold details of all the js files ending with .js. It has the pattern, which will look for .js at the end in the entry point given. Include instructs the folder in use on the files to be looked at. Include instructs the folder in use on the files to be looked at. Loader uses babel-loader for compiling codes. Loader uses babel-loader for compiling codes. Query has property presets, which is an array with value env – es5 or es6 or es7. Query has property presets, which is an array with value env – es5 or es6 or es7. Create folder src and main.js in it; write your js code in ES6. Later, run the command to see it getting compiled to es5 using webpack and babel. src/main.js let add = (a,b) => { return a+b; }; let c = add(10, 20); console.log(c); Run the command − npm run pack The compiled file looks as follows − dev/main_bundle.js !function(e) { var t = {}; function r(n) { if(t[n])return t[n].exports;var o = t[n] = {i:n,l:!1,exports:{}}; return e[n].call(o.exports,o,o.exports,r),o.l=!0,o.exports } r.m = e,r.c = t,r.d = function(e,t,n) { r.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n}) }, r.r = function(e) { "undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0}) }, r.t = function(e,t) { if(1&t&&(e = r(e)),8&t)return e; if(4&t&&"object"==typeof e&&e&&e.__esModule)return e; var n = Object.create(null); if(r.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)r.d(n,o,function(t) {return e[t]}.bind(null,o)); return n }, r.n = function(e) { var t = e&&e.__esModule?function() {return e.default}:function() {return e}; return r.d(t,"a",t),t }, r.o = function(e,t) {return Object.prototype.hasOwnProperty.call(e,t)}, r.p = "",r(r.s = 0) }([function(e,t,r) {"use strict";var n = function(e,t) {return e+t}(10,20);console.log(n)}]); !function(e) { var t = {}; function r(n) { if(t[n])return t[n].exports; var o = t[n] = {i:n,l:!1,exports:{}}; return e[n].call(o.exports,o,o.exports,r),o.l=!0,o.exports } r.m = e,r.c = t,r.d = function(e,t,n) { r.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n}) }, r.r = function(e) { "undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0}) }, r.t = function(e,t) { if(1&t&&(e=r(e)), 8&t)return e; if(4&t&&"object"==typeof e&&e&&e.__esModule)return e; var n = Object.create(null); if( r.r(n), Object.defineProperty(n,"default",{enumerable:!0,value:e}), 2&t&&"string"!=typeof e ) for(var o in e)r.d(n,o,function(t) {return e[t]}.bind(null,o)); return n }, r.n = function(e) { var t = e&&e.__esModule?function() {return e.default}:function() {return e}; return r.d(t,"a",t),t }, r.o = function(e,t) { return Object.prototype.hasOwnProperty.call(e,t) }, r.p = "",r(r.s = 0) }([function(e,t,r) { "use strict"; var n = function(e,t) {return e+t}(10,20); console.log(n) }]); The code is compiled as shown above. Webpack adds some code which is required internally and the code from main.js is seen at the end. We have consoled the value as shown above. Add the final js file in .html file as follows − <html> <head></head> <body> <script type="text/javascript" src="dev/main_bundle.js"></script> </body> </html> Run the command − npm run publish To check the output, we can open the file in − http://localhost:8080/ We get the console value as shown above. Now let us try to compile to a single file using webpack and babel. We will use webpack to bundle multiple js files into a single file. Babel will be used to compile the es6 code to es5. Now, we have 2 js files in the src/ folder - main.js and Person.js as follows − person.js export class Person { constructor(fname, lname, age, address) { this.fname = fname; this.lname = lname; this.age = age; this.address = address; } get fullname() { return this.fname +"-"+this.lname; } } We have used export to use the details of the Person class. main.js import {Person} from './person' var a = new Person("Siya", "Kapoor", "15", "Mumbai"); var persondet = a.fullname; console.log(persondet); In main.js, we have imported Person from the file path. Note − We do not have to include person.js but just the name of the file. We have created an object of Person class and consoled the details as shown above. Webpack will combine person.js and main.js and update in dev/main_bundle.js as one file. Run the command npm run publish to check the output in the browser − In this chapter, we will understand working with JSX and babel. Before we get into the details, let us understand what JSX is. JSX is a JavaScript code with a combination of xml syntax in it. JSX tag has tag name, attributes and children which make it look like xml. React uses JSX for templating instead of regular JavaScript. It is not necessary to use it, however, following are some pros that come with it. It is faster because it performs optimization while compiling code to JavaScript. It is faster because it performs optimization while compiling code to JavaScript. It is also type-safe and most of the errors can be caught during compilation. It is also type-safe and most of the errors can be caught during compilation. It makes it easier and faster to write templates, if you are familiar with HTML. It makes it easier and faster to write templates, if you are familiar with HTML. We have used babel 6 in the project setup. In case you want to switch to babel 7, install the required packages of babel using @babel/babel-package-name. We will create project setup and use webpack to compile jsx with react to normal JavaScript using Babel. To start the project setup, run the commands given below for babel, react and webpack installation. npm init Now, we will install the necessary packages we need to work with – babel ,webpack and jsx − npm install --save-dev webpack npm install --save-dev webpack-cli npm install --save-dev webpack-dev-server npm install --save-dev babel-core npm install --save-dev babel-loader npm install --save-dev babel-preset-es2015 npm install --save-dev babel-preset-react npm install --save-dev react npm install --save-dev react-dom Here is the package.json after installation − Now will create a webpack.config.js file, which will have all the details to bundle the js files and compile it into es5 using babel. To run webpack using server, there is something called webpack-server. We have added command called publish; this command will start the webpack-dev-server and will update the path where the final files are stored. Right now the path that we are going to use to update the final files is the /dev folder. To use webpack we need to run the following command − npm run publish We will create the webpack.config.js files, which have the configuration details for webpack to work. The details in the file are as follows − var path = require('path'); module.exports = { entry: { app: './src/main.js' }, output: { path: path.resolve(__dirname, 'dev'), filename: 'main_bundle.js' }, mode:'development', module: { rules: [ { test:/\.(js|jsx)$/, include: path.resolve(__dirname, 'src'), loader: 'babel-loader', query: { presets: ['es2015','react'] } } ] } }; The structure of the file is as shown above. It starts with the path, which gives the current path details. var path = require('path'); //gives the current path Next is the module.exports object, which has properties entry, output and module. Entry is the start point. Here we need to give the main js files we want to compile. entry: { app: './src/main.js' }, path.resolve(_dirname, ‘src/main.js’) -- will look for the src folder in the directory and main.js in that folder. output: { path: path.resolve(__dirname, 'dev'), filename: 'main_bundle.js' }, Output is an object with path and filename details. Path will hold the folder in which the compiled file will be kept and filename will tell the name of the final file to be used in your .html file. module: { rules: [ { test:/\.(js|jsx)$/, include: path.resolve(__dirname, 'src'), loader: 'babel-loader', query: { presets: ['es2015','react'] } } ] } Module is object with rules details which has properties ie test, include , loader, query. Module is object with rules details which has properties ie test, include , loader, query. Test will hold details of all the js file ending with .js and .jsx.It has the pattern which will look for .js and .jsx at the end in the entry point given. Test will hold details of all the js file ending with .js and .jsx.It has the pattern which will look for .js and .jsx at the end in the entry point given. Include tells the folder to be used for looking the files. Include tells the folder to be used for looking the files. Loader uses babel-loader for compiling code. Loader uses babel-loader for compiling code. Query has property presets, which is array with value env – es5 or es6 or es7. We have used es2015 and react as the preset. Query has property presets, which is array with value env – es5 or es6 or es7. We have used es2015 and react as the preset. Create folder src/. Add main.js and App.jsx in it. App.jsx import React from 'react'; class App extends React.Component { render() { var style = { color: 'red', fontSize: 50 }; return ( <div style={style}> Hello World!!! </div> ); } } export default App; main.js import React from 'react'; import ReactDOM from 'react-dom'; import App from './App.jsx'; ReactDOM.render(, document.getElementById('app')); Run the following command to bundle the .js file and convert it using presets es2015 and react. npm run pack Add main_bundle.js from the dev folder to index.html − <!DOCTYPE html> <html lang = "en"> <head> <meta charset = "UTF-8"> <title>React App</title> </head> <body> <div id = "app"></div> <script src = "dev/main_bundle.js"></script> </body> </html> npm run publish Flow is a static type checker for JavaScript. To work with flow and babel, we will first create a project setup. We have used babel 6 in the project setup. In case you want to switch to babel 7, install the required packages of babel using @babel/babel-package-name. npm init Install the required packages for flow and babel − npm install --save-dev babel-core babel-cli babel-preset-flow flow-bin babel-plugin-transform-flow-strip-types Here is the final package.json after installation. Also added babel and flow command to execute the code in command line. Create .babelrc inside the project setup and add presets as shown below Create a main.js file and write your JavaScript code using flow − main.js /* @flow */ function concat(a: string, b: string) { return a + b; } let a = concat("A", "B"); console.log(a); Use babel command to compile the code using presets: flow to normal javascript npx babel main.js --out-file main_flow.js main_flow.js function concat(a, b) { return a + b; } let a = concat("A", "B"); console.log(a); We can also make use of plugin called babel-plugin-transform-flow-strip-types instead of presets as follows − In .babelrc, add the plugin as follows − main.js /* @flow */ function concat(a: string, b: string) { return a + b; } let a = concat("A", "B"); console.log(a); npx babel main.js --out-file main_flow.js main_flow.js function concat(a, b) { return a + b; } let a = concat("A", "B"); console.log(a); In this chapter, we will create project setup using babel and gulp. Gulp is a task runner that uses Node.js as a platform. Gulp will run the tasks that will transpile JavaScript files from es6 to es5 and once done will start the server to test the changes. We have used babel 6 in the project setup. In case you want to switch to babel 7, install the required packages of babel using @babel/babel-package-name. We will create the project first using npm commands and install the required packages to start with. npm init We have created a folder called gulpbabel. Further, we will install gulp and other required dependencies. npm install gulp --save-dev npm install gulp-babel --save-dev npm install gulp-connect --save-dev npm install babel-preset-env --save-dev npm install babel-core --save-dev We will add the Preset environment details to .babelrc file as follows gulpfile.js var gulp =require('gulp'); var babel =require('gulp-babel'); var connect = require("gulp-connect"); gulp.task('build', () => { gulp.src('src/./*.js') .pipe(babel()) .pipe(gulp.dest('./dev')) }); gulp.task('watch', () => { gulp.watch('./*.js', ['build']); }); gulp.task("connect", function () { connect.server({ root: ".", livereload: true }); }); gulp.task('start', ['build', 'watch', 'connect']); We have created three task in gulp, [‘build’,’watch’,’connect’]. All the js files available in src folder will be converted to es5 using babel as follows − gulp.task('build', () => { gulp.src('src/./*.js') .pipe(babel()) .pipe(gulp.dest('./dev')) }); The final changes are stored in the dev folder. Babel uses presets details from .babelrc. In case you want to change to some other preset, you can change the details in .babelrc file. Now will create a .js file in src folder using es6 javascript and run gulp start command to execute the changes. src/main.js class Person { constructor(fname, lname, age, address) { this.fname = fname; this.lname = lname; this.age = age; this.address = address; } get fullname() { return this.fname +"-"+this.lname; } } Command: gulp start dev/main.js This is transpiled using babel − "use strict"; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i <props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var Person = function () { function Person(fname, lname, age, address) { _classCallCheck(this, Person); this.fname = fname; this.lname = lname; this.age = age; this.address = address; } _createClass(Person, [{ key: "fullname", get: function get() { return this.fname + "-" + this.lname; } }]); return Person; }(); Index.html This is done using transpiled dev/main.js − <html> <head></head> <body> <script type="text/javascript" src="dev/main.js"></script> <h1 id="displayname"></h1> <script type="text/javascript"> var a = new Student("Siya", "Kapoor", "15", "Mumbai"); var studentdet = a.fullname; document.getElementById("displayname").innerHTML = studentdet; </script> </body> </html> Output We will use ES6 features and create a simple project. Babeljs will be used to compile the code to ES5. The project will have a set of images, which will autoslide after a fixed number of seconds. We will use ES6 class to work on it. We have used babel 6 in the project setup. In case you want to switch to babel 7, install the required packages of babel using @babel/babel-package-name. We will use gulp to build the project. To start with, we will create the project setup as shown below npm init We have created a folder called babelexample. Further, we will install gulp and other required dependencies. npm install gulp --save-dev npm install gulp-babel --save-dev npm install gulp-connect --save-dev npm install babel-preset-env --save-dev Here is the Package.json after installation − We will add the Preset environment details to .babelrc file as follows − Since we need the gulp task to build the final file, we will create gulpfile.js with the task that we need gulpfile.js var gulp = require('gulp'); var babel = require('gulp-babel'); var connect = require("gulp-connect"); gulp.task('build', () => { gulp.src('src/./*.js') .pipe(babel()) .pipe(gulp.dest('./dev')) }); gulp.task('watch', () => { gulp.watch('./*.js', ['build']); }); gulp.task("connect", function () { connect.server({ root: ".", livereload: true }); }); gulp.task('start', ['build', 'watch', 'connect']); We have created three tasks in gulp, [‘build’,’watch’,’connect’]. All the js files available in src folder will be converted to es5 using babel as follows gulp.task('build', () => { gulp.src('src/./*.js') .pipe(babel()) .pipe(gulp.dest('./dev')) }); The final changes are stored in the dev folder. Babel uses presets details from .babelrc. In case you want to change to some other preset, you can change the details in .babelrc file. Now, we will create a .js file in src folder using es6 JavaScript and run gulp start command to execute the changes. The project structure is as follows − src/slidingimage.js class SlidingImage { constructor(width, height, imgcounter, timer) { this.counter = 0; this.imagecontainerwidth = width; this.imagecontainerheight = height; this.slidercounter = imgcounter; this.slidetimer = timer; this.startindex = 1; this.css = this.applycss(); this.maincontainer = this.createContainter(); this.childcontainer = this.imagecontainer(); this.autoslide(); } createContainter() { let maindiv = document.createElement('div'); maindiv.id = "maincontainer"; maindiv.class = "maincontainer"; document.body.appendChild(maindiv); return maindiv; } applycss() { let slidercss = ".maincontainer{ position : relative; margin :auto;}.left, .right { cursor: pointer; position: absolute;" + "top: 50%; width: auto; padding: 16px; margin-top: -22px; color: white; font-weight: bold; " + "font-size: 18px; transition: 0.6s ease; border-radius: 0 3px 3px 0; }.right { right: 0; border-radius: 3px 0 0 3px;}" + ".left:hover, .right:hover { background-color: rgba(0,0,0,0.8);}"; let style = document.createElement('style'); style.id = "slidercss"; style.type = "text/css"; document.getElementsByTagName("head")[0].appendChild(style); let styleall = style; if (styleall.styleSheet) { styleall.styleSheet.cssText = slidercss; } else { let text = document.createTextNode(slidercss); style.appendChild(text); } } imagecontainer() { let childdiv = []; let imgcont = []; for (let a = 1; a >= this.slidercounter; a++) { childdiv[a] = document.createElement('div'); childdiv[a].id = "childdiv" + a; childdiv[a].style.width = this.imagecontainerwidth + "px"; childdiv[a].style.height = this.imagecontainerheight + "px"; if (a > 1) { childdiv[a].style.display = "none"; } imgcont[a] = document.createElement('img'); imgcont[a].src = "src/img/img" + a + ".jpg"; imgcont[a].style.width = "100%"; imgcont[a].style.height = "100%"; childdiv[a].appendChild(imgcont[a]); this.maincontainer.appendChild(childdiv[a]); } } autoslide() { console.log(this.startindex); let previousimg = this.startindex; this.startindex++; if (this.startindex > 5) { this.startindex = 1; } setTimeout(() => { document.getElementById("childdiv" + this.startindex).style.display = ""; document.getElementById("childdiv" + previousimg).style.display = "none"; this.autoslide(); }, this.slidetimer); } } let a = new SlidingImage(300, 250, 5, 5000); We will create img/ folder in src/ as we need images to be displayed; these images are to rotate every 5 seconds.The dev/ folder will store the compiled code. Run the gulp start to build the final file. The final project structure is as shown below − In slidingimage.js, we have created a class called SlidingImage, which has methods like createcontainer, imagecontainer, and autoslide, which creates the main container and adds images to it. The autoslide method helps in changing the image after the specified time interval. let a = new SlidingImage(300, 250, 5, 5000); At this stage, the class is called. We will pass width, height, number of images and number of seconds to rotate the image. gulp start dev/slidingimage.js "use strict"; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var SlidingImage = function () { function SlidingImage(width, height, imgcounter, timer) { _classCallCheck(this, SlidingImage); this.counter = 0; this.imagecontainerwidth = width; this.imagecontainerheight = height; this.slidercounter = imgcounter; this.slidetimer = timer; this.startindex = 1; this.css = this.applycss(); this.maincontainer = this.createContainter(); this.childcontainer = this.imagecontainer(); this.autoslide(); } _createClass(SlidingImage, [{ key: "createContainter", value: function createContainter() { var maindiv = document.createElement('div'); maindiv.id = "maincontainer"; maindiv.class = "maincontainer"; document.body.appendChild(maindiv); return maindiv; } }, { key: "applycss", value: function applycss() { var slidercss = ".maincontainer{ position : relative; margin :auto;}.left, .right { cursor: pointer; position: absolute;" + "top: 50%; width: auto; padding: 16px; margin-top: -22px; color: white; font-weight: bold; " + "font-size: 18px; transition: 0.6s ease; border-radius: 0 3px 3px 0; } .right { right: 0; border-radius: 3px 0 0 3px;}" + ".left:hover, .right:hover { background-color: rgba(0,0,0,0.8);}"; var style = document.createElement('style'); style.id = "slidercss"; style.type = "text/css"; document.getElementsByTagName("head")[0].appendChild(style); var styleall = style; if (styleall.styleSheet) { styleall.styleSheet.cssText = slidercss; } else { var text = document.createTextNode(slidercss); style.appendChild(text); } } }, { key: "imagecontainer", value: function imagecontainer() { var childdiv = []; var imgcont = []; for (var _a = 1; _a <= this.slidercounter; _a++) { childdiv[_a] = document.createElement('div'); childdiv[_a].id = "childdiv" + _a; childdiv[_a].style.width = this.imagecontainerwidth + "px"; childdiv[_a].style.height = this.imagecontainerheight + "px"; if (_a > 1) { childdiv[_a].style.display = "none"; } imgcont[_a] = document.createElement('img'); imgcont[_a].src = "src/img/img" + _a + ".jpg"; imgcont[_a].style.width = "100%"; imgcont[_a].style.height = "100%"; childdiv[_a].appendChild(imgcont[_a]); this.maincontainer.appendChild(childdiv[_a]); } } }, { key: "autoslide", value: function autoslide() { var _this = this; console.log(this.startindex); var previousimg = this.startindex; this.startindex++; if (this.startindex > 5) { this.startindex = 1; } setTimeout(function () { document.getElementById("childdiv" + _this.startindex).style.display = ""; document.getElementById("childdiv" + previousimg).style.display = "none"; _this.autoslide(); }, this.slidetimer); } }]); return SlidingImage; }(); var a = new SlidingImage(300, 250, 5, 5000); We will test the line of code in browser as shown below − index.html <html> <head></head> <body> <script type="text/javascript" src="dev/slidingimage.js"></script> <h1>Sliding Image Demo</h1> </body> </html> We have used the compiled file from the dev folder in index.html. The command gulp start starts the server where we can test the output. The code compiled works fine in all browsers.
[ { "code": null, "e": 2452, "s": 2229, "text": "BabelJS is a JavaScript transpiler which transpiles new features into old standard. With this, the features can be run on both old and new browsers, hassle-free. An Australian developer, Sebastian McKenzie started BabelJS." }, { "code": null, "e": 2783, "s": 2452, "text": "JavaScript is the language that the browser understands. We use different browsers to run our applications − Chrome, Firefox, Internet Explorer, Microsoft Edge, Opera, UC browser etc. ECMA Script is the JavaScript language specification; the ECMA Script 2015 ES6 is the stable version which works fine in all new and old browsers." }, { "code": null, "e": 3102, "s": 2783, "text": "After ES5, we have had ES6, ES7, and ES8. ES6 released with a lot of new features which are not fully supported by all browsers. The same applies to ES7, ES8 and ESNext (next version of ECMA Script). It is now uncertain when it will be possible for all browsers to be compatible with all the ES versions that released." }, { "code": null, "e": 3439, "s": 3102, "text": "Incase we plan to use ES6 or ES7 or ES8 features to write our code it will tend to break in some old browsers because of lack of support of the new changes. Therefore, if we want to use new features of ECMA Script in our code and want to run it on all possible browsers available, we need a tool that will compile our final code in ES5." }, { "code": null, "e": 3859, "s": 3439, "text": "Babel does the same and it is called a transpiler that transpiles the code in the ECMA Script version that we want. It has features like presets and plugins, which configure the ECMA version we need to transpile our code. With Babel, developers can write their code using the new features in JavaScript. The users can get the codes transpiled using Babel; the codes can later be used in any browsers without any issues." }, { "code": null, "e": 3935, "s": 3859, "text": "The following table lists down the features available in ES6, ES7 and ES8 −" }, { "code": null, "e": 3977, "s": 3935, "text": "BabelJS manages the following two parts −" }, { "code": null, "e": 3989, "s": 3977, "text": "transpiling" }, { "code": null, "e": 4001, "s": 3989, "text": "polyfilling" }, { "code": null, "e": 4337, "s": 4001, "text": "Babel-transpiler converts the syntax of modern JavaScript into a form, which can be easily understood by older browsers. For example, arrow function, const, let classes will be converted to function, var, etc. Here the syntax, i.e., the arrow function is converted to a normal function keeping the functionality same in both the cases." }, { "code": null, "e": 4655, "s": 4337, "text": "There are new features added in JavaScript like promises, maps and includes. The features can be used on array; the same, when used and transpiled using babel will not get converted. In case the new feature is a method or object, we need to use Babel-polyfill along with transpiling to make it work on older browsers." }, { "code": null, "e": 4762, "s": 4655, "text": "Here is the list of ECMA Script features available in JavaScript, which can be transpiled and polyfilled −" }, { "code": null, "e": 4770, "s": 4762, "text": "Classes" }, { "code": null, "e": 4781, "s": 4770, "text": "Decorators" }, { "code": null, "e": 4787, "s": 4781, "text": "Const" }, { "code": null, "e": 4795, "s": 4787, "text": "Modules" }, { "code": null, "e": 4807, "s": 4795, "text": "Destructing" }, { "code": null, "e": 4826, "s": 4807, "text": "Default parameters" }, { "code": null, "e": 4850, "s": 4826, "text": "Computed property names" }, { "code": null, "e": 4869, "s": 4850, "text": "Object rest/spread" }, { "code": null, "e": 4885, "s": 4869, "text": "Async functions" }, { "code": null, "e": 4901, "s": 4885, "text": "Arrow functions" }, { "code": null, "e": 4917, "s": 4901, "text": "Rest parameters" }, { "code": null, "e": 4924, "s": 4917, "text": "Spread" }, { "code": null, "e": 4942, "s": 4924, "text": "Template Literals" }, { "code": null, "e": 4988, "s": 4942, "text": "ECMA Script features that can be polyfilled −" }, { "code": null, "e": 4997, "s": 4988, "text": "Promises" }, { "code": null, "e": 5001, "s": 4997, "text": "Map" }, { "code": null, "e": 5005, "s": 5001, "text": "Set" }, { "code": null, "e": 5012, "s": 5005, "text": "Symbol" }, { "code": null, "e": 5020, "s": 5012, "text": "Weakmap" }, { "code": null, "e": 5028, "s": 5020, "text": "Weakset" }, { "code": null, "e": 5038, "s": 5028, "text": "includess" }, { "code": null, "e": 5100, "s": 5038, "text": "Array.from, Array.of,Array#find,Array.buffer, Array#findIndex" }, { "code": null, "e": 5143, "s": 5100, "text": "Object.assign,Object.entries,Object.values" }, { "code": null, "e": 5275, "s": 5143, "text": "In this section, we will learn about the different features of BabelJS. Following are the most important core features of BabelJS −" }, { "code": null, "e": 5474, "s": 5275, "text": "Plugins and Presets are config details for Babel to transpile the code. Babel supports a number of plugins, which can be used individually, if we know the environment in which the code will execute." }, { "code": null, "e": 5758, "s": 5474, "text": "Babel presets are a set of plugins, i.e., config details to the babel-transpiler that instruct Babel to transpile in a specific mode. We need to use presets, which has the environment in which we want the code to be converted. For example, es2015 preset will convert the code to es5." }, { "code": null, "e": 6049, "s": 5758, "text": "There are some features like methods and objects, which cannot be transpiled. At such instances, we can make use of babel-polyfill to facilitate the use of features in any browser. Let us consider the example of promises; for the feature to work in older browsers, we need to use polyfills." }, { "code": null, "e": 6277, "s": 6049, "text": "Babel-cli comes with a bunch of commands where the code can be easily compiled on the command line. It also has features like plugins and presets to be used along with the command making it easy to transpile the code at one go." }, { "code": null, "e": 6376, "s": 6277, "text": "In this section, we will learn about the different advantages associated with the use of BabelJS −" }, { "code": null, "e": 6495, "s": 6376, "text": "BabelJS provides backward compatibility to all the newly added features to JavaScript and can be used in any browsers." }, { "code": null, "e": 6614, "s": 6495, "text": "BabelJS provides backward compatibility to all the newly added features to JavaScript and can be used in any browsers." }, { "code": null, "e": 6724, "s": 6614, "text": "BabelJS has the ability to transpile to take the next upcoming version of JavaScript - ES6, ES7, ESNext, etc." }, { "code": null, "e": 6834, "s": 6724, "text": "BabelJS has the ability to transpile to take the next upcoming version of JavaScript - ES6, ES7, ESNext, etc." }, { "code": null, "e": 6997, "s": 6834, "text": "BabelJS can be used along with gulp, webpack, flow, react, typescript, etc. making it very powerful and can be used with big project making developer’s life easy." }, { "code": null, "e": 7160, "s": 6997, "text": "BabelJS can be used along with gulp, webpack, flow, react, typescript, etc. making it very powerful and can be used with big project making developer’s life easy." }, { "code": null, "e": 7240, "s": 7160, "text": "BabelJS also works along with react JSX syntax and can be compiled in JSX form." }, { "code": null, "e": 7320, "s": 7240, "text": "BabelJS also works along with react JSX syntax and can be compiled in JSX form." }, { "code": null, "e": 7420, "s": 7320, "text": "BabelJS has support for plugins, polyfills, babel-cli that makes it easy to work with big projects." }, { "code": null, "e": 7520, "s": 7420, "text": "BabelJS has support for plugins, polyfills, babel-cli that makes it easy to work with big projects." }, { "code": null, "e": 7604, "s": 7520, "text": "In this section, we will learn about the different disadvantages of using BabelJS −" }, { "code": null, "e": 7728, "s": 7604, "text": "BabelJS code changes the syntax while transpiling which makes the code difficult to understand when released on production." }, { "code": null, "e": 7852, "s": 7728, "text": "BabelJS code changes the syntax while transpiling which makes the code difficult to understand when released on production." }, { "code": null, "e": 7924, "s": 7852, "text": "The code transpiled is more in size when compared to the original code." }, { "code": null, "e": 7996, "s": 7924, "text": "The code transpiled is more in size when compared to the original code." }, { "code": null, "e": 8123, "s": 7996, "text": "Not all ES6/7/8 or the upcoming new features can be transpiled and we have to use polyfill so that it works on older browsers." }, { "code": null, "e": 8250, "s": 8123, "text": "Not all ES6/7/8 or the upcoming new features can be transpiled and we have to use polyfill so that it works on older browsers." }, { "code": null, "e": 8308, "s": 8250, "text": "Here is the official site of babeljs https://babeljs.io/." }, { "code": null, "e": 8382, "s": 8308, "text": "In this section, we will learn how to set up the environment for BabelJS." }, { "code": null, "e": 8429, "s": 8382, "text": "To work with BabelJS we need following setup −" }, { "code": null, "e": 8436, "s": 8429, "text": "NodeJS" }, { "code": null, "e": 8440, "s": 8436, "text": "Npm" }, { "code": null, "e": 8450, "s": 8440, "text": "Babel-CLI" }, { "code": null, "e": 8463, "s": 8450, "text": "Babel-Preset" }, { "code": null, "e": 8484, "s": 8463, "text": "IDE for writing code" }, { "code": null, "e": 8643, "s": 8484, "text": "To check if nodejs is installed on your system, type node –v in the terminal. This will help you see the version of nodejs currently installed on your system." }, { "code": null, "e": 8827, "s": 8643, "text": "If it does not print anything, install nodejs on your system. To install nodejs, go to the homepage https://nodejs.org/en/download/ of nodejs and install the package based on your OS." }, { "code": null, "e": 8888, "s": 8827, "text": "The following screenshot shows the download page of nodejs −" }, { "code": null, "e": 9112, "s": 8888, "text": "Based on your OS, install the required package. Once nodejs is installed, npm will also be installed along with it. To check if npm is installed or not, type npm –v in the terminal. It should display the version of the npm." }, { "code": null, "e": 9203, "s": 9112, "text": "Babel comes with a built-in command line interface, which can be used to compile the code." }, { "code": null, "e": 9362, "s": 9203, "text": "Create a directory wherein you would be working. Here, we have created directory called babelproject. Let us make use of nodejs to create the project details." }, { "code": null, "e": 9423, "s": 9362, "text": "We have used npm init to create the project as shown below −" }, { "code": null, "e": 9470, "s": 9423, "text": "Here is the project structure that we created." }, { "code": null, "e": 9564, "s": 9470, "text": "Now to work with Babel we need to instal Babel cli, Babel preset, Babel core as shown below −" }, { "code": null, "e": 9617, "s": 9564, "text": "Execute the following command to install babel-cli −" }, { "code": null, "e": 9651, "s": 9617, "text": "npm install --save-dev babel-cli\n" }, { "code": null, "e": 9707, "s": 9651, "text": "Execute the following command to install babel-preset −" }, { "code": null, "e": 9748, "s": 9707, "text": "npm install --save-dev babel-preset-env\n" }, { "code": null, "e": 9802, "s": 9748, "text": "Execute the following command to install babel-core −" }, { "code": null, "e": 9837, "s": 9802, "text": "npm install --save-dev babel-core\n" }, { "code": null, "e": 9906, "s": 9837, "text": "After installation, here are the details available in package.json −" }, { "code": null, "e": 10156, "s": 9906, "text": "We have installed babel plugins local to the project. This is done so that we can use babel differently on our projects based on the project requirements and also different versions of babeljs. Package.json gives the version details of babeljs used." }, { "code": null, "e": 10259, "s": 10156, "text": "In order to make use of babel in our project, we need to specify the same in package.json as follows −" }, { "code": null, "e": 10424, "s": 10259, "text": "Babel is mainly used to compile JavaScript code, which will have backward compatibility. Now, we will write our code in ES6 -> ES5 or ES7 -> ES5 also ES7->ES6, etc." }, { "code": null, "e": 10619, "s": 10424, "text": "To provide instructions to Babel on the same, while executing, we need to create a file called .babelrc in the root folder. It contains a json object with details of the presets as shown below −" }, { "code": null, "e": 10764, "s": 10619, "text": "We will create the JavaScript file index.js and compile it to es2015 using Babel. Before that, we need to install the es2015 preset as follows −" }, { "code": null, "e": 10912, "s": 10764, "text": "In index.js, we have created a function using the arrow function which is a new feature added in es6. Using Babel, we will compile the code to es5." }, { "code": null, "e": 10962, "s": 10912, "text": "To execute to es2015, following command is used −" }, { "code": null, "e": 10982, "s": 10962, "text": "npx babel index.js\n" }, { "code": null, "e": 11035, "s": 10982, "text": "It displays the index.js code in es5 as shown above." }, { "code": null, "e": 11113, "s": 11035, "text": "We can store the output in the file by executing the command as shown below −" }, { "code": null, "e": 11157, "s": 11113, "text": "npx babel index.js --out-file index_es5.js\n" }, { "code": null, "e": 11206, "s": 11157, "text": "Here is the file that we created, index_es5.js −" }, { "code": null, "e": 11538, "s": 11206, "text": "BabelJS is a JavaScript transpiler, which converts new features added to JavaScript into ES5 or to react based on the preset or plugin given. ES5 is one of the oldest form of JavaScript and is supported to run on new and old browsers without any issues. In most of the examples in this tutorial, we have transpiled the code to ES5." }, { "code": null, "e": 12144, "s": 11538, "text": "We have seen many features like arrow functions, classes, promises, generators, async functions, etc. added to ES6, ES7 and ES8. When any of the newly added features are used in old browsers, it throws errors. BabelJS helps in compiling the code, which is backward compatible with older browsers. We have seen that ES5 works perfectly fine on older browsers without any issues. So considering the project environment details, if it is required to be running on older browsers, we can use any new feature in our project and compile the code to ES5 using babeljs, and use it any browsers without any issues." }, { "code": null, "e": 12202, "s": 12144, "text": "Let us consider the following example to understand this." }, { "code": null, "e": 12374, "s": 12202, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>BabelJs Testing</title>\n </head>\n <body>\n <script type=\"text/javascript\" src=\"index.js\"></script>\n </body>\n</html>" }, { "code": null, "e": 12436, "s": 12374, "text": "var _foo = () => {\n return \"Hello World\"\n};\n\nalert(_foo());" }, { "code": null, "e": 12516, "s": 12436, "text": "When we run the above html in the Chrome browser, we get the following output −" }, { "code": null, "e": 12585, "s": 12516, "text": "When the HTML is run in Firefox, it generates the following output −" }, { "code": null, "e": 12679, "s": 12585, "text": "And when the same HTML is run in Internet Explorer, it generates the following syntax error −" }, { "code": null, "e": 12862, "s": 12679, "text": "We have used the ES6 Arrow function; the same does not work on all browsers as seen above. To get this working, we have BabelJS to compile the code to ES5 and use it in all browsers." }, { "code": null, "e": 12941, "s": 12862, "text": "Will compile the js file to es5 using babeljs and check again in the browsers." }, { "code": null, "e": 12997, "s": 12941, "text": "In html file, we will use index_new.js as shown below −" }, { "code": null, "e": 13173, "s": 12997, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>BabelJs Testing</title>\n </head>\n <body>\n <script type=\"text/javascript\" src=\"index_new.js\"></script>\n </body>\n</html>" }, { "code": null, "e": 13261, "s": 13173, "text": "\"use strict\";\n\nvar _foo = function _foo() {\n return \"Hello World\";\n};\n\nalert(_foo());" }, { "code": null, "e": 13414, "s": 13261, "text": "In this chapter, we will see how to use babeljs inside our project. We will create a project using nodejs and use http local server to test our project." }, { "code": null, "e": 13474, "s": 13414, "text": "In this section, we will learn how to create project setup." }, { "code": null, "e": 13551, "s": 13474, "text": "Create a new directory and run the following command to create the project −" }, { "code": null, "e": 13561, "s": 13551, "text": "npm init\n" }, { "code": null, "e": 13628, "s": 13561, "text": "Upon execution, the above command generates the following output −" }, { "code": null, "e": 13676, "s": 13628, "text": "Following is the package.json that is created −" }, { "code": null, "e": 13838, "s": 13676, "text": "We will install the packages required to start working with babeljs. We will execute the following command to install babel-cli, babel-core, babel-preset-es2015." }, { "code": null, "e": 13903, "s": 13838, "text": "npm install babel-cli babel-core babel-preset-es2015 --save-dev\n" }, { "code": null, "e": 13970, "s": 13903, "text": "Upon execution, the above command generates the following output −" }, { "code": null, "e": 14007, "s": 13970, "text": "Package.json is updated as follows −" }, { "code": null, "e": 14103, "s": 14007, "text": "We need http server to test the js file. Execute the following command to install http server −" }, { "code": null, "e": 14139, "s": 14103, "text": "npm install lite-server --save-dev\n" }, { "code": null, "e": 14193, "s": 14139, "text": "We have added the following details in package.json −" }, { "code": null, "e": 14482, "s": 14193, "text": "In scripts, Babel takes care of transpiling the scripts.js from src folder and saves it in dev folder with name scripts.bundle.js. We have added the full command to compile the code we want in package.json. In addition, build is added which will start the lite-server to test the changes." }, { "code": null, "e": 14533, "s": 14482, "text": "The src/scripts.js has the JavaScript as follows −" }, { "code": null, "e": 14772, "s": 14533, "text": "class Student {\n constructor(fname, lname, age, address) {\n this.fname = fname;\n this.lname = lname;\n this.age = age;\n this.address = address;\n }\n\n get fullname() {\n return this.fname +\"-\"+this.lname;\n }\n}" }, { "code": null, "e": 14836, "s": 14772, "text": "We have called the transpiled script in index.html as follows −" }, { "code": null, "e": 15232, "s": 14836, "text": "<html>\n lt;head></head>\n <body>\n <script type=\"text/javascript\" src=\"dev/scripts.bundle.js?a=11\"></script>\n <h1 id=\"displayname\"></h1>\n <script type=\"text/javascript\">\n var a = new Student(\"Siya\", \"Kapoor\", \"15\", \"Mumbai\");\n var studentdet = a.fullname;\n document.getElementById(\"displayname\").innerHTML = studentdet;\n </script>\n </body>\n</html>" }, { "code": null, "e": 15362, "s": 15232, "text": "We need to run the following command, which will call babel and compile the code. The command will call Babel from package.json −" }, { "code": null, "e": 15377, "s": 15362, "text": "npm run babel\n" }, { "code": null, "e": 15442, "s": 15377, "text": "The scripts.bundle.js is the new js file created in dev folder −" }, { "code": null, "e": 15494, "s": 15442, "text": "The output of dev/scripts.bundle.js is as follows −" }, { "code": null, "e": 16726, "s": 15494, "text": "\"use strict\";\n\nvar _createClass = function () {\n function defineProperties(target, props) {\n for (var i = 0; i < props.length; i++) {\n var descriptor = props[i];\n descriptor.enumerable = descriptor.enumerable || false;\n descriptor.configurable = true;\n if (\"value\" in descriptor) descriptor.writable = true;\n Object.defineProperty(target, descriptor.key, descriptor); \n }\n }\n return function (Constructor, protoProps, staticProps) {\n if (protoProps) defineProperties(Constructor.prototype, protoProps);\n if (staticProps) defineProperties(Constructor, staticProps);\n return Constructor; \n };\n}();\n\nfunction _classCallCheck(instance, Constructor) { \n if (!(instance instanceof Constructor)) {\n throw new TypeError(\"Cannot call a class as a function\");\n }\n}\n\nvar Student = function () {\n function Student(fname, lname, age, address) {\n _classCallCheck(this, Student);\n\n this.fname = fname;\n this.lname = lname;\n this.age = age;\n this.address = address;\n }\n\n _createClass(Student, [{\n key: \"fullname\",\n get: function get() {\n return this.fname + \"-\" + this.lname;\n }\n }]);\n\n return Student;\n}();" }, { "code": null, "e": 16785, "s": 16726, "text": "Now let us run the following command to start the server −" }, { "code": null, "e": 16800, "s": 16785, "text": "npm run build\n" }, { "code": null, "e": 16861, "s": 16800, "text": "When the command runs, it will open the url in the browser −" }, { "code": null, "e": 16912, "s": 16861, "text": "The above command generates the following output −" }, { "code": null, "e": 17230, "s": 16912, "text": "The latest version of Babel, 7 released with changes to the already existing packages. The installation part remains the same as it was for Babel 6. The only difference in Babel 7 is that all the packages need to be installed with @babel/, for example @babel/core, @babel/preset-env, @babel/cli, @babel/polyfill, etc." }, { "code": null, "e": 17277, "s": 17230, "text": "Here is a project setup created using babel 7." }, { "code": null, "e": 17336, "s": 17277, "text": "Execute the following command to start the project setup −" }, { "code": null, "e": 17346, "s": 17336, "text": "npm init\n" }, { "code": null, "e": 17457, "s": 17346, "text": "npm install --save-dev @babel/core\nnpm install --save-dev @babel/cli\nnpm install --save-dev @babel/preset-env\n" }, { "code": null, "e": 17492, "s": 17457, "text": "Here is the package.json created −" }, { "code": null, "e": 17545, "s": 17492, "text": "Now will create a .babelrc file in the root folder −" }, { "code": null, "e": 17634, "s": 17545, "text": "Create a folder src/ and add file main.js to it and write your code to transpile to es5." }, { "code": null, "e": 17672, "s": 17634, "text": "let add = (a,b) => {\n return a+b;\n}" }, { "code": null, "e": 17718, "s": 17672, "text": "npx babel src/main.js --out-file main_es5.js\n" }, { "code": null, "e": 17784, "s": 17718, "text": "\"use strict\";\n\nvar add = function add(a, b) {\n return a + b;\n};" }, { "code": null, "e": 17897, "s": 17784, "text": "The working of Babel 7 remains the same as Babel 6. The only difference is the pacakge installation with @babel." }, { "code": null, "e": 17968, "s": 17897, "text": "There are some presets deprecated in babel 7. The list is as follows −" }, { "code": null, "e": 17983, "s": 17968, "text": "ES20xx presets" }, { "code": null, "e": 18000, "s": 17983, "text": "babel-preset-env" }, { "code": null, "e": 18020, "s": 18000, "text": "babel-preset-latest" }, { "code": null, "e": 18043, "s": 18020, "text": "Stage presets in Babel" }, { "code": null, "e": 18166, "s": 18043, "text": "Also the year from the packages is removed - @babel/plugin-transform-es2015-classes is now @babel/plugin-transform-classes" }, { "code": null, "e": 18297, "s": 18166, "text": "We will see one more example of working with typescript and transpile it to Es2015 JavaScript using typescript preset and babel 7." }, { "code": null, "e": 18378, "s": 18297, "text": "To work with typescript, we need typescript package to be installed as follows −" }, { "code": null, "e": 18427, "s": 18378, "text": "npm install --save-dev @babel/preset-typescript\n" }, { "code": null, "e": 18506, "s": 18427, "text": "Create test.ts file in the src/ folder and write the code in typescript form −" }, { "code": null, "e": 18592, "s": 18506, "text": "let getName = (person: string) => {\n return \"Hello, \" + person;\n}\n\ngetName(\"Siya\");" }, { "code": null, "e": 18634, "s": 18592, "text": "npx babel src/test.ts --out-file test.js\n" }, { "code": null, "e": 18741, "s": 18634, "text": "\"use strict\";\n\nvar getName = function getName(person) {\n return \"Hello, \" + person;\n};\n\ngetName(\"Siya\");" }, { "code": null, "e": 18866, "s": 18741, "text": "In this chapter, we will see the features added to ES6. We will also learn how to compile the features to ES5 using BabelJS." }, { "code": null, "e": 18944, "s": 18866, "text": "Following are the various ES6 features that we will discuss in this chapter −" }, { "code": null, "e": 18956, "s": 18944, "text": "Let + Const" }, { "code": null, "e": 18972, "s": 18956, "text": "Arrow Functions" }, { "code": null, "e": 18980, "s": 18972, "text": "Classes" }, { "code": null, "e": 18989, "s": 18980, "text": "Promises" }, { "code": null, "e": 19000, "s": 18989, "text": "Generators" }, { "code": null, "e": 19014, "s": 19000, "text": "Destructuring" }, { "code": null, "e": 19024, "s": 19014, "text": "Iterators" }, { "code": null, "e": 19043, "s": 19024, "text": "Template Literalst" }, { "code": null, "e": 19059, "s": 19043, "text": "Enhanced Object" }, { "code": null, "e": 19093, "s": 19059, "text": "Default, Rest & Spread Properties" }, { "code": null, "e": 19211, "s": 19093, "text": "Let declares a block scope local variable in JavaScript. Consider the following example to understand the use of let." }, { "code": null, "e": 19287, "s": 19211, "text": "let a = 1;\nif (a == 1) {\n let a = 2;\n console.log(a);\n}\nconsole.log(a);" }, { "code": null, "e": 19292, "s": 19287, "text": "2\n1\n" }, { "code": null, "e": 19579, "s": 19292, "text": "The reason the first console prints 2 is because a is declared again using let and will be available only in the if block. Any variable declared using let is just available within the declared block. We have declared variable a twice using let, but it does not overwrite the value of a." }, { "code": null, "e": 19781, "s": 19579, "text": "This is the difference between var and let keywords. When you declare variable using var, the variable will be available within the scope of the function or if declared will act like a global variable." }, { "code": null, "e": 19998, "s": 19781, "text": "Incase a variable is declared with let, the variable is available within the block scope. If declared inside the if statement, it will be available only within the if block. The same applies to switch, for-loop, etc." }, { "code": null, "e": 20056, "s": 19998, "text": "We will now see the code conversion in ES5 using babeljs." }, { "code": null, "e": 20111, "s": 20056, "text": "Let us run the following command to convert the code −" }, { "code": null, "e": 20151, "s": 20111, "text": "npx babel let.js --out-file let_es5.js\n" }, { "code": null, "e": 20214, "s": 20151, "text": "The output from es6 to es5 for the let keyword is as follows −" }, { "code": null, "e": 20290, "s": 20214, "text": "let a = 1;\nif (a == 1) {\n let a = 2;\n console.log(a);\n}\nconsole.log(a);" }, { "code": null, "e": 20383, "s": 20290, "text": "\"use strict\";\n\nvar a = 1;\nif (a == 1) {\n var _a = 2;\n console.log(_a);\n}\nconsole.log(a);" }, { "code": null, "e": 20575, "s": 20383, "text": "If you see the ES5 code the let keyword is replaced with the var keyword. Also the variable inside the if block is renamed to _a to have the same effect as when declared with the let keyword." }, { "code": null, "e": 20896, "s": 20575, "text": "In this section, we will learn about the working of const keyword in ES6 and ES5. Const keyword is also available within the scope; and if outside, it will throw an error. The value of const declared variable cannot be changed once assigned. Let us consider the following example to understand how const keyword is used." }, { "code": null, "e": 20959, "s": 20896, "text": "let a =1;\nif (a == 1) {\n const age = 10;\n}\nconsole.log(age);" }, { "code": null, "e": 21013, "s": 20959, "text": "Uncaught ReferenceError: age is not defined at :5:13\n" }, { "code": null, "e": 21132, "s": 21013, "text": "The above output throws an error as the const age is defined inside the if block and is available within the if block." }, { "code": null, "e": 21188, "s": 21132, "text": "We will understand the conversion to ES5 using BabelJS." }, { "code": null, "e": 21251, "s": 21188, "text": "let a =1;\nif (a == 1) {\n const age = 10;\n}\nconsole.log(age);" }, { "code": null, "e": 21295, "s": 21251, "text": "npx babel const.js --out-file const_es5.js\n" }, { "code": null, "e": 21373, "s": 21295, "text": "\"use strict\";\n\nvar a = 1;\nif (a == 1) {\n var _age = 10;\n}\nconsole.log(age);" }, { "code": null, "e": 21451, "s": 21373, "text": "Incase of ES5, const keyword is replaced with the var keyword as shown above." }, { "code": null, "e": 21694, "s": 21451, "text": "An Arrow function has a shorter syntax in comparison to the variable expression. it is also called the fat arrow function or lambda function. The function does not have its own this property. In this function, the keyword function is omitted." }, { "code": null, "e": 21767, "s": 21694, "text": "var add = (x,y) => {\n return x+y;\n}\n\nvar k = add(3,6);\nconsole.log(k);" }, { "code": null, "e": 21770, "s": 21767, "text": "9\n" }, { "code": null, "e": 21826, "s": 21770, "text": "Using BabelJS, we will transpile the above code to ES5." }, { "code": null, "e": 21899, "s": 21826, "text": "var add = (x,y) => {\n return x+y;\n}\n\nvar k = add(3,6);\nconsole.log(k);" }, { "code": null, "e": 21959, "s": 21899, "text": "npx babel arrowfunction.js --out-file arrowfunction_es5.js\n" }, { "code": null, "e": 22051, "s": 21959, "text": "Using Babel the arrow function is converted to variable expression function as shown below." }, { "code": null, "e": 22153, "s": 22051, "text": "\"use strict\";\n\nvar add = function add(x, y) {\n return x + y;\n};\n\nvar k = add(3, 6);\nconsole.log(k);" }, { "code": null, "e": 22451, "s": 22153, "text": "ES6 comes with the new Classes feature. Classes are similar to the prototype based inheritance available in ES5.The class keyword is used to define the class. Classes are like special functions and have similarities like function expression. It has a constructor, which is called inside the class." }, { "code": null, "e": 22771, "s": 22451, "text": "class Person {\n constructor(fname, lname, age, address) {\n this.fname = fname;\n this.lname = lname;\n this.age = age;\n this.address = address;\n }\n\n get fullname() {\n return this.fname +\"-\"+this.lname;\n }\n}\nvar a = new Person(\"Siya\", \"Kapoor\", \"15\", \"Mumbai\");\nvar persondet = a.fullname;" }, { "code": null, "e": 22784, "s": 22771, "text": "Siya-Kapoor\n" }, { "code": null, "e": 23104, "s": 22784, "text": "class Person {\n constructor(fname, lname, age, address) {\n this.fname = fname;\n this.lname = lname;\n this.age = age;\n this.address = address;\n }\n\n get fullname() {\n return this.fname +\"-\"+this.lname;\n }\n}\nvar a = new Person(\"Siya\", \"Kapoor\", \"15\", \"Mumbai\");\nvar persondet = a.fullname;" }, { "code": null, "e": 23148, "s": 23104, "text": "npx babel class.js --out-file class_es5.js\n" }, { "code": null, "e": 23326, "s": 23148, "text": "There is extra code added using babeljs to get the functionality working for classes same as in ES5.BabelJs makes sure the functionality works same as it would have done in ES6." }, { "code": null, "e": 24633, "s": 23326, "text": "\"use strict\";\n\nvar _createClass = function () {\n function defineProperties(target, props) {\n for (var i = 0; i < props.length; i++) {\n var descriptor = props[i];\n descriptor.enumerable = descriptor.enumerable || false;\n descriptor.configurable = true;\n if (\"value\" in descriptor) descriptor.writable = true;\n Object.defineProperty(target, descriptor.key, descriptor);\n }\n }\n return function (Constructor, protoProps, staticProps) {\n if (protoProps) defineProperties(Constructor.prototype, protoProps);\n if (staticProps) defineProperties(Constructor, staticProps);\n return Constructor;\n };\n}();\n\nfunction _classCallCheck(instance, Constructor) {\n if (!(instance instanceof Constructor)) {\n throw new TypeError(\"Cannot call a class as a function\");\n }\n}\n\nvar Person = function () {\n function Person(fname, lname, age, address) {\n _classCallCheck(this, Person);\n\n this.fname = fname;\n this.lname = lname;\n this.age = age;\n this.address = address;\n }\n\n _createClass(Person, [{\n key: \"fullname\",\n get: function get() {\n return this.fname + \"-\" + this.lname;\n }\n }]);\n\n return Person;\n}();\n\nvar a = new Person(\"Siya\", \"Kapoor\", \"15\", \"Mumbai\");\nvar persondet = a.fullname;" }, { "code": null, "e": 24708, "s": 24633, "text": "JavaScript promises are used to manage asynchronous requests in your code." }, { "code": null, "e": 24995, "s": 24708, "text": "It makes life easier and keeps code clean as you manage multiple callbacks from async requests, which have dependency. Promises provide a better way of working with callback functions. Promises are part of ES6. By default, when you create a promise, the state of the promise is pending." }, { "code": null, "e": 25027, "s": 24995, "text": "Promises come in three states −" }, { "code": null, "e": 25051, "s": 25027, "text": "pending (initial state)" }, { "code": null, "e": 25085, "s": 25051, "text": "resolved (completed successfully)" }, { "code": null, "e": 25102, "s": 25085, "text": "rejected(failed)" }, { "code": null, "e": 25278, "s": 25102, "text": "new Promise() is used to construct a promise. Promise constructor has one argument, which is a callback function. The callback function has two arguments - resolve and reject;" }, { "code": null, "e": 25435, "s": 25278, "text": "both these are internal functions. The asynchronous code which you write, i.e., Ajax call, image loading, timing functions will go in the callback function." }, { "code": null, "e": 25598, "s": 25435, "text": "If the task performed in the callback function is a success, then the resolve function is called; otherwise, the reject function is called with the error details." }, { "code": null, "e": 25658, "s": 25598, "text": "The following line of code shows a promise structure call −" }, { "code": null, "e": 26138, "s": 25658, "text": "var _promise = new Promise (function(resolve, reject) {\n var success = true;\n if (success) {\n resolve(\"success\");\n } else {\n reject(\"failure\");\n }\n});\n_promise.then(function(value) {\n //once function resolve gets called it comes over here with the value passed in resolve\n console.log(value); //success\n}).catch(function(value) {\n //once function reject gets called it comes over here with the value passed in reject\n console.log(value); // failure.\n});" }, { "code": null, "e": 26332, "s": 26138, "text": "let timingpromise = new Promise((resolve, reject) => {\n setTimeout(function() {\n resolve(\"Promise is resolved!\");\n }, 1000);\n});\n\ntimingpromise.then((msg) => {\n console.log(msg);\n});" }, { "code": null, "e": 26354, "s": 26332, "text": "Promise is resolved!\n" }, { "code": null, "e": 26548, "s": 26354, "text": "let timingpromise = new Promise((resolve, reject) => {\n setTimeout(function() {\n resolve(\"Promise is resolved!\");\n }, 1000);\n});\n\ntimingpromise.then((msg) => {\n console.log(msg);\n});" }, { "code": null, "e": 26596, "s": 26548, "text": "npx babel promise.js --out-file promise_es5.js\n" }, { "code": null, "e": 26818, "s": 26596, "text": "\"use strict\";\n\nvar timingpromise = new Promise(function (resolve, reject) {\n setTimeout(function () {\n resolve(\"Promise is resolved!\");\n }, 1000);\n});\n\ntimingpromise.then(function (msg) {\n console.log(msg);\n});" }, { "code": null, "e": 27010, "s": 26818, "text": "For promises, the code is not changing when transpiled. We need to use babel-polyfill for it to work on older browsers.The details on babel-polyfills are explained in babel - poyfill chapter." }, { "code": null, "e": 27541, "s": 27010, "text": "Generator function is like normal function. The function has special syntax function* with * to the function and yield keyword to be used inside the function. This is meant to pause or start the function when required. Normal functions cannot be stopped in between once the execution starts. It will either execute the full function or halt when it encounters the return statement. Generator performs differently here, you can halt the function with the yield keyword and start it by calling the generator again whenever required." }, { "code": null, "e": 27681, "s": 27541, "text": "function* generatorfunction(a) {\n yield a;\n yield a +1 ;\n}\n\nlet g = generatorfunction(8);\nconsole.log(g.next());\nconsole.log(g.next());" }, { "code": null, "e": 27730, "s": 27681, "text": "{value: 8, done: false}\n{value: 9, done: false}\n" }, { "code": null, "e": 27870, "s": 27730, "text": "function* generatorfunction(a) {\n yield a;\n yield a +1 ;\n}\n\nlet g = generatorfunction(8);\nconsole.log(g.next());\nconsole.log(g.next());" }, { "code": null, "e": 27922, "s": 27870, "text": "npx babel generator.js --out-file generator_es5.js\n" }, { "code": null, "e": 28565, "s": 27922, "text": "\"use strict\";\n\nvar _marked = /*#__PURE__*/regeneratorRuntime.mark(generatorfunction);\n\nfunction generatorfunction(a) {\n return regeneratorRuntime.wrap(function generatorfunction$(_context) {\n while (1) {\n switch (_context.prev = _context.next) {\n case 0:\n _context.next = 2;\n return a;\n\n case 2:\n _context.next = 4;\n return a + 1;\n \n case 4:\n case \"end\":\n return _context.stop();\n }\n }\n }, _marked, this);\n}\n\nvar g = generatorfunction(8);\nconsole.log(g.next());\nconsole.log(g.next());" }, { "code": null, "e": 28830, "s": 28565, "text": "Iterator in JavaScript gives back a JavaScript object, which has value. The object also has a flag called done, which has true/false value. It gives false if it is not the end of the iterator. Let us consider an example and see the working of iterator on an array." }, { "code": null, "e": 29010, "s": 28830, "text": "let numbers = [4, 7, 3, 10];\nlet a = numbers[Symbol.iterator]();\nconsole.log(a.next());\nconsole.log(a.next());\nconsole.log(a.next());\nconsole.log(a.next());\nconsole.log(a.next());" }, { "code": null, "e": 29136, "s": 29010, "text": "In the above example, we have used an array of numbers and called a function on the array using Symbol.iterator as the index." }, { "code": null, "e": 29205, "s": 29136, "text": "The output that we get using the next() on the array is as follows −" }, { "code": null, "e": 29334, "s": 29205, "text": "{value: 4, done: false}\n{value: 7, done: false}\n{value: 3, done: false}\n{value: 10, done: false}\n{value: undefined, done: true}\n" }, { "code": null, "e": 29685, "s": 29334, "text": "The output gives an object with value and is done as properties. Every next() method call gives the next value from the array and is done as false. The value of done will be true only when the elements from the array are done. We can use this for iterating over arrays. There are more options available like the for-of loop which is used as follows −" }, { "code": null, "e": 29760, "s": 29685, "text": "let numbers = [4, 7, 3, 10];\nfor (let n of numbers) {\n console.log(n);\n}" }, { "code": null, "e": 29770, "s": 29760, "text": "4\n7\n3\n10\n" }, { "code": null, "e": 29938, "s": 29770, "text": "When the for-of loop uses the key, it gives details of the array values as shown above. We will check both the combinations and see how babeljs transpiles them to es5." }, { "code": null, "e": 30192, "s": 29938, "text": "let numbers = [4, 7, 3, 10];\nlet a = numbers[Symbol.iterator]();\nconsole.log(a.next());\nconsole.log(a.next());\nconsole.log(a.next());\nconsole.log(a.next());\nconsole.log(a.next());\n\nlet _array = [4, 7, 3, 10];\nfor (let n of _array) {\n console.log(n);\n}" }, { "code": null, "e": 30242, "s": 30192, "text": "npx babel iterator.js --out-file iterator_es5.js\n" }, { "code": null, "e": 31080, "s": 30242, "text": "\"use strict\";\n\nvar numbers = [4, 7, 3, 10];\nvar a = numbers[Symbol.iterator]();\nconsole.log(a.next());\nconsole.log(a.next());\nconsole.log(a.next());\nconsole.log(a.next());\nconsole.log(a.next());\n\nvar _array = [4, 7, 3, 10];\nvar _iteratorNormalCompletion = true;\nvar _didIteratorError = false;\nvar _iteratorError = undefined;\n\ntry {\n for (var _iterator = _array[Symbol.iterator](),\n _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done);\n _iteratorNormalCompletion = true) {\n var n = _step.value;\n\n console.log(n);\n }\n} catch (err) {\n _didIteratorError = true;\n _iteratorError = err;\n} finally {\n try {\n if (!_iteratorNormalCompletion && _iterator.return) {\n _iterator.return();\n }\n } finally {\n if (_didIteratorError) {\n throw _iteratorError;\n }\n }\n}\n" }, { "code": null, "e": 31330, "s": 31080, "text": "There are changes added for-of loop in es5. But iterator.next is left as it is. We need to use babel-polyfill to make it work in old browsers. Babel-polyfill gets installed along with babel and the same can be used from node_modules as shown below −" }, { "code": null, "e": 31583, "s": 31330, "text": "<html>\n <head>\n <script type=\"text/javascript\" src=\"node_modules/babel-polyfill/dist/polyfill.min.js\"></script>\n <script type=\"text/javascript\" src=\"iterator_es5.js\"></script>\n </head>\n <body>\n <h1>Iterators</h1>\n </body>\n</html>" }, { "code": null, "e": 31686, "s": 31583, "text": "Destructuring property behaves like a JavaScript expression which unpacks values from arrays, objects." }, { "code": null, "e": 31754, "s": 31686, "text": "Following example will explain the working of destructuring syntax." }, { "code": null, "e": 31976, "s": 31754, "text": "let x, y, rem;\n[x, y] = [10, 20];\n\nconsole.log(x);\nconsole.log(y);\n[x, y, ...rem] = [10, 20, 30, 40, 50];\nconsole.log(rem);\n\nlet z = 0;\n({ x, y } = (z) ? { x: 10, y: 20 } : { x: 1, y: 2 });\nconsole.log(x);\nconsole.log(y);" }, { "code": null, "e": 32000, "s": 31976, "text": "10\n20\n[30, 40, 50]\n1\n2\n" }, { "code": null, "e": 32192, "s": 32000, "text": "The above line of code shows how values are assigned from the right side of the array to the variables on the left side. The variable with ...rem gets all the remaining values from the array." }, { "code": null, "e": 32299, "s": 32192, "text": "We can also assign the values from the object on the left side using conditional operator as shown below −" }, { "code": null, "e": 32395, "s": 32299, "text": "({ x, y } = (z) ? { x: 10, y: 20 } : { x: 1, y: 2 });\nconsole.log(x); // 1\nconsole.log(y); // 2" }, { "code": null, "e": 32442, "s": 32395, "text": "Let us convert the same to ES5 using babeljs −" }, { "code": null, "e": 32493, "s": 32442, "text": "npx babel destructm.js --out-file destruct_es5.js\n" }, { "code": null, "e": 32781, "s": 32493, "text": "\"use strict\";\n\nvar x = void 0,\n y = void 0,\n rem = void 0;\nx = 10;\ny = 20;\n\nconsole.log(x);\nconsole.log(y);\nx = 10;\ny = 20;\nrem = [30, 40, 50];\n\nconsole.log(rem);\n\nvar z = 0;\n\nvar _ref = z ? { x: 10, y: 20 } : { x: 1, y: 2 };\n\nx = _ref.x;\ny = _ref.y;\n\nconsole.log(x);\nconsole.log(y);" }, { "code": null, "e": 33023, "s": 32781, "text": "Template literal is a string literal which allows expressions inside it. It uses backtick(``) instead of single or double quotes. When we say expression inside a string, it means we can use variables, call a function, etc. inside the string." }, { "code": null, "e": 33161, "s": 33023, "text": "let a = 5;\nlet b = 10;\nconsole.log(`Using Template literal : Value is ${a + b}.`);\nconsole.log(\"Using normal way : Value is \" + (a + b));" }, { "code": null, "e": 33231, "s": 33161, "text": "Using Template literal : Value is 15.\nUsing normal way : Value is 15\n" }, { "code": null, "e": 33369, "s": 33231, "text": "let a = 5;\nlet b = 10;\nconsole.log(`Using Template literal : Value is ${a + b}.`);\nconsole.log(\"Using normal way : Value is \" + (a + b));" }, { "code": null, "e": 33433, "s": 33369, "text": "npx babel templateliteral.js --out-file templateliteral_es5.js\n" }, { "code": null, "e": 33594, "s": 33433, "text": "\"use strict\";\n\nvar a = 5;\nvar b = 10;\nconsole.log(\"Using Template literal : Value is \" + (a + b) + \".\");\n\nconsole.log(\"Using normal way : Value is \" + (a + b));" }, { "code": null, "e": 33737, "s": 33594, "text": "In es6, the new features added to object literals are very good and useful. We will go through few examples of object literal in ES5 and ES6 −" }, { "code": null, "e": 33990, "s": 33737, "text": "ES5\nvar red = 1, green = 2, blue = 3;\nvar rgbes5 = {\n red: red,\n green: green,\n blue: blue\n};\nconsole.log(rgbes5); // {red: 1, green: 2, blue: 3}\n\nES6\nlet rgbes6 = {\n red,\n green,\n blue\n};\nconsole.log(rgbes6); // {red: 1, green: 2, blue: 3}" }, { "code": null, "e": 34143, "s": 33990, "text": "If you see the above code, the object in ES5 and ES6 differs. In ES6, we do not have to specify the key value if the variable names are same as the key." }, { "code": null, "e": 34190, "s": 34143, "text": "Let us see the compilation to ES5 using babel." }, { "code": null, "e": 34472, "s": 34190, "text": "const red = 1, green = 2, blue = 3;\nlet rgbes5 = {\n red: red,\n green: green,\n blue: blue\n};\nconsole.log(rgbes5);\n\nlet rgbes6 = {\n red,\n green,\n blue\n};\nconsole.log(rgbes6);\n\nlet brand = \"carbrand\";\nconst cars = {\n [brand]: \"BMW\"\n}\nconsole.log(cars.carbrand); //\"BMW\"" }, { "code": null, "e": 34542, "s": 34472, "text": "npx babel enhancedobjliteral.js --out-file enhancedobjliteral_es5.js\n" }, { "code": null, "e": 35110, "s": 34542, "text": "\"use strict\";\n\nfunction _defineProperty(obj, key, value) {\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value, enumerable: true, configurable: true, writable: true\n });\n } else { obj[key] = value; } return obj;\n}\n\nvar red = 1,\n green = 2,\n blue = 3;\nvar rgbes5 = {\n red: red,\n green: green,\n blue: blue\n};\nconsole.log(rgbes5);\n\nvar rgbes6 = {\n red: red,\n green: green,\n blue: blue\n};\nconsole.log(rgbes6);\n\nvar brand = \"carbrand\";\nvar cars = _defineProperty({}, brand, \"BMW\");\n\nconsole.log(cars.carbrand); //\"BMW\"" }, { "code": null, "e": 35184, "s": 35110, "text": "In this section, we will discuss the default, rest and spread properties." }, { "code": null, "e": 35260, "s": 35184, "text": "With ES6, we can use default parameters to the function params as follows −" }, { "code": null, "e": 35372, "s": 35260, "text": "let add = (a, b = 3) => {\n return a + b;\n}\n\nconsole.log(add(10, 20)); // 30\nconsole.log(add(10)); // 13" }, { "code": null, "e": 35424, "s": 35372, "text": "Let us transpile the above code to ES5 using babel." }, { "code": null, "e": 35472, "s": 35424, "text": "npx babel default.js --out-file default_es5.js\n" }, { "code": null, "e": 35666, "s": 35472, "text": "\"use strict\";\n\nvar add = function add(a) {\n var b = arguments.length > 1 >> arguments[1] !== undefined ? arguments[1] : 3;\n return a + b;\n};\n\nconsole.log(add(10, 20));\nconsole.log(add(10));" }, { "code": null, "e": 35741, "s": 35666, "text": "Rest parameter starts with three dots(...) as shown in the example below −" }, { "code": null, "e": 35930, "s": 35741, "text": "let add = (...args) => {\n let sum = 0;\n args.forEach(function (n) {\n sum += n;\n });\n return sum;\n};\n\nconsole.log(add(1, 2)); // 3\nconsole.log(add(1, 2, 5, 6, 6, 7)); //27" }, { "code": null, "e": 36260, "s": 35930, "text": "In the above function we are passing n number of params to the function add. To add all those params if it was in ES5, we have to rely on arguments object to get the details of the arguments. With ES6, rest it helps to define the arguments with three dots as shown above and we can loop through it and get the sum of the numbers." }, { "code": null, "e": 36336, "s": 36260, "text": "Note − We cannot use additional arguments when using three dot, i.e., rest." }, { "code": null, "e": 36474, "s": 36336, "text": "let add = (...args, value) => { //syntax error\n let sum = 0;\n args.forEach(function (n) {\n sum += n;\n });\n return sum;\n};" }, { "code": null, "e": 36513, "s": 36474, "text": "The above code will give syntax error." }, { "code": null, "e": 36555, "s": 36513, "text": "The compilation to es5 looks as follows −" }, { "code": null, "e": 36597, "s": 36555, "text": "npx babel rest.js --out-file rest_es5.js\n" }, { "code": null, "e": 36920, "s": 36597, "text": "\"use strict\";\n\nvar add = function add() {\n for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n var sum = 0;\n args.forEach(function (n) {\n sum += n;\n });\n return sum;\n};\n\nconsole.log(add(1, 2));\nconsole.log(add(1, 2, 5, 6, 6, 7));" }, { "code": null, "e": 37051, "s": 36920, "text": "The Spread property also has the three dots like rest. Following is a working example, which shows how to use the spread property." }, { "code": null, "e": 37155, "s": 37051, "text": "let add = (a, b, c) => {\n return a + b + c;\n}\nlet arr = [11, 23, 3];\nconsole.log(add(...arr)); //37" }, { "code": null, "e": 37217, "s": 37155, "text": "Let us now see how the above code is transpiled using babel −" }, { "code": null, "e": 37263, "s": 37217, "text": "npx babel spread.js --out-file spread_es5.js\n" }, { "code": null, "e": 37399, "s": 37263, "text": "\"use strict\";\n\nvar add = function add(a, b, c) {\n return a + b + c;\n};\nvar arr = [11, 23, 3];\nconsole.log(add.apply(undefined, arr));" }, { "code": null, "e": 37545, "s": 37399, "text": "Proxy is an object where you can define custom behaviour for operations like property lookup, assignment, enumeration, function, invocation, etc." }, { "code": null, "e": 37582, "s": 37545, "text": "var a = new Proxy(target, handler);\n" }, { "code": null, "e": 37619, "s": 37582, "text": "Both target and handler are objects." }, { "code": null, "e": 37672, "s": 37619, "text": "target is an object or can be another proxy element." }, { "code": null, "e": 37725, "s": 37672, "text": "target is an object or can be another proxy element." }, { "code": null, "e": 37827, "s": 37725, "text": "handler will be an object with its properties as functions which will give the behaviour when called." }, { "code": null, "e": 37929, "s": 37827, "text": "handler will be an object with its properties as functions which will give the behaviour when called." }, { "code": null, "e": 37999, "s": 37929, "text": "Let us try to understand these features with the help of an example −" }, { "code": null, "e": 38266, "s": 37999, "text": "let handler = {\n get: function (target, name) {\n return name in target ? target[name] : \"invalid key\";\n }\n};\n\nlet o = {\n name: 'Siya Kapoor',\n addr: 'Mumbai'\n}\n\nlet a = new Proxy(o, handler);\nconsole.log(a.name);\nconsole.log(a.addr);\nconsole.log(a.age);" }, { "code": null, "e": 38388, "s": 38266, "text": "We have defined target and handler in the above example and used it with proxy. Proxy returns the object with key-values." }, { "code": null, "e": 38420, "s": 38388, "text": "Siya Kapoor\nMumbai\ninvalid key\n" }, { "code": null, "e": 38488, "s": 38420, "text": "Let us now see how to transpile the above code to ES5 using babel −" }, { "code": null, "e": 38532, "s": 38488, "text": "npx babel proxy.js --out-file proxy_es5.js\n" }, { "code": null, "e": 38818, "s": 38532, "text": "'use strict';\n\nvar handler = {\n get: function get(target, name) {\n return name in target ? target[name] : \"invalid key\";\n }\n};\n\nvar o = {\n name: 'Siya Kapoor',\n addr: 'Mumbai'\n};\n\nvar a = new Proxy(o, handler);\nconsole.log(a.name);\nconsole.log(a.addr);\nconsole.log(a.age);" }, { "code": null, "e": 38896, "s": 38818, "text": "In this chapter, we will see how to transpile ES6 modules to ES5 using Babel." }, { "code": null, "e": 39020, "s": 38896, "text": "Consider a scenario where parts of JavaScript code need to be reused. ES6 comes to your rescue with the concept of Modules." }, { "code": null, "e": 39199, "s": 39020, "text": "A module is nothing more than a chunk of JavaScript code written in a file. The functions or variables in a module are not available for use, unless the module file exports them." }, { "code": null, "e": 39364, "s": 39199, "text": "In simpler terms, the modules help you to write the code in your module and expose only those parts of the code that should be accessed by other parts of your code." }, { "code": null, "e": 39475, "s": 39364, "text": "Let us consider an example to understand how to use module and how to export it to make use of it in the code." }, { "code": null, "e": 39482, "s": 39475, "text": "add.js" }, { "code": null, "e": 39541, "s": 39482, "text": "var add = (x,y) => {\n return x+y;\n}\n\nmodule.exports=add;" }, { "code": null, "e": 39553, "s": 39541, "text": "multiply.js" }, { "code": null, "e": 39625, "s": 39553, "text": "var multiply = (x,y) => {\n return x*y;\n};\n\nmodule.exports = multiply;" }, { "code": null, "e": 39633, "s": 39625, "text": "main.js" }, { "code": null, "e": 39841, "s": 39633, "text": "import add from './add';\nimport multiply from './multiply'\n\nlet a = add(10,20);\nlet b = multiply(40,10);\n\nconsole.log(\"%c\"+a,\"font-size:30px;color:green;\");\nconsole.log(\"%c\"+b,\"font-size:30px;color:green;\");" }, { "code": null, "e": 40008, "s": 39841, "text": "I have three files add.js that adds 2 given numbers, multiply.js that multiplies two given numbers and main.js, which calls add and multiply, and consoles the output." }, { "code": null, "e": 40095, "s": 40008, "text": "To give add.js and multiply.js in main.js, we have to export it first as shown below −" }, { "code": null, "e": 40144, "s": 40095, "text": "module.exports = add;\nmodule.exports = multiply;" }, { "code": null, "e": 40206, "s": 40144, "text": "To use them in main.js, we need to import them as shown below" }, { "code": null, "e": 40265, "s": 40206, "text": "import add from './add';\nimport multiply from './multiply'" }, { "code": null, "e": 40352, "s": 40265, "text": "We need module bundler to build the files, so that we can execute them in the browser." }, { "code": null, "e": 40369, "s": 40352, "text": "We can do that −" }, { "code": null, "e": 40383, "s": 40369, "text": "Using Webpack" }, { "code": null, "e": 40394, "s": 40383, "text": "Using Gulp" }, { "code": null, "e": 40488, "s": 40394, "text": "In this section, we will see what the ES6 modules are. We will also learn how to use webpack." }, { "code": null, "e": 40549, "s": 40488, "text": "Before we start, we need to install the following packages −" }, { "code": null, "e": 40733, "s": 40549, "text": "npm install --save-dev webpack\nnpm install --save-dev webpack-dev-server\nnpm install --save-dev babel-core\nnpm install --save-dev babel-loader\nnpm install --save-dev babel-preset-env\n" }, { "code": null, "e": 40872, "s": 40733, "text": "We have added pack and publish tasks to scripts to run them using npm. Here is the webpack.config.js file which will build the final file." }, { "code": null, "e": 41333, "s": 40872, "text": "var path = require('path');\n\nmodule.exports = {\n entry: {\n app: './src/main.js'\n },\n output: {\n path: path.resolve(__dirname, 'dev'),\n filename: 'main_bundle.js'\n },\n mode:'development',\n module: {\n rules: [\n {\n test: /\\.js$/,\n include: path.resolve(__dirname, 'src'),\n loader: 'babel-loader',\n query: {\n presets: ['env']\n }\n }\n ]\n }\n};" }, { "code": null, "e": 41432, "s": 41333, "text": "Run the command npm run pack to build the files. The final file will be stored in the dev/ folder." }, { "code": null, "e": 41446, "s": 41432, "text": "npm run pack\n" }, { "code": null, "e": 41577, "s": 41446, "text": "dev/main_bundle.js common file is created. This file combines add.js, multiply.js and main.js and stores it in dev/main_bundle.js." }, { "code": null, "e": 47194, "s": 41577, "text": "/******/ (function(modules) { // webpackBootstrap\n/******/ // The module cache\n/******/ var installedModules = {};\n/******/\n/******/ // The require function\n/******/ function __webpack_require__(moduleId) {\n/******/\n/******/ // Check if module is in cache\n/******/ if(installedModules[moduleId]) {\n/******/ return installedModules[moduleId].exports;\n/******/ }\n/******/ // Create a new module (and put it into the cache)\n/******/ var module = installedModules[moduleId] = {\n/******/ i: moduleId,\n/******/ l: false,\n/******/ exports: {}\n/******/ };\n/******/\n/******/ // Execute the module function\n/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n/******/\n/******/ // Flag the module as loaded\n/******/ module.l = true;\n/******/\n/******/ // Return the exports of the module\n/******/ return module.exports;\n/******/ }\n/******/\n/******/\n/******/ // expose the modules object (__webpack_modules__)\n/******/ __webpack_require__.m = modules;\n/******/\n/******/ // expose the module cache\n/******/ __webpack_require__.c = installedModules;\n/******/\n/******/ // define getter function for harmony exports\n/******/ __webpack_require__.d = function(exports, name, getter) {\n/******/ if(!__webpack_require__.o(exports, name)) {\n/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });\n/******/ }\n/******/ };\n/******/\n/******/ // define __esModule on exports\n/******/ __webpack_require__.r = function(exports) {\n/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n/******/ }\n/******/ Object.defineProperty(exports, '__esModule', { value: true });\n/******/ };\n/******/\n/******/ // create a fake namespace object\n/******/ // mode & 1: value is a module id, require it\n/******/ // mode & 2: merge all properties of value into the ns\n/******/ // mode & 4: return value when already ns object\n/******/ // mode & 8|1: behave like require\n/******/ __webpack_require__.t = function(value, mode) {\n/******/ if(mode & 1) value = __webpack_require__(value);\n/******/ if(mode & 8) return value;\n/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;\n/******/ var ns = Object.create(null);\n/******/ __webpack_require__.r(ns);\n/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });\n/******/ if(mode & 2 && typeof value != 'string')\n for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));\n/******/ return ns;\n/******/ };\n/******/\n/******/ // getDefaultExport function for compatibility with non-harmony modules\n/******/ __webpack_require__.n = function(module) {\n/******/ var getter = module && module.__esModule ?\n/******/ function getDefault() { return module['default']; } :\n/******/ function getModuleExports() { return module; };\n/******/ __webpack_require__.d(getter, 'a', getter);\n/******/ return getter;\n/******/ };\n/******/\n/******/ // Object.prototype.hasOwnProperty.call\n/******/ __webpack_require__.o = function(object, property) {\n return Object.prototype.hasOwnProperty.call(object, property); \n };\n/******/\n/******/ // __webpack_public_path__\n/******/ __webpack_require__.p = \"\";\n/******/\n/******/\n/******/ // Load entry module and return exports\n/******/ return __webpack_require__(__webpack_require__.s = \"./src/main.js\");\n/******/ })\n/************************************************************************/\n/******/ ({\n/***/ \"./src/add.js\":\n/*!********************!*\\\n!*** ./src/add.js ***!\n\\********************/\n/*! no static exports found */\n/***/ (function(module, exports, __webpack_require__) {\n \"use strict\";\n\n eval(\n \"\\n\\nvar add = function add(x, y) {\\n return x + y;\\n};\n \\n\\nmodule.exports = add;\n \\n\\n//# sourceURL = webpack:///./src/add.js?\"\n );\n /***/ }),\n/***/ \"./src/main.js\":\n/*!*********************!*\\\n!*** ./src/main.js ***!\n\\*********************/\n/*! no static exports found */\n/***/ (function(module, exports, __webpack_require__) {\n\n \"use strict\";\n eval(\n \"\\n\\nvar _add = __webpack_require__(/*! ./add */ \\\"./src/add.js\\\");\n \\n\\nvar _add2 = _interopRequireDefault(_add);\n \\n\\nvar _multiply = __webpack_require__(/*! ./multiply */ \\\"./src/multiply.js\\\");\n \\n\\nvar _multiply2 = _interopRequireDefault(_multiply);\n \\n\\nfunction _interopRequireDefault(obj) {\n return obj &gt;&gt; obj.__esModule ? obj : { default: obj };\n }\n \\n\\nvar a = (0, _add2.default)(10, 20);\n \\nvar b = (0, _multiply2.default)(40, 10);\n \\n\\nconsole.log(\\\"%c\\\" + a, \\\"font-size:30px;color:green;\\\");\n \\nconsole.log(\\\"%c\\\" + b, \\\"font-size:30px;color:green;\\\");\n \\n\\n//# sourceURL = webpack:///./src/main.js?\"\n );\n\n/***/ }),\n\n/***/ \"./src/multiply.js\":\n/*!*************************!*\\\n !*** ./src/multiply.js ***!\n \\*************************/\n/*! no static exports found */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\neval(\n \"\\n\\nvar multiply = function multiply(x, y) {\\n return x * y;\\n};\n \\n\\nmodule.exports = multiply;\n \\n\\n//# sourceURL = webpack:///./src/multiply.js?\"\n);\n\n/***/ })\n\n/******/ });" }, { "code": null, "e": 47251, "s": 47194, "text": "Following is the command to test the output in browser −" }, { "code": null, "e": 47268, "s": 47251, "text": "npm run publish\n" }, { "code": null, "e": 47331, "s": 47268, "text": "Add index.html in your project. This calls dev/main_bundle.js." }, { "code": null, "e": 47456, "s": 47331, "text": "<html>\n <head></head>\n <body>\n <script type=\"text/javascript\" src=\"dev/main_bundle.js\"></script>\n </body>\n</html>" }, { "code": null, "e": 47613, "s": 47456, "text": "To use Gulp to bundle the modules into one file, we will use browserify and babelify. First, we will create project setup and install the required packages." }, { "code": null, "e": 47623, "s": 47613, "text": "npm init\n" }, { "code": null, "e": 47707, "s": 47623, "text": "Before we start with the project setup, we need to install the following packages −" }, { "code": null, "e": 47991, "s": 47707, "text": "npm install --save-dev gulp\nnpm install --save-dev babelify\nnpm install --save-dev browserify\nnpm install --save-dev babel-preset-env\nnpm install --save-dev babel-core\nnpm install --save-dev gulp-connect\nnpm install --save-dev vinyl-buffer\nnpm install --save-dev vinyl-source-stream\n" }, { "code": null, "e": 48139, "s": 47991, "text": "Let us now create the gulpfile.js, which will help run the task to bundle the modules together. We will use the same files used above with webpack." }, { "code": null, "e": 48146, "s": 48139, "text": "add.js" }, { "code": null, "e": 48205, "s": 48146, "text": "var add = (x,y) => {\n return x+y;\n}\n\nmodule.exports=add;" }, { "code": null, "e": 48217, "s": 48205, "text": "multiply.js" }, { "code": null, "e": 48289, "s": 48217, "text": "var multiply = (x,y) => {\n return x*y;\n};\n\nmodule.exports = multiply;" }, { "code": null, "e": 48297, "s": 48289, "text": "main.js" }, { "code": null, "e": 48505, "s": 48297, "text": "import add from './add';\nimport multiply from './multiply'\n\nlet a = add(10,20);\nlet b = multiply(40,10);\n\nconsole.log(\"%c\"+a,\"font-size:30px;color:green;\");\nconsole.log(\"%c\"+b,\"font-size:30px;color:green;\");" }, { "code": null, "e": 48646, "s": 48505, "text": "The gulpfile.js is created here. A user will browserfiy and use tranform to babelify. babel-preset-env is used to transpile the code to es5." }, { "code": null, "e": 48658, "s": 48646, "text": "Gulpfile.js" }, { "code": null, "e": 49407, "s": 48658, "text": "const gulp = require('gulp');\nconst babelify = require('babelify');\nconst browserify = require('browserify');\nconst connect = require(\"gulp-connect\");\nconst source = require('vinyl-source-stream');\nconst buffer = require('vinyl-buffer');\n\ngulp.task('build', () => {\n browserify('src/main.js')\n .transform('babelify', {\n presets: ['env']\n })\n .bundle()\n .pipe(source('main.js'))\n .pipe(buffer())\n .pipe(gulp.dest('dev/'));\n});\ngulp.task('default', ['es6'],() => {\n gulp.watch('src/app.js',['es6'])\n});\n\ngulp.task('watch', () => {\n gulp.watch('./*.js', ['build']);\n});\n\ngulp.task(\"connect\", function () {\n connect.server({\n root: \".\",\n livereload: true\n });\n});\n\ngulp.task('start', ['build', 'watch', 'connect']);" }, { "code": null, "e": 49529, "s": 49407, "text": "We use browserify and babelify to take care of the module export and import and combine the same to one file as follows −" }, { "code": null, "e": 49735, "s": 49529, "text": "gulp.task('build', () => {\n browserify('src/main.js')\n .transform('babelify', {\n presets: ['env']\n })\n .bundle()\n .pipe(source('main.js'))\n .pipe(buffer())\n .pipe(gulp.dest('dev/'));\n});" }, { "code": null, "e": 49808, "s": 49735, "text": "We have used transform in which babelify is called with the presets env." }, { "code": null, "e": 49892, "s": 49808, "text": "The src folder with the main.js is given to browserify and saved in the dev folder." }, { "code": null, "e": 49952, "s": 49892, "text": "We need to run the command gulp start to compile the file −" }, { "code": null, "e": 49963, "s": 49952, "text": "npm start\n" }, { "code": null, "e": 50015, "s": 49963, "text": "Here is the final file created in the dev/ folder −" }, { "code": null, "e": 51640, "s": 50015, "text": "(function() {\n function r(e,n,t) {\n function o(i,f) {\n if(!n[i]) {\n if(!e[i]) {\n var c = \"function\"==typeof require&&require;\n if(!f&&c)return c(i,!0);if(u)return u(i,!0);\n var a = new Error(\"Cannot find module '\"+i+\"'\");\n throw a.code = \"MODULE_NOT_FOUND\",a\n }\n var p = n[i] = {exports:{}};\n e[i][0].call(\n p.exports,function(r) {\n var n = e[i][1][r];\n return o(n||r)\n }\n ,p,p.exports,r,e,n,t)\n }\n return n[i].exports\n }\n for(var u=\"function\"==typeof require>>require,i = 0;i<t.length;i++)o(t[i]);return o\n }\n return r\n})()\n({1:[function(require,module,exports) {\n \"use strict\";\n\n var add = function add(x, y) {\n return x + y;\n };\n\n module.exports = add;\n},{}],2:[function(require,module,exports) {\n 'use strict';\n\n var _add = require('./add');\n var _add2 = _interopRequireDefault(_add);\n var _multiply = require('./multiply');\n var _multiply2 = _interopRequireDefault(_multiply);\n function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n var a = (0, _add2.default)(10, 20);\n var b = (0, _multiply2.default)(40, 10);\n\n console.log(\"%c\" + a, \"font-size:30px;color:green;\");\n console.log(\"%c\" + b, \"font-size:30px;color:green;\");\n},\n{\"./add\":1,\"./multiply\":3}],3:[function(require,module,exports) {\n \"use strict\";\n\n var multiply = function multiply(x, y) {\n return x * y;\n };\n\n module.exports = multiply;\n\n},{}]},{},[2]);" }, { "code": null, "e": 51727, "s": 51640, "text": "We will use the same in index.html and run the same in the browser to get the output −" }, { "code": null, "e": 51879, "s": 51727, "text": "<html>\n <head></head>\n <body>\n <h1>Modules using Gulp</h1>\n <script type=\"text/javascript\" src=\"dev/main.js\"></script>\n </body>\n</html>" }, { "code": null, "e": 51948, "s": 51879, "text": "In this chapter, we will learn how to transpile ES7 features to ES5." }, { "code": null, "e": 52007, "s": 51948, "text": "ECMA Script 7 has the following new features added to it −" }, { "code": null, "e": 52019, "s": 52007, "text": "Async-Await" }, { "code": null, "e": 52043, "s": 52019, "text": "Exponentiation Operator" }, { "code": null, "e": 52070, "s": 52043, "text": "Array.prototype.includes()" }, { "code": null, "e": 52359, "s": 52070, "text": "We will compile them to ES5 using babeljs. Depending on your project requirements, it is also possible to compile the code in any ecma version ie ES7 to ES6 or ES7 to ES5. Since ES5 version is the most stable and works fine on all modern and old browsers, we will compile the code to ES5." }, { "code": null, "e": 52712, "s": 52359, "text": "Async is an asynchronous function, which returns an implicit promise. The promise is either resolved or rejected. Async function is same as a normal standard function. The function can have await expression which pauses the execution till it returns a promise and once it gets it, the execution continues. Await will only work if the function is async." }, { "code": null, "e": 52758, "s": 52712, "text": "Here is a working example on async and await." }, { "code": null, "e": 53038, "s": 52758, "text": "let timer = () => {\n return new Promise(resolve => {\n setTimeout(() => {\n resolve(\"Promise resolved after 5 seconds\");\n }, 5000);\n });\n};\nlet out = async () => {\n let msg = await timer();\n console.log(msg);\n console.log(\"hello after await\");\n};\nout();" }, { "code": null, "e": 53090, "s": 53038, "text": "Promise resolved after 5 seconds\nhello after await\n" }, { "code": null, "e": 53330, "s": 53090, "text": "The await expression is added before the timer function is called. The timer function will return the promise after 5 seconds. So await will halt the execution until the promise on timer function is resolved or rejected and later continue." }, { "code": null, "e": 53386, "s": 53330, "text": "Let us now transpile the above code to ES5 using babel." }, { "code": null, "e": 53666, "s": 53386, "text": "let timer = () => {\n return new Promise(resolve => {\n setTimeout(() => {\n resolve(\"Promise resolved after 5 seconds\");\n }, 5000);\n });\n};\nlet out = async () => {\n let msg = await timer();\n console.log(msg);\n console.log(\"hello after await\");\n};\nout();" }, { "code": null, "e": 53720, "s": 53666, "text": "npx babel asyncawait.js --out-file asyncawait_es5.js\n" }, { "code": null, "e": 54050, "s": 53720, "text": "\"use strict\";\n\nvar timer = function timer() {\n return new Promise(function (resolve) {\n setTimeout(function () {\n resolve(\"Promise resolved after 5 seconds\");\n }, 5000);\n });\n};\nvar out = async function out() {\n var msg = await timer();\n console.log(msg);\n console.log(\"hello after await\");\n};\n\nout();" }, { "code": null, "e": 54315, "s": 54050, "text": "Babeljs does not compile object or methods; so here promises used will not be transpiled and will be shown as it is. To support promises on old browsers, we need to add code, which will have support for promises. For now, let us install babel-polyfill as follows −" }, { "code": null, "e": 54350, "s": 54315, "text": "npm install --save babel-polyfill\n" }, { "code": null, "e": 54409, "s": 54350, "text": "It should be saved as a dependency and not dev-dependency." }, { "code": null, "e": 54575, "s": 54409, "text": "To run the code in the browser, we will use the polyfill file from node_modules\\babel-polyfill\\dist\\polyfill.min.js and call it using the script tag as shown below −" }, { "code": null, "e": 54858, "s": 54575, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>BabelJs Testing</title>\n </head>\n <body>\n <script src=\"node_modules\\babel-polyfill\\dist\\polyfill.min.js\" type=\"text/javascript\"></script>\n <script type=\"text/javascript\" src=\"aynscawait_es5.js\"></script>\n </body>\n</html>" }, { "code": null, "e": 54946, "s": 54858, "text": "When you run the above test page, you will see the output in the console as shown below" }, { "code": null, "e": 55094, "s": 54946, "text": "** is the operator used for exponentiation in ES7. Following example shows the working of the same in ES7 and the code is transpiled using babeljs." }, { "code": null, "e": 55130, "s": 55094, "text": "let sqr = 9 ** 2;\nconsole.log(sqr);" }, { "code": null, "e": 55134, "s": 55130, "text": "81\n" }, { "code": null, "e": 55170, "s": 55134, "text": "let sqr = 9 ** 2;\nconsole.log(sqr);" }, { "code": null, "e": 55269, "s": 55170, "text": "To transpile the exponentiation operator, we need to install a plugin to be installed as follows −" }, { "code": null, "e": 55340, "s": 55269, "text": "npm install --save-dev babel-plugin-transform-exponentiation-operator\n" }, { "code": null, "e": 55393, "s": 55340, "text": "Add the plugin details to .babelrc file as follows −" }, { "code": null, "e": 55485, "s": 55393, "text": "{\n \"presets\":[\n \"es2015\"\n ],\n \"plugins\": [\"transform-exponentiation-operator\"]\n}" }, { "code": null, "e": 55545, "s": 55485, "text": "npx babel exponeniation.js --out-file exponeniation_es5.js\n" }, { "code": null, "e": 55604, "s": 55545, "text": "\"use strict\";\n\nvar sqr = Math.pow(9, 2);\nconsole.log(sqr);" }, { "code": null, "e": 55704, "s": 55604, "text": "This feature gives true if the element passed to it is present in the array and false if otherwise." }, { "code": null, "e": 55889, "s": 55704, "text": "let arr1 = [10, 6, 3, 9, 17];\nconsole.log(arr1.includes(9));\nlet names = ['Siya', 'Tom', 'Jerry', 'Bean', 'Ben'];\nconsole.log(names.includes('Tom'));\nconsole.log(names.includes('Be'));" }, { "code": null, "e": 55906, "s": 55889, "text": "true\ntrue\nfalse\n" }, { "code": null, "e": 56094, "s": 55906, "text": "We have to use babel-polyfill again here as includes is a method on an array and it will not get transpiled. We need additional step to include polyfill to make it work in older browsers." }, { "code": null, "e": 56279, "s": 56094, "text": "let arr1 = [10, 6, 3, 9, 17];\nconsole.log(arr1.includes(9));\nlet names = ['Siya', 'Tom', 'Jerry', 'Bean', 'Ben'];\nconsole.log(names.includes('Tom'));\nconsole.log(names.includes('Be'));" }, { "code": null, "e": 56339, "s": 56279, "text": "npx babel array_include.js --out-file array_include_es5.js\n" }, { "code": null, "e": 56539, "s": 56339, "text": "'use strict';\n\nvar arr1 = [10, 6, 3, 9, 17];\nconsole.log(arr1.includes(9));\nvar names = ['Siya', 'Tom', 'Jerry', 'Bean', 'Ben'];\nconsole.log(names.includes('Tom'));\nconsole.log(names.includes('Be'));" }, { "code": null, "e": 56609, "s": 56539, "text": "To test it in older browser, we need to use polyfill as shown below −" }, { "code": null, "e": 56895, "s": 56609, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>BabelJs Testing</title>\n </head>\n <body>\n <script src=\"node_modules\\babel-polyfill\\dist\\polyfill.min.js\" type=\"text/javascript\"></script>\n <script type=\"text/javascript\" src=\"array_include_es5.js\"></script>\n </body>\n</html>" }, { "code": null, "e": 57042, "s": 56895, "text": "String padding is the new ES8 feature added to javascript. We will work on simple example, which will transpile string padding to ES5 using babel." }, { "code": null, "e": 57175, "s": 57042, "text": "String padding adds another string from the left side as per the length specified. The syntax for string padding is as shown below −" }, { "code": null, "e": 57234, "s": 57175, "text": "str.padStart(length, string);\nstr.padEnd(length, string);\n" }, { "code": null, "e": 57322, "s": 57234, "text": "const str = 'abc';\n\nconsole.log(str.padStart(8, '_'));\nconsole.log(str.padEnd(8, '_'));" }, { "code": null, "e": 57341, "s": 57322, "text": "_____abc\nabc_____\n" }, { "code": null, "e": 57429, "s": 57341, "text": "const str = 'abc';\n\nconsole.log(str.padStart(8, '_'));\nconsole.log(str.padEnd(8, '_'));" }, { "code": null, "e": 57475, "s": 57429, "text": "npx babel strpad.js --out-file strpad_es5.js\n" }, { "code": null, "e": 57576, "s": 57475, "text": "'use strict';\n\nvar str = 'abc';\n\nconsole.log(str.padStart(8, '_'));\nconsole.log(str.padEnd(8, '_'));" }, { "code": null, "e": 57641, "s": 57576, "text": "The js has to be used along with babel-polyfill as shown below −" }, { "code": null, "e": 57920, "s": 57641, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>BabelJs Testing</title>\n </head>\n <body>\n <script src=\"node_modules\\babel-polyfill\\dist\\polyfill.min.js\" type=\"text/javascript\"></script>\n <script type=\"text/javascript\" src=\"strpad_es5.js\"></script>\n </body>\n</html>" }, { "code": null, "e": 58098, "s": 57920, "text": "BabelJS is a javascript compiler that changes the syntax of the code given based on presets and plugins available. The flow of babel compilation involves the following 3 parts −" }, { "code": null, "e": 58106, "s": 58098, "text": "parsing" }, { "code": null, "e": 58119, "s": 58106, "text": "transforming" }, { "code": null, "e": 58128, "s": 58119, "text": "printing" }, { "code": null, "e": 58447, "s": 58128, "text": "The code given to babel is given back as it is with just the syntax changed. We have already seen presets being added to .babelrc file to compile code from es6 to es5 or vice-versa. Presets are nothing but a set of plugins. Babel will not change anything if presets or plugins details are not given during compilation." }, { "code": null, "e": 58490, "s": 58447, "text": "Let us now discuss the following plugins −" }, { "code": null, "e": 58517, "s": 58490, "text": "transform-class-properties" }, { "code": null, "e": 58551, "s": 58517, "text": "Transform-exponentiation-operator" }, { "code": null, "e": 58558, "s": 58551, "text": "For-of" }, { "code": null, "e": 58581, "s": 58558, "text": "object rest and spread" }, { "code": null, "e": 58593, "s": 58581, "text": "async/await" }, { "code": null, "e": 58731, "s": 58593, "text": "Now, we will create a project setup and work on few plugins, which will give clear understanding of the requirements of plugins in babel." }, { "code": null, "e": 58741, "s": 58731, "text": "npm init\n" }, { "code": null, "e": 58836, "s": 58741, "text": "We have to install the required packages for babel – babel cli, babel core, babel-preset, etc." }, { "code": null, "e": 58901, "s": 58836, "text": "npm install babel-cli babel-core babel-preset-es2015 --save-dev\n" }, { "code": null, "e": 58966, "s": 58901, "text": "npm install @babel/cli @babel/core @babel/preset-env --save-dev\n" }, { "code": null, "e": 59023, "s": 58966, "text": "Create a js file in your project and write your js code." }, { "code": null, "e": 59072, "s": 59023, "text": "Observe the codes given below for this purpose −" }, { "code": null, "e": 59080, "s": 59072, "text": "main.js" }, { "code": null, "e": 59403, "s": 59080, "text": "class Person {\n constructor(fname, lname, age, address) {\n this.fname = fname;\n this.lname = lname;\n this.age = age;\n this.address = address;\n }\n\n get fullname() {\n return this.fname + \"-\" + this.lname;\n }\n}\nvar a = new Person(\"Siya\", \"Kapoor\", \"15\", \"Mumbai\");\nvar persondet = a.fullname;" }, { "code": null, "e": 59522, "s": 59403, "text": "Right now, we have not given any preset or plugin details to babel. If we happen to transpile the code using command −" }, { "code": null, "e": 59564, "s": 59522, "text": "npx babel main.js --out-file main_out.js\n" }, { "code": null, "e": 59576, "s": 59564, "text": "main_out.js" }, { "code": null, "e": 59899, "s": 59576, "text": "class Person {\n constructor(fname, lname, age, address) {\n this.fname = fname;\n this.lname = lname;\n this.age = age;\n this.address = address;\n }\n\n get fullname() {\n return this.fname + \"-\" + this.lname;\n }\n}\nvar a = new Person(\"Siya\", \"Kapoor\", \"15\", \"Mumbai\");\nvar persondet = a.fullname;" }, { "code": null, "e": 59970, "s": 59899, "text": "We will get the code as it is. Let us now add preset to .babelrc file." }, { "code": null, "e": 60038, "s": 59970, "text": "Note − Create .babelrc file inside the root folder of your project." }, { "code": null, "e": 60059, "s": 60038, "text": ".babelrc for babel 6" }, { "code": null, "e": 60080, "s": 60059, "text": ".babelrc for babel 7" }, { "code": null, "e": 60112, "s": 60080, "text": "{\n \"presets\":[\"@babel/env\"]\n}" }, { "code": null, "e": 60186, "s": 60112, "text": "We have already installed the presets; now let us run the command again −" }, { "code": null, "e": 60228, "s": 60186, "text": "npx babel main.js --out-file main_out.js\n" }, { "code": null, "e": 60240, "s": 60228, "text": "main_out.js" }, { "code": null, "e": 61558, "s": 60240, "text": "\"use strict\";\n\nvar _createClass = function () {\n function defineProperties(target, props) {\n for (var i = 0; i < props.length; i++) {\n var descriptor = props[i];\n descriptor.enumerable = descriptor.enumerable || false; \n descriptor.configurable = true; \n if (\"value\" in descriptor) descriptor.writable = true; \n Object.defineProperty(target, descriptor.key, descriptor); \n }\n }\n return function (Constructor, protoProps, staticProps) { \n if (protoProps) defineProperties(Constructor.prototype, protoProps); \n if (staticProps) defineProperties(Constructor, staticProps); \n return Constructor; \n }; \n}();\n\nfunction _classCallCheck(instance, Constructor) { \n if (!(instance instanceof Constructor)) {\n throw new TypeError(\"Cannot call a class as a function\"); \n } \n}\n\nvar Person = function () {\n function Person(fname, lname, age, address) {\n _classCallCheck(this, Person);\n\n this.fname = fname;\n this.lname = lname;\n this.age = age;\n this.address = address;\n }\n\n _createClass(Person, [{\n key: \"fullname\",\n get: function get() {\n return this.fname + \"-\" + this.lname;\n }\n }]);\n return Person;\n}();\n\nvar a = new Person(\"Siya\", \"Kapoor\", \"15\", \"Mumbai\");\nvar persondet = a.fullname;" }, { "code": null, "e": 61593, "s": 61558, "text": "In ES6, class syntax is as follows" }, { "code": null, "e": 61835, "s": 61593, "text": "class Person {\n constructor(fname, lname, age, address) {\n this.fname = fname;\n this.lname = lname;\n this.age = age;\n this.address = address;\n }\n\n get fullname() {\n return this.fname + \"-\" + this.lname;\n }\n}\n" }, { "code": null, "e": 61993, "s": 61835, "text": "There is constructor and all the properties of the class are defined inside it. Incase, we need to define class properties outside the class we cannot do so." }, { "code": null, "e": 62197, "s": 61993, "text": "class Person {\n name = \"Siya Kapoor\";\n\n fullname = () => {\n return this.name;\n }\n}\nvar a = new Person();\nvar persondet = a.fullname();\nconsole.log(\"%c\"+persondet, \"font-size:25px;color:red;\");" }, { "code": null, "e": 62317, "s": 62197, "text": "If we happen to compile the above code, it will throw an error in babel. This results in the code not getting compiled." }, { "code": null, "e": 62490, "s": 62317, "text": "To make this work the way we want, we can make use of babel plugin called babel-plugin-transform-class-properties. To make it work, we need to install it first as follows −" }, { "code": null, "e": 62554, "s": 62490, "text": "npm install --save-dev babel-plugin-transform-class-properties\n" }, { "code": null, "e": 62618, "s": 62554, "text": "npm install --save-dev @babel/plugin-proposal-class-properties\n" }, { "code": null, "e": 62664, "s": 62618, "text": "Add the plugin to .babelrc file for babel 6 −" }, { "code": null, "e": 62685, "s": 62664, "text": ".babelrc for babel 7" }, { "code": null, "e": 62747, "s": 62685, "text": "{\n \"plugins\": [\"@babel/plugin-proposal-class-properties\"]\n}" }, { "code": null, "e": 62783, "s": 62747, "text": "Now, we will run the command again." }, { "code": null, "e": 62825, "s": 62783, "text": "npx babel main.js --out-file main_out.js\n" }, { "code": null, "e": 62833, "s": 62825, "text": "main.js" }, { "code": null, "e": 63037, "s": 62833, "text": "class Person {\n name = \"Siya Kapoor\";\n\n fullname = () => {\n return this.name;\n }\n}\nvar a = new Person();\nvar persondet = a.fullname();\nconsole.log(\"%c\"+persondet, \"font-size:25px;color:red;\");" }, { "code": null, "e": 63061, "s": 63037, "text": "Compiled to main_out.js" }, { "code": null, "e": 63312, "s": 63061, "text": "class Person {\n constructor() {\n this.name = \"Siya Kapoor\";\n\n this.fullname = () => {\n return this.name;\n };\n }\n}\nvar a = new Person();\nvar persondet = a.fullname();\nconsole.log(\"%c\"+persondet, \"font-size:25px;color:red;\");" }, { "code": null, "e": 63319, "s": 63312, "text": "Output" }, { "code": null, "e": 63375, "s": 63319, "text": "Following is the output we get when used in a browser −" }, { "code": null, "e": 63529, "s": 63375, "text": "** is the operator used for exponentiation in ES7. Following example shows the working of same in ES7. It also shows how to transpile code using babeljs." }, { "code": null, "e": 63599, "s": 63529, "text": "let sqr = 9 ** 2;\nconsole.log(\"%c\"+sqr, \"font-size:25px;color:red;\");" }, { "code": null, "e": 63687, "s": 63599, "text": "To transpile the exponentiation operator, we need a plugin to be installed as follows −" }, { "code": null, "e": 63708, "s": 63687, "text": "Packages for babel 6" }, { "code": null, "e": 63779, "s": 63708, "text": "npm install --save-dev babel-plugin-transform-exponentiation-operator\n" }, { "code": null, "e": 63800, "s": 63779, "text": "Packages for babel 7" }, { "code": null, "e": 63872, "s": 63800, "text": "npm install --save-dev @babel/plugin-transform-exponentiation-operator\n" }, { "code": null, "e": 63937, "s": 63872, "text": "Add the plugin details to .babelrc file as follows for babel 6 −" }, { "code": null, "e": 63993, "s": 63937, "text": "{\n \"plugins\": [\"transform-exponentiation-operator\"]\n}" }, { "code": null, "e": 64014, "s": 63993, "text": ".babelrc for babel 7" }, { "code": null, "e": 64084, "s": 64014, "text": "{\n \"plugins\": [\"@babel/plugin-transform-exponentiation-operator\"]\n}" }, { "code": null, "e": 64092, "s": 64084, "text": "command" }, { "code": null, "e": 64152, "s": 64092, "text": "npx babel exponeniation.js --out-file exponeniation_out.js\n" }, { "code": null, "e": 64173, "s": 64152, "text": "exponeniation_out.js" }, { "code": null, "e": 64253, "s": 64173, "text": "let sqr = Math.pow(9, 2);\nconsole.log(\"%c\" + sqr, \"font-size:25px;color:red;\");" }, { "code": null, "e": 64260, "s": 64253, "text": "Output" }, { "code": null, "e": 64331, "s": 64260, "text": "The packages required for the plugins in babel6 and 7 are as follows −" }, { "code": null, "e": 64392, "s": 64331, "text": "npm install --save-dev babel-plugin-transform-es2015-for-of\n" }, { "code": null, "e": 64447, "s": 64392, "text": "npm install --save-dev @babel/plugin-transform-for-of\n" }, { "code": null, "e": 64467, "s": 64447, "text": ".babelrc for babel6" }, { "code": null, "e": 64513, "s": 64467, "text": "{\n \"plugins\": [\"transform-es2015-for-of\"]\n}" }, { "code": null, "e": 64533, "s": 64513, "text": ".babelrc for babel7" }, { "code": null, "e": 64586, "s": 64533, "text": "{\n \"plugins\": [\"@babel/plugin-transform-for-of\"]\n}" }, { "code": null, "e": 64595, "s": 64586, "text": "forof.js" }, { "code": null, "e": 64680, "s": 64595, "text": "let foo = [\"PHP\", \"C++\", \"Mysql\", \"JAVA\"];\nfor (var i of foo) {\n console.log(i);\n}" }, { "code": null, "e": 64724, "s": 64680, "text": "npx babel forof.js --out-file forof_es5.js\n" }, { "code": null, "e": 64737, "s": 64724, "text": "Forof_es5.js" }, { "code": null, "e": 65378, "s": 64737, "text": "let foo = [\"PHP\", \"C++\", \"Mysql\", \"JAVA\"];\nvar _iteratorNormalCompletion = true;\nvar _didIteratorError = false;\nvar _iteratorError = undefined;\n\ntry {\n for (var _iterator = foo[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {\n var i = _step.value;\n\n console.log(i);\n }\n} catch (err) {\n _didIteratorError = true;\n _iteratorError = err;\n} finally {\n try {\n if (!_iteratorNormalCompletion && _iterator.return) {\n _iterator.return();\n }\n } finally {\n if (_didIteratorError) {\n throw _iteratorError;\n }\n }\n}" }, { "code": null, "e": 65385, "s": 65378, "text": "Output" }, { "code": null, "e": 65456, "s": 65385, "text": "The packages required for the plugins in babel6 and 7 are as follows −" }, { "code": null, "e": 65522, "s": 65456, "text": "npm install --save-dev babel-plugin-transform-object-rest-spread\n" }, { "code": null, "e": 65588, "s": 65522, "text": "npm install --save-dev @babel/plugin-proposal-object-rest-spread\n" }, { "code": null, "e": 65608, "s": 65588, "text": ".babelrc for babel6" }, { "code": null, "e": 65659, "s": 65608, "text": "{\n \"plugins\": [\"transform-object-rest-spread\"]\n}" }, { "code": null, "e": 65679, "s": 65659, "text": ".babelrc for babel7" }, { "code": null, "e": 65743, "s": 65679, "text": "{\n \"plugins\": [\"@babel/plugin-proposal-object-rest-spread\"]\n}" }, { "code": null, "e": 65748, "s": 65743, "text": "o.js" }, { "code": null, "e": 65900, "s": 65748, "text": "let { x1, y1, ...z1 } = { x1: 11, y1: 12, a: 23, b: 24 };\nconsole.log(x1);\nconsole.log(y1);\nconsole.log(z1);\n\nlet n = { x1, y1, ...z1};\nconsole.log(n);" }, { "code": null, "e": 65936, "s": 65900, "text": "npx babel o.js --out-file o_es5.js\n" }, { "code": null, "e": 65945, "s": 65936, "text": "o_es5.js" }, { "code": null, "e": 66753, "s": 65945, "text": "var _extends = Object.assign || function (target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i]; for (var key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key]; \n } \n } \n } \n return target; \n};\n\nfunction _objectWithoutProperties(obj, keys) {\n var target = {};\n for (var i in obj) {\n if (keys.indexOf(i) >= 0) continue;\n if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;\n target[i] = obj[i];\n }\n return target;\n}\n\nlet _x1$y1$a$b = { x1: 11, y1: 12, a: 23, b: 24 },\n { x1, y1 } = _x1$y1$a$b,\n z1 = _objectWithoutProperties(_x1$y1$a$b, [\"x1\", \"y1\"]);\nconsole.log(x1);\nconsole.log(y1);\nconsole.log(z1);\n\nlet n = _extends({ x1, y1 }, z1);\nconsole.log(n);" }, { "code": null, "e": 66760, "s": 66753, "text": "Output" }, { "code": null, "e": 66821, "s": 66760, "text": "We need the following packages to be installed for babel 6 −" }, { "code": null, "e": 66887, "s": 66821, "text": "npm install --save-dev babel-plugin-transform-async-to-generator\n" }, { "code": null, "e": 66954, "s": 66887, "text": "npm install --save-dev @babel/plugin-transform-async-to-generator\n" }, { "code": null, "e": 66975, "s": 66954, "text": ".babelrc for babel 6" }, { "code": null, "e": 67026, "s": 66975, "text": "{\n \"plugins\": [\"transform-async-to-generator\"]\n}" }, { "code": null, "e": 67047, "s": 67026, "text": ".babelrc for babel 7" }, { "code": null, "e": 67112, "s": 67047, "text": "{\n \"plugins\": [\"@babel/plugin-transform-async-to-generator\"]\n}" }, { "code": null, "e": 67121, "s": 67112, "text": "async.js" }, { "code": null, "e": 67402, "s": 67121, "text": "let timer = () => {\n return new Promise(resolve => {\n setTimeout(() => {\n resolve(\"Promise resolved after 5 seconds\");\n }, 5000);\n });\n};\nlet out = async () => {\n let msg = await timer();\n console.log(msg);\n console.log(\"hello after await\");\n};\n\nout();" }, { "code": null, "e": 67446, "s": 67402, "text": "npx babel async.js --out-file async_es5.js\n" }, { "code": null, "e": 67459, "s": 67446, "text": "async_es5.js" }, { "code": null, "e": 68599, "s": 67459, "text": "function _asyncToGenerator(fn) {\n return function () {\n var gen = fn.apply(this, arguments);\n return new Promise(function (resolve, reject) {\n function step(key, arg) {\n try {\n var info = gen[key](arg);\n var value = info.value; \n } catch (error) {\n reject(error);\n return; \n } if (info.done) {\n resolve(value); \n } else {\n return Promise.resolve(value).then(function (value) {\n step(\"next\", value);\n },\n function (err) {\n step(\"throw\", err); }); \n }\n } return step(\"next\"); \n });\n };\n}\n\nlet timer = () => {\n return new Promise(resolve => {\n setTimeout(() => {\n resolve(\"Promise resolved after 5 seconds\");\n }, 5000);\n });\n};\nlet out = (() => {\n var _ref = _asyncToGenerator(function* () {\n let msg = yield timer();\n console.log(msg);\n console.log(\"hello after await\");\n });\n\n return function out() {\n return _ref.apply(this, arguments);\n };\n})();\nout();" }, { "code": null, "e": 68710, "s": 68599, "text": "We have to make use of polyfill for the same as it will not work in browsers where promises are not supported." }, { "code": null, "e": 68717, "s": 68710, "text": "Output" }, { "code": null, "e": 69048, "s": 68717, "text": "Babel Polyfill adds support to the web browsers for features, which are not available. Babel compiles the code from recent ecma version to the one, which we want. It changes the syntax as per the preset, but cannot do anything for the objects or methods used. We have to use polyfill for those features for backward compatibility." }, { "code": null, "e": 69139, "s": 69048, "text": "Following is the list of features that need polyfill support when used in older browsers −" }, { "code": null, "e": 69148, "s": 69139, "text": "Promises" }, { "code": null, "e": 69152, "s": 69148, "text": "Map" }, { "code": null, "e": 69156, "s": 69152, "text": "Set" }, { "code": null, "e": 69163, "s": 69156, "text": "Symbol" }, { "code": null, "e": 69171, "s": 69163, "text": "Weakmap" }, { "code": null, "e": 69179, "s": 69171, "text": "Weakset" }, { "code": null, "e": 69259, "s": 69179, "text": "Array.from, Array.includes, Array.of, Array#find, Array.buffer, Array#findIndex" }, { "code": null, "e": 69304, "s": 69259, "text": "Object.assign, Object.entries, Object.values" }, { "code": null, "e": 69377, "s": 69304, "text": "We will create project setup and also see the working of babel polyfill." }, { "code": null, "e": 69387, "s": 69377, "text": "npm init\n" }, { "code": null, "e": 69440, "s": 69387, "text": "We will now install the packages required for babel." }, { "code": null, "e": 69505, "s": 69440, "text": "npm install babel-cli babel-core babel-preset-es2015 --save-dev\n" }, { "code": null, "e": 69570, "s": 69505, "text": "npm install @babel/cli @babel/core @babel/preset-env --save-dev\n" }, { "code": null, "e": 69603, "s": 69570, "text": "Here is the final package.json −" }, { "code": null, "e": 69682, "s": 69603, "text": "We will also add es2015 to the presets, as we want to compile the code to es5." }, { "code": null, "e": 69703, "s": 69682, "text": ".babelrc for babel 6" }, { "code": null, "e": 69724, "s": 69703, "text": ".babelrc for babel 7" }, { "code": null, "e": 69756, "s": 69724, "text": "{\n \"presets\":[\"@babel/env\"]\n}" }, { "code": null, "e": 69827, "s": 69756, "text": "We will install a lite-serve so that we can test our code in browser −" }, { "code": null, "e": 69863, "s": 69827, "text": "npm install --save-dev lite-server\n" }, { "code": null, "e": 69926, "s": 69863, "text": "Let us add babel command to compile our code in package.json −" }, { "code": null, "e": 69992, "s": 69926, "text": "We have also added the build command which calls the lite-server." }, { "code": null, "e": 70127, "s": 69992, "text": "Babel-polyfill gets installed along with the babel-core package. The babel-polyfill will be available in node modules as shown below −" }, { "code": null, "e": 70198, "s": 70127, "text": "We will further work on promises and use babel-polyfill along with it." }, { "code": null, "e": 70426, "s": 70198, "text": "let timingpromise = new Promise((resolve, reject) => {\n setTimeout(function() {\n resolve(\"Promise is resolved!\");\n }, 1000);\n});\n\ntimingpromise.then((msg) => {\n console.log(\"%c\"+msg, \"font-size:25px;color:red;\");\n});" }, { "code": null, "e": 70474, "s": 70426, "text": "npx babel promise.js --out-file promise_es5.js\n" }, { "code": null, "e": 70730, "s": 70474, "text": "\"use strict\";\n\nvar timingpromise = new Promise(function (resolve, reject) {\n setTimeout(function () {\n resolve(\"Promise is resolved!\");\n }, 1000);\n});\n\ntimingpromise.then(function (msg) {\n console.log(\"%c\"+msg, \"font-size:25px;color:red;\");\n});" }, { "code": null, "e": 70932, "s": 70730, "text": "The compilation need not change anything. The code for promise has been transpiled as it is. But browsers which do not support promises will throw an error even though we have compiled the code to es5." }, { "code": null, "e": 71176, "s": 70932, "text": "To solve this issue, we need to add polyfill along with the final es5 compiled code. To run the code in browser, we will take the babel-polyfill file from node modules and add it to the .html file where we want to use promises as shown below −" }, { "code": null, "e": 71441, "s": 71176, "text": "<html>\n <head>\n </head>\n <body>\n <h1>Babel Polyfill Testing</h1>\n <script type=\"text/javascript\" src=\"node_modules/babel-polyfill/dist/polyfill.min.js\"></script>\n <script type=\"text/javascript\" src=\"promise_es5.js\"></script>\n </body>\n</html>" }, { "code": null, "e": 71546, "s": 71441, "text": "In index.html file, we have used the polyfill.min.js file from node_modules followed by promise_es5.js −" }, { "code": null, "e": 71705, "s": 71546, "text": "<script type=\"text/javascript\" src=\"node_modules/babel-polyfill/dist/polyfill.min.js\"></script>\n\n<script type=\"text/javascript\" src=\"promise_es5.js\"></script>" }, { "code": null, "e": 71787, "s": 71705, "text": "Note − Polyfill file has to be used at the start before the main javascript call." }, { "code": null, "e": 71920, "s": 71787, "text": "String padding adds another string from the left side as per the length specified. The syntax for string padding is as shown below −" }, { "code": null, "e": 71979, "s": 71920, "text": "str.padStart(length, string);\nstr.padEnd(length, string);\n" }, { "code": null, "e": 72067, "s": 71979, "text": "const str = 'abc';\n\nconsole.log(str.padStart(8, '_'));\nconsole.log(str.padEnd(8, '_'));" }, { "code": null, "e": 72086, "s": 72067, "text": "_____abc\nabc_____\n" }, { "code": null, "e": 72131, "s": 72086, "text": "npx babel strpad.js --out-file strpad_es5.js" }, { "code": null, "e": 72233, "s": 72131, "text": "'use strict';\n\nvar str = 'abc';\n\nconsole.log(str.padStart(8, '_'));\nconsole.log(str.padEnd(8, '_'));\n" }, { "code": null, "e": 72298, "s": 72233, "text": "The js has to be used along with babel-polyfill as shown below −" }, { "code": null, "e": 72578, "s": 72298, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>BabelJs Testing </title>\n </head>\n <body>\n <script src=\"node_modules/babel-polyfill/dist/polyfill.min.js\" type=\"text/javascript\"></script>\n <script type=\"text/javascript\" src=\"strpad_es5.js\"></script>\n </body>\n</html>" }, { "code": null, "e": 72642, "s": 72578, "text": "In this section, we will learn aboutMap, Set, WeakSet, WeakMap." }, { "code": null, "e": 72681, "s": 72642, "text": "Map is a object with key / value pair." }, { "code": null, "e": 72720, "s": 72681, "text": "Map is a object with key / value pair." }, { "code": null, "e": 72765, "s": 72720, "text": "Set is also a object but with unique values." }, { "code": null, "e": 72810, "s": 72765, "text": "Set is also a object but with unique values." }, { "code": null, "e": 72870, "s": 72810, "text": "WeakMap and WeakSet iare also objects with key/value pairs." }, { "code": null, "e": 72930, "s": 72870, "text": "WeakMap and WeakSet iare also objects with key/value pairs." }, { "code": null, "e": 73135, "s": 72930, "text": "Map, Set, WeakMap and WeakSet are new features added to ES6. To transpile it to be used in older browsers, we need to make use of polyfill. We will work on an example and use polyfill to compile the code." }, { "code": null, "e": 73551, "s": 73135, "text": "let m = new Map(); //map example\nm.set(\"0\",\"A\");\nm.set(\"1\",\"B\");\nconsole.log(m);\n\nlet set = new Set(); //set example\nset.add('A');\nset.add('B');\nset.add('A');\nset.add('B');\nconsole.log(set);\n\nlet ws = new WeakSet(); //weakset example\nlet x = {};\nlet y = {};\nws.add(x);\nconsole.log(ws.has(x));\nconsole.log(ws.has(y));\n\nlet wm = new WeakMap(); //weakmap example\nlet a = {};\nwm.set(a, \"hello\");\nconsole.log(wm.get(a));" }, { "code": null, "e": 73619, "s": 73551, "text": "Map(2) {\"0\" => \"A\", \"1\" => \"B\"}\nSet(2) {\"A\", \"B\"}\ntrue\nfalse\nhello\n" }, { "code": null, "e": 73659, "s": 73619, "text": "npx babel set.js --out-file set_es5.js\n" }, { "code": null, "e": 74092, "s": 73659, "text": "\"use strict\";\n\nvar m = new Map(); //map example\nm.set(\"0\", \"A\");\nm.set(\"1\", \"B\");\nconsole.log(m);\n\nvar set = new Set(); //set example\nset.add('A');\nset.add('B');\nset.add('A');\nset.add('B');\nconsole.log(set);\n\nvar ws = new WeakSet(); //weakset example\nvar x = {};\nvar y = {};\nws.add(x);\nconsole.log(ws.has(x));\nconsole.log(ws.has(y));\n\nvar wm = new WeakMap(); //weakmap example\nvar a = {};\nwm.set(a, \"hello\");\nconsole.log(wm.get(a));" }, { "code": null, "e": 74157, "s": 74092, "text": "The js has to be used along with babel-polyfill as shown below −" }, { "code": null, "e": 74433, "s": 74157, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>BabelJs Testing</title>\n </head>\n <body>\n <script src=\"node_modules/babel-polyfill/dist/polyfill.min.js\" type=\"text/javascript\"></script>\n <script type=\"text/javascript\" src=\"set_es5.js\"></script>\n </body>\n</html>" }, { "code": null, "e": 74529, "s": 74433, "text": "Many properties and methods can be used on array; for example, array.from, array.includes, etc." }, { "code": null, "e": 74605, "s": 74529, "text": "Let us consider working on the following example to understand this better." }, { "code": null, "e": 74621, "s": 74605, "text": "arraymethods.js" }, { "code": null, "e": 74727, "s": 74621, "text": "var arrNum = [1, 2, 3];\n\nconsole.log(arrNum.includes(2));\nconsole.log(Array.from([3, 4, 5], x => x + x));" }, { "code": null, "e": 74734, "s": 74727, "text": "Output" }, { "code": null, "e": 74751, "s": 74734, "text": "true\n[6, 8, 10]\n" }, { "code": null, "e": 74809, "s": 74751, "text": "npx babel arraymethods.js --out-file arraymethods_es5.js\n" }, { "code": null, "e": 74950, "s": 74809, "text": "\"use strict\";\n\nvar arrNum = [1, 2, 3];\n\nconsole.log(arrNum.includes(2));\nconsole.log(Array.from([3, 4, 5], function (x) {\nreturn x + x;\n}));" }, { "code": null, "e": 75101, "s": 74950, "text": "The methods used on the array are printed as they are. To make them work on older browsers, we need to add polyfill file at the start as shown below −" }, { "code": null, "e": 75367, "s": 75101, "text": "<html>\n <head></head>\n <body>\n <h1>Babel Polyfill Testing</h1>\n <script type=\"text/javascript\" src=\"node_modules/babel-polyfill/dist/polyfill.min.js\"></script>\n <script type=\"text/javascript\" src=\"arraymethods_es5.js\"></script>\n </body>\n</html>" }, { "code": null, "e": 75589, "s": 75367, "text": "BabelJS comes with a built-in Command Line Interface wherein, the JavaScript code can be easily compiled to the respective ECMA Script using easy to use commands. We will discuss the use of these commands in this chapter." }, { "code": null, "e": 75683, "s": 75589, "text": "First, we will install babel-cli for our project. We will use babeljs for compiling the code." }, { "code": null, "e": 75747, "s": 75683, "text": "Create a folder for your project to play around with babel-cli." }, { "code": null, "e": 75757, "s": 75747, "text": "npm init\n" }, { "code": null, "e": 75802, "s": 75757, "text": "Package.json created for the above project −" }, { "code": null, "e": 75848, "s": 75802, "text": "Let us run the commands to install babel-cli." }, { "code": null, "e": 75882, "s": 75848, "text": "npm install --save-dev babel-cli\n" }, { "code": null, "e": 75917, "s": 75882, "text": "npm install --save-dev @babel/cli\n" }, { "code": null, "e": 75984, "s": 75917, "text": "We have installed babel-cli and here is the updated package.json −" }, { "code": null, "e": 76102, "s": 75984, "text": "In addition to this, we need to install babel-preset and babel-core. Let us now see the command for the installation." }, { "code": null, "e": 76177, "s": 76102, "text": "npm install --save-dev babel-preset-env\nnpm install --save-dev babel-core\n" }, { "code": null, "e": 76254, "s": 76177, "text": "npm install --save-dev @babel/core\nnpm install --save-dev @babel/preset-env\n" }, { "code": null, "e": 76312, "s": 76254, "text": "Here is the updated package.json for the above commands −" }, { "code": null, "e": 76656, "s": 76312, "text": "Since we need to compile to JavaScript code that we are going to write to have backward compatibility, we will compile it to ECMA Script 5. For this, we need to instruct babel to look for the preset, i.e., es version wherein compilation will be done. We need to create a .babelrc> file in the root folder of our project created as shown below." }, { "code": null, "e": 76719, "s": 76656, "text": "It contains a json object with the following presets details −" }, { "code": null, "e": 76742, "s": 76719, "text": "{ \"presets\": [\"env\"] }" }, { "code": null, "e": 76783, "s": 76742, "text": "For babel 7 the .babelrc is as follows −" }, { "code": null, "e": 76815, "s": 76783, "text": "{\n \"presets\":[\"@babel/env\"]\n}" }, { "code": null, "e": 76964, "s": 76815, "text": "We have installed babel local to the project. In order to make use of babel in our project, we need to specify the same in package.json as follows −" }, { "code": null, "e": 77145, "s": 76964, "text": "Now we are ready to compile our JavaScript files. Create a folder src in your project; in this folder, create a file called main.js and write a es6 javascript code as shown below −" }, { "code": null, "e": 77168, "s": 77145, "text": "npx babel src/main.js\n" }, { "code": null, "e": 77428, "s": 77168, "text": "In the above case, the code from main.js is displayed in the terminal in es5 version. The arrow function from es6 is converted to es5 as shown above. Instead of displaying the compiled code in the terminal, we will store it in a different file as shown below." }, { "code": null, "e": 77612, "s": 77428, "text": "We have created a folder in our project called out wherein, we want the compiled files to be stored. Following is the command which will compile and store the output where we want it." }, { "code": null, "e": 77662, "s": 77612, "text": "npx babel src/main.js --out-file out/main_out.js\n" }, { "code": null, "e": 77761, "s": 77662, "text": "The option in the command --out-file helps us store the output in the file location of our choice." }, { "code": null, "e": 77899, "s": 77761, "text": "Incase we want the file to be updated every time we make changes to the main file add --watch or -w option to the command as shown below." }, { "code": null, "e": 77957, "s": 77899, "text": "npx babel src/main.js --watch --out-file out/main_out.js\n" }, { "code": null, "e": 78046, "s": 77957, "text": "You can make the change to the main file; this change will reflect in the compiled file." }, { "code": null, "e": 78198, "s": 78046, "text": "In the above case, we changed the log message and the --watch option keeps checking for any change and the same changes are added in the compiled file." }, { "code": null, "e": 78351, "s": 78198, "text": "In our previous sections, we learnt how to compile individual files. Now, we will compile a directory and store the compiled files in another directory." }, { "code": null, "e": 78491, "s": 78351, "text": "In the src folder, we will create one more js file called main1.js. At present, the src folder has 2 javascript files main.js and main1.js." }, { "code": null, "e": 78528, "s": 78491, "text": "Following is the code in the files −" }, { "code": null, "e": 78536, "s": 78528, "text": "main.js" }, { "code": null, "e": 78618, "s": 78536, "text": "var arrowfunction = () => {\n console.log(\"Added changes to the log message\");\n}" }, { "code": null, "e": 78627, "s": 78618, "text": "main1.js" }, { "code": null, "e": 78690, "s": 78627, "text": "var handler = () => {\n console.log(\"Added one more file\");\n}" }, { "code": null, "e": 78914, "s": 78690, "text": "Following command will compile code from the src folder and store it in the out/ folder. We have removed all the files from the out/ folder and kept it empty. We will run the command and check the output in the out/ folder." }, { "code": null, "e": 78943, "s": 78914, "text": "npx babel src --out-dir out\n" }, { "code": null, "e": 78999, "s": 78943, "text": "We got 2 files in the out folder - main.js and main1.js" }, { "code": null, "e": 79007, "s": 78999, "text": "main.js" }, { "code": null, "e": 79124, "s": 79007, "text": "\"use strict\";\n\nvar arrowfunction = function arrowfunction() {\n console.log(\"Added changes to the log message\");\n};" }, { "code": null, "e": 79133, "s": 79124, "text": "main1.js" }, { "code": null, "e": 79225, "s": 79133, "text": "\"use strict\";\n\nvar handler = function handler() {\n console.log(\"Added one more file\");\n};" }, { "code": null, "e": 79327, "s": 79225, "text": "Next, we will execute the command given below to compile both files into a single file using babeljs." }, { "code": null, "e": 79364, "s": 79327, "text": "npx babel src --out-file out/all.js\n" }, { "code": null, "e": 79571, "s": 79364, "text": "\"use strict\";\n\nvar arrowfunction = function arrowfunction() {\n console.log(\"Added changes to the log message\");\n};\n\"use strict\";\n\nvar handler = function handler() {\nconsole.log(\"Added one more file\");\n};\n" }, { "code": null, "e": 79676, "s": 79571, "text": "In case we want to ignore some files from being compiled, we can use the option --ignore as shown below." }, { "code": null, "e": 79735, "s": 79676, "text": "npx babel src --out-file out/all.js --ignore src/main1.js\n" }, { "code": null, "e": 79742, "s": 79735, "text": "all.js" }, { "code": null, "e": 79859, "s": 79742, "text": "\"use strict\";\n\nvar arrowfunction = function arrowfunction() {\n console.log(\"Added changes to the log message\");\n};" }, { "code": null, "e": 79992, "s": 79859, "text": "We can make use of plugins options to be used during file compilation. To make use of plugins, we need to install it as shown below." }, { "code": null, "e": 80063, "s": 79992, "text": "npm install --save-dev babel-plugin-transform-exponentiation-operator\n" }, { "code": null, "e": 80071, "s": 80063, "text": "expo.js" }, { "code": null, "e": 80107, "s": 80071, "text": "let sqr = 9 ** 2;\nconsole.log(sqr);" }, { "code": null, "e": 80211, "s": 80107, "text": "npx babel expo.js --out-file expo_compiled.js --plugins=babel-plugin-transform-exponentiation-operator\n" }, { "code": null, "e": 80271, "s": 80211, "text": "\"use strict\";\n\nvar sqr = Math.pow(9, 2);\nconsole.log(sqr);\n" }, { "code": null, "e": 80326, "s": 80271, "text": "We can also use presets in the command as shown below." }, { "code": null, "e": 80389, "s": 80326, "text": "npx babel src/main.js --out-file main_es5.js --presets=es2015\n" }, { "code": null, "e": 80459, "s": 80389, "text": "To test the above case, we have removed presets option from .babelrc." }, { "code": null, "e": 80467, "s": 80459, "text": "main.js" }, { "code": null, "e": 80549, "s": 80467, "text": "var arrowfunction = () => {\n console.log(\"Added changes to the log message\");\n}" }, { "code": null, "e": 80561, "s": 80549, "text": "main_es5.js" }, { "code": null, "e": 80678, "s": 80561, "text": "\"use strict\";\n\nvar arrowfunction = function arrowfunction() {\n console.log(\"Added changes to the log message\");\n};" }, { "code": null, "e": 80741, "s": 80678, "text": "We can also ignore .babelrc from the command line as follows −" }, { "code": null, "e": 80817, "s": 80741, "text": "npx babel --no-babelrc src/main.js --out-file main_es5.js --presets=es2015\n" }, { "code": null, "e": 81015, "s": 80817, "text": "To test the above case, we have added presets back to .babelrc and the same will get ignored because of --no-babelrc that we have added in the command. The main_es5.js file details are as follows −" }, { "code": null, "e": 81027, "s": 81015, "text": "main_es5.js" }, { "code": null, "e": 81144, "s": 81027, "text": "\"use strict\";\n\nvar arrowfunction = function arrowfunction() {\n console.log(\"Added changes to the log message\");\n};" }, { "code": null, "e": 81335, "s": 81144, "text": "Babel presets are config details to the babel-transpiler telling it to transpile it in the specified mode. Here are some of the most popular presets we are going to discuss in this chapter −" }, { "code": null, "e": 81342, "s": 81335, "text": "ES2015" }, { "code": null, "e": 81346, "s": 81342, "text": "Env" }, { "code": null, "e": 81352, "s": 81346, "text": "React" }, { "code": null, "e": 81824, "s": 81352, "text": "We need to use presets that have the environment in which we want the code to be converted. For example, es2015 preset will convert the code to es5. Preset with value env will also convert to es5. It also has additional feature, i.e., options. In case you want the feature to be supported on recent versions of browsers, babel will convert the code only if there is no support of features on those browsers. With Preset react, Babel will transpile the code when to react." }, { "code": null, "e": 81974, "s": 81824, "text": "To work with Presets, we need to create .babelrc file in our project root folder. To show the working, we will create a project setup as shown below." }, { "code": null, "e": 81984, "s": 81974, "text": "npm init\n" }, { "code": null, "e": 82079, "s": 81984, "text": "We have to install the required babel preset as follows along with babel cli, babel core, etc." }, { "code": null, "e": 82144, "s": 82079, "text": "npm install babel-cli babel-core babel-preset-es2015 --save-dev\n" }, { "code": null, "e": 82209, "s": 82144, "text": "npm install @babel/cli @babel/core @babel/preset-env --save-dev\n" }, { "code": null, "e": 82267, "s": 82209, "text": "Note − babel-preset-es2015 is deprecated babel 7 onwards." }, { "code": null, "e": 82288, "s": 82267, "text": "es2015 or @babel/env" }, { "code": null, "e": 82348, "s": 82288, "text": "Create .babelrc file in the root of the project (babel 6) −" }, { "code": null, "e": 82478, "s": 82348, "text": "In .babelrc, the presets is es2015. This is the indication to the babel compiler that we want the code to be converted to es2015." }, { "code": null, "e": 82527, "s": 82478, "text": "For babel 7, we need to use presets as follows −" }, { "code": null, "e": 82559, "s": 82527, "text": "{\n \"presets\":[\"@babel/env\"]\n}" }, { "code": null, "e": 82605, "s": 82559, "text": "Here is the package.json after installation −" }, { "code": null, "e": 82712, "s": 82605, "text": "Since we have installed babel locally, we have added babel command in the scripts section in package.json." }, { "code": null, "e": 82794, "s": 82712, "text": "Let us work on a simple example to check for the transpiling using preset es2015." }, { "code": null, "e": 82802, "s": 82794, "text": "main.js" }, { "code": null, "e": 82864, "s": 82802, "text": "let arrow = () => {\n return \"this is es6 arrow function\";\n}" }, { "code": null, "e": 82898, "s": 82864, "text": "Transpiled to es5 as shown below." }, { "code": null, "e": 82940, "s": 82898, "text": "npx babel main.js --out-file main_es5.js\n" }, { "code": null, "e": 82952, "s": 82940, "text": "main_es5.js" }, { "code": null, "e": 83041, "s": 82952, "text": "\"use strict\";\n\nvar arrow = function arrow() {\n return \"this is es6 arrow function\";\n};" }, { "code": null, "e": 83131, "s": 83041, "text": "Using Env preset, you can specify the environment you the final code to be transpiled to." }, { "code": null, "e": 83246, "s": 83131, "text": "We are going to use the same project setup created above and change the presets from es2015 to env as shown below." }, { "code": null, "e": 83361, "s": 83246, "text": "In addition, we need to install the babel-preset-env. We will execute the command given below to install the same." }, { "code": null, "e": 83402, "s": 83361, "text": "npm install babel-preset-env --save-dev\n" }, { "code": null, "e": 83452, "s": 83402, "text": "We will compile main.js again and see the output." }, { "code": null, "e": 83460, "s": 83452, "text": "main.js" }, { "code": null, "e": 83522, "s": 83460, "text": "let arrow = () => {\n return \"this is es6 arrow function\";\n}" }, { "code": null, "e": 83564, "s": 83522, "text": "npx babel main.js --out-file main_env.js\n" }, { "code": null, "e": 83576, "s": 83564, "text": "main_env.js" }, { "code": null, "e": 83665, "s": 83576, "text": "\"use strict\";\n\nvar arrow = function arrow() {\n return \"this is es6 arrow function\";\n};" }, { "code": null, "e": 83911, "s": 83665, "text": "We have seen the transpiled code is es5. Incase we know the environment in which our code is going to execute, we can use this preset to specify it. For example, if we specify the browsers as last 1 version for chrome and firefox as shown below." }, { "code": null, "e": 83953, "s": 83911, "text": "npx babel main.js --out-file main_env.js\n" }, { "code": null, "e": 83965, "s": 83953, "text": "main_env.js" }, { "code": null, "e": 84043, "s": 83965, "text": "\"use strict\";\n\nlet arrow = () => {\n return \"this is es6 arrow function\";\n};" }, { "code": null, "e": 84247, "s": 84043, "text": "We are now getting the arrow function syntax as it is. It is not transpiled into ES5 syntax. This is because the environment which we want our code to support, already has support for the arrow function." }, { "code": null, "e": 84417, "s": 84247, "text": "Babel takes care of compiling the code based on environment using the babel-preset-env. We can also target the compilation based on the nodejs environment as shown below" }, { "code": null, "e": 84470, "s": 84417, "text": "The final compilation of the code is as shown below." }, { "code": null, "e": 84512, "s": 84470, "text": "npx babel main.js --out-file main_env.js\n" }, { "code": null, "e": 84524, "s": 84512, "text": "main_env.js" }, { "code": null, "e": 84602, "s": 84524, "text": "\"use strict\";\n\nlet arrow = () => {\n return \"this is es6 arrow function\";\n};" }, { "code": null, "e": 84664, "s": 84602, "text": "Babel compiles the code as per the current version of nodejs." }, { "code": null, "e": 84788, "s": 84664, "text": "We can use react preset when we are using Reactjs. We will work on a simple example and use react preset to see the output." }, { "code": null, "e": 84868, "s": 84788, "text": "To use the preset, we need to install babel-preset-react (babel 6) as follows −" }, { "code": null, "e": 84911, "s": 84868, "text": "npm install --save-dev babel-preset-react\n" }, { "code": null, "e": 84943, "s": 84911, "text": "For babel 7, it is as follows −" }, { "code": null, "e": 84987, "s": 84943, "text": "npm install --save-dev @babel/preset-react\n" }, { "code": null, "e": 85035, "s": 84987, "text": "Changes to .babelrc are as follows for babel6 −" }, { "code": null, "e": 85047, "s": 85035, "text": "For babel 7" }, { "code": null, "e": 85089, "s": 85047, "text": "{\n \"presets\": [\"@babel/preset-react\"]\n}" }, { "code": null, "e": 85097, "s": 85089, "text": "main.js" }, { "code": null, "e": 85120, "s": 85097, "text": "<h1>Hello, world!</h1>" }, { "code": null, "e": 85162, "s": 85120, "text": "npx babel main.js --out-file main_env.js\n" }, { "code": null, "e": 85174, "s": 85162, "text": "main_env.js" }, { "code": null, "e": 85235, "s": 85174, "text": "React.createElement(\n \"h1\",\n null,\n \"Hello, world!\"\n);" }, { "code": null, "e": 85307, "s": 85235, "text": "The code from main.js is converted to reactjs syntax with preset:react." }, { "code": null, "e": 85834, "s": 85307, "text": "Webpack is a module bundler which packs all modules with dependencies – js, styles, images, etc. into static assets .js, .css, .jpg , .png, etc. Webpack comes with presets which help for compilation into the required form. For example, react preset that helps to get the final output in react form, es2015 or env preset that helps to compile the code in ES5 or 6 or 7, etc. We have used babel 6 in the project setup. In case you want to switch to babel7, install the required packages of babel using @babel/babel-package-name." }, { "code": null, "e": 85959, "s": 85834, "text": "Here, we will discuss project setup using babel and webpack. Create a folder called and open the same in visual studio IDE." }, { "code": null, "e": 86026, "s": 85959, "text": "To create the project setup, run npm initbabelwebpack as follows −" }, { "code": null, "e": 86076, "s": 86026, "text": "Here is the package.json created after npm init −" }, { "code": null, "e": 86160, "s": 86076, "text": "Now, we will install the necessary packages we need to work with babel and webpack." }, { "code": null, "e": 86344, "s": 86160, "text": "npm install --save-dev webpack\nnpm install --save-dev webpack-dev-server\nnpm install --save-dev babel-core\nnpm install --save-dev babel-loader\nnpm install --save-dev babel-preset-env\n" }, { "code": null, "e": 86390, "s": 86344, "text": "Here is the Package.json after installation −" }, { "code": null, "e": 86546, "s": 86390, "text": "Now, we will create a webpack.config.js file, which will have all the details to bundle the js files. These files will be compiled it into es5 using babel." }, { "code": null, "e": 86638, "s": 86546, "text": "To run webpack using server, we use webpack-server. Following are the details added to it −" }, { "code": null, "e": 86861, "s": 86638, "text": "We have added the publish command which will start the webpack-dev-server and will update the path where the final files are stored. Right now the path that we are going to use to update the final files is the /dev folder." }, { "code": null, "e": 86916, "s": 86861, "text": "To use webpack, we need to run the following command −" }, { "code": null, "e": 86933, "s": 86916, "text": "npm run publish\n" }, { "code": null, "e": 87049, "s": 86933, "text": "First we need to create the webpack.config.js files. These will have the configuration details for webpack to work." }, { "code": null, "e": 87090, "s": 87049, "text": "The details in the file are as follows −" }, { "code": null, "e": 87551, "s": 87090, "text": "var path = require('path');\n\nmodule.exports = {\n entry: {\n app: './src/main.js'\n },\n output: {\n path: path.resolve(__dirname, 'dev'),\n filename: 'main_bundle.js'\n },\n mode:'development',\n module: {\n rules: [\n {\n test: /\\.js$/,\n include: path.resolve(__dirname, 'src'),\n loader: 'babel-loader',\n query: {\n presets: ['env']\n }\n }\n ]\n }\n};" }, { "code": null, "e": 87660, "s": 87551, "text": "The structure of the file is as shown above. It starts with theh path, which gives the current path details." }, { "code": null, "e": 87713, "s": 87660, "text": "var path = require('path'); //gives the current path" }, { "code": null, "e": 87890, "s": 87713, "text": "Next is the module.exports object, which has properties entry, output and module. The entry is the start point. Here, we need to give the main js files that has to be compiled." }, { "code": null, "e": 87927, "s": 87890, "text": "entry: {\n app: './src/main.js'\n},\n" }, { "code": null, "e": 88042, "s": 87927, "text": "path.resolve(_dirname, ‘src/main.js’) -- will look for the src folder in the directory and main.js in that folder." }, { "code": null, "e": 88127, "s": 88042, "text": "output: {\n path: path.resolve(__dirname, 'dev'),\n filename: 'main_bundle.js'\n},\n" }, { "code": null, "e": 88322, "s": 88127, "text": "Output is an object with path and filename details. Path will hold the folder in which the compiled file will be kept and filename will tell the name of final file to be used in your .html file." }, { "code": null, "e": 88532, "s": 88322, "text": "module: {\n rules: [\n {\n test: /\\.js$/,\n include: path.resolve(__dirname, 'src'),\n loader: 'babel-loader',\n query: {\n presets: ['env']\n }\n }\n ]\n}" }, { "code": null, "e": 88613, "s": 88532, "text": "Module is an object with details of the rules. It has the following properties −" }, { "code": null, "e": 88694, "s": 88613, "text": "Module is an object with details of the rules. It has the following properties −" }, { "code": null, "e": 88699, "s": 88694, "text": "test" }, { "code": null, "e": 88707, "s": 88699, "text": "include" }, { "code": null, "e": 88714, "s": 88707, "text": "loader" }, { "code": null, "e": 88720, "s": 88714, "text": "query" }, { "code": null, "e": 88861, "s": 88720, "text": "Test will hold details of all the js files ending with .js. It has the pattern, which will look for .js at the end in the entry point given." }, { "code": null, "e": 89002, "s": 88861, "text": "Test will hold details of all the js files ending with .js. It has the pattern, which will look for .js at the end in the entry point given." }, { "code": null, "e": 89068, "s": 89002, "text": "Include instructs the folder in use on the files to be looked at." }, { "code": null, "e": 89134, "s": 89068, "text": "Include instructs the folder in use on the files to be looked at." }, { "code": null, "e": 89180, "s": 89134, "text": "Loader uses babel-loader for compiling codes." }, { "code": null, "e": 89226, "s": 89180, "text": "Loader uses babel-loader for compiling codes." }, { "code": null, "e": 89308, "s": 89226, "text": "Query has property presets, which is an array with value env – es5 or es6 or es7." }, { "code": null, "e": 89390, "s": 89308, "text": "Query has property presets, which is an array with value env – es5 or es6 or es7." }, { "code": null, "e": 89536, "s": 89390, "text": "Create folder src and main.js in it; write your js code in ES6. Later, run the command to see it getting compiled to es5 using webpack and babel." }, { "code": null, "e": 89548, "s": 89536, "text": "src/main.js" }, { "code": null, "e": 89624, "s": 89548, "text": "let add = (a,b) => {\n return a+b;\n};\nlet c = add(10, 20);\nconsole.log(c);" }, { "code": null, "e": 89642, "s": 89624, "text": "Run the command −" }, { "code": null, "e": 89656, "s": 89642, "text": "npm run pack\n" }, { "code": null, "e": 89693, "s": 89656, "text": "The compiled file looks as follows −" }, { "code": null, "e": 89712, "s": 89693, "text": "dev/main_bundle.js" }, { "code": null, "e": 92138, "s": 89712, "text": "!function(e) {\n var t = {};\n function r(n) {\n if(t[n])return t[n].exports;var o = t[n] = {i:n,l:!1,exports:{}};\n return e[n].call(o.exports,o,o.exports,r),o.l=!0,o.exports\n }\n r.m = e,r.c = t,r.d = function(e,t,n) {\n r.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n})\n },\n r.r = function(e) {\n \"undefined\"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:\"Module\"}),Object.defineProperty(e,\"__esModule\",{value:!0})\n },\n r.t = function(e,t) {\n if(1&t&&(e = r(e)),8&t)return e;\n if(4&t&&\"object\"==typeof e&&e&&e.__esModule)return e;\n var n = Object.create(null);\n if(r.r(n),Object.defineProperty(n,\"default\",{enumerable:!0,value:e}),2&t&&\"string\"!=typeof e)for(var o in e)r.d(n,o,function(t) {return e[t]}.bind(null,o));\n return n\n },\n r.n = function(e) {\n var t = e&&e.__esModule?function() {return e.default}:function() {return e};\n return r.d(t,\"a\",t),t\n },\n r.o = function(e,t) {return Object.prototype.hasOwnProperty.call(e,t)},\n r.p = \"\",r(r.s = 0)\n}([function(e,t,r) {\"use strict\";var n = function(e,t) {return e+t}(10,20);console.log(n)}]);\n!function(e) {\n var t = {};\n function r(n) {\n if(t[n])return t[n].exports;\n var o = t[n] = {i:n,l:!1,exports:{}};\n return e[n].call(o.exports,o,o.exports,r),o.l=!0,o.exports\n }\n r.m = e,r.c = t,r.d = function(e,t,n) {\n r.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n})\n },\n r.r = function(e) {\n \"undefined\"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:\"Module\"}),Object.defineProperty(e,\"__esModule\",{value:!0})\n },\n r.t = function(e,t) {\n if(1&t&&(e=r(e)),\n 8&t)return e;\n if(4&t&&\"object\"==typeof e&&e&&e.__esModule)return e;\n var n = Object.create(null);\n if(\n r.r(n),\n Object.defineProperty(n,\"default\",{enumerable:!0,value:e}),\n 2&t&&\"string\"!=typeof e\n )\n for(var o in e)r.d(n,o,function(t) {return e[t]}.bind(null,o));\n return n\n },\n r.n = function(e) {\n var t = e&&e.__esModule?function() {return e.default}:function() {return e};\n return r.d(t,\"a\",t),t\n },\n r.o = function(e,t) {\n return Object.prototype.hasOwnProperty.call(e,t)\n },\n r.p = \"\",r(r.s = 0)\n}([function(e,t,r) {\n \"use strict\";\n var n = function(e,t) {return e+t}(10,20);\n console.log(n)\n}]);" }, { "code": null, "e": 92316, "s": 92138, "text": "The code is compiled as shown above. Webpack adds some code which is required internally and the code from main.js is seen at the end. We have consoled the value as shown above." }, { "code": null, "e": 92365, "s": 92316, "text": "Add the final js file in .html file as follows −" }, { "code": null, "e": 92490, "s": 92365, "text": "<html>\n <head></head>\n <body>\n <script type=\"text/javascript\" src=\"dev/main_bundle.js\"></script>\n </body>\n</html>" }, { "code": null, "e": 92508, "s": 92490, "text": "Run the command −" }, { "code": null, "e": 92525, "s": 92508, "text": "npm run publish\n" }, { "code": null, "e": 92572, "s": 92525, "text": "To check the output, we can open the file in −" }, { "code": null, "e": 92595, "s": 92572, "text": "http://localhost:8080/" }, { "code": null, "e": 92704, "s": 92595, "text": "We get the console value as shown above. Now let us try to compile to a single file using webpack and babel." }, { "code": null, "e": 92823, "s": 92704, "text": "We will use webpack to bundle multiple js files into a single file. Babel will be used to compile the es6 code to es5." }, { "code": null, "e": 92903, "s": 92823, "text": "Now, we have 2 js files in the src/ folder - main.js and Person.js as follows −" }, { "code": null, "e": 92913, "s": 92903, "text": "person.js" }, { "code": null, "e": 93158, "s": 92913, "text": "export class Person {\n constructor(fname, lname, age, address) {\n this.fname = fname;\n this.lname = lname;\n this.age = age;\n this.address = address;\n }\n\n get fullname() {\n return this.fname +\"-\"+this.lname;\n }\n}" }, { "code": null, "e": 93218, "s": 93158, "text": "We have used export to use the details of the Person class." }, { "code": null, "e": 93226, "s": 93218, "text": "main.js" }, { "code": null, "e": 93364, "s": 93226, "text": "import {Person} from './person'\nvar a = new Person(\"Siya\", \"Kapoor\", \"15\", \"Mumbai\");\nvar persondet = a.fullname;\nconsole.log(persondet);" }, { "code": null, "e": 93420, "s": 93364, "text": "In main.js, we have imported Person from the file path." }, { "code": null, "e": 93577, "s": 93420, "text": "Note − We do not have to include person.js but just the name of the file. We have created an object of Person class and consoled the details as shown above." }, { "code": null, "e": 93735, "s": 93577, "text": "Webpack will combine person.js and main.js and update in dev/main_bundle.js as one file. Run the command npm run publish to check the output in the browser −" }, { "code": null, "e": 93862, "s": 93735, "text": "In this chapter, we will understand working with JSX and babel. Before we get into the details, let us understand what JSX is." }, { "code": null, "e": 94002, "s": 93862, "text": "JSX is a JavaScript code with a combination of xml syntax in it. JSX tag has tag name, attributes and children which make it look like xml." }, { "code": null, "e": 94146, "s": 94002, "text": "React uses JSX for templating instead of regular JavaScript. It is not necessary to use it, however, following are some pros that come with it." }, { "code": null, "e": 94228, "s": 94146, "text": "It is faster because it performs optimization while compiling code to JavaScript." }, { "code": null, "e": 94310, "s": 94228, "text": "It is faster because it performs optimization while compiling code to JavaScript." }, { "code": null, "e": 94388, "s": 94310, "text": "It is also type-safe and most of the errors can be caught during compilation." }, { "code": null, "e": 94466, "s": 94388, "text": "It is also type-safe and most of the errors can be caught during compilation." }, { "code": null, "e": 94547, "s": 94466, "text": "It makes it easier and faster to write templates, if you are familiar with HTML." }, { "code": null, "e": 94628, "s": 94547, "text": "It makes it easier and faster to write templates, if you are familiar with HTML." }, { "code": null, "e": 94782, "s": 94628, "text": "We have used babel 6 in the project setup. In case you want to switch to babel 7, install the required packages of babel using @babel/babel-package-name." }, { "code": null, "e": 94887, "s": 94782, "text": "We will create project setup and use webpack to compile jsx with react to normal JavaScript using Babel." }, { "code": null, "e": 94987, "s": 94887, "text": "To start the project setup, run the commands given below for babel, react and webpack installation." }, { "code": null, "e": 94997, "s": 94987, "text": "npm init\n" }, { "code": null, "e": 95089, "s": 94997, "text": "Now, we will install the necessary packages we need to work with – babel ,webpack and jsx −" }, { "code": null, "e": 95415, "s": 95089, "text": "npm install --save-dev webpack\nnpm install --save-dev webpack-cli\nnpm install --save-dev webpack-dev-server\nnpm install --save-dev babel-core\nnpm install --save-dev babel-loader\nnpm install --save-dev babel-preset-es2015\nnpm install --save-dev babel-preset-react\nnpm install --save-dev react\nnpm install --save-dev react-dom\n" }, { "code": null, "e": 95461, "s": 95415, "text": "Here is the package.json after installation −" }, { "code": null, "e": 95595, "s": 95461, "text": "Now will create a webpack.config.js file, which will have all the details to bundle the js files and compile it into es5 using babel." }, { "code": null, "e": 95900, "s": 95595, "text": "To run webpack using server, there is something called webpack-server. We have added command called publish; this command will start the webpack-dev-server and will update the path where the final files are stored. Right now the path that we are going to use to update the final files is the /dev folder." }, { "code": null, "e": 95954, "s": 95900, "text": "To use webpack we need to run the following command −" }, { "code": null, "e": 95971, "s": 95954, "text": "npm run publish\n" }, { "code": null, "e": 96073, "s": 95971, "text": "We will create the webpack.config.js files, which have the configuration details for webpack to work." }, { "code": null, "e": 96114, "s": 96073, "text": "The details in the file are as follows −" }, { "code": null, "e": 96591, "s": 96114, "text": "var path = require('path');\n\nmodule.exports = {\n entry: {\n app: './src/main.js'\n },\n output: {\n path: path.resolve(__dirname, 'dev'),\n filename: 'main_bundle.js'\n },\n mode:'development',\n module: {\n rules: [\n {\n test:/\\.(js|jsx)$/,\n include: path.resolve(__dirname, 'src'),\n loader: 'babel-loader',\n query: {\n presets: ['es2015','react']\n }\n }\n ]\n }\n};" }, { "code": null, "e": 96699, "s": 96591, "text": "The structure of the file is as shown above. It starts with the path, which gives the current path details." }, { "code": null, "e": 96752, "s": 96699, "text": "var path = require('path'); //gives the current path" }, { "code": null, "e": 96834, "s": 96752, "text": "Next is the module.exports object, which has properties entry, output and module." }, { "code": null, "e": 96919, "s": 96834, "text": "Entry is the start point. Here we need to give the main js files we want to compile." }, { "code": null, "e": 96955, "s": 96919, "text": "entry: {\n app: './src/main.js'\n}," }, { "code": null, "e": 97070, "s": 96955, "text": "path.resolve(_dirname, ‘src/main.js’) -- will look for the src folder in the directory and main.js in that folder." }, { "code": null, "e": 97155, "s": 97070, "text": "output: {\n path: path.resolve(__dirname, 'dev'),\n filename: 'main_bundle.js'\n},\n" }, { "code": null, "e": 97354, "s": 97155, "text": "Output is an object with path and filename details. Path will hold the folder in which the compiled file will be kept and filename will tell the name of the final file to be used in your .html file." }, { "code": null, "e": 97580, "s": 97354, "text": "module: {\n rules: [\n {\n test:/\\.(js|jsx)$/,\n include: path.resolve(__dirname, 'src'),\n loader: 'babel-loader',\n query: {\n presets: ['es2015','react']\n }\n }\n ]\n}" }, { "code": null, "e": 97671, "s": 97580, "text": "Module is object with rules details which has properties ie test, include , loader, query." }, { "code": null, "e": 97762, "s": 97671, "text": "Module is object with rules details which has properties ie test, include , loader, query." }, { "code": null, "e": 97918, "s": 97762, "text": "Test will hold details of all the js file ending with .js and .jsx.It has the pattern which will look for .js and .jsx at the end in the entry point given." }, { "code": null, "e": 98074, "s": 97918, "text": "Test will hold details of all the js file ending with .js and .jsx.It has the pattern which will look for .js and .jsx at the end in the entry point given." }, { "code": null, "e": 98133, "s": 98074, "text": "Include tells the folder to be used for looking the files." }, { "code": null, "e": 98192, "s": 98133, "text": "Include tells the folder to be used for looking the files." }, { "code": null, "e": 98237, "s": 98192, "text": "Loader uses babel-loader for compiling code." }, { "code": null, "e": 98282, "s": 98237, "text": "Loader uses babel-loader for compiling code." }, { "code": null, "e": 98406, "s": 98282, "text": "Query has property presets, which is array with value env – es5 or es6 or es7. We have used es2015 and react as the preset." }, { "code": null, "e": 98530, "s": 98406, "text": "Query has property presets, which is array with value env – es5 or es6 or es7. We have used es2015 and react as the preset." }, { "code": null, "e": 98581, "s": 98530, "text": "Create folder src/. Add main.js and App.jsx in it." }, { "code": null, "e": 98589, "s": 98581, "text": "App.jsx" }, { "code": null, "e": 98867, "s": 98589, "text": "import React from 'react';\n\nclass App extends React.Component {\n render() {\n var style = {\n color: 'red',\n fontSize: 50\n };\n return (\n <div style={style}>\n Hello World!!!\n </div>\n );\n }\n}\nexport default App;" }, { "code": null, "e": 98875, "s": 98867, "text": "main.js" }, { "code": null, "e": 99017, "s": 98875, "text": "import React from 'react';\nimport ReactDOM from 'react-dom';\nimport App from './App.jsx';\n\nReactDOM.render(, document.getElementById('app'));" }, { "code": null, "e": 99113, "s": 99017, "text": "Run the following command to bundle the .js file and convert it using presets es2015 and react." }, { "code": null, "e": 99127, "s": 99113, "text": "npm run pack\n" }, { "code": null, "e": 99182, "s": 99127, "text": "Add main_bundle.js from the dev folder to index.html −" }, { "code": null, "e": 99409, "s": 99182, "text": "<!DOCTYPE html>\n<html lang = \"en\">\n <head>\n <meta charset = \"UTF-8\">\n <title>React App</title>\n </head>\n <body>\n <div id = \"app\"></div>\n <script src = \"dev/main_bundle.js\"></script>\n </body>\n</html>" }, { "code": null, "e": 99426, "s": 99409, "text": "npm run publish\n" }, { "code": null, "e": 99693, "s": 99426, "text": "Flow is a static type checker for JavaScript. To work with flow and babel, we will first create a project setup. We have used babel 6 in the project setup. In case you want to switch to babel 7, install the required packages of babel using @babel/babel-package-name." }, { "code": null, "e": 99703, "s": 99693, "text": "npm init\n" }, { "code": null, "e": 99754, "s": 99703, "text": "Install the required packages for flow and babel −" }, { "code": null, "e": 99866, "s": 99754, "text": "npm install --save-dev babel-core babel-cli babel-preset-flow flow-bin babel-plugin-transform-flow-strip-types\n" }, { "code": null, "e": 99988, "s": 99866, "text": "Here is the final package.json after installation. Also added babel and flow command to execute the code in command line." }, { "code": null, "e": 100060, "s": 99988, "text": "Create .babelrc inside the project setup and add presets as shown below" }, { "code": null, "e": 100126, "s": 100060, "text": "Create a main.js file and write your JavaScript code using flow −" }, { "code": null, "e": 100134, "s": 100126, "text": "main.js" }, { "code": null, "e": 100248, "s": 100134, "text": "/* @flow */\nfunction concat(a: string, b: string) {\n return a + b;\n}\n\nlet a = concat(\"A\", \"B\");\nconsole.log(a);" }, { "code": null, "e": 100327, "s": 100248, "text": "Use babel command to compile the code using presets: flow to normal javascript" }, { "code": null, "e": 100370, "s": 100327, "text": "npx babel main.js --out-file main_flow.js\n" }, { "code": null, "e": 100383, "s": 100370, "text": "main_flow.js" }, { "code": null, "e": 100469, "s": 100383, "text": "function concat(a, b) {\n return a + b;\n}\n\nlet a = concat(\"A\", \"B\");\nconsole.log(a);" }, { "code": null, "e": 100579, "s": 100469, "text": "We can also make use of plugin called babel-plugin-transform-flow-strip-types instead of presets as follows −" }, { "code": null, "e": 100620, "s": 100579, "text": "In .babelrc, add the plugin as follows −" }, { "code": null, "e": 100628, "s": 100620, "text": "main.js" }, { "code": null, "e": 100742, "s": 100628, "text": "/* @flow */\nfunction concat(a: string, b: string) {\n return a + b;\n}\n\nlet a = concat(\"A\", \"B\");\nconsole.log(a);" }, { "code": null, "e": 100785, "s": 100742, "text": "npx babel main.js --out-file main_flow.js\n" }, { "code": null, "e": 100798, "s": 100785, "text": "main_flow.js" }, { "code": null, "e": 100884, "s": 100798, "text": "function concat(a, b) {\n return a + b;\n}\n\nlet a = concat(\"A\", \"B\");\nconsole.log(a);" }, { "code": null, "e": 101295, "s": 100884, "text": "In this chapter, we will create project setup using babel and gulp. Gulp is a task runner that uses Node.js as a platform. Gulp will run the tasks that will transpile JavaScript files from es6 to es5 and once done will start the server to test the changes. We have used babel 6 in the project setup. In case you want to switch to babel 7, install the required packages of babel using @babel/babel-package-name." }, { "code": null, "e": 101396, "s": 101295, "text": "We will create the project first using npm commands and install the required packages to start with." }, { "code": null, "e": 101406, "s": 101396, "text": "npm init\n" }, { "code": null, "e": 101512, "s": 101406, "text": "We have created a folder called gulpbabel. Further, we will install gulp and other required dependencies." }, { "code": null, "e": 101685, "s": 101512, "text": "npm install gulp --save-dev\nnpm install gulp-babel --save-dev\nnpm install gulp-connect --save-dev\nnpm install babel-preset-env --save-dev\nnpm install babel-core --save-dev\n" }, { "code": null, "e": 101756, "s": 101685, "text": "We will add the Preset environment details to .babelrc file as follows" }, { "code": null, "e": 101768, "s": 101756, "text": "gulpfile.js" }, { "code": null, "e": 102205, "s": 101768, "text": "var gulp =require('gulp');\nvar babel =require('gulp-babel');\nvar connect = require(\"gulp-connect\");\ngulp.task('build', () => {\n gulp.src('src/./*.js')\n .pipe(babel())\n .pipe(gulp.dest('./dev'))\n});\n\ngulp.task('watch', () => {\n gulp.watch('./*.js', ['build']);\n});\n\ngulp.task(\"connect\", function () {\n connect.server({\n root: \".\",\n livereload: true\n });\n});\n\ngulp.task('start', ['build', 'watch', 'connect']);" }, { "code": null, "e": 102361, "s": 102205, "text": "We have created three task in gulp, [‘build’,’watch’,’connect’]. All the js files available in src folder will be converted to es5 using babel as follows −" }, { "code": null, "e": 102471, "s": 102361, "text": "gulp.task('build', () => {\n gulp.src('src/./*.js')\n .pipe(babel())\n .pipe(gulp.dest('./dev'))\n});" }, { "code": null, "e": 102655, "s": 102471, "text": "The final changes are stored in the dev folder. Babel uses presets details from .babelrc. In case you want to change to some other preset, you can change the details in .babelrc file." }, { "code": null, "e": 102768, "s": 102655, "text": "Now will create a .js file in src folder using es6 javascript and run gulp start command to execute the changes." }, { "code": null, "e": 102780, "s": 102768, "text": "src/main.js" }, { "code": null, "e": 103018, "s": 102780, "text": "class Person {\n constructor(fname, lname, age, address) {\n this.fname = fname;\n this.lname = lname;\n this.age = age;\n this.address = address;\n }\n\n get fullname() {\n return this.fname +\"-\"+this.lname;\n }\n}" }, { "code": null, "e": 103038, "s": 103018, "text": "Command: gulp start" }, { "code": null, "e": 103050, "s": 103038, "text": "dev/main.js" }, { "code": null, "e": 103083, "s": 103050, "text": "This is transpiled using babel −" }, { "code": null, "e": 104321, "s": 103083, "text": "\"use strict\";\n\nvar _createClass = function () {\n function defineProperties(target, props) { \n for (var i = 0; i <props.length; i++) { \n var descriptor = props[i]; \n descriptor.enumerable = descriptor.enumerable || false; \n descriptor.configurable = true; \n if (\"value\" in descriptor) descriptor.writable = true; \n Object.defineProperty(target, descriptor.key, descriptor); \n } \n } \n return function (Constructor, protoProps, staticProps) { \n if (protoProps) defineProperties(Constructor.prototype, protoProps); \n if (staticProps) defineProperties(Constructor, staticProps); \n return Constructor; \n }; \n}();\n\nfunction _classCallCheck(instance, Constructor) {\n if (!(instance instanceof Constructor)) { \n throw new TypeError(\"Cannot call a class as a function\"); \n } \n}\n\nvar Person = function () {\n function Person(fname, lname, age, address) {\n _classCallCheck(this, Person);\n this.fname = fname;\n this.lname = lname;\n this.age = age;\n this.address = address;\n }\n _createClass(Person, [{\n key: \"fullname\",\n get: function get() {\n return this.fname + \"-\" + this.lname;\n }\n }]);\n\n return Person;\n}();" }, { "code": null, "e": 104332, "s": 104321, "text": "Index.html" }, { "code": null, "e": 104376, "s": 104332, "text": "This is done using transpiled dev/main.js −" }, { "code": null, "e": 104755, "s": 104376, "text": "<html>\n <head></head>\n <body>\n <script type=\"text/javascript\" src=\"dev/main.js\"></script>\n <h1 id=\"displayname\"></h1>\n <script type=\"text/javascript\">\n var a = new Student(\"Siya\", \"Kapoor\", \"15\", \"Mumbai\");\n var studentdet = a.fullname;\n document.getElementById(\"displayname\").innerHTML = studentdet;\n </script>\n </body>\n</html>" }, { "code": null, "e": 104762, "s": 104755, "text": "Output" }, { "code": null, "e": 105149, "s": 104762, "text": "We will use ES6 features and create a simple project. Babeljs will be used to compile the code to ES5. The project will have a set of images, which will autoslide after a fixed number of seconds. We will use ES6 class to work on it. We have used babel 6 in the project setup. In case you want to switch to babel 7, install the required packages of babel using @babel/babel-package-name." }, { "code": null, "e": 105251, "s": 105149, "text": "We will use gulp to build the project. To start with, we will create the project setup as shown below" }, { "code": null, "e": 105261, "s": 105251, "text": "npm init\n" }, { "code": null, "e": 105370, "s": 105261, "text": "We have created a folder called babelexample. Further, we will install gulp and other required dependencies." }, { "code": null, "e": 105509, "s": 105370, "text": "npm install gulp --save-dev\nnpm install gulp-babel --save-dev\nnpm install gulp-connect --save-dev\nnpm install babel-preset-env --save-dev\n" }, { "code": null, "e": 105555, "s": 105509, "text": "Here is the Package.json after installation −" }, { "code": null, "e": 105628, "s": 105555, "text": "We will add the Preset environment details to .babelrc file as follows −" }, { "code": null, "e": 105735, "s": 105628, "text": "Since we need the gulp task to build the final file, we will create gulpfile.js with the task that we need" }, { "code": null, "e": 105747, "s": 105735, "text": "gulpfile.js" }, { "code": null, "e": 106185, "s": 105747, "text": "var gulp = require('gulp');\nvar babel = require('gulp-babel');\nvar connect = require(\"gulp-connect\");\ngulp.task('build', () => {\n gulp.src('src/./*.js')\n .pipe(babel())\n .pipe(gulp.dest('./dev'))\n});\ngulp.task('watch', () => {\n gulp.watch('./*.js', ['build']);\n});\n\ngulp.task(\"connect\", function () {\n connect.server({\n root: \".\",\n livereload: true\n });\n});\n\ngulp.task('start', ['build', 'watch', 'connect']);" }, { "code": null, "e": 106340, "s": 106185, "text": "We have created three tasks in gulp, [‘build’,’watch’,’connect’]. All the js files available in src folder will be converted to es5 using babel as follows" }, { "code": null, "e": 106450, "s": 106340, "text": "gulp.task('build', () => {\n gulp.src('src/./*.js')\n .pipe(babel())\n .pipe(gulp.dest('./dev'))\n});" }, { "code": null, "e": 106634, "s": 106450, "text": "The final changes are stored in the dev folder. Babel uses presets details from .babelrc. In case you want to change to some other preset, you can change the details in .babelrc file." }, { "code": null, "e": 106751, "s": 106634, "text": "Now, we will create a .js file in src folder using es6 JavaScript and run gulp start command to execute the changes." }, { "code": null, "e": 106789, "s": 106751, "text": "The project structure is as follows −" }, { "code": null, "e": 106809, "s": 106789, "text": "src/slidingimage.js" }, { "code": null, "e": 109608, "s": 106809, "text": "class SlidingImage {\n constructor(width, height, imgcounter, timer) {\n this.counter = 0;\n this.imagecontainerwidth = width;\n this.imagecontainerheight = height;\n this.slidercounter = imgcounter;\n this.slidetimer = timer;\n this.startindex = 1;\n this.css = this.applycss();\n this.maincontainer = this.createContainter();\n this.childcontainer = this.imagecontainer();\n this.autoslide();\n }\n\n createContainter() {\n let maindiv = document.createElement('div');\n maindiv.id = \"maincontainer\";\n maindiv.class = \"maincontainer\";\n document.body.appendChild(maindiv);\n return maindiv;\n }\n\n applycss() {\n let slidercss = \".maincontainer{ position : relative; margin :auto;}.left, \n .right {\n cursor: pointer; position: absolute;\" +\n \"top: 50%; width: auto; padding: 16px; margin-top: -22px; color: white; font-weight: bold; \" +\n \"font-size: 18px; transition: 0.6s ease; border-radius: 0 3px 3px 0;\n }.right { right: 0; border-radius: 3px 0 0 3px;}\" +\n \".left:hover, .right:hover { background-color: rgba(0,0,0,0.8);}\";\n let style = document.createElement('style');\n style.id = \"slidercss\";\n style.type = \"text/css\";\n document.getElementsByTagName(\"head\")[0].appendChild(style);\n let styleall = style;\n if (styleall.styleSheet) {\n styleall.styleSheet.cssText = slidercss;\n } else {\n let text = document.createTextNode(slidercss);\n style.appendChild(text);\n }\n }\n\n imagecontainer() {\n let childdiv = [];\n let imgcont = [];\n for (let a = 1; a >= this.slidercounter; a++) {\n childdiv[a] = document.createElement('div');\n childdiv[a].id = \"childdiv\" + a;\n childdiv[a].style.width = this.imagecontainerwidth + \"px\";\n childdiv[a].style.height = this.imagecontainerheight + \"px\";\n if (a > 1) {\n childdiv[a].style.display = \"none\";\n }\n imgcont[a] = document.createElement('img');\n imgcont[a].src = \"src/img/img\" + a + \".jpg\";\n imgcont[a].style.width = \"100%\";\n imgcont[a].style.height = \"100%\";\n childdiv[a].appendChild(imgcont[a]);\n this.maincontainer.appendChild(childdiv[a]);\n }\n }\n\n autoslide() {\n console.log(this.startindex);\n let previousimg = this.startindex;\n this.startindex++;\n if (this.startindex > 5) {\n this.startindex = 1;\n }\n setTimeout(() => {\n document.getElementById(\"childdiv\" + this.startindex).style.display = \"\";\n document.getElementById(\"childdiv\" + previousimg).style.display = \"none\";\n this.autoslide();\n }, this.slidetimer);\n }\n}\n\nlet a = new SlidingImage(300, 250, 5, 5000); " }, { "code": null, "e": 109811, "s": 109608, "text": "We will create img/ folder in src/ as we need images to be displayed; these images are to rotate every 5 seconds.The dev/ folder will store the compiled code. Run the gulp start to build the final file." }, { "code": null, "e": 109859, "s": 109811, "text": "The final project structure is as shown below −" }, { "code": null, "e": 110135, "s": 109859, "text": "In slidingimage.js, we have created a class called SlidingImage, which has methods like createcontainer, imagecontainer, and autoslide, which creates the main container and adds images to it. The autoslide method helps in changing the image after the specified time interval." }, { "code": null, "e": 110180, "s": 110135, "text": "let a = new SlidingImage(300, 250, 5, 5000);" }, { "code": null, "e": 110304, "s": 110180, "text": "At this stage, the class is called. We will pass width, height, number of images and number of seconds to rotate the image." }, { "code": null, "e": 110316, "s": 110304, "text": "gulp start\n" }, { "code": null, "e": 110336, "s": 110316, "text": "dev/slidingimage.js" }, { "code": null, "e": 114535, "s": 110336, "text": "\"use strict\";\n\nvar _createClass = function () {\n function defineProperties(target, props) {\n for (var i = 0; i < props.length; i++) {\n var descriptor = props[i]; \n descriptor.enumerable = descriptor.enumerable || false; \n descriptor.configurable = true; \n if (\"value\" in descriptor) descriptor.writable = true; \n Object.defineProperty(target, descriptor.key, descriptor); \n } \n }\n return function (Constructor, protoProps, staticProps) {\n if (protoProps) defineProperties(Constructor.prototype, protoProps);\n if (staticProps) defineProperties(Constructor, staticProps); return Constructor;\n };\n}();\n\nfunction _classCallCheck(instance, Constructor) {\n if (!(instance instanceof Constructor)) {\n throw new TypeError(\"Cannot call a class as a function\"); \n } \n}\n\nvar SlidingImage = function () {\n function SlidingImage(width, height, imgcounter, timer) {\n _classCallCheck(this, SlidingImage);\n this.counter = 0;\n this.imagecontainerwidth = width;\n this.imagecontainerheight = height;\n this.slidercounter = imgcounter;\n this.slidetimer = timer;\n this.startindex = 1;\n this.css = this.applycss();\n this.maincontainer = this.createContainter();\n this.childcontainer = this.imagecontainer();\n this.autoslide();\n }\n _createClass(SlidingImage, [{\n key: \"createContainter\",\n value: function createContainter() {\n var maindiv = document.createElement('div');\n maindiv.id = \"maincontainer\";\n maindiv.class = \"maincontainer\";\n document.body.appendChild(maindiv);\n return maindiv;\n }\n }, {\n key: \"applycss\",\n value: function applycss() {\n var slidercss = \".maincontainer{ position : relative; margin :auto;}.left, .right {\n cursor: pointer; position: absolute;\" + \"top: 50%;\n width: auto;\n padding: 16px;\n margin-top: -22px;\n color: white;\n font-weight: bold;\n \" + \"font-size: 18px;\n transition: 0.6s ease;\n border-radius: 0 3px 3px 0;\n }\n .right { right: 0; border-radius: 3px 0 0 3px;}\" +\n \".left:hover, .right:hover { background-color: rgba(0,0,0,0.8);}\";\n var style = document.createElement('style');\n style.id = \"slidercss\";\n style.type = \"text/css\";\n document.getElementsByTagName(\"head\")[0].appendChild(style);\n var styleall = style;\n if (styleall.styleSheet) {\n styleall.styleSheet.cssText = slidercss;\n } else {\n var text = document.createTextNode(slidercss);\n style.appendChild(text);\n }\n }\n }, {\n key: \"imagecontainer\",\n value: function imagecontainer() {\n var childdiv = [];\n var imgcont = [];\n for (var _a = 1; _a <= this.slidercounter; _a++) {\n childdiv[_a] = document.createElement('div');\n childdiv[_a].id = \"childdiv\" + _a;\n childdiv[_a].style.width = this.imagecontainerwidth + \"px\";\n childdiv[_a].style.height = this.imagecontainerheight + \"px\";\n if (_a > 1) {\n childdiv[_a].style.display = \"none\";\n }\n imgcont[_a] = document.createElement('img');\n imgcont[_a].src = \"src/img/img\" + _a + \".jpg\";\n imgcont[_a].style.width = \"100%\";\n imgcont[_a].style.height = \"100%\";\n childdiv[_a].appendChild(imgcont[_a]);\n this.maincontainer.appendChild(childdiv[_a]);\n }\n }\n }, {\n key: \"autoslide\",\n value: function autoslide() {\n var _this = this;\n\n console.log(this.startindex);\n var previousimg = this.startindex;\n this.startindex++;\n if (this.startindex > 5) {\n this.startindex = 1;\n }\n setTimeout(function () {\n document.getElementById(\"childdiv\" + _this.startindex).style.display = \"\";\n document.getElementById(\"childdiv\" + previousimg).style.display = \"none\";\n _this.autoslide();\n }, this.slidetimer);\n }\n }]);\n return SlidingImage;\n}();\n\nvar a = new SlidingImage(300, 250, 5, 5000);" }, { "code": null, "e": 114593, "s": 114535, "text": "We will test the line of code in browser as shown below −" }, { "code": null, "e": 114604, "s": 114593, "text": "index.html" }, { "code": null, "e": 114764, "s": 114604, "text": "<html>\n <head></head>\n <body>\n <script type=\"text/javascript\" src=\"dev/slidingimage.js\"></script>\n <h1>Sliding Image Demo</h1>\n </body>\n</html>" }, { "code": null, "e": 114901, "s": 114764, "text": "We have used the compiled file from the dev folder in index.html. The command gulp start starts the server where we can test the output." } ]
Copy Elements of One ArrayList to Another ArrayList in Java
10 Jun, 2022 It is the implementation class of List Interface. It allows duplicated objects/elements and as well as maintains the insertion order. You can get the element present inside the ArrayList by the index of it now you need to pass it into the getting (index) method. You can add the elements into ArrayList using the add() method. Syntax: ArrayList Initialization ArrayList<Integer> gfg=new ArrayList<>(); There are two approaches first you actually just need to pass the reference of one ArrayList to another and in this case, if you change in one ArrayList value or element then you can see the same change in another ArrayList. The second approach is where you will create actual duplicates means if you change in one ArrayList Element then it will not reflect in the other one. In this approach, we will simply assign the first ArrayList reference to the second but there is one important aspect to look at here we did not create a new object we simply pointed the second ArrayList to the first one. So if you make a change in the first ArrayList it will reflect in the second one also because you are using the same object. We can also change one value of one ArrayList and can look for the same in the other one whether it is changed or not. Syntax: ArrayList<Integer> gfg=new ArrayList<>(); ArrayList<Integer> gfg2=gfg; Below is the implementation of the above problem statement. Java // Java Program for copying one ArrayList to another import java.io.*;import java.util.ArrayList; class GFG { public static void main(String[] args) { // creation of ArrayList of Integers ArrayList<Integer> gfg = new ArrayList<>(); // adding elements to first ArrayList gfg.add(10); gfg.add(21); gfg.add(22); gfg.add(35); // Assigning the first reference to second ArrayList<Integer> gfg2 = gfg; // Iterating over second ArrayList System.out.println( "-----Iterating over the second ArrayList----"); for (Integer value : gfg2) { System.out.println(value); } // here we changed the third element to 23 // we changed in second list and you can // see the same change in the first Arraylist gfg2.set(2, 23); System.out.println("third element of first list =" + gfg.get(2)); System.out.println("third element of second list =" + gfg2.get(2)); }} -----Iterating over the second ArrayList---- 10 21 22 35 third element of first list =23 third element of second list =23 In this approach, we will simply pass the first ArrayList in the second ArrayList’s constructor. By using this approach if we change one ArrayList element/value it will not affect the other one, so this is the approach where we actually created the duplicates. We can also change one value of one ArrayList and can look for the same in the other one whether it is changed or not. Syntax : ArrayList<Integer> gfg=new ArrayList<>(); ArrayList<Integer> gfg2=new ArrayList<>(gfg); Below is the implementation of the above problem statement: Java // Java Program for copying one ArrayList to another import java.io.*;import java.util.ArrayList; class GFG { public static void main(String[] args) { // creation of ArrayList of Integers ArrayList<Integer> gfg = new ArrayList<>(); // adding elements to first ArrayList gfg.add(10); gfg.add(21); gfg.add(22); gfg.add(35); // passing in the constructor ArrayList<Integer> gfg2 = new ArrayList<>(gfg); // Iterating over second ArrayList System.out.println( "-----Iterating over the second ArrayList----"); for (Integer value : gfg2) { System.out.println(value); } // here we changed the third element to 23 // we changed in second list and you can // here we will not see the same change in the first gfg2.set(2, 23); System.out.println("third element of first list =" + gfg.get(2)); System.out.println("third element of second list =" + gfg2.get(2)); }} -----Iterating over the second ArrayList---- 10 21 22 35 third element of first list =22 third element of second list =23 In this approach, we will iterate over each element of the first ArrayList and add that element in the second ArrayList. Here if you change first ArrayList element then it will not change the elements of the second ArrayList. We can also change one value of one ArrayList and can look for the same in the other one whether it is changed or not. Syntax : ArrayList<Integer> gfg=new ArrayList<>(); ArrayList<Integer> gfg2=new ArrayList<>(); for(Integer val: gfg){ gfg2.add(val); } Below is the implementation of the above problem statement: Java // Java Program for copying one ArrayList to another import java.io.*;import java.util.ArrayList; class GFG { public static void main(String[] args) { // creation of ArrayList of Integers ArrayList<Integer> gfg = new ArrayList<>(); // adding elements to first ArrayList gfg.add(10); gfg.add(21); gfg.add(22); gfg.add(35); ArrayList<Integer> gfg2 = new ArrayList<>(); // adding element to the second ArrayList // by iterating over one by one for (Integer value : gfg) { gfg2.add(value); } // Iterating over second ArrayList System.out.println( "-----Iterating over the second ArrayList----"); for (Integer value : gfg2) { System.out.println(value); } // here we changed the third element to 23 // we changed in second list // here we will not see the same change in the first gfg2.set(2, 23); System.out.println("third element of first list =" + gfg.get(2)); System.out.println("third element of second list =" + gfg2.get(2)); }} -----Iterating over the second ArrayList---- 10 21 22 35 third element of first list =22 third element of second list =23 The addAll() method is used to add all the elements from one ArrayList to another ArrayList. For this implementation, we have to import the package java.util.*. Step 1: Declare the ArrayList 1 and add the values to it. Step 2: Create another ArrayList 2 with the same type. Step 3: Now, simply add the values from one ArrayList to another by using the method addAll(). Specify ArrayList2.addAll(ArrayList1). Step 4: Now, print the ArrayList 2. Java import java.util.*; class GFG { public static void main(String[] args) { ArrayList<String> AL1 = new ArrayList<>(); AL1.add("geeks"); AL1.add("forgeeks"); AL1.add("learning"); AL1.add("platform"); ArrayList<String> AL2 = new ArrayList<>(); AL2.addAll(AL1); System.out.println("Original ArrayList : " + AL1); System.out.println("Copied ArrayList : " + AL2); }} Original ArrayList : [geeks, forgeeks, learning, platform] Copied ArrayList : [geeks, forgeeks, learning, platform] List.copyOf() method is used to add the elements of one ArrayList to another. To use this method, we have to import the package java.util.List.* or java.util.* . It is a static factory method. Step 1: Declare the ArrayList 1 and add the values to it. Step 2: Create another ArrayList 2 with the same type. Step 3: Now, simply add the values from one ArrayList to another by using the method List.copyOf(). Specify List.copyOf(ArrayList1) in the constructor of newly created ArrayList 2. Step 4: Now, print the ArrayList 2. Java import java.util.*; class GFG { public static void main(String[] args) { ArrayList<String> AL1 = new ArrayList<>(); AL1.add("geeks"); AL1.add("forgeeks"); AL1.add("learning"); AL1.add("platform"); ArrayList<String> AL2 = new ArrayList<>(List.copyOf(AL1)); System.out.println("Original ArrayList : " + AL1); System.out.println("Copied Arraylist : " + AL2); }} Original ArrayList : [geeks, forgeeks, learning, platform] Copied Arraylist : [geeks, forgeeks, learning, platform] keerthikarathan123 Java-ArrayList Java-Collections Picked Java Java Programs Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n10 Jun, 2022" }, { "code": null, "e": 380, "s": 53, "text": "It is the implementation class of List Interface. It allows duplicated objects/elements and as well as maintains the insertion order. You can get the element present inside the ArrayList by the index of it now you need to pass it into the getting (index) method. You can add the elements into ArrayList using the add() method." }, { "code": null, "e": 415, "s": 380, "text": "Syntax: ArrayList Initialization " }, { "code": null, "e": 457, "s": 415, "text": "ArrayList<Integer> gfg=new ArrayList<>();" }, { "code": null, "e": 833, "s": 457, "text": "There are two approaches first you actually just need to pass the reference of one ArrayList to another and in this case, if you change in one ArrayList value or element then you can see the same change in another ArrayList. The second approach is where you will create actual duplicates means if you change in one ArrayList Element then it will not reflect in the other one." }, { "code": null, "e": 1299, "s": 833, "text": "In this approach, we will simply assign the first ArrayList reference to the second but there is one important aspect to look at here we did not create a new object we simply pointed the second ArrayList to the first one. So if you make a change in the first ArrayList it will reflect in the second one also because you are using the same object. We can also change one value of one ArrayList and can look for the same in the other one whether it is changed or not." }, { "code": null, "e": 1307, "s": 1299, "text": "Syntax:" }, { "code": null, "e": 1378, "s": 1307, "text": "ArrayList<Integer> gfg=new ArrayList<>();\nArrayList<Integer> gfg2=gfg;" }, { "code": null, "e": 1438, "s": 1378, "text": "Below is the implementation of the above problem statement." }, { "code": null, "e": 1443, "s": 1438, "text": "Java" }, { "code": "// Java Program for copying one ArrayList to another import java.io.*;import java.util.ArrayList; class GFG { public static void main(String[] args) { // creation of ArrayList of Integers ArrayList<Integer> gfg = new ArrayList<>(); // adding elements to first ArrayList gfg.add(10); gfg.add(21); gfg.add(22); gfg.add(35); // Assigning the first reference to second ArrayList<Integer> gfg2 = gfg; // Iterating over second ArrayList System.out.println( \"-----Iterating over the second ArrayList----\"); for (Integer value : gfg2) { System.out.println(value); } // here we changed the third element to 23 // we changed in second list and you can // see the same change in the first Arraylist gfg2.set(2, 23); System.out.println(\"third element of first list =\" + gfg.get(2)); System.out.println(\"third element of second list =\" + gfg2.get(2)); }}", "e": 2508, "s": 1443, "text": null }, { "code": null, "e": 2630, "s": 2508, "text": "-----Iterating over the second ArrayList----\n10\n21\n22\n35\nthird element of first list =23\nthird element of second list =23" }, { "code": null, "e": 3010, "s": 2630, "text": "In this approach, we will simply pass the first ArrayList in the second ArrayList’s constructor. By using this approach if we change one ArrayList element/value it will not affect the other one, so this is the approach where we actually created the duplicates. We can also change one value of one ArrayList and can look for the same in the other one whether it is changed or not." }, { "code": null, "e": 3019, "s": 3010, "text": "Syntax :" }, { "code": null, "e": 3107, "s": 3019, "text": "ArrayList<Integer> gfg=new ArrayList<>();\nArrayList<Integer> gfg2=new ArrayList<>(gfg);" }, { "code": null, "e": 3167, "s": 3107, "text": "Below is the implementation of the above problem statement:" }, { "code": null, "e": 3172, "s": 3167, "text": "Java" }, { "code": "// Java Program for copying one ArrayList to another import java.io.*;import java.util.ArrayList; class GFG { public static void main(String[] args) { // creation of ArrayList of Integers ArrayList<Integer> gfg = new ArrayList<>(); // adding elements to first ArrayList gfg.add(10); gfg.add(21); gfg.add(22); gfg.add(35); // passing in the constructor ArrayList<Integer> gfg2 = new ArrayList<>(gfg); // Iterating over second ArrayList System.out.println( \"-----Iterating over the second ArrayList----\"); for (Integer value : gfg2) { System.out.println(value); } // here we changed the third element to 23 // we changed in second list and you can // here we will not see the same change in the first gfg2.set(2, 23); System.out.println(\"third element of first list =\" + gfg.get(2)); System.out.println(\"third element of second list =\" + gfg2.get(2)); }}", "e": 4249, "s": 3172, "text": null }, { "code": null, "e": 4371, "s": 4249, "text": "-----Iterating over the second ArrayList----\n10\n21\n22\n35\nthird element of first list =22\nthird element of second list =23" }, { "code": null, "e": 4716, "s": 4371, "text": "In this approach, we will iterate over each element of the first ArrayList and add that element in the second ArrayList. Here if you change first ArrayList element then it will not change the elements of the second ArrayList. We can also change one value of one ArrayList and can look for the same in the other one whether it is changed or not." }, { "code": null, "e": 4725, "s": 4716, "text": "Syntax :" }, { "code": null, "e": 4850, "s": 4725, "text": "ArrayList<Integer> gfg=new ArrayList<>();\nArrayList<Integer> gfg2=new ArrayList<>();\nfor(Integer val: gfg){\ngfg2.add(val);\n}" }, { "code": null, "e": 4910, "s": 4850, "text": "Below is the implementation of the above problem statement:" }, { "code": null, "e": 4915, "s": 4910, "text": "Java" }, { "code": "// Java Program for copying one ArrayList to another import java.io.*;import java.util.ArrayList; class GFG { public static void main(String[] args) { // creation of ArrayList of Integers ArrayList<Integer> gfg = new ArrayList<>(); // adding elements to first ArrayList gfg.add(10); gfg.add(21); gfg.add(22); gfg.add(35); ArrayList<Integer> gfg2 = new ArrayList<>(); // adding element to the second ArrayList // by iterating over one by one for (Integer value : gfg) { gfg2.add(value); } // Iterating over second ArrayList System.out.println( \"-----Iterating over the second ArrayList----\"); for (Integer value : gfg2) { System.out.println(value); } // here we changed the third element to 23 // we changed in second list // here we will not see the same change in the first gfg2.set(2, 23); System.out.println(\"third element of first list =\" + gfg.get(2)); System.out.println(\"third element of second list =\" + gfg2.get(2)); }}", "e": 6102, "s": 4915, "text": null }, { "code": null, "e": 6224, "s": 6102, "text": "-----Iterating over the second ArrayList----\n10\n21\n22\n35\nthird element of first list =22\nthird element of second list =23" }, { "code": null, "e": 6386, "s": 6224, "text": "The addAll() method is used to add all the elements from one ArrayList to another ArrayList. For this implementation, we have to import the package java.util.*. " }, { "code": null, "e": 6444, "s": 6386, "text": "Step 1: Declare the ArrayList 1 and add the values to it." }, { "code": null, "e": 6499, "s": 6444, "text": "Step 2: Create another ArrayList 2 with the same type." }, { "code": null, "e": 6633, "s": 6499, "text": "Step 3: Now, simply add the values from one ArrayList to another by using the method addAll(). Specify ArrayList2.addAll(ArrayList1)." }, { "code": null, "e": 6669, "s": 6633, "text": "Step 4: Now, print the ArrayList 2." }, { "code": null, "e": 6674, "s": 6669, "text": "Java" }, { "code": "import java.util.*; class GFG { public static void main(String[] args) { ArrayList<String> AL1 = new ArrayList<>(); AL1.add(\"geeks\"); AL1.add(\"forgeeks\"); AL1.add(\"learning\"); AL1.add(\"platform\"); ArrayList<String> AL2 = new ArrayList<>(); AL2.addAll(AL1); System.out.println(\"Original ArrayList : \" + AL1); System.out.println(\"Copied ArrayList : \" + AL2); }}", "e": 7107, "s": 6674, "text": null }, { "code": null, "e": 7224, "s": 7107, "text": "Original ArrayList : [geeks, forgeeks, learning, platform]\nCopied ArrayList : [geeks, forgeeks, learning, platform]\n" }, { "code": null, "e": 7417, "s": 7224, "text": "List.copyOf() method is used to add the elements of one ArrayList to another. To use this method, we have to import the package java.util.List.* or java.util.* . It is a static factory method." }, { "code": null, "e": 7475, "s": 7417, "text": "Step 1: Declare the ArrayList 1 and add the values to it." }, { "code": null, "e": 7530, "s": 7475, "text": "Step 2: Create another ArrayList 2 with the same type." }, { "code": null, "e": 7711, "s": 7530, "text": "Step 3: Now, simply add the values from one ArrayList to another by using the method List.copyOf(). Specify List.copyOf(ArrayList1) in the constructor of newly created ArrayList 2." }, { "code": null, "e": 7747, "s": 7711, "text": "Step 4: Now, print the ArrayList 2." }, { "code": null, "e": 7752, "s": 7747, "text": "Java" }, { "code": "import java.util.*; class GFG { public static void main(String[] args) { ArrayList<String> AL1 = new ArrayList<>(); AL1.add(\"geeks\"); AL1.add(\"forgeeks\"); AL1.add(\"learning\"); AL1.add(\"platform\"); ArrayList<String> AL2 = new ArrayList<>(List.copyOf(AL1)); System.out.println(\"Original ArrayList : \" + AL1); System.out.println(\"Copied Arraylist : \" + AL2); }}", "e": 8189, "s": 7752, "text": null }, { "code": null, "e": 8306, "s": 8189, "text": "Original ArrayList : [geeks, forgeeks, learning, platform]\nCopied Arraylist : [geeks, forgeeks, learning, platform]\n" }, { "code": null, "e": 8325, "s": 8306, "text": "keerthikarathan123" }, { "code": null, "e": 8340, "s": 8325, "text": "Java-ArrayList" }, { "code": null, "e": 8357, "s": 8340, "text": "Java-Collections" }, { "code": null, "e": 8364, "s": 8357, "text": "Picked" }, { "code": null, "e": 8369, "s": 8364, "text": "Java" }, { "code": null, "e": 8383, "s": 8369, "text": "Java Programs" }, { "code": null, "e": 8388, "s": 8383, "text": "Java" }, { "code": null, "e": 8405, "s": 8388, "text": "Java-Collections" } ]
SQL | Checking Existing Constraints on a Table using Data Dictionaries
05 Sep, 2018 Prerequisite: SQL-Constraints In SQL Server the data dictionary is a set of database tables used to store information about a database’s definition. One can use these data dictionaries to check the constraints on an already existing table and to change them(if possible). USER_CONSTRAINTS Data Dictionary: This data dictionary contains information about each constraint used in a database along with constraint specific information.DESC USER_CONSTRAINTS; Name Null Type ----------------- -------- ------------ OWNER VARCHAR2(30) CONSTRAINT_NAME NOT NULL VARCHAR2(30) CONSTRAINT_TYPE VARCHAR2(1) TABLE_NAME NOT NULL VARCHAR2(30) SEARCH_CONDITION LONG R_OWNER VARCHAR2(30) R_CONSTRAINT_NAME VARCHAR2(30) DELETE_RULE VARCHAR2(9) STATUS VARCHAR2(8) DEFERRABLE VARCHAR2(14) DEFERRED VARCHAR2(9) VALIDATED VARCHAR2(13) GENERATED VARCHAR2(14) BAD VARCHAR2(3) RELY VARCHAR2(4) LAST_CHANGE DATE INDEX_OWNER VARCHAR2(30) INDEX_NAME VARCHAR2(30) INVALID VARCHAR2(7) VIEW_RELATED VARCHAR2(14) Constraint types are:C - Check constraint on a table P - Primary key U - Unique key R - Referential integrity V - With check option, on a view O - With read only, on a view H - Hash expression F - Constraint that involves a REF column S - Supplemental logging Now consider the following source table “SDF”:SUPPNO SNAME STATUS CITY 21 JONYY 25 NY 22 MIKKY 11 LA 23 JIM 29 LV 24 BNFERYY 47 HW 25 TIM 41 HS Query for checking constraints on this table :SELECT CONSTRAINT_NAME, SEARCH_CONDITION AS CONSTRAINT_TYPE FROM USER_CONSTRAINTS WHERE TABLE_NAME='SDF'; Output:CONSTRAINT_NAMECONSTRAINT_TYPEXYZSTATUS<50Abc(NULL) DESC USER_CONSTRAINTS; Name Null Type ----------------- -------- ------------ OWNER VARCHAR2(30) CONSTRAINT_NAME NOT NULL VARCHAR2(30) CONSTRAINT_TYPE VARCHAR2(1) TABLE_NAME NOT NULL VARCHAR2(30) SEARCH_CONDITION LONG R_OWNER VARCHAR2(30) R_CONSTRAINT_NAME VARCHAR2(30) DELETE_RULE VARCHAR2(9) STATUS VARCHAR2(8) DEFERRABLE VARCHAR2(14) DEFERRED VARCHAR2(9) VALIDATED VARCHAR2(13) GENERATED VARCHAR2(14) BAD VARCHAR2(3) RELY VARCHAR2(4) LAST_CHANGE DATE INDEX_OWNER VARCHAR2(30) INDEX_NAME VARCHAR2(30) INVALID VARCHAR2(7) VIEW_RELATED VARCHAR2(14) Constraint types are: C - Check constraint on a table P - Primary key U - Unique key R - Referential integrity V - With check option, on a view O - With read only, on a view H - Hash expression F - Constraint that involves a REF column S - Supplemental logging Now consider the following source table “SDF”: SUPPNO SNAME STATUS CITY 21 JONYY 25 NY 22 MIKKY 11 LA 23 JIM 29 LV 24 BNFERYY 47 HW 25 TIM 41 HS Query for checking constraints on this table : SELECT CONSTRAINT_NAME, SEARCH_CONDITION AS CONSTRAINT_TYPE FROM USER_CONSTRAINTS WHERE TABLE_NAME='SDF'; Output: USER_CONS_COLUMNS Data Dictionary: We can use this Data Dictionary to find the columns to which constraint has been applied.DESC USER_CONS_COLUMNS; Name Null Type --------------- -------- -------------- OWNER NOT NULL VARCHAR2(30) CONSTRAINT_NAME NOT NULL VARCHAR2(30) TABLE_NAME NOT NULL VARCHAR2(30) COLUMN_NAME VARCHAR2(4000) POSITION NUMBER Query to check the columns of SDF table with constraints:SELECT * FROM USER_CONS_COLUMNS WHERE TABLE_NAME='SDF'; Output:OWNERCONSTRAINT_NAMETABLE_NAMECOLUMN_NAMEPOSITIONSYSTEMXYZSDFSTATUS(null)SYSTEMABCSDFSTATUS1 DESC USER_CONS_COLUMNS; Name Null Type --------------- -------- -------------- OWNER NOT NULL VARCHAR2(30) CONSTRAINT_NAME NOT NULL VARCHAR2(30) TABLE_NAME NOT NULL VARCHAR2(30) COLUMN_NAME VARCHAR2(4000) POSITION NUMBER Query to check the columns of SDF table with constraints: SELECT * FROM USER_CONS_COLUMNS WHERE TABLE_NAME='SDF'; Output: Using Cartesian Product to get Complete information on constraints:SELECT A.CONSTRAINT_NAME, A.CONSTRAINT_TYPE, B.COLUMN_NAME, B.TABLE_NAME FROM USER_CONSTRAINTS A, USER_CONS_COLUMNS B WHERE A.CONSTRAINT_NAME=B.CONSTRAINT_NAME AND A.TABLE_NAME='SDF'; Output:CONSTRAINT_NAMECONSTRAINT_TYPECOLUMN_NAMETABLE_NAMEXYZCSTATUSSDFABCPSUPPNOSDF SELECT A.CONSTRAINT_NAME, A.CONSTRAINT_TYPE, B.COLUMN_NAME, B.TABLE_NAME FROM USER_CONSTRAINTS A, USER_CONS_COLUMNS B WHERE A.CONSTRAINT_NAME=B.CONSTRAINT_NAME AND A.TABLE_NAME='SDF'; Output: SQL-Server SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. CTE in SQL How to Update Multiple Columns in Single Update Statement in SQL? SQL Interview Questions SQL | Views Difference between DELETE, DROP and TRUNCATE MySQL | Group_CONCAT() Function Window functions in SQL Difference between DDL and DML in DBMS Difference between DELETE and TRUNCATE SQL Correlated Subqueries
[ { "code": null, "e": 28, "s": 0, "text": "\n05 Sep, 2018" }, { "code": null, "e": 58, "s": 28, "text": "Prerequisite: SQL-Constraints" }, { "code": null, "e": 300, "s": 58, "text": "In SQL Server the data dictionary is a set of database tables used to store information about a database’s definition. One can use these data dictionaries to check the constraints on an already existing table and to change them(if possible)." }, { "code": null, "e": 2068, "s": 300, "text": "USER_CONSTRAINTS Data Dictionary: This data dictionary contains information about each constraint used in a database along with constraint specific information.DESC USER_CONSTRAINTS;\n\nName Null Type \n----------------- -------- ------------ \nOWNER VARCHAR2(30) \nCONSTRAINT_NAME NOT NULL VARCHAR2(30) \nCONSTRAINT_TYPE VARCHAR2(1) \nTABLE_NAME NOT NULL VARCHAR2(30) \nSEARCH_CONDITION LONG \nR_OWNER VARCHAR2(30) \nR_CONSTRAINT_NAME VARCHAR2(30) \nDELETE_RULE VARCHAR2(9) \nSTATUS VARCHAR2(8) \nDEFERRABLE VARCHAR2(14) \nDEFERRED VARCHAR2(9) \nVALIDATED VARCHAR2(13) \nGENERATED VARCHAR2(14) \nBAD VARCHAR2(3) \nRELY VARCHAR2(4) \nLAST_CHANGE DATE \nINDEX_OWNER VARCHAR2(30) \nINDEX_NAME VARCHAR2(30) \nINVALID VARCHAR2(7) \nVIEW_RELATED VARCHAR2(14) \nConstraint types are:C - Check constraint on a table \nP - Primary key \nU - Unique key \nR - Referential integrity \nV - With check option, on a view \nO - With read only, on a view \nH - Hash expression \nF - Constraint that involves a REF column \nS - Supplemental logging\nNow consider the following source table “SDF”:SUPPNO SNAME STATUS CITY\n21 JONYY 25 NY\n22 MIKKY 11 LA\n23 JIM 29 LV\n24 BNFERYY 47 HW\n25 TIM 41 HS\nQuery for checking constraints on this table :SELECT CONSTRAINT_NAME, SEARCH_CONDITION AS CONSTRAINT_TYPE \nFROM USER_CONSTRAINTS \nWHERE TABLE_NAME='SDF';\nOutput:CONSTRAINT_NAMECONSTRAINT_TYPEXYZSTATUS<50Abc(NULL)" }, { "code": null, "e": 2995, "s": 2068, "text": "DESC USER_CONSTRAINTS;\n\nName Null Type \n----------------- -------- ------------ \nOWNER VARCHAR2(30) \nCONSTRAINT_NAME NOT NULL VARCHAR2(30) \nCONSTRAINT_TYPE VARCHAR2(1) \nTABLE_NAME NOT NULL VARCHAR2(30) \nSEARCH_CONDITION LONG \nR_OWNER VARCHAR2(30) \nR_CONSTRAINT_NAME VARCHAR2(30) \nDELETE_RULE VARCHAR2(9) \nSTATUS VARCHAR2(8) \nDEFERRABLE VARCHAR2(14) \nDEFERRED VARCHAR2(9) \nVALIDATED VARCHAR2(13) \nGENERATED VARCHAR2(14) \nBAD VARCHAR2(3) \nRELY VARCHAR2(4) \nLAST_CHANGE DATE \nINDEX_OWNER VARCHAR2(30) \nINDEX_NAME VARCHAR2(30) \nINVALID VARCHAR2(7) \nVIEW_RELATED VARCHAR2(14) \n" }, { "code": null, "e": 3017, "s": 2995, "text": "Constraint types are:" }, { "code": null, "e": 3273, "s": 3017, "text": "C - Check constraint on a table \nP - Primary key \nU - Unique key \nR - Referential integrity \nV - With check option, on a view \nO - With read only, on a view \nH - Hash expression \nF - Constraint that involves a REF column \nS - Supplemental logging\n" }, { "code": null, "e": 3320, "s": 3273, "text": "Now consider the following source table “SDF”:" }, { "code": null, "e": 3468, "s": 3320, "text": "SUPPNO SNAME STATUS CITY\n21 JONYY 25 NY\n22 MIKKY 11 LA\n23 JIM 29 LV\n24 BNFERYY 47 HW\n25 TIM 41 HS\n" }, { "code": null, "e": 3515, "s": 3468, "text": "Query for checking constraints on this table :" }, { "code": null, "e": 3624, "s": 3515, "text": "SELECT CONSTRAINT_NAME, SEARCH_CONDITION AS CONSTRAINT_TYPE \nFROM USER_CONSTRAINTS \nWHERE TABLE_NAME='SDF';\n" }, { "code": null, "e": 3632, "s": 3624, "text": "Output:" }, { "code": null, "e": 4277, "s": 3632, "text": "USER_CONS_COLUMNS Data Dictionary: We can use this Data Dictionary to find the columns to which constraint has been applied.DESC USER_CONS_COLUMNS;\n\nName Null Type \n--------------- -------- -------------- \nOWNER NOT NULL VARCHAR2(30) \nCONSTRAINT_NAME NOT NULL VARCHAR2(30) \nTABLE_NAME NOT NULL VARCHAR2(30) \nCOLUMN_NAME VARCHAR2(4000) \nPOSITION NUMBER \nQuery to check the columns of SDF table with constraints:SELECT * FROM USER_CONS_COLUMNS WHERE TABLE_NAME='SDF';\nOutput:OWNERCONSTRAINT_NAMETABLE_NAMECOLUMN_NAMEPOSITIONSYSTEMXYZSDFSTATUS(null)SYSTEMABCSDFSTATUS1" }, { "code": null, "e": 4586, "s": 4277, "text": "DESC USER_CONS_COLUMNS;\n\nName Null Type \n--------------- -------- -------------- \nOWNER NOT NULL VARCHAR2(30) \nCONSTRAINT_NAME NOT NULL VARCHAR2(30) \nTABLE_NAME NOT NULL VARCHAR2(30) \nCOLUMN_NAME VARCHAR2(4000) \nPOSITION NUMBER \n" }, { "code": null, "e": 4644, "s": 4586, "text": "Query to check the columns of SDF table with constraints:" }, { "code": null, "e": 4701, "s": 4644, "text": "SELECT * FROM USER_CONS_COLUMNS WHERE TABLE_NAME='SDF';\n" }, { "code": null, "e": 4709, "s": 4701, "text": "Output:" }, { "code": null, "e": 5046, "s": 4709, "text": "Using Cartesian Product to get Complete information on constraints:SELECT A.CONSTRAINT_NAME, A.CONSTRAINT_TYPE, B.COLUMN_NAME, B.TABLE_NAME\nFROM \nUSER_CONSTRAINTS A,\nUSER_CONS_COLUMNS B\nWHERE A.CONSTRAINT_NAME=B.CONSTRAINT_NAME\nAND A.TABLE_NAME='SDF';\nOutput:CONSTRAINT_NAMECONSTRAINT_TYPECOLUMN_NAMETABLE_NAMEXYZCSTATUSSDFABCPSUPPNOSDF" }, { "code": null, "e": 5232, "s": 5046, "text": "SELECT A.CONSTRAINT_NAME, A.CONSTRAINT_TYPE, B.COLUMN_NAME, B.TABLE_NAME\nFROM \nUSER_CONSTRAINTS A,\nUSER_CONS_COLUMNS B\nWHERE A.CONSTRAINT_NAME=B.CONSTRAINT_NAME\nAND A.TABLE_NAME='SDF';\n" }, { "code": null, "e": 5240, "s": 5232, "text": "Output:" }, { "code": null, "e": 5251, "s": 5240, "text": "SQL-Server" }, { "code": null, "e": 5255, "s": 5251, "text": "SQL" }, { "code": null, "e": 5259, "s": 5255, "text": "SQL" }, { "code": null, "e": 5357, "s": 5259, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5368, "s": 5357, "text": "CTE in SQL" }, { "code": null, "e": 5434, "s": 5368, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 5458, "s": 5434, "text": "SQL Interview Questions" }, { "code": null, "e": 5470, "s": 5458, "text": "SQL | Views" }, { "code": null, "e": 5515, "s": 5470, "text": "Difference between DELETE, DROP and TRUNCATE" }, { "code": null, "e": 5547, "s": 5515, "text": "MySQL | Group_CONCAT() Function" }, { "code": null, "e": 5571, "s": 5547, "text": "Window functions in SQL" }, { "code": null, "e": 5610, "s": 5571, "text": "Difference between DDL and DML in DBMS" }, { "code": null, "e": 5649, "s": 5610, "text": "Difference between DELETE and TRUNCATE" } ]
How are Java objects stored in memory?
24 May, 2022 In Java, all objects are dynamically allocated on Heap. This is different from C++ where objects can be allocated memory either on Stack or on Heap. In C++, when we allocate the object using new(), the object is allocated on Heap, otherwise on Stack if not global or static.In Java, when we only declare a variable of a class type, only a reference is created (memory is not allocated for the object). To allocate memory to an object, we must use new(). So the object is always allocated memory on the heap (See this for more details). There are two ways to create an object of string in java: By string literalBy new keywordBy string literal: By string literal By new keyword By string literal: This is done using double-quotes. For example: String str1="GFG"; String str2="GFG"; By String Literal Every time when a string literal is created, JVM will check whether that string already exists in the string constant pool or not. If the string already exists in the string literal pool then a reference to the pooled instance is returned. If the string does not exist, then a new string instance is created in the pool. Hence, only one object will get created. Here, the JVM is not bonded to create a new memory. This is done using a new keyword. For example: String str1=new String("Hello"); String str2=new String("Hello"); By new Keyword Both str1 and str2 are objects of String. Every time when a string object is created, JVM will create it in a heap memory. In this case, the JVM will not check whether the string already exists or not. If a string already exist , then also for every string object the memory will get created separately. Here, the JVM is bond to create a new memory. For example, the following program fails in the compilation. Compiler gives error “Error here because t is not initialized”. java class Test { // class contentsvoid show(){ System.out.println("Test::show() called");}} public class Main { // Driver Code public static void main(String[] args) { Test t; // Error here because t // is not initialized t.show(); }} Output: Allocating memory using new() makes the above program work. java class Test { // class contentsvoid show(){ System.out.println("Test::show() called");}} public class Main { // Driver Code public static void main(String[] args) { // all objects are dynamically // allocated Test t = new Test(); t.show(); // No error }} Test::show() called Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. HarshithThonupunoori RShriwas sooda367 singhankitasingh066 Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Arrays in Java Split() String method in Java with examples Arrays.sort() in Java with examples Object Oriented Programming (OOPs) Concept in Java Reverse a string in Java For-each loop in Java How to iterate any Map in Java Interfaces in Java HashMap in Java with Examples ArrayList in Java
[ { "code": null, "e": 53, "s": 25, "text": "\n24 May, 2022" }, { "code": null, "e": 589, "s": 53, "text": "In Java, all objects are dynamically allocated on Heap. This is different from C++ where objects can be allocated memory either on Stack or on Heap. In C++, when we allocate the object using new(), the object is allocated on Heap, otherwise on Stack if not global or static.In Java, when we only declare a variable of a class type, only a reference is created (memory is not allocated for the object). To allocate memory to an object, we must use new(). So the object is always allocated memory on the heap (See this for more details)." }, { "code": null, "e": 648, "s": 589, "text": "There are two ways to create an object of string in java:" }, { "code": null, "e": 698, "s": 648, "text": "By string literalBy new keywordBy string literal:" }, { "code": null, "e": 716, "s": 698, "text": "By string literal" }, { "code": null, "e": 731, "s": 716, "text": "By new keyword" }, { "code": null, "e": 750, "s": 731, "text": "By string literal:" }, { "code": null, "e": 784, "s": 750, "text": "This is done using double-quotes." }, { "code": null, "e": 797, "s": 784, "text": "For example:" }, { "code": null, "e": 816, "s": 797, "text": "String str1=\"GFG\";" }, { "code": null, "e": 835, "s": 816, "text": "String str2=\"GFG\";" }, { "code": null, "e": 853, "s": 835, "text": "By String Literal" }, { "code": null, "e": 1215, "s": 853, "text": "Every time when a string literal is created, JVM will check whether that string already exists in the string constant pool or not. If the string already exists in the string literal pool then a reference to the pooled instance is returned. If the string does not exist, then a new string instance is created in the pool. Hence, only one object will get created." }, { "code": null, "e": 1267, "s": 1215, "text": "Here, the JVM is not bonded to create a new memory." }, { "code": null, "e": 1301, "s": 1267, "text": "This is done using a new keyword." }, { "code": null, "e": 1314, "s": 1301, "text": "For example:" }, { "code": null, "e": 1347, "s": 1314, "text": "String str1=new String(\"Hello\");" }, { "code": null, "e": 1380, "s": 1347, "text": "String str2=new String(\"Hello\");" }, { "code": null, "e": 1395, "s": 1380, "text": "By new Keyword" }, { "code": null, "e": 1437, "s": 1395, "text": "Both str1 and str2 are objects of String." }, { "code": null, "e": 1700, "s": 1437, "text": "Every time when a string object is created, JVM will create it in a heap memory. In this case, the JVM will not check whether the string already exists or not. If a string already exist , then also for every string object the memory will get created separately. " }, { "code": null, "e": 1871, "s": 1700, "text": "Here, the JVM is bond to create a new memory. For example, the following program fails in the compilation. Compiler gives error “Error here because t is not initialized”." }, { "code": null, "e": 1876, "s": 1871, "text": "java" }, { "code": "class Test { // class contentsvoid show(){ System.out.println(\"Test::show() called\");}} public class Main { // Driver Code public static void main(String[] args) { Test t; // Error here because t // is not initialized t.show(); }}", "e": 2164, "s": 1876, "text": null }, { "code": null, "e": 2172, "s": 2164, "text": "Output:" }, { "code": null, "e": 2235, "s": 2174, "text": "Allocating memory using new() makes the above program work. " }, { "code": null, "e": 2240, "s": 2235, "text": "java" }, { "code": "class Test { // class contentsvoid show(){ System.out.println(\"Test::show() called\");}} public class Main { // Driver Code public static void main(String[] args) { // all objects are dynamically // allocated Test t = new Test(); t.show(); // No error }}", "e": 2555, "s": 2240, "text": null }, { "code": null, "e": 2576, "s": 2555, "text": "Test::show() called\n" }, { "code": null, "e": 2701, "s": 2576, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 2722, "s": 2701, "text": "HarshithThonupunoori" }, { "code": null, "e": 2731, "s": 2722, "text": "RShriwas" }, { "code": null, "e": 2740, "s": 2731, "text": "sooda367" }, { "code": null, "e": 2760, "s": 2740, "text": "singhankitasingh066" }, { "code": null, "e": 2765, "s": 2760, "text": "Java" }, { "code": null, "e": 2770, "s": 2765, "text": "Java" }, { "code": null, "e": 2868, "s": 2770, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2883, "s": 2868, "text": "Arrays in Java" }, { "code": null, "e": 2927, "s": 2883, "text": "Split() String method in Java with examples" }, { "code": null, "e": 2963, "s": 2927, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 3014, "s": 2963, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 3039, "s": 3014, "text": "Reverse a string in Java" }, { "code": null, "e": 3061, "s": 3039, "text": "For-each loop in Java" }, { "code": null, "e": 3092, "s": 3061, "text": "How to iterate any Map in Java" }, { "code": null, "e": 3111, "s": 3092, "text": "Interfaces in Java" }, { "code": null, "e": 3141, "s": 3111, "text": "HashMap in Java with Examples" } ]
Set of Tuples in C++ with Examples
15 Dec, 2021 What is a tuple?A tuple is an object that can hold a number of elements. The elements can be of different data types. The elements of tuples are initialized as arguments in the order in which they will be accessed. Operations on tuple:1. get(): get() is used to access the tuple values and modify them, it accepts the index and tuple name as arguments to access a particular tuple element.2. make_tuple(): make_tuple() is used to assign tuple with values. The values passed should be in order with the values declared in the tuple. What is a set?Sets are a type of associative container in which each element has to be unique because the value of the element identifies it. The value of the element cannot be modified once it is added to the set, though it is possible to remove and add the modified value of that element. Some basic functions associated with Set: 1. begin(): Returns an iterator to the first element in the set.2. end(): Returns an iterator to the theoretical element that follows the last element in the set.3. size(): Returns the number of elements in the set.4. max_size(): Returns the maximum number of elements that the set can hold.5. empty(): Returns whether the set is empty. A set of tuples can be quite useful while implementing complex data structures. Below is the C++ program to implement the above approach- C++ // C++ program to demonstrate the // implementation of set of// tuples#include <bits/stdc++.h>using namespace std; // Function to print set contentsvoid print(set<tuple<int, int, int> >& setOfTuples){ for (auto x : setOfTuples) { tuple<int, int, int> tp = x; cout << get<0>(tp) << ' ' << get<1>(tp) << ' ' << get<2>(tp) << '\n'; }} // Driver codeint main(){ // Declaring a set of tuples set<tuple<int, int, int> > setOfTuples; // Initializing tuples tuple<int, int, int> tuple1; tuple1 = make_tuple(1, 2, 3); tuple<int, int, int> tuple2; tuple2 = make_tuple(2, 3, 5); tuple<int, int, int> tuple3; tuple3 = make_tuple(2, 3, 4); tuple<int, int, int> tuple4; tuple4 = make_tuple(2, 1, 4); tuple<int, int, int> tuple5; tuple5 = make_tuple(5, 8, 14); // Inserting into set setOfTuples.insert(tuple1); setOfTuples.insert(tuple2); setOfTuples.insert(tuple3); setOfTuples.insert(tuple4); setOfTuples.insert(tuple5); // Calling print function print(setOfTuples); return 0;} 1 2 3 2 1 4 2 3 4 2 3 5 5 8 14 By default, tuples are arranged in non – descending order in the set and follows the below logic:In the set, if the first value of two tuples is equal then the second value of tuples is compared and if it is also equal then the third value is compared. But it is always possible to pass a comparator to a set. Below is the C++ program to implement the above approach- C++ // C++ program to demonstrate the // implementation of set of tuples // by using custom comparator#include <bits/stdc++.h>using namespace std; // Comparator for arranging elements // in non-ascending order We can // always modify the comparator as // per the requirementstruct cmp { bool operator()(const tuple<int, int, int>& x, const tuple<int, int, int>& y) { if (get<0>(x) == get<0>(y)) { if (get<1>(x) == get<1>(y)) return get<2>(x) > get<2>(y); return get<1>(x) > get<1>(y); } return get<0>(x) > get<0>(y); }}; // Function to print set elementsvoid print(set<tuple<int, int, int>, cmp>& setOfTuples){ for (auto x : setOfTuples) { tuple<int, int, int> tp = x; cout << get<0>(tp) << ' ' << get<1>(tp) << ' ' << get<2>(tp) << '\n'; }} // Driver codeint main(){ // Declaring a set of tuples set<tuple<int, int, int>, cmp> setOfTuples; // Initializing tuples tuple<int, int, int> tuple1; tuple1 = make_tuple(1, 2, 3); tuple<int, int, int> tuple2; tuple2 = make_tuple(2, 3, 5); tuple<int, int, int> tuple3; tuple3 = make_tuple(2, 3, 4); tuple<int, int, int> tuple4; tuple4 = make_tuple(2, 1, 4); tuple<int, int, int> tuple5; tuple5 = make_tuple(5, 8, 14); // Inserting into set setOfTuples.insert(tuple1); setOfTuples.insert(tuple2); setOfTuples.insert(tuple3); setOfTuples.insert(tuple4); setOfTuples.insert(tuple5); // Calling print function print(setOfTuples); return 0;} 5 8 14 2 3 5 2 3 4 2 1 4 1 2 3 sweetyty kalrap615 cpp-set cpp-tuple 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": "\n15 Dec, 2021" }, { "code": null, "e": 267, "s": 52, "text": "What is a tuple?A tuple is an object that can hold a number of elements. The elements can be of different data types. The elements of tuples are initialized as arguments in the order in which they will be accessed." }, { "code": null, "e": 584, "s": 267, "text": "Operations on tuple:1. get(): get() is used to access the tuple values and modify them, it accepts the index and tuple name as arguments to access a particular tuple element.2. make_tuple(): make_tuple() is used to assign tuple with values. The values passed should be in order with the values declared in the tuple." }, { "code": null, "e": 876, "s": 584, "text": "What is a set?Sets are a type of associative container in which each element has to be unique because the value of the element identifies it. The value of the element cannot be modified once it is added to the set, though it is possible to remove and add the modified value of that element. " }, { "code": null, "e": 1255, "s": 876, "text": "Some basic functions associated with Set: 1. begin(): Returns an iterator to the first element in the set.2. end(): Returns an iterator to the theoretical element that follows the last element in the set.3. size(): Returns the number of elements in the set.4. max_size(): Returns the maximum number of elements that the set can hold.5. empty(): Returns whether the set is empty." }, { "code": null, "e": 1393, "s": 1255, "text": "A set of tuples can be quite useful while implementing complex data structures. Below is the C++ program to implement the above approach-" }, { "code": null, "e": 1397, "s": 1393, "text": "C++" }, { "code": "// C++ program to demonstrate the // implementation of set of// tuples#include <bits/stdc++.h>using namespace std; // Function to print set contentsvoid print(set<tuple<int, int, int> >& setOfTuples){ for (auto x : setOfTuples) { tuple<int, int, int> tp = x; cout << get<0>(tp) << ' ' << get<1>(tp) << ' ' << get<2>(tp) << '\\n'; }} // Driver codeint main(){ // Declaring a set of tuples set<tuple<int, int, int> > setOfTuples; // Initializing tuples tuple<int, int, int> tuple1; tuple1 = make_tuple(1, 2, 3); tuple<int, int, int> tuple2; tuple2 = make_tuple(2, 3, 5); tuple<int, int, int> tuple3; tuple3 = make_tuple(2, 3, 4); tuple<int, int, int> tuple4; tuple4 = make_tuple(2, 1, 4); tuple<int, int, int> tuple5; tuple5 = make_tuple(5, 8, 14); // Inserting into set setOfTuples.insert(tuple1); setOfTuples.insert(tuple2); setOfTuples.insert(tuple3); setOfTuples.insert(tuple4); setOfTuples.insert(tuple5); // Calling print function print(setOfTuples); return 0;}", "e": 2509, "s": 1397, "text": null }, { "code": null, "e": 2540, "s": 2509, "text": "1 2 3\n2 1 4\n2 3 4\n2 3 5\n5 8 14" }, { "code": null, "e": 2850, "s": 2540, "text": "By default, tuples are arranged in non – descending order in the set and follows the below logic:In the set, if the first value of two tuples is equal then the second value of tuples is compared and if it is also equal then the third value is compared. But it is always possible to pass a comparator to a set." }, { "code": null, "e": 2908, "s": 2850, "text": "Below is the C++ program to implement the above approach-" }, { "code": null, "e": 2912, "s": 2908, "text": "C++" }, { "code": "// C++ program to demonstrate the // implementation of set of tuples // by using custom comparator#include <bits/stdc++.h>using namespace std; // Comparator for arranging elements // in non-ascending order We can // always modify the comparator as // per the requirementstruct cmp { bool operator()(const tuple<int, int, int>& x, const tuple<int, int, int>& y) { if (get<0>(x) == get<0>(y)) { if (get<1>(x) == get<1>(y)) return get<2>(x) > get<2>(y); return get<1>(x) > get<1>(y); } return get<0>(x) > get<0>(y); }}; // Function to print set elementsvoid print(set<tuple<int, int, int>, cmp>& setOfTuples){ for (auto x : setOfTuples) { tuple<int, int, int> tp = x; cout << get<0>(tp) << ' ' << get<1>(tp) << ' ' << get<2>(tp) << '\\n'; }} // Driver codeint main(){ // Declaring a set of tuples set<tuple<int, int, int>, cmp> setOfTuples; // Initializing tuples tuple<int, int, int> tuple1; tuple1 = make_tuple(1, 2, 3); tuple<int, int, int> tuple2; tuple2 = make_tuple(2, 3, 5); tuple<int, int, int> tuple3; tuple3 = make_tuple(2, 3, 4); tuple<int, int, int> tuple4; tuple4 = make_tuple(2, 1, 4); tuple<int, int, int> tuple5; tuple5 = make_tuple(5, 8, 14); // Inserting into set setOfTuples.insert(tuple1); setOfTuples.insert(tuple2); setOfTuples.insert(tuple3); setOfTuples.insert(tuple4); setOfTuples.insert(tuple5); // Calling print function print(setOfTuples); return 0;}", "e": 4548, "s": 2912, "text": null }, { "code": null, "e": 4579, "s": 4548, "text": "5 8 14\n2 3 5\n2 3 4\n2 1 4\n1 2 3" }, { "code": null, "e": 4588, "s": 4579, "text": "sweetyty" }, { "code": null, "e": 4598, "s": 4588, "text": "kalrap615" }, { "code": null, "e": 4606, "s": 4598, "text": "cpp-set" }, { "code": null, "e": 4616, "s": 4606, "text": "cpp-tuple" }, { "code": null, "e": 4620, "s": 4616, "text": "C++" }, { "code": null, "e": 4624, "s": 4620, "text": "CPP" } ]
How to Calculate Rolling Correlation in R?
20 Jun, 2022 In this article, we will discuss Rolling Correlation in R Programming Language. Correlation is used to get the relationship between two variables. It will result in 1 if the correlation is positive. It will result in -1 if the correlation is negative. it will result in 0 if there is no correlation. Rolling correlations are used to get the relationship between two-time series on a rolling window. We can calculate by using rollapply() function, This is available in the zoo package, So we have to load this package. Syntax: rollapply(data, width, FUN, by.column=TRUE) where, data is the input dataframe. width is an integer that specifies the window width for the rolling correlation. FUN is the function to be applied. by.column is used to specify whether to apply the function to each column separately. We can get correlation using cor() function. Syntax: cor(column1,column2) Example 1: R program to calculate rolling correlation for the dataframe. R # load the librarylibrary(zoo) # create dataframe with 3 columnsdata = data.frame(day=1:15, col1=c(35:49), col2=c(33:47)) # displayprint(data) # get rolling correlation for col1 and# col2 with width 6print(rollapply(data, width=6, function(x) cor(x[,2],x[,3]), by.column=FALSE)) Output: Example 2: R # load the librarylibrary(zoo) # create dataframe with 3 columnsdata = data.frame( col1=c(23,45,23,32,23), col2=c(1,45,67,32,45)) # displayprint(data) # get rolling correlation for col1 and# col2 with width 2print(rollapply(data, width=2, function(x) cor(x[,1],x[,2]), by.column=FALSE)) Output: surinderdawra388 Picked R-Statistics R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R How to Split Column Into Multiple Columns in R DataFrame? Group by function in R using Dplyr How to Change Axis Scales in R Plots? How to filter R DataFrame by values in a column? R - if statement Logistic Regression in R Programming Replace Specific Characters in String in R How to import an Excel File into R ? Joining of Dataframes in R Programming
[ { "code": null, "e": 28, "s": 0, "text": "\n20 Jun, 2022" }, { "code": null, "e": 108, "s": 28, "text": "In this article, we will discuss Rolling Correlation in R Programming Language." }, { "code": null, "e": 175, "s": 108, "text": "Correlation is used to get the relationship between two variables." }, { "code": null, "e": 227, "s": 175, "text": "It will result in 1 if the correlation is positive." }, { "code": null, "e": 280, "s": 227, "text": "It will result in -1 if the correlation is negative." }, { "code": null, "e": 328, "s": 280, "text": "it will result in 0 if there is no correlation." }, { "code": null, "e": 546, "s": 328, "text": "Rolling correlations are used to get the relationship between two-time series on a rolling window. We can calculate by using rollapply() function, This is available in the zoo package, So we have to load this package." }, { "code": null, "e": 554, "s": 546, "text": "Syntax:" }, { "code": null, "e": 598, "s": 554, "text": "rollapply(data, width, FUN, by.column=TRUE)" }, { "code": null, "e": 605, "s": 598, "text": "where," }, { "code": null, "e": 634, "s": 605, "text": "data is the input dataframe." }, { "code": null, "e": 715, "s": 634, "text": "width is an integer that specifies the window width for the rolling correlation." }, { "code": null, "e": 751, "s": 715, "text": "FUN is the function to be applied." }, { "code": null, "e": 837, "s": 751, "text": "by.column is used to specify whether to apply the function to each column separately." }, { "code": null, "e": 882, "s": 837, "text": "We can get correlation using cor() function." }, { "code": null, "e": 890, "s": 882, "text": "Syntax:" }, { "code": null, "e": 911, "s": 890, "text": "cor(column1,column2)" }, { "code": null, "e": 984, "s": 911, "text": "Example 1: R program to calculate rolling correlation for the dataframe." }, { "code": null, "e": 986, "s": 984, "text": "R" }, { "code": "# load the librarylibrary(zoo) # create dataframe with 3 columnsdata = data.frame(day=1:15, col1=c(35:49), col2=c(33:47)) # displayprint(data) # get rolling correlation for col1 and# col2 with width 6print(rollapply(data, width=6, function(x) cor(x[,2],x[,3]), by.column=FALSE))", "e": 1316, "s": 986, "text": null }, { "code": null, "e": 1324, "s": 1316, "text": "Output:" }, { "code": null, "e": 1335, "s": 1324, "text": "Example 2:" }, { "code": null, "e": 1337, "s": 1335, "text": "R" }, { "code": "# load the librarylibrary(zoo) # create dataframe with 3 columnsdata = data.frame( col1=c(23,45,23,32,23), col2=c(1,45,67,32,45)) # displayprint(data) # get rolling correlation for col1 and# col2 with width 2print(rollapply(data, width=2, function(x) cor(x[,1],x[,2]), by.column=FALSE))", "e": 1675, "s": 1337, "text": null }, { "code": null, "e": 1683, "s": 1675, "text": "Output:" }, { "code": null, "e": 1700, "s": 1683, "text": "surinderdawra388" }, { "code": null, "e": 1707, "s": 1700, "text": "Picked" }, { "code": null, "e": 1720, "s": 1707, "text": "R-Statistics" }, { "code": null, "e": 1731, "s": 1720, "text": "R Language" }, { "code": null, "e": 1829, "s": 1731, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1881, "s": 1829, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 1939, "s": 1881, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 1974, "s": 1939, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 2012, "s": 1974, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 2061, "s": 2012, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 2078, "s": 2061, "text": "R - if statement" }, { "code": null, "e": 2115, "s": 2078, "text": "Logistic Regression in R Programming" }, { "code": null, "e": 2158, "s": 2115, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 2195, "s": 2158, "text": "How to import an Excel File into R ?" } ]
Student’s t-distribution in Statistics
19 Jan, 2022 Student’s t-distribution or t-distribution is a probability distribution that is used to calculate population parameters when the sample size is small and when the population variance is unknown. Theoretical work on t-distribution was done by W.S. Gosset; he has published his findings under the pen name “Student“. That’s why it is called as Student’s t-test. It is the sampling distribution of the t-statistic. The values of the t-statistic is given by: t = [ x̄ - μ ] / [ s / sqrt( n ) ] where, t = t score x̄ = sample mean, μ = population mean, s = standard deviation of the sample, n = sample size When to Use the t-Distribution? Student’s t Distribution is used when The sample size must be 30 or less than 30. The population standard deviation(σ) is unknown. The population distribution must be unimodal and skewed. Mathematical Derivation of t-Distribution : The t-distribution has been derived mathematically under the assumption of normally distributed population and the formula or equation will be like this where, c = Constant required to make the area under the curve equal to unity ν = Degrees of freedom So, this above equation indicates the probability density function(pdf) of t distribution for ν degrees of freedom. Properties of the t-Distribution : The above diagram indicates that the blue color curve is a standard normal distribution curve or a Z distribution curve because the sample size(n) is greater than 30. And the red color curve is a t-distribution curve because the sample size(n) is close to 30. Similarly, the green color curve is also a t-distribution curve because the sample size(n) is smaller than 30. The t-distribution has the following properties : The variable in t-distribution ranges from -∞ to +∞ (-∞ < t < +∞). t- distribution will be symmetric like normal distribution, if power of t is even in probability density function(pdf). For large values of ν(i.e increased sample size n); the t-distribution tends to a standard normal distribution. This implies that for different ν values, the shape of t-distribution also differs. The t-distribution is less peaked than normal distribution at the center and higher peaked in the tails. From the above diagram one can observe that the red and green curves are less peaked at the center but higher peaked at the tails than the blue curve. The value of y(peak height) attains highest at μ = 0 as one can observe the same in the above diagram. The mean of the distribution is equal to 0 for ν > 1 where ν = degrees of freedom, otherwise undefined. The median and mode of the distribution is equal to 0. The variance is equal to ν / ν-2 for ν > 2 and ∞ for 2 < ν ≤ 4 otherwise undefined. The skewness is equal to 0 for ν > 3, otherwise undefined. Note – Degrees of freedom refers to the number of independent observations in a set of data. When estimating a mean score or a proportion from a single sample, the number of independent observations is equal to the sample size minus one. Hence, the distribution of the t statistic from samples of size 10 would be described by a t distribution having 10 – 1 or 9 degrees of freedom. Similarly, a t- distribution having 15 degrees of freedom would be used with a sample of size 16. t-Distribution Table : t-Distribution table gives t-value for a different level of significance and different degrees of freedom. The calculated t-value will be compared with the tabulated t-value. For example, if one is performing student’s t-test and for that performance, he has taken 5% level of significance and he got or calculated t-value and he has taken his tabulated t-value and if calculated t-value is higher than the tabulated t-value, in that case, it will say that there is a significant difference between the population mean and the sample means at 5% level of significance and if vice versa then, in that case, it will say that there is no significant difference between the population mean and the sample means at 5% level of significance. Here is the link to the t-Distribution table: http://www.ttable.org/ sumitgumber28 data-science Engineering Mathematics Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between Propositional Logic and Predicate Logic Arrow Symbols in LaTeX Set Notations in LaTeX Activation Functions Mathematics | Walks, Trails, Paths, Cycles and Circuits in Graph Properties of Boolean Algebra Univariate, Bivariate and Multivariate data and its analysis Number of Possible Super Keys in DBMS Logic Notations in LaTeX Discrete Mathematics | Hasse Diagrams
[ { "code": null, "e": 54, "s": 26, "text": "\n19 Jan, 2022" }, { "code": null, "e": 416, "s": 54, "text": "Student’s t-distribution or t-distribution is a probability distribution that is used to calculate population parameters when the sample size is small and when the population variance is unknown. Theoretical work on t-distribution was done by W.S. Gosset; he has published his findings under the pen name “Student“. That’s why it is called as Student’s t-test. " }, { "code": null, "e": 512, "s": 416, "text": "It is the sampling distribution of the t-statistic. The values of the t-statistic is given by: " }, { "code": null, "e": 663, "s": 514, "text": "t = [ x̄ - μ ] / [ s / sqrt( n ) ]\n\nwhere,\nt = t score\nx̄ = sample mean,\nμ = population mean,\ns = standard deviation of the sample,\nn = sample size " }, { "code": null, "e": 696, "s": 663, "text": "When to Use the t-Distribution? " }, { "code": null, "e": 735, "s": 696, "text": "Student’s t Distribution is used when " }, { "code": null, "e": 781, "s": 737, "text": "The sample size must be 30 or less than 30." }, { "code": null, "e": 830, "s": 781, "text": "The population standard deviation(σ) is unknown." }, { "code": null, "e": 887, "s": 830, "text": "The population distribution must be unimodal and skewed." }, { "code": null, "e": 932, "s": 887, "text": "Mathematical Derivation of t-Distribution : " }, { "code": null, "e": 1086, "s": 932, "text": "The t-distribution has been derived mathematically under the assumption of normally distributed population and the formula or equation will be like this " }, { "code": null, "e": 1190, "s": 1088, "text": "where, c = Constant required to make the area under the curve equal to unity ν = Degrees of freedom " }, { "code": null, "e": 1307, "s": 1190, "text": "So, this above equation indicates the probability density function(pdf) of t distribution for ν degrees of freedom. " }, { "code": null, "e": 1343, "s": 1307, "text": "Properties of the t-Distribution : " }, { "code": null, "e": 1717, "s": 1345, "text": "The above diagram indicates that the blue color curve is a standard normal distribution curve or a Z distribution curve because the sample size(n) is greater than 30. And the red color curve is a t-distribution curve because the sample size(n) is close to 30. Similarly, the green color curve is also a t-distribution curve because the sample size(n) is smaller than 30. " }, { "code": null, "e": 1768, "s": 1717, "text": "The t-distribution has the following properties : " }, { "code": null, "e": 1837, "s": 1770, "text": "The variable in t-distribution ranges from -∞ to +∞ (-∞ < t < +∞)." }, { "code": null, "e": 1957, "s": 1837, "text": "t- distribution will be symmetric like normal distribution, if power of t is even in probability density function(pdf)." }, { "code": null, "e": 2153, "s": 1957, "text": "For large values of ν(i.e increased sample size n); the t-distribution tends to a standard normal distribution. This implies that for different ν values, the shape of t-distribution also differs." }, { "code": null, "e": 2409, "s": 2153, "text": "The t-distribution is less peaked than normal distribution at the center and higher peaked in the tails. From the above diagram one can observe that the red and green curves are less peaked at the center but higher peaked at the tails than the blue curve." }, { "code": null, "e": 2512, "s": 2409, "text": "The value of y(peak height) attains highest at μ = 0 as one can observe the same in the above diagram." }, { "code": null, "e": 2616, "s": 2512, "text": "The mean of the distribution is equal to 0 for ν > 1 where ν = degrees of freedom, otherwise undefined." }, { "code": null, "e": 2671, "s": 2616, "text": "The median and mode of the distribution is equal to 0." }, { "code": null, "e": 2755, "s": 2671, "text": "The variance is equal to ν / ν-2 for ν > 2 and ∞ for 2 < ν ≤ 4 otherwise undefined." }, { "code": null, "e": 2814, "s": 2755, "text": "The skewness is equal to 0 for ν > 3, otherwise undefined." }, { "code": null, "e": 3296, "s": 2814, "text": "Note – Degrees of freedom refers to the number of independent observations in a set of data. When estimating a mean score or a proportion from a single sample, the number of independent observations is equal to the sample size minus one. Hence, the distribution of the t statistic from samples of size 10 would be described by a t distribution having 10 – 1 or 9 degrees of freedom. Similarly, a t- distribution having 15 degrees of freedom would be used with a sample of size 16. " }, { "code": null, "e": 4125, "s": 3296, "text": "t-Distribution Table : t-Distribution table gives t-value for a different level of significance and different degrees of freedom. The calculated t-value will be compared with the tabulated t-value. For example, if one is performing student’s t-test and for that performance, he has taken 5% level of significance and he got or calculated t-value and he has taken his tabulated t-value and if calculated t-value is higher than the tabulated t-value, in that case, it will say that there is a significant difference between the population mean and the sample means at 5% level of significance and if vice versa then, in that case, it will say that there is no significant difference between the population mean and the sample means at 5% level of significance. Here is the link to the t-Distribution table: http://www.ttable.org/ " }, { "code": null, "e": 4139, "s": 4125, "text": "sumitgumber28" }, { "code": null, "e": 4152, "s": 4139, "text": "data-science" }, { "code": null, "e": 4176, "s": 4152, "text": "Engineering Mathematics" }, { "code": null, "e": 4274, "s": 4176, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4333, "s": 4274, "text": "Difference between Propositional Logic and Predicate Logic" }, { "code": null, "e": 4356, "s": 4333, "text": "Arrow Symbols in LaTeX" }, { "code": null, "e": 4379, "s": 4356, "text": "Set Notations in LaTeX" }, { "code": null, "e": 4400, "s": 4379, "text": "Activation Functions" }, { "code": null, "e": 4465, "s": 4400, "text": "Mathematics | Walks, Trails, Paths, Cycles and Circuits in Graph" }, { "code": null, "e": 4495, "s": 4465, "text": "Properties of Boolean Algebra" }, { "code": null, "e": 4556, "s": 4495, "text": "Univariate, Bivariate and Multivariate data and its analysis" }, { "code": null, "e": 4594, "s": 4556, "text": "Number of Possible Super Keys in DBMS" }, { "code": null, "e": 4619, "s": 4594, "text": "Logic Notations in LaTeX" } ]
Tensorflow.js tf.sum() Function
12 May, 2021 Tensorflow.js is an open-source library developed by Google for running machine learning models and deep learning neural networks in the browser or node environment. The tf.sum() function is used to calculate sum of the elements of a specified Tensor across its dimension. It reduces the given input elements along the dimensions of axes. If the parameter “keepDims” is true, the reduced dimensions are retained with length 1 else the rank of Tensor is reduced by 1. If the axes parameter has no entries, it returns a Tensor with a single element with all reduced dimensions. Syntax: tf.sum(x, axis, keepDims) Parameters: This function accepts three parameters which are illustrated below: x: The input tensor on which sum operation is being computed. If the data type is Boolean value, it will be converted into int32 and the returned output will also be in int32. axis: The specified dimension(s) to reduce. By default it reduces all dimensions. It is optional parameter. keepDims: If this parameter value is true, it retains reduced dimensions with length 1 else the rank of Tensor is reduced by 1. It is also optional parameter. Return Value: It returns a Tensor for the result of sum operation. Example 1: Javascript // Importing the tensorflow.js libraryimport * as tf from "@tensorflow/tfjs" // Initializing a some tensors const a = tf.tensor1d([0, 1]);const b = tf.tensor1d([3, 5]);const c = tf.tensor1d([2, 4, 7]); // Calling the .sum() function over // the above tensorsa.sum().print();b.sum().print();c.sum().print(); Output: Tensor 1 Tensor 8 Tensor 13 Example 2: Javascript // Importing the tensorflow.js libraryimport * as tf from "@tensorflow/tfjs" // Initializing a some tensors const a = tf.tensor1d([0, 1]);const b = tf.tensor2d([3, 5, 2, 8], [2, 2]);const c = tf.tensor1d([2, 4, 7]); // Initializing a axis parametersconst axis1 = -1;const axis2 = -2;const axis3 = 0; // Calling the .sum() function over // the above tensorsa.sum(axis1).print();b.sum(axis2, true).print();c.sum(axis1, false).print();b.sum(axis3, false).print(); Output: Tensor 1 Tensor [[5, 13],] Tensor 13 Tensor [5, 13] Tensorflow Tensorflow.js JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Remove elements from a JavaScript Array Difference Between PUT and PATCH Request Roadmap to Learn JavaScript For Beginners JavaScript | Promises Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n12 May, 2021" }, { "code": null, "e": 194, "s": 28, "text": "Tensorflow.js is an open-source library developed by Google for running machine learning models and deep learning neural networks in the browser or node environment." }, { "code": null, "e": 604, "s": 194, "text": "The tf.sum() function is used to calculate sum of the elements of a specified Tensor across its dimension. It reduces the given input elements along the dimensions of axes. If the parameter “keepDims” is true, the reduced dimensions are retained with length 1 else the rank of Tensor is reduced by 1. If the axes parameter has no entries, it returns a Tensor with a single element with all reduced dimensions." }, { "code": null, "e": 612, "s": 604, "text": "Syntax:" }, { "code": null, "e": 638, "s": 612, "text": "tf.sum(x, axis, keepDims)" }, { "code": null, "e": 718, "s": 638, "text": "Parameters: This function accepts three parameters which are illustrated below:" }, { "code": null, "e": 894, "s": 718, "text": "x: The input tensor on which sum operation is being computed. If the data type is Boolean value, it will be converted into int32 and the returned output will also be in int32." }, { "code": null, "e": 1002, "s": 894, "text": "axis: The specified dimension(s) to reduce. By default it reduces all dimensions. It is optional parameter." }, { "code": null, "e": 1161, "s": 1002, "text": "keepDims: If this parameter value is true, it retains reduced dimensions with length 1 else the rank of Tensor is reduced by 1. It is also optional parameter." }, { "code": null, "e": 1228, "s": 1161, "text": "Return Value: It returns a Tensor for the result of sum operation." }, { "code": null, "e": 1239, "s": 1228, "text": "Example 1:" }, { "code": null, "e": 1250, "s": 1239, "text": "Javascript" }, { "code": "// Importing the tensorflow.js libraryimport * as tf from \"@tensorflow/tfjs\" // Initializing a some tensors const a = tf.tensor1d([0, 1]);const b = tf.tensor1d([3, 5]);const c = tf.tensor1d([2, 4, 7]); // Calling the .sum() function over // the above tensorsa.sum().print();b.sum().print();c.sum().print();", "e": 1559, "s": 1250, "text": null }, { "code": null, "e": 1567, "s": 1559, "text": "Output:" }, { "code": null, "e": 1604, "s": 1567, "text": "Tensor\n 1\nTensor\n 8\nTensor\n 13" }, { "code": null, "e": 1615, "s": 1604, "text": "Example 2:" }, { "code": null, "e": 1626, "s": 1615, "text": "Javascript" }, { "code": "// Importing the tensorflow.js libraryimport * as tf from \"@tensorflow/tfjs\" // Initializing a some tensors const a = tf.tensor1d([0, 1]);const b = tf.tensor2d([3, 5, 2, 8], [2, 2]);const c = tf.tensor1d([2, 4, 7]); // Initializing a axis parametersconst axis1 = -1;const axis2 = -2;const axis3 = 0; // Calling the .sum() function over // the above tensorsa.sum(axis1).print();b.sum(axis2, true).print();c.sum(axis1, false).print();b.sum(axis3, false).print();", "e": 2090, "s": 1626, "text": null }, { "code": null, "e": 2098, "s": 2090, "text": "Output:" }, { "code": null, "e": 2163, "s": 2098, "text": "Tensor\n 1\nTensor\n [[5, 13],]\nTensor\n 13\nTensor\n [5, 13]" }, { "code": null, "e": 2174, "s": 2163, "text": "Tensorflow" }, { "code": null, "e": 2188, "s": 2174, "text": "Tensorflow.js" }, { "code": null, "e": 2199, "s": 2188, "text": "JavaScript" }, { "code": null, "e": 2216, "s": 2199, "text": "Web Technologies" }, { "code": null, "e": 2314, "s": 2216, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2375, "s": 2314, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2415, "s": 2375, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 2456, "s": 2415, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 2498, "s": 2456, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 2520, "s": 2498, "text": "JavaScript | Promises" }, { "code": null, "e": 2553, "s": 2520, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2615, "s": 2553, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2676, "s": 2615, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2726, "s": 2676, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Mongoose | findByIdAndRemove() Function
20 May, 2020 The findByIdAndRemove() function is used to find a matching document, remove it, passing the found document (if any) to the callback. Installation of mongoose module: You can visit the link to Install mongoose module. You can install this package by using this command.npm install mongooseAfter installing mongoose module, you can check your mongoose version in command prompt using the command.npm version mongooseAfter that, you can just create a folder and add a file for example index.js, To run this file you need to run the following command.node index.js You can visit the link to Install mongoose module. You can install this package by using this command.npm install mongoose npm install mongoose After installing mongoose module, you can check your mongoose version in command prompt using the command.npm version mongoose npm version mongoose After that, you can just create a folder and add a file for example index.js, To run this file you need to run the following command.node index.js node index.js Filename: index.js const mongoose = require('mongoose'); // Database connectionmongoose.connect('mongodb://127.0.0.1:27017/geeksforgeeks', { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true, useFindAndModify: false}); // User modelconst User = mongoose.model('User', { name: { type: String }, age: { type: Number }}); // Find a document whose // user_id=5eb987e377d884411cac6b69 and remove itvar user_id = '5eb987e377d884411cac6b69';User.findByIdAndRemove(user_id, function (err, docs) { if (err){ console.log(err) } else{ console.log("Removed User : ", docs); }}); Steps to run the program: The project structure will look like this:Make sure you have installed mongoose module using following command:npm install mongooseBelow is the sample data in the database before the function is executed, You can use any GUI tool or terminal to see the database, like we have used Robo3T GUI tool as shown below:Run index.js file using below command:node index.jsAfter the function is executed, you can see in the database that the particular user is removed as shown below: The project structure will look like this: Make sure you have installed mongoose module using following command:npm install mongoose npm install mongoose Below is the sample data in the database before the function is executed, You can use any GUI tool or terminal to see the database, like we have used Robo3T GUI tool as shown below: Run index.js file using below command:node index.js node index.js After the function is executed, you can see in the database that the particular user is removed as shown below: So this is how you can use the mongoose findByIdAndRemove() which finds a matching document, removes it, passing the found document (if any) to the callback. Mongoose MongoDB Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Spring Boot JpaRepository with Example Mongoose Populate() Method MongoDB - db.collection.Find() Method Aggregation in MongoDB MongoDB - Check the existence of the fields in the specified collection How to update Node.js and NPM to next version ? Installation of Node.js on Linux Node.js fs.readFileSync() Method How to install the previous version of node.js and npm ? Node.js fs.writeFile() Method
[ { "code": null, "e": 28, "s": 0, "text": "\n20 May, 2020" }, { "code": null, "e": 162, "s": 28, "text": "The findByIdAndRemove() function is used to find a matching document, remove it, passing the found document (if any) to the callback." }, { "code": null, "e": 195, "s": 162, "text": "Installation of mongoose module:" }, { "code": null, "e": 590, "s": 195, "text": "You can visit the link to Install mongoose module. You can install this package by using this command.npm install mongooseAfter installing mongoose module, you can check your mongoose version in command prompt using the command.npm version mongooseAfter that, you can just create a folder and add a file for example index.js, To run this file you need to run the following command.node index.js" }, { "code": null, "e": 713, "s": 590, "text": "You can visit the link to Install mongoose module. You can install this package by using this command.npm install mongoose" }, { "code": null, "e": 734, "s": 713, "text": "npm install mongoose" }, { "code": null, "e": 861, "s": 734, "text": "After installing mongoose module, you can check your mongoose version in command prompt using the command.npm version mongoose" }, { "code": null, "e": 882, "s": 861, "text": "npm version mongoose" }, { "code": null, "e": 1029, "s": 882, "text": "After that, you can just create a folder and add a file for example index.js, To run this file you need to run the following command.node index.js" }, { "code": null, "e": 1043, "s": 1029, "text": "node index.js" }, { "code": null, "e": 1062, "s": 1043, "text": "Filename: index.js" }, { "code": "const mongoose = require('mongoose'); // Database connectionmongoose.connect('mongodb://127.0.0.1:27017/geeksforgeeks', { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true, useFindAndModify: false}); // User modelconst User = mongoose.model('User', { name: { type: String }, age: { type: Number }}); // Find a document whose // user_id=5eb987e377d884411cac6b69 and remove itvar user_id = '5eb987e377d884411cac6b69';User.findByIdAndRemove(user_id, function (err, docs) { if (err){ console.log(err) } else{ console.log(\"Removed User : \", docs); }});", "e": 1677, "s": 1062, "text": null }, { "code": null, "e": 1703, "s": 1677, "text": "Steps to run the program:" }, { "code": null, "e": 2178, "s": 1703, "text": "The project structure will look like this:Make sure you have installed mongoose module using following command:npm install mongooseBelow is the sample data in the database before the function is executed, You can use any GUI tool or terminal to see the database, like we have used Robo3T GUI tool as shown below:Run index.js file using below command:node index.jsAfter the function is executed, you can see in the database that the particular user is removed as shown below:" }, { "code": null, "e": 2221, "s": 2178, "text": "The project structure will look like this:" }, { "code": null, "e": 2311, "s": 2221, "text": "Make sure you have installed mongoose module using following command:npm install mongoose" }, { "code": null, "e": 2332, "s": 2311, "text": "npm install mongoose" }, { "code": null, "e": 2514, "s": 2332, "text": "Below is the sample data in the database before the function is executed, You can use any GUI tool or terminal to see the database, like we have used Robo3T GUI tool as shown below:" }, { "code": null, "e": 2566, "s": 2514, "text": "Run index.js file using below command:node index.js" }, { "code": null, "e": 2580, "s": 2566, "text": "node index.js" }, { "code": null, "e": 2692, "s": 2580, "text": "After the function is executed, you can see in the database that the particular user is removed as shown below:" }, { "code": null, "e": 2850, "s": 2692, "text": "So this is how you can use the mongoose findByIdAndRemove() which finds a matching document, removes it, passing the found document (if any) to the callback." }, { "code": null, "e": 2859, "s": 2850, "text": "Mongoose" }, { "code": null, "e": 2867, "s": 2859, "text": "MongoDB" }, { "code": null, "e": 2875, "s": 2867, "text": "Node.js" }, { "code": null, "e": 2892, "s": 2875, "text": "Web Technologies" }, { "code": null, "e": 2990, "s": 2892, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3029, "s": 2990, "text": "Spring Boot JpaRepository with Example" }, { "code": null, "e": 3056, "s": 3029, "text": "Mongoose Populate() Method" }, { "code": null, "e": 3094, "s": 3056, "text": "MongoDB - db.collection.Find() Method" }, { "code": null, "e": 3117, "s": 3094, "text": "Aggregation in MongoDB" }, { "code": null, "e": 3189, "s": 3117, "text": "MongoDB - Check the existence of the fields in the specified collection" }, { "code": null, "e": 3237, "s": 3189, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 3270, "s": 3237, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 3303, "s": 3270, "text": "Node.js fs.readFileSync() Method" }, { "code": null, "e": 3360, "s": 3303, "text": "How to install the previous version of node.js and npm ?" } ]
Depth wise Separable Convolutional Neural Networks
28 Aug, 2019 Convolution is a very important mathematical operation in artificial neural networks(ANN’s). Convolutional neural networks (CNN’s) can be used to learn features as well as classify data with the help of image frames. There are many types of CNN’s. One class of CNN’s are depth wise separable convolutional neural networks. These type of CNN’s are widely used because of the following two reasons – They have lesser number of parameters to adjust as compared to the standard CNN’s, which reduces overfitting They are computationally cheaper because of fewer computations which makes them suitable for mobile vision applications Some important applications of these type of CNN’s are MobileNet, Xception ( both proposed by Google ) This article explains the architecture and operations used by depth wise separable convolutional networks and derives its efficiency over simple convolution neural networks. Suppose there is an input data of size Df x Df x M, where Df x Df can be the image size and M is the number of channels (3 for an RGB image). Suppose there are N filters/kernels of size Dk x Dk x M. If a normal convolution operation is done, then, the output size will be Dp x Dp x N. The number of multiplications in 1 convolution operation = size of filter = Dk x Dk x M Since there are N filters and each filter slides vertically and horizontally Dp times, the total number of multiplications become N x Dp x Dp x (Multiplications per convolution) So for normal convolution operation Total no of multiplications = N x Dp2 x Dk2 x M Now look at depth-wise separable convolutions. This process is broken down into 2 operations – Depth-wise convolutionsPoint-wise convolutions Depth-wise convolutions Point-wise convolutions DEPTH WISE CONVOLUTIONIn depth-wise operation, convolution is applied to a single channel at a time unlike standard CNN’s in which it is done for all the M channels. So here the filters/kernels will be of size Dk x Dk x 1. Given there are M channels in the input data, then M such filters are required. Output will be of size Dp x Dp x M.Cost of this operation:A single convolution operation require Dk x Dk multiplications.Since the filter are slided by Dp x Dp times across all the M channels,the total number of multiplications is equal to M x Dp x Dp x Dk x DkSo for depth wise convolution operationTotal no of multiplications = M x Dk2 x Dp2POINT WISE CONVOLUTIONIn point-wise operation, a 1×1 convolution operation is applied on the M channels. So the filter size for this operation will be 1 x 1 x M. Say we use N such filters, the output size becomes Dp x Dp x N.Cost of this operation:A single convolution operation require 1 x M multiplications.Since the filter is being slided by Dp x Dp times,the total number of multiplications is equal to M x Dp x Dp x (no. of filters)So for point wise convolution operationTotal no of multiplications = M x Dp2 x NTherefore, for overall operation:Total multiplications = Depth wise conv. multiplications + Point wise conv. multiplicationsTotal multiplications = M * Dk2 * Dp2 + M * Dp2 * N = M * Dp2 * (Dk2 + n)So for depth wise separable convolution operationTotal no of multiplications = M x Dp2 x (Dk2 + N)Comparison between the complexities of these types of convolution operations<Type of ConvolutionComplexityStandardN x Dp2 x Dg2 x MDepth wise separableM x Dp2 x (Dk2 + N) Complexity of depth wise separable convolutions -------------------------------------------------- = RATIO ( R ) Complexity of standard convolution Upon solving:Ratio(R) = 1/N + 1/Dk2As an example, consider N = 100 and Dk = 512. Then the ratio R = 0.010004This means that the depth wise separable convolution network, in this example, performs 100 times lesser multiplications as compared to a standard constitutional neural network.This implies that we can deploy faster convolution neural network models without losing much of the accuracy.My Personal Notes arrow_drop_upSave DEPTH WISE CONVOLUTIONIn depth-wise operation, convolution is applied to a single channel at a time unlike standard CNN’s in which it is done for all the M channels. So here the filters/kernels will be of size Dk x Dk x 1. Given there are M channels in the input data, then M such filters are required. Output will be of size Dp x Dp x M.Cost of this operation:A single convolution operation require Dk x Dk multiplications.Since the filter are slided by Dp x Dp times across all the M channels,the total number of multiplications is equal to M x Dp x Dp x Dk x DkSo for depth wise convolution operationTotal no of multiplications = M x Dk2 x Dp2 In depth-wise operation, convolution is applied to a single channel at a time unlike standard CNN’s in which it is done for all the M channels. So here the filters/kernels will be of size Dk x Dk x 1. Given there are M channels in the input data, then M such filters are required. Output will be of size Dp x Dp x M. Cost of this operation: A single convolution operation require Dk x Dk multiplications. Since the filter are slided by Dp x Dp times across all the M channels, the total number of multiplications is equal to M x Dp x Dp x Dk x Dk So for depth wise convolution operation Total no of multiplications = M x Dk2 x Dp2 POINT WISE CONVOLUTIONIn point-wise operation, a 1×1 convolution operation is applied on the M channels. So the filter size for this operation will be 1 x 1 x M. Say we use N such filters, the output size becomes Dp x Dp x N.Cost of this operation:A single convolution operation require 1 x M multiplications.Since the filter is being slided by Dp x Dp times,the total number of multiplications is equal to M x Dp x Dp x (no. of filters)So for point wise convolution operationTotal no of multiplications = M x Dp2 x NTherefore, for overall operation:Total multiplications = Depth wise conv. multiplications + Point wise conv. multiplicationsTotal multiplications = M * Dk2 * Dp2 + M * Dp2 * N = M * Dp2 * (Dk2 + n)So for depth wise separable convolution operationTotal no of multiplications = M x Dp2 x (Dk2 + N)Comparison between the complexities of these types of convolution operations<Type of ConvolutionComplexityStandardN x Dp2 x Dg2 x MDepth wise separableM x Dp2 x (Dk2 + N) Complexity of depth wise separable convolutions -------------------------------------------------- = RATIO ( R ) Complexity of standard convolution Upon solving:Ratio(R) = 1/N + 1/Dk2As an example, consider N = 100 and Dk = 512. Then the ratio R = 0.010004This means that the depth wise separable convolution network, in this example, performs 100 times lesser multiplications as compared to a standard constitutional neural network.This implies that we can deploy faster convolution neural network models without losing much of the accuracy.My Personal Notes arrow_drop_upSave In point-wise operation, a 1×1 convolution operation is applied on the M channels. So the filter size for this operation will be 1 x 1 x M. Say we use N such filters, the output size becomes Dp x Dp x N. Cost of this operation: A single convolution operation require 1 x M multiplications. Since the filter is being slided by Dp x Dp times, the total number of multiplications is equal to M x Dp x Dp x (no. of filters) So for point wise convolution operation Total no of multiplications = M x Dp2 x N Therefore, for overall operation: Total multiplications = Depth wise conv. multiplications + Point wise conv. multiplications Total multiplications = M * Dk2 * Dp2 + M * Dp2 * N = M * Dp2 * (Dk2 + n) So for depth wise separable convolution operation Total no of multiplications = M x Dp2 x (Dk2 + N) < Complexity of depth wise separable convolutions -------------------------------------------------- = RATIO ( R ) Complexity of standard convolution Upon solving: Ratio(R) = 1/N + 1/Dk2 As an example, consider N = 100 and Dk = 512. Then the ratio R = 0.010004 This means that the depth wise separable convolution network, in this example, performs 100 times lesser multiplications as compared to a standard constitutional neural network. This implies that we can deploy faster convolution neural network models without losing much of the accuracy. MeghnaNatraj Neural Network Articles GBlog Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n28 Aug, 2019" }, { "code": null, "e": 377, "s": 54, "text": "Convolution is a very important mathematical operation in artificial neural networks(ANN’s). Convolutional neural networks (CNN’s) can be used to learn features as well as classify data with the help of image frames. There are many types of CNN’s. One class of CNN’s are depth wise separable convolutional neural networks." }, { "code": null, "e": 452, "s": 377, "text": "These type of CNN’s are widely used because of the following two reasons –" }, { "code": null, "e": 561, "s": 452, "text": "They have lesser number of parameters to adjust as compared to the standard CNN’s, which reduces overfitting" }, { "code": null, "e": 681, "s": 561, "text": "They are computationally cheaper because of fewer computations which makes them suitable for mobile vision applications" }, { "code": null, "e": 784, "s": 681, "text": "Some important applications of these type of CNN’s are MobileNet, Xception ( both proposed by Google )" }, { "code": null, "e": 958, "s": 784, "text": "This article explains the architecture and operations used by depth wise separable convolutional networks and derives its efficiency over simple convolution neural networks." }, { "code": null, "e": 1243, "s": 958, "text": "Suppose there is an input data of size Df x Df x M, where Df x Df can be the image size and M is the number of channels (3 for an RGB image). Suppose there are N filters/kernels of size Dk x Dk x M. If a normal convolution operation is done, then, the output size will be Dp x Dp x N." }, { "code": null, "e": 1331, "s": 1243, "text": "The number of multiplications in 1 convolution operation = size of filter = Dk x Dk x M" }, { "code": null, "e": 1418, "s": 1331, "text": "Since there are N filters and each filter slides vertically and horizontally Dp times," }, { "code": null, "e": 1509, "s": 1418, "text": "the total number of multiplications become N x Dp x Dp x (Multiplications per convolution)" }, { "code": null, "e": 1545, "s": 1509, "text": "So for normal convolution operation" }, { "code": null, "e": 1593, "s": 1545, "text": "Total no of multiplications = N x Dp2 x Dk2 x M" }, { "code": null, "e": 1688, "s": 1593, "text": "Now look at depth-wise separable convolutions. This process is broken down into 2 operations –" }, { "code": null, "e": 1735, "s": 1688, "text": "Depth-wise convolutionsPoint-wise convolutions" }, { "code": null, "e": 1759, "s": 1735, "text": "Depth-wise convolutions" }, { "code": null, "e": 1783, "s": 1759, "text": "Point-wise convolutions" }, { "code": null, "e": 4003, "s": 1783, "text": "DEPTH WISE CONVOLUTIONIn depth-wise operation, convolution is applied to a single channel at a time unlike standard CNN’s in which it is done for all the M channels. So here the filters/kernels will be of size Dk x Dk x 1. Given there are M channels in the input data, then M such filters are required. Output will be of size Dp x Dp x M.Cost of this operation:A single convolution operation require Dk x Dk multiplications.Since the filter are slided by Dp x Dp times across all the M channels,the total number of multiplications is equal to M x Dp x Dp x Dk x DkSo for depth wise convolution operationTotal no of multiplications = M x Dk2 x Dp2POINT WISE CONVOLUTIONIn point-wise operation, a 1×1 convolution operation is applied on the M channels. So the filter size for this operation will be 1 x 1 x M. Say we use N such filters, the output size becomes Dp x Dp x N.Cost of this operation:A single convolution operation require 1 x M multiplications.Since the filter is being slided by Dp x Dp times,the total number of multiplications is equal to M x Dp x Dp x (no. of filters)So for point wise convolution operationTotal no of multiplications = M x Dp2 x NTherefore, for overall operation:Total multiplications = Depth wise conv. multiplications + Point wise conv. multiplicationsTotal multiplications = M * Dk2 * Dp2 + M * Dp2 * N = M * Dp2 * (Dk2 + n)So for depth wise separable convolution operationTotal no of multiplications = M x Dp2 x (Dk2 + N)Comparison between the complexities of these types of convolution operations<Type of ConvolutionComplexityStandardN x Dp2 x Dg2 x MDepth wise separableM x Dp2 x (Dk2 + N) Complexity of depth wise separable convolutions \n-------------------------------------------------- = RATIO ( R )\n Complexity of standard convolution \nUpon solving:Ratio(R) = 1/N + 1/Dk2As an example, consider N = 100 and Dk = 512. Then the ratio R = 0.010004This means that the depth wise separable convolution network, in this example, performs 100 times lesser multiplications as compared to a standard constitutional neural network.This implies that we can deploy faster convolution neural network models without losing much of the accuracy.My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 4650, "s": 4003, "text": "DEPTH WISE CONVOLUTIONIn depth-wise operation, convolution is applied to a single channel at a time unlike standard CNN’s in which it is done for all the M channels. So here the filters/kernels will be of size Dk x Dk x 1. Given there are M channels in the input data, then M such filters are required. Output will be of size Dp x Dp x M.Cost of this operation:A single convolution operation require Dk x Dk multiplications.Since the filter are slided by Dp x Dp times across all the M channels,the total number of multiplications is equal to M x Dp x Dp x Dk x DkSo for depth wise convolution operationTotal no of multiplications = M x Dk2 x Dp2" }, { "code": null, "e": 4967, "s": 4650, "text": "In depth-wise operation, convolution is applied to a single channel at a time unlike standard CNN’s in which it is done for all the M channels. So here the filters/kernels will be of size Dk x Dk x 1. Given there are M channels in the input data, then M such filters are required. Output will be of size Dp x Dp x M." }, { "code": null, "e": 4991, "s": 4967, "text": "Cost of this operation:" }, { "code": null, "e": 5055, "s": 4991, "text": "A single convolution operation require Dk x Dk multiplications." }, { "code": null, "e": 5127, "s": 5055, "text": "Since the filter are slided by Dp x Dp times across all the M channels," }, { "code": null, "e": 5197, "s": 5127, "text": "the total number of multiplications is equal to M x Dp x Dp x Dk x Dk" }, { "code": null, "e": 5237, "s": 5197, "text": "So for depth wise convolution operation" }, { "code": null, "e": 5281, "s": 5237, "text": "Total no of multiplications = M x Dk2 x Dp2" }, { "code": null, "e": 6855, "s": 5281, "text": "POINT WISE CONVOLUTIONIn point-wise operation, a 1×1 convolution operation is applied on the M channels. So the filter size for this operation will be 1 x 1 x M. Say we use N such filters, the output size becomes Dp x Dp x N.Cost of this operation:A single convolution operation require 1 x M multiplications.Since the filter is being slided by Dp x Dp times,the total number of multiplications is equal to M x Dp x Dp x (no. of filters)So for point wise convolution operationTotal no of multiplications = M x Dp2 x NTherefore, for overall operation:Total multiplications = Depth wise conv. multiplications + Point wise conv. multiplicationsTotal multiplications = M * Dk2 * Dp2 + M * Dp2 * N = M * Dp2 * (Dk2 + n)So for depth wise separable convolution operationTotal no of multiplications = M x Dp2 x (Dk2 + N)Comparison between the complexities of these types of convolution operations<Type of ConvolutionComplexityStandardN x Dp2 x Dg2 x MDepth wise separableM x Dp2 x (Dk2 + N) Complexity of depth wise separable convolutions \n-------------------------------------------------- = RATIO ( R )\n Complexity of standard convolution \nUpon solving:Ratio(R) = 1/N + 1/Dk2As an example, consider N = 100 and Dk = 512. Then the ratio R = 0.010004This means that the depth wise separable convolution network, in this example, performs 100 times lesser multiplications as compared to a standard constitutional neural network.This implies that we can deploy faster convolution neural network models without losing much of the accuracy.My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 7059, "s": 6855, "text": "In point-wise operation, a 1×1 convolution operation is applied on the M channels. So the filter size for this operation will be 1 x 1 x M. Say we use N such filters, the output size becomes Dp x Dp x N." }, { "code": null, "e": 7083, "s": 7059, "text": "Cost of this operation:" }, { "code": null, "e": 7145, "s": 7083, "text": "A single convolution operation require 1 x M multiplications." }, { "code": null, "e": 7196, "s": 7145, "text": "Since the filter is being slided by Dp x Dp times," }, { "code": null, "e": 7275, "s": 7196, "text": "the total number of multiplications is equal to M x Dp x Dp x (no. of filters)" }, { "code": null, "e": 7315, "s": 7275, "text": "So for point wise convolution operation" }, { "code": null, "e": 7357, "s": 7315, "text": "Total no of multiplications = M x Dp2 x N" }, { "code": null, "e": 7391, "s": 7357, "text": "Therefore, for overall operation:" }, { "code": null, "e": 7483, "s": 7391, "text": "Total multiplications = Depth wise conv. multiplications + Point wise conv. multiplications" }, { "code": null, "e": 7557, "s": 7483, "text": "Total multiplications = M * Dk2 * Dp2 + M * Dp2 * N = M * Dp2 * (Dk2 + n)" }, { "code": null, "e": 7607, "s": 7557, "text": "So for depth wise separable convolution operation" }, { "code": null, "e": 7657, "s": 7607, "text": "Total no of multiplications = M x Dp2 x (Dk2 + N)" }, { "code": null, "e": 7659, "s": 7657, "text": "<" }, { "code": null, "e": 7822, "s": 7659, "text": " Complexity of depth wise separable convolutions \n-------------------------------------------------- = RATIO ( R )\n Complexity of standard convolution \n" }, { "code": null, "e": 7836, "s": 7822, "text": "Upon solving:" }, { "code": null, "e": 7859, "s": 7836, "text": "Ratio(R) = 1/N + 1/Dk2" }, { "code": null, "e": 7933, "s": 7859, "text": "As an example, consider N = 100 and Dk = 512. Then the ratio R = 0.010004" }, { "code": null, "e": 8111, "s": 7933, "text": "This means that the depth wise separable convolution network, in this example, performs 100 times lesser multiplications as compared to a standard constitutional neural network." }, { "code": null, "e": 8221, "s": 8111, "text": "This implies that we can deploy faster convolution neural network models without losing much of the accuracy." }, { "code": null, "e": 8234, "s": 8221, "text": "MeghnaNatraj" }, { "code": null, "e": 8249, "s": 8234, "text": "Neural Network" }, { "code": null, "e": 8258, "s": 8249, "text": "Articles" }, { "code": null, "e": 8264, "s": 8258, "text": "GBlog" } ]
How to trigger click on select box on hover using jQuery ?
01 Dec, 2021 In this article, we are going to learn, how we can trigger a click event on the select box or drop-down menu while hovering the mouse using jQuery. For creating such behavior for a select box, we will use the jQuery attr() method. This method is used to set or return the attributes and values of the selected elements on the webpage. Note that we will not be able to directly trigger the click event on hover, so we are using the attr() method to get the work done. Approach: We will call the hover() method on the following id or class of the select box. We will use the attr() method to get the size of the select box and in the same method we will change its size to 1, so when we move the cursor out from the select box it gets back to the default size. By using this approach, we will be able to show the whole list on mouse hover and when the user selects any value from the list it goes back to the default view. Example: HTML <!DOCTYPE html><head> <script src= "https://code.jquery.com/jquery-3.6.0.min.js" integrity= "sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin= "anonymous"> </script> <title>Trigger click on hover on the select box</title> <style> body { margin: 0px; padding: 0px; box-sizing: border-box; } .main{ display: flex; align-items: center; align-items: center; justify-content: center; margin: 50px; } .main div{ width: 100px; height: 100px; background-color: red; margin: 10px; border-radius: 50%; cursor: pointer; } #select_value{ outline: none; width: 120px; } </style></head><body><div class="main"> <select id="select_value"> <!-- There are five items on the list --> <option value="">Select</option> <option value="Actor">Actor</option> <option value="Dancer">Dancer</option> <option value="Singer">Singer</option> <option value="Musician">Musician</option> <option value="Fighter">Fighter</option> </select></div></body><script> $(function(){ // When the user hovers over the select box, // it gets the value of the whole list. $('#select_value').hover(function() { $(this).attr('size', $('option').length); }, // When the user stops hovering over the select box, // it gets back to the normal or default value. function() { $(this).attr('size', 1); }); // When the user clicks on the select box, // it gets the value of the selected item. $('#select_value').click(function() { $(this).attr('size', 1); }); }); </script></html> Output: HTML-Questions jQuery-Methods jQuery-Questions Picked HTML JQuery Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. REST API (Introduction) Design a Tribute Page using HTML & CSS Build a Survey Form using HTML and CSS Angular File Upload Form validation using jQuery JQuery | Set the value of an input text field How to change selected value of a drop-down list using jQuery? Form validation using jQuery How to add options to a select element using jQuery? jQuery | children() with Examples
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Dec, 2021" }, { "code": null, "e": 176, "s": 28, "text": "In this article, we are going to learn, how we can trigger a click event on the select box or drop-down menu while hovering the mouse using jQuery." }, { "code": null, "e": 495, "s": 176, "text": "For creating such behavior for a select box, we will use the jQuery attr() method. This method is used to set or return the attributes and values of the selected elements on the webpage. Note that we will not be able to directly trigger the click event on hover, so we are using the attr() method to get the work done." }, { "code": null, "e": 949, "s": 495, "text": "Approach: We will call the hover() method on the following id or class of the select box. We will use the attr() method to get the size of the select box and in the same method we will change its size to 1, so when we move the cursor out from the select box it gets back to the default size. By using this approach, we will be able to show the whole list on mouse hover and when the user selects any value from the list it goes back to the default view." }, { "code": null, "e": 959, "s": 949, "text": "Example: " }, { "code": null, "e": 964, "s": 959, "text": "HTML" }, { "code": "<!DOCTYPE html><head> <script src= \"https://code.jquery.com/jquery-3.6.0.min.js\" integrity= \"sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=\" crossorigin= \"anonymous\"> </script> <title>Trigger click on hover on the select box</title> <style> body { margin: 0px; padding: 0px; box-sizing: border-box; } .main{ display: flex; align-items: center; align-items: center; justify-content: center; margin: 50px; } .main div{ width: 100px; height: 100px; background-color: red; margin: 10px; border-radius: 50%; cursor: pointer; } #select_value{ outline: none; width: 120px; } </style></head><body><div class=\"main\"> <select id=\"select_value\"> <!-- There are five items on the list --> <option value=\"\">Select</option> <option value=\"Actor\">Actor</option> <option value=\"Dancer\">Dancer</option> <option value=\"Singer\">Singer</option> <option value=\"Musician\">Musician</option> <option value=\"Fighter\">Fighter</option> </select></div></body><script> $(function(){ // When the user hovers over the select box, // it gets the value of the whole list. $('#select_value').hover(function() { $(this).attr('size', $('option').length); }, // When the user stops hovering over the select box, // it gets back to the normal or default value. function() { $(this).attr('size', 1); }); // When the user clicks on the select box, // it gets the value of the selected item. $('#select_value').click(function() { $(this).attr('size', 1); }); }); </script></html>", "e": 2881, "s": 964, "text": null }, { "code": null, "e": 2889, "s": 2881, "text": "Output:" }, { "code": null, "e": 2904, "s": 2889, "text": "HTML-Questions" }, { "code": null, "e": 2919, "s": 2904, "text": "jQuery-Methods" }, { "code": null, "e": 2936, "s": 2919, "text": "jQuery-Questions" }, { "code": null, "e": 2943, "s": 2936, "text": "Picked" }, { "code": null, "e": 2948, "s": 2943, "text": "HTML" }, { "code": null, "e": 2955, "s": 2948, "text": "JQuery" }, { "code": null, "e": 2972, "s": 2955, "text": "Web Technologies" }, { "code": null, "e": 2977, "s": 2972, "text": "HTML" }, { "code": null, "e": 3075, "s": 2977, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3099, "s": 3075, "text": "REST API (Introduction)" }, { "code": null, "e": 3138, "s": 3099, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 3177, "s": 3138, "text": "Build a Survey Form using HTML and CSS" }, { "code": null, "e": 3197, "s": 3177, "text": "Angular File Upload" }, { "code": null, "e": 3226, "s": 3197, "text": "Form validation using jQuery" }, { "code": null, "e": 3272, "s": 3226, "text": "JQuery | Set the value of an input text field" }, { "code": null, "e": 3335, "s": 3272, "text": "How to change selected value of a drop-down list using jQuery?" }, { "code": null, "e": 3364, "s": 3335, "text": "Form validation using jQuery" }, { "code": null, "e": 3417, "s": 3364, "text": "How to add options to a select element using jQuery?" } ]
Modulo 10^9+7 (1000000007)
23 Jun, 2022 In most programming competitions, we are required to answer the result in 10^9+7 modulo. The reason behind this is, if problem constraints are large integers, only efficient algorithms can solve them in an allowed limited time.What is modulo operation: The remainder obtained after the division operation on two operands is known as modulo operation. The operator for doing modulus operation is ‘%’. For ex: a % b = c which means, when a is divided by b it gives the remainder c, 7%2 = 1, 17%3 = 2.Why do we need modulo: The reason of taking Mod is to prevent integer overflows. The largest integer data type in C/C++ is unsigned long long int which is of 64 bit and can handle integer from 0 to (2^64 – 1). But in some problems where the growth rate of output is very high, this high range of unsigned long long may be insufficient. Suppose in a 64 bit variable ‘A’, 2^62 is stored and in another 64 bit variable ‘B’, 2^63 is stored. When we multiply A and B, the system does not give a runtime error or exception. It just does some bogus computation and stores the bogus result because the bit size of the result comes after multiplication overflows. In some of the problems, to compute the result modulo inverse is needed and this number helps a lot because it is prime. Also, this number should be large enough otherwise modular inverse techniques may fail in some situations. Due to these reasons, problem setters require to give the answer as a result of modulo of some number N. There are certain criteria on which the value of N depends: It should just be large enough to fit in the largest integer data type i.e it makes sure that there is no overflow in the result.It should be a prime number because if we take mod of a number by Prime the result is generally spaced i.e. the results are very different results in comparison to mod the number by non-prime, that is why primes are generally used for mod. It should just be large enough to fit in the largest integer data type i.e it makes sure that there is no overflow in the result. It should be a prime number because if we take mod of a number by Prime the result is generally spaced i.e. the results are very different results in comparison to mod the number by non-prime, that is why primes are generally used for mod. 10^9+7 fulfills both the criteria. It is the first 10-digit prime number and fits in int data type as well. In fact, any prime number less than 2^30 will be fine in order to prevent possible overflows.How modulo is used: A few distributive properties of modulo are as follows: ( a + b) % c = ( ( a % c ) + ( b % c ) ) % c( a * b) % c = ( ( a % c ) * ( b % c ) ) % c( a – b) % c = ( ( a % c ) – ( b % c ) ) % c( a / b ) % c = ( ( a % c ) / ( b % c ) ) % c ( a + b) % c = ( ( a % c ) + ( b % c ) ) % c ( a * b) % c = ( ( a % c ) * ( b % c ) ) % c ( a – b) % c = ( ( a % c ) – ( b % c ) ) % c ( a / b ) % c = ( ( a % c ) / ( b % c ) ) % c So, modulo is distributive over +, * and – but not over / [Please refer Modular Division for details]NOTE: The result of ( a % b ) will always be less than b.In the case of computer programs, due to the size of variable limitations, we perform modulo M at each intermediate stage so that range overflow never occurs. Example: a = 145785635595363569532135132 b = 3151635135413512165131321321 c = 999874455222222200651351351 m = 1000000007 Print (a*b*c)%m. Method 1: First, multiply all the number and then take modulo: (a*b*c)%m = (459405448184212290893339835148809 515332440033400818566717735644307024625348601572) % 1000000007 a*b*c does not fit even in the unsigned long long int due to which system drop some of its most significant digits. Therefore, it gives the wrong answer. (a*b*c)%m = 798848767 Method 2: Take modulo at each intermediate steps: i = 1 i = (i*a) % m // i = 508086243 i = (i*b) % m // i = 144702857 i = (i*c) % m // i = 798848767 i = 798848767 Method 2 always gives the correct answer. Function for finding factorial of a large number using modulo but at different positions. C++ C Java Python3 C# Javascript unsigned long long factorial(int n){ const unsigned int M = 1000000007; unsigned long long f = 1; for (int i = 1; i <= n; i++) f = f * i; // WRONG APPROACH as // f may exceed (2^64 - 1) return f % M;} // This code is contributed by Shubham Singh unsigned long long factorial(int n){ const unsigned int M = 1000000007; unsigned long long f = 1; for (int i = 1; i <= n; i++) f = f * i; // WRONG APPROACH as // f may exceed (2^64 - 1) return f % M;} static long factorial(int n){ const long M = 1000000007; long f = 1; for (int i = 1; i <= n; i++) f = f * i; // WRONG APPROACH as // f may exceed (2^64 - 1) return f % M;} // This code is contributed by rutvik_56. def factorial( n) : M = 1000000007 f = 1 for i in range(1, n + 1): f = f * i # WRONG APPROACH as # f may exceed (2^64 - 1) return f % M # This code is contributed by# Shubham Singh(SHUBHAMSINGH10) static long factorial(int n){ const long M = 1000000007; long f = 1; for (int i = 1; i <= n; i++) f = f * i; // WRONG APPROACH as // f may exceed (2^64 - 1) return f % M;} // This code is contributed by pratham76. function factorial( n){ let M = 1000000007; let f = 1; for (let i = 1; i <= n; i++) f = f * i; // WRONG APPROACH as // f may exceed (2^64 - 1) return f % M;} # This code is contributed by# Shubham Singh(SHUBHAMSINGH10) C++ C Java Python3 C# Javascript unsigned long long factorial(int n){ const unsigned int M = 1000000007; unsigned long long f = 1; for (int i = 1; i <= n; i++) f = (f*i) % M; // Now f never can // exceed 10^9+7 return f;} // This code is contributed by Shubham Singh unsigned long long factorial(int n){ const unsigned int M = 1000000007; unsigned long long f = 1; for (int i = 1; i <= n; i++) f = (f*i) % M; // Now f never can // exceed 10^9+7 return f;} static long factorial(int n){ long M = 1000000007; long f = 1; for (int i = 1; i <= n; i++) f = (f*i) % M; // Now f never can // exceed 10^9+7 return f;} // This code is contributed by Dharanendra L V. def factorial( n) : M = 1000000007 f = 1 for i in range(1, n + 1): f = (f * i) % M # Now f never can # exceed 10^9+7 return f # This code is contributed by# Shubham Singh(SHUBHAMSINGH10) static long factorial(int n){ long M = 1000000007; long f = 1; for (int i = 1; i <= n; i++) f = (f*i) % M; // Now f never can // exceed 10^9+7 return f;} // This code is contributed by Dharanendra L V. function factorial( n){ let M = 1000000007; let f = 1; for (let i = 1; i <= n; i++) f = (f*i) % M; // Now f never can // exceed 10^9+7 return f;} The same procedure can be followed for addition. (a + b + c) % M is the same as ( ( ( a + b ) % M ) + c ) % M. Perform % M every time a number is added so as to avoid overflow. Note: In most of the programming languages (like in C/C++) when you perform the modular operation with negative numbers it gives a negative result like -5%3 = -2, but what the result comes after the modular operation should be in the range 0 to n-1 means the -5%3 = 1. So for this convert it into a positive modular equivalent. C++ C Java Python3 C# Javascript int mod(int a, int m){ return (a % m + m) % m;} // This code is contributed by// Shubham Singh(SHUBHAMSINGH10) int mod(int a, int m){ return (a%m + m) % m;} static int mod(int a, int m){ return (a%m + m) % m;}// This code is contributed by//Shubham Singh(SHUBHAMSINGH10) def mod(a, m): return (a%m + m) % m # This code is contributed by# Shubham Singh(SHUBHAMSINGH10) static int mod(int a, int m){ return (a % m + m) % m;} // This code is contributed by//Shubham Singh(SHUBHAMSINGH10) function mod( a, m){ return (a%m + m) % m;} But the rules are different for division. To perform division in modulo arithmetic, we need to first understand the concept of modulo multiplicative inverse. Modulo multiplicative Inverse(MMI): The multiplicative inverse of a number y is z if(z * y) == 1. Dividing a number x by another number y is the same as multiplying x with the multiplicative inverse of y. x / y == x * y^(-1) == x * z (where z is multiplicative inverse of y). In normal arithmetic, the multiplicative inverse of y is a float value. Ex: Multiplicative inverse of 7 is 0.142..., of 3 is 0.333... . In mathematics, the modular multiplicative inverse of an integer ‘a’ is an integer ‘x’ such that the product ax is congruent to 1 with respect to the modulus m. ax = 1( mod m) The remainder after dividing ax by the integer m is 1. Example: If M = 7, the MMI of 4 is 2 as (4 * 2) %7 == 1, If M = 11, the MMI of 7 is 8 as (7 * 8) % 11 == 1, If M = 13, the MMI of 7 is 2 as (7 * 2) % 13 == 1. Observe that the MMI of a number may be different for different M. So, if we are performing modulo arithmetic in our program and we need the result of the operation x / y, we should NOT perform z = (x/y) % M; instead, we should perform y_inv = findMMI(y, M); z = (x * y_inv) % M; Now one question remains.. How to find the MMI of a number n. There exist two algorithms to find MMI of a number. First is the Extended Euclidean algorithm and the second using Fermat’s Little Theorem. You can find both the methods in the given link: Modular multiplicative inverseFinding modular multiplicative inverses also has practical applications in the field of cryptography, i.e. public-key cryptography and the RSA Algorithm. A benefit for the computer implementation of these applications is that there exists a very fast algorithm (the extended Euclidean algorithm) that can be used for the calculation of modular multiplicative inverses.References: https://www.quora.com/What-exactly-is-print-it-modulo-10-9-+-7-in-competitive-programming-websites https://discuss.codechef.com/questions/4698/use-of-modulo-1000007-in-competitions https://codeaccepted.wordpress.com/2014/02/15/output-the-answer-modulo-109-7/This article is contributed by Akash 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 [email protected]. 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 zeto kristy6678 mitrukahitesh rutvik_56 pratham76 dharanendralv23 jana_sayantan navihere Modular Arithmetic number-theory Competitive Programming Mathematical number-theory Mathematical Modular Arithmetic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Practice for cracking any coding interview Arrow operator -> in C/C++ with Examples Prefix Sum Array - Implementation and Applications in Competitive Programming Top 10 Algorithms and Data Structures for Competitive Programming Bits manipulation (Important tactics) Program for Fibonacci numbers Set in C++ Standard Template Library (STL) Write a program to print all permutations of a given string C++ Data Types Merge two sorted arrays
[ { "code": null, "e": 54, "s": 26, "text": "\n23 Jun, 2022" }, { "code": null, "e": 577, "s": 54, "text": "In most programming competitions, we are required to answer the result in 10^9+7 modulo. The reason behind this is, if problem constraints are large integers, only efficient algorithms can solve them in an allowed limited time.What is modulo operation: The remainder obtained after the division operation on two operands is known as modulo operation. The operator for doing modulus operation is ‘%’. For ex: a % b = c which means, when a is divided by b it gives the remainder c, 7%2 = 1, 17%3 = 2.Why do we need modulo: " }, { "code": null, "e": 1211, "s": 577, "text": "The reason of taking Mod is to prevent integer overflows. The largest integer data type in C/C++ is unsigned long long int which is of 64 bit and can handle integer from 0 to (2^64 – 1). But in some problems where the growth rate of output is very high, this high range of unsigned long long may be insufficient. Suppose in a 64 bit variable ‘A’, 2^62 is stored and in another 64 bit variable ‘B’, 2^63 is stored. When we multiply A and B, the system does not give a runtime error or exception. It just does some bogus computation and stores the bogus result because the bit size of the result comes after multiplication overflows. " }, { "code": null, "e": 1439, "s": 1211, "text": "In some of the problems, to compute the result modulo inverse is needed and this number helps a lot because it is prime. Also, this number should be large enough otherwise modular inverse techniques may fail in some situations." }, { "code": null, "e": 1606, "s": 1439, "text": "Due to these reasons, problem setters require to give the answer as a result of modulo of some number N. There are certain criteria on which the value of N depends: " }, { "code": null, "e": 1975, "s": 1606, "text": "It should just be large enough to fit in the largest integer data type i.e it makes sure that there is no overflow in the result.It should be a prime number because if we take mod of a number by Prime the result is generally spaced i.e. the results are very different results in comparison to mod the number by non-prime, that is why primes are generally used for mod." }, { "code": null, "e": 2105, "s": 1975, "text": "It should just be large enough to fit in the largest integer data type i.e it makes sure that there is no overflow in the result." }, { "code": null, "e": 2345, "s": 2105, "text": "It should be a prime number because if we take mod of a number by Prime the result is generally spaced i.e. the results are very different results in comparison to mod the number by non-prime, that is why primes are generally used for mod." }, { "code": null, "e": 2624, "s": 2345, "text": "10^9+7 fulfills both the criteria. It is the first 10-digit prime number and fits in int data type as well. In fact, any prime number less than 2^30 will be fine in order to prevent possible overflows.How modulo is used: A few distributive properties of modulo are as follows: " }, { "code": null, "e": 2802, "s": 2624, "text": "( a + b) % c = ( ( a % c ) + ( b % c ) ) % c( a * b) % c = ( ( a % c ) * ( b % c ) ) % c( a – b) % c = ( ( a % c ) – ( b % c ) ) % c( a / b ) % c = ( ( a % c ) / ( b % c ) ) % c" }, { "code": null, "e": 2847, "s": 2802, "text": "( a + b) % c = ( ( a % c ) + ( b % c ) ) % c" }, { "code": null, "e": 2892, "s": 2847, "text": "( a * b) % c = ( ( a % c ) * ( b % c ) ) % c" }, { "code": null, "e": 2937, "s": 2892, "text": "( a – b) % c = ( ( a % c ) – ( b % c ) ) % c" }, { "code": null, "e": 2983, "s": 2937, "text": "( a / b ) % c = ( ( a % c ) / ( b % c ) ) % c" }, { "code": null, "e": 3300, "s": 2983, "text": "So, modulo is distributive over +, * and – but not over / [Please refer Modular Division for details]NOTE: The result of ( a % b ) will always be less than b.In the case of computer programs, due to the size of variable limitations, we perform modulo M at each intermediate stage so that range overflow never occurs." }, { "code": null, "e": 4008, "s": 3300, "text": "Example:\na = 145785635595363569532135132\nb = 3151635135413512165131321321\nc = 999874455222222200651351351\nm = 1000000007\nPrint (a*b*c)%m.\n\nMethod 1:\nFirst, multiply all the number and then take modulo:\n(a*b*c)%m = (459405448184212290893339835148809\n515332440033400818566717735644307024625348601572) % \n1000000007\na*b*c does not fit even in the unsigned long long \nint due to which system drop some of its most \nsignificant digits. Therefore, it gives the wrong answer.\n(a*b*c)%m = 798848767\n\nMethod 2:\nTake modulo at each intermediate steps:\ni = 1\ni = (i*a) % m // i = 508086243\ni = (i*b) % m // i = 144702857\ni = (i*c) % m // i = 798848767\ni = 798848767 \n\nMethod 2 always gives the correct answer." }, { "code": null, "e": 4100, "s": 4008, "text": "Function for finding factorial of a large number using modulo but at different positions. " }, { "code": null, "e": 4104, "s": 4100, "text": "C++" }, { "code": null, "e": 4106, "s": 4104, "text": "C" }, { "code": null, "e": 4111, "s": 4106, "text": "Java" }, { "code": null, "e": 4119, "s": 4111, "text": "Python3" }, { "code": null, "e": 4122, "s": 4119, "text": "C#" }, { "code": null, "e": 4133, "s": 4122, "text": "Javascript" }, { "code": "unsigned long long factorial(int n){ const unsigned int M = 1000000007; unsigned long long f = 1; for (int i = 1; i <= n; i++) f = f * i; // WRONG APPROACH as // f may exceed (2^64 - 1) return f % M;} // This code is contributed by Shubham Singh", "e": 4420, "s": 4133, "text": null }, { "code": "unsigned long long factorial(int n){ const unsigned int M = 1000000007; unsigned long long f = 1; for (int i = 1; i <= n; i++) f = f * i; // WRONG APPROACH as // f may exceed (2^64 - 1) return f % M;}", "e": 4662, "s": 4420, "text": null }, { "code": "static long factorial(int n){ const long M = 1000000007; long f = 1; for (int i = 1; i <= n; i++) f = f * i; // WRONG APPROACH as // f may exceed (2^64 - 1) return f % M;} // This code is contributed by rutvik_56.", "e": 4917, "s": 4662, "text": null }, { "code": "def factorial( n) : M = 1000000007 f = 1 for i in range(1, n + 1): f = f * i # WRONG APPROACH as # f may exceed (2^64 - 1) return f % M # This code is contributed by# Shubham Singh(SHUBHAMSINGH10)", "e": 5152, "s": 4917, "text": null }, { "code": "static long factorial(int n){ const long M = 1000000007; long f = 1; for (int i = 1; i <= n; i++) f = f * i; // WRONG APPROACH as // f may exceed (2^64 - 1) return f % M;} // This code is contributed by pratham76.", "e": 5407, "s": 5152, "text": null }, { "code": "function factorial( n){ let M = 1000000007; let f = 1; for (let i = 1; i <= n; i++) f = f * i; // WRONG APPROACH as // f may exceed (2^64 - 1) return f % M;} # This code is contributed by# Shubham Singh(SHUBHAMSINGH10)", "e": 5667, "s": 5407, "text": null }, { "code": null, "e": 5671, "s": 5667, "text": "C++" }, { "code": null, "e": 5673, "s": 5671, "text": "C" }, { "code": null, "e": 5678, "s": 5673, "text": "Java" }, { "code": null, "e": 5686, "s": 5678, "text": "Python3" }, { "code": null, "e": 5689, "s": 5686, "text": "C#" }, { "code": null, "e": 5700, "s": 5689, "text": "Javascript" }, { "code": "unsigned long long factorial(int n){ const unsigned int M = 1000000007; unsigned long long f = 1; for (int i = 1; i <= n; i++) f = (f*i) % M; // Now f never can // exceed 10^9+7 return f;} // This code is contributed by Shubham Singh", "e": 5978, "s": 5700, "text": null }, { "code": "unsigned long long factorial(int n){ const unsigned int M = 1000000007; unsigned long long f = 1; for (int i = 1; i <= n; i++) f = (f*i) % M; // Now f never can // exceed 10^9+7 return f;}", "e": 6211, "s": 5978, "text": null }, { "code": "static long factorial(int n){ long M = 1000000007; long f = 1; for (int i = 1; i <= n; i++) f = (f*i) % M; // Now f never can // exceed 10^9+7 return f;} // This code is contributed by Dharanendra L V.", "e": 6457, "s": 6211, "text": null }, { "code": "def factorial( n) : M = 1000000007 f = 1 for i in range(1, n + 1): f = (f * i) % M # Now f never can # exceed 10^9+7 return f # This code is contributed by# Shubham Singh(SHUBHAMSINGH10)", "e": 6688, "s": 6457, "text": null }, { "code": "static long factorial(int n){ long M = 1000000007; long f = 1; for (int i = 1; i <= n; i++) f = (f*i) % M; // Now f never can // exceed 10^9+7 return f;} // This code is contributed by Dharanendra L V.", "e": 6934, "s": 6688, "text": null }, { "code": "function factorial( n){ let M = 1000000007; let f = 1; for (let i = 1; i <= n; i++) f = (f*i) % M; // Now f never can // exceed 10^9+7 return f;}", "e": 7124, "s": 6934, "text": null }, { "code": null, "e": 7301, "s": 7124, "text": "The same procedure can be followed for addition. (a + b + c) % M is the same as ( ( ( a + b ) % M ) + c ) % M. Perform % M every time a number is added so as to avoid overflow." }, { "code": null, "e": 7631, "s": 7301, "text": "Note: In most of the programming languages (like in C/C++) when you perform the modular operation with negative numbers it gives a negative result like -5%3 = -2, but what the result comes after the modular operation should be in the range 0 to n-1 means the -5%3 = 1. So for this convert it into a positive modular equivalent. " }, { "code": null, "e": 7635, "s": 7631, "text": "C++" }, { "code": null, "e": 7637, "s": 7635, "text": "C" }, { "code": null, "e": 7642, "s": 7637, "text": "Java" }, { "code": null, "e": 7650, "s": 7642, "text": "Python3" }, { "code": null, "e": 7653, "s": 7650, "text": "C#" }, { "code": null, "e": 7664, "s": 7653, "text": "Javascript" }, { "code": "int mod(int a, int m){ return (a % m + m) % m;} // This code is contributed by// Shubham Singh(SHUBHAMSINGH10)", "e": 7778, "s": 7664, "text": null }, { "code": "int mod(int a, int m){ return (a%m + m) % m;}", "e": 7827, "s": 7778, "text": null }, { "code": "static int mod(int a, int m){ return (a%m + m) % m;}// This code is contributed by//Shubham Singh(SHUBHAMSINGH10)", "e": 7944, "s": 7827, "text": null }, { "code": "def mod(a, m): return (a%m + m) % m # This code is contributed by# Shubham Singh(SHUBHAMSINGH10)", "e": 8044, "s": 7944, "text": null }, { "code": "static int mod(int a, int m){ return (a % m + m) % m;} // This code is contributed by//Shubham Singh(SHUBHAMSINGH10)", "e": 8164, "s": 8044, "text": null }, { "code": "function mod( a, m){ return (a%m + m) % m;}", "e": 8211, "s": 8164, "text": null }, { "code": null, "e": 8369, "s": 8211, "text": "But the rules are different for division. To perform division in modulo arithmetic, we need to first understand the concept of modulo multiplicative inverse." }, { "code": null, "e": 9014, "s": 8369, "text": "Modulo multiplicative Inverse(MMI): The multiplicative inverse of a number y is z if(z * y) == 1. Dividing a number x by another number y is the same as multiplying x with the multiplicative inverse of y. x / y == x * y^(-1) == x * z (where z is multiplicative inverse of y). In normal arithmetic, the multiplicative inverse of y is a float value. Ex: Multiplicative inverse of 7 is 0.142..., of 3 is 0.333... . In mathematics, the modular multiplicative inverse of an integer ‘a’ is an integer ‘x’ such that the product ax is congruent to 1 with respect to the modulus m. ax = 1( mod m) The remainder after dividing ax by the integer m is 1. " }, { "code": null, "e": 9173, "s": 9014, "text": "Example:\nIf M = 7, the MMI of 4 is 2 as (4 * 2) %7 == 1,\nIf M = 11, the MMI of 7 is 8 as (7 * 8) % 11 == 1,\nIf M = 13, the MMI of 7 is 2 as (7 * 2) % 13 == 1." }, { "code": null, "e": 9369, "s": 9173, "text": "Observe that the MMI of a number may be different for different M. So, if we are performing modulo arithmetic in our program and we need the result of the operation x / y, we should NOT perform " }, { "code": null, "e": 9384, "s": 9369, "text": "z = (x/y) % M;" }, { "code": null, "e": 9413, "s": 9384, "text": "instead, we should perform " }, { "code": null, "e": 9457, "s": 9413, "text": "y_inv = findMMI(y, M);\nz = (x * y_inv) % M;" }, { "code": null, "e": 10796, "s": 9457, "text": "Now one question remains.. How to find the MMI of a number n. There exist two algorithms to find MMI of a number. First is the Extended Euclidean algorithm and the second using Fermat’s Little Theorem. You can find both the methods in the given link: Modular multiplicative inverseFinding modular multiplicative inverses also has practical applications in the field of cryptography, i.e. public-key cryptography and the RSA Algorithm. A benefit for the computer implementation of these applications is that there exists a very fast algorithm (the extended Euclidean algorithm) that can be used for the calculation of modular multiplicative inverses.References: https://www.quora.com/What-exactly-is-print-it-modulo-10-9-+-7-in-competitive-programming-websites https://discuss.codechef.com/questions/4698/use-of-modulo-1000007-in-competitions https://codeaccepted.wordpress.com/2014/02/15/output-the-answer-modulo-109-7/This article is contributed by Akash 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 [email protected]. 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": 10811, "s": 10796, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 10816, "s": 10811, "text": "zeto" }, { "code": null, "e": 10827, "s": 10816, "text": "kristy6678" }, { "code": null, "e": 10841, "s": 10827, "text": "mitrukahitesh" }, { "code": null, "e": 10851, "s": 10841, "text": "rutvik_56" }, { "code": null, "e": 10861, "s": 10851, "text": "pratham76" }, { "code": null, "e": 10877, "s": 10861, "text": "dharanendralv23" }, { "code": null, "e": 10891, "s": 10877, "text": "jana_sayantan" }, { "code": null, "e": 10900, "s": 10891, "text": "navihere" }, { "code": null, "e": 10919, "s": 10900, "text": "Modular Arithmetic" }, { "code": null, "e": 10933, "s": 10919, "text": "number-theory" }, { "code": null, "e": 10957, "s": 10933, "text": "Competitive Programming" }, { "code": null, "e": 10970, "s": 10957, "text": "Mathematical" }, { "code": null, "e": 10984, "s": 10970, "text": "number-theory" }, { "code": null, "e": 10997, "s": 10984, "text": "Mathematical" }, { "code": null, "e": 11016, "s": 10997, "text": "Modular Arithmetic" }, { "code": null, "e": 11114, "s": 11016, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 11157, "s": 11114, "text": "Practice for cracking any coding interview" }, { "code": null, "e": 11198, "s": 11157, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 11276, "s": 11198, "text": "Prefix Sum Array - Implementation and Applications in Competitive Programming" }, { "code": null, "e": 11342, "s": 11276, "text": "Top 10 Algorithms and Data Structures for Competitive Programming" }, { "code": null, "e": 11380, "s": 11342, "text": "Bits manipulation (Important tactics)" }, { "code": null, "e": 11410, "s": 11380, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 11453, "s": 11410, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 11513, "s": 11453, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 11528, "s": 11513, "text": "C++ Data Types" } ]
Length of longest subarray with positive product
16 Nov, 2021 Given an array arr[] consisting of N integers, the task is to print the length of the longest subarray with a positive product. Examples: Input: arr[] ={0, 1, -2, -3, -4}Output: 3Explanation:The longest subarray with positive products is: {1, -2, -3}. Therefore, the required length is 3. Input: arr[]={-1, -2, 0, 1, 2}Output: 2Explanation:The longest subarray with positive products are: {-1, -2}, {1, 2}. Therefore, the required length is 2. Naive Approach: The simplest approach to solve the problem is to generate all possible subarrays and check if its product is positive or not. Among all such subarrays, print the length of the longest subarray obtained.Time Complexity: (N3)Auxiliary Space: O(1)Efficient Approach: The problem can be solved using Dynamic Programming. The idea here is to maintain the count of positive elements and negative elements such that their product is positive. Follow the steps below to solve the problem: Initialize the variable, say res, to store the length of the longest subarray with the positive product.Initialize two variables, Pos and Neg, to store the length of the current subarray with the positive and negative products respectively.Iterate over the array.If arr[i] = 0: Reset the value of Pos and Neg.If arr[i] > 0: Increment Pos by 1. If at least one element is present in the subarray with the negative product, then increment Neg by 1.If arr[i] < 0: Swap Pos and Neg and increment the Neg by 1. If at least one element is present in the subarray with the positive product, then increment Pos also.Update res=max(res, Pos). Initialize the variable, say res, to store the length of the longest subarray with the positive product. Initialize two variables, Pos and Neg, to store the length of the current subarray with the positive and negative products respectively. Iterate over the array. If arr[i] = 0: Reset the value of Pos and Neg. If arr[i] > 0: Increment Pos by 1. If at least one element is present in the subarray with the negative product, then increment Neg by 1. If arr[i] < 0: Swap Pos and Neg and increment the Neg by 1. If at least one element is present in the subarray with the positive product, then increment Pos also. Update res=max(res, Pos). C++ Python3 Java C# Javascript // C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to find the length of// longest subarray whose product// is positiveint maxLenSub(int arr[], int N){ // Stores the length of current // subarray with positive product int Pos = 0; // Stores the length of current // subarray with negative product int Neg = 0; // Stores the length of the longest // subarray with positive product int res = 0; for (int i = 0; i < N; i++) { if (arr[i] == 0) { // Reset the value Pos = Neg = 0; } // If current element is positive else if (arr[i] > 0) { // Increment the length of // subarray with positive product Pos += 1; // If at least one element is // present in the subarray with // negative product if (Neg != 0) { Neg += 1; } // Update res res = max(res, Pos); } // If current element is negative else { swap(Pos, Neg); // Increment the length of subarray // with negative product Neg += 1; // If at least one element is present // in the subarray with positive product if (Pos != 0) { Pos += 1; } // Update res res = max(res, Pos); } } return res;} // Driver Codeint main(){ int arr[] = { -1, -2, -3, 0, 1 }; int N = sizeof(arr) / sizeof(arr[0]); cout << maxLenSub(arr, N);} # Python3 program to implement# the above approach # Function to find the length of# longest subarray whose product# is positivedef maxLenSub(arr, N): # Stores the length of current # subarray with positive product Pos = 0 # Stores the length of current # subarray with negative product Neg = 0 # Stores the length of the longest # subarray with positive product res = 0 for i in range(N): if (arr[i] == 0): # Reset the value Pos = Neg = 0 # If current element is positive elif (arr[i] > 0): # Increment the length of # subarray with positive product Pos += 1 # If at least one element is # present in the subarray with # negative product if (Neg != 0): Neg += 1 # Update res res = max(res, Pos) # If current element is negative else: Pos, Neg = Neg, Pos # Increment the length of subarray # with negative product Neg += 1 # If at least one element is present # in the subarray with positive product if (Pos != 0): Pos += 1 # Update res res = max(res, Pos) return res # Driver Codeif __name__ == '__main__': arr = [ -1, -2, -3, 0, 1 ] N = len(arr) print(maxLenSub(arr, N)) # This code is contributed by mohit kumar 29 // Java program to implement// the above approachimport java.util.*;class GFG{ // Function to find the length of// longest subarray whose product// is positivestatic int maxLenSub(int arr[], int N){ // Stores the length of current // subarray with positive product int Pos = 0; // Stores the length of current // subarray with negative product int Neg = 0; // Stores the length of the longest // subarray with positive product int res = 0; for (int i = 0; i < N; i++) { if (arr[i] == 0) { // Reset the value Pos = Neg = 0; } // If current element is positive else if (arr[i] > 0) { // Increment the length of // subarray with positive product Pos += 1; // If at least one element is // present in the subarray with // negative product if (Neg != 0) { Neg += 1; } // Update res res = Math.max(res, Pos); } // If current element is negative else { Pos = Pos + Neg; Neg = Pos - Neg; Pos = Pos - Neg; // Increment the length of subarray // with negative product Neg += 1; // If at least one element is present // in the subarray with positive product if (Pos != 0) { Pos += 1; } // Update res res = Math.max(res, Pos); } } return res;} // Driver Codepublic static void main(String[] args){ int arr[] = {-1, -2, -3, 0, 1}; int N = arr.length; System.out.print(maxLenSub(arr, N));}} // This code is contributed by Rajput-Ji // C# program to implement// the above approachusing System;class GFG{ // Function to find the length of// longest subarray whose product// is positivestatic int maxLenSub(int[] arr, int N){ // Stores the length of current // subarray with positive product int Pos = 0; // Stores the length of current // subarray with negative product int Neg = 0; // Stores the length of the longest // subarray with positive product int res = 0; for (int i = 0; i < N; i++) { if (arr[i] == 0) { // Reset the value Pos = Neg = 0; } // If current element is positive else if (arr[i] > 0) { // Increment the length of // subarray with positive product Pos += 1; // If at least one element is // present in the subarray with // negative product if (Neg != 0) { Neg += 1; } // Update res res = Math.Max(res, Pos); } // If current element is negative else { Pos = Pos + Neg; Neg = Pos - Neg; Pos = Pos - Neg; // Increment the length of subarray // with negative product Neg += 1; // If at least one element is present // in the subarray with positive product if (Pos != 0) { Pos += 1; } // Update res res = Math.Max(res, Pos); } } return res;} // Driver Codepublic static void Main(){ int[] arr = {-1, -2, -3, 0, 1}; int N = arr.Length; Console.Write(maxLenSub(arr, N));}} // This code is contributed by Chitranayal <script> // JavaScript program to implement// the above approach // Function to find the length of// longest subarray whose product// is positivefunction maxLenSub(arr, N){ // Stores the length of current // subarray with positive product var Pos = 0; // Stores the length of current // subarray with negative product var Neg = 0; // Stores the length of the longest // subarray with positive product var res = 0; for (var i = 0; i < N; i++) { if (arr[i] == 0) { // Reset the value Pos = Neg = 0; } // If current element is positive else if (arr[i] > 0) { // Increment the length of // subarray with positive product Pos += 1; // If at least one element is // present in the subarray with // negative product if (Neg != 0) { Neg += 1; } // Update res res = Math.max(res, Pos); } // If current element is negative else { [Pos, Neg] = [Neg, Pos]; // Increment the length of subarray // with negative product Neg += 1; // If at least one element is present // in the subarray with positive product if (Pos != 0) { Pos += 1; } // Update res res = Math.max(res, Pos); } } return res;} // Driver Codevar arr = [-1, -2, -3, 0, 1];var N = arr.length;document.write( maxLenSub(arr, N)); </script> 2 Time Complexity: O(N)Auxiliary Space: O(1) mohit kumar 29 Rajput-Ji ukasp noob2000 anmolsharma283 subarray Arrays Dynamic Programming Mathematical Searching Arrays Searching Dynamic Programming Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Data Structures Window Sliding Technique Search, insert and delete in an unsorted array Chocolate Distribution Problem What is Data Structure: Types, Classifications and Applications Program for Fibonacci numbers 0-1 Knapsack Problem | DP-10 Longest Common Subsequence | DP-4 Longest Palindromic Substring | Set 1 Longest Increasing Subsequence | DP-3
[ { "code": null, "e": 52, "s": 24, "text": "\n16 Nov, 2021" }, { "code": null, "e": 180, "s": 52, "text": "Given an array arr[] consisting of N integers, the task is to print the length of the longest subarray with a positive product." }, { "code": null, "e": 190, "s": 180, "text": "Examples:" }, { "code": null, "e": 341, "s": 190, "text": "Input: arr[] ={0, 1, -2, -3, -4}Output: 3Explanation:The longest subarray with positive products is: {1, -2, -3}. Therefore, the required length is 3." }, { "code": null, "e": 496, "s": 341, "text": "Input: arr[]={-1, -2, 0, 1, 2}Output: 2Explanation:The longest subarray with positive products are: {-1, -2}, {1, 2}. Therefore, the required length is 2." }, { "code": null, "e": 993, "s": 496, "text": "Naive Approach: The simplest approach to solve the problem is to generate all possible subarrays and check if its product is positive or not. Among all such subarrays, print the length of the longest subarray obtained.Time Complexity: (N3)Auxiliary Space: O(1)Efficient Approach: The problem can be solved using Dynamic Programming. The idea here is to maintain the count of positive elements and negative elements such that their product is positive. Follow the steps below to solve the problem:" }, { "code": null, "e": 1627, "s": 993, "text": "Initialize the variable, say res, to store the length of the longest subarray with the positive product.Initialize two variables, Pos and Neg, to store the length of the current subarray with the positive and negative products respectively.Iterate over the array.If arr[i] = 0: Reset the value of Pos and Neg.If arr[i] > 0: Increment Pos by 1. If at least one element is present in the subarray with the negative product, then increment Neg by 1.If arr[i] < 0: Swap Pos and Neg and increment the Neg by 1. If at least one element is present in the subarray with the positive product, then increment Pos also.Update res=max(res, Pos)." }, { "code": null, "e": 1732, "s": 1627, "text": "Initialize the variable, say res, to store the length of the longest subarray with the positive product." }, { "code": null, "e": 1869, "s": 1732, "text": "Initialize two variables, Pos and Neg, to store the length of the current subarray with the positive and negative products respectively." }, { "code": null, "e": 1893, "s": 1869, "text": "Iterate over the array." }, { "code": null, "e": 1940, "s": 1893, "text": "If arr[i] = 0: Reset the value of Pos and Neg." }, { "code": null, "e": 2078, "s": 1940, "text": "If arr[i] > 0: Increment Pos by 1. If at least one element is present in the subarray with the negative product, then increment Neg by 1." }, { "code": null, "e": 2241, "s": 2078, "text": "If arr[i] < 0: Swap Pos and Neg and increment the Neg by 1. If at least one element is present in the subarray with the positive product, then increment Pos also." }, { "code": null, "e": 2267, "s": 2241, "text": "Update res=max(res, Pos)." }, { "code": null, "e": 2271, "s": 2267, "text": "C++" }, { "code": null, "e": 2279, "s": 2271, "text": "Python3" }, { "code": null, "e": 2284, "s": 2279, "text": "Java" }, { "code": null, "e": 2287, "s": 2284, "text": "C#" }, { "code": null, "e": 2298, "s": 2287, "text": "Javascript" }, { "code": "// C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to find the length of// longest subarray whose product// is positiveint maxLenSub(int arr[], int N){ // Stores the length of current // subarray with positive product int Pos = 0; // Stores the length of current // subarray with negative product int Neg = 0; // Stores the length of the longest // subarray with positive product int res = 0; for (int i = 0; i < N; i++) { if (arr[i] == 0) { // Reset the value Pos = Neg = 0; } // If current element is positive else if (arr[i] > 0) { // Increment the length of // subarray with positive product Pos += 1; // If at least one element is // present in the subarray with // negative product if (Neg != 0) { Neg += 1; } // Update res res = max(res, Pos); } // If current element is negative else { swap(Pos, Neg); // Increment the length of subarray // with negative product Neg += 1; // If at least one element is present // in the subarray with positive product if (Pos != 0) { Pos += 1; } // Update res res = max(res, Pos); } } return res;} // Driver Codeint main(){ int arr[] = { -1, -2, -3, 0, 1 }; int N = sizeof(arr) / sizeof(arr[0]); cout << maxLenSub(arr, N);}", "e": 3908, "s": 2298, "text": null }, { "code": "# Python3 program to implement# the above approach # Function to find the length of# longest subarray whose product# is positivedef maxLenSub(arr, N): # Stores the length of current # subarray with positive product Pos = 0 # Stores the length of current # subarray with negative product Neg = 0 # Stores the length of the longest # subarray with positive product res = 0 for i in range(N): if (arr[i] == 0): # Reset the value Pos = Neg = 0 # If current element is positive elif (arr[i] > 0): # Increment the length of # subarray with positive product Pos += 1 # If at least one element is # present in the subarray with # negative product if (Neg != 0): Neg += 1 # Update res res = max(res, Pos) # If current element is negative else: Pos, Neg = Neg, Pos # Increment the length of subarray # with negative product Neg += 1 # If at least one element is present # in the subarray with positive product if (Pos != 0): Pos += 1 # Update res res = max(res, Pos) return res # Driver Codeif __name__ == '__main__': arr = [ -1, -2, -3, 0, 1 ] N = len(arr) print(maxLenSub(arr, N)) # This code is contributed by mohit kumar 29", "e": 5393, "s": 3908, "text": null }, { "code": "// Java program to implement// the above approachimport java.util.*;class GFG{ // Function to find the length of// longest subarray whose product// is positivestatic int maxLenSub(int arr[], int N){ // Stores the length of current // subarray with positive product int Pos = 0; // Stores the length of current // subarray with negative product int Neg = 0; // Stores the length of the longest // subarray with positive product int res = 0; for (int i = 0; i < N; i++) { if (arr[i] == 0) { // Reset the value Pos = Neg = 0; } // If current element is positive else if (arr[i] > 0) { // Increment the length of // subarray with positive product Pos += 1; // If at least one element is // present in the subarray with // negative product if (Neg != 0) { Neg += 1; } // Update res res = Math.max(res, Pos); } // If current element is negative else { Pos = Pos + Neg; Neg = Pos - Neg; Pos = Pos - Neg; // Increment the length of subarray // with negative product Neg += 1; // If at least one element is present // in the subarray with positive product if (Pos != 0) { Pos += 1; } // Update res res = Math.max(res, Pos); } } return res;} // Driver Codepublic static void main(String[] args){ int arr[] = {-1, -2, -3, 0, 1}; int N = arr.length; System.out.print(maxLenSub(arr, N));}} // This code is contributed by Rajput-Ji", "e": 7162, "s": 5393, "text": null }, { "code": "// C# program to implement// the above approachusing System;class GFG{ // Function to find the length of// longest subarray whose product// is positivestatic int maxLenSub(int[] arr, int N){ // Stores the length of current // subarray with positive product int Pos = 0; // Stores the length of current // subarray with negative product int Neg = 0; // Stores the length of the longest // subarray with positive product int res = 0; for (int i = 0; i < N; i++) { if (arr[i] == 0) { // Reset the value Pos = Neg = 0; } // If current element is positive else if (arr[i] > 0) { // Increment the length of // subarray with positive product Pos += 1; // If at least one element is // present in the subarray with // negative product if (Neg != 0) { Neg += 1; } // Update res res = Math.Max(res, Pos); } // If current element is negative else { Pos = Pos + Neg; Neg = Pos - Neg; Pos = Pos - Neg; // Increment the length of subarray // with negative product Neg += 1; // If at least one element is present // in the subarray with positive product if (Pos != 0) { Pos += 1; } // Update res res = Math.Max(res, Pos); } } return res;} // Driver Codepublic static void Main(){ int[] arr = {-1, -2, -3, 0, 1}; int N = arr.Length; Console.Write(maxLenSub(arr, N));}} // This code is contributed by Chitranayal", "e": 8909, "s": 7162, "text": null }, { "code": "<script> // JavaScript program to implement// the above approach // Function to find the length of// longest subarray whose product// is positivefunction maxLenSub(arr, N){ // Stores the length of current // subarray with positive product var Pos = 0; // Stores the length of current // subarray with negative product var Neg = 0; // Stores the length of the longest // subarray with positive product var res = 0; for (var i = 0; i < N; i++) { if (arr[i] == 0) { // Reset the value Pos = Neg = 0; } // If current element is positive else if (arr[i] > 0) { // Increment the length of // subarray with positive product Pos += 1; // If at least one element is // present in the subarray with // negative product if (Neg != 0) { Neg += 1; } // Update res res = Math.max(res, Pos); } // If current element is negative else { [Pos, Neg] = [Neg, Pos]; // Increment the length of subarray // with negative product Neg += 1; // If at least one element is present // in the subarray with positive product if (Pos != 0) { Pos += 1; } // Update res res = Math.max(res, Pos); } } return res;} // Driver Codevar arr = [-1, -2, -3, 0, 1];var N = arr.length;document.write( maxLenSub(arr, N)); </script>", "e": 10478, "s": 8909, "text": null }, { "code": null, "e": 10480, "s": 10478, "text": "2" }, { "code": null, "e": 10523, "s": 10480, "text": "Time Complexity: O(N)Auxiliary Space: O(1)" }, { "code": null, "e": 10538, "s": 10523, "text": "mohit kumar 29" }, { "code": null, "e": 10548, "s": 10538, "text": "Rajput-Ji" }, { "code": null, "e": 10554, "s": 10548, "text": "ukasp" }, { "code": null, "e": 10563, "s": 10554, "text": "noob2000" }, { "code": null, "e": 10578, "s": 10563, "text": "anmolsharma283" }, { "code": null, "e": 10587, "s": 10578, "text": "subarray" }, { "code": null, "e": 10594, "s": 10587, "text": "Arrays" }, { "code": null, "e": 10614, "s": 10594, "text": "Dynamic Programming" }, { "code": null, "e": 10627, "s": 10614, "text": "Mathematical" }, { "code": null, "e": 10637, "s": 10627, "text": "Searching" }, { "code": null, "e": 10644, "s": 10637, "text": "Arrays" }, { "code": null, "e": 10654, "s": 10644, "text": "Searching" }, { "code": null, "e": 10674, "s": 10654, "text": "Dynamic Programming" }, { "code": null, "e": 10687, "s": 10674, "text": "Mathematical" }, { "code": null, "e": 10785, "s": 10687, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 10817, "s": 10785, "text": "Introduction to Data Structures" }, { "code": null, "e": 10842, "s": 10817, "text": "Window Sliding Technique" }, { "code": null, "e": 10889, "s": 10842, "text": "Search, insert and delete in an unsorted array" }, { "code": null, "e": 10920, "s": 10889, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 10984, "s": 10920, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 11014, "s": 10984, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 11043, "s": 11014, "text": "0-1 Knapsack Problem | DP-10" }, { "code": null, "e": 11077, "s": 11043, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 11115, "s": 11077, "text": "Longest Palindromic Substring | Set 1" } ]
Reverse array elements in Julia – reverse(), reverse!() and reverseind() Methods
01 Apr, 2020 The reverse() is an inbuilt function in julia which is used to reverse the specified vector v from start to stop. Syntax:reverse(v, start, stop)orreverse(A; dims::Integer) Parameters: v: Specified vector. start: Specified starting value. stop: Specified stopping value. A: Specified array. dims::Integer: Specified dimensions. Returns: It returns a reversed copy of the vector. Example 1: # Julia program to illustrate # the use of reverse() method # Getting the reversed copy of # the specified vector.A = Vector(2:8)println(reverse(A))println(reverse(A, 3, 6))println(reverse(A, 7, 4)) Output: [8, 7, 6, 5, 4, 3, 2] [2, 3, 7, 6, 5, 4, 8] [2, 3, 4, 5, 6, 7, 8] Example 2: # Julia program to illustrate # the use of reverse() method # Getting reversed array in # the specified dimensionA = [5 10; 15 20]println(reverse(A, dims = 1))println(reverse(A, dims = 2)) Output: The reverse!() is an inbuilt function in julia which is In-place version of reverse() function. Syntax:reverse!(v, start, stop) Parameters: v: Specified vector. start: Specified starting value. stop: Specified stopping value. Returns: It returns a reversed copy of the vector. Example: # Julia program to illustrate # the use of reverse !() method # Getting the reversed copy of # the specified vector.A = Vector(2:8)println(reverse !(A))println(reverse !(A, 3, 6)) Output: [8, 7, 6, 5, 4, 3, 2] [8, 7, 3, 4, 5, 6, 2] The reverseind() is an inbuilt function in julia which is used to return the corresponding index in v so that v[reverseind(v, i)] == reverse(v)[i], where i is the given index. Syntax:reverseind(v, i) Parameters: v: Specified string. i: Specified index. Returns: It returns the corresponding index in v so that v[reverseind(v, i)] == reverse(v)[i]. Example: # Julia program to illustrate # the use of reverseind() method # Getting the corresponding index in v# so that v[reverseind(v, i)] == reverse(v)[i]V = reverse("Geeks")for i in 1:length(r) print(V[reverseind("Geeks", i)])end Output: Julia Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Apr, 2020" }, { "code": null, "e": 142, "s": 28, "text": "The reverse() is an inbuilt function in julia which is used to reverse the specified vector v from start to stop." }, { "code": null, "e": 200, "s": 142, "text": "Syntax:reverse(v, start, stop)orreverse(A; dims::Integer)" }, { "code": null, "e": 212, "s": 200, "text": "Parameters:" }, { "code": null, "e": 233, "s": 212, "text": "v: Specified vector." }, { "code": null, "e": 266, "s": 233, "text": "start: Specified starting value." }, { "code": null, "e": 298, "s": 266, "text": "stop: Specified stopping value." }, { "code": null, "e": 318, "s": 298, "text": "A: Specified array." }, { "code": null, "e": 355, "s": 318, "text": "dims::Integer: Specified dimensions." }, { "code": null, "e": 406, "s": 355, "text": "Returns: It returns a reversed copy of the vector." }, { "code": null, "e": 417, "s": 406, "text": "Example 1:" }, { "code": "# Julia program to illustrate # the use of reverse() method # Getting the reversed copy of # the specified vector.A = Vector(2:8)println(reverse(A))println(reverse(A, 3, 6))println(reverse(A, 7, 4))", "e": 618, "s": 417, "text": null }, { "code": null, "e": 626, "s": 618, "text": "Output:" }, { "code": null, "e": 692, "s": 626, "text": "[8, 7, 6, 5, 4, 3, 2]\n[2, 3, 7, 6, 5, 4, 8]\n[2, 3, 4, 5, 6, 7, 8]" }, { "code": null, "e": 703, "s": 692, "text": "Example 2:" }, { "code": "# Julia program to illustrate # the use of reverse() method # Getting reversed array in # the specified dimensionA = [5 10; 15 20]println(reverse(A, dims = 1))println(reverse(A, dims = 2))", "e": 894, "s": 703, "text": null }, { "code": null, "e": 902, "s": 894, "text": "Output:" }, { "code": null, "e": 998, "s": 902, "text": "The reverse!() is an inbuilt function in julia which is In-place version of reverse() function." }, { "code": null, "e": 1030, "s": 998, "text": "Syntax:reverse!(v, start, stop)" }, { "code": null, "e": 1042, "s": 1030, "text": "Parameters:" }, { "code": null, "e": 1063, "s": 1042, "text": "v: Specified vector." }, { "code": null, "e": 1096, "s": 1063, "text": "start: Specified starting value." }, { "code": null, "e": 1128, "s": 1096, "text": "stop: Specified stopping value." }, { "code": null, "e": 1179, "s": 1128, "text": "Returns: It returns a reversed copy of the vector." }, { "code": null, "e": 1188, "s": 1179, "text": "Example:" }, { "code": "# Julia program to illustrate # the use of reverse !() method # Getting the reversed copy of # the specified vector.A = Vector(2:8)println(reverse !(A))println(reverse !(A, 3, 6))", "e": 1370, "s": 1188, "text": null }, { "code": null, "e": 1378, "s": 1370, "text": "Output:" }, { "code": null, "e": 1423, "s": 1378, "text": "[8, 7, 6, 5, 4, 3, 2]\n[8, 7, 3, 4, 5, 6, 2]\n" }, { "code": null, "e": 1599, "s": 1423, "text": "The reverseind() is an inbuilt function in julia which is used to return the corresponding index in v so that v[reverseind(v, i)] == reverse(v)[i], where i is the given index." }, { "code": null, "e": 1623, "s": 1599, "text": "Syntax:reverseind(v, i)" }, { "code": null, "e": 1635, "s": 1623, "text": "Parameters:" }, { "code": null, "e": 1656, "s": 1635, "text": "v: Specified string." }, { "code": null, "e": 1676, "s": 1656, "text": "i: Specified index." }, { "code": null, "e": 1771, "s": 1676, "text": "Returns: It returns the corresponding index in v so that v[reverseind(v, i)] == reverse(v)[i]." }, { "code": null, "e": 1780, "s": 1771, "text": "Example:" }, { "code": "# Julia program to illustrate # the use of reverseind() method # Getting the corresponding index in v# so that v[reverseind(v, i)] == reverse(v)[i]V = reverse(\"Geeks\")for i in 1:length(r) print(V[reverseind(\"Geeks\", i)])end", "e": 2009, "s": 1780, "text": null }, { "code": null, "e": 2017, "s": 2009, "text": "Output:" }, { "code": null, "e": 2023, "s": 2017, "text": "Julia" } ]
Implementation of ls | wc command
30 Apr, 2018 ls | wc command : Using ls|wc, we can count new lines, words and letters of all files of current directory. We can see from the following after execution of the code we get same results. Prerequisites :ls command | wc command | piping in linux Approach : First, we have to use pipe for inter process communication over an array where a[0] is used for reading and a[1] is used for writing. We can replicate the process using fork. In the parent process, standard output is closed so that output of ls command will go to a[0] and similarly standard input is closed in children process. Now, if we run the program output will be as same as command of linux ls|wc. Below is the implementation of above approach : // C code to implement ls | wc command#include <stdio.h>#include <stdlib.h>#include <fcntl.h>#include<errno.h>#include<sys/wait.h>#include <unistd.h>int main(){ // array of 2 size a[0] is for // reading and a[1] is for // writing over a pipe int a[2]; // using pipe for inter // process communication pipe(a); if(!fork()) { // closing normal stdout close(1); // making stdout same as a[1] dup(a[1]); // closing reading part of pipe // we don't need of it at this time close(a[0]); // executing ls execlp("ls","ls",NULL); } else { // closing normal stdin close(0); // making stdin same as a[0] dup(a[0]); // closing writing part in parent, // we don't need of it at this time close(a[1]); // executing wc execlp("wc","wc",NULL); }} linux-command Linux-Unix Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. nohup Command in Linux with Examples 'dd' command in Linux How to Find Out File Types in Linux Start/Stop/Restart Services Using Systemctl in Linux mv command in Linux with examples bc command in Linux with examples du command in Linux with examples uniq Command in LINUX with examples vi Editor in UNIX Multi-Line Comment in Shell Script
[ { "code": null, "e": 54, "s": 26, "text": "\n30 Apr, 2018" }, { "code": null, "e": 241, "s": 54, "text": "ls | wc command : Using ls|wc, we can count new lines, words and letters of all files of current directory. We can see from the following after execution of the code we get same results." }, { "code": null, "e": 298, "s": 241, "text": "Prerequisites :ls command | wc command | piping in linux" }, { "code": null, "e": 715, "s": 298, "text": "Approach : First, we have to use pipe for inter process communication over an array where a[0] is used for reading and a[1] is used for writing. We can replicate the process using fork. In the parent process, standard output is closed so that output of ls command will go to a[0] and similarly standard input is closed in children process. Now, if we run the program output will be as same as command of linux ls|wc." }, { "code": null, "e": 763, "s": 715, "text": "Below is the implementation of above approach :" }, { "code": "// C code to implement ls | wc command#include <stdio.h>#include <stdlib.h>#include <fcntl.h>#include<errno.h>#include<sys/wait.h>#include <unistd.h>int main(){ // array of 2 size a[0] is for // reading and a[1] is for // writing over a pipe int a[2]; // using pipe for inter // process communication pipe(a); if(!fork()) { // closing normal stdout close(1); // making stdout same as a[1] dup(a[1]); // closing reading part of pipe // we don't need of it at this time close(a[0]); // executing ls execlp(\"ls\",\"ls\",NULL); } else { // closing normal stdin close(0); // making stdin same as a[0] dup(a[0]); // closing writing part in parent, // we don't need of it at this time close(a[1]); // executing wc execlp(\"wc\",\"wc\",NULL); }}", "e": 1730, "s": 763, "text": null }, { "code": null, "e": 1744, "s": 1730, "text": "linux-command" }, { "code": null, "e": 1755, "s": 1744, "text": "Linux-Unix" }, { "code": null, "e": 1774, "s": 1755, "text": "Technical Scripter" }, { "code": null, "e": 1872, "s": 1774, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1909, "s": 1872, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 1931, "s": 1909, "text": "'dd' command in Linux" }, { "code": null, "e": 1967, "s": 1931, "text": "How to Find Out File Types in Linux" }, { "code": null, "e": 2020, "s": 1967, "text": "Start/Stop/Restart Services Using Systemctl in Linux" }, { "code": null, "e": 2054, "s": 2020, "text": "mv command in Linux with examples" }, { "code": null, "e": 2088, "s": 2054, "text": "bc command in Linux with examples" }, { "code": null, "e": 2122, "s": 2088, "text": "du command in Linux with examples" }, { "code": null, "e": 2158, "s": 2122, "text": "uniq Command in LINUX with examples" }, { "code": null, "e": 2176, "s": 2158, "text": "vi Editor in UNIX" } ]
Reverse words in a given string
29 Jun, 2022 Let the input string be “i like this program very much”. The function should change the string to “much very program this like i” Examples: Input: s = “geeks quiz practice code” Output: s = “code practice quiz geeks” Input: s = “getting good at coding needs a lot of practice” Output: s = “practice of lot a needs coding at good getting” Algorithm: Initially, reverse the individual words of the given string one by one, for the above example, after reversing individual words the string should be “i ekil siht margorp yrev hcum”. Reverse the whole string from start to end to get the desired output “much very program this like i” in the above example. Below is the implementation of the above approach: C++ C Java Python3 C# Javascript // C++ program to reverse a string#include <bits/stdc++.h>using namespace std; // Function to reverse words*/void reverseWords(string s){ // temporary vector to store all words vector<string> tmp; string str = ""; for (int i = 0; i < s.length(); i++) { // Check if we encounter space // push word(str) to vector // and make str NULL if (s[i] == ' ') { tmp.push_back(str); str = ""; } // Else add character to // str to form current word else str += s[i]; } // Last word remaining,add it to vector tmp.push_back(str); // Now print from last to first in vector int i; for (i = tmp.size() - 1; i > 0; i--) cout << tmp[i] << " "; // Last word remaining,print it cout << tmp[0] << endl;} // Driver Codeint main(){ string s = "i like this program very much"; reverseWords(s); return 0;} // C program to reverse a string#include <stdio.h> // Function to reverse any sequence// starting with pointer begin and// ending with pointer endvoid reverse(char* begin, char* end){ char temp; while (begin < end) { temp = *begin; *begin++ = *end; *end-- = temp; }} // Function to reverse words*/void reverseWords(char* s){ char* word_begin = s; // Word boundary char* temp = s; // Reversing individual words as // explained in the first step while (*temp) { temp++; if (*temp == '\0') { reverse(word_begin, temp - 1); } else if (*temp == ' ') { reverse(word_begin, temp - 1); word_begin = temp + 1; } } // Reverse the entire string reverse(s, temp - 1);} // Driver Codeint main(){ char s[] = "i like this program very much"; char* temp = s; reverseWords(s); printf("%s", s); return 0;} // Java program to// reverse a Stringimport java.util.*;class GFG{ // Reverse the letters// of the wordstatic void reverse(char str[], int start, int end){ // Temporary variable // to store character char temp; while (start <= end) { // Swapping the first // and last character temp = str[start]; str[start] = str[end]; str[end] = temp; start++; end--; }}// Function to reverse wordsstatic char[] reverseWords(char []s){ // Reversing individual words as // explained in the first step int start = 0; for (int end = 0; end < s.length; end++) { // If we see a space, we // reverse the previous // word (word between // the indexes start and end-1 // i.e., s[start..end-1] if (s[end] == ' ') { reverse(s, start, end); start = end + 1; } } // Reverse the last word reverse(s, start, s.length - 1); // Reverse the entire String reverse(s, 0, s.length - 1); return s;} // Driver Codepublic static void main(String[] args){ String s = "i like this program very much "; char []p = reverseWords(s.toCharArray()); System.out.print(p);}} // This code is contributed by gauravrajput1 # Python3 program to reverse a string # Function to reverse each word in the stringdef reverse_word(s, start, end): while start < end: s[start], s[end] = s[end], s[start] start = start + 1 end -= 1 s = "i like this program very much" # Convert string to list to use it as a char arrays = list(s)start = 0while True: # We use a try catch block because for # the last word the list.index() function # returns a ValueError as it cannot find # a space in the list try: # Find the next space end = s.index(' ', start) # Call reverse_word function # to reverse each word reverse_word(s, start, end - 1) #Update start variable start = end + 1 except ValueError: # Reverse the last word reverse_word(s, start, len(s) - 1) break # Reverse the entire lists.reverse() # Convert the list back to# string using string.join() functions = "".join(s) print(s) # Solution contributed by Prem Nagdeo // C# program to// reverse a Stringusing System; class GFG{ // Reverse the letters// of the wordstatic void reverse(char []str, int start, int end){ // Temporary variable // to store character char temp; while (start <= end) { // Swapping the first // and last character temp = str[start]; str[start] = str[end]; str[end] = temp; start++; end--; }} // Function to reverse wordsstatic char[] reverseWords(char []s){ // Reversing individual words as // explained in the first step int start = 0; for (int end = 0; end < s.Length; end++) { // If we see a space, we // reverse the previous // word (word between // the indexes start and end-1 // i.e., s[start..end-1] if (s[end] == ' ') { reverse(s, start, end); start = end + 1; } } // Reverse the last word reverse(s, start, s.Length - 1); // Reverse the entire String reverse(s, 0, s.Length - 1); return s;} // Driver Codepublic static void Main(String[] args){ String s = "i like this program very much "; char []p = reverseWords(s.ToCharArray()); Console.Write(p);}} // This code is contributed by jana_sayantan <script> // Javascript program to // reverse a String // Reverse the letters // of the word function reverse(str,start,end) { // Temporary variable // to store character let temp; while (start <= end) { // Swapping the first // and last character temp = str[start]; str[start]=str[end]; str[end]=temp; start++; end--; } } // Function to reverse words function reverseWords(s) { // Reversing individual words as // explained in the first step s=s.split(""); let start = 0; for (let end = 0; end < s.length; end++) { // If we see a space, we // reverse the previous // word (word between // the indexes start and end-1 // i.e., s[start..end-1] if (s[end] == ' ') { reverse(s, start, end); start = end + 1; } } // Reverse the last word reverse(s, start, s.length - 1); // Reverse the entire String reverse(s, 0, s.length - 1); return s.join(""); } // Driver Code var s = "i like this program very much "; document.write(reverseWords(s)); // This code is contributed by avanitrachhadiya2155</script> much very program this like i Time complexity: O(n), Auxiliary Space: O(n) The above code doesn’t handle the cases when the string starts with space. The following version handles this specific case and doesn’t make unnecessary calls to reverse function in the case of multiple spaces in between. Thanks to rka143 for providing this version. C++ C // C++ program for above approach:void reverseWords(char* s){ char* word_begin = NULL; // /* temp is for word boundary */ char* temp = s; /*STEP 1 of the above algorithm */ while (*temp) { /*This condition is to make sure that the string start with valid character (not space) only*/ if ((word_begin == NULL) && (*temp != ' ')) { word_begin = temp; } if (word_begin && ((*(temp + 1) == ' ') || (*(temp + 1) == '\0'))) { reverse(word_begin, temp); word_begin = NULL; } temp++; } /* End of while */ /*STEP 2 of the above algorithm */ reverse(s, temp - 1);} // This code is contributed by rutvik_56. // C program for above approach void reverseWords(char* s){ char* word_begin = NULL; // /* temp is for word boundary */ char* temp = s; /*STEP 1 of the above algorithm */ while (*temp) { /*This condition is to make sure that the string start with valid character (not space) only*/ if ((word_begin == NULL) && (*temp != ' ')) { word_begin = temp; } if (word_begin && ((*(temp + 1) == ' ') || (*(temp + 1) == '\0'))) { reverse(word_begin, temp); word_begin = NULL; } temp++; } /* End of while */ /*STEP 2 of the above algorithm */ reverse(s, temp - 1);} Time Complexity: O(n), Auxiliary Space: O(n) as we’re storing string in the new variable. We can do the above task by splitting and saving the string in a reverse manner. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to reverse a string// s = input() #include <bits/stdc++.h>using namespace std; int main(){ string s[] = { "i", "like", "this", "program", "very", "much" }; string ans = ""; for (int i = 5; i >= 0; i--) { ans += s[i] + " "; } cout << ("Reversed String:") << endl; cout << (ans.substr(0, ans.length() - 1)) << endl; return 0;} // Java program to reverse a string// s = input()public class ReverseWords{ public static void main(String[] args) { String s[] = "i like this program very much". split(" "); String ans = ""; for (int i = s.length - 1; i >= 0; i--) { ans += s[i] + " "; } System.out.println("Reversed String:"); System.out.println(ans.substring(0, ans.length() - 1)); }} # Python3 program to reverse a string# s = input()s = "i like this program very much"words = s.split(' ')string =[]for word in words: string.insert(0, word) print("Reversed String:")print(" ".join(string)) # Solution proposed bu Uttam // C# program to reverse a string// s = input() using System;public class ReverseWords{ public static void Main() { string[] s = "i like this program very much". Split(' '); string ans = ""; for (int i = s.Length - 1; i >= 0; i--) { ans += s[i] + " "; } Console.Write("Reversed String:\n"); Console.Write(ans.Substring(0, ans.Length - 1)); }} <script> // JavaScript program to reverse a string var s= ["i", "like", "this", "program", "very", "much"]; var ans =""; for (var i = 5; i >= 0; i--) { ans += s[i] + " "; } document.write("Reversed String:"+ "<br>"); document.write(ans.slice(0,ans.length-1)); </script> Reversed String: much very program this like i Time Complexity: O(n), Auxiliary Space: O(n) as we’re storing string in the new variable. The above task can also be accomplished by splitting and directly swapping the string starting from the middle. As direct swapping is involved, less space is consumed too. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ code to reverse a string #include <bits/stdc++.h>using namespace std; // Reverse the stringstring RevString(string s[], int l){ // Check if number of words is even if (l % 2 == 0) { // Find the middle word int j = l / 2; // Starting from the middle // start swapping words at // jth position and l-1-j position while (j <= l - 1) { string temp; temp = s[l - j - 1]; s[l - j - 1] = s[j]; s[j] = temp; j += 1; } } // Check if number of words is odd else { // Find the middle word int j = (l / 2) + 1; // Starting from the middle start // swapping the words at jth // position and l-1-j position while (j <= l - 1) { string temp; temp = s[l - j - 1]; s[l - j - 1] = s[j]; s[j] = temp; j += 1; } } string S = s[0]; // Return the reversed sentence for (int i = 1; i < 9; i++) { S = S + " " + s[i]; } return S;} // Driver codeint main(){ string s = "getting good at coding " "needs a lot of practice"; string words[] = { "getting", "good", "at", "coding", "needs", "a", "lot", "of", "practice" }; cout << RevString(words, 9) << endl; return 0;} // Java code to reverse a stringclass GFG{ // Reverse the stringpublic static String[] RevString(String[] s, int l){ // Check if number of words is even if (l % 2 == 0) { // Find the middle word int j = l / 2; // Starting from the middle // start swapping words at // jth position and l-1-j position while (j <= l - 1) { String temp; temp = s[l - j - 1]; s[l - j - 1] = s[j]; s[j] = temp; j += 1; } } // Check if number of words is odd else { // Find the middle word int j = (l / 2) + 1; // Starting from the middle start // swapping the words at jth // position and l-1-j position while (j <= l - 1) { String temp; temp = s[l - j - 1]; s[l - j - 1] = s[j]; s[j] = temp; j += 1; } } // Return the reversed sentence return s;} // Driver Codepublic static void main(String[] args){ String s = "getting good at coding " + "needs a lot of practice"; String[] words = s.split("\\s"); words = RevString(words, words.length); s = String.join(" ", words); System.out.println(s);}} // This code is contributed by MuskanKalra1 # Python3 code to reverse a string # Reverse the stringdef RevString(s,l): # Check if number of words is even if l%2 == 0: # Find the middle word j = int(l/2) # Starting from the middle # start swapping words # at jth position and l-1-j position while(j <= l - 1): s[j], s[l - j - 1] = s[l - j - 1], s[j] j += 1 # Check if number of words is odd else: # Find the middle word j = int(l/2 + 1) # Starting from the middle # start swapping the words # at jth position and l-1-j position while(j <= l - 1): s[j], s[l - 1 - j] = s[l - j - 1], s[j] j += 1 # return the reversed sentence return s; # Driver Codes = 'getting good at coding needs a lot of practice'string = s.split(' ')string = RevString(string,len(string))print(" ".join(string)) // C# code to reverse a stringusing System;class GFG{ // Reverse the stringstatic string RevString(string[] s, int l){ // Check if number of words is even if (l % 2 == 0) { // Find the middle word int j = l / 2; // Starting from the middle // start swapping words at // jth position and l-1-j position while (j <= l - 1) { string temp; temp = s[l - j - 1]; s[l - j - 1] = s[j]; s[j] = temp; j += 1; } } // Check if number of words is odd else { // Find the middle word int j = (l / 2) + 1; // Starting from the middle start // swapping the words at jth // position and l-1-j position while (j <= l - 1) { string temp; temp = s[l - j - 1]; s[l - j - 1] = s[j]; s[j] = temp; j += 1; } } string S = s[0]; // Return the reversed sentence for (int i = 1; i < 9; i++) { S = S + " " + s[i]; } return S;} // Driver Codepublic static void Main(){ string []words = { "getting", "good", "at", "coding", "needs", "a", "lot", "of", "practice" }; string a = RevString(words, words.Length); Console.WriteLine(a);}} // This code is contributed by Aarti_Rathi and shivanisinghss2110 <script> // Javascript code to reverse a string // Reverse the stringfunction RevString(s, l){ // Check if number of words is even if (l % 2 == 0) { // Find the middle word let j = parseInt(l / 2, 10); // Starting from the middle // start swapping words at // jth position and l-1-j position while (j <= l - 1) { let temp; temp = s[l - j - 1]; s[l - j - 1] = s[j]; s[j] = temp; j += 1; } } // Check if number of words is odd else { // Find the middle word let j = parseInt((l / 2), 10) + 1; // Starting from the middle start // swapping the words at jth // position and l-1-j position while (j <= l - 1) { let temp; temp = s[l - j - 1]; s[l - j - 1] = s[j]; s[j] = temp; j += 1; } } let S = s[0]; // Return the reversed sentence for(let i = 1; i < 9; i++) { S = S + " " + s[i]; } return S;} // Driver codelet s = "getting good at coding " "needs a lot of practice"; let words = [ "getting", "good", "at", "coding", "needs", "a", "lot", "of", "practice"]; document.write(RevString(words, 9)); // This code is contributed by suresh07 </script> practice of lot a needs coding at good getting Time complexity: O(n), Auxiliary Space: O(n) Go through the string and mirror each word in the string, then, in the end, mirror the whole string. The following C++ code can handle multiple contiguous spaces. C++ Java #include <algorithm>#include <iostream>#include <string> using namespace std; string reverse_words(string s){ int left = 0, i = 0, n = s.size(); while (s[i] == ' ') i++; left = i; while (i < n) { if (i + 1 == n || s[i] == ' ') { int j = i - 1; if (i + 1 == n) j++; while (left < j) swap(s[left++], s[j--]); left = i + 1; } if (i > left && s[left] == ' ') left = i; i++; } reverse(s.begin(), s.end()); return s;} int main(){ string str = "Be a game changer the world is already " "full of players"; str = reverse_words(str); cout << str; return 0;} /*package whatever //do not write package name here */ import java.io.*; class GFG { // Java does not have built-in swap function to swap // characters of a string public static String swap(String str, int i, int j) { char ch[] = str.toCharArray(); char temp = ch[i]; ch[i] = ch[j]; ch[j] = temp; return new String(ch); } public static String reverse_words(String s) { int left = 0, i = 0, n = s.length(); while (s.charAt(i) == ' ') i++; left = i; while (i < n) { if (i + 1 == n || s.charAt(i) == ' ') { int j = i - 1; if (i + 1 == n) j++; while (left < j) s = swap(s, left++, j--); left = i + 1; } if (i > left && s.charAt(left) == ' ') left = i; i++; } // Use StringBuilder ".reverse()" method to reverse // the whole string. s = new StringBuilder(s).reverse().toString(); return s; } // Driver Code public static void main(String[] args) { String str = "Be a game changer the world is already full of players"; str = reverse_words(str); System.out.println(str); }}//This code is contributed by KaaL-EL. players of full already is world the changer game a Be Method: Using slicing method and join functions. Python3 # python code to reverse words in a given string # input stringstring = "getting good at coding needs a lot of practice"# spliting words in the given string# using slicing reverse the wordss = string.split()[::-1]# joining the reversed string and# printing the outputprint(" ".join(s)) practice of lot a needs coding at good getting Time complexity: O(n2), Auxiliary Space: O(n) Please write comments if you find any bug in the above code/algorithm, or find other ways to solve the same problem. Uttamk94 Deepak Kumar Agarwal ukasp Akanksha_Rai premnagdeo utsav akarshan GauravRajput1 pratyushpraveen MuskanKalra1 jana_sayantan shivanisinghss2110 rutvik_56 divyeshrabadiya07 divyesh072019 avanitrachhadiya2155 suresh07 akshitsaxenaa09 davidgatea21 chandramauliguptach kaalel laxmigangarajula03 sachinvinod1904 Accolite Adobe Amazon CBSE - Class 11 Cisco Goldman Sachs MakeMyTrip MAQ Software Microsoft Morgan Stanley Paytm Payu Reverse SAP Labs school-programming Wipro Zoho Strings Paytm Zoho Morgan Stanley Accolite Amazon Microsoft MakeMyTrip Payu Goldman Sachs MAQ Software Adobe Wipro SAP Labs Cisco Strings Reverse Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n29 Jun, 2022" }, { "code": null, "e": 184, "s": 54, "text": "Let the input string be “i like this program very much”. The function should change the string to “much very program this like i”" }, { "code": null, "e": 195, "s": 184, "text": "Examples: " }, { "code": null, "e": 272, "s": 195, "text": "Input: s = “geeks quiz practice code” Output: s = “code practice quiz geeks”" }, { "code": null, "e": 394, "s": 272, "text": "Input: s = “getting good at coding needs a lot of practice” Output: s = “practice of lot a needs coding at good getting” " }, { "code": null, "e": 407, "s": 394, "text": "Algorithm: " }, { "code": null, "e": 589, "s": 407, "text": "Initially, reverse the individual words of the given string one by one, for the above example, after reversing individual words the string should be “i ekil siht margorp yrev hcum”." }, { "code": null, "e": 712, "s": 589, "text": "Reverse the whole string from start to end to get the desired output “much very program this like i” in the above example." }, { "code": null, "e": 764, "s": 712, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 768, "s": 764, "text": "C++" }, { "code": null, "e": 770, "s": 768, "text": "C" }, { "code": null, "e": 775, "s": 770, "text": "Java" }, { "code": null, "e": 783, "s": 775, "text": "Python3" }, { "code": null, "e": 786, "s": 783, "text": "C#" }, { "code": null, "e": 797, "s": 786, "text": "Javascript" }, { "code": "// C++ program to reverse a string#include <bits/stdc++.h>using namespace std; // Function to reverse words*/void reverseWords(string s){ // temporary vector to store all words vector<string> tmp; string str = \"\"; for (int i = 0; i < s.length(); i++) { // Check if we encounter space // push word(str) to vector // and make str NULL if (s[i] == ' ') { tmp.push_back(str); str = \"\"; } // Else add character to // str to form current word else str += s[i]; } // Last word remaining,add it to vector tmp.push_back(str); // Now print from last to first in vector int i; for (i = tmp.size() - 1; i > 0; i--) cout << tmp[i] << \" \"; // Last word remaining,print it cout << tmp[0] << endl;} // Driver Codeint main(){ string s = \"i like this program very much\"; reverseWords(s); return 0;}", "e": 1748, "s": 797, "text": null }, { "code": "// C program to reverse a string#include <stdio.h> // Function to reverse any sequence// starting with pointer begin and// ending with pointer endvoid reverse(char* begin, char* end){ char temp; while (begin < end) { temp = *begin; *begin++ = *end; *end-- = temp; }} // Function to reverse words*/void reverseWords(char* s){ char* word_begin = s; // Word boundary char* temp = s; // Reversing individual words as // explained in the first step while (*temp) { temp++; if (*temp == '\\0') { reverse(word_begin, temp - 1); } else if (*temp == ' ') { reverse(word_begin, temp - 1); word_begin = temp + 1; } } // Reverse the entire string reverse(s, temp - 1);} // Driver Codeint main(){ char s[] = \"i like this program very much\"; char* temp = s; reverseWords(s); printf(\"%s\", s); return 0;}", "e": 2679, "s": 1748, "text": null }, { "code": "// Java program to// reverse a Stringimport java.util.*;class GFG{ // Reverse the letters// of the wordstatic void reverse(char str[], int start, int end){ // Temporary variable // to store character char temp; while (start <= end) { // Swapping the first // and last character temp = str[start]; str[start] = str[end]; str[end] = temp; start++; end--; }}// Function to reverse wordsstatic char[] reverseWords(char []s){ // Reversing individual words as // explained in the first step int start = 0; for (int end = 0; end < s.length; end++) { // If we see a space, we // reverse the previous // word (word between // the indexes start and end-1 // i.e., s[start..end-1] if (s[end] == ' ') { reverse(s, start, end); start = end + 1; } } // Reverse the last word reverse(s, start, s.length - 1); // Reverse the entire String reverse(s, 0, s.length - 1); return s;} // Driver Codepublic static void main(String[] args){ String s = \"i like this program very much \"; char []p = reverseWords(s.toCharArray()); System.out.print(p);}} // This code is contributed by gauravrajput1", "e": 3870, "s": 2679, "text": null }, { "code": "# Python3 program to reverse a string # Function to reverse each word in the stringdef reverse_word(s, start, end): while start < end: s[start], s[end] = s[end], s[start] start = start + 1 end -= 1 s = \"i like this program very much\" # Convert string to list to use it as a char arrays = list(s)start = 0while True: # We use a try catch block because for # the last word the list.index() function # returns a ValueError as it cannot find # a space in the list try: # Find the next space end = s.index(' ', start) # Call reverse_word function # to reverse each word reverse_word(s, start, end - 1) #Update start variable start = end + 1 except ValueError: # Reverse the last word reverse_word(s, start, len(s) - 1) break # Reverse the entire lists.reverse() # Convert the list back to# string using string.join() functions = \"\".join(s) print(s) # Solution contributed by Prem Nagdeo", "e": 4874, "s": 3870, "text": null }, { "code": "// C# program to// reverse a Stringusing System; class GFG{ // Reverse the letters// of the wordstatic void reverse(char []str, int start, int end){ // Temporary variable // to store character char temp; while (start <= end) { // Swapping the first // and last character temp = str[start]; str[start] = str[end]; str[end] = temp; start++; end--; }} // Function to reverse wordsstatic char[] reverseWords(char []s){ // Reversing individual words as // explained in the first step int start = 0; for (int end = 0; end < s.Length; end++) { // If we see a space, we // reverse the previous // word (word between // the indexes start and end-1 // i.e., s[start..end-1] if (s[end] == ' ') { reverse(s, start, end); start = end + 1; } } // Reverse the last word reverse(s, start, s.Length - 1); // Reverse the entire String reverse(s, 0, s.Length - 1); return s;} // Driver Codepublic static void Main(String[] args){ String s = \"i like this program very much \"; char []p = reverseWords(s.ToCharArray()); Console.Write(p);}} // This code is contributed by jana_sayantan", "e": 6074, "s": 4874, "text": null }, { "code": "<script> // Javascript program to // reverse a String // Reverse the letters // of the word function reverse(str,start,end) { // Temporary variable // to store character let temp; while (start <= end) { // Swapping the first // and last character temp = str[start]; str[start]=str[end]; str[end]=temp; start++; end--; } } // Function to reverse words function reverseWords(s) { // Reversing individual words as // explained in the first step s=s.split(\"\"); let start = 0; for (let end = 0; end < s.length; end++) { // If we see a space, we // reverse the previous // word (word between // the indexes start and end-1 // i.e., s[start..end-1] if (s[end] == ' ') { reverse(s, start, end); start = end + 1; } } // Reverse the last word reverse(s, start, s.length - 1); // Reverse the entire String reverse(s, 0, s.length - 1); return s.join(\"\"); } // Driver Code var s = \"i like this program very much \"; document.write(reverseWords(s)); // This code is contributed by avanitrachhadiya2155</script>", "e": 7483, "s": 6074, "text": null }, { "code": null, "e": 7513, "s": 7483, "text": "much very program this like i" }, { "code": null, "e": 7558, "s": 7513, "text": "Time complexity: O(n), Auxiliary Space: O(n)" }, { "code": null, "e": 7826, "s": 7558, "text": "The above code doesn’t handle the cases when the string starts with space. The following version handles this specific case and doesn’t make unnecessary calls to reverse function in the case of multiple spaces in between. Thanks to rka143 for providing this version. " }, { "code": null, "e": 7830, "s": 7826, "text": "C++" }, { "code": null, "e": 7832, "s": 7830, "text": "C" }, { "code": "// C++ program for above approach:void reverseWords(char* s){ char* word_begin = NULL; // /* temp is for word boundary */ char* temp = s; /*STEP 1 of the above algorithm */ while (*temp) { /*This condition is to make sure that the string start with valid character (not space) only*/ if ((word_begin == NULL) && (*temp != ' ')) { word_begin = temp; } if (word_begin && ((*(temp + 1) == ' ') || (*(temp + 1) == '\\0'))) { reverse(word_begin, temp); word_begin = NULL; } temp++; } /* End of while */ /*STEP 2 of the above algorithm */ reverse(s, temp - 1);} // This code is contributed by rutvik_56.", "e": 8529, "s": 7832, "text": null }, { "code": "// C program for above approach void reverseWords(char* s){ char* word_begin = NULL; // /* temp is for word boundary */ char* temp = s; /*STEP 1 of the above algorithm */ while (*temp) { /*This condition is to make sure that the string start with valid character (not space) only*/ if ((word_begin == NULL) && (*temp != ' ')) { word_begin = temp; } if (word_begin && ((*(temp + 1) == ' ') || (*(temp + 1) == '\\0'))) { reverse(word_begin, temp); word_begin = NULL; } temp++; } /* End of while */ /*STEP 2 of the above algorithm */ reverse(s, temp - 1);}", "e": 9251, "s": 8529, "text": null }, { "code": null, "e": 9341, "s": 9251, "text": "Time Complexity: O(n), Auxiliary Space: O(n) as we’re storing string in the new variable." }, { "code": null, "e": 9423, "s": 9341, "text": "We can do the above task by splitting and saving the string in a reverse manner. " }, { "code": null, "e": 9474, "s": 9423, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 9478, "s": 9474, "text": "C++" }, { "code": null, "e": 9483, "s": 9478, "text": "Java" }, { "code": null, "e": 9491, "s": 9483, "text": "Python3" }, { "code": null, "e": 9494, "s": 9491, "text": "C#" }, { "code": null, "e": 9505, "s": 9494, "text": "Javascript" }, { "code": "// C++ program to reverse a string// s = input() #include <bits/stdc++.h>using namespace std; int main(){ string s[] = { \"i\", \"like\", \"this\", \"program\", \"very\", \"much\" }; string ans = \"\"; for (int i = 5; i >= 0; i--) { ans += s[i] + \" \"; } cout << (\"Reversed String:\") << endl; cout << (ans.substr(0, ans.length() - 1)) << endl; return 0;}", "e": 9899, "s": 9505, "text": null }, { "code": "// Java program to reverse a string// s = input()public class ReverseWords{ public static void main(String[] args) { String s[] = \"i like this program very much\". split(\" \"); String ans = \"\"; for (int i = s.length - 1; i >= 0; i--) { ans += s[i] + \" \"; } System.out.println(\"Reversed String:\"); System.out.println(ans.substring(0, ans.length() - 1)); }}", "e": 10395, "s": 9899, "text": null }, { "code": "# Python3 program to reverse a string# s = input()s = \"i like this program very much\"words = s.split(' ')string =[]for word in words: string.insert(0, word) print(\"Reversed String:\")print(\" \".join(string)) # Solution proposed bu Uttam", "e": 10633, "s": 10395, "text": null }, { "code": "// C# program to reverse a string// s = input() using System;public class ReverseWords{ public static void Main() { string[] s = \"i like this program very much\". Split(' '); string ans = \"\"; for (int i = s.Length - 1; i >= 0; i--) { ans += s[i] + \" \"; } Console.Write(\"Reversed String:\\n\"); Console.Write(ans.Substring(0, ans.Length - 1)); }}", "e": 11121, "s": 10633, "text": null }, { "code": "<script> // JavaScript program to reverse a string var s= [\"i\", \"like\", \"this\", \"program\", \"very\", \"much\"]; var ans =\"\"; for (var i = 5; i >= 0; i--) { ans += s[i] + \" \"; } document.write(\"Reversed String:\"+ \"<br>\"); document.write(ans.slice(0,ans.length-1)); </script>", "e": 11458, "s": 11121, "text": null }, { "code": null, "e": 11505, "s": 11458, "text": "Reversed String:\nmuch very program this like i" }, { "code": null, "e": 11597, "s": 11507, "text": "Time Complexity: O(n), Auxiliary Space: O(n) as we’re storing string in the new variable." }, { "code": null, "e": 11772, "s": 11597, "text": "The above task can also be accomplished by splitting and directly swapping the string starting from the middle. As direct swapping is involved, less space is consumed too. " }, { "code": null, "e": 11823, "s": 11772, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 11827, "s": 11823, "text": "C++" }, { "code": null, "e": 11832, "s": 11827, "text": "Java" }, { "code": null, "e": 11840, "s": 11832, "text": "Python3" }, { "code": null, "e": 11843, "s": 11840, "text": "C#" }, { "code": null, "e": 11854, "s": 11843, "text": "Javascript" }, { "code": "// C++ code to reverse a string #include <bits/stdc++.h>using namespace std; // Reverse the stringstring RevString(string s[], int l){ // Check if number of words is even if (l % 2 == 0) { // Find the middle word int j = l / 2; // Starting from the middle // start swapping words at // jth position and l-1-j position while (j <= l - 1) { string temp; temp = s[l - j - 1]; s[l - j - 1] = s[j]; s[j] = temp; j += 1; } } // Check if number of words is odd else { // Find the middle word int j = (l / 2) + 1; // Starting from the middle start // swapping the words at jth // position and l-1-j position while (j <= l - 1) { string temp; temp = s[l - j - 1]; s[l - j - 1] = s[j]; s[j] = temp; j += 1; } } string S = s[0]; // Return the reversed sentence for (int i = 1; i < 9; i++) { S = S + \" \" + s[i]; } return S;} // Driver codeint main(){ string s = \"getting good at coding \" \"needs a lot of practice\"; string words[] = { \"getting\", \"good\", \"at\", \"coding\", \"needs\", \"a\", \"lot\", \"of\", \"practice\" }; cout << RevString(words, 9) << endl; return 0;}", "e": 13211, "s": 11854, "text": null }, { "code": "// Java code to reverse a stringclass GFG{ // Reverse the stringpublic static String[] RevString(String[] s, int l){ // Check if number of words is even if (l % 2 == 0) { // Find the middle word int j = l / 2; // Starting from the middle // start swapping words at // jth position and l-1-j position while (j <= l - 1) { String temp; temp = s[l - j - 1]; s[l - j - 1] = s[j]; s[j] = temp; j += 1; } } // Check if number of words is odd else { // Find the middle word int j = (l / 2) + 1; // Starting from the middle start // swapping the words at jth // position and l-1-j position while (j <= l - 1) { String temp; temp = s[l - j - 1]; s[l - j - 1] = s[j]; s[j] = temp; j += 1; } } // Return the reversed sentence return s;} // Driver Codepublic static void main(String[] args){ String s = \"getting good at coding \" + \"needs a lot of practice\"; String[] words = s.split(\"\\\\s\"); words = RevString(words, words.length); s = String.join(\" \", words); System.out.println(s);}} // This code is contributed by MuskanKalra1", "e": 14611, "s": 13211, "text": null }, { "code": "# Python3 code to reverse a string # Reverse the stringdef RevString(s,l): # Check if number of words is even if l%2 == 0: # Find the middle word j = int(l/2) # Starting from the middle # start swapping words # at jth position and l-1-j position while(j <= l - 1): s[j], s[l - j - 1] = s[l - j - 1], s[j] j += 1 # Check if number of words is odd else: # Find the middle word j = int(l/2 + 1) # Starting from the middle # start swapping the words # at jth position and l-1-j position while(j <= l - 1): s[j], s[l - 1 - j] = s[l - j - 1], s[j] j += 1 # return the reversed sentence return s; # Driver Codes = 'getting good at coding needs a lot of practice'string = s.split(' ')string = RevString(string,len(string))print(\" \".join(string))", "e": 15456, "s": 14611, "text": null }, { "code": "// C# code to reverse a stringusing System;class GFG{ // Reverse the stringstatic string RevString(string[] s, int l){ // Check if number of words is even if (l % 2 == 0) { // Find the middle word int j = l / 2; // Starting from the middle // start swapping words at // jth position and l-1-j position while (j <= l - 1) { string temp; temp = s[l - j - 1]; s[l - j - 1] = s[j]; s[j] = temp; j += 1; } } // Check if number of words is odd else { // Find the middle word int j = (l / 2) + 1; // Starting from the middle start // swapping the words at jth // position and l-1-j position while (j <= l - 1) { string temp; temp = s[l - j - 1]; s[l - j - 1] = s[j]; s[j] = temp; j += 1; } } string S = s[0]; // Return the reversed sentence for (int i = 1; i < 9; i++) { S = S + \" \" + s[i]; } return S;} // Driver Codepublic static void Main(){ string []words = { \"getting\", \"good\", \"at\", \"coding\", \"needs\", \"a\", \"lot\", \"of\", \"practice\" }; string a = RevString(words, words.Length); Console.WriteLine(a);}} // This code is contributed by Aarti_Rathi and shivanisinghss2110", "e": 16892, "s": 15456, "text": null }, { "code": "<script> // Javascript code to reverse a string // Reverse the stringfunction RevString(s, l){ // Check if number of words is even if (l % 2 == 0) { // Find the middle word let j = parseInt(l / 2, 10); // Starting from the middle // start swapping words at // jth position and l-1-j position while (j <= l - 1) { let temp; temp = s[l - j - 1]; s[l - j - 1] = s[j]; s[j] = temp; j += 1; } } // Check if number of words is odd else { // Find the middle word let j = parseInt((l / 2), 10) + 1; // Starting from the middle start // swapping the words at jth // position and l-1-j position while (j <= l - 1) { let temp; temp = s[l - j - 1]; s[l - j - 1] = s[j]; s[j] = temp; j += 1; } } let S = s[0]; // Return the reversed sentence for(let i = 1; i < 9; i++) { S = S + \" \" + s[i]; } return S;} // Driver codelet s = \"getting good at coding \" \"needs a lot of practice\"; let words = [ \"getting\", \"good\", \"at\", \"coding\", \"needs\", \"a\", \"lot\", \"of\", \"practice\"]; document.write(RevString(words, 9)); // This code is contributed by suresh07 </script>", "e": 18268, "s": 16892, "text": null }, { "code": null, "e": 18315, "s": 18268, "text": "practice of lot a needs coding at good getting" }, { "code": null, "e": 18360, "s": 18315, "text": "Time complexity: O(n), Auxiliary Space: O(n)" }, { "code": null, "e": 18461, "s": 18360, "text": "Go through the string and mirror each word in the string, then, in the end, mirror the whole string." }, { "code": null, "e": 18523, "s": 18461, "text": "The following C++ code can handle multiple contiguous spaces." }, { "code": null, "e": 18527, "s": 18523, "text": "C++" }, { "code": null, "e": 18532, "s": 18527, "text": "Java" }, { "code": "#include <algorithm>#include <iostream>#include <string> using namespace std; string reverse_words(string s){ int left = 0, i = 0, n = s.size(); while (s[i] == ' ') i++; left = i; while (i < n) { if (i + 1 == n || s[i] == ' ') { int j = i - 1; if (i + 1 == n) j++; while (left < j) swap(s[left++], s[j--]); left = i + 1; } if (i > left && s[left] == ' ') left = i; i++; } reverse(s.begin(), s.end()); return s;} int main(){ string str = \"Be a game changer the world is already \" \"full of players\"; str = reverse_words(str); cout << str; return 0;}", "e": 19259, "s": 18532, "text": null }, { "code": "/*package whatever //do not write package name here */ import java.io.*; class GFG { // Java does not have built-in swap function to swap // characters of a string public static String swap(String str, int i, int j) { char ch[] = str.toCharArray(); char temp = ch[i]; ch[i] = ch[j]; ch[j] = temp; return new String(ch); } public static String reverse_words(String s) { int left = 0, i = 0, n = s.length(); while (s.charAt(i) == ' ') i++; left = i; while (i < n) { if (i + 1 == n || s.charAt(i) == ' ') { int j = i - 1; if (i + 1 == n) j++; while (left < j) s = swap(s, left++, j--); left = i + 1; } if (i > left && s.charAt(left) == ' ') left = i; i++; } // Use StringBuilder \".reverse()\" method to reverse // the whole string. s = new StringBuilder(s).reverse().toString(); return s; } // Driver Code public static void main(String[] args) { String str = \"Be a game changer the world is already full of players\"; str = reverse_words(str); System.out.println(str); }}//This code is contributed by KaaL-EL.", "e": 20606, "s": 19259, "text": null }, { "code": null, "e": 20661, "s": 20606, "text": "players of full already is world the changer game a Be" }, { "code": null, "e": 20711, "s": 20661, "text": "Method: Using slicing method and join functions." }, { "code": null, "e": 20719, "s": 20711, "text": "Python3" }, { "code": "# python code to reverse words in a given string # input stringstring = \"getting good at coding needs a lot of practice\"# spliting words in the given string# using slicing reverse the wordss = string.split()[::-1]# joining the reversed string and# printing the outputprint(\" \".join(s))", "e": 21005, "s": 20719, "text": null }, { "code": null, "e": 21052, "s": 21005, "text": "practice of lot a needs coding at good getting" }, { "code": null, "e": 21077, "s": 21052, "text": "Time complexity: O(n2), " }, { "code": null, "e": 21099, "s": 21077, "text": "Auxiliary Space: O(n)" }, { "code": null, "e": 21216, "s": 21099, "text": "Please write comments if you find any bug in the above code/algorithm, or find other ways to solve the same problem." }, { "code": null, "e": 21225, "s": 21216, "text": "Uttamk94" }, { "code": null, "e": 21246, "s": 21225, "text": "Deepak Kumar Agarwal" }, { "code": null, "e": 21252, "s": 21246, "text": "ukasp" }, { "code": null, "e": 21265, "s": 21252, "text": "Akanksha_Rai" }, { "code": null, "e": 21276, "s": 21265, "text": "premnagdeo" }, { "code": null, "e": 21291, "s": 21276, "text": "utsav akarshan" }, { "code": null, "e": 21305, "s": 21291, "text": "GauravRajput1" }, { "code": null, "e": 21321, "s": 21305, "text": "pratyushpraveen" }, { "code": null, "e": 21334, "s": 21321, "text": "MuskanKalra1" }, { "code": null, "e": 21348, "s": 21334, "text": "jana_sayantan" }, { "code": null, "e": 21367, "s": 21348, "text": "shivanisinghss2110" }, { "code": null, "e": 21377, "s": 21367, "text": "rutvik_56" }, { "code": null, "e": 21395, "s": 21377, "text": "divyeshrabadiya07" }, { "code": null, "e": 21409, "s": 21395, "text": "divyesh072019" }, { "code": null, "e": 21430, "s": 21409, "text": "avanitrachhadiya2155" }, { "code": null, "e": 21439, "s": 21430, "text": "suresh07" }, { "code": null, "e": 21455, "s": 21439, "text": "akshitsaxenaa09" }, { "code": null, "e": 21468, "s": 21455, "text": "davidgatea21" }, { "code": null, "e": 21488, "s": 21468, "text": "chandramauliguptach" }, { "code": null, "e": 21495, "s": 21488, "text": "kaalel" }, { "code": null, "e": 21514, "s": 21495, "text": "laxmigangarajula03" }, { "code": null, "e": 21530, "s": 21514, "text": "sachinvinod1904" }, { "code": null, "e": 21539, "s": 21530, "text": "Accolite" }, { "code": null, "e": 21545, "s": 21539, "text": "Adobe" }, { "code": null, "e": 21552, "s": 21545, "text": "Amazon" }, { "code": null, "e": 21568, "s": 21552, "text": "CBSE - Class 11" }, { "code": null, "e": 21574, "s": 21568, "text": "Cisco" }, { "code": null, "e": 21588, "s": 21574, "text": "Goldman Sachs" }, { "code": null, "e": 21599, "s": 21588, "text": "MakeMyTrip" }, { "code": null, "e": 21612, "s": 21599, "text": "MAQ Software" }, { "code": null, "e": 21622, "s": 21612, "text": "Microsoft" }, { "code": null, "e": 21637, "s": 21622, "text": "Morgan Stanley" }, { "code": null, "e": 21643, "s": 21637, "text": "Paytm" }, { "code": null, "e": 21648, "s": 21643, "text": "Payu" }, { "code": null, "e": 21656, "s": 21648, "text": "Reverse" }, { "code": null, "e": 21665, "s": 21656, "text": "SAP Labs" }, { "code": null, "e": 21684, "s": 21665, "text": "school-programming" }, { "code": null, "e": 21690, "s": 21684, "text": "Wipro" }, { "code": null, "e": 21695, "s": 21690, "text": "Zoho" }, { "code": null, "e": 21703, "s": 21695, "text": "Strings" }, { "code": null, "e": 21709, "s": 21703, "text": "Paytm" }, { "code": null, "e": 21714, "s": 21709, "text": "Zoho" }, { "code": null, "e": 21729, "s": 21714, "text": "Morgan Stanley" }, { "code": null, "e": 21738, "s": 21729, "text": "Accolite" }, { "code": null, "e": 21745, "s": 21738, "text": "Amazon" }, { "code": null, "e": 21755, "s": 21745, "text": "Microsoft" }, { "code": null, "e": 21766, "s": 21755, "text": "MakeMyTrip" }, { "code": null, "e": 21771, "s": 21766, "text": "Payu" }, { "code": null, "e": 21785, "s": 21771, "text": "Goldman Sachs" }, { "code": null, "e": 21798, "s": 21785, "text": "MAQ Software" }, { "code": null, "e": 21804, "s": 21798, "text": "Adobe" }, { "code": null, "e": 21810, "s": 21804, "text": "Wipro" }, { "code": null, "e": 21819, "s": 21810, "text": "SAP Labs" }, { "code": null, "e": 21825, "s": 21819, "text": "Cisco" }, { "code": null, "e": 21833, "s": 21825, "text": "Strings" }, { "code": null, "e": 21841, "s": 21833, "text": "Reverse" } ]
Python | Select random value from a list
05 Jul, 2022 In this article, we will cover how to Randomly Select Elements From a List in Python. Generating random numbers has always been a useful utility in day-day programming for games or various types of gambling etc. Hence knowledge and shorthands of it in any programming language is always a plus to have. Let’s discuss all the different ways to select random values from a list. In Python random choice() function to select a random item from a list, This random.choice() function is designed for the specific purpose of getting a Random sampling from a list in Python from the container and hence is the most common method to achieve this task of getting a random number from a list. Python3 import random # initializing listtest_list = [1, 4, 5, 2, 7] # printing original listprint("Original list is : " + str(test_list)) # using random.choice() to# get a random numberrandom_num = random.choice(test_list) # printing random numberprint("Random selected number is : " + str(random_num)) Output: Original list is : [1, 4, 5, 2, 7] Random selected number is : 1 This method is used to generate a random number in a range, for lists, we can specify the range to be 0 to its length, and get the index, and then the corresponding value. This also gives the option of getting even placed elements or elements at the index of a certain multiple. Python3 import random # initializing listtest_list = [1, 4, 5, 2, 7] # printing original listprint("Original list is : " + str(test_list)) # using random.randrange() to# get a random numberrand_idx = random.randrange(len(test_list))random_num = test_list[rand_idx] # printing random numberprint("Random selected number is : " + str(random_num)) Output: Original list is : [1, 4, 5, 2, 7] Random selected number is : 7 Yet another method to generate the random number, this also can be used to generate any number in a range, and then using that number index, we can find the value at the corresponding index, just like the above-mentioned technique. But it differs by the fact that it required 2 mandatory arguments for range. Python3 import random # initializing listtest_list = [1, 4, 5, 2, 7] # printing original listprint("Original list is : " + str(test_list)) # using random.randint() to# get a random numberrand_idx = random.randint(0, len(test_list)-1)random_num = test_list[rand_idx] # printing random numberprint("Random selected number is : " + str(random_num)) Output: Original list is : [1, 4, 5, 2, 7] Random selected number is : 4 This method generates the floating-point numbers in the range of 0 to 1. We can also get the index value of list using this function by multiplying the result and then typecasting to int to get the integer index and then the corresponding list value. Python3 import random # initializing listtest_list = [1, 4, 5, 2, 7] # printing original listprint("Original list is : " + str(test_list)) # using random.random() to# get a random numberrand_idx = int(random.random() * len(test_list))random_num = test_list[rand_idx] # printing random numberprint("Random selected number is : " + str(random_num)) Output: Original list is : [1, 4, 5, 2, 7] Random selected number is : 7 Python has a built-in function called random.sample(). The random module contains the random.sample function (). The ability to choose multiple items from a list is helpful. Python3 import randomtest_list = [1, 4, 5, 2, 7]print("Original list is : " + str(test_list)) print("Random element is :", random.sample(test_list, 5)) Output: Original list is : [1, 4, 5, 2, 7] Random element is : [7, 4, 1, 5, 2] The random.choices function is stored in the random module (). Selecting numerous items from a list or a single item from a particular sequence is handy. Python3 import randomtest_list = [11, 44, 55, 22, 77]print("Original list is : " + str(test_list)) print("Random element is :", random.choices(test_list, k=4)) Output: Original list is : [11, 44, 55, 22, 77] Random element is : [11, 11, 44, 77] surajkumarguptaintern Python list-programs python-list Python python-list Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n05 Jul, 2022" }, { "code": null, "e": 139, "s": 52, "text": "In this article, we will cover how to Randomly Select Elements From a List in Python. " }, { "code": null, "e": 431, "s": 139, "text": "Generating random numbers has always been a useful utility in day-day programming for games or various types of gambling etc. Hence knowledge and shorthands of it in any programming language is always a plus to have. Let’s discuss all the different ways to select random values from a list. " }, { "code": null, "e": 738, "s": 431, "text": "In Python random choice() function to select a random item from a list, This random.choice() function is designed for the specific purpose of getting a Random sampling from a list in Python from the container and hence is the most common method to achieve this task of getting a random number from a list. " }, { "code": null, "e": 746, "s": 738, "text": "Python3" }, { "code": "import random # initializing listtest_list = [1, 4, 5, 2, 7] # printing original listprint(\"Original list is : \" + str(test_list)) # using random.choice() to# get a random numberrandom_num = random.choice(test_list) # printing random numberprint(\"Random selected number is : \" + str(random_num))", "e": 1042, "s": 746, "text": null }, { "code": null, "e": 1050, "s": 1042, "text": "Output:" }, { "code": null, "e": 1115, "s": 1050, "text": "Original list is : [1, 4, 5, 2, 7]\nRandom selected number is : 1" }, { "code": null, "e": 1395, "s": 1115, "text": "This method is used to generate a random number in a range, for lists, we can specify the range to be 0 to its length, and get the index, and then the corresponding value. This also gives the option of getting even placed elements or elements at the index of a certain multiple. " }, { "code": null, "e": 1403, "s": 1395, "text": "Python3" }, { "code": "import random # initializing listtest_list = [1, 4, 5, 2, 7] # printing original listprint(\"Original list is : \" + str(test_list)) # using random.randrange() to# get a random numberrand_idx = random.randrange(len(test_list))random_num = test_list[rand_idx] # printing random numberprint(\"Random selected number is : \" + str(random_num))", "e": 1740, "s": 1403, "text": null }, { "code": null, "e": 1748, "s": 1740, "text": "Output:" }, { "code": null, "e": 1813, "s": 1748, "text": "Original list is : [1, 4, 5, 2, 7]\nRandom selected number is : 7" }, { "code": null, "e": 2123, "s": 1813, "text": "Yet another method to generate the random number, this also can be used to generate any number in a range, and then using that number index, we can find the value at the corresponding index, just like the above-mentioned technique. But it differs by the fact that it required 2 mandatory arguments for range. " }, { "code": null, "e": 2131, "s": 2123, "text": "Python3" }, { "code": "import random # initializing listtest_list = [1, 4, 5, 2, 7] # printing original listprint(\"Original list is : \" + str(test_list)) # using random.randint() to# get a random numberrand_idx = random.randint(0, len(test_list)-1)random_num = test_list[rand_idx] # printing random numberprint(\"Random selected number is : \" + str(random_num))", "e": 2469, "s": 2131, "text": null }, { "code": null, "e": 2477, "s": 2469, "text": "Output:" }, { "code": null, "e": 2542, "s": 2477, "text": "Original list is : [1, 4, 5, 2, 7]\nRandom selected number is : 4" }, { "code": null, "e": 2794, "s": 2542, "text": "This method generates the floating-point numbers in the range of 0 to 1. We can also get the index value of list using this function by multiplying the result and then typecasting to int to get the integer index and then the corresponding list value. " }, { "code": null, "e": 2802, "s": 2794, "text": "Python3" }, { "code": "import random # initializing listtest_list = [1, 4, 5, 2, 7] # printing original listprint(\"Original list is : \" + str(test_list)) # using random.random() to# get a random numberrand_idx = int(random.random() * len(test_list))random_num = test_list[rand_idx] # printing random numberprint(\"Random selected number is : \" + str(random_num))", "e": 3141, "s": 2802, "text": null }, { "code": null, "e": 3149, "s": 3141, "text": "Output:" }, { "code": null, "e": 3214, "s": 3149, "text": "Original list is : [1, 4, 5, 2, 7]\nRandom selected number is : 7" }, { "code": null, "e": 3388, "s": 3214, "text": "Python has a built-in function called random.sample(). The random module contains the random.sample function (). The ability to choose multiple items from a list is helpful." }, { "code": null, "e": 3396, "s": 3388, "text": "Python3" }, { "code": "import randomtest_list = [1, 4, 5, 2, 7]print(\"Original list is : \" + str(test_list)) print(\"Random element is :\", random.sample(test_list, 5))", "e": 3540, "s": 3396, "text": null }, { "code": null, "e": 3548, "s": 3540, "text": "Output:" }, { "code": null, "e": 3619, "s": 3548, "text": "Original list is : [1, 4, 5, 2, 7]\nRandom element is : [7, 4, 1, 5, 2]" }, { "code": null, "e": 3773, "s": 3619, "text": "The random.choices function is stored in the random module (). Selecting numerous items from a list or a single item from a particular sequence is handy." }, { "code": null, "e": 3781, "s": 3773, "text": "Python3" }, { "code": "import randomtest_list = [11, 44, 55, 22, 77]print(\"Original list is : \" + str(test_list)) print(\"Random element is :\", random.choices(test_list, k=4))", "e": 3933, "s": 3781, "text": null }, { "code": null, "e": 3941, "s": 3933, "text": "Output:" }, { "code": null, "e": 4018, "s": 3941, "text": "Original list is : [11, 44, 55, 22, 77]\nRandom element is : [11, 11, 44, 77]" }, { "code": null, "e": 4040, "s": 4018, "text": "surajkumarguptaintern" }, { "code": null, "e": 4061, "s": 4040, "text": "Python list-programs" }, { "code": null, "e": 4073, "s": 4061, "text": "python-list" }, { "code": null, "e": 4080, "s": 4073, "text": "Python" }, { "code": null, "e": 4092, "s": 4080, "text": "python-list" } ]
Job Sequencing Problem | Practice | GeeksforGeeks
Given a set of N jobs where each jobi has a deadline and profit associated with it. Each job takes 1 unit of time to complete and only one job can be scheduled at a time. We earn the profit associated with job if and only if the job is completed by its deadline. Find the number of jobs done and the maximum profit. Note: Jobs will be given in the form (Jobid, Deadline, Profit) associated with that Job. Example 1: Input: N = 4 Jobs = {(1,4,20),(2,1,10),(3,1,40),(4,1,30)} Output: 2 60 Explanation: Job1 and Job3 can be done with maximum profit of 60 (20+40). Example 2: Input: N = 5 Jobs = {(1,2,100),(2,1,19),(3,2,27), (4,1,25),(5,1,15)} Output: 2 127 Explanation: 2 jobs can be done with maximum profit of 127 (100+27). Your Task : You don't need to read input or print anything. Your task is to complete the function JobScheduling() which takes an integer N and an array of Jobs(Job id, Deadline, Profit) as input and returns the count of jobs and maximum profit. Expected Time Complexity: O(NlogN) Expected Auxilliary Space: O(N) Constraints: 1 <= N <= 105 1 <= Deadline <= 100 1 <= Profit <= 500 0 goyalshivank7901 hour ago // easy c++ code static bool comp (Job a , Job b){ return a.profit > b.profit;} vector<int> JobScheduling(Job arr[], int n) { vector<bool> vis(101,false); sort(arr,arr+n,comp); int deadline = 0; int profit = 0; for(int i=0;i<n;i++){ for(int k=arr[i].dead;k>0;k--){ if(vis[k]==false){ vis[k]=arr[i].profit; deadline++; profit+=arr[i].profit; break;}}} return {deadline,profit};} 0 sauravkumar487364 hours ago class Solution { public: //Function to find the maximum profit and the number of jobs done. static bool comp(const Job &a,const Job &b) { return a.profit>b.profit; } vector<int> JobScheduling(Job arr[], int n) { // your code here sort(arr,arr+n,comp); vector<int>ans; int count=0,profit=0; vector<int>deadline(101,-1); for(int i=0;i<n;i++) { int j=arr[i].dead; for(int k=j;k>0;k--) { if(deadline[k]==-1) { deadline[k]=arr[i].profit; count++; profit+=arr[i].profit; break; } } } ans.push_back(count); ans.push_back(profit); return ans; } }; 0 hawtsauce2k2 days ago Java | O(nlogn) Time | O(n) Space class Solution { int[] JobScheduling(Job arr[], int n) { Arrays.sort(arr, (a, b) -> a.deadline - b.deadline); PriorityQueue<Integer> pq = new PriorityQueue<>(); int time = 0, profit = 0; for(int i = 0; i < n; i ++) { int p = arr[i].profit; int d = arr[i].deadline; if(time + 1 <= d) { profit += p; pq.offer(p); time ++; } else { if(!pq.isEmpty() && pq.peek() < p) { profit += p - pq.poll(); pq.offer(p); } } } return new int[]{pq.size(), profit}; } } 0 hrithikrsgupta3 days ago t.c. O(NlogN) Using path compression to find free day for the job. class Solution { public: static bool comp(Job a,Job b){ return a.profit>b.profit; } int findPos(int pos,vector<int> &parent){ if(parent[pos]==0) return -1; if(parent[pos] == pos) return parent[pos] = pos-1; return parent[pos] = findPos(parent[pos],parent); } vector<int> JobScheduling(Job arr[], int n) { vector<int> parent(102); for(int i=0;i<=101;i++) parent[i] = i; sort(arr,arr+n,comp); int mx = 0, count = 0; for(int i=0;i<n;i++){ int pos = findPos(arr[i].dead,parent); if(pos==-1) continue; mx += arr[i].profit; count++; } return {count,mx}; } }; 0 nilesh2253 days ago class Solution{ //Function to find the maximum profit and the number of jobs done. int[] JobScheduling(Job arr[], int n) { PriorityQueue<Job> pq = new PriorityQueue<>((a,b)->b.profit-a.profit); int maxDead = 0; for(int i=0;i<n;i++){ pq.add(arr[i]); if(arr[i].deadline > maxDead){ maxDead = arr[i].deadline; } } int[] vis = new int[maxDead+1]; int count = 0; int maxProfit = 0; while(!pq.isEmpty()){ Job pol = pq.poll(); for(int i=pol.deadline;i>=1;i--){ if(vis[i]==0){ vis[i] = 1; count++; maxProfit += pol.profit; break; } } } return new int[] {count,maxProfit}; }} We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab. Make sure you are not using ad-blockers. Disable browser extensions. We recommend using latest version of your browser for best experience. Avoid using static/global variables in coding problems as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases in coding problems does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
[ { "code": null, "e": 323, "s": 238, "text": "Given a set of N jobs where each jobi has a deadline and profit associated with it. " }, { "code": null, "e": 503, "s": 323, "text": "Each job takes 1 unit of time to complete and only one job can be scheduled at a time. We earn the profit associated with job if and only if the job is completed by its deadline. " }, { "code": null, "e": 556, "s": 503, "text": "Find the number of jobs done and the maximum profit." }, { "code": null, "e": 645, "s": 556, "text": "Note: Jobs will be given in the form (Jobid, Deadline, Profit) associated with that Job." }, { "code": null, "e": 657, "s": 645, "text": "\nExample 1:" }, { "code": null, "e": 803, "s": 657, "text": "Input:\nN = 4\nJobs = {(1,4,20),(2,1,10),(3,1,40),(4,1,30)}\nOutput:\n2 60\nExplanation:\nJob1 and Job3 can be done with\nmaximum profit of 60 (20+40).\n" }, { "code": null, "e": 814, "s": 803, "text": "Example 2:" }, { "code": null, "e": 974, "s": 814, "text": "Input:\nN = 5\nJobs = {(1,2,100),(2,1,19),(3,2,27),\n (4,1,25),(5,1,15)}\nOutput:\n2 127\nExplanation:\n2 jobs can be done with\nmaximum profit of 127 (100+27)." }, { "code": null, "e": 1220, "s": 974, "text": "\nYour Task :\nYou don't need to read input or print anything. Your task is to complete the function JobScheduling() which takes an integer N and an array of Jobs(Job id, Deadline, Profit) as input and returns the count of jobs and maximum profit." }, { "code": null, "e": 1288, "s": 1220, "text": "\nExpected Time Complexity: O(NlogN)\nExpected Auxilliary Space: O(N)" }, { "code": null, "e": 1356, "s": 1288, "text": "\nConstraints:\n1 <= N <= 105\n1 <= Deadline <= 100\n1 <= Profit <= 500" }, { "code": null, "e": 1358, "s": 1356, "text": "0" }, { "code": null, "e": 1384, "s": 1358, "text": "goyalshivank7901 hour ago" }, { "code": null, "e": 1401, "s": 1384, "text": "// easy c++ code" }, { "code": null, "e": 1946, "s": 1401, "text": "static bool comp (Job a , Job b){\n return a.profit > b.profit;}\n \n vector<int> JobScheduling(Job arr[], int n) \n { \n vector<bool> vis(101,false);\n sort(arr,arr+n,comp);\n int deadline = 0;\n int profit = 0;\n for(int i=0;i<n;i++){\n for(int k=arr[i].dead;k>0;k--){\n if(vis[k]==false){\n vis[k]=arr[i].profit;\n deadline++;\n profit+=arr[i].profit;\n break;}}}\n return {deadline,profit};} " }, { "code": null, "e": 1948, "s": 1946, "text": "0" }, { "code": null, "e": 1976, "s": 1948, "text": "sauravkumar487364 hours ago" }, { "code": null, "e": 2824, "s": 1976, "text": "class Solution \n{\n public:\n //Function to find the maximum profit and the number of jobs done.\n static bool comp(const Job &a,const Job &b)\n {\n return a.profit>b.profit;\n }\n vector<int> JobScheduling(Job arr[], int n) \n { \n // your code here\n sort(arr,arr+n,comp);\n vector<int>ans;\n int count=0,profit=0;\n vector<int>deadline(101,-1);\n for(int i=0;i<n;i++)\n {\n int j=arr[i].dead;\n for(int k=j;k>0;k--)\n {\n if(deadline[k]==-1)\n {\n deadline[k]=arr[i].profit;\n count++;\n profit+=arr[i].profit;\n break;\n }\n }\n }\n ans.push_back(count);\n ans.push_back(profit);\n return ans;\n } \n};" }, { "code": null, "e": 2826, "s": 2824, "text": "0" }, { "code": null, "e": 2848, "s": 2826, "text": "hawtsauce2k2 days ago" }, { "code": null, "e": 2882, "s": 2848, "text": "Java | O(nlogn) Time | O(n) Space" }, { "code": null, "e": 3582, "s": 2882, "text": "class Solution\n{\n int[] JobScheduling(Job arr[], int n)\n {\n Arrays.sort(arr, (a, b) -> a.deadline - b.deadline);\n PriorityQueue<Integer> pq = new PriorityQueue<>();\n int time = 0, profit = 0;\n for(int i = 0; i < n; i ++) {\n int p = arr[i].profit;\n int d = arr[i].deadline;\n if(time + 1 <= d) {\n profit += p;\n pq.offer(p);\n time ++;\n } else {\n if(!pq.isEmpty() && pq.peek() < p) {\n profit += p - pq.poll();\n pq.offer(p);\n }\n }\n }\n return new int[]{pq.size(), profit};\n \n }\n}" }, { "code": null, "e": 3584, "s": 3582, "text": "0" }, { "code": null, "e": 3609, "s": 3584, "text": "hrithikrsgupta3 days ago" }, { "code": null, "e": 3623, "s": 3609, "text": "t.c. O(NlogN)" }, { "code": null, "e": 3678, "s": 3625, "text": "Using path compression to find free day for the job." }, { "code": null, "e": 4499, "s": 3680, "text": "class Solution { public: static bool comp(Job a,Job b){ return a.profit>b.profit; } int findPos(int pos,vector<int> &parent){ if(parent[pos]==0) return -1; if(parent[pos] == pos) return parent[pos] = pos-1; return parent[pos] = findPos(parent[pos],parent); } vector<int> JobScheduling(Job arr[], int n) { vector<int> parent(102); for(int i=0;i<=101;i++) parent[i] = i; sort(arr,arr+n,comp); int mx = 0, count = 0; for(int i=0;i<n;i++){ int pos = findPos(arr[i].dead,parent); if(pos==-1) continue; mx += arr[i].profit; count++; } return {count,mx}; } };" }, { "code": null, "e": 4503, "s": 4501, "text": "0" }, { "code": null, "e": 4523, "s": 4503, "text": "nilesh2253 days ago" }, { "code": null, "e": 5332, "s": 4523, "text": "class Solution{ //Function to find the maximum profit and the number of jobs done. int[] JobScheduling(Job arr[], int n) { PriorityQueue<Job> pq = new PriorityQueue<>((a,b)->b.profit-a.profit); int maxDead = 0; for(int i=0;i<n;i++){ pq.add(arr[i]); if(arr[i].deadline > maxDead){ maxDead = arr[i].deadline; } } int[] vis = new int[maxDead+1]; int count = 0; int maxProfit = 0; while(!pq.isEmpty()){ Job pol = pq.poll(); for(int i=pol.deadline;i>=1;i--){ if(vis[i]==0){ vis[i] = 1; count++; maxProfit += pol.profit; break; } } } return new int[] {count,maxProfit}; }}" }, { "code": null, "e": 5478, "s": 5332, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 5514, "s": 5478, "text": " Login to access your submissions. " }, { "code": null, "e": 5524, "s": 5514, "text": "\nProblem\n" }, { "code": null, "e": 5534, "s": 5524, "text": "\nContest\n" }, { "code": null, "e": 5597, "s": 5534, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 5782, "s": 5597, "text": "Avoid using static/global variables in your code as your code is tested \n against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 6066, "s": 5782, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code.\n On submission, your code is tested against multiple test cases consisting of all\n possible corner cases and stress constraints." }, { "code": null, "e": 6212, "s": 6066, "text": "You can access the hints to get an idea about what is expected of you as well as\n the final solution code." }, { "code": null, "e": 6289, "s": 6212, "text": "You can view the solutions submitted by other users from the submission tab." }, { "code": null, "e": 6330, "s": 6289, "text": "Make sure you are not using ad-blockers." }, { "code": null, "e": 6358, "s": 6330, "text": "Disable browser extensions." }, { "code": null, "e": 6429, "s": 6358, "text": "We recommend using latest version of your browser for best experience." }, { "code": null, "e": 6616, "s": 6429, "text": "Avoid using static/global variables in coding problems as your code is tested \n against multiple test cases and these tend to retain their previous values." } ]
SQL | Constraints
09 Jun, 2021 Constraints are the rules that we can apply on the type of data in a table. That is, we can specify the limit on the type of data that can be stored in a particular column in a table using constraints. The available constraints in SQL are: NOT NULL: This constraint tells that we cannot store a null value in a column. That is, if a column is specified as NOT NULL then we will not be able to store null in this particular column any more. UNIQUE: This constraint when specified with a column, tells that all the values in the column must be unique. That is, the values in any row of a column must not be repeated. PRIMARY KEY: A primary key is a field which can uniquely identify each row in a table. And this constraint is used to specify a field in a table as primary key. FOREIGN KEY: A Foreign key is a field which can uniquely identify each row in a another table. And this constraint is used to specify a field as Foreign key. CHECK: This constraint helps to validate the values of a column to meet a particular condition. That is, it helps to ensure that the value stored in a column meets a specific condition. DEFAULT: This constraint specifies a default value for the column when no value is specified by the user. How to specify constraints? We can specify constraints at the time of creating the table using CREATE TABLE statement. We can also specify the constraints after creating a table using ALTER TABLE statement. Syntax: Below is the syntax to create constraints using CREATE TABLE statement at the time of creating the table. CREATE TABLE sample_table ( column1 data_type(size) constraint_name, column2 data_type(size) constraint_name, column3 data_type(size) constraint_name, .... ); sample_table: Name of the table to be created. data_type: Type of data that can be stored in the field. constraint_name: Name of the constraint. for example- NOT NULL, UNIQUE, PRIMARY KEY etc. Let us see each of the constraint in detail. 1. NOT NULL – If we specify a field in a table to be NOT NULL. Then the field will never accept null value. That is, you will be not allowed to insert a new row in the table without specifying any value to this field. For example, the below query creates a table Student with the fields ID and NAME as NOT NULL. That is, we are bound to specify values for these two fields every time we wish to insert a new row. CREATE TABLE Student ( ID int(6) NOT NULL, NAME varchar(10) NOT NULL, ADDRESS varchar(20) ); 2. UNIQUE –This constraint helps to uniquely identify each row in the table. i.e. for a particular column, all the rows should have unique values. We can have more than one UNIQUE columns in a table. For example, the below query creates a table Student where the field ID is specified as UNIQUE. i.e, no two students can have the same ID. Unique constraint in detail. CREATE TABLE Student ( ID int(6) NOT NULL UNIQUE, NAME varchar(10), ADDRESS varchar(20) ); 3. PRIMARY KEY – Primary Key is a field which uniquely identifies each row in the table. If a field in a table as primary key, then the field will not be able to contain NULL values as well as all the rows should have unique values for this field. So, in other words we can say that this is combination of NOT NULL and UNIQUE constraints. A table can have only one field as primary key. Below query will create a table named Student and specifies the field ID as primary key. CREATE TABLE Student ( ID int(6) NOT NULL UNIQUE, NAME varchar(10), ADDRESS varchar(20), PRIMARY KEY(ID) ); 4. FOREIGN KEY – Foreign Key is a field in a table which uniquely identifies each row of a another table. That is, this field points to primary key of another table. This usually creates a kind of link between the tables. Consider the two tables as shown below: Orders Customers As we can see clearly that the field C_ID in Orders table is the primary key in Customers table, i.e. it uniquely identifies each row in the Customers table. Therefore, it is a Foreign Key in Orders table. Syntax: CREATE TABLE Orders ( O_ID int NOT NULL, ORDER_NO int NOT NULL, C_ID int, PRIMARY KEY (O_ID), FOREIGN KEY (C_ID) REFERENCES Customers(C_ID) ) (i) CHECK – Using the CHECK constraint we can specify a condition for a field, which should be satisfied at the time of entering values for this field. For example, the below query creates a table Student and specifies the condition for the field AGE as (AGE >= 18 ). That is, the user will not be allowed to enter any record in the table with AGE < 18. Check constraint in detail CREATE TABLE Student ( ID int(6) NOT NULL, NAME varchar(10) NOT NULL, AGE int NOT NULL CHECK (AGE >= 18) ); (ii) DEFAULT – This constraint is used to provide a default value for the fields. That is, if at the time of entering new records in the table if the user does not specify any value for these fields then the default value will be assigned to them. For example, the below query will create a table named Student and specify the default value for the field AGE as 18. CREATE TABLE Student ( ID int(6) NOT NULL, NAME varchar(10) NOT NULL, AGE int DEFAULT 18 ); This article is contributed by 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 [email protected]. 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. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. 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 adityasonani19 SQL-basics DBMS SQL DBMS SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between Clustered and Non-clustered index Introduction of DBMS (Database Management System) | Set 1 Introduction of B-Tree SQL | Views Introduction of ER Model SQL | DDL, DQL, DML, DCL and TCL Commands How to find Nth highest salary from a table SQL | ALTER (RENAME) How to Update Multiple Columns in Single Update Statement in SQL? SQL | Views
[ { "code": null, "e": 52, "s": 24, "text": "\n09 Jun, 2021" }, { "code": null, "e": 255, "s": 52, "text": "Constraints are the rules that we can apply on the type of data in a table. That is, we can specify the limit on the type of data that can be stored in a particular column in a table using constraints. " }, { "code": null, "e": 295, "s": 255, "text": "The available constraints in SQL are: " }, { "code": null, "e": 495, "s": 295, "text": "NOT NULL: This constraint tells that we cannot store a null value in a column. That is, if a column is specified as NOT NULL then we will not be able to store null in this particular column any more." }, { "code": null, "e": 670, "s": 495, "text": "UNIQUE: This constraint when specified with a column, tells that all the values in the column must be unique. That is, the values in any row of a column must not be repeated." }, { "code": null, "e": 831, "s": 670, "text": "PRIMARY KEY: A primary key is a field which can uniquely identify each row in a table. And this constraint is used to specify a field in a table as primary key." }, { "code": null, "e": 989, "s": 831, "text": "FOREIGN KEY: A Foreign key is a field which can uniquely identify each row in a another table. And this constraint is used to specify a field as Foreign key." }, { "code": null, "e": 1175, "s": 989, "text": "CHECK: This constraint helps to validate the values of a column to meet a particular condition. That is, it helps to ensure that the value stored in a column meets a specific condition." }, { "code": null, "e": 1281, "s": 1175, "text": "DEFAULT: This constraint specifies a default value for the column when no value is specified by the user." }, { "code": null, "e": 1489, "s": 1281, "text": "How to specify constraints? We can specify constraints at the time of creating the table using CREATE TABLE statement. We can also specify the constraints after creating a table using ALTER TABLE statement. " }, { "code": null, "e": 1605, "s": 1489, "text": "Syntax: Below is the syntax to create constraints using CREATE TABLE statement at the time of creating the table. " }, { "code": null, "e": 1959, "s": 1605, "text": "CREATE TABLE sample_table\n(\ncolumn1 data_type(size) constraint_name,\ncolumn2 data_type(size) constraint_name,\ncolumn3 data_type(size) constraint_name,\n....\n);\n\nsample_table: Name of the table to be created.\ndata_type: Type of data that can be stored in the field.\nconstraint_name: Name of the constraint. for example- NOT NULL, UNIQUE, PRIMARY KEY etc. " }, { "code": null, "e": 2006, "s": 1959, "text": "Let us see each of the constraint in detail. " }, { "code": null, "e": 2421, "s": 2006, "text": "1. NOT NULL – If we specify a field in a table to be NOT NULL. Then the field will never accept null value. That is, you will be not allowed to insert a new row in the table without specifying any value to this field. For example, the below query creates a table Student with the fields ID and NAME as NOT NULL. That is, we are bound to specify values for these two fields every time we wish to insert a new row. " }, { "code": null, "e": 2514, "s": 2421, "text": "CREATE TABLE Student\n(\nID int(6) NOT NULL,\nNAME varchar(10) NOT NULL,\nADDRESS varchar(20)\n);" }, { "code": null, "e": 2884, "s": 2514, "text": "2. UNIQUE –This constraint helps to uniquely identify each row in the table. i.e. for a particular column, all the rows should have unique values. We can have more than one UNIQUE columns in a table. For example, the below query creates a table Student where the field ID is specified as UNIQUE. i.e, no two students can have the same ID. Unique constraint in detail. " }, { "code": null, "e": 2975, "s": 2884, "text": "CREATE TABLE Student\n(\nID int(6) NOT NULL UNIQUE,\nNAME varchar(10),\nADDRESS varchar(20)\n);" }, { "code": null, "e": 3453, "s": 2975, "text": "3. PRIMARY KEY – Primary Key is a field which uniquely identifies each row in the table. If a field in a table as primary key, then the field will not be able to contain NULL values as well as all the rows should have unique values for this field. So, in other words we can say that this is combination of NOT NULL and UNIQUE constraints. A table can have only one field as primary key. Below query will create a table named Student and specifies the field ID as primary key. " }, { "code": null, "e": 3561, "s": 3453, "text": "CREATE TABLE Student\n(\nID int(6) NOT NULL UNIQUE,\nNAME varchar(10),\nADDRESS varchar(20),\nPRIMARY KEY(ID)\n);" }, { "code": null, "e": 3825, "s": 3561, "text": "4. FOREIGN KEY – Foreign Key is a field in a table which uniquely identifies each row of a another table. That is, this field points to primary key of another table. This usually creates a kind of link between the tables. Consider the two tables as shown below: " }, { "code": null, "e": 3832, "s": 3825, "text": "Orders" }, { "code": null, "e": 3846, "s": 3836, "text": "Customers" }, { "code": null, "e": 4064, "s": 3848, "text": "As we can see clearly that the field C_ID in Orders table is the primary key in Customers table, i.e. it uniquely identifies each row in the Customers table. Therefore, it is a Foreign Key in Orders table. Syntax: " }, { "code": null, "e": 4206, "s": 4064, "text": "CREATE TABLE Orders\n(\nO_ID int NOT NULL,\nORDER_NO int NOT NULL,\nC_ID int,\nPRIMARY KEY (O_ID),\nFOREIGN KEY (C_ID) REFERENCES Customers(C_ID)\n)" }, { "code": null, "e": 4589, "s": 4206, "text": "(i) CHECK – Using the CHECK constraint we can specify a condition for a field, which should be satisfied at the time of entering values for this field. For example, the below query creates a table Student and specifies the condition for the field AGE as (AGE >= 18 ). That is, the user will not be allowed to enter any record in the table with AGE < 18. Check constraint in detail " }, { "code": null, "e": 4697, "s": 4589, "text": "CREATE TABLE Student\n(\nID int(6) NOT NULL,\nNAME varchar(10) NOT NULL,\nAGE int NOT NULL CHECK (AGE >= 18)\n);" }, { "code": null, "e": 5065, "s": 4697, "text": "(ii) DEFAULT – This constraint is used to provide a default value for the fields. That is, if at the time of entering new records in the table if the user does not specify any value for these fields then the default value will be assigned to them. For example, the below query will create a table named Student and specify the default value for the field AGE as 18. " }, { "code": null, "e": 5157, "s": 5065, "text": "CREATE TABLE Student\n(\nID int(6) NOT NULL,\nNAME varchar(10) NOT NULL,\nAGE int DEFAULT 18\n);" }, { "code": null, "e": 5455, "s": 5157, "text": "This article is contributed by 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 [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. " }, { "code": null, "e": 5803, "s": 5455, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. " }, { "code": null, "e": 5928, "s": 5803, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 5943, "s": 5928, "text": "adityasonani19" }, { "code": null, "e": 5954, "s": 5943, "text": "SQL-basics" }, { "code": null, "e": 5959, "s": 5954, "text": "DBMS" }, { "code": null, "e": 5963, "s": 5959, "text": "SQL" }, { "code": null, "e": 5968, "s": 5963, "text": "DBMS" }, { "code": null, "e": 5972, "s": 5968, "text": "SQL" }, { "code": null, "e": 6070, "s": 5972, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6123, "s": 6070, "text": "Difference between Clustered and Non-clustered index" }, { "code": null, "e": 6181, "s": 6123, "text": "Introduction of DBMS (Database Management System) | Set 1" }, { "code": null, "e": 6204, "s": 6181, "text": "Introduction of B-Tree" }, { "code": null, "e": 6216, "s": 6204, "text": "SQL | Views" }, { "code": null, "e": 6241, "s": 6216, "text": "Introduction of ER Model" }, { "code": null, "e": 6283, "s": 6241, "text": "SQL | DDL, DQL, DML, DCL and TCL Commands" }, { "code": null, "e": 6327, "s": 6283, "text": "How to find Nth highest salary from a table" }, { "code": null, "e": 6348, "s": 6327, "text": "SQL | ALTER (RENAME)" }, { "code": null, "e": 6414, "s": 6348, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" } ]
Given a linked list of line segments, remove middle points
24 Jun, 2022 Given a linked list of coordinates where adjacent points either form a vertical line or a horizontal line. Delete points from the linked list which are in the middle of a horizontal or vertical line. Examples: Input: (0,10)->(1,10)->(5,10)->(7,10) | (7,5)->(20,5)->(40,5) Output: Linked List should be changed to following (0,10)->(7,10) | (7,5)->(40,5) The given linked list represents a horizontal line from (0,10) to (7, 10) followed by a vertical line from (7, 10) to (7, 5), followed by a horizontal line from (7, 5) to (40, 5). Input: (2,3)->(4,3)->(6,3)->(10,3)->(12,3) Output: Linked List should be changed to following (2,3)->(12,3) There is only one vertical line, so all middle points are removed. Source: Microsoft Interview Experience The idea is to keep track of the current node, next node, and next-next node. While the next node is the same as the next-next node, keep deleting the next node. In this complete procedure, we need to keep an eye on the shifting of pointers and checking for NULL values. Following are implementations of the above idea. C++ C Java Python3 C# Javascript // C++ program to remove intermediate points// in a linked list that represents horizontal// and vertical line segments#include <bits/stdc++.h>using namespace std; // Node has 3 fields including x, y// coordinates and a pointer// to next nodeclass Node{ public: int x, y; Node *next;}; /* Function to insert a node at the beginning */void push(Node ** head_ref, int x,int y){ Node* new_node =new Node(); new_node->x = x; new_node->y = y; new_node->next = (*head_ref); (*head_ref) = new_node;} /* Utility function to print a singly linked list */void printList(Node *head){ Node *temp = head; while (temp != NULL) { cout << "(" << temp->x << "," << temp->y << ")-> "; temp = temp->next; } cout<<endl; } // Utility function to remove Next from linked list// and link nodes after it to headvoid deleteNode(Node *head, Node *Next){ head->next = Next->next; Next->next = NULL; free(Next);} // This function deletes middle nodes in a sequence of// horizontal and vertical line segments represented by// linked list.Node* deleteMiddle(Node *head){ // If only one node or no node...Return back if (head == NULL || head->next == NULL || head->next->next == NULL) return head; Node* Next = head->next; Node *NextNext = Next->next ; // Check if this is a vertical line or horizontal line if (head->x == Next->x) { // Find middle nodes with same x value, and delete them while (NextNext != NULL && Next->x == NextNext->x) { deleteNode(head, Next); // Update Next and NextNext for next iteration Next = NextNext; NextNext = NextNext->next; } } else if (head->y==Next->y) // If horizontal line { // Find middle nodes with same y value, and delete them while (NextNext != NULL && Next->y == NextNext->y) { deleteNode(head, Next); // Update Next and NextNext for next iteration Next = NextNext; NextNext = NextNext->next; } } else // Adjacent points must have either same x or same y { puts("Given linked list is not valid"); return NULL; } // Recur for next segment deleteMiddle(head->next); return head;} // Driver program to test above functionsint main(){ Node *head = NULL; push(&head, 40,5); push(&head, 20,5); push(&head, 10,5); push(&head, 10,8); push(&head, 10,10); push(&head, 3,10); push(&head, 1,10); push(&head, 0,10); cout << "Given Linked List: \n"; printList(head); if (deleteMiddle(head) != NULL); { cout << "Modified Linked List: \n"; printList(head); } return 0;}// This is code is contributed by rathbhupendra // C program to remove intermediate points in a linked list// that represents horizontal and vertical line segments#include <stdio.h>#include <stdlib.h> // Node has 3 fields including x, y coordinates and a pointer// to next nodestruct Node{ int x, y; struct Node *next;}; /* Function to insert a node at the beginning */void push(struct Node ** head_ref, int x,int y){ struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); new_node->x = x; new_node->y = y; new_node->next = (*head_ref); (*head_ref) = new_node;} /* Utility function to print a singly linked list */void printList(struct Node *head){ struct Node *temp = head; while (temp != NULL) { printf("(%d,%d)-> ", temp->x,temp->y); temp = temp->next; } printf("\n"); } // Utility function to remove Next from linked list// and link nodes after it to headvoid deleteNode(struct Node *head, struct Node *Next){ head->next = Next->next; Next->next = NULL; free(Next);} // This function deletes middle nodes in a sequence of// horizontal and vertical line segments represented by// linked list.struct Node* deleteMiddle(struct Node *head){ // If only one node or no node...Return back if (head==NULL || head->next ==NULL || head->next->next==NULL) return head; struct Node* Next = head->next; struct Node *NextNext = Next->next ; // Check if this is a vertical line or horizontal line if (head->x == Next->x) { // Find middle nodes with same x value, and delete them while (NextNext !=NULL && Next->x==NextNext->x) { deleteNode(head, Next); // Update Next and NextNext for next iteration Next = NextNext; NextNext = NextNext->next; } } else if (head->y==Next->y) // If horizontal line { // Find middle nodes with same y value, and delete them while (NextNext !=NULL && Next->y==NextNext->y) { deleteNode(head, Next); // Update Next and NextNext for next iteration Next = NextNext; NextNext = NextNext->next; } } else // Adjacent points must have either same x or same y { puts("Given linked list is not valid"); return NULL; } // Recur for next segment deleteMiddle(head->next); return head;} // Driver program to test above functionsint main(){ struct Node *head = NULL; push(&head, 40,5); push(&head, 20,5); push(&head, 10,5); push(&head, 10,8); push(&head, 10,10); push(&head, 3,10); push(&head, 1,10); push(&head, 0,10); printf("Given Linked List: \n"); printList(head); if (deleteMiddle(head) != NULL); { printf("Modified Linked List: \n"); printList(head); } return 0;} // Java program to remove middle points in a linked list of// line segments,class LinkedList{ Node head; // head of list /* Linked list Node*/ class Node { int x,y; Node next; Node(int x, int y) { this.x = x; this.y = y; next = null; } } // This function deletes middle nodes in a sequence of // horizontal and vertical line segments represented // by linked list. Node deleteMiddle() { // If only one node or no node...Return back if (head == null || head.next == null || head.next.next == null) return head; Node Next = head.next; Node NextNext = Next.next; // check if this is vertical or horizontal line if (head.x == Next.x) { // Find middle nodes with same value as x and // delete them. while (NextNext != null && Next.x == NextNext.x) { head.next = Next.next; Next.next = null; // Update NextNext for the next iteration Next = NextNext; NextNext = NextNext.next; } } // if horizontal else if (head.y == Next.y) { // find middle nodes with same value as y and // delete them while (NextNext != null && Next.y == NextNext.y) { head.next = Next.next; Next.next = null; // Update NextNext for the next iteration Next = NextNext; NextNext = NextNext.next; } } // Adjacent points should have same x or same y else { System.out.println("Given list is not valid"); return null; } // recur for other segment // temporarily store the head and move head forward. Node temp = head; head = head.next; // call deleteMiddle() for next segment this.deleteMiddle(); // restore head head = temp; // return the head return head; } /* Given a reference (pointer to pointer) to the head of a list and an int, push a new node on the front of the list. */ void push(int x, int y) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(x,y); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } void printList() { Node temp = head; while (temp != null) { System.out.print("("+temp.x+","+temp.y+")->"); temp = temp.next; } System.out.println(); } /* Driver program to test above functions */ public static void main(String args[]) { LinkedList llist = new LinkedList(); llist.push(40,5); llist.push(20,5); llist.push(10,5); llist.push(10,8); llist.push(10,10); llist.push(3,10); llist.push(1,10); llist.push(0,10); System.out.println("Given list"); llist.printList(); if (llist.deleteMiddle() != null) { System.out.println("Modified Linked List is"); llist.printList(); } }} /* This code is contributed by Rajat Mishra */ # Python program to remove middle points in a linked list of# line segments,class LinkedList(object): def __init__(self): self.head = None # Linked list Node class Node(object): def __init__(self, x, y): self.x = x self.y = y self.next = None # This function deletes middle nodes in a sequence of # horizontal and vertical line segments represented # by linked list. def deleteMiddle(self): # If only one node or no node...Return back if self.head == None or self.head.next == None or self.head.next.next == None: return self.head Next = self.head.next NextNext = Next.next # check if this is vertical or horizontal line if self.head.x == Next.x: # Find middle nodes with same value as x and # delete them. while NextNext != None and Next.x == NextNext.x: self.head.next = Next.next Next.next = None # Update NextNext for the next iteration Next = NextNext NextNext = NextNext.next elif self.head.y == Next.y: # find middle nodes with same value as y and # delete them while NextNext != None and Next.y == NextNext.y: self.head.next = Next.next Next.next = None # Update NextNext for the next iteration Next = NextNext NextNext = NextNext.next else: # Adjacent points should have same x or same y print ("Given list is not valid") return None # recur for other segment # temporarily store the head and move head forward. temp = self.head self.head = self.head.next # call deleteMiddle() for next segment self.deleteMiddle() # restore head self.head = temp # return the head return self.head # Given a reference (pointer to pointer) to the head # of a list and an int, push a new node on the front # of the list. def push(self, x, y): # 1 & 2: Allocate the Node & # Put in the data new_node = self.Node(x, y) # 3. Make next of new Node as head new_node.next = self.head # 4. Move the head to point to new Node self.head = new_node def printList(self): temp = self.head while temp != None: print ("(" + str(temp.x) + "," + str(temp.y) + ")->",end=" ") temp = temp.next print () # Driver programllist = LinkedList()llist.push(40,5)llist.push(20,5)llist.push(10,5)llist.push(10,8)llist.push(10,10)llist.push(3,10)llist.push(1,10)llist.push(0,10) print ("Given list")llist.printList() if llist.deleteMiddle() != None: print ("Modified Linked List is") llist.printList() # This code is contributed by BHAVYA JAIN // C# program to remove middle// points in a linked list of// line segments,using System; public class LinkedList{ Node head; // head of list /* Linked list Node*/ class Node { public int x,y; public Node next; public Node(int x, int y) { this.x = x; this.y = y; next = null; } } // This function deletes middle // nodes in a sequence of horizontal and // vertical line segments represented // by linked list. Node deleteMiddle() { // If only one node or no node...Return back if (head == null || head.next == null || head.next.next == null) return head; Node Next = head.next; Node NextNext = Next.next; // check if this is vertical or horizontal line if (head.x == Next.x) { // Find middle nodes with same // value as x and delete them. while (NextNext != null && Next.x == NextNext.x) { head.next = Next.next; Next.next = null; // Update NextNext for // the next iteration Next = NextNext; NextNext = NextNext.next; } } // if horizontal else if (head.y == Next.y) { // find middle nodes with same // value as y and delete them while (NextNext != null && Next.y == NextNext.y) { head.next = Next.next; Next.next = null; // Update NextNext for the next iteration Next = NextNext; NextNext = NextNext.next; } } // Adjacent points should have same x or same y else { Console.WriteLine("Given list is not valid"); return null; } // recur for other segment // temporarily store the // head and move head forward. Node temp = head; head = head.next; // call deleteMiddle() for next segment this.deleteMiddle(); // restore head head = temp; // return the head return head; } /* Given a reference (pointer to pointer) to the head of a list and an int, push a new node on the front of the list. */ void push(int x, int y) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(x,y); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } void printList() { Node temp = head; while (temp != null) { Console.Write("("+temp.x + "," + temp.y + ")->"); temp = temp.next; } Console.WriteLine(); } /* Driver code */ public static void Main(String []args) { LinkedList llist = new LinkedList(); llist.push(40,5); llist.push(20,5); llist.push(10,5); llist.push(10,8); llist.push(10,10); llist.push(3,10); llist.push(1,10); llist.push(0,10); Console.WriteLine("Given list"); llist.printList(); if (llist.deleteMiddle() != null) { Console.WriteLine("Modified Linked List is"); llist.printList(); } }} // This code is contributed by Rajput-Ji <script> // Javascript program to remove middle// points in a linked list of// line segments,var head; // head of list /* Linked list Node */ class Node { constructor(x , y) { this.x = x; this.y = y; this.next = null; } } // This function deletes middle // nodes in a sequence of // horizontal and vertical line // segments represented // by linked list. function deleteMiddle() { // If only one node or no // node...Return back if (head == null || head.next == null || head.next.next == null) return head; var Next = head.next;var NextNext = Next.next; // check if this is vertical or // horizontal line if (head.x == Next.x) { // Find middle nodes with same // value as x and // delete them. while (NextNext != null && Next.x == NextNext.x) { head.next = Next.next; Next.next = null; // Update NextNext for the next iteration Next = NextNext; NextNext = NextNext.next; } } // if horizontal else if (head.y == Next.y) { // find middle nodes with same value as y and // delete them while (NextNext != null && Next.y == NextNext.y) { head.next = Next.next; Next.next = null; // Update NextNext for the next iteration Next = NextNext; NextNext = NextNext.next; } } // Adjacent points should have same x or same y else { document.write("Given list is not valid"); return null; } // recur for other segment // temporarily store the head and move head forward.var temp = head; head = head.next; // call deleteMiddle() for next segment this.deleteMiddle(); // restore head head = temp; // return the head return head; } /* Given a reference (pointer to pointer) to the head of a list and an int, push a new node on the front of the list. */ function push(x , y) { /* 1 & 2: Allocate the Node & Put in the data */var new_node = new Node(x, y); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } function printList() {var temp = head; while (temp != null) { document.write("(" + temp.x + "," + temp.y + ")->"); temp = temp.next; } document.write("<br/>"); } /* Driver program to test above functions */ push(40, 5); push(20, 5); push(10, 5); push(10, 8); push(10, 10); push(3, 10); push(1, 10); push(0, 10); document.write("Given list<br/>"); printList(); if (deleteMiddle() != null) { document.write("Modified Linked List is<br/>"); printList(); } // This code contributed by gauravrajput1 </script> Given Linked List: (0,10)-> (1,10)-> (3,10)-> (10,10)-> (10,8)-> (10,5)-> (20,5)-> (40,5)-> Modified Linked List: (0,10)-> (10,10)-> (10,5)-> (40,5)-> Time Complexity of the above solution is O(n) where n is a number of nodes in the given linked list. Exercise: The above code is recursive, write an iterative code for the same problem. Please see below for the solution.Iterative approach for removing middle points in a linked list of line segments Rajput-Ji rathbhupendra nidhi_biet GauravRajput1 sooda367 ruhelaa48 simranarora5sos amartyaghoshgfg hardikkoriintern Linked List Linked List Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. LinkedList in Java Doubly Linked List | Set 1 (Introduction and Insertion) Introduction to Data Structures Detect loop in a linked list Merge two sorted linked lists Find the middle of a given linked list Linked List vs Array What is Data Structure: Types, Classifications and Applications Merge Sort for Linked Lists Add two numbers represented by linked lists | Set 1
[ { "code": null, "e": 54, "s": 26, "text": "\n24 Jun, 2022" }, { "code": null, "e": 254, "s": 54, "text": "Given a linked list of coordinates where adjacent points either form a vertical line or a horizontal line. Delete points from the linked list which are in the middle of a horizontal or vertical line." }, { "code": null, "e": 265, "s": 254, "text": "Examples: " }, { "code": null, "e": 886, "s": 265, "text": "Input: (0,10)->(1,10)->(5,10)->(7,10)\n |\n (7,5)->(20,5)->(40,5)\nOutput: Linked List should be changed to following\n (0,10)->(7,10)\n |\n (7,5)->(40,5) \nThe given linked list represents a horizontal line from (0,10) \nto (7, 10) followed by a vertical line from (7, 10) to (7, 5), \nfollowed by a horizontal line from (7, 5) to (40, 5).\n\nInput: (2,3)->(4,3)->(6,3)->(10,3)->(12,3)\nOutput: Linked List should be changed to following\n (2,3)->(12,3) \nThere is only one vertical line, so all middle points are removed." }, { "code": null, "e": 925, "s": 886, "text": "Source: Microsoft Interview Experience" }, { "code": null, "e": 1196, "s": 925, "text": "The idea is to keep track of the current node, next node, and next-next node. While the next node is the same as the next-next node, keep deleting the next node. In this complete procedure, we need to keep an eye on the shifting of pointers and checking for NULL values." }, { "code": null, "e": 1246, "s": 1196, "text": "Following are implementations of the above idea. " }, { "code": null, "e": 1250, "s": 1246, "text": "C++" }, { "code": null, "e": 1252, "s": 1250, "text": "C" }, { "code": null, "e": 1257, "s": 1252, "text": "Java" }, { "code": null, "e": 1265, "s": 1257, "text": "Python3" }, { "code": null, "e": 1268, "s": 1265, "text": "C#" }, { "code": null, "e": 1279, "s": 1268, "text": "Javascript" }, { "code": "// C++ program to remove intermediate points// in a linked list that represents horizontal// and vertical line segments#include <bits/stdc++.h>using namespace std; // Node has 3 fields including x, y// coordinates and a pointer// to next nodeclass Node{ public: int x, y; Node *next;}; /* Function to insert a node at the beginning */void push(Node ** head_ref, int x,int y){ Node* new_node =new Node(); new_node->x = x; new_node->y = y; new_node->next = (*head_ref); (*head_ref) = new_node;} /* Utility function to print a singly linked list */void printList(Node *head){ Node *temp = head; while (temp != NULL) { cout << \"(\" << temp->x << \",\" << temp->y << \")-> \"; temp = temp->next; } cout<<endl; } // Utility function to remove Next from linked list// and link nodes after it to headvoid deleteNode(Node *head, Node *Next){ head->next = Next->next; Next->next = NULL; free(Next);} // This function deletes middle nodes in a sequence of// horizontal and vertical line segments represented by// linked list.Node* deleteMiddle(Node *head){ // If only one node or no node...Return back if (head == NULL || head->next == NULL || head->next->next == NULL) return head; Node* Next = head->next; Node *NextNext = Next->next ; // Check if this is a vertical line or horizontal line if (head->x == Next->x) { // Find middle nodes with same x value, and delete them while (NextNext != NULL && Next->x == NextNext->x) { deleteNode(head, Next); // Update Next and NextNext for next iteration Next = NextNext; NextNext = NextNext->next; } } else if (head->y==Next->y) // If horizontal line { // Find middle nodes with same y value, and delete them while (NextNext != NULL && Next->y == NextNext->y) { deleteNode(head, Next); // Update Next and NextNext for next iteration Next = NextNext; NextNext = NextNext->next; } } else // Adjacent points must have either same x or same y { puts(\"Given linked list is not valid\"); return NULL; } // Recur for next segment deleteMiddle(head->next); return head;} // Driver program to test above functionsint main(){ Node *head = NULL; push(&head, 40,5); push(&head, 20,5); push(&head, 10,5); push(&head, 10,8); push(&head, 10,10); push(&head, 3,10); push(&head, 1,10); push(&head, 0,10); cout << \"Given Linked List: \\n\"; printList(head); if (deleteMiddle(head) != NULL); { cout << \"Modified Linked List: \\n\"; printList(head); } return 0;}// This is code is contributed by rathbhupendra", "e": 4057, "s": 1279, "text": null }, { "code": "// C program to remove intermediate points in a linked list// that represents horizontal and vertical line segments#include <stdio.h>#include <stdlib.h> // Node has 3 fields including x, y coordinates and a pointer// to next nodestruct Node{ int x, y; struct Node *next;}; /* Function to insert a node at the beginning */void push(struct Node ** head_ref, int x,int y){ struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); new_node->x = x; new_node->y = y; new_node->next = (*head_ref); (*head_ref) = new_node;} /* Utility function to print a singly linked list */void printList(struct Node *head){ struct Node *temp = head; while (temp != NULL) { printf(\"(%d,%d)-> \", temp->x,temp->y); temp = temp->next; } printf(\"\\n\"); } // Utility function to remove Next from linked list// and link nodes after it to headvoid deleteNode(struct Node *head, struct Node *Next){ head->next = Next->next; Next->next = NULL; free(Next);} // This function deletes middle nodes in a sequence of// horizontal and vertical line segments represented by// linked list.struct Node* deleteMiddle(struct Node *head){ // If only one node or no node...Return back if (head==NULL || head->next ==NULL || head->next->next==NULL) return head; struct Node* Next = head->next; struct Node *NextNext = Next->next ; // Check if this is a vertical line or horizontal line if (head->x == Next->x) { // Find middle nodes with same x value, and delete them while (NextNext !=NULL && Next->x==NextNext->x) { deleteNode(head, Next); // Update Next and NextNext for next iteration Next = NextNext; NextNext = NextNext->next; } } else if (head->y==Next->y) // If horizontal line { // Find middle nodes with same y value, and delete them while (NextNext !=NULL && Next->y==NextNext->y) { deleteNode(head, Next); // Update Next and NextNext for next iteration Next = NextNext; NextNext = NextNext->next; } } else // Adjacent points must have either same x or same y { puts(\"Given linked list is not valid\"); return NULL; } // Recur for next segment deleteMiddle(head->next); return head;} // Driver program to test above functionsint main(){ struct Node *head = NULL; push(&head, 40,5); push(&head, 20,5); push(&head, 10,5); push(&head, 10,8); push(&head, 10,10); push(&head, 3,10); push(&head, 1,10); push(&head, 0,10); printf(\"Given Linked List: \\n\"); printList(head); if (deleteMiddle(head) != NULL); { printf(\"Modified Linked List: \\n\"); printList(head); } return 0;}", "e": 6855, "s": 4057, "text": null }, { "code": "// Java program to remove middle points in a linked list of// line segments,class LinkedList{ Node head; // head of list /* Linked list Node*/ class Node { int x,y; Node next; Node(int x, int y) { this.x = x; this.y = y; next = null; } } // This function deletes middle nodes in a sequence of // horizontal and vertical line segments represented // by linked list. Node deleteMiddle() { // If only one node or no node...Return back if (head == null || head.next == null || head.next.next == null) return head; Node Next = head.next; Node NextNext = Next.next; // check if this is vertical or horizontal line if (head.x == Next.x) { // Find middle nodes with same value as x and // delete them. while (NextNext != null && Next.x == NextNext.x) { head.next = Next.next; Next.next = null; // Update NextNext for the next iteration Next = NextNext; NextNext = NextNext.next; } } // if horizontal else if (head.y == Next.y) { // find middle nodes with same value as y and // delete them while (NextNext != null && Next.y == NextNext.y) { head.next = Next.next; Next.next = null; // Update NextNext for the next iteration Next = NextNext; NextNext = NextNext.next; } } // Adjacent points should have same x or same y else { System.out.println(\"Given list is not valid\"); return null; } // recur for other segment // temporarily store the head and move head forward. Node temp = head; head = head.next; // call deleteMiddle() for next segment this.deleteMiddle(); // restore head head = temp; // return the head return head; } /* Given a reference (pointer to pointer) to the head of a list and an int, push a new node on the front of the list. */ void push(int x, int y) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(x,y); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } void printList() { Node temp = head; while (temp != null) { System.out.print(\"(\"+temp.x+\",\"+temp.y+\")->\"); temp = temp.next; } System.out.println(); } /* Driver program to test above functions */ public static void main(String args[]) { LinkedList llist = new LinkedList(); llist.push(40,5); llist.push(20,5); llist.push(10,5); llist.push(10,8); llist.push(10,10); llist.push(3,10); llist.push(1,10); llist.push(0,10); System.out.println(\"Given list\"); llist.printList(); if (llist.deleteMiddle() != null) { System.out.println(\"Modified Linked List is\"); llist.printList(); } }} /* This code is contributed by Rajat Mishra */", "e": 10246, "s": 6855, "text": null }, { "code": "# Python program to remove middle points in a linked list of# line segments,class LinkedList(object): def __init__(self): self.head = None # Linked list Node class Node(object): def __init__(self, x, y): self.x = x self.y = y self.next = None # This function deletes middle nodes in a sequence of # horizontal and vertical line segments represented # by linked list. def deleteMiddle(self): # If only one node or no node...Return back if self.head == None or self.head.next == None or self.head.next.next == None: return self.head Next = self.head.next NextNext = Next.next # check if this is vertical or horizontal line if self.head.x == Next.x: # Find middle nodes with same value as x and # delete them. while NextNext != None and Next.x == NextNext.x: self.head.next = Next.next Next.next = None # Update NextNext for the next iteration Next = NextNext NextNext = NextNext.next elif self.head.y == Next.y: # find middle nodes with same value as y and # delete them while NextNext != None and Next.y == NextNext.y: self.head.next = Next.next Next.next = None # Update NextNext for the next iteration Next = NextNext NextNext = NextNext.next else: # Adjacent points should have same x or same y print (\"Given list is not valid\") return None # recur for other segment # temporarily store the head and move head forward. temp = self.head self.head = self.head.next # call deleteMiddle() for next segment self.deleteMiddle() # restore head self.head = temp # return the head return self.head # Given a reference (pointer to pointer) to the head # of a list and an int, push a new node on the front # of the list. def push(self, x, y): # 1 & 2: Allocate the Node & # Put in the data new_node = self.Node(x, y) # 3. Make next of new Node as head new_node.next = self.head # 4. Move the head to point to new Node self.head = new_node def printList(self): temp = self.head while temp != None: print (\"(\" + str(temp.x) + \",\" + str(temp.y) + \")->\",end=\" \") temp = temp.next print () # Driver programllist = LinkedList()llist.push(40,5)llist.push(20,5)llist.push(10,5)llist.push(10,8)llist.push(10,10)llist.push(3,10)llist.push(1,10)llist.push(0,10) print (\"Given list\")llist.printList() if llist.deleteMiddle() != None: print (\"Modified Linked List is\") llist.printList() # This code is contributed by BHAVYA JAIN", "e": 13124, "s": 10246, "text": null }, { "code": "// C# program to remove middle// points in a linked list of// line segments,using System; public class LinkedList{ Node head; // head of list /* Linked list Node*/ class Node { public int x,y; public Node next; public Node(int x, int y) { this.x = x; this.y = y; next = null; } } // This function deletes middle // nodes in a sequence of horizontal and // vertical line segments represented // by linked list. Node deleteMiddle() { // If only one node or no node...Return back if (head == null || head.next == null || head.next.next == null) return head; Node Next = head.next; Node NextNext = Next.next; // check if this is vertical or horizontal line if (head.x == Next.x) { // Find middle nodes with same // value as x and delete them. while (NextNext != null && Next.x == NextNext.x) { head.next = Next.next; Next.next = null; // Update NextNext for // the next iteration Next = NextNext; NextNext = NextNext.next; } } // if horizontal else if (head.y == Next.y) { // find middle nodes with same // value as y and delete them while (NextNext != null && Next.y == NextNext.y) { head.next = Next.next; Next.next = null; // Update NextNext for the next iteration Next = NextNext; NextNext = NextNext.next; } } // Adjacent points should have same x or same y else { Console.WriteLine(\"Given list is not valid\"); return null; } // recur for other segment // temporarily store the // head and move head forward. Node temp = head; head = head.next; // call deleteMiddle() for next segment this.deleteMiddle(); // restore head head = temp; // return the head return head; } /* Given a reference (pointer to pointer) to the head of a list and an int, push a new node on the front of the list. */ void push(int x, int y) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(x,y); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } void printList() { Node temp = head; while (temp != null) { Console.Write(\"(\"+temp.x + \",\" + temp.y + \")->\"); temp = temp.next; } Console.WriteLine(); } /* Driver code */ public static void Main(String []args) { LinkedList llist = new LinkedList(); llist.push(40,5); llist.push(20,5); llist.push(10,5); llist.push(10,8); llist.push(10,10); llist.push(3,10); llist.push(1,10); llist.push(0,10); Console.WriteLine(\"Given list\"); llist.printList(); if (llist.deleteMiddle() != null) { Console.WriteLine(\"Modified Linked List is\"); llist.printList(); } }} // This code is contributed by Rajput-Ji", "e": 16573, "s": 13124, "text": null }, { "code": "<script> // Javascript program to remove middle// points in a linked list of// line segments,var head; // head of list /* Linked list Node */ class Node { constructor(x , y) { this.x = x; this.y = y; this.next = null; } } // This function deletes middle // nodes in a sequence of // horizontal and vertical line // segments represented // by linked list. function deleteMiddle() { // If only one node or no // node...Return back if (head == null || head.next == null || head.next.next == null) return head; var Next = head.next;var NextNext = Next.next; // check if this is vertical or // horizontal line if (head.x == Next.x) { // Find middle nodes with same // value as x and // delete them. while (NextNext != null && Next.x == NextNext.x) { head.next = Next.next; Next.next = null; // Update NextNext for the next iteration Next = NextNext; NextNext = NextNext.next; } } // if horizontal else if (head.y == Next.y) { // find middle nodes with same value as y and // delete them while (NextNext != null && Next.y == NextNext.y) { head.next = Next.next; Next.next = null; // Update NextNext for the next iteration Next = NextNext; NextNext = NextNext.next; } } // Adjacent points should have same x or same y else { document.write(\"Given list is not valid\"); return null; } // recur for other segment // temporarily store the head and move head forward.var temp = head; head = head.next; // call deleteMiddle() for next segment this.deleteMiddle(); // restore head head = temp; // return the head return head; } /* Given a reference (pointer to pointer) to the head of a list and an int, push a new node on the front of the list. */ function push(x , y) { /* 1 & 2: Allocate the Node & Put in the data */var new_node = new Node(x, y); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } function printList() {var temp = head; while (temp != null) { document.write(\"(\" + temp.x + \",\" + temp.y + \")->\"); temp = temp.next; } document.write(\"<br/>\"); } /* Driver program to test above functions */ push(40, 5); push(20, 5); push(10, 5); push(10, 8); push(10, 10); push(3, 10); push(1, 10); push(0, 10); document.write(\"Given list<br/>\"); printList(); if (deleteMiddle() != null) { document.write(\"Modified Linked List is<br/>\"); printList(); } // This code contributed by gauravrajput1 </script>", "e": 19756, "s": 16573, "text": null }, { "code": null, "e": 19912, "s": 19756, "text": "Given Linked List: \n(0,10)-> (1,10)-> (3,10)-> (10,10)-> (10,8)-> (10,5)-> (20,5)-> (40,5)-> \nModified Linked List: \n(0,10)-> (10,10)-> (10,5)-> (40,5)-> \n" }, { "code": null, "e": 20013, "s": 19912, "text": "Time Complexity of the above solution is O(n) where n is a number of nodes in the given linked list." }, { "code": null, "e": 20024, "s": 20013, "text": "Exercise: " }, { "code": null, "e": 20214, "s": 20024, "text": "The above code is recursive, write an iterative code for the same problem. Please see below for the solution.Iterative approach for removing middle points in a linked list of line segments " }, { "code": null, "e": 20224, "s": 20214, "text": "Rajput-Ji" }, { "code": null, "e": 20238, "s": 20224, "text": "rathbhupendra" }, { "code": null, "e": 20249, "s": 20238, "text": "nidhi_biet" }, { "code": null, "e": 20263, "s": 20249, "text": "GauravRajput1" }, { "code": null, "e": 20272, "s": 20263, "text": "sooda367" }, { "code": null, "e": 20282, "s": 20272, "text": "ruhelaa48" }, { "code": null, "e": 20298, "s": 20282, "text": "simranarora5sos" }, { "code": null, "e": 20314, "s": 20298, "text": "amartyaghoshgfg" }, { "code": null, "e": 20331, "s": 20314, "text": "hardikkoriintern" }, { "code": null, "e": 20343, "s": 20331, "text": "Linked List" }, { "code": null, "e": 20355, "s": 20343, "text": "Linked List" }, { "code": null, "e": 20453, "s": 20355, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 20472, "s": 20453, "text": "LinkedList in Java" }, { "code": null, "e": 20528, "s": 20472, "text": "Doubly Linked List | Set 1 (Introduction and Insertion)" }, { "code": null, "e": 20560, "s": 20528, "text": "Introduction to Data Structures" }, { "code": null, "e": 20589, "s": 20560, "text": "Detect loop in a linked list" }, { "code": null, "e": 20619, "s": 20589, "text": "Merge two sorted linked lists" }, { "code": null, "e": 20658, "s": 20619, "text": "Find the middle of a given linked list" }, { "code": null, "e": 20679, "s": 20658, "text": "Linked List vs Array" }, { "code": null, "e": 20743, "s": 20679, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 20771, "s": 20743, "text": "Merge Sort for Linked Lists" } ]
React native SectionList Component
01 Aug, 2021 The SectionList Component is an inbuilt React Native list view component that renders sectioned lists. As the name suggests, it is used to display lists of data in different sections. It is a Pure Component supporting most of the features like pull-to-refresh, scroll loading, separators, headers, and footers, etc. SectionLists are primarily used for displaying lists in sections. In the case that section support is not required, a FlatList or ScrollView Component should be used. Syntax: <SectionList sections={} renderItem={} /> SectionList Props: renderItem: (required) It is a react element that is used as the default renderer for displaying the items in the different sections of the list. sections: (required) It is an array of data (with different objects for different sections) that is to be rendered. extraData: It is a property that informs the list to re-render (since it implements PureComponent). initialNumToRender: It is the number of items to be rendered when the screen is loaded initially. inverted: If set to true, it will reverse the direction of the scroll. ItemSeparatorComponent: It is a component that will be rendered between every item (except at the top or the bottom). keyExtractor: It is used to extract a unique key for a particular item in the list. ListEmptyComponent: It can be a component or react element that is rendered in case of an empty list. ListFooterComponent: It can be a component or react element that is rendered at the end of the list. ListHeaderComponent: It can be a component or react element that is rendered at the start of the list. onEndReached: It is a callback called when the scroll position reaches the onEndReachedThreshold. onEndReachedThreshold: It is a value that tells exactly how far the bottom of the list should be from the screen end so as to trigger the onEndReached. onRefresh: If it is given, a RefreshControl will be inserted to the “Pull to Refresh” functionality. onViewableItemsChanged: It is a function that is called during changes in the row viewability. refreshing: It is set as true when the screen is refreshed when waiting for new data. renderSectionFooter: It is rendered at the bottom of every section. renderSectionHeader: It is rendered at the top of every section. SectionSeparatorComponent: It is rendered at the top and bottom of every section to distinguish them from each other. stickySectionHeadersEnabled: It is used to make section headers stick to the top of the screen. SectionList Methods: flashScrollIndicators(): It is used to show the scroll indicators for a brief moment. recordInteraction(): It is used to inform the list about any interaction that might have occurred. scrollToLocation(): It is used to scroll to the item at any specified sectionIndex and itemIndex. Installation: Here we will use the Expo CLI version that will much smoother to run your React Native applications. Follow the below steps one by one to setup your React native environment. Step 1: Open your terminal and install expo-cli by the following command.npm install -g expo-cli Step 1: Open your terminal and install expo-cli by the following command. npm install -g expo-cli Step 2: Now create a project by the following command.expo init sectionlist-demo Step 2: Now create a project by the following command. expo init sectionlist-demo Step 3: Now go into your project folder i.e. sectionlist-democd sectionlist-demo Step 3: Now go into your project folder i.e. sectionlist-demo cd sectionlist-demo Project Structure: It will look like this: Example: In this example, we will see how to use basic SectionList Component. App.js import React, { Component } from "react";import { Text, View, StyleSheet, SectionList } from "react-native";import { Icon } from "react-native-elements"; class App extends Component { state = { data: [ { title: "Operating System", data: [ "Processes & Threads", "Memory Management", "CPU Scheduling", "Process Synchronization", "Deadlock", ], }, { title: "Computer Network", data: [ "Data Link Layer", "Network Layer", "Transport Layer", "Application Layer", "Network Security", ], }, { title: "DBMS", data: [ "Entity Relationship Model", "Normalisation", "Transaction and Concurrency Control", "Indexing, B and B+ trees", "File Organization", ], }, ], }; render() { return ( <View style={styles.screen}> // Using Section List <SectionList sections={this.state.data} keyExtractor={(item, index) => item + index} renderItem={({ item }) => ( <View style={styles.row}> <Text style={styles.rowText}>{item}</Text> <Icon name="ios-eye" type="ionicon" color="#C2185B" /> </View> )} renderSectionHeader={({ section: { title } }) => ( <Text style={styles.header}>{title}</Text> )} /> </View> ); }} // Screen stylesconst styles = StyleSheet.create({ screen: { marginTop: 18, }, header: { fontSize: 30, color: "#FFF", marginTop: 10, padding: 2, backgroundColor: "#C2185B", textAlign: "center", }, row: { marginHorizontal: 15, marginTop: 10, flexDirection: "row", justifyContent: "space-between", alignItems: "center", paddingHorizontal: 2, }, rowText: { fontSize: 18, },}); export default App; Step to run the application: Start the server by using the following command. npm run android Output: If your emulator did not open automatically then you need to do it manually. First, go to your android studio and run the emulator. Now start the server again. Reference: https://reactnative.dev/docs/sectionlist Picked React-Native Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Aug, 2021" }, { "code": null, "e": 511, "s": 28, "text": "The SectionList Component is an inbuilt React Native list view component that renders sectioned lists. As the name suggests, it is used to display lists of data in different sections. It is a Pure Component supporting most of the features like pull-to-refresh, scroll loading, separators, headers, and footers, etc. SectionLists are primarily used for displaying lists in sections. In the case that section support is not required, a FlatList or ScrollView Component should be used." }, { "code": null, "e": 519, "s": 511, "text": "Syntax:" }, { "code": null, "e": 573, "s": 519, "text": "<SectionList\n sections={}\n renderItem={}\n/>" }, { "code": null, "e": 592, "s": 573, "text": "SectionList Props:" }, { "code": null, "e": 738, "s": 592, "text": "renderItem: (required) It is a react element that is used as the default renderer for displaying the items in the different sections of the list." }, { "code": null, "e": 854, "s": 738, "text": "sections: (required) It is an array of data (with different objects for different sections) that is to be rendered." }, { "code": null, "e": 954, "s": 854, "text": "extraData: It is a property that informs the list to re-render (since it implements PureComponent)." }, { "code": null, "e": 1052, "s": 954, "text": "initialNumToRender: It is the number of items to be rendered when the screen is loaded initially." }, { "code": null, "e": 1123, "s": 1052, "text": "inverted: If set to true, it will reverse the direction of the scroll." }, { "code": null, "e": 1241, "s": 1123, "text": "ItemSeparatorComponent: It is a component that will be rendered between every item (except at the top or the bottom)." }, { "code": null, "e": 1325, "s": 1241, "text": "keyExtractor: It is used to extract a unique key for a particular item in the list." }, { "code": null, "e": 1427, "s": 1325, "text": "ListEmptyComponent: It can be a component or react element that is rendered in case of an empty list." }, { "code": null, "e": 1528, "s": 1427, "text": "ListFooterComponent: It can be a component or react element that is rendered at the end of the list." }, { "code": null, "e": 1631, "s": 1528, "text": "ListHeaderComponent: It can be a component or react element that is rendered at the start of the list." }, { "code": null, "e": 1729, "s": 1631, "text": "onEndReached: It is a callback called when the scroll position reaches the onEndReachedThreshold." }, { "code": null, "e": 1881, "s": 1729, "text": "onEndReachedThreshold: It is a value that tells exactly how far the bottom of the list should be from the screen end so as to trigger the onEndReached." }, { "code": null, "e": 1982, "s": 1881, "text": "onRefresh: If it is given, a RefreshControl will be inserted to the “Pull to Refresh” functionality." }, { "code": null, "e": 2077, "s": 1982, "text": "onViewableItemsChanged: It is a function that is called during changes in the row viewability." }, { "code": null, "e": 2163, "s": 2077, "text": "refreshing: It is set as true when the screen is refreshed when waiting for new data." }, { "code": null, "e": 2231, "s": 2163, "text": "renderSectionFooter: It is rendered at the bottom of every section." }, { "code": null, "e": 2296, "s": 2231, "text": "renderSectionHeader: It is rendered at the top of every section." }, { "code": null, "e": 2414, "s": 2296, "text": "SectionSeparatorComponent: It is rendered at the top and bottom of every section to distinguish them from each other." }, { "code": null, "e": 2510, "s": 2414, "text": "stickySectionHeadersEnabled: It is used to make section headers stick to the top of the screen." }, { "code": null, "e": 2531, "s": 2510, "text": "SectionList Methods:" }, { "code": null, "e": 2617, "s": 2531, "text": "flashScrollIndicators(): It is used to show the scroll indicators for a brief moment." }, { "code": null, "e": 2716, "s": 2617, "text": "recordInteraction(): It is used to inform the list about any interaction that might have occurred." }, { "code": null, "e": 2814, "s": 2716, "text": "scrollToLocation(): It is used to scroll to the item at any specified sectionIndex and itemIndex." }, { "code": null, "e": 3003, "s": 2814, "text": "Installation: Here we will use the Expo CLI version that will much smoother to run your React Native applications. Follow the below steps one by one to setup your React native environment." }, { "code": null, "e": 3100, "s": 3003, "text": "Step 1: Open your terminal and install expo-cli by the following command.npm install -g expo-cli" }, { "code": null, "e": 3174, "s": 3100, "text": "Step 1: Open your terminal and install expo-cli by the following command." }, { "code": null, "e": 3198, "s": 3174, "text": "npm install -g expo-cli" }, { "code": null, "e": 3279, "s": 3198, "text": "Step 2: Now create a project by the following command.expo init sectionlist-demo" }, { "code": null, "e": 3334, "s": 3279, "text": "Step 2: Now create a project by the following command." }, { "code": null, "e": 3361, "s": 3334, "text": "expo init sectionlist-demo" }, { "code": null, "e": 3442, "s": 3361, "text": "Step 3: Now go into your project folder i.e. sectionlist-democd sectionlist-demo" }, { "code": null, "e": 3504, "s": 3442, "text": "Step 3: Now go into your project folder i.e. sectionlist-demo" }, { "code": null, "e": 3524, "s": 3504, "text": "cd sectionlist-demo" }, { "code": null, "e": 3567, "s": 3524, "text": "Project Structure: It will look like this:" }, { "code": null, "e": 3645, "s": 3567, "text": "Example: In this example, we will see how to use basic SectionList Component." }, { "code": null, "e": 3652, "s": 3645, "text": "App.js" }, { "code": "import React, { Component } from \"react\";import { Text, View, StyleSheet, SectionList } from \"react-native\";import { Icon } from \"react-native-elements\"; class App extends Component { state = { data: [ { title: \"Operating System\", data: [ \"Processes & Threads\", \"Memory Management\", \"CPU Scheduling\", \"Process Synchronization\", \"Deadlock\", ], }, { title: \"Computer Network\", data: [ \"Data Link Layer\", \"Network Layer\", \"Transport Layer\", \"Application Layer\", \"Network Security\", ], }, { title: \"DBMS\", data: [ \"Entity Relationship Model\", \"Normalisation\", \"Transaction and Concurrency Control\", \"Indexing, B and B+ trees\", \"File Organization\", ], }, ], }; render() { return ( <View style={styles.screen}> // Using Section List <SectionList sections={this.state.data} keyExtractor={(item, index) => item + index} renderItem={({ item }) => ( <View style={styles.row}> <Text style={styles.rowText}>{item}</Text> <Icon name=\"ios-eye\" type=\"ionicon\" color=\"#C2185B\" /> </View> )} renderSectionHeader={({ section: { title } }) => ( <Text style={styles.header}>{title}</Text> )} /> </View> ); }} // Screen stylesconst styles = StyleSheet.create({ screen: { marginTop: 18, }, header: { fontSize: 30, color: \"#FFF\", marginTop: 10, padding: 2, backgroundColor: \"#C2185B\", textAlign: \"center\", }, row: { marginHorizontal: 15, marginTop: 10, flexDirection: \"row\", justifyContent: \"space-between\", alignItems: \"center\", paddingHorizontal: 2, }, rowText: { fontSize: 18, },}); export default App;", "e": 5578, "s": 3652, "text": null }, { "code": null, "e": 5656, "s": 5578, "text": "Step to run the application: Start the server by using the following command." }, { "code": null, "e": 5672, "s": 5656, "text": "npm run android" }, { "code": null, "e": 5840, "s": 5672, "text": "Output: If your emulator did not open automatically then you need to do it manually. First, go to your android studio and run the emulator. Now start the server again." }, { "code": null, "e": 5892, "s": 5840, "text": "Reference: https://reactnative.dev/docs/sectionlist" }, { "code": null, "e": 5899, "s": 5892, "text": "Picked" }, { "code": null, "e": 5912, "s": 5899, "text": "React-Native" }, { "code": null, "e": 5929, "s": 5912, "text": "Web Technologies" } ]
Draw Colorful Spiral Web Using Turtle Graphics in Python - GeeksforGeeks
20 Oct, 2020 Prerequisite: Turtle Basics “Turtle” is a Python feature like a drawing board, which lets us command a turtle to draw all over it. This comes packed with the standard Python package and need not be installed externally. Methods used: forward(value): moves the turtle in the forward direction. turtle.Pen(): setup the turtle pen speed(value): changes the speed of the turtle width(value): set the width left(value): moves the turtle left. bgcolor(color_name): changes background-color Approach: Import turtle. Define colors using the list data structure in python. Setup a turtle pen for drawing the Spiral Web. Start making the Spiral Web according to your logic. Below is the implementation of the above approach. Python3 # import turtleimport turtle # defining colorscolors = ['red', 'yellow', 'green', 'purple', 'blue', 'orange'] # setup turtle pent= turtle.Pen() # changes the speed of the turtlet.speed(10) # changes the background colorturtle.bgcolor("black") # make spiral_webfor x in range(200): t.pencolor(colors[x%6]) # setting color t.width(x/100 + 1) # setting width t.forward(x) # moving forward t.left(59) # moving left turtle.done()t.speed(10) turtle.bgcolor("black") # changes the background color # make spiral_webfor x in range(200): t.pencolor(colors[x%6]) # setting color t.width(x/100 + 1) # setting width t.forward(x) # moving forward t.left(59) # moving left turtle.done() Output: pulkitagarwal03pulkit Python-turtle Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Check if element exists in list in Python Python | os.path.join() method Selecting rows in pandas DataFrame based on conditions Defaultdict in Python Python | Get unique values from a list Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24292, "s": 24264, "text": "\n20 Oct, 2020" }, { "code": null, "e": 24320, "s": 24292, "text": "Prerequisite: Turtle Basics" }, { "code": null, "e": 24512, "s": 24320, "text": "“Turtle” is a Python feature like a drawing board, which lets us command a turtle to draw all over it. This comes packed with the standard Python package and need not be installed externally." }, { "code": null, "e": 24526, "s": 24512, "text": "Methods used:" }, { "code": null, "e": 24585, "s": 24526, "text": "forward(value): moves the turtle in the forward direction." }, { "code": null, "e": 24620, "s": 24585, "text": "turtle.Pen(): setup the turtle pen" }, { "code": null, "e": 24666, "s": 24620, "text": "speed(value): changes the speed of the turtle" }, { "code": null, "e": 24694, "s": 24666, "text": "width(value): set the width" }, { "code": null, "e": 24730, "s": 24694, "text": "left(value): moves the turtle left." }, { "code": null, "e": 24776, "s": 24730, "text": "bgcolor(color_name): changes background-color" }, { "code": null, "e": 24786, "s": 24776, "text": "Approach:" }, { "code": null, "e": 24801, "s": 24786, "text": "Import turtle." }, { "code": null, "e": 24856, "s": 24801, "text": "Define colors using the list data structure in python." }, { "code": null, "e": 24903, "s": 24856, "text": "Setup a turtle pen for drawing the Spiral Web." }, { "code": null, "e": 24958, "s": 24903, "text": "Start making the Spiral Web according to your logic. " }, { "code": null, "e": 25009, "s": 24958, "text": "Below is the implementation of the above approach." }, { "code": null, "e": 25017, "s": 25009, "text": "Python3" }, { "code": "# import turtleimport turtle # defining colorscolors = ['red', 'yellow', 'green', 'purple', 'blue', 'orange'] # setup turtle pent= turtle.Pen() # changes the speed of the turtlet.speed(10) # changes the background colorturtle.bgcolor(\"black\") # make spiral_webfor x in range(200): t.pencolor(colors[x%6]) # setting color t.width(x/100 + 1) # setting width t.forward(x) # moving forward t.left(59) # moving left turtle.done()t.speed(10) turtle.bgcolor(\"black\") # changes the background color # make spiral_webfor x in range(200): t.pencolor(colors[x%6]) # setting color t.width(x/100 + 1) # setting width t.forward(x) # moving forward t.left(59) # moving left turtle.done()", "e": 25714, "s": 25017, "text": null }, { "code": null, "e": 25725, "s": 25717, "text": "Output:" }, { "code": null, "e": 25751, "s": 25729, "text": "pulkitagarwal03pulkit" }, { "code": null, "e": 25765, "s": 25751, "text": "Python-turtle" }, { "code": null, "e": 25772, "s": 25765, "text": "Python" }, { "code": null, "e": 25870, "s": 25772, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25902, "s": 25870, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 25944, "s": 25902, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26000, "s": 25944, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26042, "s": 26000, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26073, "s": 26042, "text": "Python | os.path.join() method" }, { "code": null, "e": 26128, "s": 26073, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 26150, "s": 26128, "text": "Defaultdict in Python" }, { "code": null, "e": 26189, "s": 26150, "text": "Python | Get unique values from a list" }, { "code": null, "e": 26218, "s": 26189, "text": "Create a directory in Python" } ]
Angle Between Hands of a Clock in C++
Suppose we have two numbers, hour and minutes. We have to find a smaller angle (in sexagesimal units) formed between the hour and the minute hand. So if the input is like hour = 12 and min := 30, then the result will be 165°. To solve this, we will follow these steps − if h = 12, then set h := 0 if h = 12, then set h := 0 if m = 60, then set m := 0 if m = 60, then set m := 0 hAngle := 0.5 * (60h) + m hAngle := 0.5 * (60h) + m mAngle := 6m mAngle := 6m ret := |hAngle - mAngle| ret := |hAngle - mAngle| return minimum of ret and (360 – ret) return minimum of ret and (360 – ret) Let us see the following implementation to get better understanding − Live Demo #include <bits/stdc++.h> using namespace std; class Solution { public: double angleClock(int h, int m) { if(h == 12) h = 0; if(m == 60) m = 0; double hAngle = 0.5*((60 * h) + m); double mAngle = 6 * m; double ret = abs(hAngle - mAngle); return min(360 - ret, ret); } }; main(){ Solution ob; cout << (ob.angleClock(12, 30)); } 12 30 165.00000
[ { "code": null, "e": 1288, "s": 1062, "text": "Suppose we have two numbers, hour and minutes. We have to find a smaller angle (in sexagesimal units) formed between the hour and the minute hand. So if the input is like hour = 12 and min := 30, then the result will be 165°." }, { "code": null, "e": 1332, "s": 1288, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1359, "s": 1332, "text": "if h = 12, then set h := 0" }, { "code": null, "e": 1386, "s": 1359, "text": "if h = 12, then set h := 0" }, { "code": null, "e": 1413, "s": 1386, "text": "if m = 60, then set m := 0" }, { "code": null, "e": 1440, "s": 1413, "text": "if m = 60, then set m := 0" }, { "code": null, "e": 1466, "s": 1440, "text": "hAngle := 0.5 * (60h) + m" }, { "code": null, "e": 1492, "s": 1466, "text": "hAngle := 0.5 * (60h) + m" }, { "code": null, "e": 1505, "s": 1492, "text": "mAngle := 6m" }, { "code": null, "e": 1518, "s": 1505, "text": "mAngle := 6m" }, { "code": null, "e": 1543, "s": 1518, "text": "ret := |hAngle - mAngle|" }, { "code": null, "e": 1568, "s": 1543, "text": "ret := |hAngle - mAngle|" }, { "code": null, "e": 1606, "s": 1568, "text": "return minimum of ret and (360 – ret)" }, { "code": null, "e": 1644, "s": 1606, "text": "return minimum of ret and (360 – ret)" }, { "code": null, "e": 1714, "s": 1644, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 1725, "s": 1714, "text": " Live Demo" }, { "code": null, "e": 2099, "s": 1725, "text": "#include <bits/stdc++.h>\nusing namespace std;\nclass Solution {\npublic:\n double angleClock(int h, int m) {\n if(h == 12) h = 0;\n if(m == 60) m = 0;\n double hAngle = 0.5*((60 * h) + m);\n double mAngle = 6 * m;\n double ret = abs(hAngle - mAngle);\n return min(360 - ret, ret);\n }\n};\nmain(){\n Solution ob;\n cout << (ob.angleClock(12, 30));\n}" }, { "code": null, "e": 2105, "s": 2099, "text": "12\n30" }, { "code": null, "e": 2115, "s": 2105, "text": "165.00000" } ]
SQL Overview
SQL is a programming language for Relational Databases. It is designed over relational algebra and tuple relational calculus. SQL comes as a package with all major distributions of RDBMS. SQL comprises both data definition and data manipulation languages. Using the data definition properties of SQL, one can design and modify database schema, whereas data manipulation properties allows SQL to store and retrieve data from database. SQL uses the following set of commands to define database schema − Creates new databases, tables and views from RDBMS. For example − Create database tutorialspoint; Create table article; Create view for_students; Drops commands, views, tables, and databases from RDBMS. For example− Drop object_type object_name; Drop database tutorialspoint; Drop table article; Drop view for_students; Modifies database schema. Alter object_type object_name parameters; For example− Alter table article add subject varchar; This command adds an attribute in the relation article with the name subject of string type. SQL is equipped with data manipulation language (DML). DML modifies the database instance by inserting, updating and deleting its data. DML is responsible for all forms data modification in a database. SQL contains the following set of commands in its DML section − SELECT/FROM/WHERE INSERT INTO/VALUES UPDATE/SET/WHERE DELETE FROM/WHERE These basic constructs allow database programmers and users to enter data and information into the database and retrieve efficiently using a number of filter options. SELECT − This is one of the fundamental query command of SQL. It is similar to the projection operation of relational algebra. It selects the attributes based on the condition described by WHERE clause. SELECT − This is one of the fundamental query command of SQL. It is similar to the projection operation of relational algebra. It selects the attributes based on the condition described by WHERE clause. FROM − This clause takes a relation name as an argument from which attributes are to be selected/projected. In case more than one relation names are given, this clause corresponds to Cartesian product. FROM − This clause takes a relation name as an argument from which attributes are to be selected/projected. In case more than one relation names are given, this clause corresponds to Cartesian product. WHERE − This clause defines predicate or conditions, which must match in order to qualify the attributes to be projected. WHERE − This clause defines predicate or conditions, which must match in order to qualify the attributes to be projected. For example − Select author_name From book_author Where age > 50; This command will yield the names of authors from the relation book_author whose age is greater than 50. This command is used for inserting values into the rows of a table (relation). Syntax− INSERT INTO table (column1 [, column2, column3 ... ]) VALUES (value1 [, value2, value3 ... ]) Or INSERT INTO table VALUES (value1, [value2, ... ]) For example − INSERT INTO tutorialspoint (Author, Subject) VALUES ("anonymous", "computers"); This command is used for updating or modifying the values of columns in a table (relation). Syntax − UPDATE table_name SET column_name = value [, column_name = value ...] [WHERE condition] For example − UPDATE tutorialspoint SET Author="webmaster" WHERE Author="anonymous"; This command is used for removing one or more rows from a table (relation). Syntax − DELETE FROM table_name [WHERE condition]; For example − DELETE FROM tutorialspoints WHERE Author="unknown"; 178 Lectures 14.5 hours Arnab Chakraborty 194 Lectures 16 hours Arnab Chakraborty Print Add Notes Bookmark this page
[ { "code": null, "e": 2470, "s": 2282, "text": "SQL is a programming language for Relational Databases. It is designed over relational algebra and tuple relational calculus. SQL comes as a package with all major distributions of RDBMS." }, { "code": null, "e": 2716, "s": 2470, "text": "SQL comprises both data definition and data manipulation languages. Using the data definition properties of SQL, one can design and modify database schema, whereas data manipulation properties allows SQL to store and retrieve data from database." }, { "code": null, "e": 2783, "s": 2716, "text": "SQL uses the following set of commands to define database schema −" }, { "code": null, "e": 2835, "s": 2783, "text": "Creates new databases, tables and views from RDBMS." }, { "code": null, "e": 2849, "s": 2835, "text": "For example −" }, { "code": null, "e": 2930, "s": 2849, "text": "Create database tutorialspoint;\nCreate table article;\nCreate view for_students;\n" }, { "code": null, "e": 2987, "s": 2930, "text": "Drops commands, views, tables, and databases from RDBMS." }, { "code": null, "e": 3000, "s": 2987, "text": "For example−" }, { "code": null, "e": 3105, "s": 3000, "text": "Drop object_type object_name;\nDrop database tutorialspoint;\nDrop table article;\nDrop view for_students;\n" }, { "code": null, "e": 3131, "s": 3105, "text": "Modifies database schema." }, { "code": null, "e": 3174, "s": 3131, "text": "Alter object_type object_name parameters;\n" }, { "code": null, "e": 3187, "s": 3174, "text": "For example−" }, { "code": null, "e": 3229, "s": 3187, "text": "Alter table article add subject varchar;\n" }, { "code": null, "e": 3322, "s": 3229, "text": "This command adds an attribute in the relation article with the name subject of string type." }, { "code": null, "e": 3588, "s": 3322, "text": "SQL is equipped with data manipulation language (DML). DML modifies the database instance by inserting, updating and deleting its data. DML is responsible for all forms data modification in a database. SQL contains the following set of commands in its DML section −" }, { "code": null, "e": 3606, "s": 3588, "text": "SELECT/FROM/WHERE" }, { "code": null, "e": 3625, "s": 3606, "text": "INSERT INTO/VALUES" }, { "code": null, "e": 3642, "s": 3625, "text": "UPDATE/SET/WHERE" }, { "code": null, "e": 3660, "s": 3642, "text": "DELETE FROM/WHERE" }, { "code": null, "e": 3827, "s": 3660, "text": "These basic constructs allow database programmers and users to enter data and information into the database and retrieve efficiently using a number of filter options." }, { "code": null, "e": 4030, "s": 3827, "text": "SELECT − This is one of the fundamental query command of SQL. It is similar to the projection operation of relational algebra. It selects the attributes based on the condition described by WHERE clause." }, { "code": null, "e": 4233, "s": 4030, "text": "SELECT − This is one of the fundamental query command of SQL. It is similar to the projection operation of relational algebra. It selects the attributes based on the condition described by WHERE clause." }, { "code": null, "e": 4435, "s": 4233, "text": "FROM − This clause takes a relation name as an argument from which attributes are to be selected/projected. In case more than one relation names are given, this clause corresponds to Cartesian product." }, { "code": null, "e": 4637, "s": 4435, "text": "FROM − This clause takes a relation name as an argument from which attributes are to be selected/projected. In case more than one relation names are given, this clause corresponds to Cartesian product." }, { "code": null, "e": 4759, "s": 4637, "text": "WHERE − This clause defines predicate or conditions, which must match in order to qualify the attributes to be projected." }, { "code": null, "e": 4881, "s": 4759, "text": "WHERE − This clause defines predicate or conditions, which must match in order to qualify the attributes to be projected." }, { "code": null, "e": 4895, "s": 4881, "text": "For example −" }, { "code": null, "e": 4948, "s": 4895, "text": "Select author_name\nFrom book_author\nWhere age > 50;\n" }, { "code": null, "e": 5053, "s": 4948, "text": "This command will yield the names of authors from the relation book_author whose age is greater than 50." }, { "code": null, "e": 5132, "s": 5053, "text": "This command is used for inserting values into the rows of a table (relation)." }, { "code": null, "e": 5140, "s": 5132, "text": "Syntax−" }, { "code": null, "e": 5235, "s": 5140, "text": "INSERT INTO table (column1 [, column2, column3 ... ]) VALUES (value1 [, value2, value3 ... ])\n" }, { "code": null, "e": 5238, "s": 5235, "text": "Or" }, { "code": null, "e": 5289, "s": 5238, "text": "INSERT INTO table VALUES (value1, [value2, ... ])\n" }, { "code": null, "e": 5303, "s": 5289, "text": "For example −" }, { "code": null, "e": 5384, "s": 5303, "text": "INSERT INTO tutorialspoint (Author, Subject) VALUES (\"anonymous\", \"computers\");\n" }, { "code": null, "e": 5476, "s": 5384, "text": "This command is used for updating or modifying the values of columns in a table (relation)." }, { "code": null, "e": 5485, "s": 5476, "text": "Syntax −" }, { "code": null, "e": 5574, "s": 5485, "text": "UPDATE table_name SET column_name = value [, column_name = value ...] [WHERE condition]\n" }, { "code": null, "e": 5588, "s": 5574, "text": "For example −" }, { "code": null, "e": 5660, "s": 5588, "text": "UPDATE tutorialspoint SET Author=\"webmaster\" WHERE Author=\"anonymous\";\n" }, { "code": null, "e": 5736, "s": 5660, "text": "This command is used for removing one or more rows from a table (relation)." }, { "code": null, "e": 5745, "s": 5736, "text": "Syntax −" }, { "code": null, "e": 5788, "s": 5745, "text": "DELETE FROM table_name [WHERE condition];\n" }, { "code": null, "e": 5802, "s": 5788, "text": "For example −" }, { "code": null, "e": 5858, "s": 5802, "text": "DELETE FROM tutorialspoints\n WHERE Author=\"unknown\";\n" }, { "code": null, "e": 5895, "s": 5858, "text": "\n 178 Lectures \n 14.5 hours \n" }, { "code": null, "e": 5914, "s": 5895, "text": " Arnab Chakraborty" }, { "code": null, "e": 5949, "s": 5914, "text": "\n 194 Lectures \n 16 hours \n" }, { "code": null, "e": 5968, "s": 5949, "text": " Arnab Chakraborty" }, { "code": null, "e": 5975, "s": 5968, "text": " Print" }, { "code": null, "e": 5986, "s": 5975, "text": " Add Notes" } ]
Run Linux Natively on Windows 10
Microsoft has introduced the WSL Subsystem for Linux, which lets users run their favorite Linux distributions directly from Windows 10 without dual-booting or using a virtual machine. While this is a step in the right direction for Microsoft, it's not quite there yet in terms of full functionality. Specifically, WSL does not support AF_PACKET for security restrictions. This means that you won't be able to put a Wi-Fi adapter in promiscuous mode (or monitor mode), and tools that require raw sockets to function properly won't work, such as Nmap. To do so, run the PowerShell with administrator rights and hit the following command. Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Windows-Subsystem-Linux Download the 'Kali Linux' Application from the Microsoft Store by searching for "Kali Linux" on the list. And from there, click "Get" to begin installing. It will ask for system reboot after the package download it will install automatically. Once your system has rebooted and you've logged back into your account, launch the Kali from the Cortana bar. The user will be prompted every time to enter the root password for the configuring the package since the default version of Kali Linux in the windows-10 OS installed without root permission. So, to enable the root privilege, hit the following commands. Sudo –i Chmod +s /bin/su With that done, you'll be prompted to create and configure a Kali Linux username and password. When all set, the important first thing don't forget is to add the kali Linux repository in the /etc/apt/source.list file and then update it just like any Linux system with the following command. Sudo apt-get update Sudo apt-get upgrade It might be possible that the Windows Defender could treat or detect Kali repository as viruses or malware and blocks some portion of the program. To prevent these errors, add Windows Defender exclusion for the Kali Linux folder. Since this version of kali Linux will be in command mode out rightly. Now we need to set up the XFCE desktop manager but need to install some utilities first. Run the following command to install wget which is a utility that can download files over HTTP. Enter your password you created in the previous step when prompted and hit Y to proceed with the download and install. sudo apt-get install wget wget https://kali.sh/xfce4.sh sudo sh xfce4.sh Now it is time to start up the xrdp server to connect to the XFCE desktop manager using Remote Desktop. Run the following command sudo /etc/init.d/xrdp start Finally, the xrdp server has started, then open up the remote command connection (RDP) prompt using mstsc and connect to 127.0.0.1:3390. Then, you are required to logged-in with the previously defined ID and Password in the GUI. And, you got the full-fledged Linux XFC desktop. Enjoy.
[ { "code": null, "e": 1246, "s": 1062, "text": "Microsoft has introduced the WSL Subsystem for Linux, which lets users run their favorite Linux distributions directly from Windows 10 without dual-booting or using a virtual machine." }, { "code": null, "e": 1612, "s": 1246, "text": "While this is a step in the right direction for Microsoft, it's not quite there yet in terms of full functionality. Specifically, WSL does not support AF_PACKET for security restrictions. This means that you won't be able to put a Wi-Fi adapter in promiscuous mode (or monitor mode), and tools that require raw sockets to function properly won't work, such as Nmap." }, { "code": null, "e": 1698, "s": 1612, "text": "To do so, run the PowerShell with administrator rights and hit the following command." }, { "code": null, "e": 1783, "s": 1698, "text": "Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Windows-Subsystem-Linux" }, { "code": null, "e": 2136, "s": 1783, "text": "Download the 'Kali Linux' Application from the Microsoft Store by searching for \"Kali Linux\" on the list. And from there, click \"Get\" to begin installing. It will ask for system reboot after the package download it will install automatically. Once your system has rebooted and you've logged back into your account, launch the Kali from the Cortana bar." }, { "code": null, "e": 2390, "s": 2136, "text": "The user will be prompted every time to enter the root password for the configuring the package since the default version of Kali Linux in the windows-10 OS installed without root permission. So, to enable the root privilege, hit the following commands." }, { "code": null, "e": 2415, "s": 2390, "text": "Sudo –i\nChmod +s /bin/su" }, { "code": null, "e": 2706, "s": 2415, "text": "With that done, you'll be prompted to create and configure a Kali Linux username and password. When all set, the important first thing don't forget is to add the kali Linux repository in the /etc/apt/source.list file and then update it just like any Linux system with the following command." }, { "code": null, "e": 2747, "s": 2706, "text": "Sudo apt-get update\nSudo apt-get upgrade" }, { "code": null, "e": 2977, "s": 2747, "text": "It might be possible that the Windows Defender could treat or detect Kali repository as viruses or malware and blocks some portion of the program. To prevent these errors, add Windows Defender exclusion for the Kali Linux folder." }, { "code": null, "e": 3351, "s": 2977, "text": "Since this version of kali Linux will be in command mode out rightly. Now we need to set up the XFCE desktop manager but need to install some utilities first. Run the following command to install wget which is a utility that can download files over HTTP. Enter your password you created in the previous step when\nprompted and hit Y to proceed with the download and install." }, { "code": null, "e": 3424, "s": 3351, "text": "sudo apt-get install wget\nwget https://kali.sh/xfce4.sh\nsudo sh xfce4.sh" }, { "code": null, "e": 3554, "s": 3424, "text": "Now it is time to start up the xrdp server to connect to the XFCE desktop manager using Remote\nDesktop. Run the following command" }, { "code": null, "e": 3582, "s": 3554, "text": "sudo /etc/init.d/xrdp start" }, { "code": null, "e": 3867, "s": 3582, "text": "Finally, the xrdp server has started, then open up the remote command connection (RDP) prompt using mstsc and connect to 127.0.0.1:3390. Then, you are required to logged-in with the previously defined ID and Password in the GUI. And, you got the full-fledged Linux XFC desktop. Enjoy." } ]
Count number of binary strings of length N having only 0's and 1's - GeeksforGeeks
22 Apr, 2021 Given an integer N, the task is to count the number of binary strings of length N having only 0’s and 1’s. Note: Since the count can be very large, return the answer modulo 10^9+7. Examples: Input: 2 Output: 4 Explanation: The numbers are 00, 01, 11, 10. Hence the count is 4. Input: 3 Output: 8 Explanation: The numbers are 000, 001, 011, 010, 111, 101, 110, 100. Hence the count is 8. Approach: The problem can be easily solved by using Permutation and Combination. At each position of the string there can only be two possibilities, i.e., 0 or 1. Therefore, the total number of permutation of 0 and 1 in a string of length N is given by 2*2*2*...(N times), i.e., 2^N. The answer can be very large, hence modulo by 10^9+7 is returned. Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std;#define ll long long#define mod (ll)(1e9 + 7) // Iterative Function to calculate (x^y)%p in O(log y)ll power(ll x, ll y, ll p){ ll res = 1; // Initialize result x = x % p; // Update x if it is more than or // equal to p while (y > 0) { // If y is odd, multiply x with result if (y & 1) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res;} // Function to count the number of binary// strings of length N having only 0's and 1'sll findCount(ll N){ int count = power(2, N, mod); return count;} // Driver codeint main(){ ll N = 25; cout << findCount(N); return 0;} // Java implementation of the above approachimport java.util.*; class GFG{ static int mod = (int) (1e9 + 7); // Iterative Function to calculate (x^y)%p in O(log y)static int power(int x, int y, int p){ int res = 1; // Initialize result x = x % p; // Update x if it is more than or // equal to p while (y > 0) { // If y is odd, multiply x with result if ((y & 1)==1) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res;} // Function to count the number of binary// strings of length N having only 0's and 1'sstatic int findCount(int N){ int count = power(2, N, mod); return count;} // Driver codepublic static void main(String[] args){ int N = 25; System.out.println(findCount(N));}} /* This code contributed by PrinciRaj1992 */ # Python 3 implementation of the approachmod = 1000000007 # Iterative Function to calculate (x^y)%p in O(log y)def power(x, y, p): res = 1 # Initialize result x = x % p # Update x if it is more than or # equal to p while (y > 0): # If y is odd, multiply x with result if (y & 1): res = (res * x) % p # y must be even now y = y >> 1 # y = y/2 x = (x * x) % p return res # Function to count the number of binary# strings of length N having only 0's and 1'sdef findCount(N): count = power(2, N, mod) return count # Driver codeif __name__ == '__main__': N = 25 print(findCount(N)) # This code is contributed by# Surendra_Gangwar // C# implementation of the above approachusing System; class GFG{ static int mod = (int) (1e9 + 7); // Iterative Function to calculate (x^y)%p in O(log y) static int power(int x, int y, int p) { int res = 1; // Initialize result x = x % p; // Update x if it is more than or // equal to p while (y > 0) { // If y is odd, multiply x with result if ((y & 1) == 1) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res; } // Function to count the number of binary // strings of length N having only 0's and 1's static int findCount(int N) { int count = power(2, N, mod); return count; } // Driver code public static void Main() { int N = 25; Console.WriteLine(findCount(N)); }} // This code is contributed by Ryuga <?php// PHP implementation of the approach // Iterative Function to calculate// (x^y)%p in O(log y)function power($x, $y){ $p = 1000000007; $res = 1; // Initialize result $x = $x % $p; // Update x if it is more // than or equal to p while ($y > 0) { // If y is odd, multiply x with result if ($y & 1) $res = ($res * $x) % $p; // y must be even now $y = $y >> 1; // y = y/2 $x = ($x * $x) % $p; } return $res;} // Function to count the number of binary// strings of length N having only 0's and 1'sfunction findCount($N){ $count = power(2, $N); return $count;} // Driver code$N = 25; echo findCount($N); // This code is contributed by Rajput-Ji?> <script> // Javascript implementation of the approachmod = 1000000007 // Iterative Function to calculate// (x^y)%p in O(log y)function power(x, y, p){ // Initialize result var res = 1; // Update x if it is more than or // equal to p x = x % p; while (y > 0) { // If y is odd, multiply x with result if (y & 1) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res;} // Function to count the number of binary// strings of length N having only 0's and 1'sfunction findCount(N){ var count = power(2, N, mod); return count;} // Driver codevar N = 25; document.write(findCount(N)); // This code is contributed by noob2000 </script> 33554432 SURENDRA_GANGWAR princiraj1992 ankthon Rajput-Ji ManasChhabra2 noob2000 maths-power Combinatorial Mathematical Mathematical Combinatorial Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Combinations with repetitions Ways to sum to N using Natural Numbers up to K with repetitions allowed Generate all possible combinations of at most X characters from a given array Given number of matches played, find number of teams in tournament Largest substring with same Characters Program for Fibonacci numbers C++ Data Types Set in C++ Standard Template Library (STL) Coin Change | DP-7 Merge two sorted arrays
[ { "code": null, "e": 25476, "s": 25448, "text": "\n22 Apr, 2021" }, { "code": null, "e": 25657, "s": 25476, "text": "Given an integer N, the task is to count the number of binary strings of length N having only 0’s and 1’s. Note: Since the count can be very large, return the answer modulo 10^9+7." }, { "code": null, "e": 25669, "s": 25657, "text": "Examples: " }, { "code": null, "e": 25755, "s": 25669, "text": "Input: 2 Output: 4 Explanation: The numbers are 00, 01, 11, 10. Hence the count is 4." }, { "code": null, "e": 25867, "s": 25755, "text": "Input: 3 Output: 8 Explanation: The numbers are 000, 001, 011, 010, 111, 101, 110, 100. Hence the count is 8. " }, { "code": null, "e": 26217, "s": 25867, "text": "Approach: The problem can be easily solved by using Permutation and Combination. At each position of the string there can only be two possibilities, i.e., 0 or 1. Therefore, the total number of permutation of 0 and 1 in a string of length N is given by 2*2*2*...(N times), i.e., 2^N. The answer can be very large, hence modulo by 10^9+7 is returned." }, { "code": null, "e": 26270, "s": 26217, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 26274, "s": 26270, "text": "C++" }, { "code": null, "e": 26279, "s": 26274, "text": "Java" }, { "code": null, "e": 26287, "s": 26279, "text": "Python3" }, { "code": null, "e": 26290, "s": 26287, "text": "C#" }, { "code": null, "e": 26294, "s": 26290, "text": "PHP" }, { "code": null, "e": 26305, "s": 26294, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std;#define ll long long#define mod (ll)(1e9 + 7) // Iterative Function to calculate (x^y)%p in O(log y)ll power(ll x, ll y, ll p){ ll res = 1; // Initialize result x = x % p; // Update x if it is more than or // equal to p while (y > 0) { // If y is odd, multiply x with result if (y & 1) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res;} // Function to count the number of binary// strings of length N having only 0's and 1'sll findCount(ll N){ int count = power(2, N, mod); return count;} // Driver codeint main(){ ll N = 25; cout << findCount(N); return 0;}", "e": 27077, "s": 26305, "text": null }, { "code": "// Java implementation of the above approachimport java.util.*; class GFG{ static int mod = (int) (1e9 + 7); // Iterative Function to calculate (x^y)%p in O(log y)static int power(int x, int y, int p){ int res = 1; // Initialize result x = x % p; // Update x if it is more than or // equal to p while (y > 0) { // If y is odd, multiply x with result if ((y & 1)==1) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res;} // Function to count the number of binary// strings of length N having only 0's and 1'sstatic int findCount(int N){ int count = power(2, N, mod); return count;} // Driver codepublic static void main(String[] args){ int N = 25; System.out.println(findCount(N));}} /* This code contributed by PrinciRaj1992 */", "e": 27940, "s": 27077, "text": null }, { "code": "# Python 3 implementation of the approachmod = 1000000007 # Iterative Function to calculate (x^y)%p in O(log y)def power(x, y, p): res = 1 # Initialize result x = x % p # Update x if it is more than or # equal to p while (y > 0): # If y is odd, multiply x with result if (y & 1): res = (res * x) % p # y must be even now y = y >> 1 # y = y/2 x = (x * x) % p return res # Function to count the number of binary# strings of length N having only 0's and 1'sdef findCount(N): count = power(2, N, mod) return count # Driver codeif __name__ == '__main__': N = 25 print(findCount(N)) # This code is contributed by# Surendra_Gangwar", "e": 28661, "s": 27940, "text": null }, { "code": "// C# implementation of the above approachusing System; class GFG{ static int mod = (int) (1e9 + 7); // Iterative Function to calculate (x^y)%p in O(log y) static int power(int x, int y, int p) { int res = 1; // Initialize result x = x % p; // Update x if it is more than or // equal to p while (y > 0) { // If y is odd, multiply x with result if ((y & 1) == 1) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res; } // Function to count the number of binary // strings of length N having only 0's and 1's static int findCount(int N) { int count = power(2, N, mod); return count; } // Driver code public static void Main() { int N = 25; Console.WriteLine(findCount(N)); }} // This code is contributed by Ryuga", "e": 29648, "s": 28661, "text": null }, { "code": "<?php// PHP implementation of the approach // Iterative Function to calculate// (x^y)%p in O(log y)function power($x, $y){ $p = 1000000007; $res = 1; // Initialize result $x = $x % $p; // Update x if it is more // than or equal to p while ($y > 0) { // If y is odd, multiply x with result if ($y & 1) $res = ($res * $x) % $p; // y must be even now $y = $y >> 1; // y = y/2 $x = ($x * $x) % $p; } return $res;} // Function to count the number of binary// strings of length N having only 0's and 1'sfunction findCount($N){ $count = power(2, $N); return $count;} // Driver code$N = 25; echo findCount($N); // This code is contributed by Rajput-Ji?>", "e": 30392, "s": 29648, "text": null }, { "code": "<script> // Javascript implementation of the approachmod = 1000000007 // Iterative Function to calculate// (x^y)%p in O(log y)function power(x, y, p){ // Initialize result var res = 1; // Update x if it is more than or // equal to p x = x % p; while (y > 0) { // If y is odd, multiply x with result if (y & 1) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res;} // Function to count the number of binary// strings of length N having only 0's and 1'sfunction findCount(N){ var count = power(2, N, mod); return count;} // Driver codevar N = 25; document.write(findCount(N)); // This code is contributed by noob2000 </script>", "e": 31165, "s": 30392, "text": null }, { "code": null, "e": 31174, "s": 31165, "text": "33554432" }, { "code": null, "e": 31193, "s": 31176, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 31207, "s": 31193, "text": "princiraj1992" }, { "code": null, "e": 31215, "s": 31207, "text": "ankthon" }, { "code": null, "e": 31225, "s": 31215, "text": "Rajput-Ji" }, { "code": null, "e": 31239, "s": 31225, "text": "ManasChhabra2" }, { "code": null, "e": 31248, "s": 31239, "text": "noob2000" }, { "code": null, "e": 31260, "s": 31248, "text": "maths-power" }, { "code": null, "e": 31274, "s": 31260, "text": "Combinatorial" }, { "code": null, "e": 31287, "s": 31274, "text": "Mathematical" }, { "code": null, "e": 31300, "s": 31287, "text": "Mathematical" }, { "code": null, "e": 31314, "s": 31300, "text": "Combinatorial" }, { "code": null, "e": 31412, "s": 31314, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31442, "s": 31412, "text": "Combinations with repetitions" }, { "code": null, "e": 31514, "s": 31442, "text": "Ways to sum to N using Natural Numbers up to K with repetitions allowed" }, { "code": null, "e": 31592, "s": 31514, "text": "Generate all possible combinations of at most X characters from a given array" }, { "code": null, "e": 31659, "s": 31592, "text": "Given number of matches played, find number of teams in tournament" }, { "code": null, "e": 31698, "s": 31659, "text": "Largest substring with same Characters" }, { "code": null, "e": 31728, "s": 31698, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 31743, "s": 31728, "text": "C++ Data Types" }, { "code": null, "e": 31786, "s": 31743, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 31805, "s": 31786, "text": "Coin Change | DP-7" } ]
WebRTC - MediaStream APIs
The MediaStream API was designed to easy access the media streams from local cameras and microphones. The getUserMedia() method is the primary way to access local input devices. The API has a few key points − A real-time media stream is represented by a stream object in the form of video or audio A real-time media stream is represented by a stream object in the form of video or audio It provides a security level through user permissions asking the user before a web application can start fetching a stream It provides a security level through user permissions asking the user before a web application can start fetching a stream The selection of input devices is handled by the MediaStream API (for example, when there are two cameras or microphones connected to the device) The selection of input devices is handled by the MediaStream API (for example, when there are two cameras or microphones connected to the device) Each MediaStream object includes several MediaStreamTrack objects. They represent video and audio from different input devices. Each MediaStreamTrack object may include several channels (right and left audio channels). These are the smallest parts defined by the MediaStream API. There are two ways to output MediaStream objects. First, we can render output into a video or audio element. Secondly, we can send output to the RTCPeerConnection object, which then send it to a remote peer. Let's create a simple WebRTC application. It will show a video element on the screen, ask the user permission to use the camera, and show a live video stream in the browser. Create an index.html file − <!DOCTYPE html> <html lang = "en"> <head> <meta charset = "utf-8" /> </head> <body> <video autoplay></video> <script src = "client.js"></script> </body> </html> Then create the client.js file and add the following; function hasUserMedia() { //check if the browser supports the WebRTC return !!(navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia); } if (hasUserMedia()) { navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia; //enabling video and audio channels navigator.getUserMedia({ video: true, audio: true }, function (stream) { var video = document.querySelector('video'); //inserting our stream to the video tag video.src = window.URL.createObjectURL(stream); }, function (err) {}); } else { alert("WebRTC is not supported"); } Here we create the hasUserMedia() function which checks whether WebRTC is supported or not. Then we access the getUserMedia function where the second parameter is a callback that accept the stream coming from the user's device. Then we load our stream into the video element using window.URL.createObjectURL which creates a URL representing the object given in parameter. Now refresh your page, click Allow, and you should see your face on the screen. Remember to run all your scripts using the web server. We have already installed one in the WebRTC Environment Tutorial. MediaStream.active (read only) − Returns true if the MediaStream is active, or false otherwise. MediaStream.active (read only) − Returns true if the MediaStream is active, or false otherwise. MediaStream.ended (read only, deprecated) − Return true if the ended event has been fired on the object, meaning that the stream has been completely read, or false if the end of the stream has not been reached. MediaStream.ended (read only, deprecated) − Return true if the ended event has been fired on the object, meaning that the stream has been completely read, or false if the end of the stream has not been reached. MediaStream.id (read only) − A unique identifier for the object. MediaStream.id (read only) − A unique identifier for the object. MediaStream.label (read only, deprecated) − A unique identifier assigned by the user agent. MediaStream.label (read only, deprecated) − A unique identifier assigned by the user agent. You can see how the above properties look in my browser − MediaStream.onactive − A handler for an active event that is fired when a MediaStream object becomes active. MediaStream.onactive − A handler for an active event that is fired when a MediaStream object becomes active. MediaStream.onaddtrack − A handler for an addtrack event that is fired when a new MediaStreamTrack object is added. MediaStream.onaddtrack − A handler for an addtrack event that is fired when a new MediaStreamTrack object is added. MediaStream.onended (deprecated) − A handler for an ended event that is fired when the streaming is terminating. MediaStream.onended (deprecated) − A handler for an ended event that is fired when the streaming is terminating. MediaStream.oninactive − A handler for an inactive event that is fired when a MediaStream object becomes inactive. MediaStream.oninactive − A handler for an inactive event that is fired when a MediaStream object becomes inactive. MediaStream.onremovetrack − A handler for a removetrack event that is fired when a MediaStreamTrack object is removed from it. MediaStream.onremovetrack − A handler for a removetrack event that is fired when a MediaStreamTrack object is removed from it. MediaStream.addTrack() − Adds the MediaStreamTrack object given as argument to the MediaStream. If the track has already been added, nothing happens. MediaStream.addTrack() − Adds the MediaStreamTrack object given as argument to the MediaStream. If the track has already been added, nothing happens. MediaStream.clone() − Returns a clone of the MediaStream object with a new ID. MediaStream.clone() − Returns a clone of the MediaStream object with a new ID. MediaStream.getAudioTracks() − Returns a list of the audio MediaStreamTrack objects from the MediaStream object. MediaStream.getAudioTracks() − Returns a list of the audio MediaStreamTrack objects from the MediaStream object. MediaStream.getTrackById() − Returns the track by ID. If the argument is empty or the ID is not found, it returns null. If several tracks have the same ID, it returns the first one. MediaStream.getTrackById() − Returns the track by ID. If the argument is empty or the ID is not found, it returns null. If several tracks have the same ID, it returns the first one. MediaStream.getTracks() − Returns a list of all MediaStreamTrack objects from the MediaStream object. MediaStream.getTracks() − Returns a list of all MediaStreamTrack objects from the MediaStream object. MediaStream.getVideoTracks() − Returns a list of the video MediaStreamTrack objects from the MediaStream object. MediaStream.getVideoTracks() − Returns a list of the video MediaStreamTrack objects from the MediaStream object. MediaStream.removeTrack() − Removes the MediaStreamTrack object given as argument from the MediaStream. If the track has already been removed, nothing happens. MediaStream.removeTrack() − Removes the MediaStreamTrack object given as argument from the MediaStream. If the track has already been removed, nothing happens. To test the above APIs change change the index.html in the following way − <!DOCTYPE html> <html lang = "en"> <head> <meta charset = "utf-8" /> </head> <body> <video autoplay></video> <div><button id = "btnGetAudioTracks">getAudioTracks() </button></div> <div><button id = "btnGetTrackById">getTrackById() </button></div> <div><button id = "btnGetTracks">getTracks()</button></div> <div><button id = "btnGetVideoTracks">getVideoTracks() </button></div> <div><button id = "btnRemoveAudioTrack">removeTrack() - audio </button></div> <div><button id = "btnRemoveVideoTrack">removeTrack() - video </button></div> <script src = "client.js"></script> </body> </html> We added a few buttons to try out several MediaStream APIs. Then we should add event handlers for our newly created button. Modify the client.js file this way − var stream; function hasUserMedia() { //check if the browser supports the WebRTC return !!(navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia); } if (hasUserMedia()) { navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia; //enabling video and audio channels navigator.getUserMedia({ video: true, audio: true }, function (s) { stream = s; var video = document.querySelector('video'); //inserting our stream to the video tag video.src = window.URL.createObjectURL(stream); }, function (err) {}); } else { alert("WebRTC is not supported"); } btnGetAudioTracks.addEventListener("click", function(){ console.log("getAudioTracks"); console.log(stream.getAudioTracks()); }); btnGetTrackById.addEventListener("click", function(){ console.log("getTrackById"); console.log(stream.getTrackById(stream.getAudioTracks()[0].id)); }); btnGetTracks.addEventListener("click", function(){ console.log("getTracks()"); console.log(stream.getTracks()); }); btnGetVideoTracks.addEventListener("click", function(){ console.log("getVideoTracks()"); console.log(stream.getVideoTracks()); }); btnRemoveAudioTrack.addEventListener("click", function(){ console.log("removeAudioTrack()"); stream.removeTrack(stream.getAudioTracks()[0]); }); btnRemoveVideoTrack.addEventListener("click", function(){ console.log("removeVideoTrack()"); stream.removeTrack(stream.getVideoTracks()[0]); }); Now refresh your page. Click on the getAudioTracks() button, then click on the removeTrack() - audio button. The audio track should now be removed. Then do the same for the video track. If you click the getTracks() button you should see all MediaStreamTracks (all connected video and audio inputs). Then click on the getTrackById() to get audio MediaStreamTrack. In this chapter, we created a simple WebRTC application using the MediaStream API. Now you should have a clear overview of the various MediaStream APIs that make WebRTC work.
[ { "code": null, "e": 2199, "s": 2021, "text": "The MediaStream API was designed to easy access the media streams from local cameras and microphones. The getUserMedia() method is the primary way to access local input devices." }, { "code": null, "e": 2230, "s": 2199, "text": "The API has a few key points −" }, { "code": null, "e": 2319, "s": 2230, "text": "A real-time media stream is represented by a stream object in the form of video or audio" }, { "code": null, "e": 2408, "s": 2319, "text": "A real-time media stream is represented by a stream object in the form of video or audio" }, { "code": null, "e": 2531, "s": 2408, "text": "It provides a security level through user permissions asking the user before a web application can start fetching a stream" }, { "code": null, "e": 2654, "s": 2531, "text": "It provides a security level through user permissions asking the user before a web application can start fetching a stream" }, { "code": null, "e": 2800, "s": 2654, "text": "The selection of input devices is handled by the MediaStream API (for example, when there are two cameras or microphones connected to the device)" }, { "code": null, "e": 2946, "s": 2800, "text": "The selection of input devices is handled by the MediaStream API (for example, when there are two cameras or microphones connected to the device)" }, { "code": null, "e": 3074, "s": 2946, "text": "Each MediaStream object includes several MediaStreamTrack objects. They represent video and audio from different input devices." }, { "code": null, "e": 3226, "s": 3074, "text": "Each MediaStreamTrack object may include several channels (right and left audio channels). These are the smallest parts defined by the MediaStream API." }, { "code": null, "e": 3435, "s": 3226, "text": "There are two ways to output MediaStream objects. First, we can render output into a video or audio element. Secondly, we can send output to the RTCPeerConnection object, which then send it to a remote peer." }, { "code": null, "e": 3637, "s": 3435, "text": "Let's create a simple WebRTC application. It will show a video element on the screen, ask the user permission to use the camera, and show a live video stream in the browser. Create an index.html file −" }, { "code": null, "e": 3841, "s": 3637, "text": "<!DOCTYPE html> \n<html lang = \"en\">\n \n <head> \n <meta charset = \"utf-8\" /> \n </head> \n\t\n <body> \n <video autoplay></video> \n <script src = \"client.js\"></script> \n </body>\n\t\n</html>" }, { "code": null, "e": 3895, "s": 3841, "text": "Then create the client.js file and add the following;" }, { "code": null, "e": 4581, "s": 3895, "text": "function hasUserMedia() { \n //check if the browser supports the WebRTC \n return !!(navigator.getUserMedia || navigator.webkitGetUserMedia || \n navigator.mozGetUserMedia); \n} \n\nif (hasUserMedia()) { \n navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia\n || navigator.mozGetUserMedia; \n\t\t\n //enabling video and audio channels \n navigator.getUserMedia({ video: true, audio: true }, function (stream) { \n var video = document.querySelector('video'); \n\t\t\n //inserting our stream to the video tag \n video.src = window.URL.createObjectURL(stream); \n }, function (err) {}); \n} else { \n alert(\"WebRTC is not supported\"); \n}" }, { "code": null, "e": 4953, "s": 4581, "text": "Here we create the hasUserMedia() function which checks whether WebRTC is supported or not. Then we access the getUserMedia function where the second parameter is a callback that accept the stream coming from the user's device. Then we load our stream into the video element using window.URL.createObjectURL which creates a URL representing the object given in parameter." }, { "code": null, "e": 5033, "s": 4953, "text": "Now refresh your page, click Allow, and you should see your face on the screen." }, { "code": null, "e": 5154, "s": 5033, "text": "Remember to run all your scripts using the web server. We have already installed one in the WebRTC Environment Tutorial." }, { "code": null, "e": 5250, "s": 5154, "text": "MediaStream.active (read only) − Returns true if the MediaStream is active, or false otherwise." }, { "code": null, "e": 5346, "s": 5250, "text": "MediaStream.active (read only) − Returns true if the MediaStream is active, or false otherwise." }, { "code": null, "e": 5557, "s": 5346, "text": "MediaStream.ended (read only, deprecated) − Return true if the ended event has been fired on the object, meaning that the stream has been completely read, or false if the end of the stream has not been reached." }, { "code": null, "e": 5768, "s": 5557, "text": "MediaStream.ended (read only, deprecated) − Return true if the ended event has been fired on the object, meaning that the stream has been completely read, or false if the end of the stream has not been reached." }, { "code": null, "e": 5833, "s": 5768, "text": "MediaStream.id (read only) − A unique identifier for the object." }, { "code": null, "e": 5898, "s": 5833, "text": "MediaStream.id (read only) − A unique identifier for the object." }, { "code": null, "e": 5990, "s": 5898, "text": "MediaStream.label (read only, deprecated) − A unique identifier assigned by the user agent." }, { "code": null, "e": 6082, "s": 5990, "text": "MediaStream.label (read only, deprecated) − A unique identifier assigned by the user agent." }, { "code": null, "e": 6140, "s": 6082, "text": "You can see how the above properties look in my browser −" }, { "code": null, "e": 6249, "s": 6140, "text": "MediaStream.onactive − A handler for an active event that is fired when a MediaStream object becomes active." }, { "code": null, "e": 6358, "s": 6249, "text": "MediaStream.onactive − A handler for an active event that is fired when a MediaStream object becomes active." }, { "code": null, "e": 6474, "s": 6358, "text": "MediaStream.onaddtrack − A handler for an addtrack event that is fired when a new MediaStreamTrack object is added." }, { "code": null, "e": 6590, "s": 6474, "text": "MediaStream.onaddtrack − A handler for an addtrack event that is fired when a new MediaStreamTrack object is added." }, { "code": null, "e": 6703, "s": 6590, "text": "MediaStream.onended (deprecated) − A handler for an ended event that is fired when the streaming is terminating." }, { "code": null, "e": 6816, "s": 6703, "text": "MediaStream.onended (deprecated) − A handler for an ended event that is fired when the streaming is terminating." }, { "code": null, "e": 6931, "s": 6816, "text": "MediaStream.oninactive − A handler for an inactive event that is fired when a MediaStream object becomes inactive." }, { "code": null, "e": 7046, "s": 6931, "text": "MediaStream.oninactive − A handler for an inactive event that is fired when a MediaStream object becomes inactive." }, { "code": null, "e": 7173, "s": 7046, "text": "MediaStream.onremovetrack − A handler for a removetrack event that is fired when a MediaStreamTrack object is removed from it." }, { "code": null, "e": 7300, "s": 7173, "text": "MediaStream.onremovetrack − A handler for a removetrack event that is fired when a MediaStreamTrack object is removed from it." }, { "code": null, "e": 7450, "s": 7300, "text": "MediaStream.addTrack() − Adds the MediaStreamTrack object given as argument to the MediaStream. If the track has already been added, nothing happens." }, { "code": null, "e": 7600, "s": 7450, "text": "MediaStream.addTrack() − Adds the MediaStreamTrack object given as argument to the MediaStream. If the track has already been added, nothing happens." }, { "code": null, "e": 7679, "s": 7600, "text": "MediaStream.clone() − Returns a clone of the MediaStream object with a new ID." }, { "code": null, "e": 7758, "s": 7679, "text": "MediaStream.clone() − Returns a clone of the MediaStream object with a new ID." }, { "code": null, "e": 7871, "s": 7758, "text": "MediaStream.getAudioTracks() − Returns a list of the audio MediaStreamTrack objects from the MediaStream object." }, { "code": null, "e": 7984, "s": 7871, "text": "MediaStream.getAudioTracks() − Returns a list of the audio MediaStreamTrack objects from the MediaStream object." }, { "code": null, "e": 8166, "s": 7984, "text": "MediaStream.getTrackById() − Returns the track by ID. If the argument is empty or the ID is not found, it returns null. If several tracks have the same ID, it returns the first one." }, { "code": null, "e": 8348, "s": 8166, "text": "MediaStream.getTrackById() − Returns the track by ID. If the argument is empty or the ID is not found, it returns null. If several tracks have the same ID, it returns the first one." }, { "code": null, "e": 8450, "s": 8348, "text": "MediaStream.getTracks() − Returns a list of all MediaStreamTrack objects from the MediaStream object." }, { "code": null, "e": 8552, "s": 8450, "text": "MediaStream.getTracks() − Returns a list of all MediaStreamTrack objects from the MediaStream object." }, { "code": null, "e": 8665, "s": 8552, "text": "MediaStream.getVideoTracks() − Returns a list of the video MediaStreamTrack objects from the MediaStream object." }, { "code": null, "e": 8778, "s": 8665, "text": "MediaStream.getVideoTracks() − Returns a list of the video MediaStreamTrack objects from the MediaStream object." }, { "code": null, "e": 8938, "s": 8778, "text": "MediaStream.removeTrack() − Removes the MediaStreamTrack object given as argument from the MediaStream. If the track has already been removed, nothing happens." }, { "code": null, "e": 9098, "s": 8938, "text": "MediaStream.removeTrack() − Removes the MediaStreamTrack object given as argument from the MediaStream. If the track has already been removed, nothing happens." }, { "code": null, "e": 9173, "s": 9098, "text": "To test the above APIs change change the index.html in the following way −" }, { "code": null, "e": 9889, "s": 9173, "text": "<!DOCTYPE html> \n<html lang = \"en\">\n \n <head> \n <meta charset = \"utf-8\" /> \n </head>\n\t\n <body> \n <video autoplay></video> \n <div><button id = \"btnGetAudioTracks\">getAudioTracks()\n </button></div> \n <div><button id = \"btnGetTrackById\">getTrackById()\n </button></div> \n <div><button id = \"btnGetTracks\">getTracks()</button></div> \n <div><button id = \"btnGetVideoTracks\">getVideoTracks()\n </button></div> \n <div><button id = \"btnRemoveAudioTrack\">removeTrack() - audio\n </button></div> \n <div><button id = \"btnRemoveVideoTrack\">removeTrack() - video\n </button></div> \n <script src = \"client.js\"></script> \n </body> \n\t\n</html>" }, { "code": null, "e": 10050, "s": 9889, "text": "We added a few buttons to try out several MediaStream APIs. Then we should add event handlers for our newly created button. Modify the client.js file this way −" }, { "code": null, "e": 11654, "s": 10050, "text": "var stream;\n \nfunction hasUserMedia() { \n //check if the browser supports the WebRTC \n return !!(navigator.getUserMedia || navigator.webkitGetUserMedia || \n navigator.mozGetUserMedia); \n} \n \nif (hasUserMedia()) {\n navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia\n || navigator.mozGetUserMedia; \n\t\t\n //enabling video and audio channels \n navigator.getUserMedia({ video: true, audio: true }, function (s) { \n stream = s; \n var video = document.querySelector('video'); \n\t\t\n //inserting our stream to the video tag \n video.src = window.URL.createObjectURL(stream); \n }, function (err) {}); \n\t\n} else { \n alert(\"WebRTC is not supported\"); \n}\n \nbtnGetAudioTracks.addEventListener(\"click\", function(){ \n console.log(\"getAudioTracks\"); \n console.log(stream.getAudioTracks()); \n});\n \nbtnGetTrackById.addEventListener(\"click\", function(){ \n console.log(\"getTrackById\"); \n console.log(stream.getTrackById(stream.getAudioTracks()[0].id)); \n});\n \nbtnGetTracks.addEventListener(\"click\", function(){ \n console.log(\"getTracks()\"); \n console.log(stream.getTracks()); \n});\n \nbtnGetVideoTracks.addEventListener(\"click\", function(){ \n console.log(\"getVideoTracks()\"); \n console.log(stream.getVideoTracks()); \n});\n\nbtnRemoveAudioTrack.addEventListener(\"click\", function(){ \n console.log(\"removeAudioTrack()\"); \n stream.removeTrack(stream.getAudioTracks()[0]); \n});\n \nbtnRemoveVideoTrack.addEventListener(\"click\", function(){ \n console.log(\"removeVideoTrack()\"); \n stream.removeTrack(stream.getVideoTracks()[0]); \n});" }, { "code": null, "e": 11840, "s": 11654, "text": "Now refresh your page. Click on the getAudioTracks() button, then click on the removeTrack() - audio button. The audio track should now be removed. Then do the same for the video track." }, { "code": null, "e": 12017, "s": 11840, "text": "If you click the getTracks() button you should see all MediaStreamTracks (all connected video and audio inputs). Then click on the getTrackById() to get audio MediaStreamTrack." } ]
Ruby | Module
10 Oct, 2018 A Module is a collection of methods, constants, and class variables. Modules are defined as a class, but with the module keyword not with class keyword. Important Points about Modules: You cannot inherit modules or you can’t create a subclass of a module. Objects cannot be created from a module. Modules are used as namespaces and as mixins. All the classes are modules, but all the modules are not classes. The class can use namespaces, but they cannot use mixins like modules. The name of a module must start with a capital letter. Syntax: module Module_name # statements to be executed end Example: # Ruby program to illustrate # the module # Creating a module with name Gfgmodule Gfg C = 10; # Prefix with name of Module # module method def Gfg.portal puts "Welcome to GFG Portal!" end # Prefix with the name of Module # module method def Gfg.tutorial puts "Ruby Tutorial!" end # Prefix with the name of Module # module method def Gfg.topic puts "Topic - Module" end end # displaying the value of # module constantputs Gfg::C # calling the methods of the moduleGfg.portalGfg.tutorialGfg.topic Output: 10 Welcome to GFG Portal! Ruby Tutorial! Topic - Module Note: To define module method user have to prefix the name of the module with the method name while defining the method. The benefit of defining module method is that user can call this method by simply using the name of module and dot operator as shown in above example. A user can access the value of a module constant by using the double colon operator(::) as shown in the above example. If the user will define a method with def keyword only inside a module i.e. def method_name then it will consider as an instance method. A user cannot access instance method directly with the use of the dot operator as he cannot make the instance of the module. To access the instance method defined inside the module, the user has to include the module inside a class and then use the class instance to access that method. Below example illustrate this concept clearly. The user can use the module inside the class by using include keyword. In this case, the module works like a namespace. Example: # Ruby program to illustrate how # to use module inside a class # Creating a module with name Gfgmodule Gfg # module method def portal puts "Welcome to GFG Portal!" end # module method def tutorial puts "Ruby Tutorial!" end # module method def topic puts "Topic - Module" end end # Create classclass GeeksforGeeks # Include module in class # by using 'include' keyword include Gfg # Method of the class def add x = 30 + 20 puts x end end # Creating objects of class obj_class = GeeksforGeeks.new # calling module methods# with the help of GeeksforGeeks# class objectobj_class.portal obj_class.tutorialobj_class.topic # Calling class method obj_class.add Output: Welcome to GFG Portal! Ruby Tutorial! Topic - Module 50 Use of Modules: A module is a way categorize the methods and constants so that user can reuse them. Suppose he wants to write two methods and also want to use these methods in multiple programs. So, he will write these methods in a module, so that he can easily call this module in any program with the help of require keyword without re-writing code. Example: # Ruby program for creating a module # define modulemodule Gfg # module method def Gfg.portal() puts "Module Method 1" end # module method def Gfg.tutorial() puts "Module Method 2" end end Note: Save this program in a file named as my.rb. You can use this into another program with the help of require keyword. This is like including the header files in C/C++ program. Using Command: ruby my.rb Now create a another file containing the following code: # Ruby program to show how to use a # module using require keyword # adding module require "./my.rb" # calling the methods of module GfgGfg.portal()Gfg.tutorial() Save this file as my1.rb. Using Command: ruby my1.rb Output: Module Method 1 Module Method 2 Ruby Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Make a Custom Array of Hashes in Ruby? Ruby | Enumerator each_with_index function Ruby | unless Statement and unless Modifier Ruby | Array class find_index() operation Ruby For Beginners Ruby | String concat Method Ruby | Types of Variables Ruby on Rails Introduction Ruby | Array shift() function
[ { "code": null, "e": 52, "s": 24, "text": "\n10 Oct, 2018" }, { "code": null, "e": 205, "s": 52, "text": "A Module is a collection of methods, constants, and class variables. Modules are defined as a class, but with the module keyword not with class keyword." }, { "code": null, "e": 237, "s": 205, "text": "Important Points about Modules:" }, { "code": null, "e": 308, "s": 237, "text": "You cannot inherit modules or you can’t create a subclass of a module." }, { "code": null, "e": 349, "s": 308, "text": "Objects cannot be created from a module." }, { "code": null, "e": 395, "s": 349, "text": "Modules are used as namespaces and as mixins." }, { "code": null, "e": 461, "s": 395, "text": "All the classes are modules, but all the modules are not classes." }, { "code": null, "e": 532, "s": 461, "text": "The class can use namespaces, but they cannot use mixins like modules." }, { "code": null, "e": 587, "s": 532, "text": "The name of a module must start with a capital letter." }, { "code": null, "e": 595, "s": 587, "text": "Syntax:" }, { "code": null, "e": 652, "s": 595, "text": "module Module_name\n\n # statements to be executed\n\nend\n" }, { "code": null, "e": 661, "s": 652, "text": "Example:" }, { "code": "# Ruby program to illustrate # the module # Creating a module with name Gfgmodule Gfg C = 10; # Prefix with name of Module # module method def Gfg.portal puts \"Welcome to GFG Portal!\" end # Prefix with the name of Module # module method def Gfg.tutorial puts \"Ruby Tutorial!\" end # Prefix with the name of Module # module method def Gfg.topic puts \"Topic - Module\" end end # displaying the value of # module constantputs Gfg::C # calling the methods of the moduleGfg.portalGfg.tutorialGfg.topic", "e": 1258, "s": 661, "text": null }, { "code": null, "e": 1266, "s": 1258, "text": "Output:" }, { "code": null, "e": 1323, "s": 1266, "text": "10\nWelcome to GFG Portal!\nRuby Tutorial!\nTopic - Module\n" }, { "code": null, "e": 1329, "s": 1323, "text": "Note:" }, { "code": null, "e": 1595, "s": 1329, "text": "To define module method user have to prefix the name of the module with the method name while defining the method. The benefit of defining module method is that user can call this method by simply using the name of module and dot operator as shown in above example." }, { "code": null, "e": 1714, "s": 1595, "text": "A user can access the value of a module constant by using the double colon operator(::) as shown in the above example." }, { "code": null, "e": 1976, "s": 1714, "text": "If the user will define a method with def keyword only inside a module i.e. def method_name then it will consider as an instance method. A user cannot access instance method directly with the use of the dot operator as he cannot make the instance of the module." }, { "code": null, "e": 2185, "s": 1976, "text": "To access the instance method defined inside the module, the user has to include the module inside a class and then use the class instance to access that method. Below example illustrate this concept clearly." }, { "code": null, "e": 2305, "s": 2185, "text": "The user can use the module inside the class by using include keyword. In this case, the module works like a namespace." }, { "code": null, "e": 2314, "s": 2305, "text": "Example:" }, { "code": "# Ruby program to illustrate how # to use module inside a class # Creating a module with name Gfgmodule Gfg # module method def portal puts \"Welcome to GFG Portal!\" end # module method def tutorial puts \"Ruby Tutorial!\" end # module method def topic puts \"Topic - Module\" end end # Create classclass GeeksforGeeks # Include module in class # by using 'include' keyword include Gfg # Method of the class def add x = 30 + 20 puts x end end # Creating objects of class obj_class = GeeksforGeeks.new # calling module methods# with the help of GeeksforGeeks# class objectobj_class.portal obj_class.tutorialobj_class.topic # Calling class method obj_class.add ", "e": 3114, "s": 2314, "text": null }, { "code": null, "e": 3122, "s": 3114, "text": "Output:" }, { "code": null, "e": 3179, "s": 3122, "text": "Welcome to GFG Portal!\nRuby Tutorial!\nTopic - Module\n50\n" }, { "code": null, "e": 3531, "s": 3179, "text": "Use of Modules: A module is a way categorize the methods and constants so that user can reuse them. Suppose he wants to write two methods and also want to use these methods in multiple programs. So, he will write these methods in a module, so that he can easily call this module in any program with the help of require keyword without re-writing code." }, { "code": null, "e": 3540, "s": 3531, "text": "Example:" }, { "code": "# Ruby program for creating a module # define modulemodule Gfg # module method def Gfg.portal() puts \"Module Method 1\" end # module method def Gfg.tutorial() puts \"Module Method 2\" end end ", "e": 3799, "s": 3540, "text": null }, { "code": null, "e": 3979, "s": 3799, "text": "Note: Save this program in a file named as my.rb. You can use this into another program with the help of require keyword. This is like including the header files in C/C++ program." }, { "code": null, "e": 3994, "s": 3979, "text": "Using Command:" }, { "code": null, "e": 4005, "s": 3994, "text": "ruby my.rb" }, { "code": null, "e": 4062, "s": 4005, "text": "Now create a another file containing the following code:" }, { "code": "# Ruby program to show how to use a # module using require keyword # adding module require \"./my.rb\" # calling the methods of module GfgGfg.portal()Gfg.tutorial()", "e": 4227, "s": 4062, "text": null }, { "code": null, "e": 4253, "s": 4227, "text": "Save this file as my1.rb." }, { "code": null, "e": 4268, "s": 4253, "text": "Using Command:" }, { "code": null, "e": 4280, "s": 4268, "text": "ruby my1.rb" }, { "code": null, "e": 4288, "s": 4280, "text": "Output:" }, { "code": null, "e": 4321, "s": 4288, "text": "Module Method 1\nModule Method 2\n" }, { "code": null, "e": 4326, "s": 4321, "text": "Ruby" }, { "code": null, "e": 4424, "s": 4326, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4470, "s": 4424, "text": "How to Make a Custom Array of Hashes in Ruby?" }, { "code": null, "e": 4513, "s": 4470, "text": "Ruby | Enumerator each_with_index function" }, { "code": null, "e": 4557, "s": 4513, "text": "Ruby | unless Statement and unless Modifier" }, { "code": null, "e": 4599, "s": 4557, "text": "Ruby | Array class find_index() operation" }, { "code": null, "e": 4618, "s": 4599, "text": "Ruby For Beginners" }, { "code": null, "e": 4646, "s": 4618, "text": "Ruby | String concat Method" }, { "code": null, "e": 4672, "s": 4646, "text": "Ruby | Types of Variables" }, { "code": null, "e": 4699, "s": 4672, "text": "Ruby on Rails Introduction" } ]
Python – API.get_status() in Tweepy
05 Jun, 2020 Twitter is a popular social network where users share messages called tweets. Twitter allows us to mine the data of any user using Twitter API or Tweepy. The data will be tweets extracted from the user. The first thing to do is get the consumer key, consumer secret, access key and access secret from twitter developer available easily for each user. These keys will help the API for authentication. The API.get_status() method of the API class in Tweepy module is used to fetch a status / tweet. Syntax : API.get_status(parameters) Parameters : id : The id of the status. trim_user : A boolean indicating if user IDs should be provided, instead of complete user objects. The defaults value is False. Returns : an object of the class Status Example 1 : Consider the following tweet: # import the moduleimport tweepy # assign the values accordinglyconsumer_key = ""consumer_secret = ""access_token = ""access_token_secret = "" # authorization of consumer key and consumer secretauth = tweepy.OAuthHandler(consumer_key, consumer_secret) # set access to user's access key and access secret auth.set_access_token(access_token, access_token_secret) # calling the api api = tweepy.API(auth) # the ID of the statusID = # obtaining the statusstatus = api.get_status(ID) # printing the text of the statusprint("The text of the status is : " + status.text) Output : The text of the tweet is : This is a tweet. Example 2 : Consider the following tweet :Obtaining the screen name, the number of replies and the number of retweets for the above tweet. # the ID of the statusID = 1265569813281280006 # obtaining the statusstatus = api.get_status(ID) # printing the text of the statusprint("The text of the status is : \n\n" + status.text) # printing the screen nameprint("\nThe status was posted by : " + status.user.screen_name) # printing the number of likesprint("The status has been liked " + str(status.favorite_count) + " number of times.") # printing the number of retweetsprint("The status has been retweeted " + str(status.retweet_count) + " number of times.") Output : The text of the status is : Apart from coding, what GEEKS are doing in quarantine? Reply us... #Quarantine #QuarantineLife #coding #programming The status was posted by : geeksforgeeks The status has been liked 25 number of times. The status has been retweeted 3 number of times. Python-Tweepy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to iterate through Excel rows in Python? Rotate axis tick labels in Seaborn and Matplotlib Deque in Python Queue in Python Defaultdict in Python Check if element exists in list in Python Python Classes and Objects Bar Plot in Matplotlib reduce() in Python Python | Get unique values from a list
[ { "code": null, "e": 28, "s": 0, "text": "\n05 Jun, 2020" }, { "code": null, "e": 428, "s": 28, "text": "Twitter is a popular social network where users share messages called tweets. Twitter allows us to mine the data of any user using Twitter API or Tweepy. The data will be tweets extracted from the user. The first thing to do is get the consumer key, consumer secret, access key and access secret from twitter developer available easily for each user. These keys will help the API for authentication." }, { "code": null, "e": 525, "s": 428, "text": "The API.get_status() method of the API class in Tweepy module is used to fetch a status / tweet." }, { "code": null, "e": 561, "s": 525, "text": "Syntax : API.get_status(parameters)" }, { "code": null, "e": 574, "s": 561, "text": "Parameters :" }, { "code": null, "e": 601, "s": 574, "text": "id : The id of the status." }, { "code": null, "e": 729, "s": 601, "text": "trim_user : A boolean indicating if user IDs should be provided, instead of complete user objects. The defaults value is False." }, { "code": null, "e": 769, "s": 729, "text": "Returns : an object of the class Status" }, { "code": null, "e": 811, "s": 769, "text": "Example 1 : Consider the following tweet:" }, { "code": "# import the moduleimport tweepy # assign the values accordinglyconsumer_key = \"\"consumer_secret = \"\"access_token = \"\"access_token_secret = \"\" # authorization of consumer key and consumer secretauth = tweepy.OAuthHandler(consumer_key, consumer_secret) # set access to user's access key and access secret auth.set_access_token(access_token, access_token_secret) # calling the api api = tweepy.API(auth) # the ID of the statusID = # obtaining the statusstatus = api.get_status(ID) # printing the text of the statusprint(\"The text of the status is : \" + status.text)", "e": 1383, "s": 811, "text": null }, { "code": null, "e": 1392, "s": 1383, "text": "Output :" }, { "code": null, "e": 1436, "s": 1392, "text": "The text of the tweet is : This is a tweet." }, { "code": null, "e": 1575, "s": 1436, "text": "Example 2 : Consider the following tweet :Obtaining the screen name, the number of replies and the number of retweets for the above tweet." }, { "code": "# the ID of the statusID = 1265569813281280006 # obtaining the statusstatus = api.get_status(ID) # printing the text of the statusprint(\"The text of the status is : \\n\\n\" + status.text) # printing the screen nameprint(\"\\nThe status was posted by : \" + status.user.screen_name) # printing the number of likesprint(\"The status has been liked \" + str(status.favorite_count) + \" number of times.\") # printing the number of retweetsprint(\"The status has been retweeted \" + str(status.retweet_count) + \" number of times.\")", "e": 2097, "s": 1575, "text": null }, { "code": null, "e": 2106, "s": 2097, "text": "Output :" }, { "code": null, "e": 2392, "s": 2106, "text": "The text of the status is : \n\nApart from coding, what GEEKS are doing in quarantine?\n\nReply us...\n\n#Quarantine #QuarantineLife #coding #programming\n\nThe status was posted by : geeksforgeeks\nThe status has been liked 25 number of times.\nThe status has been retweeted 3 number of times.\n" }, { "code": null, "e": 2406, "s": 2392, "text": "Python-Tweepy" }, { "code": null, "e": 2413, "s": 2406, "text": "Python" }, { "code": null, "e": 2511, "s": 2413, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2556, "s": 2511, "text": "How to iterate through Excel rows in Python?" }, { "code": null, "e": 2606, "s": 2556, "text": "Rotate axis tick labels in Seaborn and Matplotlib" }, { "code": null, "e": 2622, "s": 2606, "text": "Deque in Python" }, { "code": null, "e": 2638, "s": 2622, "text": "Queue in Python" }, { "code": null, "e": 2660, "s": 2638, "text": "Defaultdict in Python" }, { "code": null, "e": 2702, "s": 2660, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2729, "s": 2702, "text": "Python Classes and Objects" }, { "code": null, "e": 2752, "s": 2729, "text": "Bar Plot in Matplotlib" }, { "code": null, "e": 2771, "s": 2752, "text": "reduce() in Python" } ]
Find the farthest smaller number in the right side
13 Jun, 2022 Given an array arr[] of size N. For every element in the array, the task is to find the index of the farthest element in the array to the right which is smaller than the current element. If no such number exists then print -1. Examples: Input: arr[] = {3, 1, 5, 2, 4} Output: 3 -1 4 -1 -1 arr[3] is the farthest smallest element to the right of arr[0]. arr[4] is the farthest smallest element to the right of arr[2]. And for the rest of the elements, there is no smaller element to their right. Input: arr[] = {1, 2, 3, 4, 0} Output: 4 4 4 4 -1 Approach 1 : (Brute Force Method) A brute force approach to this problem can be, keep a variable idx = -1 from beginning and for each element start traversing the same array from the backward upto (i+1)th index. And, if at any index j find smaller element from the current element, i.e. (a[i] > a[j]) break from the loop. Below is the implementation of the above approach : C++ Java C# // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to find the farthest// smaller number in the right sidevoid farthest_min(int a[], int n){ for (int i = 0; i < n; i++) { // keeping the idx = -1 from beginning int idx = -1; // traverse the given array backward for (int j = n - 1; j > i; j--) { // if found any element smaller if (a[i] > a[j]) { // update that index and break idx = j; break; } } // Print the required index cout << idx << " "; }} // Driver codeint main(){ int a[] = { 3, 1, 5, 2, 4 }; int n = sizeof(a) / sizeof(a[0]); farthest_min(a, n); return 0;} // this code is contributed by Rajdeep // Java implementation of the approachclass GFG { // Function to find the farthest // smaller number in the right side static void farthest_min(int[] a, int n) { // To store minimum element // in the range i to n for (int i = 0; i < n; i++) { // keeping the idx = -1 from beginning int idx = -1; for (int j = n - 1; j > i; j--) { // if found any element smaller if (a[i] > a[j]) { // update that index and break idx = j; break; } } System.out.print(idx + " "); } } // Driver code public static void main(String[] args) { int[] a = { 3, 1, 5, 2, 4 }; int n = a.length; farthest_min(a, n); }} // This code is contributed by Rajdeep // C# implementation of the approachusing System;class GFG { // Function to find the farthest // smaller number in the right side static void farthest_min(int[] a, int n) { // To store minimum element // in the range i to n for (int i = 0; i < n; i++) { // keeping the idx = -1 from beginning int idx = -1; for (int j = n - 1; j > i; j--) { // if found any element smaller if (a[i] > a[j]) { // update that index and break idx = j; break; } } Console.Write(idx + " "); } } // Driver code public static void Main() { int[] a = { 3, 1, 5, 2, 4 }; int n = a.Length; farthest_min(a, n); }} // This code is contributed by Samim Hossain Mondal. 3 -1 4 -1 -1 Time Complexity : O(N^2)Auxiliary Space : O(1) Approach 2 : (Optimized Method) An efficient approach is to create a suffix_min[] array where suffix_min[i] stores the minimum element from the subarray arr[i ... N – 1]. Now for any element arr[i], binary search can be used on the subarray suffix_min[i + 1 ... N – 1] to find the farthest smallest element to the right of arr[i]. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to find the farthest// smaller number in the right sidevoid farthest_min(int a[], int n){ // To store minimum element // in the range i to n int suffix_min[n]; suffix_min[n - 1] = a[n - 1]; for (int i = n - 2; i >= 0; i--) { suffix_min[i] = min(suffix_min[i + 1], a[i]); } for (int i = 0; i < n; i++) { int low = i + 1, high = n - 1, ans = -1; while (low <= high) { int mid = (low + high) / 2; // If current element in the suffix_min // is less than a[i] then move right if (suffix_min[mid] < a[i]) { ans = mid; low = mid + 1; } else high = mid - 1; } // Print the required answer cout << ans << " "; }} // Driver codeint main(){ int a[] = { 3, 1, 5, 2, 4 }; int n = sizeof(a) / sizeof(a[0]); farthest_min(a, n); return 0;} // Java implementation of the approachclass GFG { // Function to find the farthest // smaller number in the right side static void farthest_min(int[] a, int n) { // To store minimum element // in the range i to n int[] suffix_min = new int[n]; suffix_min[n - 1] = a[n - 1]; for (int i = n - 2; i >= 0; i--) { suffix_min[i] = Math.min(suffix_min[i + 1], a[i]); } for (int i = 0; i < n; i++) { int low = i + 1, high = n - 1, ans = -1; while (low <= high) { int mid = (low + high) / 2; // If current element in the suffix_min // is less than a[i] then move right if (suffix_min[mid] < a[i]) { ans = mid; low = mid + 1; } else high = mid - 1; } // Print the required answer System.out.print(ans + " "); } } // Driver code public static void main(String[] args) { int[] a = { 3, 1, 5, 2, 4 }; int n = a.length; farthest_min(a, n); }} // This code is contributed by ihritik # Python3 implementation of the approach # Function to find the farthest# smaller number in the right side def farthest_min(a, n): # To store minimum element # in the range i to n suffix_min = [0 for i in range(n)] suffix_min[n - 1] = a[n - 1] for i in range(n - 2, -1, -1): suffix_min[i] = min(suffix_min[i + 1], a[i]) for i in range(n): low = i + 1 high = n - 1 ans = -1 while (low <= high): mid = (low + high) // 2 # If current element in the suffix_min # is less than a[i] then move right if (suffix_min[mid] < a[i]): ans = mid low = mid + 1 else: high = mid - 1 # Print the required answer print(ans, end=" ") # Driver codea = [3, 1, 5, 2, 4]n = len(a) farthest_min(a, n) # This code is contributed by Mohit Kumar // C# implementation of the approachusing System;class GFG { // Function to find the farthest // smaller number in the right side static void farthest_min(int[] a, int n) { // To store minimum element // in the range i to n int[] suffix_min = new int[n]; suffix_min[n - 1] = a[n - 1]; for (int i = n - 2; i >= 0; i--) { suffix_min[i] = Math.Min(suffix_min[i + 1], a[i]); } for (int i = 0; i < n; i++) { int low = i + 1, high = n - 1, ans = -1; while (low <= high) { int mid = (low + high) / 2; // If current element in the suffix_min // is less than a[i] then move right if (suffix_min[mid] < a[i]) { ans = mid; low = mid + 1; } else high = mid - 1; } // Print the required answer Console.Write(ans + " "); } } // Driver code public static void Main() { int[] a = { 3, 1, 5, 2, 4 }; int n = a.Length; farthest_min(a, n); }} // This code is contributed by ihritik Javascript<script> // Javascript implementation of the approach // Function to find the farthest// smaller number in the right sidefunction farthest_min(a, n){ // To store minimum element // in the range i to n let suffix_min = new Array(n); suffix_min[n - 1] = a[n - 1]; for (let i = n - 2; i >= 0; i--) { suffix_min[i] = Math.min(suffix_min[i + 1], a[i]); } for (let i = 0; i < n; i++) { let low = i + 1, high = n - 1, ans = -1; while (low <= high) { let mid = Math.floor((low + high) / 2); // If current element in the suffix_min // is less than a[i] then move right if (suffix_min[mid] < a[i]) { ans = mid; low = mid + 1; } else high = mid - 1; } // Print the required answer document.write(ans + " "); }} // Driver code let a = [ 3, 1, 5, 2, 4 ]; let n = a.length; farthest_min(a, n); //This code is contributed by Mayank Tyagi </script> 3 -1 4 -1 -1 Time Complexity: O(N* log(N) )Auxiliary Space: O(N) mohit kumar 29 ihritik nidhi_biet ujjwalgoel1103 mayanktyagi1709 gulshankumarar231 rajdeepmallick999 samim2000 Binary Search Suffix-Array Arrays Searching Arrays Searching Binary Search Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n13 Jun, 2022" }, { "code": null, "e": 282, "s": 54, "text": "Given an array arr[] of size N. For every element in the array, the task is to find the index of the farthest element in the array to the right which is smaller than the current element. If no such number exists then print -1. " }, { "code": null, "e": 293, "s": 282, "text": "Examples: " }, { "code": null, "e": 551, "s": 293, "text": "Input: arr[] = {3, 1, 5, 2, 4} Output: 3 -1 4 -1 -1 arr[3] is the farthest smallest element to the right of arr[0]. arr[4] is the farthest smallest element to the right of arr[2]. And for the rest of the elements, there is no smaller element to their right." }, { "code": null, "e": 602, "s": 551, "text": "Input: arr[] = {1, 2, 3, 4, 0} Output: 4 4 4 4 -1 " }, { "code": null, "e": 636, "s": 602, "text": "Approach 1 : (Brute Force Method)" }, { "code": null, "e": 925, "s": 636, "text": "A brute force approach to this problem can be, keep a variable idx = -1 from beginning and for each element start traversing the same array from the backward upto (i+1)th index. And, if at any index j find smaller element from the current element, i.e. (a[i] > a[j]) break from the loop." }, { "code": null, "e": 977, "s": 925, "text": "Below is the implementation of the above approach :" }, { "code": null, "e": 981, "s": 977, "text": "C++" }, { "code": null, "e": 986, "s": 981, "text": "Java" }, { "code": null, "e": 989, "s": 986, "text": "C#" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to find the farthest// smaller number in the right sidevoid farthest_min(int a[], int n){ for (int i = 0; i < n; i++) { // keeping the idx = -1 from beginning int idx = -1; // traverse the given array backward for (int j = n - 1; j > i; j--) { // if found any element smaller if (a[i] > a[j]) { // update that index and break idx = j; break; } } // Print the required index cout << idx << \" \"; }} // Driver codeint main(){ int a[] = { 3, 1, 5, 2, 4 }; int n = sizeof(a) / sizeof(a[0]); farthest_min(a, n); return 0;} // this code is contributed by Rajdeep", "e": 1807, "s": 989, "text": null }, { "code": "// Java implementation of the approachclass GFG { // Function to find the farthest // smaller number in the right side static void farthest_min(int[] a, int n) { // To store minimum element // in the range i to n for (int i = 0; i < n; i++) { // keeping the idx = -1 from beginning int idx = -1; for (int j = n - 1; j > i; j--) { // if found any element smaller if (a[i] > a[j]) { // update that index and break idx = j; break; } } System.out.print(idx + \" \"); } } // Driver code public static void main(String[] args) { int[] a = { 3, 1, 5, 2, 4 }; int n = a.length; farthest_min(a, n); }} // This code is contributed by Rajdeep", "e": 2714, "s": 1807, "text": null }, { "code": "// C# implementation of the approachusing System;class GFG { // Function to find the farthest // smaller number in the right side static void farthest_min(int[] a, int n) { // To store minimum element // in the range i to n for (int i = 0; i < n; i++) { // keeping the idx = -1 from beginning int idx = -1; for (int j = n - 1; j > i; j--) { // if found any element smaller if (a[i] > a[j]) { // update that index and break idx = j; break; } } Console.Write(idx + \" \"); } } // Driver code public static void Main() { int[] a = { 3, 1, 5, 2, 4 }; int n = a.Length; farthest_min(a, n); }} // This code is contributed by Samim Hossain Mondal.", "e": 3594, "s": 2714, "text": null }, { "code": null, "e": 3608, "s": 3594, "text": "3 -1 4 -1 -1 " }, { "code": null, "e": 3656, "s": 3608, "text": "Time Complexity : O(N^2)Auxiliary Space : O(1)" }, { "code": null, "e": 3688, "s": 3656, "text": "Approach 2 : (Optimized Method)" }, { "code": null, "e": 3987, "s": 3688, "text": "An efficient approach is to create a suffix_min[] array where suffix_min[i] stores the minimum element from the subarray arr[i ... N – 1]. Now for any element arr[i], binary search can be used on the subarray suffix_min[i + 1 ... N – 1] to find the farthest smallest element to the right of arr[i]." }, { "code": null, "e": 4039, "s": 3987, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 4043, "s": 4039, "text": "C++" }, { "code": null, "e": 4048, "s": 4043, "text": "Java" }, { "code": null, "e": 4056, "s": 4048, "text": "Python3" }, { "code": null, "e": 4059, "s": 4056, "text": "C#" }, { "code": null, "e": 4070, "s": 4059, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to find the farthest// smaller number in the right sidevoid farthest_min(int a[], int n){ // To store minimum element // in the range i to n int suffix_min[n]; suffix_min[n - 1] = a[n - 1]; for (int i = n - 2; i >= 0; i--) { suffix_min[i] = min(suffix_min[i + 1], a[i]); } for (int i = 0; i < n; i++) { int low = i + 1, high = n - 1, ans = -1; while (low <= high) { int mid = (low + high) / 2; // If current element in the suffix_min // is less than a[i] then move right if (suffix_min[mid] < a[i]) { ans = mid; low = mid + 1; } else high = mid - 1; } // Print the required answer cout << ans << \" \"; }} // Driver codeint main(){ int a[] = { 3, 1, 5, 2, 4 }; int n = sizeof(a) / sizeof(a[0]); farthest_min(a, n); return 0;}", "e": 5083, "s": 4070, "text": null }, { "code": "// Java implementation of the approachclass GFG { // Function to find the farthest // smaller number in the right side static void farthest_min(int[] a, int n) { // To store minimum element // in the range i to n int[] suffix_min = new int[n]; suffix_min[n - 1] = a[n - 1]; for (int i = n - 2; i >= 0; i--) { suffix_min[i] = Math.min(suffix_min[i + 1], a[i]); } for (int i = 0; i < n; i++) { int low = i + 1, high = n - 1, ans = -1; while (low <= high) { int mid = (low + high) / 2; // If current element in the suffix_min // is less than a[i] then move right if (suffix_min[mid] < a[i]) { ans = mid; low = mid + 1; } else high = mid - 1; } // Print the required answer System.out.print(ans + \" \"); } } // Driver code public static void main(String[] args) { int[] a = { 3, 1, 5, 2, 4 }; int n = a.length; farthest_min(a, n); }} // This code is contributed by ihritik", "e": 6291, "s": 5083, "text": null }, { "code": "# Python3 implementation of the approach # Function to find the farthest# smaller number in the right side def farthest_min(a, n): # To store minimum element # in the range i to n suffix_min = [0 for i in range(n)] suffix_min[n - 1] = a[n - 1] for i in range(n - 2, -1, -1): suffix_min[i] = min(suffix_min[i + 1], a[i]) for i in range(n): low = i + 1 high = n - 1 ans = -1 while (low <= high): mid = (low + high) // 2 # If current element in the suffix_min # is less than a[i] then move right if (suffix_min[mid] < a[i]): ans = mid low = mid + 1 else: high = mid - 1 # Print the required answer print(ans, end=\" \") # Driver codea = [3, 1, 5, 2, 4]n = len(a) farthest_min(a, n) # This code is contributed by Mohit Kumar", "e": 7184, "s": 6291, "text": null }, { "code": "// C# implementation of the approachusing System;class GFG { // Function to find the farthest // smaller number in the right side static void farthest_min(int[] a, int n) { // To store minimum element // in the range i to n int[] suffix_min = new int[n]; suffix_min[n - 1] = a[n - 1]; for (int i = n - 2; i >= 0; i--) { suffix_min[i] = Math.Min(suffix_min[i + 1], a[i]); } for (int i = 0; i < n; i++) { int low = i + 1, high = n - 1, ans = -1; while (low <= high) { int mid = (low + high) / 2; // If current element in the suffix_min // is less than a[i] then move right if (suffix_min[mid] < a[i]) { ans = mid; low = mid + 1; } else high = mid - 1; } // Print the required answer Console.Write(ans + \" \"); } } // Driver code public static void Main() { int[] a = { 3, 1, 5, 2, 4 }; int n = a.Length; farthest_min(a, n); }} // This code is contributed by ihritik", "e": 8387, "s": 7184, "text": null }, { "code": "Javascript<script> // Javascript implementation of the approach // Function to find the farthest// smaller number in the right sidefunction farthest_min(a, n){ // To store minimum element // in the range i to n let suffix_min = new Array(n); suffix_min[n - 1] = a[n - 1]; for (let i = n - 2; i >= 0; i--) { suffix_min[i] = Math.min(suffix_min[i + 1], a[i]); } for (let i = 0; i < n; i++) { let low = i + 1, high = n - 1, ans = -1; while (low <= high) { let mid = Math.floor((low + high) / 2); // If current element in the suffix_min // is less than a[i] then move right if (suffix_min[mid] < a[i]) { ans = mid; low = mid + 1; } else high = mid - 1; } // Print the required answer document.write(ans + \" \"); }} // Driver code let a = [ 3, 1, 5, 2, 4 ]; let n = a.length; farthest_min(a, n); //This code is contributed by Mayank Tyagi </script>", "e": 9426, "s": 8387, "text": null }, { "code": null, "e": 9440, "s": 9426, "text": "3 -1 4 -1 -1 " }, { "code": null, "e": 9492, "s": 9440, "text": "Time Complexity: O(N* log(N) )Auxiliary Space: O(N)" }, { "code": null, "e": 9507, "s": 9492, "text": "mohit kumar 29" }, { "code": null, "e": 9515, "s": 9507, "text": "ihritik" }, { "code": null, "e": 9526, "s": 9515, "text": "nidhi_biet" }, { "code": null, "e": 9541, "s": 9526, "text": "ujjwalgoel1103" }, { "code": null, "e": 9557, "s": 9541, "text": "mayanktyagi1709" }, { "code": null, "e": 9575, "s": 9557, "text": "gulshankumarar231" }, { "code": null, "e": 9593, "s": 9575, "text": "rajdeepmallick999" }, { "code": null, "e": 9603, "s": 9593, "text": "samim2000" }, { "code": null, "e": 9617, "s": 9603, "text": "Binary Search" }, { "code": null, "e": 9630, "s": 9617, "text": "Suffix-Array" }, { "code": null, "e": 9637, "s": 9630, "text": "Arrays" }, { "code": null, "e": 9647, "s": 9637, "text": "Searching" }, { "code": null, "e": 9654, "s": 9647, "text": "Arrays" }, { "code": null, "e": 9664, "s": 9654, "text": "Searching" }, { "code": null, "e": 9678, "s": 9664, "text": "Binary Search" } ]
Using Single-Row Functions
Oracle SQL supplies a rich library of in-built functions which can be employed for various tasks. The essential capabilities of a functions can be the case conversion of strings, in-string or substring operations, mathematical computations on numeric data, and date operations on date type values. SQL Functions optionally take arguments from the user and mandatorily return a value. On a broader category, there are two types of functions :- Single Row functions - Single row functions are the one who work on single row and return one output per row. For example, length and case conversion functions are single row functions. Multiple Row functions - Multiple row functions work upon group of rows and return one result for the complete set of rows. They are also known as Group Functions. Single row functions can be character functions, numeric functions, date functions, and conversion functions. Note that these functions are used to manipulate data items. These functions require one or more input arguments and operate on each row, thereby returning one output value for each row. Argument can be a column, literal or an expression. Single row functions can be used in SELECT statement, WHERE and ORDER BY clause. Single row functions can be - General functions - Usually contains NULL handling functions. The functions under the category are NVL, NVL2, NULLIF, COALESCE, CASE, DECODE. General functions - Usually contains NULL handling functions. The functions under the category are NVL, NVL2, NULLIF, COALESCE, CASE, DECODE. Case Conversion functions - Accepts character input and returns a character value. Functions under the category are UPPER, LOWER and INITCAP. UPPER function converts a string to upper case. LOWER function converts a string to lower case. INITCAP function converts only the initial alphabets of a string to upper case. Case Conversion functions - Accepts character input and returns a character value. Functions under the category are UPPER, LOWER and INITCAP. UPPER function converts a string to upper case. UPPER function converts a string to upper case. LOWER function converts a string to lower case. LOWER function converts a string to lower case. INITCAP function converts only the initial alphabets of a string to upper case. INITCAP function converts only the initial alphabets of a string to upper case. Character functions - Accepts character input and returns number or character value. Functions under the category are CONCAT, LENGTH, SUBSTR, INSTR, LPAD, RPAD, TRIM and REPLACE. CONCAT function concatenates two string values. LENGTH function returns the length of the input string. SUBSTR function returns a portion of a string from a given start point to an end point. INSTR function returns numeric position of a character or a string in a given string. LPAD and RPAD functions pad the given string upto a specific length with a given character. TRIM function trims the string input from the start or end. REPLACE function replaces characters from the input string with a given character. Character functions - Accepts character input and returns number or character value. Functions under the category are CONCAT, LENGTH, SUBSTR, INSTR, LPAD, RPAD, TRIM and REPLACE. CONCAT function concatenates two string values. CONCAT function concatenates two string values. LENGTH function returns the length of the input string. LENGTH function returns the length of the input string. SUBSTR function returns a portion of a string from a given start point to an end point. SUBSTR function returns a portion of a string from a given start point to an end point. INSTR function returns numeric position of a character or a string in a given string. INSTR function returns numeric position of a character or a string in a given string. LPAD and RPAD functions pad the given string upto a specific length with a given character. LPAD and RPAD functions pad the given string upto a specific length with a given character. TRIM function trims the string input from the start or end. TRIM function trims the string input from the start or end. REPLACE function replaces characters from the input string with a given character. REPLACE function replaces characters from the input string with a given character. Date functions - Date arithmetic operations return date or numeric values. Functions under the category are MONTHS_BETWEEN, ADD_MONTHS, NEXT_DAY, LAST_DAY, ROUND and TRUNC. MONTHS_BETWEEN function returns the count of months between the two dates. ADD_MONTHS function add 'n' number of months to an input date. NEXT_DAY function returns the next day of the date specified. LAST_DAY function returns last day of the month of the input date. ROUND and TRUNC functions are used to round and truncates the date value. Date functions - Date arithmetic operations return date or numeric values. Functions under the category are MONTHS_BETWEEN, ADD_MONTHS, NEXT_DAY, LAST_DAY, ROUND and TRUNC. MONTHS_BETWEEN function returns the count of months between the two dates. MONTHS_BETWEEN function returns the count of months between the two dates. ADD_MONTHS function add 'n' number of months to an input date. ADD_MONTHS function add 'n' number of months to an input date. NEXT_DAY function returns the next day of the date specified. NEXT_DAY function returns the next day of the date specified. LAST_DAY function returns last day of the month of the input date. LAST_DAY function returns last day of the month of the input date. ROUND and TRUNC functions are used to round and truncates the date value. ROUND and TRUNC functions are used to round and truncates the date value. Number functions - Accepts numeric input and returns numeric values. Functions under the category are ROUND, TRUNC, and MOD. ROUND and TRUNC functions are used to round and truncate the number value. MOD is used to return the remainder of the division operation between two numbers. Number functions - Accepts numeric input and returns numeric values. Functions under the category are ROUND, TRUNC, and MOD. ROUND and TRUNC functions are used to round and truncate the number value. ROUND and TRUNC functions are used to round and truncate the number value. MOD is used to return the remainder of the division operation between two numbers. MOD is used to return the remainder of the division operation between two numbers. The SELECT query below demonstrates the use of NVL function. SELECT first_name, last_name, salary, NVL (commission_pct,0) FROM employees WHERE rownum < 5; FIRST_NAME LAST_NAME SALARY NVL(COMMISSION_PCT,0) -------------------- ------------------------- ---------- --------------------- Steven King 24000 0 Neena Kochhar 17000 0 Lex De Haan 17000 0 Alexander Hunold 9000 0 The SELECT query below demonstrates the use of case conversion functions. SELECT UPPER (first_name), INITCAP (last_name), LOWER (job_id) FROM employees WHERE rownum < 5; UPPER(FIRST_NAME) INITCAP(LAST_NAME) LOWER(JOB_ -------------------- ------------------------- ---------- STEVEN King ad_pres NEENA Kochhar ad_vp LEX De Haan ad_vp ALEXANDER Hunold it_prog The SELECT query below demonstrates the use of CONCAT function to concatenate two string values. SELECT CONCAT (first_name, last_name) FROM employees WHERE rownum < 5; CONCAT(FIRST_NAME,LAST_NAME) -------------------------------- EllenAbel SundarAnde MozheAtkinson DavidAustin The SELECT query below demonstrates the use of SUBSTR and INSTR functions. SUBSTR function returns the portion of input string from 1st position to 5th position. INSTR function returns the numeric position of character 'a' in the first name. SELECT SUBSTR (first_name,1,5), INSTR (first_name,'a') FROM employees WHERE rownum < 5; SUBST INSTR(FIRST_NAME,'A') ----- --------------------- Ellen 0 Sunda 5 Mozhe 0 David 2 The SELECT query below demonstrates the usage of LPAD and RPAD to pretty print the employee and job information. SELECT RPAD(first_name,10,'_')||LPAD (job_id,15,'_') FROM employees WHERE rownum < 5; RPAD(FIRST_NAME,10,'_')|| ------------------------- Steven____________AD_PRES Neena_______________AD_VP Lex_________________AD_VP Alexander_________IT_PROG The SELECT query below demonstrates the use of ROUND and TRUNC functions. SELECT ROUND (1372.472,1) FROM dual; ROUND(1372.472,1) ----------------- 1372.5 SELECT TRUNC (72183,-2) FROM dual; TRUNC(72183,-2) --------------- 72100 The SELECT query below shows a date arithmetic function where difference of employee hire date and sysdate is done. SELECT employee_id, (sysdate - hire_date) Employment_days FROM employees WHERE rownum < 5; EMPLOYEE_ID EMPLOYMENT_DAYS ----------- --------------- 100 3698.61877 101 2871.61877 102 4583.61877 103 2767.61877 The SELECT query below demonstrates the use of MONTHS_BETWEEN, ADD_MONTHS, NEXT_DAY and LAST_DAY functions. SELECT employee_id, MONTHS_BETWEEN (sysdate, hire_date) Employment_months FROM employees WHERE rownum < 5; EMPLOYEE_ID EMPLOYMENT_MONTHS ----------- ----------------- 100 121.504216 101 94.3751837 102 150.633248 103 90.9558289 SELECT ADD_MONTHS (sysdate, 5), NEXT_DAY (sysdate), LAST_DAY (sysdate) FROM dual; ADD_MONTH NEXT_DAY( LAST_DAY( --------- --------- --------- 01-JAN-14 05-AUG-13 31-AUG-13
[ { "code": null, "e": 2981, "s": 2597, "text": "Oracle SQL supplies a rich library of in-built functions which can be employed for various tasks. The essential capabilities of a functions can be the case conversion of strings, in-string or substring operations, mathematical computations on numeric data, and date operations on date type values. SQL Functions optionally take arguments from the user and mandatorily return a value." }, { "code": null, "e": 3041, "s": 2981, "text": "On a broader category, there are two types of functions :- " }, { "code": null, "e": 3227, "s": 3041, "text": "Single Row functions - Single row functions are the one who work on single row and return one output per row. For example, length and case conversion functions are single row functions." }, { "code": null, "e": 3391, "s": 3227, "text": "Multiple Row functions - Multiple row functions work upon group of rows and return one result for the complete set of rows. They are also known as Group Functions." }, { "code": null, "e": 3851, "s": 3391, "text": "Single row functions can be character functions, numeric functions, date functions, and conversion functions. Note that these functions are used to manipulate data items. These functions require one or more input arguments and operate on each row, thereby returning one output value for each row. Argument can be a column, literal or an expression. Single row functions can be used in SELECT statement, WHERE and ORDER BY clause. Single row functions can be -" }, { "code": null, "e": 3993, "s": 3851, "text": "General functions - Usually contains NULL handling functions. The functions under the category are NVL, NVL2, NULLIF, COALESCE, CASE, DECODE." }, { "code": null, "e": 4135, "s": 3993, "text": "General functions - Usually contains NULL handling functions. The functions under the category are NVL, NVL2, NULLIF, COALESCE, CASE, DECODE." }, { "code": null, "e": 4457, "s": 4135, "text": "Case Conversion functions - Accepts character input and returns a character value. Functions under the category are UPPER, LOWER and INITCAP.\n\nUPPER function converts a string to upper case.\nLOWER function converts a string to lower case.\nINITCAP function converts only the initial alphabets of a string to upper case. \n\n" }, { "code": null, "e": 4599, "s": 4457, "text": "Case Conversion functions - Accepts character input and returns a character value. Functions under the category are UPPER, LOWER and INITCAP." }, { "code": null, "e": 4647, "s": 4599, "text": "UPPER function converts a string to upper case." }, { "code": null, "e": 4695, "s": 4647, "text": "UPPER function converts a string to upper case." }, { "code": null, "e": 4743, "s": 4695, "text": "LOWER function converts a string to lower case." }, { "code": null, "e": 4791, "s": 4743, "text": "LOWER function converts a string to lower case." }, { "code": null, "e": 4872, "s": 4791, "text": "INITCAP function converts only the initial alphabets of a string to upper case. " }, { "code": null, "e": 4953, "s": 4872, "text": "INITCAP function converts only the initial alphabets of a string to upper case. " }, { "code": null, "e": 5650, "s": 4955, "text": "Character functions - Accepts character input and returns number or character value. Functions under the category are CONCAT, LENGTH, SUBSTR, INSTR, LPAD, RPAD, TRIM and REPLACE.\n\nCONCAT function concatenates two string values.\nLENGTH function returns the length of the input string.\nSUBSTR function returns a portion of a string from a given start point to an end point.\nINSTR function returns numeric position of a character or a string in a given string.\nLPAD and RPAD functions pad the given string upto a specific length with a given character.\nTRIM function trims the string input from the start or end.\nREPLACE function replaces characters from the input string with a given character.\n\n" }, { "code": null, "e": 5830, "s": 5650, "text": "Character functions - Accepts character input and returns number or character value. Functions under the category are CONCAT, LENGTH, SUBSTR, INSTR, LPAD, RPAD, TRIM and REPLACE.\n" }, { "code": null, "e": 5878, "s": 5830, "text": "CONCAT function concatenates two string values." }, { "code": null, "e": 5926, "s": 5878, "text": "CONCAT function concatenates two string values." }, { "code": null, "e": 5982, "s": 5926, "text": "LENGTH function returns the length of the input string." }, { "code": null, "e": 6038, "s": 5982, "text": "LENGTH function returns the length of the input string." }, { "code": null, "e": 6126, "s": 6038, "text": "SUBSTR function returns a portion of a string from a given start point to an end point." }, { "code": null, "e": 6214, "s": 6126, "text": "SUBSTR function returns a portion of a string from a given start point to an end point." }, { "code": null, "e": 6300, "s": 6214, "text": "INSTR function returns numeric position of a character or a string in a given string." }, { "code": null, "e": 6386, "s": 6300, "text": "INSTR function returns numeric position of a character or a string in a given string." }, { "code": null, "e": 6478, "s": 6386, "text": "LPAD and RPAD functions pad the given string upto a specific length with a given character." }, { "code": null, "e": 6570, "s": 6478, "text": "LPAD and RPAD functions pad the given string upto a specific length with a given character." }, { "code": null, "e": 6630, "s": 6570, "text": "TRIM function trims the string input from the start or end." }, { "code": null, "e": 6690, "s": 6630, "text": "TRIM function trims the string input from the start or end." }, { "code": null, "e": 6773, "s": 6690, "text": "REPLACE function replaces characters from the input string with a given character." }, { "code": null, "e": 6856, "s": 6773, "text": "REPLACE function replaces characters from the input string with a given character." }, { "code": null, "e": 7373, "s": 6856, "text": "Date functions - Date arithmetic operations return date or numeric values. Functions under the category are MONTHS_BETWEEN, ADD_MONTHS, NEXT_DAY, LAST_DAY, ROUND and TRUNC.\n\nMONTHS_BETWEEN function returns the count of months between the two dates.\nADD_MONTHS function add 'n' number of months to an input date.\nNEXT_DAY function returns the next day of the date specified.\nLAST_DAY function returns last day of the month of the input date.\nROUND and TRUNC functions are used to round and truncates the date value.\n\n" }, { "code": null, "e": 7547, "s": 7373, "text": "Date functions - Date arithmetic operations return date or numeric values. Functions under the category are MONTHS_BETWEEN, ADD_MONTHS, NEXT_DAY, LAST_DAY, ROUND and TRUNC.\n" }, { "code": null, "e": 7622, "s": 7547, "text": "MONTHS_BETWEEN function returns the count of months between the two dates." }, { "code": null, "e": 7697, "s": 7622, "text": "MONTHS_BETWEEN function returns the count of months between the two dates." }, { "code": null, "e": 7760, "s": 7697, "text": "ADD_MONTHS function add 'n' number of months to an input date." }, { "code": null, "e": 7823, "s": 7760, "text": "ADD_MONTHS function add 'n' number of months to an input date." }, { "code": null, "e": 7885, "s": 7823, "text": "NEXT_DAY function returns the next day of the date specified." }, { "code": null, "e": 7947, "s": 7885, "text": "NEXT_DAY function returns the next day of the date specified." }, { "code": null, "e": 8014, "s": 7947, "text": "LAST_DAY function returns last day of the month of the input date." }, { "code": null, "e": 8081, "s": 8014, "text": "LAST_DAY function returns last day of the month of the input date." }, { "code": null, "e": 8155, "s": 8081, "text": "ROUND and TRUNC functions are used to round and truncates the date value." }, { "code": null, "e": 8229, "s": 8155, "text": "ROUND and TRUNC functions are used to round and truncates the date value." }, { "code": null, "e": 8518, "s": 8229, "text": "Number functions - Accepts numeric input and returns numeric values. Functions under the category are ROUND, TRUNC, and MOD. \n\n\tROUND and TRUNC functions are used to round and truncate the number value.\n\tMOD is used to return the remainder of the division operation between two numbers.\n\n" }, { "code": null, "e": 8645, "s": 8518, "text": "Number functions - Accepts numeric input and returns numeric values. Functions under the category are ROUND, TRUNC, and MOD. \n" }, { "code": null, "e": 8721, "s": 8645, "text": "\tROUND and TRUNC functions are used to round and truncate the number value." }, { "code": null, "e": 8797, "s": 8721, "text": "\tROUND and TRUNC functions are used to round and truncate the number value." }, { "code": null, "e": 8881, "s": 8797, "text": "\tMOD is used to return the remainder of the division operation between two numbers." }, { "code": null, "e": 8965, "s": 8881, "text": "\tMOD is used to return the remainder of the division operation between two numbers." }, { "code": null, "e": 9027, "s": 8965, "text": "The SELECT query below demonstrates the use of NVL function. " }, { "code": null, "e": 9603, "s": 9027, "text": "SELECT first_name, last_name, salary, NVL (commission_pct,0) \nFROM employees\nWHERE rownum < 5;\n\nFIRST_NAME LAST_NAME SALARY NVL(COMMISSION_PCT,0)\n-------------------- ------------------------- ---------- ---------------------\nSteven King 24000 0\nNeena Kochhar 17000 0\nLex De Haan 17000 0\nAlexander Hunold 9000 0" }, { "code": null, "e": 9677, "s": 9603, "text": "The SELECT query below demonstrates the use of case conversion functions." }, { "code": null, "e": 10106, "s": 9677, "text": "SELECT UPPER (first_name), INITCAP (last_name), LOWER (job_id)\nFROM employees\nWHERE rownum < 5;\n\nUPPER(FIRST_NAME) INITCAP(LAST_NAME) LOWER(JOB_\n-------------------- ------------------------- ----------\nSTEVEN King ad_pres\nNEENA Kochhar ad_vp\nLEX De Haan ad_vp\nALEXANDER Hunold it_prog" }, { "code": null, "e": 10203, "s": 10106, "text": "The SELECT query below demonstrates the use of CONCAT function to concatenate two string values." }, { "code": null, "e": 10385, "s": 10203, "text": "SELECT CONCAT (first_name, last_name) \nFROM employees\nWHERE rownum < 5;\n\nCONCAT(FIRST_NAME,LAST_NAME)\n--------------------------------\nEllenAbel\nSundarAnde\nMozheAtkinson\nDavidAustin" }, { "code": null, "e": 10627, "s": 10385, "text": "The SELECT query below demonstrates the use of SUBSTR and INSTR functions. SUBSTR function returns the portion of input string from 1st position to 5th position. INSTR function returns the numeric position of character 'a' in the first name." }, { "code": null, "e": 10884, "s": 10627, "text": "SELECT SUBSTR (first_name,1,5), INSTR (first_name,'a')\nFROM employees\nWHERE rownum < 5;\n\nSUBST INSTR(FIRST_NAME,'A')\n----- ---------------------\nEllen 0\nSunda 5\nMozhe 0\nDavid 2" }, { "code": null, "e": 10998, "s": 10884, "text": "\nThe SELECT query below demonstrates the usage of LPAD and RPAD to pretty print the employee and job information." }, { "code": null, "e": 11241, "s": 10998, "text": "SELECT RPAD(first_name,10,'_')||LPAD (job_id,15,'_')\nFROM employees\nWHERE rownum < 5;\n\nRPAD(FIRST_NAME,10,'_')||\n-------------------------\nSteven____________AD_PRES\nNeena_______________AD_VP\nLex_________________AD_VP\nAlexander_________IT_PROG" }, { "code": null, "e": 11315, "s": 11241, "text": "The SELECT query below demonstrates the use of ROUND and TRUNC functions." }, { "code": null, "e": 11492, "s": 11315, "text": "SELECT ROUND (1372.472,1)\nFROM dual;\n\nROUND(1372.472,1)\n-----------------\n 1372.5\n\nSELECT TRUNC (72183,-2)\nFROM dual;\n\nTRUNC(72183,-2)\n---------------\n 72100" }, { "code": null, "e": 11608, "s": 11492, "text": "The SELECT query below shows a date arithmetic function where difference of employee hire date and sysdate is done." }, { "code": null, "e": 11877, "s": 11608, "text": "SELECT employee_id, (sysdate - hire_date) Employment_days\nFROM employees\nWHERE rownum < 5;\n\nEMPLOYEE_ID EMPLOYMENT_DAYS\n----------- ---------------\n 100 3698.61877\n 101 2871.61877\n 102 4583.61877\n 103 2767.61877\n " }, { "code": null, "e": 11985, "s": 11877, "text": "The SELECT query below demonstrates the use of MONTHS_BETWEEN, ADD_MONTHS, NEXT_DAY and LAST_DAY functions." } ]
How to Upload File using formidable module in Node.js ?
27 Apr, 2020 Formidable module is used for parsing form data, especially file uploads. It is easy to use and integrate into your project for handling incoming form data and file uploads. Installation of formidable module: You can visit the link Install formidable module. You can install this package by using this command.npm install formidableAfter installing formidable module, you can check your yargs version in command prompt using the command.npm version formidableAfter that, you can just create a folder and add a file for example index.js, To run this file you need to run the following command.node index.js You can visit the link Install formidable module. You can install this package by using this command.npm install formidable npm install formidable After installing formidable module, you can check your yargs version in command prompt using the command.npm version formidable npm version formidable After that, you can just create a folder and add a file for example index.js, To run this file you need to run the following command.node index.js node index.js Filename: index.js const express = require('express');const fs = require('fs');const path = require('path')const formidable = require('formidable'); const app = express(); app.post('/api/upload', (req, res, next) => { const form = new formidable.IncomingForm(); form.parse(req, function(err, fields, files){ var oldPath = files.profilePic.path; var newPath = path.join(__dirname, 'uploads') + '/'+files.profilePic.name var rawData = fs.readFileSync(oldPath) fs.writeFile(newPath, rawData, function(err){ if(err) console.log(err) return res.send("Successfully uploaded") }) })}); app.listen(3000, function(err){ if(err) console.log(err) console.log('Server listening on Port 3000');}); Steps to run the program: The project structure will look like this:NOTE: ‘uploads’ is the folder where your files will be uploaded.Make sure you have install express and formidable module using following commands:npm install formidable npm install expressRun index.js file using below command:node index.jsNow open POSTMAN to run this API and send sample data as shown below:Here in body, we have passed send two fields, one is name of type=’Text’ and other is profilePic of type=’File’ as shown above.Now go to your uploads folder, your file is uploaded as shown below: The project structure will look like this:NOTE: ‘uploads’ is the folder where your files will be uploaded. Make sure you have install express and formidable module using following commands:npm install formidable npm install express npm install formidable npm install express Run index.js file using below command:node index.js node index.js Now open POSTMAN to run this API and send sample data as shown below:Here in body, we have passed send two fields, one is name of type=’Text’ and other is profilePic of type=’File’ as shown above. Now go to your uploads folder, your file is uploaded as shown below: So this is how you can use formidable module for uploading files and handling incoming form data easily and efficiently. Node.js-Misc Node.js Web Technologies Web technologies Questions Write From Home Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between promise and async await in Node.js Mongoose | findByIdAndUpdate() Function Installation of Node.js on Windows JWT Authentication with Node.js How to use an ES6 import in Node.js? Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React
[ { "code": null, "e": 54, "s": 26, "text": "\n27 Apr, 2020" }, { "code": null, "e": 228, "s": 54, "text": "Formidable module is used for parsing form data, especially file uploads. It is easy to use and integrate into your project for handling incoming form data and file uploads." }, { "code": null, "e": 263, "s": 228, "text": "Installation of formidable module:" }, { "code": null, "e": 660, "s": 263, "text": "You can visit the link Install formidable module. You can install this package by using this command.npm install formidableAfter installing formidable module, you can check your yargs version in command prompt using the command.npm version formidableAfter that, you can just create a folder and add a file for example index.js, To run this file you need to run the following command.node index.js" }, { "code": null, "e": 784, "s": 660, "text": "You can visit the link Install formidable module. You can install this package by using this command.npm install formidable" }, { "code": null, "e": 807, "s": 784, "text": "npm install formidable" }, { "code": null, "e": 935, "s": 807, "text": "After installing formidable module, you can check your yargs version in command prompt using the command.npm version formidable" }, { "code": null, "e": 958, "s": 935, "text": "npm version formidable" }, { "code": null, "e": 1105, "s": 958, "text": "After that, you can just create a folder and add a file for example index.js, To run this file you need to run the following command.node index.js" }, { "code": null, "e": 1119, "s": 1105, "text": "node index.js" }, { "code": null, "e": 1138, "s": 1119, "text": "Filename: index.js" }, { "code": "const express = require('express');const fs = require('fs');const path = require('path')const formidable = require('formidable'); const app = express(); app.post('/api/upload', (req, res, next) => { const form = new formidable.IncomingForm(); form.parse(req, function(err, fields, files){ var oldPath = files.profilePic.path; var newPath = path.join(__dirname, 'uploads') + '/'+files.profilePic.name var rawData = fs.readFileSync(oldPath) fs.writeFile(newPath, rawData, function(err){ if(err) console.log(err) return res.send(\"Successfully uploaded\") }) })}); app.listen(3000, function(err){ if(err) console.log(err) console.log('Server listening on Port 3000');});", "e": 1907, "s": 1138, "text": null }, { "code": null, "e": 1933, "s": 1907, "text": "Steps to run the program:" }, { "code": null, "e": 2479, "s": 1933, "text": "The project structure will look like this:NOTE: ‘uploads’ is the folder where your files will be uploaded.Make sure you have install express and formidable module using following commands:npm install formidable\nnpm install expressRun index.js file using below command:node index.jsNow open POSTMAN to run this API and send sample data as shown below:Here in body, we have passed send two fields, one is name of type=’Text’ and other is profilePic of type=’File’ as shown above.Now go to your uploads folder, your file is uploaded as shown below:" }, { "code": null, "e": 2586, "s": 2479, "text": "The project structure will look like this:NOTE: ‘uploads’ is the folder where your files will be uploaded." }, { "code": null, "e": 2711, "s": 2586, "text": "Make sure you have install express and formidable module using following commands:npm install formidable\nnpm install express" }, { "code": null, "e": 2754, "s": 2711, "text": "npm install formidable\nnpm install express" }, { "code": null, "e": 2806, "s": 2754, "text": "Run index.js file using below command:node index.js" }, { "code": null, "e": 2820, "s": 2806, "text": "node index.js" }, { "code": null, "e": 3017, "s": 2820, "text": "Now open POSTMAN to run this API and send sample data as shown below:Here in body, we have passed send two fields, one is name of type=’Text’ and other is profilePic of type=’File’ as shown above." }, { "code": null, "e": 3086, "s": 3017, "text": "Now go to your uploads folder, your file is uploaded as shown below:" }, { "code": null, "e": 3207, "s": 3086, "text": "So this is how you can use formidable module for uploading files and handling incoming form data easily and efficiently." }, { "code": null, "e": 3220, "s": 3207, "text": "Node.js-Misc" }, { "code": null, "e": 3228, "s": 3220, "text": "Node.js" }, { "code": null, "e": 3245, "s": 3228, "text": "Web Technologies" }, { "code": null, "e": 3272, "s": 3245, "text": "Web technologies Questions" }, { "code": null, "e": 3288, "s": 3272, "text": "Write From Home" }, { "code": null, "e": 3386, "s": 3288, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3440, "s": 3386, "text": "Difference between promise and async await in Node.js" }, { "code": null, "e": 3480, "s": 3440, "text": "Mongoose | findByIdAndUpdate() Function" }, { "code": null, "e": 3515, "s": 3480, "text": "Installation of Node.js on Windows" }, { "code": null, "e": 3547, "s": 3515, "text": "JWT Authentication with Node.js" }, { "code": null, "e": 3584, "s": 3547, "text": "How to use an ES6 import in Node.js?" }, { "code": null, "e": 3646, "s": 3584, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3707, "s": 3646, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3757, "s": 3707, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 3800, "s": 3757, "text": "How to fetch data from an API in ReactJS ?" } ]
How to Sum Diagonal Cells in a range in Excel?
06 Sep, 2021 The calculation of matrices is one of the most difficult numerical computation tasks. You may need to add values diagonally in a table when performing mathematical computations. Excel allows you to sum diagonal numbers without having to add the values one by one. We’ll go through how to sum cells diagonally down or diagonally up. Example: The image below shows a matrix & we want to add the elements of the diagonal. Diagonal1 is the right diagonal & Diagonal2 is the left diagonal as its top element is on the left. To do conditional formatting use the following steps :Step 1: Select the Matrix/Table. Then Go to the home tab & select the conditional formatting option. Step 2: Choose New Rule. Step 3: Select: “Use a formula to determine which cells to format” & in the rule description give the format values for the formula. Here we give 1st cell name of the matrix in the formula, i.e., column(B2) – row(B2) (For diagonal) Step 4: Click on the format. Choose the color, fonts, etc, for formatting & then click on OK. Step 6: Click on Ok. You will get your cells formatted. A range of cells containing values can be seen in the image below : Check the cell ranges, say, ‘B2’ is the first upper-left cell. This is significant because cell ‘B2’ serves as the start point for the diagonal sum. We SUM the diagonal values down from the first cell ‘B2’ diagonally right till ‘E5’. Here we want right the diagonal sum, i.e., sum of the cells: B2+C3+D4+E5 . To do sum of the Left diagonal we will use the formula : =SUM((COLUMN(Cells Reference)-ROW(Cells Reference) =cellName )*Cells Reference) into a blank cell , Say F6 Step 1: Go to the cell, where you want to get the result of the addition. Step 2 : There write : =SUM((COLUMN(B2:E5)-ROW(B2:E5)=M1)*B2:E5) Step 3 : Press Ctrl + Shift + Enter. You will get the left diagonal sum. Here you can see the left diagonal sum = 1+1+1+1 = 4 Note: Here M1 contains the difference between columns & rows. Currently, in the above image, it is 0. If we go to M1 & change its value to 2 : The addition now is changed to 49 which is the sum of D2 + E3 , i.e., 44+5 = 9. The value 2 of M here indicates the diagonal 2 steps above the current diagonal(in other way we exclude 2 columns & 2 rows) If we go to M1 & change its value to -1 : The addition now is changed to 74 which is the sum of B3 + C4 + D5 , i.e., 3+4+67. The value -1 of M here indicates the diagonal 1 step below the current diagonal(in other way we exclude 1 column & 1 row downwards) Check the cell ranges, say, ‘E2’ is the first upper right cell. This is significant because cell ‘B5’ serves as the start point for the diagonal sum. We SUM the diagonal values down from the first cell ‘E2’ diagonally right till ‘B5’. Here we want right the diagonal sum , i.e., sum of the cells: E2+D3+C4+B5. To do sum of the right diagonal we will use the formula : =SUM(Cell Reference*((ROWS(Cell Reference) + Ri)-ROW(Cell Reference)=COLUMN(Cell Reference)-Ci)) into a blank cell , Say F6 Ri => the number of rows in front of the data range's initial cell. Ci => the number of columns in front of the data range's initial cell. Example 1: If you have a 5*5 matrix from Row 1 & column A (i.e., From A1 to E5), then if we formula : = SUM(A1:E5*((ROWS(A1:E5)+0)-ROW(A1:E5)=COLUMN(A1:E5))) Here Ri = 0, then the no of rows in front of the first cell of the data range is 0, so the addition is done for: A4+ B3 + C2 + D1 Example 2 : Step 1: Go to the cell, where you want to get the result of the addition. Step 2 : There write : =SUM(B2:E5*((ROWS(B2:E5)+2)-ROW(B2:E5)=COLUMN(B2:E5)-1)) Step 3 : Press Ctrl + Shift + Enter. You will get the left diagonal sum. Here you can see the right diagonal sum = 11+14+2+2 = 29 In the above example also we have the same number of rows & columns in the cell range. But the thing in the below example differ is that there are different numbers of columns & rows in front of the cell range. Suppose we want to calculate sum of the elements diagonally up : Here, Ci = 2 & Ri = 2: as the number of rows in front of the cell reference is 2 & the number of columns in front of the actual cell references is 1. In the image below, you can see that the number of rows = 6 & the number of columns = 5 in the cell references.To find the diagonal sum, follow these steps : Step 1: Go to the cell, where you want to get the result of the addition. Step 2: There write : = SUMPRODUCT(((MATCH($A$3:$A$8,$A$3:$A$8,0)-MATCH($B$2:$F$2,$B$2:$F$2,0))=5-4)*($B$3:$F$8)) Step 3: Press Ctrl + Shift + Enter. The basic formula comes next if we wish to start at the beginning and multiply the total of the numbers or values diagonally by the start column of cell ‘B3’. Take note of the number of rows labeled ‘pink’ in the calculation below. = SUMPRODUCT(((MATCH($A$3:$A$5,$A$3:$A$5,0)-MATCH($B$2:$D$2,$B$2:$D$2,0))=1-1)*($B$3:$D$5)) = SUMPRODUCT((((ROW($A$3:$A$5)-1)-(COLUMN($B$2:$D$2)-2))=3-1)*($B$3:$D$5)) Use the ARRAY formula below to get the sum of the values diagonally down for a certain number of columns. The formula is found in cell ‘I11’ in the image above, while the condition ‘number 3’ is found in cell ‘G11’ in the image above. Only the first 4 columns of the data range are included in this calculation, which is the diagonal sum of values (enter the formula in one line). = SUM(IF(ROW(OFFSET($B$3:$F$8,0,0,$G$11,G11))-MAX(ROW(OFFSET($B$3:$F$8,0,0,$G$11,G11)))= COLUMN(OFFSET($B$3:$F$8,0,0,$G$11,G11))-MAX(COLUMN(OFFSET($B$3:$F$8,0,0,$G$11,G11))), OFFSET($B$3:$F$8,0,0,$G$11,G11),FALSE)) Note that here, in G11, we are specifying the column up to which we want to sum the diagonal elements. Excel-functions Picked Excel Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n06 Sep, 2021" }, { "code": null, "e": 385, "s": 52, "text": "The calculation of matrices is one of the most difficult numerical computation tasks. You may need to add values diagonally in a table when performing mathematical computations. Excel allows you to sum diagonal numbers without having to add the values one by one. We’ll go through how to sum cells diagonally down or diagonally up." }, { "code": null, "e": 572, "s": 385, "text": "Example: The image below shows a matrix & we want to add the elements of the diagonal. Diagonal1 is the right diagonal & Diagonal2 is the left diagonal as its top element is on the left." }, { "code": null, "e": 727, "s": 572, "text": "To do conditional formatting use the following steps :Step 1: Select the Matrix/Table. Then Go to the home tab & select the conditional formatting option." }, { "code": null, "e": 752, "s": 727, "text": "Step 2: Choose New Rule." }, { "code": null, "e": 984, "s": 752, "text": "Step 3: Select: “Use a formula to determine which cells to format” & in the rule description give the format values for the formula. Here we give 1st cell name of the matrix in the formula, i.e., column(B2) – row(B2) (For diagonal)" }, { "code": null, "e": 1078, "s": 984, "text": "Step 4: Click on the format. Choose the color, fonts, etc, for formatting & then click on OK." }, { "code": null, "e": 1099, "s": 1078, "text": "Step 6: Click on Ok." }, { "code": null, "e": 1134, "s": 1099, "text": "You will get your cells formatted." }, { "code": null, "e": 1202, "s": 1134, "text": "A range of cells containing values can be seen in the image below :" }, { "code": null, "e": 1436, "s": 1202, "text": "Check the cell ranges, say, ‘B2’ is the first upper-left cell. This is significant because cell ‘B2’ serves as the start point for the diagonal sum. We SUM the diagonal values down from the first cell ‘B2’ diagonally right till ‘E5’." }, { "code": null, "e": 1569, "s": 1436, "text": "Here we want right the diagonal sum, i.e., sum of the cells: B2+C3+D4+E5 . To do sum of the Left diagonal we will use the formula :" }, { "code": null, "e": 1677, "s": 1569, "text": "=SUM((COLUMN(Cells Reference)-ROW(Cells Reference) =cellName )*Cells Reference) \ninto a blank cell , Say F6" }, { "code": null, "e": 1751, "s": 1677, "text": "Step 1: Go to the cell, where you want to get the result of the addition." }, { "code": null, "e": 1816, "s": 1751, "text": "Step 2 : There write : =SUM((COLUMN(B2:E5)-ROW(B2:E5)=M1)*B2:E5)" }, { "code": null, "e": 1853, "s": 1816, "text": "Step 3 : Press Ctrl + Shift + Enter." }, { "code": null, "e": 1942, "s": 1853, "text": "You will get the left diagonal sum. Here you can see the left diagonal sum = 1+1+1+1 = 4" }, { "code": null, "e": 2044, "s": 1942, "text": "Note: Here M1 contains the difference between columns & rows. Currently, in the above image, it is 0." }, { "code": null, "e": 2085, "s": 2044, "text": "If we go to M1 & change its value to 2 :" }, { "code": null, "e": 2289, "s": 2085, "text": "The addition now is changed to 49 which is the sum of D2 + E3 , i.e., 44+5 = 9. The value 2 of M here indicates the diagonal 2 steps above the current diagonal(in other way we exclude 2 columns & 2 rows)" }, { "code": null, "e": 2331, "s": 2289, "text": "If we go to M1 & change its value to -1 :" }, { "code": null, "e": 2546, "s": 2331, "text": "The addition now is changed to 74 which is the sum of B3 + C4 + D5 , i.e., 3+4+67. The value -1 of M here indicates the diagonal 1 step below the current diagonal(in other way we exclude 1 column & 1 row downwards)" }, { "code": null, "e": 2781, "s": 2546, "text": "Check the cell ranges, say, ‘E2’ is the first upper right cell. This is significant because cell ‘B5’ serves as the start point for the diagonal sum. We SUM the diagonal values down from the first cell ‘E2’ diagonally right till ‘B5’." }, { "code": null, "e": 2915, "s": 2781, "text": "Here we want right the diagonal sum , i.e., sum of the cells: E2+D3+C4+B5. To do sum of the right diagonal we will use the formula :" }, { "code": null, "e": 3179, "s": 2915, "text": "=SUM(Cell Reference*((ROWS(Cell Reference) + Ri)-ROW(Cell Reference)=COLUMN(Cell Reference)-Ci)) \ninto a blank cell , Say F6\nRi => the number of rows in front of the data range's initial cell.\nCi => the number of columns in front of the data range's initial cell." }, { "code": null, "e": 3281, "s": 3179, "text": "Example 1: If you have a 5*5 matrix from Row 1 & column A (i.e., From A1 to E5), then if we formula :" }, { "code": null, "e": 3337, "s": 3281, "text": "= SUM(A1:E5*((ROWS(A1:E5)+0)-ROW(A1:E5)=COLUMN(A1:E5)))" }, { "code": null, "e": 3468, "s": 3337, "text": "Here Ri = 0, then the no of rows in front of the first cell of the data range is 0, so the addition is done for: A4+ B3 + C2 + D1" }, { "code": null, "e": 3480, "s": 3468, "text": "Example 2 :" }, { "code": null, "e": 3554, "s": 3480, "text": "Step 1: Go to the cell, where you want to get the result of the addition." }, { "code": null, "e": 3634, "s": 3554, "text": "Step 2 : There write : =SUM(B2:E5*((ROWS(B2:E5)+2)-ROW(B2:E5)=COLUMN(B2:E5)-1))" }, { "code": null, "e": 3671, "s": 3634, "text": "Step 3 : Press Ctrl + Shift + Enter." }, { "code": null, "e": 3764, "s": 3671, "text": "You will get the left diagonal sum. Here you can see the right diagonal sum = 11+14+2+2 = 29" }, { "code": null, "e": 3975, "s": 3764, "text": "In the above example also we have the same number of rows & columns in the cell range. But the thing in the below example differ is that there are different numbers of columns & rows in front of the cell range." }, { "code": null, "e": 4040, "s": 3975, "text": "Suppose we want to calculate sum of the elements diagonally up :" }, { "code": null, "e": 4191, "s": 4040, "text": "Here, Ci = 2 & Ri = 2: as the number of rows in front of the cell reference is 2 & the number of columns in front of the actual cell references is 1." }, { "code": null, "e": 4349, "s": 4191, "text": "In the image below, you can see that the number of rows = 6 & the number of columns = 5 in the cell references.To find the diagonal sum, follow these steps :" }, { "code": null, "e": 4423, "s": 4349, "text": "Step 1: Go to the cell, where you want to get the result of the addition." }, { "code": null, "e": 4537, "s": 4423, "text": "Step 2: There write : = SUMPRODUCT(((MATCH($A$3:$A$8,$A$3:$A$8,0)-MATCH($B$2:$F$2,$B$2:$F$2,0))=5-4)*($B$3:$F$8))" }, { "code": null, "e": 4573, "s": 4537, "text": "Step 3: Press Ctrl + Shift + Enter." }, { "code": null, "e": 4806, "s": 4573, "text": "The basic formula comes next if we wish to start at the beginning and multiply the total of the numbers or values diagonally by the start column of cell ‘B3’. Take note of the number of rows labeled ‘pink’ in the calculation below." }, { "code": null, "e": 4973, "s": 4806, "text": "= SUMPRODUCT(((MATCH($A$3:$A$5,$A$3:$A$5,0)-MATCH($B$2:$D$2,$B$2:$D$2,0))=1-1)*($B$3:$D$5))\n= SUMPRODUCT((((ROW($A$3:$A$5)-1)-(COLUMN($B$2:$D$2)-2))=3-1)*($B$3:$D$5))" }, { "code": null, "e": 5354, "s": 4973, "text": "Use the ARRAY formula below to get the sum of the values diagonally down for a certain number of columns. The formula is found in cell ‘I11’ in the image above, while the condition ‘number 3’ is found in cell ‘G11’ in the image above. Only the first 4 columns of the data range are included in this calculation, which is the diagonal sum of values (enter the formula in one line)." }, { "code": null, "e": 5569, "s": 5354, "text": "= SUM(IF(ROW(OFFSET($B$3:$F$8,0,0,$G$11,G11))-MAX(ROW(OFFSET($B$3:$F$8,0,0,$G$11,G11)))=\nCOLUMN(OFFSET($B$3:$F$8,0,0,$G$11,G11))-MAX(COLUMN(OFFSET($B$3:$F$8,0,0,$G$11,G11))),\nOFFSET($B$3:$F$8,0,0,$G$11,G11),FALSE))" }, { "code": null, "e": 5673, "s": 5569, "text": "Note that here, in G11, we are specifying the column up to which we want to sum the diagonal elements. " }, { "code": null, "e": 5689, "s": 5673, "text": "Excel-functions" }, { "code": null, "e": 5696, "s": 5689, "text": "Picked" }, { "code": null, "e": 5702, "s": 5696, "text": "Excel" } ]
How to find the percentage of missing values in a dataframe in R?
07 Apr, 2021 In this article, let’s discuss how to find the percentage of missing values (NAs) in R Programming Language. Percentage of NAs denote the fraction of data cells that are not defined by a definite cell value. The percentage of NA values can be calculated using the following formula : Percentage of NAs = (Number of cells with NA) * 100 /(Total number of cells) Method 1: The total number of cells can be found by using the product of the inbuilt dim() function in R, which returns two values, each indicating the number of rows and columns respectively. The number of cells with NA values can be computed by using the sum() and is.na() functions in R respectively. The following code snippet first evaluates each data cell value to return a logical value of true if there is a missing value and false, if not. Then, the summation of these NA values is done using sum() function. sum(is.na(data_frame)) R # declaring a data frame in Rdata_frame = data.frame(C1= c(1, 2, NA, 0), C2= c( NA, NA, 3, 8), C3= c("A", "V", "j", "y")) print("Original data frame")print(data_frame) # calculating the product of dimensions of dataframe totalcells = prod(dim(data_frame))print("Total number of cells ")print(totalcells) # calculating the number of cells with namissingcells = sum(is.na(data_frame))print("Missing value cells")print(missingcells) # calculating percentage of missing valuespercentage = (missingcells * 100 )/(totalcells)print("Percentage of missing values' cells")print (percentage) Output [1] "Original data frame" C1 C2 C3 1 1 NA A 2 2 NA V 3 NA 3 j 4 0 8 y [1] "Total number of cells " [1] 12 [1] "Missing value cells" [1] 3 [1] "Percentage of missing values' cells" [1] 25 Method 2: We can simply use the mean() function in R, to carry out the division of missing cells by the total number of cells. is.na() function is first used to determine whether the data cell value is true or false and then the mean() method is applied over it. The time complexity required is polynomial with respect to the size of data frame, since each data cell value is evaluated. R # declaring a data frame in Rdata_frame = data.frame(C1= c(1, 2, NA, 0), C2= c( NA, NA, 3, 8), C3= c("A", "V", "j", "y"), C4=c(NA,NA,NA,NA)) print("Original data frame")print(data_frame) # calculating percentage of missing valuespercentage = mean(is.na(data_frame)) * 100print ("percentage of missing values")print (percentage) Output [1] "Original data frame" C1 C2 C3 C4 1 1 NA A NA 2 2 NA V NA 3 NA 3 j NA 4 0 8 y NA [1] "percentage of missing values" [1] 43.75 Picked R DataFrame-Programs R-DataFrame R Language R Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R How to Split Column Into Multiple Columns in R DataFrame? Group by function in R using Dplyr How to Change Axis Scales in R Plots? R - if statement How to Split Column Into Multiple Columns in R DataFrame? How to filter R DataFrame by values in a column? Replace Specific Characters in String in R Merge DataFrames by Column Names in R How to Sort a DataFrame in R ?
[ { "code": null, "e": 28, "s": 0, "text": "\n07 Apr, 2021" }, { "code": null, "e": 312, "s": 28, "text": "In this article, let’s discuss how to find the percentage of missing values (NAs) in R Programming Language. Percentage of NAs denote the fraction of data cells that are not defined by a definite cell value. The percentage of NA values can be calculated using the following formula :" }, { "code": null, "e": 389, "s": 312, "text": "Percentage of NAs = (Number of cells with NA) * 100 /(Total number of cells)" }, { "code": null, "e": 583, "s": 389, "text": "Method 1: The total number of cells can be found by using the product of the inbuilt dim() function in R, which returns two values, each indicating the number of rows and columns respectively. " }, { "code": null, "e": 909, "s": 583, "text": "The number of cells with NA values can be computed by using the sum() and is.na() functions in R respectively. The following code snippet first evaluates each data cell value to return a logical value of true if there is a missing value and false, if not. Then, the summation of these NA values is done using sum() function. " }, { "code": null, "e": 932, "s": 909, "text": "sum(is.na(data_frame))" }, { "code": null, "e": 934, "s": 932, "text": "R" }, { "code": "# declaring a data frame in Rdata_frame = data.frame(C1= c(1, 2, NA, 0), C2= c( NA, NA, 3, 8), C3= c(\"A\", \"V\", \"j\", \"y\")) print(\"Original data frame\")print(data_frame) # calculating the product of dimensions of dataframe totalcells = prod(dim(data_frame))print(\"Total number of cells \")print(totalcells) # calculating the number of cells with namissingcells = sum(is.na(data_frame))print(\"Missing value cells\")print(missingcells) # calculating percentage of missing valuespercentage = (missingcells * 100 )/(totalcells)print(\"Percentage of missing values' cells\")print (percentage)", "e": 1566, "s": 934, "text": null }, { "code": null, "e": 1573, "s": 1566, "text": "Output" }, { "code": null, "e": 1770, "s": 1573, "text": "[1] \"Original data frame\"\n C1 C2 C3\n1 1 NA A\n2 2 NA V\n3 NA 3 j\n4 0 8 y\n[1] \"Total number of cells \"\n[1] 12\n[1] \"Missing value cells\"\n[1] 3\n[1] \"Percentage of missing values' cells\"\n[1] 25" }, { "code": null, "e": 2158, "s": 1770, "text": "Method 2: We can simply use the mean() function in R, to carry out the division of missing cells by the total number of cells. is.na() function is first used to determine whether the data cell value is true or false and then the mean() method is applied over it. The time complexity required is polynomial with respect to the size of data frame, since each data cell value is evaluated. " }, { "code": null, "e": 2160, "s": 2158, "text": "R" }, { "code": "# declaring a data frame in Rdata_frame = data.frame(C1= c(1, 2, NA, 0), C2= c( NA, NA, 3, 8), C3= c(\"A\", \"V\", \"j\", \"y\"), C4=c(NA,NA,NA,NA)) print(\"Original data frame\")print(data_frame) # calculating percentage of missing valuespercentage = mean(is.na(data_frame)) * 100print (\"percentage of missing values\")print (percentage)", "e": 2560, "s": 2160, "text": null }, { "code": null, "e": 2567, "s": 2560, "text": "Output" }, { "code": null, "e": 2707, "s": 2567, "text": "[1] \"Original data frame\"\n C1 C2 C3 C4\n1 1 NA A NA\n2 2 NA V NA\n3 NA 3 j NA\n4 0 8 y NA\n[1] \"percentage of missing values\"\n[1] 43.75" }, { "code": null, "e": 2714, "s": 2707, "text": "Picked" }, { "code": null, "e": 2735, "s": 2714, "text": "R DataFrame-Programs" }, { "code": null, "e": 2747, "s": 2735, "text": "R-DataFrame" }, { "code": null, "e": 2758, "s": 2747, "text": "R Language" }, { "code": null, "e": 2769, "s": 2758, "text": "R Programs" }, { "code": null, "e": 2867, "s": 2769, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2919, "s": 2867, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 2977, "s": 2919, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 3012, "s": 2977, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 3050, "s": 3012, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 3067, "s": 3050, "text": "R - if statement" }, { "code": null, "e": 3125, "s": 3067, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 3174, "s": 3125, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 3217, "s": 3174, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 3255, "s": 3217, "text": "Merge DataFrames by Column Names in R" } ]
PHP | mysqli_connect() Function
06 Jul, 2021 The mysqli_connect() function in PHP is used to connect you to the database. In the previous version of the connection mysql_connect() was used for connection and then there comes mysqli_connect() where i means improved version of connection and is more secure than mysql_connect().Syntax: mysqli_connect ( "host", "username", "password", "database_name" ) Parameters used: host: It is optional and it specify the host name or IP address. In case of local server localhost is used as a general keyword to connect local server and run the program. username: It is optional and it specify mysql username. In local server username is root. Password: It is optional and it specify mysql password. database_name: It is database name where operation perform on data. It also optional. Return values: It returns an object which represent MySql connection. If connection failed then it return FALSE. Program: Below is the implementation of mysqli_connect() function. php <?php mysqli_connect("localhost", "root", "", "GFG"); if(mysqli_connect_error()) echo "Connection Error."; else echo "Database Connection Successfully.";?> Output: Database Connection Successfully. saurabh1990aror mysql PHP-function Misc SQL Misc Misc SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n06 Jul, 2021" }, { "code": null, "e": 346, "s": 54, "text": "The mysqli_connect() function in PHP is used to connect you to the database. In the previous version of the connection mysql_connect() was used for connection and then there comes mysqli_connect() where i means improved version of connection and is more secure than mysql_connect().Syntax: " }, { "code": null, "e": 413, "s": 346, "text": "mysqli_connect ( \"host\", \"username\", \"password\", \"database_name\" )" }, { "code": null, "e": 432, "s": 413, "text": "Parameters used: " }, { "code": null, "e": 605, "s": 432, "text": "host: It is optional and it specify the host name or IP address. In case of local server localhost is used as a general keyword to connect local server and run the program." }, { "code": null, "e": 695, "s": 605, "text": "username: It is optional and it specify mysql username. In local server username is root." }, { "code": null, "e": 751, "s": 695, "text": "Password: It is optional and it specify mysql password." }, { "code": null, "e": 837, "s": 751, "text": "database_name: It is database name where operation perform on data. It also optional." }, { "code": null, "e": 854, "s": 837, "text": "Return values: " }, { "code": null, "e": 952, "s": 854, "text": "It returns an object which represent MySql connection. If connection failed then it return FALSE." }, { "code": null, "e": 1020, "s": 952, "text": "Program: Below is the implementation of mysqli_connect() function. " }, { "code": null, "e": 1024, "s": 1020, "text": "php" }, { "code": "<?php mysqli_connect(\"localhost\", \"root\", \"\", \"GFG\"); if(mysqli_connect_error()) echo \"Connection Error.\"; else echo \"Database Connection Successfully.\";?>", "e": 1204, "s": 1024, "text": null }, { "code": null, "e": 1214, "s": 1204, "text": "Output: " }, { "code": null, "e": 1248, "s": 1214, "text": "Database Connection Successfully." }, { "code": null, "e": 1266, "s": 1250, "text": "saurabh1990aror" }, { "code": null, "e": 1272, "s": 1266, "text": "mysql" }, { "code": null, "e": 1285, "s": 1272, "text": "PHP-function" }, { "code": null, "e": 1290, "s": 1285, "text": "Misc" }, { "code": null, "e": 1294, "s": 1290, "text": "SQL" }, { "code": null, "e": 1299, "s": 1294, "text": "Misc" }, { "code": null, "e": 1304, "s": 1299, "text": "Misc" }, { "code": null, "e": 1308, "s": 1304, "text": "SQL" } ]
while loop in Perl
21 Nov, 2019 A while loop in Perl generally takes an expression in parenthesis. If the expression is True then the code within the body of while loop is executed. A while loop is used when we don’t know the number of times we want the loop to be executed however we know the termination condition of the loop. It is also known as an entry controlled loop as the condition is checked before executing the loop. The while loop can be thought of as a repeating if statement. Syntax : while (condition) { # Code to be executed } Flow Chart: Example : # Perl program to illustrate# the while loop # while loop$count = 3;while ($count >= 0){ $count = $count - 1; print "GeeksForGeeks\n";} Output: GeeksForGeeks GeeksForGeeks GeeksForGeeks GeeksForGeeks A Nested while loop is one in which one while loop is used inside another while loop. In a Nested while loop, for each iteration of the outer while loop, the inner while loop gets executed completely. #!/usr/bin/perl# Perl program for Nested while loop$a = 0; # while loop execution while( $a <= 2 ){ $b = 0; while( $b <= 2 ) { printf "$a $b\n"; $b++; } $a++; } Output: 0 0 0 1 0 2 1 0 1 1 1 2 2 0 2 1 2 2 While loop can execute infinite times which means there is no terminating condition for this loop. In other words, we can say there are some conditions that always remain true, which causes while loop to execute infinite times or we can say it never terminates. Below program will print the specified statement infinite time and also gives the runtime error as Output Limit Exceeded on online IDE # Perl program to illustrate# the infinite while loop # infinite while loop# containing condition 1 # which is always truewhile(1){ print "Infinite While Loop\n";} Output: Infinite While Loop Infinite While Loop Infinite While Loop Infinite While Loop . . . . Perl-Loops Perl Perl Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Perl Tutorial - Learn Perl With Examples Perl | ne operator Perl | Basic Syntax of a Perl Program Perl | Opening and Reading a File Perl | File Handling Introduction Perl | Writing to a File Perl | Decision Making (if, if-else, Nested–if, if-elsif ladder, unless, unless-else, unless-elsif) Perl | Multidimensional Hashes Perl | Data Types Perl | qw Operator
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Nov, 2019" }, { "code": null, "e": 487, "s": 28, "text": "A while loop in Perl generally takes an expression in parenthesis. If the expression is True then the code within the body of while loop is executed. A while loop is used when we don’t know the number of times we want the loop to be executed however we know the termination condition of the loop. It is also known as an entry controlled loop as the condition is checked before executing the loop. The while loop can be thought of as a repeating if statement." }, { "code": null, "e": 496, "s": 487, "text": "Syntax :" }, { "code": null, "e": 545, "s": 496, "text": "while (condition)\n{\n # Code to be executed\n}\n" }, { "code": null, "e": 557, "s": 545, "text": "Flow Chart:" }, { "code": null, "e": 567, "s": 557, "text": "Example :" }, { "code": "# Perl program to illustrate# the while loop # while loop$count = 3;while ($count >= 0){ $count = $count - 1; print \"GeeksForGeeks\\n\";}", "e": 710, "s": 567, "text": null }, { "code": null, "e": 718, "s": 710, "text": "Output:" }, { "code": null, "e": 775, "s": 718, "text": "GeeksForGeeks\nGeeksForGeeks\nGeeksForGeeks\nGeeksForGeeks\n" }, { "code": null, "e": 976, "s": 775, "text": "A Nested while loop is one in which one while loop is used inside another while loop. In a Nested while loop, for each iteration of the outer while loop, the inner while loop gets executed completely." }, { "code": "#!/usr/bin/perl# Perl program for Nested while loop$a = 0; # while loop execution while( $a <= 2 ){ $b = 0; while( $b <= 2 ) { printf \"$a $b\\n\"; $b++; } $a++; } ", "e": 1185, "s": 976, "text": null }, { "code": null, "e": 1193, "s": 1185, "text": "Output:" }, { "code": null, "e": 1230, "s": 1193, "text": "0 0\n0 1\n0 2\n1 0\n1 1\n1 2\n2 0\n2 1\n2 2\n" }, { "code": null, "e": 1492, "s": 1230, "text": "While loop can execute infinite times which means there is no terminating condition for this loop. In other words, we can say there are some conditions that always remain true, which causes while loop to execute infinite times or we can say it never terminates." }, { "code": null, "e": 1627, "s": 1492, "text": "Below program will print the specified statement infinite time and also gives the runtime error as Output Limit Exceeded on online IDE" }, { "code": "# Perl program to illustrate# the infinite while loop # infinite while loop# containing condition 1 # which is always truewhile(1){ print \"Infinite While Loop\\n\";}", "e": 1795, "s": 1627, "text": null }, { "code": null, "e": 1803, "s": 1795, "text": "Output:" }, { "code": null, "e": 1892, "s": 1803, "text": "Infinite While Loop\nInfinite While Loop\nInfinite While Loop\nInfinite While Loop\n.\n.\n.\n.\n" }, { "code": null, "e": 1903, "s": 1892, "text": "Perl-Loops" }, { "code": null, "e": 1908, "s": 1903, "text": "Perl" }, { "code": null, "e": 1913, "s": 1908, "text": "Perl" }, { "code": null, "e": 2011, "s": 1913, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2052, "s": 2011, "text": "Perl Tutorial - Learn Perl With Examples" }, { "code": null, "e": 2071, "s": 2052, "text": "Perl | ne operator" }, { "code": null, "e": 2109, "s": 2071, "text": "Perl | Basic Syntax of a Perl Program" }, { "code": null, "e": 2143, "s": 2109, "text": "Perl | Opening and Reading a File" }, { "code": null, "e": 2177, "s": 2143, "text": "Perl | File Handling Introduction" }, { "code": null, "e": 2202, "s": 2177, "text": "Perl | Writing to a File" }, { "code": null, "e": 2302, "s": 2202, "text": "Perl | Decision Making (if, if-else, Nested–if, if-elsif ladder, unless, unless-else, unless-elsif)" }, { "code": null, "e": 2333, "s": 2302, "text": "Perl | Multidimensional Hashes" }, { "code": null, "e": 2351, "s": 2333, "text": "Perl | Data Types" } ]
Print Patterns in PL/SQL
26 Feb, 2021 You have given a number n then you have to print number a right-angled pyramid of * Examples: Input : 3 Output : * ** *** Input : 7 Output : * ** *** **** ***** ****** ******* C DECLARE -- declare variable n, --I AND J of datatype number N NUMBER := 7; I NUMBER; J NUMBER;BEGIN -- loop from 1 to n FOR I IN 1..N LOOP FOR J IN 1..I LOOP DBMS_OUTPUT.PUT('*') ; -- printing * END LOOP; DBMS_OUTPUT.NEW_LINE; -- for new line END LOOP;END;--Program End Output: * ** *** **** ***** ****** ******* viswajit4u pattern-printing SQL-PL/SQL DBMS SQL pattern-printing DBMS SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n26 Feb, 2021" }, { "code": null, "e": 149, "s": 53, "text": "You have given a number n then you have to print number a right-angled pyramid of * Examples: " }, { "code": null, "e": 232, "s": 149, "text": "Input : 3\nOutput :\n*\n**\n***\n\nInput : 7\nOutput :\n*\n**\n***\n****\n*****\n******\n*******" }, { "code": null, "e": 236, "s": 234, "text": "C" }, { "code": "DECLARE -- declare variable n, --I AND J of datatype number N NUMBER := 7; I NUMBER; J NUMBER;BEGIN -- loop from 1 to n FOR I IN 1..N LOOP FOR J IN 1..I LOOP DBMS_OUTPUT.PUT('*') ; -- printing * END LOOP; DBMS_OUTPUT.NEW_LINE; -- for new line END LOOP;END;--Program End", "e": 532, "s": 236, "text": null }, { "code": null, "e": 542, "s": 532, "text": "Output: " }, { "code": null, "e": 577, "s": 542, "text": "*\n**\n***\n****\n*****\n******\n*******" }, { "code": null, "e": 590, "s": 579, "text": "viswajit4u" }, { "code": null, "e": 607, "s": 590, "text": "pattern-printing" }, { "code": null, "e": 618, "s": 607, "text": "SQL-PL/SQL" }, { "code": null, "e": 623, "s": 618, "text": "DBMS" }, { "code": null, "e": 627, "s": 623, "text": "SQL" }, { "code": null, "e": 644, "s": 627, "text": "pattern-printing" }, { "code": null, "e": 649, "s": 644, "text": "DBMS" }, { "code": null, "e": 653, "s": 649, "text": "SQL" } ]
Python – distort() method in Wand
23 Dec, 2021 ImageMagick provides several ways to distort an image by applying various transformations against user-supplied arguments. In Wand, the method distort() is used, and follows a basic function. Syntax : wand.image.distort(method, arguments, best_fit) Parameters : Following are the Distortion Methods : Source Image: Code Example 1: Python3 # Import Image from wand.image modulefrom wand.image import Image # Read image using Image functionwith Image(filename ="gog.png") as img: img.distort('arc', (45, )) img.save(filename ='gogdistort1.png') Output Image: Code Example 2: Changing DISTORTION_METHOD to ‘perspective’. Python3 # Import Image from wand.image modulefrom wand.image import Image # Read image using Image functionwith Image(filename ="gog.png") as img: arguments = (0, 0, 20, 60, 90, 0, 70, 63, 0, 90, 5, 83, 90, 90, 85, 88) img.distort('perspective', arguments) img.save(filename ='gogdistort.png') Output Image: sagar0719kumar surinderdawra388 ruhelaa48 Python-gui Python-wand Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Python OOPs Concepts Convert integer to string in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Dec, 2021" }, { "code": null, "e": 221, "s": 28, "text": "ImageMagick provides several ways to distort an image by applying various transformations against user-supplied arguments. In Wand, the method distort() is used, and follows a basic function. " }, { "code": null, "e": 232, "s": 221, "text": "Syntax : " }, { "code": null, "e": 280, "s": 232, "text": "wand.image.distort(method, arguments, best_fit)" }, { "code": null, "e": 295, "s": 280, "text": "Parameters : " }, { "code": null, "e": 336, "s": 295, "text": "Following are the Distortion Methods : " }, { "code": null, "e": 352, "s": 336, "text": "Source Image: " }, { "code": null, "e": 370, "s": 352, "text": "Code Example 1: " }, { "code": null, "e": 378, "s": 370, "text": "Python3" }, { "code": "# Import Image from wand.image modulefrom wand.image import Image # Read image using Image functionwith Image(filename =\"gog.png\") as img: img.distort('arc', (45, )) img.save(filename ='gogdistort1.png')", "e": 588, "s": 378, "text": null }, { "code": null, "e": 604, "s": 588, "text": "Output Image: " }, { "code": null, "e": 667, "s": 604, "text": "Code Example 2: Changing DISTORTION_METHOD to ‘perspective’. " }, { "code": null, "e": 675, "s": 667, "text": "Python3" }, { "code": "# Import Image from wand.image modulefrom wand.image import Image # Read image using Image functionwith Image(filename =\"gog.png\") as img: arguments = (0, 0, 20, 60, 90, 0, 70, 63, 0, 90, 5, 83, 90, 90, 85, 88) img.distort('perspective', arguments) img.save(filename ='gogdistort.png')", "e": 1018, "s": 675, "text": null }, { "code": null, "e": 1034, "s": 1018, "text": "Output Image: " }, { "code": null, "e": 1051, "s": 1036, "text": "sagar0719kumar" }, { "code": null, "e": 1068, "s": 1051, "text": "surinderdawra388" }, { "code": null, "e": 1078, "s": 1068, "text": "ruhelaa48" }, { "code": null, "e": 1089, "s": 1078, "text": "Python-gui" }, { "code": null, "e": 1101, "s": 1089, "text": "Python-wand" }, { "code": null, "e": 1108, "s": 1101, "text": "Python" }, { "code": null, "e": 1206, "s": 1108, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1248, "s": 1206, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1270, "s": 1248, "text": "Enumerate() in Python" }, { "code": null, "e": 1305, "s": 1270, "text": "Read a file line by line in Python" }, { "code": null, "e": 1331, "s": 1305, "text": "Python String | replace()" }, { "code": null, "e": 1363, "s": 1331, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1392, "s": 1363, "text": "*args and **kwargs in Python" }, { "code": null, "e": 1419, "s": 1392, "text": "Python Classes and Objects" }, { "code": null, "e": 1449, "s": 1419, "text": "Iterate over a list in Python" }, { "code": null, "e": 1470, "s": 1449, "text": "Python OOPs Concepts" } ]
Java sqrt() method with Examples
09 Apr, 2018 The java.lang.Math.sqrt() returns the square root of a value of type double passed to it as argument. If the argument is NaN or negative, then the result is NaN. If the argument is positive infinity, then the result is positive infinity. If the argument passed is positive zero or negative zero then the result will be same as that of the argument. Syntax: public static double sqrt(double a) Parameter : a : the value whose square root is to be returned. Return : This method returns the positive square root value of the argument passed to it. Example 1: To show working of java.lang.Math.sqrt() method. // Java program to demonstrate working// of java.lang.Math.sqrt() methodimport java.lang.Math; class Gfg { // driver code public static void main(String args[]) { double a = 30; System.out.println(Math.sqrt(a)); a = 45; System.out.println(Math.sqrt(a)); a = 60; System.out.println(Math.sqrt(a)); a = 90; System.out.println(Math.sqrt(a)); }} Output: 5.477225575051661 6.708203932499369 7.745966692414834 9.486832980505138 Example 2: To show working of java.lang.Math.sqrt() method when argument is NaN or +infinity. // Java program to demonstrate working// of java.lang.Math.sqrt() methodimport java.lang.Math; // importing java.lang package public class GFG { public static void main(String[] args) { double positiveInfinity = Double.POSITIVE_INFINITY; double negativeVal = -5; double nan = Double.NaN; double result; // Here argument is negative, // output will be NaN result = Math.sqrt(negativeVal); System.out.println(result); // Here argument is positive infinity, // output will also positive infinity result = Math.sqrt(positiveInfinity); System.out.println(result); // Here argument is NaN, output will be NaN result = Math.sqrt(nan); System.out.println(result); }} Output: NaN Infinity NaN Java-lang package java-math Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Interfaces in Java Collections in Java Stream In Java Singleton Class in Java Set in Java Introduction to Java Constructors in Java Multithreading in Java LinkedList in Java Initializing a List in Java
[ { "code": null, "e": 53, "s": 25, "text": "\n09 Apr, 2018" }, { "code": null, "e": 402, "s": 53, "text": "The java.lang.Math.sqrt() returns the square root of a value of type double passed to it as argument. If the argument is NaN or negative, then the result is NaN. If the argument is positive infinity, then the result is positive infinity. If the argument passed is positive zero or negative zero then the result will be same as that of the argument." }, { "code": null, "e": 410, "s": 402, "text": "Syntax:" }, { "code": null, "e": 601, "s": 410, "text": "public static double sqrt(double a)\nParameter :\na : the value whose square root is to be returned.\nReturn :\nThis method returns the positive square root value of \nthe argument passed to it.\n" }, { "code": null, "e": 661, "s": 601, "text": "Example 1: To show working of java.lang.Math.sqrt() method." }, { "code": "// Java program to demonstrate working// of java.lang.Math.sqrt() methodimport java.lang.Math; class Gfg { // driver code public static void main(String args[]) { double a = 30; System.out.println(Math.sqrt(a)); a = 45; System.out.println(Math.sqrt(a)); a = 60; System.out.println(Math.sqrt(a)); a = 90; System.out.println(Math.sqrt(a)); }}", "e": 1087, "s": 661, "text": null }, { "code": null, "e": 1095, "s": 1087, "text": "Output:" }, { "code": null, "e": 1168, "s": 1095, "text": "5.477225575051661\n6.708203932499369\n7.745966692414834\n9.486832980505138\n" }, { "code": null, "e": 1262, "s": 1168, "text": "Example 2: To show working of java.lang.Math.sqrt() method when argument is NaN or +infinity." }, { "code": "// Java program to demonstrate working// of java.lang.Math.sqrt() methodimport java.lang.Math; // importing java.lang package public class GFG { public static void main(String[] args) { double positiveInfinity = Double.POSITIVE_INFINITY; double negativeVal = -5; double nan = Double.NaN; double result; // Here argument is negative, // output will be NaN result = Math.sqrt(negativeVal); System.out.println(result); // Here argument is positive infinity, // output will also positive infinity result = Math.sqrt(positiveInfinity); System.out.println(result); // Here argument is NaN, output will be NaN result = Math.sqrt(nan); System.out.println(result); }}", "e": 2044, "s": 1262, "text": null }, { "code": null, "e": 2052, "s": 2044, "text": "Output:" }, { "code": null, "e": 2070, "s": 2052, "text": "NaN\nInfinity\nNaN\n" }, { "code": null, "e": 2088, "s": 2070, "text": "Java-lang package" }, { "code": null, "e": 2098, "s": 2088, "text": "java-math" }, { "code": null, "e": 2103, "s": 2098, "text": "Java" }, { "code": null, "e": 2108, "s": 2103, "text": "Java" }, { "code": null, "e": 2206, "s": 2108, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2225, "s": 2206, "text": "Interfaces in Java" }, { "code": null, "e": 2245, "s": 2225, "text": "Collections in Java" }, { "code": null, "e": 2260, "s": 2245, "text": "Stream In Java" }, { "code": null, "e": 2284, "s": 2260, "text": "Singleton Class in Java" }, { "code": null, "e": 2296, "s": 2284, "text": "Set in Java" }, { "code": null, "e": 2317, "s": 2296, "text": "Introduction to Java" }, { "code": null, "e": 2338, "s": 2317, "text": "Constructors in Java" }, { "code": null, "e": 2361, "s": 2338, "text": "Multithreading in Java" }, { "code": null, "e": 2380, "s": 2361, "text": "LinkedList in Java" } ]
Warning control in Python Programs
Warning is different from error in a program. If error is encountered, Python program terminates instantly. Warning on the other hand is not fatal. It displays certain message but program continues. Warnings are issued to alert the user of certain conditions which aren't exactly exceptions. Typically warning appears if some deprecated usage of certain programming element like keyword/function/class etc. is found. Warning messages are displayed by warn() function defined in 'warning' module of Python's standard library. Warning is actually a subclass of Exception in built-in class hierarchy. There are a number of built-in Warning subclasses. User defined subclass can also be defined. Following code defines a class with a deprecated method and a method scheduled to be deprecated in a future version of the said class. # warningexample.py import warnings class WarnExample: def __init__(self): self.text = "Warning" def method1(self): warnings.warn( "method1 is deprecated, use new_method instead", DeprecationWarning ) print ('method1', len(self.text)) def method2(self): warnings.warn( "method2 will be deprecated in version 2, use new_method instead", PendingDeprecationWarning ) print ('method2', len(self.text)) def new_method(self): print ('new method', len(self.text)) if __name__=='__main__': e = WarnExample() e.method1() e.method2() e.new_method() If above script is executed from command prompt as E:\python37>python warningexample.py No warning messages are displayed on terminal. For that you have to use _Wd switch as below E:\python37>python -Wd warningexample.py warningexample.py:10: DeprecationWarning: method1 is deprecated, use new_method instead DeprecationWarning method1 7 warningexample.py:19: PendingDeprecationWarning: method2 will be deprecated in version 2, use new_method instead PendingDeprecationWarning method2 7 new method 7 Similarly, following interactive session too doesn't show any warning messages. E:\python37>python >>> from warningexample import WarnExample >>> e = WarnExample() >>> e.method1() method1 7 >>> e.method2() method2 7 >>> e.new_method() new method 7 You have to start Python session with –Wd E:\python37>python -Wd >>> from warningexample import WarnExample >>> e=WarnExample() >>> e.method1() E:\python37\warningexample.py:10: DeprecationWarning: method1 is deprecated, use new_method instead DeprecationWarning method1 7 >>> e.method2() E:\python37\warningexample.py:17: PendingDeprecationWarning: method2 will be deprecated in version 2, use new_method instead PendingDeprecationWarning method2 7 >>> e.new_method() new method 7 The warnings filter controls whether warnings are ignored, displayed, or turned into errors (raising an exception). Following interactive session sets filter to default by simplefilter() function. E:\python37>python >>> import warnings >>> warnings.simplefilter('default') >>> from warningexample import WarnExample >>> e=WarnExample() >>> e.method1() E:\python37\warningexample.py:10: DeprecationWarning: method1 is deprecated, use new_method instead DeprecationWarning method1 7 >>> e.method2() E:\python37\warningexample.py:17: PendingDeprecationWarning: method2 will be deprecated in version 2, use new_method instead PendingDeprecationWarning method2 7 >>> e.new_method() new method 7 In order to temporarily suppress warnings, set simplefilter to 'ignore'. import warnings def function(): warnings.warn("deprecated", DeprecationWarning) with warnings.catch_warnings(): warnings.simplefilter("ignore") function()
[ { "code": null, "e": 1604, "s": 1187, "text": "Warning is different from error in a program. If error is encountered, Python program terminates instantly. Warning on the other hand is not fatal. It displays certain message but program continues. Warnings are issued to alert the user of certain conditions which aren't exactly exceptions. Typically warning appears if some deprecated usage of certain programming element like keyword/function/class etc. is found." }, { "code": null, "e": 1879, "s": 1604, "text": "Warning messages are displayed by warn() function defined in 'warning' module of Python's standard library. Warning is actually a subclass of Exception in built-in class hierarchy. There are a number of built-in Warning subclasses. User defined subclass can also be defined." }, { "code": null, "e": 2014, "s": 1879, "text": "Following code defines a class with a deprecated method and a method scheduled to be deprecated in a future version of the said class." }, { "code": null, "e": 2641, "s": 2014, "text": "# warningexample.py\nimport warnings\nclass WarnExample:\n def __init__(self):\n self.text = \"Warning\"\n\ndef method1(self):\n warnings.warn(\n \"method1 is deprecated, use new_method instead\",\n DeprecationWarning\n )\n print ('method1', len(self.text))\n def method2(self):\n warnings.warn(\n \"method2 will be deprecated in version 2, use new_method instead\",\n PendingDeprecationWarning\n )\n print ('method2', len(self.text))\n def new_method(self):\n print ('new method', len(self.text))\nif __name__=='__main__':\n e = WarnExample()\n e.method1()\n e.method2()\n e.new_method()" }, { "code": null, "e": 2692, "s": 2641, "text": "If above script is executed from command prompt as" }, { "code": null, "e": 2729, "s": 2692, "text": "E:\\python37>python warningexample.py" }, { "code": null, "e": 2821, "s": 2729, "text": "No warning messages are displayed on terminal. For that you have to use _Wd switch as below" }, { "code": null, "e": 3141, "s": 2821, "text": "E:\\python37>python -Wd warningexample.py\nwarningexample.py:10: DeprecationWarning: method1 is deprecated, use new_method instead\nDeprecationWarning\nmethod1 7\nwarningexample.py:19: PendingDeprecationWarning: method2 will be deprecated in version 2, use new_method instead\nPendingDeprecationWarning\nmethod2 7\nnew method 7" }, { "code": null, "e": 3221, "s": 3141, "text": "Similarly, following interactive session too doesn't show any warning messages." }, { "code": null, "e": 3389, "s": 3221, "text": "E:\\python37>python\n>>> from warningexample import WarnExample\n>>> e = WarnExample()\n>>> e.method1()\nmethod1 7\n>>> e.method2()\nmethod2 7\n>>> e.new_method()\nnew method 7" }, { "code": null, "e": 3431, "s": 3389, "text": "You have to start Python session with –Wd" }, { "code": null, "e": 3871, "s": 3431, "text": "E:\\python37>python -Wd\n>>> from warningexample import WarnExample\n>>> e=WarnExample()\n>>> e.method1()\nE:\\python37\\warningexample.py:10: DeprecationWarning: method1 is deprecated, use new_method instead\nDeprecationWarning\nmethod1 7\n>>> e.method2()\nE:\\python37\\warningexample.py:17: PendingDeprecationWarning: method2 will be deprecated in version 2, use new_method instead\nPendingDeprecationWarning\nmethod2 7\n>>> e.new_method()\nnew method 7" }, { "code": null, "e": 3987, "s": 3871, "text": "The warnings filter controls whether warnings are ignored, displayed, or turned into errors (raising an exception)." }, { "code": null, "e": 4068, "s": 3987, "text": "Following interactive session sets filter to default by simplefilter() function." }, { "code": null, "e": 4561, "s": 4068, "text": "E:\\python37>python\n>>> import warnings\n>>> warnings.simplefilter('default')\n>>> from warningexample import WarnExample\n>>> e=WarnExample()\n>>> e.method1()\nE:\\python37\\warningexample.py:10: DeprecationWarning: method1 is deprecated, use new_method instead\nDeprecationWarning\nmethod1 7\n>>> e.method2()\nE:\\python37\\warningexample.py:17: PendingDeprecationWarning: method2 will be deprecated in version 2, use new_method instead\nPendingDeprecationWarning\nmethod2 7\n>>> e.new_method()\nnew method 7" }, { "code": null, "e": 4634, "s": 4561, "text": "In order to temporarily suppress warnings, set simplefilter to 'ignore'." }, { "code": null, "e": 4791, "s": 4634, "text": "import warnings\n\ndef function():\nwarnings.warn(\"deprecated\", DeprecationWarning)\n\nwith warnings.catch_warnings():\nwarnings.simplefilter(\"ignore\")\nfunction()" } ]
How to enable webview java script in android?
This example demonstrate about How to enable webview java script in android. 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:app = "http://schemas.android.com/apk/res-auto" xmlns:tools = "http://schemas.android.com/tools" android:layout_width = "match_parent" android:gravity = "center" android:layout_height = "match_parent" tools:context = ".MainActivity" android:orientation = "vertical"> <WebView android:id = "@+id/web_view" android:layout_width = "match_parent" android:layout_height = "match_parent" /> </LinearLayout> In the above code, we have taken web view to show google.com. Step 3 − Add the following code to src/MainActivity.java package com.example.myapplication; import android.os.Build; import android.os.Bundle; import android.support.annotation.RequiresApi; import android.support.v7.app.AppCompatActivity; import android.webkit.WebView; import android.widget.EditText; public class MainActivity extends AppCompatActivity { @RequiresApi(api = Build.VERSION_CODES.P) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); WebView web_view = findViewById(R.id.web_view); web_view.loadUrl("https://www.google.com/"); web_view.requestFocus(); web_view.getSettings().setLightTouchEnabled(true); web_view.getSettings().setJavaScriptEnabled(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 = "com.example.myapplication"> <uses-permission android:name = "android.permission.INTERNET"/> <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 – Click here to download the project code
[ { "code": null, "e": 1264, "s": 1187, "text": "This example demonstrate about How to enable webview java script in android." }, { "code": null, "e": 1393, "s": 1264, "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": 1458, "s": 1393, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2025, "s": 1458, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<LinearLayout 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:gravity = \"center\"\n android:layout_height = \"match_parent\"\n tools:context = \".MainActivity\"\n android:orientation = \"vertical\">\n <WebView\n android:id = \"@+id/web_view\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\" />\n</LinearLayout>" }, { "code": null, "e": 2087, "s": 2025, "text": "In the above code, we have taken web view to show google.com." }, { "code": null, "e": 2144, "s": 2087, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 2902, "s": 2144, "text": "package com.example.myapplication;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.support.annotation.RequiresApi;\nimport android.support.v7.app.AppCompatActivity;\nimport android.webkit.WebView;\nimport android.widget.EditText;\npublic class MainActivity extends AppCompatActivity {\n @RequiresApi(api = Build.VERSION_CODES.P)\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n WebView web_view = findViewById(R.id.web_view);\n web_view.loadUrl(\"https://www.google.com/\");\n web_view.requestFocus();\n web_view.getSettings().setLightTouchEnabled(true);\n web_view.getSettings().setJavaScriptEnabled(true);\n }\n}" }, { "code": null, "e": 2957, "s": 2902, "text": "Step 4 − Add the following code to AndroidManifest.xml" }, { "code": null, "e": 3734, "s": 2957, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<manifest xmlns:android = \"http://schemas.android.com/apk/res/android\"\n package = \"com.example.myapplication\">\n <uses-permission android:name = \"android.permission.INTERNET\"/>\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": 4081, "s": 3734, "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": 4121, "s": 4081, "text": "Click here to download the project code" } ]
Python def Keyword
29 Sep, 2021 Python def keyword is used to define a function, it is placed before a function name that is provided by the user to create a user-defined function. In python, a function is a logical unit of code containing a sequence of statements indented under a name given using the “def” keyword. In python def keyword is the most used keyword. Syntax: def function_name: function definition statements... Use of def keyword: In the case of classes, the def keyword is used for defining the methods of a class. def keyword is also required to define the special member function of a class like __init__(). The possible practical application is that it provides the feature of code reusability rather than writing the piece of code again and again we can define a function and write the code inside the function with the help of the def keyword. It will be more clear in the illustrated example given below. There can possibly be many applications of def depending upon the use cases. Example 1: Use of def keyword. In this example, we are going to create a user define a function using def keyword. Python3 # Python3 code to demonstrate# def keyword # function for subtraction of 2 numbers.def subNumbers(x, y): return (x-y) # main codea = 90b = 50 # finding subtractionresult = subNumbers(a, b) # print statementprint("subtraction of ", a, " and ", b, " is = ", result) Output: subtraction of 90 and 50 is = 40 Example 2: User defines a function with first 10 prime numbers. Python3 # Python program to print first 10# prime numbers # A function name prime is defined# using defdef prime(n): x = 1 count = 0 while count < n: for d in range(2, x, 1): if x % d == 0: x += 1 else: print(x) x += 1 count += 1 # Driver Coden = 10 # print statementprint("First 10 prime numbers are: ")prime(n) Output: First 10 prime numbers are: 1 2 3 5 7 11 13 17 19 23 Example 3: User defines a function with a factorial number. Python3 # Python program to find the# factorial of a number # Function name factorial is defineddef factorial(n): if n == 1: return n else: return n*factorial(n-1) # Main codenum = 6 # check is the number is negativeif num < 0: print("Sorry, factorial does not exist for negative numbers")elif num == 0: print("The factorial of 0 is 1")else: print("The factorial of", num, "is", factorial(num)) Output: The factorial of 6 is 720 sweetyty Picked python-basics Python-Functions Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n29 Sep, 2021" }, { "code": null, "e": 387, "s": 53, "text": "Python def keyword is used to define a function, it is placed before a function name that is provided by the user to create a user-defined function. In python, a function is a logical unit of code containing a sequence of statements indented under a name given using the “def” keyword. In python def keyword is the most used keyword." }, { "code": null, "e": 395, "s": 387, "text": "Syntax:" }, { "code": null, "e": 453, "s": 395, "text": "def function_name: \n function definition statements..." }, { "code": null, "e": 473, "s": 453, "text": "Use of def keyword:" }, { "code": null, "e": 558, "s": 473, "text": "In the case of classes, the def keyword is used for defining the methods of a class." }, { "code": null, "e": 653, "s": 558, "text": "def keyword is also required to define the special member function of a class like __init__()." }, { "code": null, "e": 1032, "s": 653, "text": "The possible practical application is that it provides the feature of code reusability rather than writing the piece of code again and again we can define a function and write the code inside the function with the help of the def keyword. It will be more clear in the illustrated example given below. There can possibly be many applications of def depending upon the use cases. " }, { "code": null, "e": 1063, "s": 1032, "text": "Example 1: Use of def keyword." }, { "code": null, "e": 1147, "s": 1063, "text": "In this example, we are going to create a user define a function using def keyword." }, { "code": null, "e": 1155, "s": 1147, "text": "Python3" }, { "code": "# Python3 code to demonstrate# def keyword # function for subtraction of 2 numbers.def subNumbers(x, y): return (x-y) # main codea = 90b = 50 # finding subtractionresult = subNumbers(a, b) # print statementprint(\"subtraction of \", a, \" and \", b, \" is = \", result)", "e": 1422, "s": 1155, "text": null }, { "code": null, "e": 1430, "s": 1422, "text": "Output:" }, { "code": null, "e": 1468, "s": 1430, "text": "subtraction of 90 and 50 is = 40" }, { "code": null, "e": 1534, "s": 1468, "text": "Example 2: User defines a function with first 10 prime numbers. " }, { "code": null, "e": 1542, "s": 1534, "text": "Python3" }, { "code": "# Python program to print first 10# prime numbers # A function name prime is defined# using defdef prime(n): x = 1 count = 0 while count < n: for d in range(2, x, 1): if x % d == 0: x += 1 else: print(x) x += 1 count += 1 # Driver Coden = 10 # print statementprint(\"First 10 prime numbers are: \")prime(n)", "e": 1930, "s": 1542, "text": null }, { "code": null, "e": 1939, "s": 1930, "text": "Output: " }, { "code": null, "e": 1994, "s": 1939, "text": "First 10 prime numbers are: \n1\n2\n3\n5\n7\n11\n13\n17\n19\n23" }, { "code": null, "e": 2055, "s": 1994, "text": " Example 3: User defines a function with a factorial number." }, { "code": null, "e": 2063, "s": 2055, "text": "Python3" }, { "code": "# Python program to find the# factorial of a number # Function name factorial is defineddef factorial(n): if n == 1: return n else: return n*factorial(n-1) # Main codenum = 6 # check is the number is negativeif num < 0: print(\"Sorry, factorial does not exist for negative numbers\")elif num == 0: print(\"The factorial of 0 is 1\")else: print(\"The factorial of\", num, \"is\", factorial(num))", "e": 2479, "s": 2063, "text": null }, { "code": null, "e": 2487, "s": 2479, "text": "Output:" }, { "code": null, "e": 2513, "s": 2487, "text": "The factorial of 6 is 720" }, { "code": null, "e": 2522, "s": 2513, "text": "sweetyty" }, { "code": null, "e": 2529, "s": 2522, "text": "Picked" }, { "code": null, "e": 2543, "s": 2529, "text": "python-basics" }, { "code": null, "e": 2560, "s": 2543, "text": "Python-Functions" }, { "code": null, "e": 2567, "s": 2560, "text": "Python" } ]
Smallest string which not a subsequence of the given string
09 Jun, 2021 Given a string str, consisting of lowercase alphabets, the task is to find the shortest string which is not a subsequence of the given string. If multiple strings exist, then print any one of them. Examples: Input: str = “abaabcc” Output: d Explanation: One of the possible shortest string which is not a subsequence of the given string is “d”. Therefore, the required output is “d”. Input: str = “abcdefghijklmnopqrstuvwxyzaabbccdd” Output: ze Approach: The problem can be solved using Greedy technique. Follow the steps below to solve the problem: Initialize a string, say shortestString, to store the shortest string which is not a subsequence of the given string. Initialize a Set, say segments, to store all possible characters of each subsegment. Traverse the string and insert the character of the string into segments and check if the segments contain all the lowercase alphabets or not. If found to be true, then append the current character into shortestString and remove all the elements from the segments. Iterate over all possible lowercase alphabets in the range [a – z] and check if the current character is present in the segment or not. If found to be true, then insert the current character into shortestString. Finally, print the value of shortestString. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to find shortest string which// not a subsequence of the given stringstring ShortestSubsequenceNotPresent(string str){ // Stores the shortest string which is // not a subsequence of the given string string shortestString; // Stores length of string int N = str.length(); // Stores distinct character of subsegments unordered_set<char> subsegments; // Traverse the given string for (int i = 0; i < N; i++) { // Insert current character // into subsegments subsegments.insert(str[i]); // If all lowercase alphabets // present in the subsegment if (subsegments.size() == 26) { // Insert the last character of // subsegment into shortestString shortestString.push_back(str[i]); // Remove all elements from // the current subsegment subsegments.clear(); } } // Traverse all lowercase alphabets for (char ch = 'a'; ch <= 'z'; ch++) { // If current character is not // present in the subsegment if (subsegments.count(ch) == 0) { shortestString.push_back(ch); // Return shortestString return shortestString; } } return shortestString;} // Driver Codeint main(){ // Given String string str = "abcdefghijklmnopqrstuvwxyzaabbccdd"; cout << ShortestSubsequenceNotPresent(str); return 0;} // Java program to implement// the above approach import java.io.*;import java.util.*; class GFG { public static String ShortestSubsequenceNotPresent(String str) { // Stores the shortest string which is // not a subsequence of the given string String shortestString = ""; // Stores length of string int N = str.length(); // Stores distinct character of subsegments HashSet<Character> subsegments = new HashSet<>(); // Traverse the given string for (int i = 0; i < N; i++) { // Insert current character // into subsegments subsegments.add(str.charAt(i)); // If all lowercase alphabets // present in the subsegment if (subsegments.size() == 26) { // Insert the last character of // subsegment into shortestString shortestString = shortestString + str.charAt(i); // Remove all elements from // the current subsegment subsegments.clear(); } } // Traverse all lowercase alphabets for (char ch = 'a'; ch <= 'z'; ch++) { // If current character is not // present in the subsegment if (!subsegments.contains(ch)) { shortestString = shortestString + ch; // Return shortestString return shortestString; } } return shortestString; } // Driver Code public static void main(String[] args) { String str = "abcdefghijklmnopqrstuvwxyzaabbccdd"; System.out.print( ShortestSubsequenceNotPresent(str)); }}// This code is contributed by Manu Pathria # Python3 program to implement# the above approach # Function to find shortest string which# not a subsequence of the given stringdef ShortestSubsequenceNotPresent(Str): # Stores the shortest string which is # not a subsequence of the given string shortestString = "" # Stores length of string N = len(Str) # Stores distinct character of subsegments subsegments = set() # Traverse the given string for i in range(N): # Insert current character # into subsegments subsegments.add(Str[i]) # If all lowercase alphabets # present in the subsegment if (len(subsegments) == 26) : # Insert the last character of # subsegment into shortestString shortestString += Str[i] # Remove all elements from # the current subsegment subsegments.clear() # Traverse all lowercase alphabets for ch in range(int(26)): # If current character is not # present in the subsegment if (chr(ch + 97) not in subsegments) : shortestString += chr(ch + 97) # Return shortestString return shortestString return shortestString # Driver code# Given StringStr = "abcdefghijklmnopqrstuvwxyzaabbccdd" print(ShortestSubsequenceNotPresent(Str)) # This code is contributed by divyeshrabadiya07 // C# program to implement// the above approachusing System;using System.Collections.Generic; class GFG{ public static String ShortestSubsequenceNotPresent( String str){ // Stores the shortest string which is // not a subsequence of the given string String shortestString = ""; // Stores length of string int N = str.Length; // Stores distinct character of subsegments HashSet<char> subsegments = new HashSet<char>(); // Traverse the given string for(int i = 0; i < N; i++) { // Insert current character // into subsegments subsegments.Add(str[i]); // If all lowercase alphabets // present in the subsegment if (subsegments.Count == 26) { // Insert the last character of // subsegment into shortestString shortestString = shortestString + str[i]; // Remove all elements from // the current subsegment subsegments.Clear(); } } // Traverse all lowercase alphabets for(char ch = 'a'; ch <= 'z'; ch++) { // If current character is not // present in the subsegment if (!subsegments.Contains(ch)) { shortestString = shortestString + ch; // Return shortestString return shortestString; } } return shortestString;} // Driver Codepublic static void Main(String[] args){ String str = "abcdefghijklmnopqrstuvwxyzaabbccdd"; Console.Write( ShortestSubsequenceNotPresent(str));}} // This code is contributed by Rajput-Ji <script> // JavaScript program to implement// the above approach // Function to find shortest string which// not a subsequence of the given stringfunction ShortestSubsequenceNotPresent(str){ // Stores the shortest string which is // not a subsequence of the given string var shortestString = []; // Stores length of string var N = str.length; // Stores distinct character of subsegments var subsegments = new Set(); // Traverse the given string for (var i = 0; i < N; i++) { // Insert current character // into subsegments subsegments.add(str[i].charCodeAt(0)); // If all lowercase alphabets // present in the subsegment if (subsegments.size == 26) { // Insert the last character of // subsegment into shortestString shortestString.push(str[i]); // Remove all elements from // the current subsegment subsegments = new Set(); } } // Traverse all lowercase alphabets for (var ch = 'a'.charCodeAt(0); ch <= 'z'.charCodeAt(0); ch++) { // If current character is not // present in the subsegment if (!subsegments.has(ch)) { shortestString.push(String.fromCharCode(ch)); // Return shortestString return shortestString.join(""); } } return shortestString.join("");} // Driver Code // Given Stringvar str = "abcdefghijklmnopqrstuvwxyzaabbccdd"; document.write( ShortestSubsequenceNotPresent(str)); </script> ze Time Complexity: O(N) Auxiliary Space: O(N) manupathria Rajput-Ji divyeshrabadiya07 rrrtnx cpp-unordered_set Facebook interview-preparation prefix subsequence Greedy Sorting Strings Facebook Strings Greedy Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Huffman Coding | Greedy Algo-3 Coin Change | DP-7 Activity Selection Problem | Greedy Algo-1 Fractional Knapsack Problem Job Sequencing Problem Merge Sort Bubble Sort Algorithm QuickSort Insertion Sort Selection Sort Algorithm
[ { "code": null, "e": 54, "s": 26, "text": "\n09 Jun, 2021" }, { "code": null, "e": 252, "s": 54, "text": "Given a string str, consisting of lowercase alphabets, the task is to find the shortest string which is not a subsequence of the given string. If multiple strings exist, then print any one of them." }, { "code": null, "e": 262, "s": 252, "text": "Examples:" }, { "code": null, "e": 439, "s": 262, "text": "Input: str = “abaabcc” Output: d Explanation: One of the possible shortest string which is not a subsequence of the given string is “d”. Therefore, the required output is “d”. " }, { "code": null, "e": 501, "s": 439, "text": "Input: str = “abcdefghijklmnopqrstuvwxyzaabbccdd” Output: ze " }, { "code": null, "e": 606, "s": 501, "text": "Approach: The problem can be solved using Greedy technique. Follow the steps below to solve the problem:" }, { "code": null, "e": 724, "s": 606, "text": "Initialize a string, say shortestString, to store the shortest string which is not a subsequence of the given string." }, { "code": null, "e": 809, "s": 724, "text": "Initialize a Set, say segments, to store all possible characters of each subsegment." }, { "code": null, "e": 1074, "s": 809, "text": "Traverse the string and insert the character of the string into segments and check if the segments contain all the lowercase alphabets or not. If found to be true, then append the current character into shortestString and remove all the elements from the segments." }, { "code": null, "e": 1286, "s": 1074, "text": "Iterate over all possible lowercase alphabets in the range [a – z] and check if the current character is present in the segment or not. If found to be true, then insert the current character into shortestString." }, { "code": null, "e": 1330, "s": 1286, "text": "Finally, print the value of shortestString." }, { "code": null, "e": 1381, "s": 1330, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 1385, "s": 1381, "text": "C++" }, { "code": null, "e": 1390, "s": 1385, "text": "Java" }, { "code": null, "e": 1398, "s": 1390, "text": "Python3" }, { "code": null, "e": 1401, "s": 1398, "text": "C#" }, { "code": null, "e": 1412, "s": 1401, "text": "Javascript" }, { "code": "// C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to find shortest string which// not a subsequence of the given stringstring ShortestSubsequenceNotPresent(string str){ // Stores the shortest string which is // not a subsequence of the given string string shortestString; // Stores length of string int N = str.length(); // Stores distinct character of subsegments unordered_set<char> subsegments; // Traverse the given string for (int i = 0; i < N; i++) { // Insert current character // into subsegments subsegments.insert(str[i]); // If all lowercase alphabets // present in the subsegment if (subsegments.size() == 26) { // Insert the last character of // subsegment into shortestString shortestString.push_back(str[i]); // Remove all elements from // the current subsegment subsegments.clear(); } } // Traverse all lowercase alphabets for (char ch = 'a'; ch <= 'z'; ch++) { // If current character is not // present in the subsegment if (subsegments.count(ch) == 0) { shortestString.push_back(ch); // Return shortestString return shortestString; } } return shortestString;} // Driver Codeint main(){ // Given String string str = \"abcdefghijklmnopqrstuvwxyzaabbccdd\"; cout << ShortestSubsequenceNotPresent(str); return 0;}", "e": 2944, "s": 1412, "text": null }, { "code": "// Java program to implement// the above approach import java.io.*;import java.util.*; class GFG { public static String ShortestSubsequenceNotPresent(String str) { // Stores the shortest string which is // not a subsequence of the given string String shortestString = \"\"; // Stores length of string int N = str.length(); // Stores distinct character of subsegments HashSet<Character> subsegments = new HashSet<>(); // Traverse the given string for (int i = 0; i < N; i++) { // Insert current character // into subsegments subsegments.add(str.charAt(i)); // If all lowercase alphabets // present in the subsegment if (subsegments.size() == 26) { // Insert the last character of // subsegment into shortestString shortestString = shortestString + str.charAt(i); // Remove all elements from // the current subsegment subsegments.clear(); } } // Traverse all lowercase alphabets for (char ch = 'a'; ch <= 'z'; ch++) { // If current character is not // present in the subsegment if (!subsegments.contains(ch)) { shortestString = shortestString + ch; // Return shortestString return shortestString; } } return shortestString; } // Driver Code public static void main(String[] args) { String str = \"abcdefghijklmnopqrstuvwxyzaabbccdd\"; System.out.print( ShortestSubsequenceNotPresent(str)); }}// This code is contributed by Manu Pathria", "e": 4708, "s": 2944, "text": null }, { "code": "# Python3 program to implement# the above approach # Function to find shortest string which# not a subsequence of the given stringdef ShortestSubsequenceNotPresent(Str): # Stores the shortest string which is # not a subsequence of the given string shortestString = \"\" # Stores length of string N = len(Str) # Stores distinct character of subsegments subsegments = set() # Traverse the given string for i in range(N): # Insert current character # into subsegments subsegments.add(Str[i]) # If all lowercase alphabets # present in the subsegment if (len(subsegments) == 26) : # Insert the last character of # subsegment into shortestString shortestString += Str[i] # Remove all elements from # the current subsegment subsegments.clear() # Traverse all lowercase alphabets for ch in range(int(26)): # If current character is not # present in the subsegment if (chr(ch + 97) not in subsegments) : shortestString += chr(ch + 97) # Return shortestString return shortestString return shortestString # Driver code# Given StringStr = \"abcdefghijklmnopqrstuvwxyzaabbccdd\" print(ShortestSubsequenceNotPresent(Str)) # This code is contributed by divyeshrabadiya07", "e": 6115, "s": 4708, "text": null }, { "code": "// C# program to implement// the above approachusing System;using System.Collections.Generic; class GFG{ public static String ShortestSubsequenceNotPresent( String str){ // Stores the shortest string which is // not a subsequence of the given string String shortestString = \"\"; // Stores length of string int N = str.Length; // Stores distinct character of subsegments HashSet<char> subsegments = new HashSet<char>(); // Traverse the given string for(int i = 0; i < N; i++) { // Insert current character // into subsegments subsegments.Add(str[i]); // If all lowercase alphabets // present in the subsegment if (subsegments.Count == 26) { // Insert the last character of // subsegment into shortestString shortestString = shortestString + str[i]; // Remove all elements from // the current subsegment subsegments.Clear(); } } // Traverse all lowercase alphabets for(char ch = 'a'; ch <= 'z'; ch++) { // If current character is not // present in the subsegment if (!subsegments.Contains(ch)) { shortestString = shortestString + ch; // Return shortestString return shortestString; } } return shortestString;} // Driver Codepublic static void Main(String[] args){ String str = \"abcdefghijklmnopqrstuvwxyzaabbccdd\"; Console.Write( ShortestSubsequenceNotPresent(str));}} // This code is contributed by Rajput-Ji", "e": 7752, "s": 6115, "text": null }, { "code": "<script> // JavaScript program to implement// the above approach // Function to find shortest string which// not a subsequence of the given stringfunction ShortestSubsequenceNotPresent(str){ // Stores the shortest string which is // not a subsequence of the given string var shortestString = []; // Stores length of string var N = str.length; // Stores distinct character of subsegments var subsegments = new Set(); // Traverse the given string for (var i = 0; i < N; i++) { // Insert current character // into subsegments subsegments.add(str[i].charCodeAt(0)); // If all lowercase alphabets // present in the subsegment if (subsegments.size == 26) { // Insert the last character of // subsegment into shortestString shortestString.push(str[i]); // Remove all elements from // the current subsegment subsegments = new Set(); } } // Traverse all lowercase alphabets for (var ch = 'a'.charCodeAt(0); ch <= 'z'.charCodeAt(0); ch++) { // If current character is not // present in the subsegment if (!subsegments.has(ch)) { shortestString.push(String.fromCharCode(ch)); // Return shortestString return shortestString.join(\"\"); } } return shortestString.join(\"\");} // Driver Code // Given Stringvar str = \"abcdefghijklmnopqrstuvwxyzaabbccdd\"; document.write( ShortestSubsequenceNotPresent(str)); </script>", "e": 9287, "s": 7752, "text": null }, { "code": null, "e": 9290, "s": 9287, "text": "ze" }, { "code": null, "e": 9334, "s": 9290, "text": "Time Complexity: O(N) Auxiliary Space: O(N)" }, { "code": null, "e": 9346, "s": 9334, "text": "manupathria" }, { "code": null, "e": 9356, "s": 9346, "text": "Rajput-Ji" }, { "code": null, "e": 9374, "s": 9356, "text": "divyeshrabadiya07" }, { "code": null, "e": 9381, "s": 9374, "text": "rrrtnx" }, { "code": null, "e": 9399, "s": 9381, "text": "cpp-unordered_set" }, { "code": null, "e": 9408, "s": 9399, "text": "Facebook" }, { "code": null, "e": 9430, "s": 9408, "text": "interview-preparation" }, { "code": null, "e": 9437, "s": 9430, "text": "prefix" }, { "code": null, "e": 9449, "s": 9437, "text": "subsequence" }, { "code": null, "e": 9456, "s": 9449, "text": "Greedy" }, { "code": null, "e": 9464, "s": 9456, "text": "Sorting" }, { "code": null, "e": 9472, "s": 9464, "text": "Strings" }, { "code": null, "e": 9481, "s": 9472, "text": "Facebook" }, { "code": null, "e": 9489, "s": 9481, "text": "Strings" }, { "code": null, "e": 9496, "s": 9489, "text": "Greedy" }, { "code": null, "e": 9504, "s": 9496, "text": "Sorting" }, { "code": null, "e": 9602, "s": 9504, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9633, "s": 9602, "text": "Huffman Coding | Greedy Algo-3" }, { "code": null, "e": 9652, "s": 9633, "text": "Coin Change | DP-7" }, { "code": null, "e": 9695, "s": 9652, "text": "Activity Selection Problem | Greedy Algo-1" }, { "code": null, "e": 9723, "s": 9695, "text": "Fractional Knapsack Problem" }, { "code": null, "e": 9746, "s": 9723, "text": "Job Sequencing Problem" }, { "code": null, "e": 9757, "s": 9746, "text": "Merge Sort" }, { "code": null, "e": 9779, "s": 9757, "text": "Bubble Sort Algorithm" }, { "code": null, "e": 9789, "s": 9779, "text": "QuickSort" }, { "code": null, "e": 9804, "s": 9789, "text": "Insertion Sort" } ]
Python – Convert Tuple String to Integer Tuple
01 Mar, 2020 Interconversion of data is a popular problem developers generally deal with. One can face a problem to convert tuple string to integer tuple. Let’s discuss certain ways in which this task can be performed. Method #1 : Using tuple() + int() + replace() + split()The combination of above methods can be used to perform this task. In this, we perform the conversion using tuple() and int(). Extraction of elements is done by replace() and split(). # Python3 code to demonstrate working of # Convert Tuple String to Integer Tuple# Using tuple() + int() + replace() + split() # initializing string test_str = "(7, 8, 9)" # printing original string print("The original string is : " + test_str) # Convert Tuple String to Integer Tuple# Using tuple() + int() + replace() + split()res = tuple(int(num) for num in test_str.replace('(', '').replace(')', '').replace('...', '').split(', ')) # printing result print("The tuple after conversion is : " + str(res)) The original string is : (7, 8, 9) The tuple after conversion is : (7, 8, 9) Method #2 : Using eval()This is recommended method to solve this task. This performs the interconversion task internally. # Python3 code to demonstrate working of # Convert Tuple String to Integer Tuple# Using eval() # initializing string test_str = "(7, 8, 9)" # printing original string print("The original string is : " + test_str) # Convert Tuple String to Integer Tuple# Using eval()res = eval(test_str) # printing result print("The tuple after conversion is : " + str(res)) The original string is : (7, 8, 9) The tuple after conversion is : (7, 8, 9) Python tuple-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n01 Mar, 2020" }, { "code": null, "e": 259, "s": 53, "text": "Interconversion of data is a popular problem developers generally deal with. One can face a problem to convert tuple string to integer tuple. Let’s discuss certain ways in which this task can be performed." }, { "code": null, "e": 498, "s": 259, "text": "Method #1 : Using tuple() + int() + replace() + split()The combination of above methods can be used to perform this task. In this, we perform the conversion using tuple() and int(). Extraction of elements is done by replace() and split()." }, { "code": "# Python3 code to demonstrate working of # Convert Tuple String to Integer Tuple# Using tuple() + int() + replace() + split() # initializing string test_str = \"(7, 8, 9)\" # printing original string print(\"The original string is : \" + test_str) # Convert Tuple String to Integer Tuple# Using tuple() + int() + replace() + split()res = tuple(int(num) for num in test_str.replace('(', '').replace(')', '').replace('...', '').split(', ')) # printing result print(\"The tuple after conversion is : \" + str(res)) ", "e": 1010, "s": 498, "text": null }, { "code": null, "e": 1088, "s": 1010, "text": "The original string is : (7, 8, 9)\nThe tuple after conversion is : (7, 8, 9)\n" }, { "code": null, "e": 1212, "s": 1090, "text": "Method #2 : Using eval()This is recommended method to solve this task. This performs the interconversion task internally." }, { "code": "# Python3 code to demonstrate working of # Convert Tuple String to Integer Tuple# Using eval() # initializing string test_str = \"(7, 8, 9)\" # printing original string print(\"The original string is : \" + test_str) # Convert Tuple String to Integer Tuple# Using eval()res = eval(test_str) # printing result print(\"The tuple after conversion is : \" + str(res)) ", "e": 1576, "s": 1212, "text": null }, { "code": null, "e": 1654, "s": 1576, "text": "The original string is : (7, 8, 9)\nThe tuple after conversion is : (7, 8, 9)\n" }, { "code": null, "e": 1676, "s": 1654, "text": "Python tuple-programs" }, { "code": null, "e": 1683, "s": 1676, "text": "Python" }, { "code": null, "e": 1699, "s": 1683, "text": "Python Programs" } ]
What is API? How it is useful in Web Development ?
20 Sep, 2019 API stands for Application Programming Interface (main participant of all the interactivity)It is like a messenger that takes our requests to a system and returns a response back to us via seamless connectivity.We use APIs in many cases like to get data for a web application or to connect to a remote server that has data like weather that keeps changing or to enable two applications to exchange data among each other.API not only provide reusability of code but also uses the concept of Abstraction (showing functionality by hiding complexity).Most common real life use of API concepts include: Waiter in a restaurant taking your order request to the chef and bringing back the requested dish Switchboard turning off the tubelight just on a single press Booking a flight online from sites like MMT(web based) Signing up in a shopping site from Facebook Account(web based) Different APIs will communicate in different ways: XML-RCP/SOAP: Both uses XML JavaScript: Focused around Javascript RESTful APIs: HTTP protocol (HyperText Transfer Protocol) used (best for web APIs) APIs’ major features in Web DevelopmentAPIs can be used for mashups that is information from one site can be mixed with that of another. Authentication is one of the important things to be noted as all APIs are not public. API keys are required in case of authentication for safe use. For example, please refer to Gmail API AuthenticationThere are some APIs which do not require any access token. Example: Github APIhttps://api.github.com Output: { "current_user_url": "https://api.github.com/user", "current_user_authorizations_html_url": "https://github.com/settings/connections/applications{/client_id}", "authorizations_url": "https://api.github.com/authorizations", "code_search_url": "https://api.github.com/search/code?q={query}{&page, per_page, sort, order}", "commit_search_url": "https://api.github.com/search/commits?q={query}{&page, per_page, sort, order}", "emails_url": "https://api.github.com/user/emails", "emojis_url": "https://api.github.com/emojis", "events_url": "https://api.github.com/events", "feeds_url": "https://api.github.com/feeds", "followers_url": "https://api.github.com/user/followers", "following_url": "https://api.github.com/user/following{/target}", "gists_url": "https://api.github.com/gists{/gist_id}", "hub_url": "https://api.github.com/hub", "issue_search_url": "https://api.github.com/search/issues?q={query}{&page, per_page, sort, order}", "issues_url": "https://api.github.com/issues", "keys_url": "https://api.github.com/user/keys", "notifications_url": "https://api.github.com/notifications", "organization_repositories_url": "https://api.github.com/orgs/{org}/repos{?type, page, per_page, sort}", "organization_url": "https://api.github.com/orgs/{org}", "public_gists_url": "https://api.github.com/gists/public", "rate_limit_url": "https://api.github.com/rate_limit", "repository_url": "https://api.github.com/repos/{owner}/{repo}", "repository_search_url": "https://api.github.com/search/repositories?q={query}{&page, per_page, sort, order}", "current_user_repositories_url": "https://api.github.com/user/repos{?type, page, per_page, sort}", "starred_url": "https://api.github.com/user/starred{/owner}{/repo}", "starred_gists_url": "https://api.github.com/gists/starred", "team_url": "https://api.github.com/teams", "user_url": "https://api.github.com/users/{user}", "user_organizations_url": "https://api.github.com/user/orgs", "user_repositories_url": "https://api.github.com/users/{user}/repos{?type, page, per_page, sort}", "user_search_url": "https://api.github.com/search/users?q={query}{&page, per_page, sort, order}" } List in JSON format https://api.github.com/feedsOutput:{ "timeline_url": "https://github.com/timeline", "user_url": "https://github.com/{user}", "security_advisories_url": "https://github.com/security-advisories", "_links": { "timeline": { "href": "https://github.com/timeline", "type": "application/atom+xml" }, "user": { "href": "https://github.com/{user}", "type": "application/atom+xml" }, "security_advisories": { "href": "https://github.com/security-advisories", "type": "application/atom+xml" } } } https://api.github.com/rate_limit{ "resources": { "core": { "limit": 60, "remaining": 56, "reset": 1567928119 }, "search": { "limit": 10, "remaining": 10, "reset": 1567924666 }, "graphql": { "limit": 0, "remaining": 0, "reset": 1567928206 }, "integration_manifest": { "limit": 5000, "remaining": 5000, "reset": 1567928206 } }, "rate": { "limit": 60, "remaining": 56, "reset": 1567928119 } } https://api.github.com/feedsOutput:{ "timeline_url": "https://github.com/timeline", "user_url": "https://github.com/{user}", "security_advisories_url": "https://github.com/security-advisories", "_links": { "timeline": { "href": "https://github.com/timeline", "type": "application/atom+xml" }, "user": { "href": "https://github.com/{user}", "type": "application/atom+xml" }, "security_advisories": { "href": "https://github.com/security-advisories", "type": "application/atom+xml" } } } { "timeline_url": "https://github.com/timeline", "user_url": "https://github.com/{user}", "security_advisories_url": "https://github.com/security-advisories", "_links": { "timeline": { "href": "https://github.com/timeline", "type": "application/atom+xml" }, "user": { "href": "https://github.com/{user}", "type": "application/atom+xml" }, "security_advisories": { "href": "https://github.com/security-advisories", "type": "application/atom+xml" } } } https://api.github.com/rate_limit{ "resources": { "core": { "limit": 60, "remaining": 56, "reset": 1567928119 }, "search": { "limit": 10, "remaining": 10, "reset": 1567924666 }, "graphql": { "limit": 0, "remaining": 0, "reset": 1567928206 }, "integration_manifest": { "limit": 5000, "remaining": 5000, "reset": 1567928206 } }, "rate": { "limit": 60, "remaining": 56, "reset": 1567928119 } } { "resources": { "core": { "limit": 60, "remaining": 56, "reset": 1567928119 }, "search": { "limit": 10, "remaining": 10, "reset": 1567924666 }, "graphql": { "limit": 0, "remaining": 0, "reset": 1567928206 }, "integration_manifest": { "limit": 5000, "remaining": 5000, "reset": 1567928206 } }, "rate": { "limit": 60, "remaining": 56, "reset": 1567928119 } } Picked Web-API Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n20 Sep, 2019" }, { "code": null, "e": 652, "s": 54, "text": "API stands for Application Programming Interface (main participant of all the interactivity)It is like a messenger that takes our requests to a system and returns a response back to us via seamless connectivity.We use APIs in many cases like to get data for a web application or to connect to a remote server that has data like weather that keeps changing or to enable two applications to exchange data among each other.API not only provide reusability of code but also uses the concept of Abstraction (showing functionality by hiding complexity).Most common real life use of API concepts include:" }, { "code": null, "e": 750, "s": 652, "text": "Waiter in a restaurant taking your order request to the chef and bringing back the requested dish" }, { "code": null, "e": 811, "s": 750, "text": "Switchboard turning off the tubelight just on a single press" }, { "code": null, "e": 866, "s": 811, "text": "Booking a flight online from sites like MMT(web based)" }, { "code": null, "e": 929, "s": 866, "text": "Signing up in a shopping site from Facebook Account(web based)" }, { "code": null, "e": 980, "s": 929, "text": "Different APIs will communicate in different ways:" }, { "code": null, "e": 1008, "s": 980, "text": "XML-RCP/SOAP: Both uses XML" }, { "code": null, "e": 1046, "s": 1008, "text": "JavaScript: Focused around Javascript" }, { "code": null, "e": 1129, "s": 1046, "text": "RESTful APIs: HTTP protocol (HyperText Transfer Protocol) used (best for web APIs)" }, { "code": null, "e": 1526, "s": 1129, "text": "APIs’ major features in Web DevelopmentAPIs can be used for mashups that is information from one site can be mixed with that of another. Authentication is one of the important things to be noted as all APIs are not public. API keys are required in case of authentication for safe use. For example, please refer to Gmail API AuthenticationThere are some APIs which do not require any access token." }, { "code": null, "e": 1568, "s": 1526, "text": "Example: Github APIhttps://api.github.com" }, { "code": null, "e": 1576, "s": 1568, "text": "Output:" }, { "code": null, "e": 3766, "s": 1576, "text": "{\n \"current_user_url\": \"https://api.github.com/user\",\n \"current_user_authorizations_html_url\": \"https://github.com/settings/connections/applications{/client_id}\",\n \"authorizations_url\": \"https://api.github.com/authorizations\",\n \"code_search_url\": \"https://api.github.com/search/code?q={query}{&page, per_page, sort, order}\",\n \"commit_search_url\": \"https://api.github.com/search/commits?q={query}{&page, per_page, sort, order}\",\n \"emails_url\": \"https://api.github.com/user/emails\",\n \"emojis_url\": \"https://api.github.com/emojis\",\n \"events_url\": \"https://api.github.com/events\",\n \"feeds_url\": \"https://api.github.com/feeds\",\n \"followers_url\": \"https://api.github.com/user/followers\",\n \"following_url\": \"https://api.github.com/user/following{/target}\",\n \"gists_url\": \"https://api.github.com/gists{/gist_id}\",\n \"hub_url\": \"https://api.github.com/hub\",\n \"issue_search_url\": \"https://api.github.com/search/issues?q={query}{&page, per_page, sort, order}\",\n \"issues_url\": \"https://api.github.com/issues\",\n \"keys_url\": \"https://api.github.com/user/keys\",\n \"notifications_url\": \"https://api.github.com/notifications\",\n \"organization_repositories_url\": \"https://api.github.com/orgs/{org}/repos{?type, page, per_page, sort}\",\n \"organization_url\": \"https://api.github.com/orgs/{org}\",\n \"public_gists_url\": \"https://api.github.com/gists/public\",\n \"rate_limit_url\": \"https://api.github.com/rate_limit\",\n \"repository_url\": \"https://api.github.com/repos/{owner}/{repo}\",\n \"repository_search_url\": \"https://api.github.com/search/repositories?q={query}{&page, per_page, sort, order}\",\n \"current_user_repositories_url\": \"https://api.github.com/user/repos{?type, page, per_page, sort}\",\n \"starred_url\": \"https://api.github.com/user/starred{/owner}{/repo}\",\n \"starred_gists_url\": \"https://api.github.com/gists/starred\",\n \"team_url\": \"https://api.github.com/teams\",\n \"user_url\": \"https://api.github.com/users/{user}\",\n \"user_organizations_url\": \"https://api.github.com/user/orgs\",\n \"user_repositories_url\": \"https://api.github.com/users/{user}/repos{?type, page, per_page, sort}\",\n \"user_search_url\": \"https://api.github.com/search/users?q={query}{&page, per_page, sort, order}\"\n}\n" }, { "code": null, "e": 3786, "s": 3766, "text": "List in JSON format" }, { "code": null, "e": 4858, "s": 3786, "text": "https://api.github.com/feedsOutput:{\n \"timeline_url\": \"https://github.com/timeline\",\n \"user_url\": \"https://github.com/{user}\",\n \"security_advisories_url\": \"https://github.com/security-advisories\",\n \"_links\": {\n \"timeline\": {\n \"href\": \"https://github.com/timeline\",\n \"type\": \"application/atom+xml\"\n },\n \"user\": {\n \"href\": \"https://github.com/{user}\",\n \"type\": \"application/atom+xml\"\n },\n \"security_advisories\": {\n \"href\": \"https://github.com/security-advisories\",\n \"type\": \"application/atom+xml\"\n }\n }\n}\nhttps://api.github.com/rate_limit{\n \"resources\": {\n \"core\": {\n \"limit\": 60,\n \"remaining\": 56,\n \"reset\": 1567928119\n },\n \"search\": {\n \"limit\": 10,\n \"remaining\": 10,\n \"reset\": 1567924666\n },\n \"graphql\": {\n \"limit\": 0,\n \"remaining\": 0,\n \"reset\": 1567928206\n },\n \"integration_manifest\": {\n \"limit\": 5000,\n \"remaining\": 5000,\n \"reset\": 1567928206\n }\n },\n \"rate\": {\n \"limit\": 60,\n \"remaining\": 56,\n \"reset\": 1567928119\n }\n}\n" }, { "code": null, "e": 5415, "s": 4858, "text": "https://api.github.com/feedsOutput:{\n \"timeline_url\": \"https://github.com/timeline\",\n \"user_url\": \"https://github.com/{user}\",\n \"security_advisories_url\": \"https://github.com/security-advisories\",\n \"_links\": {\n \"timeline\": {\n \"href\": \"https://github.com/timeline\",\n \"type\": \"application/atom+xml\"\n },\n \"user\": {\n \"href\": \"https://github.com/{user}\",\n \"type\": \"application/atom+xml\"\n },\n \"security_advisories\": {\n \"href\": \"https://github.com/security-advisories\",\n \"type\": \"application/atom+xml\"\n }\n }\n}\n" }, { "code": null, "e": 5937, "s": 5415, "text": "{\n \"timeline_url\": \"https://github.com/timeline\",\n \"user_url\": \"https://github.com/{user}\",\n \"security_advisories_url\": \"https://github.com/security-advisories\",\n \"_links\": {\n \"timeline\": {\n \"href\": \"https://github.com/timeline\",\n \"type\": \"application/atom+xml\"\n },\n \"user\": {\n \"href\": \"https://github.com/{user}\",\n \"type\": \"application/atom+xml\"\n },\n \"security_advisories\": {\n \"href\": \"https://github.com/security-advisories\",\n \"type\": \"application/atom+xml\"\n }\n }\n}\n" }, { "code": null, "e": 6453, "s": 5937, "text": "https://api.github.com/rate_limit{\n \"resources\": {\n \"core\": {\n \"limit\": 60,\n \"remaining\": 56,\n \"reset\": 1567928119\n },\n \"search\": {\n \"limit\": 10,\n \"remaining\": 10,\n \"reset\": 1567924666\n },\n \"graphql\": {\n \"limit\": 0,\n \"remaining\": 0,\n \"reset\": 1567928206\n },\n \"integration_manifest\": {\n \"limit\": 5000,\n \"remaining\": 5000,\n \"reset\": 1567928206\n }\n },\n \"rate\": {\n \"limit\": 60,\n \"remaining\": 56,\n \"reset\": 1567928119\n }\n}\n" }, { "code": null, "e": 6936, "s": 6453, "text": "{\n \"resources\": {\n \"core\": {\n \"limit\": 60,\n \"remaining\": 56,\n \"reset\": 1567928119\n },\n \"search\": {\n \"limit\": 10,\n \"remaining\": 10,\n \"reset\": 1567924666\n },\n \"graphql\": {\n \"limit\": 0,\n \"remaining\": 0,\n \"reset\": 1567928206\n },\n \"integration_manifest\": {\n \"limit\": 5000,\n \"remaining\": 5000,\n \"reset\": 1567928206\n }\n },\n \"rate\": {\n \"limit\": 60,\n \"remaining\": 56,\n \"reset\": 1567928119\n }\n}\n" }, { "code": null, "e": 6943, "s": 6936, "text": "Picked" }, { "code": null, "e": 6951, "s": 6943, "text": "Web-API" }, { "code": null, "e": 6968, "s": 6951, "text": "Web Technologies" }, { "code": null, "e": 6995, "s": 6968, "text": "Web technologies Questions" } ]
Selecting Multiple Columns Based On Condition in SQL
30 Nov, 2021 In the real world scenario where we have to select the only columns from a given table, now that columns selected can be single or multiple as per requirement. For Example: Write a query that gave the names of EMPLOYEE in an organization, so here we have to pick out only the name column from that particular EMPLOYEE table. Similarly, another example of multiple columns can be: Write a query which gave the names and salary of all employees working in an organization. So here we have to select 2 columns of name and salary. The examples above make us understand that selection of columns is very important while learning SQL. First, we will learn how to select a single column from a table then we will move towards multiple columns. first, we create our database to execute the select queries Step 1: Creating the database Use the below SQL query to create a database called geeks: CREATE DATABASE geeks; Step 2: Using the database USE geeks; Step 3: Table Creation CREATE TABLE Employee ( EmpID int, FirstName varchar(255), LastName varchar(255), Salary INT ); Step 4: Adding data to the table INSERT INTO Employee VALUES(1, 'john' , 'ryther', 10000); INSERT INTO Employee VALUES(2, 'Alex' , 'Hamilton', 20000); INSERT INTO Employee VALUES(3, 'Sze' , 'Chauhan' , 10000); INSERT INTO Employee VALUES(4,'Shiv', 'Chauhan', 50000); Step 5: Now we see different cases in SQL to fetch desire output. Case 1: Selecting a single column in SQL In SQL, selecting any column is one of the easiest things as you have to type only the SELECT command and after that, the column name and the output will be the desired column. Syntax: SELECT (Column Name) FROM (Table Name); To make it more clear let’s take a general example of the EMPLOYEE table, which we have created above. Now, we have to select the column First_Name from the given table. Query: SELECT FirstName FROM EMPLOYEE; Output: Case 2: Selecting a single column based on conditions Now, we see how we have to fetch out the first name of those employees whose salary is 10,000. From the table, it is quite clear that our desired output should be: John and Sze. To solve such queries we have to simply put a WHERE clause in our code along with the condition, as shown in the below query: Query: SELECT FirstName FROM EMPLOYEE WHERE Salary=10000; Output: Case 3: Selecting multiple columns in SQL Selecting multiple columns in SQL with or without any condition is as simple as selecting a single column and not only simple but also the same as that. Taking our previous example further, this time we have to write a query to get a first name as well as last name from the employee table which means that we have to fetch 2 columns, the solution is very simple, we have to write all those columns names with SELECT clause which we want to fetch (In our case its first name and last name) and then table name. The syntax for which is shown below Syntax: SELECT column1,column2,column3... FROM table name; In our example, the code will be as follows Query: SELECT FirstName,LastName FROM Employee; Output: Case 4: Selecting multiple columns with conditions When we have to select multiple columns along with some condition, we put a WHERE clause and write our condition inside that clause. It is not mandatory to choose the WHERE clause there can be multiple options to put conditions depending on the query asked but most conditions are satisfied with the WHERE clause. As per the above example, this time we are going to put multiple conditions. For example: Write a query in SQL to select a first name and last name of an employee who has either salary of 10000 or has the last name of Chauhan. For this query, there are three things Selecting columns first name and last name i.e. SELECT First_Name, Last_Name. From the employee table i.e. FROM Employee Now, conditions are the tricky part as there are two conditions, let’s deal one by one Salary must be 10000 i.e. Salary=10000 the Last name should be Chauhan i.e. Last_name=’chauhan’ Salary must be 10000 i.e. Salary=10000 the Last name should be Chauhan i.e. Last_name=’chauhan’ And, hence our query has been solved, now we have to just put the above things in proper format as shown Query: SELECT FirstName, LastName FROM Employee WHERE Salary=10000 OR LastName='Chauhan'; Output: We can match from the table that the employees which have a salary of 10000 are john and sze and the employees who have the last name Chauhan are sze and shiv and that’s what our desired result is. Picked SQL-Query SQL-Server SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Update Multiple Columns in Single Update Statement in SQL? Window functions in SQL What is Temporary Table in SQL? SQL using Python SQL | Sub queries in From Clause SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter RANK() Function in SQL Server SQL Query to Convert VARCHAR to INT SQL Query to Compare Two Dates SQL Query to Insert Multiple Rows
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Nov, 2021" }, { "code": null, "e": 555, "s": 28, "text": "In the real world scenario where we have to select the only columns from a given table, now that columns selected can be single or multiple as per requirement. For Example: Write a query that gave the names of EMPLOYEE in an organization, so here we have to pick out only the name column from that particular EMPLOYEE table. Similarly, another example of multiple columns can be: Write a query which gave the names and salary of all employees working in an organization. So here we have to select 2 columns of name and salary." }, { "code": null, "e": 765, "s": 555, "text": "The examples above make us understand that selection of columns is very important while learning SQL. First, we will learn how to select a single column from a table then we will move towards multiple columns." }, { "code": null, "e": 825, "s": 765, "text": "first, we create our database to execute the select queries" }, { "code": null, "e": 855, "s": 825, "text": "Step 1: Creating the database" }, { "code": null, "e": 914, "s": 855, "text": "Use the below SQL query to create a database called geeks:" }, { "code": null, "e": 937, "s": 914, "text": "CREATE DATABASE geeks;" }, { "code": null, "e": 964, "s": 937, "text": "Step 2: Using the database" }, { "code": null, "e": 975, "s": 964, "text": "USE geeks;" }, { "code": null, "e": 998, "s": 975, "text": "Step 3: Table Creation" }, { "code": null, "e": 1106, "s": 998, "text": "CREATE TABLE Employee \n( \nEmpID int, \nFirstName varchar(255), \nLastName varchar(255), \nSalary INT \n);" }, { "code": null, "e": 1139, "s": 1106, "text": "Step 4: Adding data to the table" }, { "code": null, "e": 1373, "s": 1139, "text": "INSERT INTO Employee VALUES(1, 'john' , 'ryther', 10000);\nINSERT INTO Employee VALUES(2, 'Alex' , 'Hamilton', 20000);\nINSERT INTO Employee VALUES(3, 'Sze' , 'Chauhan' , 10000);\nINSERT INTO Employee VALUES(4,'Shiv', 'Chauhan', 50000);" }, { "code": null, "e": 1439, "s": 1373, "text": "Step 5: Now we see different cases in SQL to fetch desire output." }, { "code": null, "e": 1480, "s": 1439, "text": "Case 1: Selecting a single column in SQL" }, { "code": null, "e": 1657, "s": 1480, "text": "In SQL, selecting any column is one of the easiest things as you have to type only the SELECT command and after that, the column name and the output will be the desired column." }, { "code": null, "e": 1665, "s": 1657, "text": "Syntax:" }, { "code": null, "e": 1705, "s": 1665, "text": "SELECT (Column Name)\nFROM (Table Name);" }, { "code": null, "e": 1875, "s": 1705, "text": "To make it more clear let’s take a general example of the EMPLOYEE table, which we have created above. Now, we have to select the column First_Name from the given table." }, { "code": null, "e": 1882, "s": 1875, "text": "Query:" }, { "code": null, "e": 1914, "s": 1882, "text": "SELECT FirstName\nFROM EMPLOYEE;" }, { "code": null, "e": 1924, "s": 1914, "text": "Output: " }, { "code": null, "e": 1980, "s": 1924, "text": "Case 2: Selecting a single column based on conditions" }, { "code": null, "e": 2284, "s": 1980, "text": "Now, we see how we have to fetch out the first name of those employees whose salary is 10,000. From the table, it is quite clear that our desired output should be: John and Sze. To solve such queries we have to simply put a WHERE clause in our code along with the condition, as shown in the below query:" }, { "code": null, "e": 2291, "s": 2284, "text": "Query:" }, { "code": null, "e": 2342, "s": 2291, "text": "SELECT FirstName\nFROM EMPLOYEE\nWHERE Salary=10000;" }, { "code": null, "e": 2350, "s": 2342, "text": "Output:" }, { "code": null, "e": 2392, "s": 2350, "text": "Case 3: Selecting multiple columns in SQL" }, { "code": null, "e": 2939, "s": 2392, "text": "Selecting multiple columns in SQL with or without any condition is as simple as selecting a single column and not only simple but also the same as that. Taking our previous example further, this time we have to write a query to get a first name as well as last name from the employee table which means that we have to fetch 2 columns, the solution is very simple, we have to write all those columns names with SELECT clause which we want to fetch (In our case its first name and last name) and then table name. The syntax for which is shown below" }, { "code": null, "e": 2947, "s": 2939, "text": "Syntax:" }, { "code": null, "e": 2998, "s": 2947, "text": "SELECT column1,column2,column3...\nFROM table name;" }, { "code": null, "e": 3042, "s": 2998, "text": "In our example, the code will be as follows" }, { "code": null, "e": 3049, "s": 3042, "text": "Query:" }, { "code": null, "e": 3090, "s": 3049, "text": "SELECT FirstName,LastName\nFROM Employee;" }, { "code": null, "e": 3098, "s": 3090, "text": "Output:" }, { "code": null, "e": 3149, "s": 3098, "text": "Case 4: Selecting multiple columns with conditions" }, { "code": null, "e": 3540, "s": 3149, "text": "When we have to select multiple columns along with some condition, we put a WHERE clause and write our condition inside that clause. It is not mandatory to choose the WHERE clause there can be multiple options to put conditions depending on the query asked but most conditions are satisfied with the WHERE clause. As per the above example, this time we are going to put multiple conditions." }, { "code": null, "e": 3690, "s": 3540, "text": "For example: Write a query in SQL to select a first name and last name of an employee who has either salary of 10000 or has the last name of Chauhan." }, { "code": null, "e": 3729, "s": 3690, "text": "For this query, there are three things" }, { "code": null, "e": 3807, "s": 3729, "text": "Selecting columns first name and last name i.e. SELECT First_Name, Last_Name." }, { "code": null, "e": 3850, "s": 3807, "text": "From the employee table i.e. FROM Employee" }, { "code": null, "e": 4033, "s": 3850, "text": "Now, conditions are the tricky part as there are two conditions, let’s deal one by one Salary must be 10000 i.e. Salary=10000 the Last name should be Chauhan i.e. Last_name=’chauhan’" }, { "code": null, "e": 4073, "s": 4033, "text": " Salary must be 10000 i.e. Salary=10000" }, { "code": null, "e": 4131, "s": 4073, "text": " the Last name should be Chauhan i.e. Last_name=’chauhan’" }, { "code": null, "e": 4236, "s": 4131, "text": "And, hence our query has been solved, now we have to just put the above things in proper format as shown" }, { "code": null, "e": 4243, "s": 4236, "text": "Query:" }, { "code": null, "e": 4326, "s": 4243, "text": "SELECT FirstName, LastName\nFROM Employee\nWHERE Salary=10000 OR LastName='Chauhan';" }, { "code": null, "e": 4334, "s": 4326, "text": "Output:" }, { "code": null, "e": 4532, "s": 4334, "text": "We can match from the table that the employees which have a salary of 10000 are john and sze and the employees who have the last name Chauhan are sze and shiv and that’s what our desired result is." }, { "code": null, "e": 4539, "s": 4532, "text": "Picked" }, { "code": null, "e": 4549, "s": 4539, "text": "SQL-Query" }, { "code": null, "e": 4560, "s": 4549, "text": "SQL-Server" }, { "code": null, "e": 4564, "s": 4560, "text": "SQL" }, { "code": null, "e": 4568, "s": 4564, "text": "SQL" }, { "code": null, "e": 4666, "s": 4568, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4732, "s": 4666, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 4756, "s": 4732, "text": "Window functions in SQL" }, { "code": null, "e": 4788, "s": 4756, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 4805, "s": 4788, "text": "SQL using Python" }, { "code": null, "e": 4838, "s": 4805, "text": "SQL | Sub queries in From Clause" }, { "code": null, "e": 4916, "s": 4838, "text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter" }, { "code": null, "e": 4946, "s": 4916, "text": "RANK() Function in SQL Server" }, { "code": null, "e": 4982, "s": 4946, "text": "SQL Query to Convert VARCHAR to INT" }, { "code": null, "e": 5013, "s": 4982, "text": "SQL Query to Compare Two Dates" } ]
PHP | Magic Constants
17 Aug, 2021 Magic constants: Magic constants are the predefined constants in PHP which is used on the basis of their use. These constants are created by various extensions. There are nine magic constant in the PHP and all of the constant resolved at the compile-time, not like the regular constant which is resolved at run time. There are eight magic constants that start and end with double underscores (__). All the constants are listed below with the example code: 1. __line__: This magic constant return the current line number of the file. If you use this magic constant in your program file somewhere then this constant will display the line number during compile time. Syntax: .__line__ Example: PHP <?php echo "The Line number is : ". __line__; ?> Output: The Line number is : 3 2. __file__: This magic constant return the full path of the executed file with the name of the file. Syntax: .__file__ Example: PHP <?php echo "The file name is : ". __file__; ?> Output: The file name is : /home/3d27a639c57aaed9efa5880e613bc273.php 3. __dir__: This magic constant return the directory of the executed file. Syntax: .__dir__ Example: PHP <?php echo "The directory is : ". __dir__; ?> Output: The directory is : /home 4. __function__: This magic constant return the name of the function where this magic constant is included. Syntax: .__function__ Example: PHP <?phpfunction Geeks(){ echo "The function name is : ". __function__;}Geeks();?> Output: The function name is : Geeks 5. __class__: This magic constant return the name of the class where this magic constant is included. Syntax: __class__ Example: PHP <?phpclass Geeks{ public function getClassName(){ return __class__; }}$obj = new Geeks();echo $obj->getClassName();?> Output: Geeks 6. __method__: This magic constant return the method name where this magic constant is included. Syntax: __method__ Example: PHP <?phpclass Company{ public function GeeksforGeeks(){ return __method__; }}$obj = new Company();echo $obj->GeeksforGeeks();?> Output: Company::GeeksforGeeks 7. __namespace__: This magic constant return the current namespace where this magic constant is included. Syntax: __namespace__ Example: PHP <?phpnamespace GeeksforGeeks; class Company { public function gfg() { return __namespace__; }} $obj = new Company();echo $obj->gfg(); ?> Output: GeeksforGeeks 8. __trait__: This magic constant return the trait name where this magic constant is included. Syntax: __trait__ Example: PHP <?phptrait GeeksforGeeks{ function gfg(){ echo __trait__; } } class Company{ use GeeksforGeeks; } $a = new Company; $a->gfg(); ?> Output: GeeksforGeeks 9. ClassName::class: This magic constant return the fully qualified class name. Syntax: ClassName::class Example: PHP <?php namespace Computer_Sciecnec_Portal;class Geeks{ } echo Geeks::class;//Classname::class ?> Output: Computer_Sciecnec_Portal\Geeks Reference: https://www.php.net/manual/en/language.constants.predefined.php simmytarika5 Picked PHP PHP Programs Technical Scripter Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to execute PHP code using command line ? How to delete an array element based on key in PHP? PHP in_array() Function How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? How to execute PHP code using command line ? How to delete an array element based on key in PHP? How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? How to pop an alert message box using PHP ?
[ { "code": null, "e": 28, "s": 0, "text": "\n17 Aug, 2021" }, { "code": null, "e": 485, "s": 28, "text": "Magic constants: Magic constants are the predefined constants in PHP which is used on the basis of their use. These constants are created by various extensions. There are nine magic constant in the PHP and all of the constant resolved at the compile-time, not like the regular constant which is resolved at run time. There are eight magic constants that start and end with double underscores (__). All the constants are listed below with the example code: " }, { "code": null, "e": 693, "s": 485, "text": "1. __line__: This magic constant return the current line number of the file. If you use this magic constant in your program file somewhere then this constant will display the line number during compile time." }, { "code": null, "e": 702, "s": 693, "text": "Syntax: " }, { "code": null, "e": 712, "s": 702, "text": ".__line__" }, { "code": null, "e": 722, "s": 712, "text": "Example: " }, { "code": null, "e": 726, "s": 722, "text": "PHP" }, { "code": "<?php echo \"The Line number is : \". __line__; ?>", "e": 777, "s": 726, "text": null }, { "code": null, "e": 786, "s": 777, "text": "Output: " }, { "code": null, "e": 809, "s": 786, "text": "The Line number is : 3" }, { "code": null, "e": 911, "s": 809, "text": "2. __file__: This magic constant return the full path of the executed file with the name of the file." }, { "code": null, "e": 920, "s": 911, "text": "Syntax: " }, { "code": null, "e": 930, "s": 920, "text": ".__file__" }, { "code": null, "e": 940, "s": 930, "text": "Example: " }, { "code": null, "e": 944, "s": 940, "text": "PHP" }, { "code": "<?php echo \"The file name is : \". __file__; ?>", "e": 993, "s": 944, "text": null }, { "code": null, "e": 1002, "s": 993, "text": "Output: " }, { "code": null, "e": 1064, "s": 1002, "text": "The file name is : /home/3d27a639c57aaed9efa5880e613bc273.php" }, { "code": null, "e": 1139, "s": 1064, "text": "3. __dir__: This magic constant return the directory of the executed file." }, { "code": null, "e": 1148, "s": 1139, "text": "Syntax: " }, { "code": null, "e": 1157, "s": 1148, "text": ".__dir__" }, { "code": null, "e": 1167, "s": 1157, "text": "Example: " }, { "code": null, "e": 1171, "s": 1167, "text": "PHP" }, { "code": "<?php echo \"The directory is : \". __dir__; ?>", "e": 1219, "s": 1171, "text": null }, { "code": null, "e": 1228, "s": 1219, "text": "Output: " }, { "code": null, "e": 1253, "s": 1228, "text": "The directory is : /home" }, { "code": null, "e": 1361, "s": 1253, "text": "4. __function__: This magic constant return the name of the function where this magic constant is included." }, { "code": null, "e": 1370, "s": 1361, "text": "Syntax: " }, { "code": null, "e": 1384, "s": 1370, "text": ".__function__" }, { "code": null, "e": 1394, "s": 1384, "text": "Example: " }, { "code": null, "e": 1398, "s": 1394, "text": "PHP" }, { "code": "<?phpfunction Geeks(){ echo \"The function name is : \". __function__;}Geeks();?>", "e": 1481, "s": 1398, "text": null }, { "code": null, "e": 1490, "s": 1481, "text": "Output: " }, { "code": null, "e": 1519, "s": 1490, "text": "The function name is : Geeks" }, { "code": null, "e": 1621, "s": 1519, "text": "5. __class__: This magic constant return the name of the class where this magic constant is included." }, { "code": null, "e": 1630, "s": 1621, "text": "Syntax: " }, { "code": null, "e": 1640, "s": 1630, "text": "__class__" }, { "code": null, "e": 1650, "s": 1640, "text": "Example: " }, { "code": null, "e": 1654, "s": 1650, "text": "PHP" }, { "code": "<?phpclass Geeks{ public function getClassName(){ return __class__; }}$obj = new Geeks();echo $obj->getClassName();?>", "e": 1785, "s": 1654, "text": null }, { "code": null, "e": 1794, "s": 1785, "text": "Output: " }, { "code": null, "e": 1801, "s": 1794, "text": "Geeks " }, { "code": null, "e": 1898, "s": 1801, "text": "6. __method__: This magic constant return the method name where this magic constant is included." }, { "code": null, "e": 1907, "s": 1898, "text": "Syntax: " }, { "code": null, "e": 1918, "s": 1907, "text": "__method__" }, { "code": null, "e": 1928, "s": 1918, "text": "Example: " }, { "code": null, "e": 1932, "s": 1928, "text": "PHP" }, { "code": "<?phpclass Company{ public function GeeksforGeeks(){ return __method__; }}$obj = new Company();echo $obj->GeeksforGeeks();?>", "e": 2071, "s": 1932, "text": null }, { "code": null, "e": 2080, "s": 2071, "text": "Output: " }, { "code": null, "e": 2104, "s": 2080, "text": "Company::GeeksforGeeks " }, { "code": null, "e": 2210, "s": 2104, "text": "7. __namespace__: This magic constant return the current namespace where this magic constant is included." }, { "code": null, "e": 2219, "s": 2210, "text": "Syntax: " }, { "code": null, "e": 2233, "s": 2219, "text": "__namespace__" }, { "code": null, "e": 2243, "s": 2233, "text": "Example: " }, { "code": null, "e": 2247, "s": 2243, "text": "PHP" }, { "code": "<?phpnamespace GeeksforGeeks; class Company { public function gfg() { return __namespace__; }} $obj = new Company();echo $obj->gfg(); ?>", "e": 2398, "s": 2247, "text": null }, { "code": null, "e": 2407, "s": 2398, "text": "Output: " }, { "code": null, "e": 2421, "s": 2407, "text": "GeeksforGeeks" }, { "code": null, "e": 2516, "s": 2421, "text": "8. __trait__: This magic constant return the trait name where this magic constant is included." }, { "code": null, "e": 2525, "s": 2516, "text": "Syntax: " }, { "code": null, "e": 2535, "s": 2525, "text": "__trait__" }, { "code": null, "e": 2545, "s": 2535, "text": "Example: " }, { "code": null, "e": 2549, "s": 2545, "text": "PHP" }, { "code": "<?phptrait GeeksforGeeks{ function gfg(){ echo __trait__; } } class Company{ use GeeksforGeeks; } $a = new Company; $a->gfg(); ?>", "e": 2731, "s": 2549, "text": null }, { "code": null, "e": 2740, "s": 2731, "text": "Output: " }, { "code": null, "e": 2755, "s": 2740, "text": "GeeksforGeeks " }, { "code": null, "e": 2835, "s": 2755, "text": "9. ClassName::class: This magic constant return the fully qualified class name." }, { "code": null, "e": 2844, "s": 2835, "text": "Syntax: " }, { "code": null, "e": 2861, "s": 2844, "text": "ClassName::class" }, { "code": null, "e": 2871, "s": 2861, "text": "Example: " }, { "code": null, "e": 2875, "s": 2871, "text": "PHP" }, { "code": "<?php namespace Computer_Sciecnec_Portal;class Geeks{ } echo Geeks::class;//Classname::class ?>", "e": 2971, "s": 2875, "text": null }, { "code": null, "e": 2980, "s": 2971, "text": "Output: " }, { "code": null, "e": 3012, "s": 2980, "text": "Computer_Sciecnec_Portal\\Geeks " }, { "code": null, "e": 3088, "s": 3012, "text": "Reference: https://www.php.net/manual/en/language.constants.predefined.php " }, { "code": null, "e": 3101, "s": 3088, "text": "simmytarika5" }, { "code": null, "e": 3108, "s": 3101, "text": "Picked" }, { "code": null, "e": 3112, "s": 3108, "text": "PHP" }, { "code": null, "e": 3125, "s": 3112, "text": "PHP Programs" }, { "code": null, "e": 3144, "s": 3125, "text": "Technical Scripter" }, { "code": null, "e": 3161, "s": 3144, "text": "Web Technologies" }, { "code": null, "e": 3165, "s": 3161, "text": "PHP" }, { "code": null, "e": 3263, "s": 3165, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3308, "s": 3263, "text": "How to execute PHP code using command line ?" }, { "code": null, "e": 3360, "s": 3308, "text": "How to delete an array element based on key in PHP?" }, { "code": null, "e": 3384, "s": 3360, "text": "PHP in_array() Function" }, { "code": null, "e": 3434, "s": 3384, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 3474, "s": 3434, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 3519, "s": 3474, "text": "How to execute PHP code using command line ?" }, { "code": null, "e": 3571, "s": 3519, "text": "How to delete an array element based on key in PHP?" }, { "code": null, "e": 3621, "s": 3571, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 3661, "s": 3621, "text": "How to convert array to string in PHP ?" } ]
NPDA for accepting the language L = {aibjckdl | i==k or j==l,i>=1,j>=1}
28 Aug, 2019 Prerequisite – Pushdown automata, Pushdown automata acceptance by final stateProblem – Design a non deterministic PDA for accepting the language L = { : i==k or j==l, i>=1, j>=1}, i.e., L = {abcd, aabccd, aaabcccd, abbcdd, aabbccdd, aabbbccddd, ......} In each string, the number of a’s are followed by any number of b’s and b’s are followed by the number of c’s equal to the number of a’s and c’s are followed by number of d’s equal number of b’s. Explanation –Here, we need to maintain the order of a’s, b’s, c’s and d’s.That is, all the a’s are coming first then all the b’s are coming and then all the c’s are coming then all the d’s are coming . Thus, we need a stack along with the state diagram. The count of a’s and b’s is maintained by the stack.We will take 2 stack alphabets: = { a, b, c, d, z } Where, = set of all the stack alphabetz = stack start symbol Approach used in the construction of PDA –In designing a NPDA, for every a’, ‘b’, ‘c’ and ‘d’ will comes in proper order. For i==k : Whenever ‘a’ comes, push it in stack and if ‘a’ comes again then also push it in the stack.After that, if ‘b’ comes not do any operation. After that, when ‘c’ comes then pop ‘a’ from the stack each time.After that, if ‘d’ comes not do any operation. For j==l : Whenever ‘a’ comes, not do any operation.After that, if ‘b’ comes push it in stack and if ‘b’ comes again then also push it in the stack. After that, when ‘c’ comes not do any operation.After that, if ‘d’ comes then pop ‘b’ from the stack each time. So that the stack becomes empty.If stack is empty then we can say that the string is accepted by the PDA. Stack transition functions – (q0, a, z) (q1, az) (q0, a, z) (q3, z) (q1, a, a) (q1, aa) (q1, b, a) (q1, a) (q1, c, a) (q2, ) (q2, c, a) (q2, ) (q2, d, ) (q2, ) (q2, , z) (qf1, z) (q3 a, z) (q3, z) (q3 b, z) (q3, bz) (q3 b, b) (q3, bb) (q3 c, b) (q3, b) (q3, d, b) (q4, ) (q4, d, b) (q4, ) (q4, , z) (qf2, z) Where, q0 = Initial stateqf1, qf2 = Final state = indicates pop operation So, this is our required non deterministic PDA for accepting the language L ={ : i==k or j==l, i>=1, j>=1}. nidhi_biet GATE CS Theory of Computation & Automata Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between Clustered and Non-clustered index Introduction of Process Synchronization Three address code in Compiler Differences between IPv4 and IPv6 Phases of a Compiler Introduction of Finite Automata Difference between DFA and NFA Turing Machine in TOC Chomsky Hierarchy in Theory of Computation Boyer-Moore Majority Voting Algorithm
[ { "code": null, "e": 54, "s": 26, "text": "\n28 Aug, 2019" }, { "code": null, "e": 243, "s": 54, "text": "Prerequisite – Pushdown automata, Pushdown automata acceptance by final stateProblem – Design a non deterministic PDA for accepting the language L = { : i==k or j==l, i>=1, j>=1}, i.e.," }, { "code": null, "e": 311, "s": 243, "text": "L = {abcd, aabccd, aaabcccd, abbcdd, aabbccdd, aabbbccddd, ......} " }, { "code": null, "e": 507, "s": 311, "text": "In each string, the number of a’s are followed by any number of b’s and b’s are followed by the number of c’s equal to the number of a’s and c’s are followed by number of d’s equal number of b’s." }, { "code": null, "e": 845, "s": 507, "text": "Explanation –Here, we need to maintain the order of a’s, b’s, c’s and d’s.That is, all the a’s are coming first then all the b’s are coming and then all the c’s are coming then all the d’s are coming . Thus, we need a stack along with the state diagram. The count of a’s and b’s is maintained by the stack.We will take 2 stack alphabets:" }, { "code": null, "e": 867, "s": 845, "text": " = { a, b, c, d, z } " }, { "code": null, "e": 928, "s": 867, "text": "Where, = set of all the stack alphabetz = stack start symbol" }, { "code": null, "e": 1050, "s": 928, "text": "Approach used in the construction of PDA –In designing a NPDA, for every a’, ‘b’, ‘c’ and ‘d’ will comes in proper order." }, { "code": null, "e": 1311, "s": 1050, "text": "For i==k : Whenever ‘a’ comes, push it in stack and if ‘a’ comes again then also push it in the stack.After that, if ‘b’ comes not do any operation. After that, when ‘c’ comes then pop ‘a’ from the stack each time.After that, if ‘d’ comes not do any operation." }, { "code": null, "e": 1572, "s": 1311, "text": "For j==l : Whenever ‘a’ comes, not do any operation.After that, if ‘b’ comes push it in stack and if ‘b’ comes again then also push it in the stack. After that, when ‘c’ comes not do any operation.After that, if ‘d’ comes then pop ‘b’ from the stack each time." }, { "code": null, "e": 1678, "s": 1572, "text": "So that the stack becomes empty.If stack is empty then we can say that the string is accepted by the PDA." }, { "code": null, "e": 1707, "s": 1678, "text": "Stack transition functions –" }, { "code": null, "e": 2014, "s": 1707, "text": "(q0, a, z) (q1, az)\n(q0, a, z) (q3, z)\n(q1, a, a) (q1, aa)\n(q1, b, a) (q1, a)\n(q1, c, a) (q2, ) \n(q2, c, a) (q2, ) \n(q2, d, ) (q2, ) \n(q2, , z) (qf1, z) \n(q3 a, z) (q3, z)\n(q3 b, z) (q3, bz)\n(q3 b, b) (q3, bb)\n(q3 c, b) (q3, b)\n(q3, d, b) (q4, ) \n(q4, d, b) (q4, ) \n(q4, , z) (qf2, z) \n" }, { "code": null, "e": 2088, "s": 2014, "text": "Where, q0 = Initial stateqf1, qf2 = Final state = indicates pop operation" }, { "code": null, "e": 2199, "s": 2088, "text": "So, this is our required non deterministic PDA for accepting the language L ={ : i==k or j==l, i>=1, j>=1}." }, { "code": null, "e": 2210, "s": 2199, "text": "nidhi_biet" }, { "code": null, "e": 2218, "s": 2210, "text": "GATE CS" }, { "code": null, "e": 2251, "s": 2218, "text": "Theory of Computation & Automata" }, { "code": null, "e": 2349, "s": 2251, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2402, "s": 2349, "text": "Difference between Clustered and Non-clustered index" }, { "code": null, "e": 2442, "s": 2402, "text": "Introduction of Process Synchronization" }, { "code": null, "e": 2473, "s": 2442, "text": "Three address code in Compiler" }, { "code": null, "e": 2507, "s": 2473, "text": "Differences between IPv4 and IPv6" }, { "code": null, "e": 2528, "s": 2507, "text": "Phases of a Compiler" }, { "code": null, "e": 2560, "s": 2528, "text": "Introduction of Finite Automata" }, { "code": null, "e": 2591, "s": 2560, "text": "Difference between DFA and NFA" }, { "code": null, "e": 2613, "s": 2591, "text": "Turing Machine in TOC" }, { "code": null, "e": 2656, "s": 2613, "text": "Chomsky Hierarchy in Theory of Computation" } ]
Java Program For Inserting A Node In A Linked List
22 Dec, 2021 We have introduced Linked Lists in the previous post. We also created a simple linked list with 3 nodes and discussed linked list traversal.All programs discussed in this post consider the following representations of the linked list. Java // Linked List Classclass LinkedList{ // Head of list Node head; // Node Class class Node { int data; Node next; // Constructor to create // a new node Node(int d) { data = d; next = null; } }} In this post, methods to insert a new node in linked list are discussed. A node can be added in three ways 1) At the front of the linked list 2) After a given node. 3) At the end of the linked list. Add a node at the front: (4 steps process) The new node is always added before the head of the given Linked List. And newly added node becomes the new head of the Linked List. For example, if the given Linked List is 10->15->20->25 and we add an item 5 at the front, then the Linked List becomes 5->10->15->20->25. Let us call the function that adds at the front of the list is push(). The push() must receive a pointer to the head pointer, because push must change the head pointer to point to the new node (See this) Following are the 4 steps to add a node at the front. Java /* This function is in LinkedList class. Inserts a new Node at front of the list. This method is defined inside LinkedList class shown above */public void push(int new_data){ /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); // 3. Make next of new Node as head new_node.next = head; // 4. Move the head to point to // new Node head = new_node;} Time complexity of push() is O(1) as it does a constant amount of work.Add a node after a given node: (5 steps process) We are given a pointer to a node, and the new node is inserted after the given node. Java /* This function is in LinkedList class. Inserts a new node after the given prev_node. This method is defined inside LinkedList class shown above */public void insertAfter(Node prev_node, int new_data) { // 1. Check if the given Node is null if (prev_node == null) { System.out.println( "The given previous node cannot be null"); return; } /* 2. Allocate the Node & 3. Put in the data*/ Node new_node = new Node(new_data); // 4. Make next of new Node as next // of prev_node new_node.next = prev_node.next; // 5. make next of prev_node as new_node prev_node.next = new_node; } Time complexity of insertAfter() is O(1) as it does a constant amount of work. Add a node at the end: (6 steps process) The new node is always added after the last node of the given Linked List. For example if the given Linked List is 5->10->15->20->25 and we add an item 30 at the end, then the Linked List becomes 5->10->15->20->25->30. Since a Linked List is typically represented by the head of it, we have to traverse the list till the end and then change the next to last node to a new node. Following are the 6 steps to add node at the end. Java /* Appends a new node at the end. This method is defined inside LinkedList class shown above */public void append(int new_data){ /* 1. Allocate the Node & 2. Put in the data 3. Set next as null */ Node new_node = new Node(new_data); /* 4. If the Linked List is empty, then make the new node as head */ if (head == null) { head = new Node(new_data); return; } /* 4. This new node is going to be the last node, so make next of it as null */ new_node.next = null; // 5. Else traverse till the last node Node last = head; while (last.next != null) last = last.next; // 6. Change the next of last node last.next = new_node; return;} Time complexity of append is O(n) where n is the number of nodes in the linked list. Since there is a loop from head to end, the function does O(n) work. This method can also be optimized to work in O(1) by keeping an extra pointer to the tail of the linked list/ Following is a complete program that uses all of the above methods to create a linked list. Java // A complete working Java program to // demonstrate all insertion methods// on linked listclass LinkedList{ // head of list Node head; // Linked list Node class Node { int data; Node next; Node(int d) { data = d; next = null; } } // Inserts a new Node at front // of the list. public void push(int new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); // 3. Make next of new Node as head new_node.next = head; // 4. Move the head to point to // new Node head = new_node; } // Inserts a new node after the // given prev_node. public void insertAfter(Node prev_node, int new_data) { // 1. Check if the given Node is null if (prev_node == null) { System.out.println( "The given previous node cannot be null"); return; } /* 2 & 3: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); // 4. Make next of new Node as next // of prev_node new_node.next = prev_node.next; // 5. make next of prev_node as // new_node prev_node.next = new_node; } /* Appends a new node at the end. This method is defined inside LinkedList class shown above */ public void append(int new_data) { /* 1. Allocate the Node & 2. Put in the data 3. Set next as null */ Node new_node = new Node(new_data); /* 4. If the Linked List is empty, then make the new node as head */ if (head == null) { head = new Node(new_data); return; } /* 4. This new node is going to be the last node, so make next of it as null */ new_node.next = null; // 5. Else traverse till the last node Node last = head; while (last.next != null) last = last.next; // 6. Change the next of last node last.next = new_node; return; } /* This function prints contents of linked list starting from the given node */ public void printList() { Node tnode = head; while (tnode != null) { System.out.print(tnode.data + " "); tnode = tnode.next; } } // Driver code public static void main(String[] args) { // Start with the empty list LinkedList llist = new LinkedList(); // Insert 6. So linked list // becomes 6->NUllist llist.append(6); // Insert 7 at the beginning. // So linked list becomes // 7->6->NUllist llist.push(7); // Insert 1 at the beginning. // So linked list becomes // 1->7->6->NUllist llist.push(1); // Insert 4 at the end. // So linked list becomes // 1->7->6->4->NUllist llist.append(4); // Insert 8, after 7. So linked // list becomes // 1->7->8->6->4->NUllist llist.insertAfter(llist.head.next, 8); System.out.println( "Created Linked list is: "); llist.printList(); }}// This code is contributed by Rajat Mishra Output: Created Linked list is: 1 7 8 6 4 Please refer complete article on Linked List | Set 2 (Inserting a node) for more details! Linked Lists TCS Wipro Java Java Programs Linked List Wipro TCS Linked List Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Introduction to Java Constructors in Java Exceptions in Java Generics in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class Factory method design pattern in Java Java Program to Remove Duplicate Elements From the Array
[ { "code": null, "e": 52, "s": 24, "text": "\n22 Dec, 2021" }, { "code": null, "e": 288, "s": 52, "text": "We have introduced Linked Lists in the previous post. We also created a simple linked list with 3 nodes and discussed linked list traversal.All programs discussed in this post consider the following representations of the linked list. " }, { "code": null, "e": 293, "s": 288, "text": "Java" }, { "code": "// Linked List Classclass LinkedList{ // Head of list Node head; // Node Class class Node { int data; Node next; // Constructor to create // a new node Node(int d) { data = d; next = null; } }}", "e": 595, "s": 293, "text": null }, { "code": null, "e": 794, "s": 595, "text": "In this post, methods to insert a new node in linked list are discussed. A node can be added in three ways 1) At the front of the linked list 2) After a given node. 3) At the end of the linked list." }, { "code": null, "e": 1313, "s": 794, "text": "Add a node at the front: (4 steps process) The new node is always added before the head of the given Linked List. And newly added node becomes the new head of the Linked List. For example, if the given Linked List is 10->15->20->25 and we add an item 5 at the front, then the Linked List becomes 5->10->15->20->25. Let us call the function that adds at the front of the list is push(). The push() must receive a pointer to the head pointer, because push must change the head pointer to point to the new node (See this)" }, { "code": null, "e": 1367, "s": 1313, "text": "Following are the 4 steps to add a node at the front." }, { "code": null, "e": 1372, "s": 1367, "text": "Java" }, { "code": "/* This function is in LinkedList class. Inserts a new Node at front of the list. This method is defined inside LinkedList class shown above */public void push(int new_data){ /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); // 3. Make next of new Node as head new_node.next = head; // 4. Move the head to point to // new Node head = new_node;}", "e": 1797, "s": 1372, "text": null }, { "code": null, "e": 2002, "s": 1797, "text": "Time complexity of push() is O(1) as it does a constant amount of work.Add a node after a given node: (5 steps process) We are given a pointer to a node, and the new node is inserted after the given node." }, { "code": null, "e": 2007, "s": 2002, "text": "Java" }, { "code": "/* This function is in LinkedList class. Inserts a new node after the given prev_node. This method is defined inside LinkedList class shown above */public void insertAfter(Node prev_node, int new_data) { // 1. Check if the given Node is null if (prev_node == null) { System.out.println( \"The given previous node cannot be null\"); return; } /* 2. Allocate the Node & 3. Put in the data*/ Node new_node = new Node(new_data); // 4. Make next of new Node as next // of prev_node new_node.next = prev_node.next; // 5. make next of prev_node as new_node prev_node.next = new_node; }", "e": 2702, "s": 2007, "text": null }, { "code": null, "e": 2781, "s": 2702, "text": "Time complexity of insertAfter() is O(1) as it does a constant amount of work." }, { "code": null, "e": 3200, "s": 2781, "text": "Add a node at the end: (6 steps process) The new node is always added after the last node of the given Linked List. For example if the given Linked List is 5->10->15->20->25 and we add an item 30 at the end, then the Linked List becomes 5->10->15->20->25->30. Since a Linked List is typically represented by the head of it, we have to traverse the list till the end and then change the next to last node to a new node." }, { "code": null, "e": 3250, "s": 3200, "text": "Following are the 6 steps to add node at the end." }, { "code": null, "e": 3255, "s": 3250, "text": "Java" }, { "code": "/* Appends a new node at the end. This method is defined inside LinkedList class shown above */public void append(int new_data){ /* 1. Allocate the Node & 2. Put in the data 3. Set next as null */ Node new_node = new Node(new_data); /* 4. If the Linked List is empty, then make the new node as head */ if (head == null) { head = new Node(new_data); return; } /* 4. This new node is going to be the last node, so make next of it as null */ new_node.next = null; // 5. Else traverse till the last node Node last = head; while (last.next != null) last = last.next; // 6. Change the next of last node last.next = new_node; return;}", "e": 4003, "s": 3255, "text": null }, { "code": null, "e": 4267, "s": 4003, "text": "Time complexity of append is O(n) where n is the number of nodes in the linked list. Since there is a loop from head to end, the function does O(n) work. This method can also be optimized to work in O(1) by keeping an extra pointer to the tail of the linked list/" }, { "code": null, "e": 4359, "s": 4267, "text": "Following is a complete program that uses all of the above methods to create a linked list." }, { "code": null, "e": 4364, "s": 4359, "text": "Java" }, { "code": "// A complete working Java program to // demonstrate all insertion methods// on linked listclass LinkedList{ // head of list Node head; // Linked list Node class Node { int data; Node next; Node(int d) { data = d; next = null; } } // Inserts a new Node at front // of the list. public void push(int new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); // 3. Make next of new Node as head new_node.next = head; // 4. Move the head to point to // new Node head = new_node; } // Inserts a new node after the // given prev_node. public void insertAfter(Node prev_node, int new_data) { // 1. Check if the given Node is null if (prev_node == null) { System.out.println( \"The given previous node cannot be null\"); return; } /* 2 & 3: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); // 4. Make next of new Node as next // of prev_node new_node.next = prev_node.next; // 5. make next of prev_node as // new_node prev_node.next = new_node; } /* Appends a new node at the end. This method is defined inside LinkedList class shown above */ public void append(int new_data) { /* 1. Allocate the Node & 2. Put in the data 3. Set next as null */ Node new_node = new Node(new_data); /* 4. If the Linked List is empty, then make the new node as head */ if (head == null) { head = new Node(new_data); return; } /* 4. This new node is going to be the last node, so make next of it as null */ new_node.next = null; // 5. Else traverse till the last node Node last = head; while (last.next != null) last = last.next; // 6. Change the next of last node last.next = new_node; return; } /* This function prints contents of linked list starting from the given node */ public void printList() { Node tnode = head; while (tnode != null) { System.out.print(tnode.data + \" \"); tnode = tnode.next; } } // Driver code public static void main(String[] args) { // Start with the empty list LinkedList llist = new LinkedList(); // Insert 6. So linked list // becomes 6->NUllist llist.append(6); // Insert 7 at the beginning. // So linked list becomes // 7->6->NUllist llist.push(7); // Insert 1 at the beginning. // So linked list becomes // 1->7->6->NUllist llist.push(1); // Insert 4 at the end. // So linked list becomes // 1->7->6->4->NUllist llist.append(4); // Insert 8, after 7. So linked // list becomes // 1->7->8->6->4->NUllist llist.insertAfter(llist.head.next, 8); System.out.println( \"Created Linked list is: \"); llist.printList(); }}// This code is contributed by Rajat Mishra", "e": 7783, "s": 4364, "text": null }, { "code": null, "e": 7791, "s": 7783, "text": "Output:" }, { "code": null, "e": 7831, "s": 7791, "text": " Created Linked list is: 1 7 8 6 4" }, { "code": null, "e": 7921, "s": 7831, "text": "Please refer complete article on Linked List | Set 2 (Inserting a node) for more details!" }, { "code": null, "e": 7934, "s": 7921, "text": "Linked Lists" }, { "code": null, "e": 7938, "s": 7934, "text": "TCS" }, { "code": null, "e": 7944, "s": 7938, "text": "Wipro" }, { "code": null, "e": 7949, "s": 7944, "text": "Java" }, { "code": null, "e": 7963, "s": 7949, "text": "Java Programs" }, { "code": null, "e": 7975, "s": 7963, "text": "Linked List" }, { "code": null, "e": 7981, "s": 7975, "text": "Wipro" }, { "code": null, "e": 7985, "s": 7981, "text": "TCS" }, { "code": null, "e": 7997, "s": 7985, "text": "Linked List" }, { "code": null, "e": 8002, "s": 7997, "text": "Java" }, { "code": null, "e": 8100, "s": 8002, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8115, "s": 8100, "text": "Stream In Java" }, { "code": null, "e": 8136, "s": 8115, "text": "Introduction to Java" }, { "code": null, "e": 8157, "s": 8136, "text": "Constructors in Java" }, { "code": null, "e": 8176, "s": 8157, "text": "Exceptions in Java" }, { "code": null, "e": 8193, "s": 8176, "text": "Generics in Java" }, { "code": null, "e": 8219, "s": 8193, "text": "Java Programming Examples" }, { "code": null, "e": 8253, "s": 8219, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 8300, "s": 8253, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 8338, "s": 8300, "text": "Factory method design pattern in Java" } ]
What is Memory-Mapped File in Java?
06 Apr, 2022 Memory-mapped files are casual special files in Java that help to access content directly from memory. Java Programming supports memory-mapped files with java.nio package. Memory-mapped I/O uses the filesystem to establish a virtual memory mapping from the user directly to the filesystem pages. It can be simply treated as a large array. Memory used to load Memory-mapped files is outside of Java Heap Space. Here we use the MappedByteBuffer to read and write from memory. This utility can be used to create and store efficient memory-mapped files. Some major important features about MappedByteBuffer is as follows: MappedByteBuffer and file mapping remain valid until the garbage is collected. sun.misc.Cleaner is probably the only option available to clear memory-mapped files.Reading and writing in the memory-mapped file is generally done by the operating system to write content into a disk.Prefer Direct buffer to Indirect Buffer for better performance.Memory used to load File is outside Java heap and reside on shared memory which allows us to two different ways to access the file. By the way, this depends upon, whether you are using the direct or indirect buffer. MappedByteBuffer and file mapping remain valid until the garbage is collected. sun.misc.Cleaner is probably the only option available to clear memory-mapped files. Reading and writing in the memory-mapped file is generally done by the operating system to write content into a disk. Prefer Direct buffer to Indirect Buffer for better performance. Memory used to load File is outside Java heap and reside on shared memory which allows us to two different ways to access the file. By the way, this depends upon, whether you are using the direct or indirect buffer. Let us do rollover through and implementing the same before concluding out merits and demerits of memory-mapped file Example: Java // Java Program to illustrate Memory Mapped File via// RandomAccessFile to open a file using FileChannel's map()// method // Importing standard classes from respective packagesimport java.io.*;import java.io.RandomAccessFile;import java.nio.MappedByteBuffer;import java.nio.channels.FileChannel;import java.util.Scanner; // Main classpublic class GFG { // The next line shows 10 MB as the max value of the // count private static int count = 10485760; // Main driver method public static void main(String[] args) throws Exception { // Display message asking user to enter the input // string System.out.print("enter character or string"); // The method RandomAccessFile has an object sc and // is used to create a text file // Try block to check for exceptions try (RandomAccessFile sc = new RandomAccessFile("text.txt", "rw")) { // Scanner class to take objects input // Taking String a as input Scanner s = new Scanner(System.in); String a; a = s.next(); // Mapping the file with the memory // Here the out is the object // This command will help us enable the read and // write functions MappedByteBuffer out = sc.getChannel().map( FileChannel.MapMode.READ_WRITE, 0, 10); // Writing into memory mapped file // taking it as 10 and printing it accordingly for (int i = 0; i < 10; i++) { System.out.println((out.put((byte)i))); } // Print the display message as soon // as the memory is done writing System.out.println( "Writing to Memory is complete"); // Reading from memory mapped files // You can increase the size , it not be 10 , it // can be higher or lower Depending on the size // of the file for (int i = 0; i < 10; i++) { System.out.println((char)out.get(i)); } // Display message on the console showcasing // successful execution of the program System.out.println( "Reading from Memory is complete"); } }} Output: By far we have studied what and why we use memory-mapped files alongside have seen the implementation too. But with these merits, also do comes demerits which are shown below: Merits of the memory-mapped file are as follows: Performance: Memory-mapped Files are way faster than the standard ones. Sharing latency: File can be shared, giving you shared memory between processes and can be more 10x lower latency than using a Socket over loopback. Big Files: It allows us to showcase the larger files which are not accessible otherwise. They are much faster and cleaner. Demerits of the memory-mapped file are as follows: Faults: One of the demerits of the Memory Mapped File is its increasing number of page faults as the memory keeps increasing. Since only a little of it gets into memory, the page you might request if isn’t available into the memory may result in a page fault. But thankfully, most operating systems can generally map all the memory and access it directly using Java Programming Language. surindertarika1234 simmytarika5 Java-Files Picked 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": "\n06 Apr, 2022" }, { "code": null, "e": 439, "s": 28, "text": "Memory-mapped files are casual special files in Java that help to access content directly from memory. Java Programming supports memory-mapped files with java.nio package. Memory-mapped I/O uses the filesystem to establish a virtual memory mapping from the user directly to the filesystem pages. It can be simply treated as a large array. Memory used to load Memory-mapped files is outside of Java Heap Space." }, { "code": null, "e": 647, "s": 439, "text": "Here we use the MappedByteBuffer to read and write from memory. This utility can be used to create and store efficient memory-mapped files. Some major important features about MappedByteBuffer is as follows:" }, { "code": null, "e": 1206, "s": 647, "text": "MappedByteBuffer and file mapping remain valid until the garbage is collected. sun.misc.Cleaner is probably the only option available to clear memory-mapped files.Reading and writing in the memory-mapped file is generally done by the operating system to write content into a disk.Prefer Direct buffer to Indirect Buffer for better performance.Memory used to load File is outside Java heap and reside on shared memory which allows us to two different ways to access the file. By the way, this depends upon, whether you are using the direct or indirect buffer." }, { "code": null, "e": 1370, "s": 1206, "text": "MappedByteBuffer and file mapping remain valid until the garbage is collected. sun.misc.Cleaner is probably the only option available to clear memory-mapped files." }, { "code": null, "e": 1488, "s": 1370, "text": "Reading and writing in the memory-mapped file is generally done by the operating system to write content into a disk." }, { "code": null, "e": 1552, "s": 1488, "text": "Prefer Direct buffer to Indirect Buffer for better performance." }, { "code": null, "e": 1768, "s": 1552, "text": "Memory used to load File is outside Java heap and reside on shared memory which allows us to two different ways to access the file. By the way, this depends upon, whether you are using the direct or indirect buffer." }, { "code": null, "e": 1885, "s": 1768, "text": "Let us do rollover through and implementing the same before concluding out merits and demerits of memory-mapped file" }, { "code": null, "e": 1894, "s": 1885, "text": "Example:" }, { "code": null, "e": 1899, "s": 1894, "text": "Java" }, { "code": "// Java Program to illustrate Memory Mapped File via// RandomAccessFile to open a file using FileChannel's map()// method // Importing standard classes from respective packagesimport java.io.*;import java.io.RandomAccessFile;import java.nio.MappedByteBuffer;import java.nio.channels.FileChannel;import java.util.Scanner; // Main classpublic class GFG { // The next line shows 10 MB as the max value of the // count private static int count = 10485760; // Main driver method public static void main(String[] args) throws Exception { // Display message asking user to enter the input // string System.out.print(\"enter character or string\"); // The method RandomAccessFile has an object sc and // is used to create a text file // Try block to check for exceptions try (RandomAccessFile sc = new RandomAccessFile(\"text.txt\", \"rw\")) { // Scanner class to take objects input // Taking String a as input Scanner s = new Scanner(System.in); String a; a = s.next(); // Mapping the file with the memory // Here the out is the object // This command will help us enable the read and // write functions MappedByteBuffer out = sc.getChannel().map( FileChannel.MapMode.READ_WRITE, 0, 10); // Writing into memory mapped file // taking it as 10 and printing it accordingly for (int i = 0; i < 10; i++) { System.out.println((out.put((byte)i))); } // Print the display message as soon // as the memory is done writing System.out.println( \"Writing to Memory is complete\"); // Reading from memory mapped files // You can increase the size , it not be 10 , it // can be higher or lower Depending on the size // of the file for (int i = 0; i < 10; i++) { System.out.println((char)out.get(i)); } // Display message on the console showcasing // successful execution of the program System.out.println( \"Reading from Memory is complete\"); } }}", "e": 4180, "s": 1899, "text": null }, { "code": null, "e": 4188, "s": 4180, "text": "Output:" }, { "code": null, "e": 4364, "s": 4188, "text": "By far we have studied what and why we use memory-mapped files alongside have seen the implementation too. But with these merits, also do comes demerits which are shown below:" }, { "code": null, "e": 4413, "s": 4364, "text": "Merits of the memory-mapped file are as follows:" }, { "code": null, "e": 4485, "s": 4413, "text": "Performance: Memory-mapped Files are way faster than the standard ones." }, { "code": null, "e": 4634, "s": 4485, "text": "Sharing latency: File can be shared, giving you shared memory between processes and can be more 10x lower latency than using a Socket over loopback." }, { "code": null, "e": 4757, "s": 4634, "text": "Big Files: It allows us to showcase the larger files which are not accessible otherwise. They are much faster and cleaner." }, { "code": null, "e": 4808, "s": 4757, "text": "Demerits of the memory-mapped file are as follows:" }, { "code": null, "e": 5196, "s": 4808, "text": "Faults: One of the demerits of the Memory Mapped File is its increasing number of page faults as the memory keeps increasing. Since only a little of it gets into memory, the page you might request if isn’t available into the memory may result in a page fault. But thankfully, most operating systems can generally map all the memory and access it directly using Java Programming Language." }, { "code": null, "e": 5215, "s": 5196, "text": "surindertarika1234" }, { "code": null, "e": 5228, "s": 5215, "text": "simmytarika5" }, { "code": null, "e": 5239, "s": 5228, "text": "Java-Files" }, { "code": null, "e": 5246, "s": 5239, "text": "Picked" }, { "code": null, "e": 5251, "s": 5246, "text": "Java" }, { "code": null, "e": 5256, "s": 5251, "text": "Java" } ]
Python | Pandas Period.month
06 Jan, 2019 Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas Period.month attribute return an integer value. The returned value represents the value of month in the given period object. January being 1 to December being 12. Syntax : Period.month Parameters : None Return : month Example #1: Use Period.month attribute to find the value of month in the given Period object. # importing pandas as pdimport pandas as pd # Create the Period objectprd = pd.Period(freq ='S', year = 2000, month = 2, day = 21, hour = 8, minute = 21) # Print the Period objectprint(prd) Output : Now we will use the Period.month attribute to find out value of month in prd object. # return value of monthprd.month Output : As we can see in the output, the Period.month attribute has returned 2 indicating that the given period object has ‘February’ as a month. Example #2: Use Period.month attribute to find the value of month in the given Period object. # importing pandas as pdimport pandas as pd # Create the Period objectprd = pd.Period(freq ='T', year = 2006, month = 10, hour = 15, minute = 49) # Print the Period objectprint(prd) Output : Now we will use the Period.month attribute to find out value of month in prd object. # return value of monthprd.month Output : As we can see in the output, the Period.month attribute has returned 10 indicating that the given period object has ‘October’ as a month. Pandas scalar-period Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Convert integer to string in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Jan, 2019" }, { "code": null, "e": 242, "s": 28, "text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier." }, { "code": null, "e": 412, "s": 242, "text": "Pandas Period.month attribute return an integer value. The returned value represents the value of month in the given period object. January being 1 to December being 12." }, { "code": null, "e": 434, "s": 412, "text": "Syntax : Period.month" }, { "code": null, "e": 452, "s": 434, "text": "Parameters : None" }, { "code": null, "e": 467, "s": 452, "text": "Return : month" }, { "code": null, "e": 561, "s": 467, "text": "Example #1: Use Period.month attribute to find the value of month in the given Period object." }, { "code": "# importing pandas as pdimport pandas as pd # Create the Period objectprd = pd.Period(freq ='S', year = 2000, month = 2, day = 21, hour = 8, minute = 21) # Print the Period objectprint(prd)", "e": 769, "s": 561, "text": null }, { "code": null, "e": 778, "s": 769, "text": "Output :" }, { "code": null, "e": 863, "s": 778, "text": "Now we will use the Period.month attribute to find out value of month in prd object." }, { "code": "# return value of monthprd.month", "e": 896, "s": 863, "text": null }, { "code": null, "e": 905, "s": 896, "text": "Output :" }, { "code": null, "e": 1043, "s": 905, "text": "As we can see in the output, the Period.month attribute has returned 2 indicating that the given period object has ‘February’ as a month." }, { "code": null, "e": 1137, "s": 1043, "text": "Example #2: Use Period.month attribute to find the value of month in the given Period object." }, { "code": "# importing pandas as pdimport pandas as pd # Create the Period objectprd = pd.Period(freq ='T', year = 2006, month = 10, hour = 15, minute = 49) # Print the Period objectprint(prd)", "e": 1321, "s": 1137, "text": null }, { "code": null, "e": 1330, "s": 1321, "text": "Output :" }, { "code": null, "e": 1415, "s": 1330, "text": "Now we will use the Period.month attribute to find out value of month in prd object." }, { "code": "# return value of monthprd.month", "e": 1448, "s": 1415, "text": null }, { "code": null, "e": 1457, "s": 1448, "text": "Output :" }, { "code": null, "e": 1595, "s": 1457, "text": "As we can see in the output, the Period.month attribute has returned 10 indicating that the given period object has ‘October’ as a month." }, { "code": null, "e": 1616, "s": 1595, "text": "Pandas scalar-period" }, { "code": null, "e": 1630, "s": 1616, "text": "Python-pandas" }, { "code": null, "e": 1637, "s": 1630, "text": "Python" }, { "code": null, "e": 1735, "s": 1637, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1753, "s": 1735, "text": "Python Dictionary" }, { "code": null, "e": 1795, "s": 1753, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1817, "s": 1795, "text": "Enumerate() in Python" }, { "code": null, "e": 1852, "s": 1817, "text": "Read a file line by line in Python" }, { "code": null, "e": 1878, "s": 1852, "text": "Python String | replace()" }, { "code": null, "e": 1910, "s": 1878, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1939, "s": 1910, "text": "*args and **kwargs in Python" }, { "code": null, "e": 1966, "s": 1939, "text": "Python Classes and Objects" }, { "code": null, "e": 1996, "s": 1966, "text": "Iterate over a list in Python" } ]
Output of Java program | Set 16 (Threads)
19 May, 2017 Prerequisites: multi-threading in java , Life cycle and states of a thread , Joining threads in java , start() method in java1) What could be the output of the following program? public class Test implements Runnable{ public void run() { System.out.printf("GFG "); System.out.printf("Geeks "); } public static void main(String[] args) { Test obj = new Test(); Thread thread = new Thread(obj); thread.start(); System.out.printf("Geeks "); try { thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("for "); }} a) GFG Geeks Geeks forb) Geeks GFG Geeks forc) Either a or bd) Both a and b together Ans. (c)Explanation: From the statement “thread.start()”, we have two threads Main thread and “thread” thread. So either “GFG” can be printed or “Geeks”, depend on which thread, thread scheduler schedule.For (a), the parent thread after calling start() method is paused and the thread scheduler schedules the child thread which then completes its execution. Following this, the parent thread is scheduled. For (b), the parent thread calls start() method but continues its execution and prints on the console. When join() method is called, the parent thread has to wait for its child to complete its execution. Thread scheduler schedules child thread while the parent waits for the child to complete. 2) What is the output of the following program? public class Test implements Runnable{ public void run() { System.out.printf("GFG "); } public static void main(String[] args) throws InterruptedException { Thread thread1 = new Thread(new Test()); thread1.start(); thread1.start(); System.out.println(thread1.getState()); }} a) GFG GFG TERMINATEDb) GFG TERMINATEDc) Compilation Errord) Runtime Error Ans. (d)Explanation: Invoking start() method on a thread moves the thread to a RUNNABLE state. But invoking start() method on a thread that has already started throws a IllegalThreadStateException because the thread is already in RUNNABLE state. 3) What is the output of the following program? public class Test extends Thread implements Runnable{ public void run() { System.out.printf("GFG "); } public static void main(String[] args) throws InterruptedException { Test obj = new Test(); obj.run(); obj.start(); }} a) Runtime errorb) Compilation errorc) GFG GFGd) None of the aboveAns. (c)Explanation: Test class extends Thread class that has start() method implemented. So invoking start() on an object that extends Thread class invokes run() method defined in the program. 4) What is the output of the following program? class myThread implements Runnable{ public void run() { Test.obj.notify(); }} public class Test implements Runnable{ public static Test obj; private int data; public Test() { data = 10; } public void run() { obj = new Test(); obj.wait(); obj.data += 20; System.out.println(obj.data); } public static void main(String[] args) throws InterruptedException { Thread thread1 = new Thread(new Test()); Thread thread2 = new Thread(new myThread()); thread1.start(); thread2.start(); System.out.printf(" GFG - "); }} a) 30 GFG –b) GFG – 30c) GFG –d) Compilation error Ans. (d)Explanation: An object must first acquire a lock before calling wait() method. Also wait() method throws Checked exception(InterruptedException), we must include it in a try-catch block or throws it. 5)What is the output of the following program? import java.util.concurrent.*; public class Test implements Runnable{ public static CyclicBarrier barrier = new CyclicBarrier(3); public void run() { System.out.printf(" GFG "); try { barrier.await(); } catch (InterruptedException | BrokenBarrierException e) { e.printStackTrace(); } } public static void main(String[] args) throws InterruptedException { Thread thread1 = new Thread(new Test()); Thread thread2 = new Thread(new Test()); thread1.start(); thread2.start(); System.out.printf(" GeeksforGeeks "); try { barrier.await(); } catch (InterruptedException | BrokenBarrierException e) { e.printStackTrace(); } System.out.printf(" End "); }} a) GeeksforGeeks GFG GFG Endb) GFG GeeksforGeeks GFG Endc) GFG GFG GeeksforGeeks Endd) All the above Ans. (d)Explanation: For (a), the parent thread keep executing until it reaches the barrier. The child thread are then scheduled. For (b), thread scheduler scheduler thread1. Once it reaches the barrier, the parent thread is scheduled. Once parent thread reached the barrier, thread2 is scheduled. For (c), Both the child thread are scheduled. Finally when each of the child threads reach the barrier, the parent thread is scheduled. This article is contributed by Mayank Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. 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. Java-Multithreading Java-Output Program Output Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Arrow operator -> in C/C++ with Examples Output of Java Program | Set 1 Output of C Programs | Set 1 delete keyword in C++ Output of C++ programs | Set 50 Runtime Errors C++ Programming Multiple Choice Questions Different ways to copy a string in C/C++ Output of C Programs | Set 2 Output of C++ Program | Set 1
[ { "code": null, "e": 54, "s": 26, "text": "\n19 May, 2017" }, { "code": null, "e": 233, "s": 54, "text": "Prerequisites: multi-threading in java , Life cycle and states of a thread , Joining threads in java , start() method in java1) What could be the output of the following program?" }, { "code": "public class Test implements Runnable{ public void run() { System.out.printf(\"GFG \"); System.out.printf(\"Geeks \"); } public static void main(String[] args) { Test obj = new Test(); Thread thread = new Thread(obj); thread.start(); System.out.printf(\"Geeks \"); try { thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(\"for \"); }}", "e": 746, "s": 233, "text": null }, { "code": null, "e": 831, "s": 746, "text": "a) GFG Geeks Geeks forb) Geeks GFG Geeks forc) Either a or bd) Both a and b together" }, { "code": null, "e": 1531, "s": 831, "text": "Ans. (c)Explanation: From the statement “thread.start()”, we have two threads Main thread and “thread” thread. So either “GFG” can be printed or “Geeks”, depend on which thread, thread scheduler schedule.For (a), the parent thread after calling start() method is paused and the thread scheduler schedules the child thread which then completes its execution. Following this, the parent thread is scheduled. For (b), the parent thread calls start() method but continues its execution and prints on the console. When join() method is called, the parent thread has to wait for its child to complete its execution. Thread scheduler schedules child thread while the parent waits for the child to complete." }, { "code": null, "e": 1579, "s": 1531, "text": "2) What is the output of the following program?" }, { "code": "public class Test implements Runnable{ public void run() { System.out.printf(\"GFG \"); } public static void main(String[] args) throws InterruptedException { Thread thread1 = new Thread(new Test()); thread1.start(); thread1.start(); System.out.println(thread1.getState()); }}", "e": 1907, "s": 1579, "text": null }, { "code": null, "e": 1982, "s": 1907, "text": "a) GFG GFG TERMINATEDb) GFG TERMINATEDc) Compilation Errord) Runtime Error" }, { "code": null, "e": 2228, "s": 1982, "text": "Ans. (d)Explanation: Invoking start() method on a thread moves the thread to a RUNNABLE state. But invoking start() method on a thread that has already started throws a IllegalThreadStateException because the thread is already in RUNNABLE state." }, { "code": null, "e": 2276, "s": 2228, "text": "3) What is the output of the following program?" }, { "code": "public class Test extends Thread implements Runnable{ public void run() { System.out.printf(\"GFG \"); } public static void main(String[] args) throws InterruptedException { Test obj = new Test(); obj.run(); obj.start(); }}", "e": 2544, "s": 2276, "text": null }, { "code": null, "e": 2804, "s": 2544, "text": "a) Runtime errorb) Compilation errorc) GFG GFGd) None of the aboveAns. (c)Explanation: Test class extends Thread class that has start() method implemented. So invoking start() on an object that extends Thread class invokes run() method defined in the program." }, { "code": null, "e": 2852, "s": 2804, "text": "4) What is the output of the following program?" }, { "code": "class myThread implements Runnable{ public void run() { Test.obj.notify(); }} public class Test implements Runnable{ public static Test obj; private int data; public Test() { data = 10; } public void run() { obj = new Test(); obj.wait(); obj.data += 20; System.out.println(obj.data); } public static void main(String[] args) throws InterruptedException { Thread thread1 = new Thread(new Test()); Thread thread2 = new Thread(new myThread()); thread1.start(); thread2.start(); System.out.printf(\" GFG - \"); }}", "e": 3509, "s": 2852, "text": null }, { "code": null, "e": 3560, "s": 3509, "text": "a) 30 GFG –b) GFG – 30c) GFG –d) Compilation error" }, { "code": null, "e": 3768, "s": 3560, "text": "Ans. (d)Explanation: An object must first acquire a lock before calling wait() method. Also wait() method throws Checked exception(InterruptedException), we must include it in a try-catch block or throws it." }, { "code": null, "e": 3815, "s": 3768, "text": "5)What is the output of the following program?" }, { "code": "import java.util.concurrent.*; public class Test implements Runnable{ public static CyclicBarrier barrier = new CyclicBarrier(3); public void run() { System.out.printf(\" GFG \"); try { barrier.await(); } catch (InterruptedException | BrokenBarrierException e) { e.printStackTrace(); } } public static void main(String[] args) throws InterruptedException { Thread thread1 = new Thread(new Test()); Thread thread2 = new Thread(new Test()); thread1.start(); thread2.start(); System.out.printf(\" GeeksforGeeks \"); try { barrier.await(); } catch (InterruptedException | BrokenBarrierException e) { e.printStackTrace(); } System.out.printf(\" End \"); }}", "e": 4670, "s": 3815, "text": null }, { "code": null, "e": 4771, "s": 4670, "text": "a) GeeksforGeeks GFG GFG Endb) GFG GeeksforGeeks GFG Endc) GFG GFG GeeksforGeeks Endd) All the above" }, { "code": null, "e": 5205, "s": 4771, "text": "Ans. (d)Explanation: For (a), the parent thread keep executing until it reaches the barrier. The child thread are then scheduled. For (b), thread scheduler scheduler thread1. Once it reaches the barrier, the parent thread is scheduled. Once parent thread reached the barrier, thread2 is scheduled. For (c), Both the child thread are scheduled. Finally when each of the child threads reach the barrier, the parent thread is scheduled." }, { "code": null, "e": 5505, "s": 5205, "text": "This article is contributed by Mayank Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 5630, "s": 5505, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 5650, "s": 5630, "text": "Java-Multithreading" }, { "code": null, "e": 5662, "s": 5650, "text": "Java-Output" }, { "code": null, "e": 5677, "s": 5662, "text": "Program Output" }, { "code": null, "e": 5775, "s": 5677, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5816, "s": 5775, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 5847, "s": 5816, "text": "Output of Java Program | Set 1" }, { "code": null, "e": 5876, "s": 5847, "text": "Output of C Programs | Set 1" }, { "code": null, "e": 5898, "s": 5876, "text": "delete keyword in C++" }, { "code": null, "e": 5930, "s": 5898, "text": "Output of C++ programs | Set 50" }, { "code": null, "e": 5945, "s": 5930, "text": "Runtime Errors" }, { "code": null, "e": 5987, "s": 5945, "text": "C++ Programming Multiple Choice Questions" }, { "code": null, "e": 6028, "s": 5987, "text": "Different ways to copy a string in C/C++" }, { "code": null, "e": 6057, "s": 6028, "text": "Output of C Programs | Set 2" } ]
React Native Top Tab Navigator
12 Nov, 2021 To create a Top Tab Navigator, we need to use the createMaterialTopTabNavigator function available in the react-navigation library. It is designed with the material theme tab bar on the top of the screen. It allows switching between various tabs by tapping them or swiping horizontally. Default transition animations are available. Props: In React Native the when components are created they must be customized according to the need that properties are called props. initialRouteName: initialRouteName is the props that are used to route the name that is rendered on the initial load of the navigator. screenOptions: screenOptions are the props in the React Native that are used as default options for the screens inside the navigator. The default option is used to apply all the screen navigators. tabBarPosition: This type of prop is used to set the position of the tab bar in tab view with the default value being set on the ‘top’. lazy: The lazy props are used to check whether the boolean value indicating whether the screens will be lazily rendered or not. By default, the screen is shown in the viewport experience. lazyPlaceholder: The lazyPlaceholder props in React Native a function that returns a React element to be rendered for those routes that have not been rendered yet. By default, the render value is Null. removeClippedSubviews: The removeClippedSubviewsa is used to improve the memory hierarchy. It takes the boolean value which indicates whether to remove invisible views from the view hierarchy. keyboardDismissMode: This prop is used to take the string value which indicates whether the keyboard gets dismissed as a response to the drag gesture. The other values in keyboard Dismiss mode are auto,on-drag, none. timingConfig: timingConfig the props timing a configuration object used for the timing animation, which occurs when tabs are pressed. The other properties of timingConfig are duration and number. position: an animated value used to listen to the position updates. From time to time, it will change when the user presses the tabs. Options: The options in React Native are used for configuration purposes. Configuration is executed when configuring the screens in the navigator. title: The option title is generally used as a fallback for the headerTitle and tabBarLabel. tabBarIcon: The tabBarIcon options return React.A node that is used to display in the tab bar section is color: string in reacts Native widget. tabBarLabel:The tabBarLabel in the title string of a tab that is displayed in the tab bar section of the widget of the screen in React Native. tabBarAccessibilityLabel: It is an options can be an accessibility label that is read by the screen reader when the user presses the tab. tabBarTestID:The tabBarTestID option can be an ID used to locate this tab button in tests. Events: tabPress: the tabPress event set goes off when the user presses the current screen’s tab button in the tab bar section. By default, it is used when we scroll it to the top . tabLongPress: the event which is fired when the user presses the current screen’s tab button in the tab bar for a long duration of a time . Helpers: jumpTo: The Helpers jumpTo is used to execute a function to navigate an existing screen in the tab navigator, which accepts names and params as its arguments, where name is string and params is an object . Now let’s see how to create a Top Tab Navigator: Step 1: Open your terminal and install expo-cli by the following command.npm install -g expo-cli Step 1: Open your terminal and install expo-cli by the following command. npm install -g expo-cli Step 2: Now create a project by the following command.expo init top-tab-navigator-demo Step 2: Now create a project by the following command. expo init top-tab-navigator-demo Step 3: Now go into your project folder i.e. top-tab-navigator-democd top-tab-navigator-demo Step 3: Now go into your project folder i.e. top-tab-navigator-demo cd top-tab-navigator-demo Step 4: Install the required packages using the following command:npm install –save react-navigation react-navigation-tabs react-native-paper react-native-vector-icons Step 4: Install the required packages using the following command: npm install –save react-navigation react-navigation-tabs react-native-paper react-native-vector-icons Project Structure: The project directory should look like the following: Example: Now, let’s set up our Top Tab Navigator in our App.js file. There will be 3 screens in our demo application: Home Screen, User Screen, and Settings Screen. Thus, we will have 3 tabs to navigate between these 3 screens. Example: First, we will add our App.js file which will hold the Material Bottom Tab Navigator logic. Along with the basic information regarding the screen and label, we will also add icons and basic styles while setting it up. App.js import React from "react";import { Ionicons } from "@expo/vector-icons";import { createAppContainer } from "react-navigation";import { createMaterialTopTabNavigator } from "react-navigation-tabs"; import ProfileScreen from "./screens/ProfileScreen";import ImagesScreen from "./screens/ImagesScreen";import VideoScreen from "./screens/VideosScreen"; const TabNavigator = createMaterialTopTabNavigator( { Profile: { screen: ProfileScreen, navigationOptions: { tabBarLabel: "Profile", showLabel: ({ focused }) => { console.log(focused); return focused ? true : false; }, tabBarIcon: (tabInfo) => ( <Ionicons name="ios-person-circle-outline" size={tabInfo.focused ? 25 : 20} color={tabInfo.tintColor} /> ), }, }, Images: { screen: ImagesScreen, navigationOptions: { tabBarLabel: "Images", tabBarIcon: (tabInfo) => ( <Ionicons name="ios-images-outline" size={tabInfo.focused ? 24 : 20} color={tabInfo.tintColor} /> ), }, }, Video: { screen: VideoScreen, navigationOptions: { tabBarLabel: "Videos", tabBarIcon: (tabInfo) => ( <Ionicons name="ios-videocam-outline" size={tabInfo.focused ? 25 : 20} color={tabInfo.tintColor} /> ), }, }, }, { tabBarOptions: { showIcon: true, style: { backgroundColor: "#006600", marginTop: 28, }, }, }); const Navigator = createAppContainer(TabNavigator); export default function App() { return ( <Navigator> <ProfileScreen /> </Navigator> );} Profile.js import React from "react";import { Text, View } from "react-native";import { Ionicons } from "@expo/vector-icons"; const Profile = () => { return ( <View style={{ flex: 1, alignItems: "center", justifyContent: "center" }}> <Text style={{ color: "#006600", fontSize: 40 }}>Profile Screen!</Text> <Ionicons name="ios-person-circle-outline" size={80} color="#006600" /> </View> );}; export default Profile; Images.js import React from "react";import { Text, View } from "react-native";import { Ionicons } from "@expo/vector-icons"; const Images = () => { return ( <View style={{ flex: 1, alignItems: "center", justifyContent: "center" }}> <Text style={{ color: "#006600", fontSize: 40 }}> Images Screen! </Text> <Ionicons name="ios-images-outline" size={80} color="#006600" /> </View> );}; export default Images; Videos.js import React from "react";import { Text, View } from "react-native";import { Ionicons } from "@expo/vector-icons"; const Videos = () => { return ( <View style={{ flex: 1, alignItems: "center", justifyContent: "center" }}> <Text style={{ color: "#006600", fontSize: 40 }}> Videos Screen! </Text> <Ionicons name="ios-videocam-outline" size={80} color="#006600" /> </View> );}; export default Videos; Start the server by using the following command. expo start Output: Reference: https://reactnavigation.org/docs/material-top-tab-navigator/ kapoorsagar226 Picked React-Native Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array REST API (Introduction) Difference Between PUT and PATCH Request Roadmap to Learn JavaScript For Beginners How to float three div side by side using CSS? ReactJS | Router How to get character array from string in JavaScript?
[ { "code": null, "e": 28, "s": 0, "text": "\n12 Nov, 2021" }, { "code": null, "e": 360, "s": 28, "text": "To create a Top Tab Navigator, we need to use the createMaterialTopTabNavigator function available in the react-navigation library. It is designed with the material theme tab bar on the top of the screen. It allows switching between various tabs by tapping them or swiping horizontally. Default transition animations are available." }, { "code": null, "e": 495, "s": 360, "text": "Props: In React Native the when components are created they must be customized according to the need that properties are called props." }, { "code": null, "e": 630, "s": 495, "text": "initialRouteName: initialRouteName is the props that are used to route the name that is rendered on the initial load of the navigator." }, { "code": null, "e": 827, "s": 630, "text": "screenOptions: screenOptions are the props in the React Native that are used as default options for the screens inside the navigator. The default option is used to apply all the screen navigators." }, { "code": null, "e": 963, "s": 827, "text": "tabBarPosition: This type of prop is used to set the position of the tab bar in tab view with the default value being set on the ‘top’." }, { "code": null, "e": 1151, "s": 963, "text": "lazy: The lazy props are used to check whether the boolean value indicating whether the screens will be lazily rendered or not. By default, the screen is shown in the viewport experience." }, { "code": null, "e": 1353, "s": 1151, "text": "lazyPlaceholder: The lazyPlaceholder props in React Native a function that returns a React element to be rendered for those routes that have not been rendered yet. By default, the render value is Null." }, { "code": null, "e": 1546, "s": 1353, "text": "removeClippedSubviews: The removeClippedSubviewsa is used to improve the memory hierarchy. It takes the boolean value which indicates whether to remove invisible views from the view hierarchy." }, { "code": null, "e": 1764, "s": 1546, "text": "keyboardDismissMode: This prop is used to take the string value which indicates whether the keyboard gets dismissed as a response to the drag gesture. The other values in keyboard Dismiss mode are auto,on-drag, none." }, { "code": null, "e": 1960, "s": 1764, "text": "timingConfig: timingConfig the props timing a configuration object used for the timing animation, which occurs when tabs are pressed. The other properties of timingConfig are duration and number." }, { "code": null, "e": 2094, "s": 1960, "text": "position: an animated value used to listen to the position updates. From time to time, it will change when the user presses the tabs." }, { "code": null, "e": 2242, "s": 2094, "text": "Options: The options in React Native are used for configuration purposes. Configuration is executed when configuring the screens in the navigator." }, { "code": null, "e": 2335, "s": 2242, "text": "title: The option title is generally used as a fallback for the headerTitle and tabBarLabel." }, { "code": null, "e": 2480, "s": 2335, "text": "tabBarIcon: The tabBarIcon options return React.A node that is used to display in the tab bar section is color: string in reacts Native widget." }, { "code": null, "e": 2623, "s": 2480, "text": "tabBarLabel:The tabBarLabel in the title string of a tab that is displayed in the tab bar section of the widget of the screen in React Native." }, { "code": null, "e": 2761, "s": 2623, "text": "tabBarAccessibilityLabel: It is an options can be an accessibility label that is read by the screen reader when the user presses the tab." }, { "code": null, "e": 2852, "s": 2761, "text": "tabBarTestID:The tabBarTestID option can be an ID used to locate this tab button in tests." }, { "code": null, "e": 2861, "s": 2852, "text": "Events: " }, { "code": null, "e": 3035, "s": 2861, "text": "tabPress: the tabPress event set goes off when the user presses the current screen’s tab button in the tab bar section. By default, it is used when we scroll it to the top ." }, { "code": null, "e": 3175, "s": 3035, "text": "tabLongPress: the event which is fired when the user presses the current screen’s tab button in the tab bar for a long duration of a time ." }, { "code": null, "e": 3186, "s": 3177, "text": "Helpers:" }, { "code": null, "e": 3392, "s": 3186, "text": "jumpTo: The Helpers jumpTo is used to execute a function to navigate an existing screen in the tab navigator, which accepts names and params as its arguments, where name is string and params is an object ." }, { "code": null, "e": 3441, "s": 3392, "text": "Now let’s see how to create a Top Tab Navigator:" }, { "code": null, "e": 3538, "s": 3441, "text": "Step 1: Open your terminal and install expo-cli by the following command.npm install -g expo-cli" }, { "code": null, "e": 3612, "s": 3538, "text": "Step 1: Open your terminal and install expo-cli by the following command." }, { "code": null, "e": 3636, "s": 3612, "text": "npm install -g expo-cli" }, { "code": null, "e": 3723, "s": 3636, "text": "Step 2: Now create a project by the following command.expo init top-tab-navigator-demo" }, { "code": null, "e": 3778, "s": 3723, "text": "Step 2: Now create a project by the following command." }, { "code": null, "e": 3811, "s": 3778, "text": "expo init top-tab-navigator-demo" }, { "code": null, "e": 3904, "s": 3811, "text": "Step 3: Now go into your project folder i.e. top-tab-navigator-democd top-tab-navigator-demo" }, { "code": null, "e": 3972, "s": 3904, "text": "Step 3: Now go into your project folder i.e. top-tab-navigator-demo" }, { "code": null, "e": 3998, "s": 3972, "text": "cd top-tab-navigator-demo" }, { "code": null, "e": 4166, "s": 3998, "text": "Step 4: Install the required packages using the following command:npm install –save react-navigation react-navigation-tabs react-native-paper react-native-vector-icons" }, { "code": null, "e": 4233, "s": 4166, "text": "Step 4: Install the required packages using the following command:" }, { "code": null, "e": 4335, "s": 4233, "text": "npm install –save react-navigation react-navigation-tabs react-native-paper react-native-vector-icons" }, { "code": null, "e": 4410, "s": 4337, "text": "Project Structure: The project directory should look like the following:" }, { "code": null, "e": 4420, "s": 4410, "text": "Example: " }, { "code": null, "e": 4639, "s": 4420, "text": "Now, let’s set up our Top Tab Navigator in our App.js file. There will be 3 screens in our demo application: Home Screen, User Screen, and Settings Screen. Thus, we will have 3 tabs to navigate between these 3 screens." }, { "code": null, "e": 4866, "s": 4639, "text": "Example: First, we will add our App.js file which will hold the Material Bottom Tab Navigator logic. Along with the basic information regarding the screen and label, we will also add icons and basic styles while setting it up." }, { "code": null, "e": 4873, "s": 4866, "text": "App.js" }, { "code": "import React from \"react\";import { Ionicons } from \"@expo/vector-icons\";import { createAppContainer } from \"react-navigation\";import { createMaterialTopTabNavigator } from \"react-navigation-tabs\"; import ProfileScreen from \"./screens/ProfileScreen\";import ImagesScreen from \"./screens/ImagesScreen\";import VideoScreen from \"./screens/VideosScreen\"; const TabNavigator = createMaterialTopTabNavigator( { Profile: { screen: ProfileScreen, navigationOptions: { tabBarLabel: \"Profile\", showLabel: ({ focused }) => { console.log(focused); return focused ? true : false; }, tabBarIcon: (tabInfo) => ( <Ionicons name=\"ios-person-circle-outline\" size={tabInfo.focused ? 25 : 20} color={tabInfo.tintColor} /> ), }, }, Images: { screen: ImagesScreen, navigationOptions: { tabBarLabel: \"Images\", tabBarIcon: (tabInfo) => ( <Ionicons name=\"ios-images-outline\" size={tabInfo.focused ? 24 : 20} color={tabInfo.tintColor} /> ), }, }, Video: { screen: VideoScreen, navigationOptions: { tabBarLabel: \"Videos\", tabBarIcon: (tabInfo) => ( <Ionicons name=\"ios-videocam-outline\" size={tabInfo.focused ? 25 : 20} color={tabInfo.tintColor} /> ), }, }, }, { tabBarOptions: { showIcon: true, style: { backgroundColor: \"#006600\", marginTop: 28, }, }, }); const Navigator = createAppContainer(TabNavigator); export default function App() { return ( <Navigator> <ProfileScreen /> </Navigator> );}", "e": 6611, "s": 4873, "text": null }, { "code": null, "e": 6622, "s": 6611, "text": "Profile.js" }, { "code": "import React from \"react\";import { Text, View } from \"react-native\";import { Ionicons } from \"@expo/vector-icons\"; const Profile = () => { return ( <View style={{ flex: 1, alignItems: \"center\", justifyContent: \"center\" }}> <Text style={{ color: \"#006600\", fontSize: 40 }}>Profile Screen!</Text> <Ionicons name=\"ios-person-circle-outline\" size={80} color=\"#006600\" /> </View> );}; export default Profile;", "e": 7046, "s": 6622, "text": null }, { "code": null, "e": 7056, "s": 7046, "text": "Images.js" }, { "code": "import React from \"react\";import { Text, View } from \"react-native\";import { Ionicons } from \"@expo/vector-icons\"; const Images = () => { return ( <View style={{ flex: 1, alignItems: \"center\", justifyContent: \"center\" }}> <Text style={{ color: \"#006600\", fontSize: 40 }}> Images Screen! </Text> <Ionicons name=\"ios-images-outline\" size={80} color=\"#006600\" /> </View> );}; export default Images;", "e": 7538, "s": 7056, "text": null }, { "code": null, "e": 7548, "s": 7538, "text": "Videos.js" }, { "code": "import React from \"react\";import { Text, View } from \"react-native\";import { Ionicons } from \"@expo/vector-icons\"; const Videos = () => { return ( <View style={{ flex: 1, alignItems: \"center\", justifyContent: \"center\" }}> <Text style={{ color: \"#006600\", fontSize: 40 }}> Videos Screen! </Text> <Ionicons name=\"ios-videocam-outline\" size={80} color=\"#006600\" /> </View> );}; export default Videos;", "e": 8032, "s": 7548, "text": null }, { "code": null, "e": 8081, "s": 8032, "text": "Start the server by using the following command." }, { "code": null, "e": 8092, "s": 8081, "text": "expo start" }, { "code": null, "e": 8100, "s": 8092, "text": "Output:" }, { "code": null, "e": 8172, "s": 8100, "text": "Reference: https://reactnavigation.org/docs/material-top-tab-navigator/" }, { "code": null, "e": 8187, "s": 8172, "text": "kapoorsagar226" }, { "code": null, "e": 8194, "s": 8187, "text": "Picked" }, { "code": null, "e": 8207, "s": 8194, "text": "React-Native" }, { "code": null, "e": 8224, "s": 8207, "text": "Web Technologies" }, { "code": null, "e": 8322, "s": 8224, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8383, "s": 8322, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 8426, "s": 8383, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 8498, "s": 8426, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 8538, "s": 8498, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 8562, "s": 8538, "text": "REST API (Introduction)" }, { "code": null, "e": 8603, "s": 8562, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 8645, "s": 8603, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 8692, "s": 8645, "text": "How to float three div side by side using CSS?" }, { "code": null, "e": 8709, "s": 8692, "text": "ReactJS | Router" } ]
Perl | Writing to a File
07 Mar, 2019 A filehandle is a variable that is used to read and write to a file. This filehandle gets associated with the file. In order to write to the file, it is opened in write mode as shown below: open (FH, ‘>’, “filename.txt”); If the file is existing then it truncates the old content of file with the new content. Otherwise a new file will be created and content will be added. print() function is used to write content to a file. Syntax: print filehandle string Here, filehandle is associated to the file at the time of opening the file and string holds the content to be written to the file. Example : # Opening file Hello.txt in write modeopen (fh, ">", "Hello.txt"); # Getting the string to be written# to the file from the userprint "Enter the content to be added\n";$a = <>; # Writing to the fileprint fh $a; # Closing the fileclose(fh) or "Couldn't close the file"; Before Writing to File: Executing Code to Write: Updated File: Here is how the program works:Step 1: Opening file Hello.txt in write mode.Step 2: Getting the text from the standard input keyboard.Step 3: Writing the string stored in ‘$a’ to the file pointed by filehandle ‘fh’Step 4: Closing the file. Copying Content from one file to another: Before Code Execution:Source File:Destination File: Example :Example below reads the content from the source file and writes it to destination file. # Source File $src = 'Source.txt'; # Destination File$des = 'Destination.txt'; # open source file for readingopen(FHR, '<', $src); # open destination file for writingopen(FHW, '>', $des); print("Copying content from $src to $des\n");while(<FHR>){ print FHW $_; } # Closing the filehandlesclose(FHR);close(FHW); print "File content copied successfully!\n"; Executing Code: Updated Destination File: Here is how the program works:-Step 1: Opening 2 files Source.txt in read mode and Destination.txt in write mode.Step 2: Reading the content from the FHR which is filehandle to read content while FHW is a filehandle to write content to file.Step 3: Copying the content with the use of print function.Step 4: Close the conn once reading file is done. There are two ways in which Errors can be handled Throw an exception if file cannot be opened (Handling an error) Give a warning if file cannot be opened and continue running (Error reporting) Throw an Exception (Using Die Function)When filehandle could not be assigned a valid file pointer at that time die gets executed printing the message and kills the current program.Example : # Initializing filename $filename = 'Hello.txt'; # $filename = 'ello.txt'; # Prints an error and exits # if file not found open(fh, '<', $filename) or die "Couldn't Open file $filename"; In the above code when File exists it simply gets executed with no errors but if file doesn’t exists then it generates an error and code terminates. Give a warning (Using warn function)When filehandle could not be assigned a valid file pointer it just prints warning message using warn function and keeps running.Example : # Initializing filename $filename = 'GFG.txt'; # Opening a file and reading content if(open(fh, '<', $filename)) { while(<fh>) { print $_; } } # Executes if file not found else{ warn "Couldn't Open a file $filename"; } When File exists: When File doesn’t exists: Perl-files Picked Perl Perl Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Perl | split() Function Perl | push() Function Perl | chomp() Function Perl | substr() function Perl | grep() Function Perl | exists() Function Perl Tutorial - Learn Perl With Examples Perl | length() Function Perl | Subroutines or Functions Use of print() and say() in Perl
[ { "code": null, "e": 28, "s": 0, "text": "\n07 Mar, 2019" }, { "code": null, "e": 144, "s": 28, "text": "A filehandle is a variable that is used to read and write to a file. This filehandle gets associated with the file." }, { "code": null, "e": 218, "s": 144, "text": "In order to write to the file, it is opened in write mode as shown below:" }, { "code": null, "e": 250, "s": 218, "text": "open (FH, ‘>’, “filename.txt”);" }, { "code": null, "e": 402, "s": 250, "text": "If the file is existing then it truncates the old content of file with the new content. Otherwise a new file will be created and content will be added." }, { "code": null, "e": 455, "s": 402, "text": "print() function is used to write content to a file." }, { "code": null, "e": 487, "s": 455, "text": "Syntax: print filehandle string" }, { "code": null, "e": 618, "s": 487, "text": "Here, filehandle is associated to the file at the time of opening the file and string holds the content to be written to the file." }, { "code": null, "e": 628, "s": 618, "text": "Example :" }, { "code": "# Opening file Hello.txt in write modeopen (fh, \">\", \"Hello.txt\"); # Getting the string to be written# to the file from the userprint \"Enter the content to be added\\n\";$a = <>; # Writing to the fileprint fh $a; # Closing the fileclose(fh) or \"Couldn't close the file\"; ", "e": 901, "s": 628, "text": null }, { "code": null, "e": 925, "s": 901, "text": "Before Writing to File:" }, { "code": null, "e": 950, "s": 925, "text": "Executing Code to Write:" }, { "code": null, "e": 964, "s": 950, "text": "Updated File:" }, { "code": null, "e": 1245, "s": 964, "text": "Here is how the program works:Step 1: Opening file Hello.txt in write mode.Step 2: Getting the text from the standard input keyboard.Step 3: Writing the string stored in ‘$a’ to the file pointed by filehandle ‘fh’Step 4: Closing the file. Copying Content from one file to another:" }, { "code": null, "e": 1297, "s": 1245, "text": "Before Code Execution:Source File:Destination File:" }, { "code": null, "e": 1394, "s": 1297, "text": "Example :Example below reads the content from the source file and writes it to destination file." }, { "code": "# Source File $src = 'Source.txt'; # Destination File$des = 'Destination.txt'; # open source file for readingopen(FHR, '<', $src); # open destination file for writingopen(FHW, '>', $des); print(\"Copying content from $src to $des\\n\");while(<FHR>){ print FHW $_; } # Closing the filehandlesclose(FHR);close(FHW); print \"File content copied successfully!\\n\";", "e": 1763, "s": 1394, "text": null }, { "code": null, "e": 1779, "s": 1763, "text": "Executing Code:" }, { "code": null, "e": 1805, "s": 1779, "text": "Updated Destination File:" }, { "code": null, "e": 2156, "s": 1805, "text": "Here is how the program works:-Step 1: Opening 2 files Source.txt in read mode and Destination.txt in write mode.Step 2: Reading the content from the FHR which is filehandle to read content while FHW is a filehandle to write content to file.Step 3: Copying the content with the use of print function.Step 4: Close the conn once reading file is done. " }, { "code": null, "e": 2206, "s": 2156, "text": "There are two ways in which Errors can be handled" }, { "code": null, "e": 2270, "s": 2206, "text": "Throw an exception if file cannot be opened (Handling an error)" }, { "code": null, "e": 2349, "s": 2270, "text": "Give a warning if file cannot be opened and continue running (Error reporting)" }, { "code": null, "e": 2539, "s": 2349, "text": "Throw an Exception (Using Die Function)When filehandle could not be assigned a valid file pointer at that time die gets executed printing the message and kills the current program.Example :" }, { "code": "# Initializing filename $filename = 'Hello.txt'; # $filename = 'ello.txt'; # Prints an error and exits # if file not found open(fh, '<', $filename) or die \"Couldn't Open file $filename\"; ", "e": 2734, "s": 2539, "text": null }, { "code": null, "e": 2883, "s": 2734, "text": "In the above code when File exists it simply gets executed with no errors but if file doesn’t exists then it generates an error and code terminates." }, { "code": null, "e": 3057, "s": 2883, "text": "Give a warning (Using warn function)When filehandle could not be assigned a valid file pointer it just prints warning message using warn function and keeps running.Example :" }, { "code": "# Initializing filename $filename = 'GFG.txt'; # Opening a file and reading content if(open(fh, '<', $filename)) { while(<fh>) { print $_; } } # Executes if file not found else{ warn \"Couldn't Open a file $filename\"; } ", "e": 3303, "s": 3057, "text": null }, { "code": null, "e": 3321, "s": 3303, "text": "When File exists:" }, { "code": null, "e": 3347, "s": 3321, "text": "When File doesn’t exists:" }, { "code": null, "e": 3358, "s": 3347, "text": "Perl-files" }, { "code": null, "e": 3365, "s": 3358, "text": "Picked" }, { "code": null, "e": 3370, "s": 3365, "text": "Perl" }, { "code": null, "e": 3375, "s": 3370, "text": "Perl" }, { "code": null, "e": 3473, "s": 3375, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3497, "s": 3473, "text": "Perl | split() Function" }, { "code": null, "e": 3520, "s": 3497, "text": "Perl | push() Function" }, { "code": null, "e": 3544, "s": 3520, "text": "Perl | chomp() Function" }, { "code": null, "e": 3569, "s": 3544, "text": "Perl | substr() function" }, { "code": null, "e": 3592, "s": 3569, "text": "Perl | grep() Function" }, { "code": null, "e": 3617, "s": 3592, "text": "Perl | exists() Function" }, { "code": null, "e": 3658, "s": 3617, "text": "Perl Tutorial - Learn Perl With Examples" }, { "code": null, "e": 3683, "s": 3658, "text": "Perl | length() Function" }, { "code": null, "e": 3715, "s": 3683, "text": "Perl | Subroutines or Functions" } ]
HTML | DOM Anchor Object
06 Feb, 2019 The Anchor Object in HTML DOM is used to represent the <a> element . The anchor element can be accessed by using getElementById() method. Syntax: document.getElementById("ID"); Where ID is assigned to the anchor tag. Property Values: charset: It is used to set or return the character-set. It is not supported by HTML 5. download: It is used to set or return the target link to download when user click. hreflang: It is used set or return the language of linked document. media: It is used to set or return the linked media. coords: It is used to set or return the coordinate of links. name: It is used to set or return the anchor name. rel: It is used to set or return the relation between current document and linked document. shape: It is used to set or return the shape of link. type: It is used to set or return the type of links. target: It is used to set or return the target link. rev: It is used to set or return the relation between linked document and current document. Example 1: This example describes the getElementById() method to access <a> element. <!DOCTYPE html> <html> <head> <title> HTML DOM Anchor Object </title> </head> <body> <center> <h1>GeeksForGeeks</h1> <h2>DOM Anchor Object</h2> <p>Welcome to <a href = "https://www.geeksforgeeks.org/" id="GFG"> GeeksforGeeks </a> </p> <button onclick = "myGeeks()">Submit</button> <p id = "sudo"></p> <script> function myGeeks() { var x = document.getElementById("GFG").href; document.getElementById("sudo").innerHTML = x; } </script> </center></body> </html> Output:Before Click on the Button :After Click on the Button : Example 2: Anchor Object can be created by using the document.createElement Method. <!DOCTYPE html> <html> <head> <title> HTML DOM Anchor Object </title> </head> <body> <center> <h1>GeeksForGeeks</h1> <h2>DOM Anchor Object </h2> <p id = "gfg">Welcome to </p> <button onclick = "myGeeks()"> Submit </button> <!-- script to describe anchor object --> <script> function myGeeks() { /* Create anchor tag */ var g = document.createElement("A"); var f = document.createTextNode("GeeksForGeeks"); g.setAttribute("href", "https://www.geeksforgeeks.org/"); g.appendChild(f); document.getElementById("gfg").appendChild(g); } </script> </center></body> </html> Output:Before Click on the Button :After Click on the Button: Supported Browsers: The browser supported by DOM Anchor Object are listed below: Google Chrome Firefox Internet Explorer Opera Safari HTML-DOM Picked 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 ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? REST API (Introduction) Hide or show elements in HTML using display property Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Feb, 2019" }, { "code": null, "e": 166, "s": 28, "text": "The Anchor Object in HTML DOM is used to represent the <a> element . The anchor element can be accessed by using getElementById() method." }, { "code": null, "e": 174, "s": 166, "text": "Syntax:" }, { "code": null, "e": 206, "s": 174, "text": "document.getElementById(\"ID\"); " }, { "code": null, "e": 246, "s": 206, "text": "Where ID is assigned to the anchor tag." }, { "code": null, "e": 263, "s": 246, "text": "Property Values:" }, { "code": null, "e": 350, "s": 263, "text": "charset: It is used to set or return the character-set. It is not supported by HTML 5." }, { "code": null, "e": 433, "s": 350, "text": "download: It is used to set or return the target link to download when user click." }, { "code": null, "e": 501, "s": 433, "text": "hreflang: It is used set or return the language of linked document." }, { "code": null, "e": 554, "s": 501, "text": "media: It is used to set or return the linked media." }, { "code": null, "e": 615, "s": 554, "text": "coords: It is used to set or return the coordinate of links." }, { "code": null, "e": 666, "s": 615, "text": "name: It is used to set or return the anchor name." }, { "code": null, "e": 758, "s": 666, "text": "rel: It is used to set or return the relation between current document and linked document." }, { "code": null, "e": 812, "s": 758, "text": "shape: It is used to set or return the shape of link." }, { "code": null, "e": 865, "s": 812, "text": "type: It is used to set or return the type of links." }, { "code": null, "e": 918, "s": 865, "text": "target: It is used to set or return the target link." }, { "code": null, "e": 1010, "s": 918, "text": "rev: It is used to set or return the relation between linked document and current document." }, { "code": null, "e": 1095, "s": 1010, "text": "Example 1: This example describes the getElementById() method to access <a> element." }, { "code": "<!DOCTYPE html> <html> <head> <title> HTML DOM Anchor Object </title> </head> <body> <center> <h1>GeeksForGeeks</h1> <h2>DOM Anchor Object</h2> <p>Welcome to <a href = \"https://www.geeksforgeeks.org/\" id=\"GFG\"> GeeksforGeeks </a> </p> <button onclick = \"myGeeks()\">Submit</button> <p id = \"sudo\"></p> <script> function myGeeks() { var x = document.getElementById(\"GFG\").href; document.getElementById(\"sudo\").innerHTML = x; } </script> </center></body> </html> ", "e": 1817, "s": 1095, "text": null }, { "code": null, "e": 1880, "s": 1817, "text": "Output:Before Click on the Button :After Click on the Button :" }, { "code": null, "e": 1964, "s": 1880, "text": "Example 2: Anchor Object can be created by using the document.createElement Method." }, { "code": "<!DOCTYPE html> <html> <head> <title> HTML DOM Anchor Object </title> </head> <body> <center> <h1>GeeksForGeeks</h1> <h2>DOM Anchor Object </h2> <p id = \"gfg\">Welcome to </p> <button onclick = \"myGeeks()\"> Submit </button> <!-- script to describe anchor object --> <script> function myGeeks() { /* Create anchor tag */ var g = document.createElement(\"A\"); var f = document.createTextNode(\"GeeksForGeeks\"); g.setAttribute(\"href\", \"https://www.geeksforgeeks.org/\"); g.appendChild(f); document.getElementById(\"gfg\").appendChild(g); } </script> </center></body> </html> ", "e": 2830, "s": 1964, "text": null }, { "code": null, "e": 2892, "s": 2830, "text": "Output:Before Click on the Button :After Click on the Button:" }, { "code": null, "e": 2973, "s": 2892, "text": "Supported Browsers: The browser supported by DOM Anchor Object are listed below:" }, { "code": null, "e": 2987, "s": 2973, "text": "Google Chrome" }, { "code": null, "e": 2995, "s": 2987, "text": "Firefox" }, { "code": null, "e": 3013, "s": 2995, "text": "Internet Explorer" }, { "code": null, "e": 3019, "s": 3013, "text": "Opera" }, { "code": null, "e": 3026, "s": 3019, "text": "Safari" }, { "code": null, "e": 3035, "s": 3026, "text": "HTML-DOM" }, { "code": null, "e": 3042, "s": 3035, "text": "Picked" }, { "code": null, "e": 3047, "s": 3042, "text": "HTML" }, { "code": null, "e": 3064, "s": 3047, "text": "Web Technologies" }, { "code": null, "e": 3069, "s": 3064, "text": "HTML" }, { "code": null, "e": 3167, "s": 3069, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3215, "s": 3167, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 3277, "s": 3215, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3327, "s": 3277, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 3351, "s": 3327, "text": "REST API (Introduction)" }, { "code": null, "e": 3404, "s": 3351, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 3437, "s": 3404, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 3499, "s": 3437, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3560, "s": 3499, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3610, "s": 3560, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
SHA in Python
14 Feb, 2018 SHA, ( Secure Hash Algorithms ) are set of cryptographic hash functions defined by the language to be used for various applications such as password security etc. Some variants of it are supported by Python in the “hashlib” library. These can be found using “algorithms_guaranteed” function of hashlib. # Python 3 code to check # available algorithms import hashlib # prints all available algorithmsprint ("The available algorithms are : ", end ="")print (hashlib.algorithms_guaranteed) Output: The available algorithms are : {'sha256', 'sha384', 'sha224', 'sha512', 'sha1', 'md5'} To proceed with, lets first discuss the functions going to be used in this article. Functions associated : encode() : Converts the string into bytes to be acceptable by hash function. hexdigest() : Returns the encoded data in hexadecimal format. The different SHA hash functions are explained below. SHA256 : This hash function belong to hash class SHA-2, the internal block size of it is 32 bits. SHA384 : This hash function belong to hash class SHA-2, the internal block size of it is 32 bits. This is one of the truncated version. SHA224 : This hash function belong to hash class SHA-2, the internal block size of it is 32 bits. This is one of the truncated version. SHA512 : This hash function belong to hash class SHA-2, the internal block size of it is 64 bits. SHA1 : The 160 bit hash function that resembles MD5 hash in working and was discontinued to be used seeing its security vulnerabilities. Below code implements these hash functions. # Python 3 code to demonstrate# SHA hash algorithms. import hashlib # initializing stringstr = "GeeksforGeeks" # encoding GeeksforGeeks using encode()# then sending to SHA256()result = hashlib.sha256(str.encode()) # printing the equivalent hexadecimal value.print("The hexadecimal equivalent of SHA256 is : ")print(result.hexdigest()) print ("\r") # initializing stringstr = "GeeksforGeeks" # encoding GeeksforGeeks using encode()# then sending to SHA384()result = hashlib.sha384(str.encode()) # printing the equivalent hexadecimal value.print("The hexadecimal equivalent of SHA384 is : ")print(result.hexdigest()) print ("\r") # initializing stringstr = "GeeksforGeeks" # encoding GeeksforGeeks using encode()# then sending to SHA224()result = hashlib.sha224(str.encode()) # printing the equivalent hexadecimal value.print("The hexadecimal equivalent of SHA224 is : ")print(result.hexdigest()) print ("\r") # initializing stringstr = "GeeksforGeeks" # encoding GeeksforGeeks using encode()# then sending to SHA512()result = hashlib.sha512(str.encode()) # printing the equivalent hexadecimal value.print("The hexadecimal equivalent of SHA512 is : ")print(result.hexdigest()) print ("\r") # initializing stringstr = "GeeksforGeeks" # encoding GeeksforGeeks using encode()# then sending to SHA1()result = hashlib.sha1(str.encode()) # printing the equivalent hexadecimal value.print("The hexadecimal equivalent of SHA1 is : ")print(result.hexdigest()) Output: The hexadecimal equivalent of SHA256 is : f6071725e7ddeb434fb6b32b8ec4a2b14dd7db0d785347b2fb48f9975126178f The hexadecimal equivalent of SHA384 is : d1e67b8819b009ec7929933b6fc1928dd64b5df31bcde6381b9d3f90488d253240490460c0a5a1a873da8236c12ef9b3 The hexadecimal equivalent of SHA224 is : 173994f309f727ca939bb185086cd7b36e66141c9e52ba0bdcfd145d The hexadecimal equivalent of SHA512 is : 0d8fb9370a5bf7b892be4865cdf8b658a82209624e33ed71cae353b0df254a75db63d1baa35ad99f26f1b399c31f3c666a7fc67ecef3bdcdb7d60e8ada90b722 The hexadecimal equivalent of SHA1 is : 4175a37afd561152fb60c305d4fa6026b7e79856 Explanation : The above code takes string and converts it into the byte equivalent using encode() so that it can be accepted by the hash function. The SHA hash functions encode it and then using hexdigest(), hexadecimal equivalent encoded string is printed. cryptography Python cryptography Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Iterate over a list in Python Python Classes and Objects Convert integer to string in Python Python | os.path.join() method
[ { "code": null, "e": 52, "s": 24, "text": "\n14 Feb, 2018" }, { "code": null, "e": 355, "s": 52, "text": "SHA, ( Secure Hash Algorithms ) are set of cryptographic hash functions defined by the language to be used for various applications such as password security etc. Some variants of it are supported by Python in the “hashlib” library. These can be found using “algorithms_guaranteed” function of hashlib." }, { "code": "# Python 3 code to check # available algorithms import hashlib # prints all available algorithmsprint (\"The available algorithms are : \", end =\"\")print (hashlib.algorithms_guaranteed)", "e": 541, "s": 355, "text": null }, { "code": null, "e": 549, "s": 541, "text": "Output:" }, { "code": null, "e": 637, "s": 549, "text": "The available algorithms are : {'sha256', 'sha384', 'sha224', 'sha512', 'sha1', 'md5'}\n" }, { "code": null, "e": 721, "s": 637, "text": "To proceed with, lets first discuss the functions going to be used in this article." }, { "code": null, "e": 744, "s": 721, "text": "Functions associated :" }, { "code": null, "e": 821, "s": 744, "text": "encode() : Converts the string into bytes to be acceptable by hash function." }, { "code": null, "e": 883, "s": 821, "text": "hexdigest() : Returns the encoded data in hexadecimal format." }, { "code": null, "e": 937, "s": 883, "text": "The different SHA hash functions are explained below." }, { "code": null, "e": 1035, "s": 937, "text": "SHA256 : This hash function belong to hash class SHA-2, the internal block size of it is 32 bits." }, { "code": null, "e": 1171, "s": 1035, "text": "SHA384 : This hash function belong to hash class SHA-2, the internal block size of it is 32 bits. This is one of the truncated version." }, { "code": null, "e": 1307, "s": 1171, "text": "SHA224 : This hash function belong to hash class SHA-2, the internal block size of it is 32 bits. This is one of the truncated version." }, { "code": null, "e": 1405, "s": 1307, "text": "SHA512 : This hash function belong to hash class SHA-2, the internal block size of it is 64 bits." }, { "code": null, "e": 1542, "s": 1405, "text": "SHA1 : The 160 bit hash function that resembles MD5 hash in working and was discontinued to be used seeing its security vulnerabilities." }, { "code": null, "e": 1586, "s": 1542, "text": "Below code implements these hash functions." }, { "code": "# Python 3 code to demonstrate# SHA hash algorithms. import hashlib # initializing stringstr = \"GeeksforGeeks\" # encoding GeeksforGeeks using encode()# then sending to SHA256()result = hashlib.sha256(str.encode()) # printing the equivalent hexadecimal value.print(\"The hexadecimal equivalent of SHA256 is : \")print(result.hexdigest()) print (\"\\r\") # initializing stringstr = \"GeeksforGeeks\" # encoding GeeksforGeeks using encode()# then sending to SHA384()result = hashlib.sha384(str.encode()) # printing the equivalent hexadecimal value.print(\"The hexadecimal equivalent of SHA384 is : \")print(result.hexdigest()) print (\"\\r\") # initializing stringstr = \"GeeksforGeeks\" # encoding GeeksforGeeks using encode()# then sending to SHA224()result = hashlib.sha224(str.encode()) # printing the equivalent hexadecimal value.print(\"The hexadecimal equivalent of SHA224 is : \")print(result.hexdigest()) print (\"\\r\") # initializing stringstr = \"GeeksforGeeks\" # encoding GeeksforGeeks using encode()# then sending to SHA512()result = hashlib.sha512(str.encode()) # printing the equivalent hexadecimal value.print(\"The hexadecimal equivalent of SHA512 is : \")print(result.hexdigest()) print (\"\\r\") # initializing stringstr = \"GeeksforGeeks\" # encoding GeeksforGeeks using encode()# then sending to SHA1()result = hashlib.sha1(str.encode()) # printing the equivalent hexadecimal value.print(\"The hexadecimal equivalent of SHA1 is : \")print(result.hexdigest())", "e": 3055, "s": 1586, "text": null }, { "code": null, "e": 3063, "s": 3055, "text": "Output:" }, { "code": null, "e": 3670, "s": 3063, "text": "The hexadecimal equivalent of SHA256 is : \nf6071725e7ddeb434fb6b32b8ec4a2b14dd7db0d785347b2fb48f9975126178f\n\nThe hexadecimal equivalent of SHA384 is : \nd1e67b8819b009ec7929933b6fc1928dd64b5df31bcde6381b9d3f90488d253240490460c0a5a1a873da8236c12ef9b3\n\nThe hexadecimal equivalent of SHA224 is : \n173994f309f727ca939bb185086cd7b36e66141c9e52ba0bdcfd145d\n\nThe hexadecimal equivalent of SHA512 is : \n0d8fb9370a5bf7b892be4865cdf8b658a82209624e33ed71cae353b0df254a75db63d1baa35ad99f26f1b399c31f3c666a7fc67ecef3bdcdb7d60e8ada90b722\n\nThe hexadecimal equivalent of SHA1 is : \n4175a37afd561152fb60c305d4fa6026b7e79856\n" }, { "code": null, "e": 3928, "s": 3670, "text": "Explanation : The above code takes string and converts it into the byte equivalent using encode() so that it can be accepted by the hash function. The SHA hash functions encode it and then using hexdigest(), hexadecimal equivalent encoded string is printed." }, { "code": null, "e": 3941, "s": 3928, "text": "cryptography" }, { "code": null, "e": 3948, "s": 3941, "text": "Python" }, { "code": null, "e": 3961, "s": 3948, "text": "cryptography" }, { "code": null, "e": 4059, "s": 3961, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4077, "s": 4059, "text": "Python Dictionary" }, { "code": null, "e": 4119, "s": 4077, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 4141, "s": 4119, "text": "Enumerate() in Python" }, { "code": null, "e": 4167, "s": 4141, "text": "Python String | replace()" }, { "code": null, "e": 4199, "s": 4167, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 4228, "s": 4199, "text": "*args and **kwargs in Python" }, { "code": null, "e": 4258, "s": 4228, "text": "Iterate over a list in Python" }, { "code": null, "e": 4285, "s": 4258, "text": "Python Classes and Objects" }, { "code": null, "e": 4321, "s": 4285, "text": "Convert integer to string in Python" } ]